Spaces:
Sleeping
Sleeping
File size: 9,217 Bytes
a6680e7 ecab17a f84a554 ecab17a f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 ecab17a a6680e7 ecab17a f84a554 a6680e7 f84a554 a6680e7 a6e26b8 f84a554 a6e26b8 a6680e7 a6e26b8 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 ecab17a 292292a ecab17a f84a554 ecab17a f84a554 ecab17a f84a554 a6680e7 ecab17a f84a554 ecab17a f84a554 ecab17a f84a554 ecab17a f84a554 ecab17a f84a554 a6680e7 f84a554 ecab17a a6680e7 ecab17a f84a554 ecab17a f84a554 ecab17a f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 f84a554 a6680e7 ecab17a a6e26b8 a6680e7 ecab17a a6680e7 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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
"""
Vector Store and Embeddings Module using ChromaDB with sentence-transformers
UPDATED for ChromaDB v0.4.22+ (auto-persist, no manual persist needed)
"""
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:
"""Custom embedder using sentence-transformers for multimodal content"""
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]:
"""Generate embedding for text"""
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]]:
"""Generate embeddings for batch of texts"""
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:
"""Vector store manager using ChromaDB (v0.4.22+ with auto-persist)"""
def __init__(self):
self.persist_directory = CHROMA_DB_PATH
self.embedder = CLIPEmbedder()
print(f"\nπ Initializing ChromaDB at: {self.persist_directory}")
# NEW ChromaDB v0.4.22+ - PersistentClient auto-persists
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
)
# Get or create collection
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):
"""Add documents to vector store"""
texts = []
metadatas = []
ids = []
print(f"\nπ Adding documents for: {doc_id}")
# Add text chunks
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")
# Add image descriptions and OCR text
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")
# Add table content
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:
# Generate embeddings
print(f" π Generating {len(texts)} embeddings...")
embeddings = self.embedder.embed_batch(texts)
# Add to collection
try:
self.collection.add(
ids=ids,
documents=texts,
embeddings=embeddings,
metadatas=metadatas
)
print(f"β
Successfully added {len(texts)} items to vector store")
# Auto-persist happens here
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]:
"""Search vector store for similar documents"""
try:
query_embedding = self.embedder.embed(query)
results = self.collection.query(
query_embeddings=[query_embedding],
n_results=n_results
)
# Format 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]:
"""Split text into chunks with overlap"""
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:
"""Get information about the collection"""
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):
"""Delete all documents related to a specific doc_id"""
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):
"""
No-op for compatibility with older code.
ChromaDB v0.4.22+ uses PersistentClient which auto-persists.
This method kept for backward compatibility.
"""
print("β
Vector store is using auto-persist (no manual persist needed)")
def clear_all(self):
"""Clear all documents from collection"""
try:
# Delete collection and recreate
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}") |