File size: 7,895 Bytes
e4ac86d
ecab17a
f84a554
ecab17a
 
f84a554
 
 
 
 
 
 
a6680e7
f84a554
a6680e7
f84a554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecab17a
 
 
f84a554
 
 
a6680e7
f84a554
a6e26b8
f84a554
 
a6e26b8
a6680e7
a6e26b8
a6680e7
 
f84a554
 
 
 
 
 
 
 
 
 
a6680e7
f84a554
 
 
 
 
 
 
 
 
 
 
a6680e7
f84a554
 
 
 
 
 
 
 
 
 
 
a6680e7
f84a554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6680e7
f84a554
 
 
 
 
 
 
 
 
 
 
 
 
 
a6680e7
f84a554
 
a6680e7
f84a554
 
 
 
 
 
 
 
 
a6680e7
 
f84a554
a6680e7
ecab17a
 
 
f84a554
 
ecab17a
f84a554
 
ecab17a
f84a554
ecab17a
f84a554
 
 
 
 
ecab17a
 
f84a554
ecab17a
f84a554
ecab17a
f84a554
ecab17a
 
 
 
 
f84a554
 
 
 
 
 
 
 
 
ecab17a
 
 
 
f84a554
ecab17a
f84a554
 
ecab17a
 
 
f84a554
 
 
 
a6680e7
f84a554
 
 
a6680e7
 
 
f84a554
 
 
 
e4ac86d
 
ecab17a
a6e26b8
ecab17a
f84a554
a6e26b8
f84a554
a6e26b8
 
a6680e7
ecab17a
f84a554
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

import os
import json
from typing import List, Dict
import chromadb
from sentence_transformers import SentenceTransformer
import numpy as np
from config import CHROMA_DB_PATH, EMBEDDING_MODEL, EMBEDDING_DIM


class CLIPEmbedder:
    def __init__(self, model_name: str = EMBEDDING_MODEL):
        print(f"πŸ”„ Loading embedding model: {model_name}")
        self.model = SentenceTransformer(model_name)
        print(f"βœ… Model loaded successfully")
    
    def embed(self, text: str) -> List[float]:
        try:
            embedding = self.model.encode(text, convert_to_numpy=False)
            return embedding.tolist() if hasattr(embedding, 'tolist') else embedding
        except Exception as e:
            print(f"Error embedding text: {e}")
            return [0.0] * EMBEDDING_DIM
    
    def embed_batch(self, texts: List[str]) -> List[List[float]]:
        try:
            embeddings = self.model.encode(texts, convert_to_numpy=False)
            return [e.tolist() if hasattr(e, 'tolist') else e for e in embeddings]
        except Exception as e:
            print(f"Error embedding batch: {e}")
            return [[0.0] * EMBEDDING_DIM] * len(texts)


class VectorStore:
    def __init__(self):
        self.persist_directory = CHROMA_DB_PATH
        self.embedder = CLIPEmbedder()
        
        print(f"\nπŸ”„ Initializing ChromaDB at: {self.persist_directory}")
        
        try:
            self.client = chromadb.PersistentClient(
                path=self.persist_directory
            )
            print(f"βœ… ChromaDB PersistentClient initialized")
        except Exception as e:
            print(f"❌ Error initializing ChromaDB: {e}")
            print(f"Trying fallback initialization...")
            self.client = chromadb.PersistentClient(
                path=self.persist_directory
            )
        
        try:
            self.collection = self.client.get_or_create_collection(
                name="multimodal_rag",
                metadata={"hnsw:space": "cosine"}
            )
            count = self.collection.count()
            print(f"βœ… Collection loaded: {count} items in store")
        except Exception as e:
            print(f"Error with collection: {e}")
            self.collection = self.client.get_or_create_collection(
                name="multimodal_rag"
            )

    def add_documents(self, documents: List[Dict], doc_id: str):
        texts = []
        metadatas = []
        ids = []
        
        print(f"\nπŸ“š Adding documents for: {doc_id}")
        
        if 'text' in documents and documents['text']:
            chunks = self._chunk_text(documents['text'], chunk_size=1000, overlap=200)
            for idx, chunk in enumerate(chunks):
                texts.append(chunk)
                metadatas.append({
                    'doc_id': doc_id,
                    'type': 'text',
                    'chunk_idx': str(idx)
                })
                ids.append(f"{doc_id}_text_{idx}")
            print(f"  βœ… Text: {len(chunks)} chunks")
        
        if 'images' in documents:
            image_count = 0
            for idx, image_data in enumerate(documents['images']):
                if image_data.get('ocr_text'):
                    texts.append(f"Image {idx}: {image_data['ocr_text']}")
                    metadatas.append({
                        'doc_id': doc_id,
                        'type': 'image',
                        'image_idx': str(idx),
                        'image_path': image_data.get('path', '')
                    })
                    ids.append(f"{doc_id}_image_{idx}")
                    image_count += 1
            if image_count > 0:
                print(f"  βœ… Images: {image_count} with OCR text")
        
        if 'tables' in documents:
            table_count = 0
            for idx, table_data in enumerate(documents['tables']):
                if table_data.get('content'):
                    texts.append(f"Table {idx}: {table_data.get('content', '')}")
                    metadatas.append({
                        'doc_id': doc_id,
                        'type': 'table',
                        'table_idx': str(idx)
                    })
                    ids.append(f"{doc_id}_table_{idx}")
                    table_count += 1
            if table_count > 0:
                print(f"  βœ… Tables: {table_count}")
        
        if texts:
            print(f"  πŸ”„ Generating {len(texts)} embeddings...")
            embeddings = self.embedder.embed_batch(texts)
            
            try:
                self.collection.add(
                    ids=ids,
                    documents=texts,
                    embeddings=embeddings,
                    metadatas=metadatas
                )
                print(f"βœ… Successfully added {len(texts)} items to vector store")
                print(f"βœ… Data persisted automatically to: {self.persist_directory}")
            except Exception as e:
                print(f"❌ Error adding to collection: {e}")

    def search(self, query: str, n_results: int = 5) -> List[Dict]:
        try:
            query_embedding = self.embedder.embed(query)
            
            results = self.collection.query(
                query_embeddings=[query_embedding],
                n_results=n_results
            )
            
            formatted_results = []
            if results['documents']:
                for i, doc in enumerate(results['documents'][0]):
                    metadata = results['metadatas'][0][i] if results['metadatas'] else {}
                    distance = results['distances'][0][i] if results['distances'] else 0
                    
                    formatted_results.append({
                        'content': doc,
                        'metadata': metadata,
                        'distance': distance,
                        'type': metadata.get('type', 'unknown')
                    })
            
            return formatted_results
        except Exception as e:
            print(f"Error searching vector store: {e}")
            return []

    def _chunk_text(self, text: str, chunk_size: int = 1000, overlap: int = 200) -> List[str]:
        chunks = []
        start = 0
        while start < len(text):
            end = start + chunk_size
            chunks.append(text[start:end])
            start = end - overlap
        return chunks

    def get_collection_info(self) -> Dict:
        try:
            count = self.collection.count()
            return {
                'name': 'multimodal_rag',
                'count': count,
                'status': 'active',
                'persist_path': self.persist_directory
            }
        except Exception as e:
            print(f"Error getting collection info: {e}")
            return {'status': 'error', 'message': str(e)}

    def delete_by_doc_id(self, doc_id: str):
        try:
            # Get all IDs with this doc_id
            results = self.collection.get(where={'doc_id': doc_id})
            if results['ids']:
                self.collection.delete(ids=results['ids'])
                print(f"βœ… Deleted {len(results['ids'])} documents for {doc_id}")
                # Auto-persist on delete
                print(f"βœ… Changes persisted automatically")
        except Exception as e:
            print(f"Error deleting documents: {e}")

    def persist(self):

        print("βœ… Vector store is using auto-persist")

    def clear_all(self):
        try:
            self.client.delete_collection(name="multimodal_rag")
            self.collection = self.client.get_or_create_collection(
                name="multimodal_rag",
                metadata={"hnsw:space": "cosine"}
            )
            print("βœ… Collection cleared and reset")
        except Exception as e:
            print(f"Error clearing collection: {e}")