Spaces:
Sleeping
Sleeping
Upload 14 files
Browse files- requirements.txt +1 -0
- src/retriever.py +32 -27
requirements.txt
CHANGED
|
@@ -10,3 +10,4 @@ groq>=1.7.0
|
|
| 10 |
PyPDF2>=3.0.0
|
| 11 |
pymysql>=1.1.0
|
| 12 |
cryptography>=42.0.0
|
|
|
|
|
|
| 10 |
PyPDF2>=3.0.0
|
| 11 |
pymysql>=1.1.0
|
| 12 |
cryptography>=42.0.0
|
| 13 |
+
fastembed>=0.4.0
|
src/retriever.py
CHANGED
|
@@ -167,14 +167,15 @@ class HybridLegalRetriever:
|
|
| 167 |
self,
|
| 168 |
query: str,
|
| 169 |
top_k: int = 6,
|
| 170 |
-
vector_weight: float = 0.
|
| 171 |
-
bm25_weight: float = 0.
|
| 172 |
chapter_filter: Optional[str] = None
|
| 173 |
) -> List[Dict[str, Any]]:
|
| 174 |
if not self.indexed_chunks:
|
| 175 |
return []
|
| 176 |
|
| 177 |
clean_query = query.strip()
|
|
|
|
| 178 |
|
| 179 |
# 1. Dense Semantic Search via HuggingFace CPU embedding (fastembed BAAI/bge-small-en-v1.5)
|
| 180 |
vector_scores: Dict[str, float] = {}
|
|
@@ -187,7 +188,7 @@ class HybridLegalRetriever:
|
|
| 187 |
|
| 188 |
vector_res = self.collection.query(
|
| 189 |
query_embeddings=[query_embedding],
|
| 190 |
-
n_results=
|
| 191 |
where=where_filter
|
| 192 |
)
|
| 193 |
|
|
@@ -208,7 +209,7 @@ class HybridLegalRetriever:
|
|
| 208 |
doc_scores = self.bm25.get_scores(tokens)
|
| 209 |
max_bm25 = np.max(doc_scores) if len(doc_scores) > 0 and np.max(doc_scores) > 0 else 1.0
|
| 210 |
|
| 211 |
-
top_bm25_indices = np.argsort(doc_scores)[::-1][:
|
| 212 |
for idx in top_bm25_indices:
|
| 213 |
chunk = self.indexed_chunks[idx]
|
| 214 |
if chapter_filter and chapter_filter != "All" and chunk["chapter"] != chapter_filter:
|
|
@@ -218,7 +219,6 @@ class HybridLegalRetriever:
|
|
| 218 |
# 3. Hybrid Merge (Weighted Rank + Normalized Score)
|
| 219 |
combined_scores: Dict[str, float] = {}
|
| 220 |
all_candidate_ids = set(vector_scores.keys()).union(set(bm25_scores.keys()))
|
| 221 |
-
|
| 222 |
chunk_dict = {c["chunk_id"]: c for c in self.indexed_chunks}
|
| 223 |
|
| 224 |
for doc_id in all_candidate_ids:
|
|
@@ -226,39 +226,44 @@ class HybridLegalRetriever:
|
|
| 226 |
b_score = bm25_scores.get(doc_id, 0.0)
|
| 227 |
combined_scores[doc_id] = (vector_weight * v_score) + (bm25_weight * b_score)
|
| 228 |
|
| 229 |
-
|
| 230 |
|
| 231 |
-
|
|
|
|
| 232 |
seen_chunk_ids = set()
|
| 233 |
chunk_idx_map = {c["chunk_id"]: i for i, c in enumerate(self.indexed_chunks)}
|
| 234 |
|
| 235 |
-
for doc_id, score in
|
|
|
|
|
|
|
| 236 |
chunk = chunk_dict.get(doc_id)
|
| 237 |
if chunk and doc_id not in seen_chunk_ids:
|
| 238 |
seen_chunk_ids.add(doc_id)
|
| 239 |
-
|
| 240 |
**chunk,
|
| 241 |
"retrieval_score": round(score, 4),
|
| 242 |
"vector_score": round(vector_scores.get(doc_id, 0.0), 4),
|
| 243 |
"bm25_score": round(bm25_scores.get(doc_id, 0.0), 4)
|
| 244 |
})
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
|
|
|
|
|
|
| 263 |
|
| 264 |
-
return results
|
|
|
|
| 167 |
self,
|
| 168 |
query: str,
|
| 169 |
top_k: int = 6,
|
| 170 |
+
vector_weight: float = 0.55,
|
| 171 |
+
bm25_weight: float = 0.45,
|
| 172 |
chapter_filter: Optional[str] = None
|
| 173 |
) -> List[Dict[str, Any]]:
|
| 174 |
if not self.indexed_chunks:
|
| 175 |
return []
|
| 176 |
|
| 177 |
clean_query = query.strip()
|
| 178 |
+
candidate_k = min(max(top_k * 10, 60), len(self.indexed_chunks))
|
| 179 |
|
| 180 |
# 1. Dense Semantic Search via HuggingFace CPU embedding (fastembed BAAI/bge-small-en-v1.5)
|
| 181 |
vector_scores: Dict[str, float] = {}
|
|
|
|
| 188 |
|
| 189 |
vector_res = self.collection.query(
|
| 190 |
query_embeddings=[query_embedding],
|
| 191 |
+
n_results=candidate_k,
|
| 192 |
where=where_filter
|
| 193 |
)
|
| 194 |
|
|
|
|
| 209 |
doc_scores = self.bm25.get_scores(tokens)
|
| 210 |
max_bm25 = np.max(doc_scores) if len(doc_scores) > 0 and np.max(doc_scores) > 0 else 1.0
|
| 211 |
|
| 212 |
+
top_bm25_indices = np.argsort(doc_scores)[::-1][:candidate_k]
|
| 213 |
for idx in top_bm25_indices:
|
| 214 |
chunk = self.indexed_chunks[idx]
|
| 215 |
if chapter_filter and chapter_filter != "All" and chunk["chapter"] != chapter_filter:
|
|
|
|
| 219 |
# 3. Hybrid Merge (Weighted Rank + Normalized Score)
|
| 220 |
combined_scores: Dict[str, float] = {}
|
| 221 |
all_candidate_ids = set(vector_scores.keys()).union(set(bm25_scores.keys()))
|
|
|
|
| 222 |
chunk_dict = {c["chunk_id"]: c for c in self.indexed_chunks}
|
| 223 |
|
| 224 |
for doc_id in all_candidate_ids:
|
|
|
|
| 226 |
b_score = bm25_scores.get(doc_id, 0.0)
|
| 227 |
combined_scores[doc_id] = (vector_weight * v_score) + (bm25_weight * b_score)
|
| 228 |
|
| 229 |
+
sorted_candidates = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)
|
| 230 |
|
| 231 |
+
# Primary distinct highest-scoring chunks
|
| 232 |
+
primary_results = []
|
| 233 |
seen_chunk_ids = set()
|
| 234 |
chunk_idx_map = {c["chunk_id"]: i for i, c in enumerate(self.indexed_chunks)}
|
| 235 |
|
| 236 |
+
for doc_id, score in sorted_candidates:
|
| 237 |
+
if len(primary_results) >= top_k:
|
| 238 |
+
break
|
| 239 |
chunk = chunk_dict.get(doc_id)
|
| 240 |
if chunk and doc_id not in seen_chunk_ids:
|
| 241 |
seen_chunk_ids.add(doc_id)
|
| 242 |
+
primary_results.append({
|
| 243 |
**chunk,
|
| 244 |
"retrieval_score": round(score, 4),
|
| 245 |
"vector_score": round(vector_scores.get(doc_id, 0.0), 4),
|
| 246 |
"bm25_score": round(bm25_scores.get(doc_id, 0.0), 4)
|
| 247 |
})
|
| 248 |
|
| 249 |
+
# Neighbor expansion: enrich the top primary results with their preceding and succeeding statutory chunks
|
| 250 |
+
results = list(primary_results)
|
| 251 |
+
for chunk in primary_results[:3]:
|
| 252 |
+
c_idx = chunk_idx_map.get(chunk["chunk_id"])
|
| 253 |
+
if c_idx is not None:
|
| 254 |
+
for offset in [-1, 1, 2]:
|
| 255 |
+
target_idx = c_idx + offset
|
| 256 |
+
if 0 <= target_idx < len(self.indexed_chunks):
|
| 257 |
+
nbr_chunk = self.indexed_chunks[target_idx]
|
| 258 |
+
nbr_id = nbr_chunk["chunk_id"]
|
| 259 |
+
if nbr_chunk.get("chapter") == chunk.get("chapter") and nbr_id not in seen_chunk_ids and len(results) < top_k + 4:
|
| 260 |
+
seen_chunk_ids.add(nbr_id)
|
| 261 |
+
decay = 0.96 ** abs(offset)
|
| 262 |
+
results.append({
|
| 263 |
+
**nbr_chunk,
|
| 264 |
+
"retrieval_score": round(chunk["retrieval_score"] * decay, 4),
|
| 265 |
+
"vector_score": 0.0,
|
| 266 |
+
"bm25_score": round(chunk["retrieval_score"] * decay, 4)
|
| 267 |
+
})
|
| 268 |
|
| 269 |
+
return results
|