Spaces:
Running
Running
Update app/policy_vector_db.py
Browse files- app/policy_vector_db.py +48 -108
app/policy_vector_db.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import torch
|
| 4 |
-
from typing import List, Dict
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
import chromadb
|
| 7 |
from chromadb.config import Settings
|
|
@@ -11,20 +11,23 @@ import logging
|
|
| 11 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
-
|
| 15 |
class PolicyVectorDB:
|
| 16 |
"""
|
| 17 |
Manages the connection, population, and querying of a ChromaDB vector database
|
| 18 |
for policy documents.
|
| 19 |
"""
|
| 20 |
-
def __init__(self, persist_directory: str, top_k_default: int =
|
| 21 |
self.persist_directory = persist_directory
|
| 22 |
self.client = chromadb.PersistentClient(path=persist_directory, settings=Settings(allow_reset=True))
|
| 23 |
self.collection_name = "neepco_dop_policies"
|
|
|
|
|
|
|
|
|
|
| 24 |
logger.info("Loading embedding model 'BAAI/bge-large-en-v1.5'. This may take a moment...")
|
| 25 |
-
self.embedding_model = SentenceTransformer('BAAI/bge-large-en-v1.5', device='cpu')
|
| 26 |
logger.info("Embedding model loaded successfully.")
|
| 27 |
-
|
|
|
|
| 28 |
self.top_k_default = top_k_default
|
| 29 |
self.relevance_threshold = relevance_threshold
|
| 30 |
|
|
@@ -40,23 +43,12 @@ class PolicyVectorDB:
|
|
| 40 |
return self.collection
|
| 41 |
|
| 42 |
def _flatten_metadata(self, metadata: Dict) -> Dict:
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
"""
|
| 46 |
-
flattened = {}
|
| 47 |
-
for key, value in metadata.items():
|
| 48 |
-
if isinstance(value, list):
|
| 49 |
-
flattened[key] = ', '.join(map(str, value))
|
| 50 |
-
elif value is None:
|
| 51 |
-
flattened[key] = ''
|
| 52 |
-
else:
|
| 53 |
-
flattened[key] = str(value)
|
| 54 |
-
return flattened
|
| 55 |
|
| 56 |
def add_chunks(self, chunks: List[Dict]):
|
| 57 |
"""
|
| 58 |
Adds a list of chunks to the vector database, skipping any that already exist.
|
| 59 |
-
Token count is added for each chunk if possible.
|
| 60 |
"""
|
| 61 |
collection = self._get_collection()
|
| 62 |
if not chunks:
|
|
@@ -69,122 +61,70 @@ class PolicyVectorDB:
|
|
| 69 |
if not chunks_with_ids:
|
| 70 |
return
|
| 71 |
|
| 72 |
-
|
| 73 |
-
existing_records = collection.get(ids=ids_to_check)
|
| 74 |
-
existing_ids = set(existing_records['ids'])
|
| 75 |
new_chunks = [chunk for chunk in chunks_with_ids if str(chunk.get('id')) not in existing_ids]
|
| 76 |
|
| 77 |
if not new_chunks:
|
| 78 |
logger.info("All provided chunks already exist in the database. No new data to add.")
|
| 79 |
return
|
| 80 |
-
|
| 81 |
logger.info(f"Adding {len(new_chunks)} new chunks to the vector database...")
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
for i in range(0, len(new_chunks), batch_size):
|
| 84 |
batch = new_chunks[i:i + batch_size]
|
| 85 |
-
|
| 86 |
ids = [str(chunk['id']) for chunk in batch]
|
| 87 |
texts = [chunk['text'] for chunk in batch]
|
| 88 |
-
metadatas = []
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
import tiktoken
|
| 94 |
-
encoding = tiktoken.get_encoding("cl100k_base")
|
| 95 |
-
token_count = len(encoding.encode(chunk['text']))
|
| 96 |
-
metadata['token_count'] = str(token_count)
|
| 97 |
-
except Exception:
|
| 98 |
-
pass
|
| 99 |
-
metadatas.append(metadata)
|
| 100 |
-
|
| 101 |
-
embeddings = self.embedding_model.encode(
|
| 102 |
-
texts, normalize_embeddings=True, show_progress_bar=False
|
| 103 |
-
).tolist()
|
| 104 |
collection.add(ids=ids, embeddings=embeddings, documents=texts, metadatas=metadatas)
|
| 105 |
logger.info(f"Added batch {i//batch_size + 1}/{(len(new_chunks) + batch_size - 1) // batch_size}")
|
| 106 |
-
|
| 107 |
logger.info(f"Finished adding {len(new_chunks)} chunks.")
|
| 108 |
|
| 109 |
-
def search(self, query_text: str, top_k:
|
| 110 |
-
filter_by_keywords: Optional[List[str]] = None) -> List[Dict]:
|
| 111 |
"""
|
| 112 |
-
Searches the vector database
|
| 113 |
-
|
| 114 |
"""
|
| 115 |
collection = self._get_collection()
|
| 116 |
-
|
| 117 |
-
# Add instruction prefix for BGE retrieval models.
|
| 118 |
instructed_query = f"Represent this sentence for searching relevant passages: {query_text}"
|
|
|
|
|
|
|
| 119 |
query_embedding = self.embedding_model.encode([instructed_query], normalize_embeddings=True).tolist()
|
|
|
|
| 120 |
k = top_k if top_k is not None else self.top_k_default
|
| 121 |
-
|
| 122 |
-
#
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
"n_results": k * 2,
|
| 130 |
-
"include": ["documents", "metadatas", "distances"]
|
| 131 |
-
}
|
| 132 |
-
if where_clause:
|
| 133 |
-
query_params["where"] = where_clause
|
| 134 |
-
|
| 135 |
-
results = collection.query(**query_params)
|
| 136 |
-
|
| 137 |
search_results = []
|
| 138 |
if results and results.get('documents') and results['documents'][0]:
|
| 139 |
-
for i, doc in enumerate(results['documents']):
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
keep = True
|
| 145 |
-
if filter_by_keywords and metadata.get('financial_keywords'):
|
| 146 |
-
stored_keywords = [kw.strip() for kw in metadata['financial_keywords'].split(',')]
|
| 147 |
-
if not any(kw in stored_keywords for kw in filter_by_keywords):
|
| 148 |
-
keep = False
|
| 149 |
-
if keep and relevance_score >= self.relevance_threshold:
|
| 150 |
search_results.append({
|
| 151 |
'text': doc,
|
| 152 |
-
'metadata':
|
| 153 |
'relevance_score': relevance_score
|
| 154 |
})
|
| 155 |
-
|
|
|
|
| 156 |
return sorted(search_results, key=lambda x: x['relevance_score'], reverse=True)[:k]
|
| 157 |
|
| 158 |
-
def get_stats(self) -> Dict:
|
| 159 |
-
"""
|
| 160 |
-
Get quick analytics for your DB: total chunks, unique sections, counts of keyworded chunks.
|
| 161 |
-
"""
|
| 162 |
-
collection = self._get_collection()
|
| 163 |
-
total_count = collection.count()
|
| 164 |
-
if total_count == 0:
|
| 165 |
-
return {"total_chunks": 0}
|
| 166 |
-
|
| 167 |
-
sample = collection.get(limit=min(100, total_count), include=["metadatas"])
|
| 168 |
-
sections = set()
|
| 169 |
-
has_financial_keywords = 0
|
| 170 |
-
has_authority_keywords = 0
|
| 171 |
-
|
| 172 |
-
for metadata in sample.get('metadatas', []):
|
| 173 |
-
if metadata.get('section'):
|
| 174 |
-
sections.add(metadata['section'])
|
| 175 |
-
if metadata.get('financial_keywords'):
|
| 176 |
-
has_financial_keywords += 1
|
| 177 |
-
if metadata.get('authority_keywords'):
|
| 178 |
-
has_authority_keywords += 1
|
| 179 |
-
|
| 180 |
-
return {
|
| 181 |
-
"total_chunks": total_count,
|
| 182 |
-
"unique_sections": list(sections),
|
| 183 |
-
"chunks_with_financial_keywords": has_financial_keywords,
|
| 184 |
-
"chunks_with_authority_keywords": has_authority_keywords,
|
| 185 |
-
}
|
| 186 |
-
|
| 187 |
-
|
| 188 |
def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> bool:
|
| 189 |
"""
|
| 190 |
Checks if the DB is empty and populates it from a JSONL file if needed.
|
|
@@ -198,7 +138,7 @@ def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> b
|
|
| 198 |
if not os.path.exists(chunks_file_path):
|
| 199 |
logger.error(f"Chunks file not found at '{chunks_file_path}'. Cannot populate DB.")
|
| 200 |
return False
|
| 201 |
-
|
| 202 |
chunks_to_add = []
|
| 203 |
with open(chunks_file_path, 'r', encoding='utf-8') as f:
|
| 204 |
for line in f:
|
|
@@ -206,7 +146,7 @@ def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> b
|
|
| 206 |
chunks_to_add.append(json.loads(line))
|
| 207 |
except json.JSONDecodeError:
|
| 208 |
logger.warning(f"Skipping malformed line in chunks file: {line.strip()}")
|
| 209 |
-
|
| 210 |
if not chunks_to_add:
|
| 211 |
logger.warning(f"Chunks file at '{chunks_file_path}' is empty or invalid. No data to add.")
|
| 212 |
return False
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import torch
|
| 4 |
+
from typing import List, Dict
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
import chromadb
|
| 7 |
from chromadb.config import Settings
|
|
|
|
| 11 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
|
|
|
| 14 |
class PolicyVectorDB:
|
| 15 |
"""
|
| 16 |
Manages the connection, population, and querying of a ChromaDB vector database
|
| 17 |
for policy documents.
|
| 18 |
"""
|
| 19 |
+
def __init__(self, persist_directory: str, top_k_default: int = 5, relevance_threshold: float = 0.5):
|
| 20 |
self.persist_directory = persist_directory
|
| 21 |
self.client = chromadb.PersistentClient(path=persist_directory, settings=Settings(allow_reset=True))
|
| 22 |
self.collection_name = "neepco_dop_policies"
|
| 23 |
+
|
| 24 |
+
# Using a powerful open-source embedding model.
|
| 25 |
+
# Change 'cpu' to 'cuda' if a GPU is available for significantly faster embedding.
|
| 26 |
logger.info("Loading embedding model 'BAAI/bge-large-en-v1.5'. This may take a moment...")
|
| 27 |
+
self.embedding_model = SentenceTransformer('BAAI/bge-large-en-v1.5', device='cpu')
|
| 28 |
logger.info("Embedding model loaded successfully.")
|
| 29 |
+
|
| 30 |
+
self.collection = None # Initialize collection as None for lazy loading
|
| 31 |
self.top_k_default = top_k_default
|
| 32 |
self.relevance_threshold = relevance_threshold
|
| 33 |
|
|
|
|
| 43 |
return self.collection
|
| 44 |
|
| 45 |
def _flatten_metadata(self, metadata: Dict) -> Dict:
|
| 46 |
+
"""Ensures all metadata values are strings, as required by some ChromaDB versions."""
|
| 47 |
+
return {key: str(value) for key, value in metadata.items()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
def add_chunks(self, chunks: List[Dict]):
|
| 50 |
"""
|
| 51 |
Adds a list of chunks to the vector database, skipping any that already exist.
|
|
|
|
| 52 |
"""
|
| 53 |
collection = self._get_collection()
|
| 54 |
if not chunks:
|
|
|
|
| 61 |
if not chunks_with_ids:
|
| 62 |
return
|
| 63 |
|
| 64 |
+
existing_ids = set(collection.get(ids=[str(c['id']) for c in chunks_with_ids])['ids'])
|
|
|
|
|
|
|
| 65 |
new_chunks = [chunk for chunk in chunks_with_ids if str(chunk.get('id')) not in existing_ids]
|
| 66 |
|
| 67 |
if not new_chunks:
|
| 68 |
logger.info("All provided chunks already exist in the database. No new data to add.")
|
| 69 |
return
|
| 70 |
+
|
| 71 |
logger.info(f"Adding {len(new_chunks)} new chunks to the vector database...")
|
| 72 |
+
|
| 73 |
+
# Process in batches for efficiency
|
| 74 |
+
batch_size = 32 # Reduced batch size for potentially large embeddings
|
| 75 |
for i in range(0, len(new_chunks), batch_size):
|
| 76 |
batch = new_chunks[i:i + batch_size]
|
| 77 |
+
|
| 78 |
ids = [str(chunk['id']) for chunk in batch]
|
| 79 |
texts = [chunk['text'] for chunk in batch]
|
| 80 |
+
metadatas = [self._flatten_metadata(chunk.get('metadata', {})) for chunk in batch]
|
| 81 |
+
|
| 82 |
+
# For BGE models, it's recommended not to add instructions to the document embeddings
|
| 83 |
+
embeddings = self.embedding_model.encode(texts, normalize_embeddings=True, show_progress_bar=False).tolist()
|
| 84 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
collection.add(ids=ids, embeddings=embeddings, documents=texts, metadatas=metadatas)
|
| 86 |
logger.info(f"Added batch {i//batch_size + 1}/{(len(new_chunks) + batch_size - 1) // batch_size}")
|
| 87 |
+
|
| 88 |
logger.info(f"Finished adding {len(new_chunks)} chunks.")
|
| 89 |
|
| 90 |
+
def search(self, query_text: str, top_k: int = None) -> List[Dict]:
|
|
|
|
| 91 |
"""
|
| 92 |
+
Searches the vector database for a given query text.
|
| 93 |
+
Returns a list of results filtered by a relevance threshold.
|
| 94 |
"""
|
| 95 |
collection = self._get_collection()
|
| 96 |
+
|
| 97 |
+
# ✅ IMPROVEMENT: Add the recommended instruction prefix for BGE retrieval models.
|
| 98 |
instructed_query = f"Represent this sentence for searching relevant passages: {query_text}"
|
| 99 |
+
|
| 100 |
+
# ✅ IMPROVEMENT: Normalize embeddings for more accurate similarity search.
|
| 101 |
query_embedding = self.embedding_model.encode([instructed_query], normalize_embeddings=True).tolist()
|
| 102 |
+
|
| 103 |
k = top_k if top_k is not None else self.top_k_default
|
| 104 |
+
|
| 105 |
+
# Retrieve more results initially to allow for filtering
|
| 106 |
+
results = collection.query(
|
| 107 |
+
query_embeddings=query_embedding,
|
| 108 |
+
n_results=k * 2, # Retrieve more to filter by threshold
|
| 109 |
+
include=["documents", "metadatas", "distances"]
|
| 110 |
+
)
|
| 111 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
search_results = []
|
| 113 |
if results and results.get('documents') and results['documents'][0]:
|
| 114 |
+
for i, doc in enumerate(results['documents'][0]):
|
| 115 |
+
# The distance for normalized embeddings is often interpreted as 1 - cosine_similarity
|
| 116 |
+
relevance_score = 1 - results['distances'][0][i]
|
| 117 |
+
|
| 118 |
+
if relevance_score >= self.relevance_threshold:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
search_results.append({
|
| 120 |
'text': doc,
|
| 121 |
+
'metadata': results['metadatas'][0][i],
|
| 122 |
'relevance_score': relevance_score
|
| 123 |
})
|
| 124 |
+
|
| 125 |
+
# Sort by relevance score and return the top_k results
|
| 126 |
return sorted(search_results, key=lambda x: x['relevance_score'], reverse=True)[:k]
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> bool:
|
| 129 |
"""
|
| 130 |
Checks if the DB is empty and populates it from a JSONL file if needed.
|
|
|
|
| 138 |
if not os.path.exists(chunks_file_path):
|
| 139 |
logger.error(f"Chunks file not found at '{chunks_file_path}'. Cannot populate DB.")
|
| 140 |
return False
|
| 141 |
+
|
| 142 |
chunks_to_add = []
|
| 143 |
with open(chunks_file_path, 'r', encoding='utf-8') as f:
|
| 144 |
for line in f:
|
|
|
|
| 146 |
chunks_to_add.append(json.loads(line))
|
| 147 |
except json.JSONDecodeError:
|
| 148 |
logger.warning(f"Skipping malformed line in chunks file: {line.strip()}")
|
| 149 |
+
|
| 150 |
if not chunks_to_add:
|
| 151 |
logger.warning(f"Chunks file at '{chunks_file_path}' is empty or invalid. No data to add.")
|
| 152 |
return False
|