File size: 6,147 Bytes
3022fd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fc9148
 
 
 
3022fd1
6fc9148
 
 
3022fd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import json
from typing import Dict, List
from pathlib import Path
import numpy as np
from datetime import datetime
from sentence_transformers import SentenceTransformer
from huggingface_hub import HfApi
import os

class VectorStore:
    def __init__(self):
        self.documents = []
        self.metadata = []  # λ¬Έμ„œ 메타데이터 μ €μž₯
        self.model = SentenceTransformer('all-MiniLM-L6-v2')
        self.hf_api = HfApi()
        self.dataset_name = "bluewhale2025/parseai_202506"  # Hugging Face dataset 이름
        
        # 데이터셋이 μ—†μœΌλ©΄ 생성
        try:
            self.hf_api.create_repo(
                repo_id=self.dataset_name,
                repo_type="dataset",
                private=True  # 개인 λ°μ΄ν„°μ…‹μœΌλ‘œ μ„€μ •
            )
            print(f"데이터셋 {self.dataset_name} 생성 μ™„λ£Œ")
        except Exception as e:
            print(f"데이터셋 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
        
    def add_document(self, text: str, metadata: Dict) -> None:
        """λ¬Έμ„œλ₯Ό μ €μž₯"""
        try:
            # λ¬Έμ„œ μ €μž₯
            self.documents.append(text)
            
            # 메타데이터 μ €μž₯
            metadata["timestamp"] = str(datetime.now())
            self.metadata.append(metadata)
            
            # 벑터 생성
            vector = self.model.encode(text)
            
            # 디렉토리 생성
            os.makedirs("vectors", exist_ok=True)
            os.makedirs("metadata", exist_ok=True)
            
            # 파일 경둜 μ„€μ •
            doc_id = len(self.documents)
            vector_path = f"vectors/{doc_id}.npy"
            metadata_path = f"metadata/{doc_id}.json"
            
            # μž„μ‹œ 파일둜 μ €μž₯
            np.save(vector_path, vector)
            with open(metadata_path, 'w', encoding='utf-8') as f:
                json.dump(metadata, f)
            
            # Hugging Face에 μ—…λ‘œλ“œ
            self.hf_api.upload_file(
                path_or_fileobj=vector_path,
                path_in_repo=vector_path,
                repo_id=self.dataset_name,
                repo_type="dataset"
            )
            
            self.hf_api.upload_file(
                path_or_fileobj=metadata_path,
                path_in_repo=metadata_path,
                repo_id=self.dataset_name,
                repo_type="dataset"
            )
            
            # μž„μ‹œ 파일 μ‚­μ œ
            os.remove(vector_path)
            os.remove(metadata_path)
            
        except Exception as e:
            raise Exception(f"λ¬Έμ„œ μ €μž₯ 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
    
    def search(self, query: str, top_k: int = 5) -> List[Dict]:
        """ν‚€μ›Œλ“œ 검색"""
        try:
            # 쿼리 벑터 생성
            query_vector = self.model.encode(query)
            
            # Hugging Faceμ—μ„œ λͺ¨λ“  벑터 λ‘œλ“œ
            vectors = []
            metadata = []
            
            # λͺ¨λ“  벑터 파일 λ‘œλ“œ
            files = self.hf_api.list_repo_files(
                repo_id=self.dataset_name,
                repo_type="dataset"
            )
            
            # 파일 μ •λ ¬ (1λΆ€ν„° μ‹œμž‘)
            vector_files = sorted([f for f in files if f.startswith("vectors/")])
            metadata_files = sorted([f for f in files if f.startswith("metadata/")])
            
            if not vector_files or not metadata_files:
                return []
            
            # 파일 λ‘œλ“œ
            for vector_file, metadata_file in zip(vector_files, metadata_files):
                vector = np.load(self.hf_api.download_file(
                    repo_id=self.dataset_name,
                    filename=vector_file,
                    repo_type="dataset"
                ))
                vectors.append(vector)
                
                meta = json.load(self.hf_api.download_file(
                    repo_id=self.dataset_name,
                    filename=metadata_file,
                    repo_type="dataset"
                ))
                metadata.append(meta)
            
            # μœ μ‚¬λ„ 계산
            similarities = cosine_similarity(vectors, [query_vector]).flatten()
            
            # μœ μ‚¬λ„ 기반 μ •λ ¬
            sorted_idx = np.argsort(similarities)[::-1][:top_k]
            
            # κ²°κ³Ό 생성
            results = []
            for idx in sorted_idx:
                results.append({
                    "filename": metadata[idx]["filename"],
                    "total_pages": metadata[idx]["total_pages"],
                    "summary": metadata[idx]["summary"],
                    "timestamp": metadata[idx]["timestamp"],
                    "similarity": float(similarities[idx])
                })
            
            return results
            
        except Exception as e:
            raise Exception(f"검색 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
    
    def _save_metadata(self) -> None:
        """메타데이터 μ €μž₯"""
        try:
            Path(self.metadata_path).parent.mkdir(parents=True, exist_ok=True)
            with open(self.metadata_path, 'w', encoding='utf-8') as f:
                json.dump({
                    "documents": self.documents,
                    "metadata": self.metadata
                }, f, ensure_ascii=False, indent=2)
        except Exception as e:
            raise Exception(f"메타데이터 μ €μž₯ 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
    
    def _load_metadata(self):
        """메타데이터 λ‘œλ“œ"""
        try:
            if Path(self.metadata_path).exists():
                with open(self.metadata_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.documents = data["documents"]
                    self.metadata = data["metadata"]
        except Exception as e:
            raise Exception(f"메타데이터 λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ: {str(e)}")

    def load(self) -> None:
        """μ €μž₯된 메타데이터 뢈러였기"""
        self._load_metadata()

# 싱글톀 μΈμŠ€ν„΄μŠ€ 생성
vector_store = VectorStore()