Spaces:
Sleeping
Sleeping
Upload 47 files
Browse files- data/.DS_Store +0 -0
- data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/data_level0.bin +3 -0
- data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/header.bin +3 -0
- data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/index_metadata.pickle +3 -0
- data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/length.bin +3 -0
- data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/link_lists.bin +3 -0
- data/index/chroma/chroma.sqlite3 +2 -2
- src/rag_engine.py +39 -41
- src/retriever.py +99 -85
data/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/data_level0.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:423451437a04a3330e17b40e30ee155cf9b8ef9664dc26316cfdc3be547a8b16
|
| 3 |
+
size 3432448
|
data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/header.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3151fea805a8e5192b86c250a6e20c543792821ac2c042fcd1e1d0b5cbeced79
|
| 3 |
+
size 100
|
data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/index_metadata.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f63571043ba477231445cdd263ca65f7bcf7139204b83ad2d67c5c436ab8a19d
|
| 3 |
+
size 221820
|
data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/length.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3175353d921361a795a5f08ae15e5350cdd5a63ff016111dbbadc3f503f7ae1e
|
| 3 |
+
size 8192
|
data/index/chroma/cdd2d4b6-28a3-4a09-b666-1480dba8711f/link_lists.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a786aa2c707776c0b63dd83d339d80bf53df2b5ee29f9ec240cb810b10d9d214
|
| 3 |
+
size 18188
|
data/index/chroma/chroma.sqlite3
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd400b49ec64864bc0d65982e441e0260251049f20347a121f6c23aefaa2c53d
|
| 3 |
+
size 21999616
|
src/rag_engine.py
CHANGED
|
@@ -264,47 +264,45 @@ class LegalRAGEngine:
|
|
| 264 |
return normalized
|
| 265 |
|
| 266 |
def _enhance_search_query(self, query: str) -> str:
|
| 267 |
-
"""
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
if additions:
|
| 307 |
-
return f"{query} {' '.join(additions)}"
|
| 308 |
return query
|
| 309 |
|
| 310 |
def decide_and_route(self, query: str, history: List[Dict[str, str]]) -> Dict[str, Any]:
|
|
|
|
| 264 |
return normalized
|
| 265 |
|
| 266 |
def _enhance_search_query(self, query: str) -> str:
|
| 267 |
+
"""Uses fast instruction LLM to autonomously extract legal topics, acts, and sections without hardcoded lists."""
|
| 268 |
+
clean_q = query.strip()
|
| 269 |
+
if not clean_q:
|
| 270 |
+
return query
|
| 271 |
+
|
| 272 |
+
groq_clients = self.get_groq_clients_in_rotation()
|
| 273 |
+
if not groq_clients:
|
| 274 |
+
return query
|
| 275 |
+
|
| 276 |
+
prompt = f"""You are an autonomous legal query analyzer for CA Foundation Paper-2: Business Laws (ICAI syllabus: Contract Act 1872, Sale of Goods Act 1930, Partnership Act 1932, LLP Act 2008, Companies Act 2013, Negotiable Instruments Act 1881).
|
| 277 |
+
|
| 278 |
+
Given this user question or case scenario, output ONLY 3 to 6 essential legal search terms (doctrine name, statutory concept, governing Act, and section numbers if applicable) to look up in the ICAI study material.
|
| 279 |
+
Do NOT explain anything. Return ONLY the search terms on a single line.
|
| 280 |
+
|
| 281 |
+
Question:
|
| 282 |
+
{clean_q}"""
|
| 283 |
+
|
| 284 |
+
for client in groq_clients:
|
| 285 |
+
try:
|
| 286 |
+
resp = client.chat.completions.create(
|
| 287 |
+
model="qwen/qwen3.8-27b",
|
| 288 |
+
messages=[{"role": "user", "content": prompt}],
|
| 289 |
+
temperature=0.0,
|
| 290 |
+
max_tokens=35,
|
| 291 |
+
timeout=4.0
|
| 292 |
+
)
|
| 293 |
+
if resp and resp.choices and resp.choices[0].message:
|
| 294 |
+
extracted = resp.choices[0].message.content.strip()
|
| 295 |
+
# Strip quotes or markdown backticks if any
|
| 296 |
+
extracted = re.sub(r"[\"`\*]", "", extracted).replace("\n", " ").strip()
|
| 297 |
+
if extracted and len(extracted) > 3:
|
| 298 |
+
# For long case studies/story questions, the model-extracted statutory terms
|
| 299 |
+
# provide exact alignment with textbook chapter/section titles without noise.
|
| 300 |
+
if len(clean_q.split()) > 10:
|
| 301 |
+
return extracted
|
| 302 |
+
return f"{clean_q} {extracted}"
|
| 303 |
+
except Exception as e:
|
| 304 |
+
continue
|
| 305 |
+
|
|
|
|
|
|
|
| 306 |
return query
|
| 307 |
|
| 308 |
def decide_and_route(self, query: str, history: List[Dict[str, str]]) -> Dict[str, Any]:
|
src/retriever.py
CHANGED
|
@@ -11,40 +11,17 @@ from dotenv import load_dotenv
|
|
| 11 |
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
r"\bcorporte\b": "corporate",
|
| 20 |
-
r"\bpromisor\b": "promisor",
|
| 21 |
-
r"\bpromiser\b": "promisor",
|
| 22 |
-
r"\blibility\b": "liability",
|
| 23 |
-
r"\bliabilty\b": "liability",
|
| 24 |
-
r"\bseverel\b": "several",
|
| 25 |
-
r"\bseverall\b": "several",
|
| 26 |
-
r"\bagrement\b": "agreement",
|
| 27 |
-
r"\bpartnr\b": "partner",
|
| 28 |
-
r"\bpartneship\b": "partnership",
|
| 29 |
-
r"\bconsideratn\b": "consideration",
|
| 30 |
-
r"\bultra viers\b": "ultra vires",
|
| 31 |
-
r"\bultravires\b": "ultra vires",
|
| 32 |
-
r"\bcaveat emptre\b": "caveat emptor",
|
| 33 |
-
r"\bcompnay\b": "company",
|
| 34 |
-
r"\bcompnies\b": "companies"
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
def normalize_legal_spelling(text: str) -> str:
|
| 38 |
-
cleaned = text
|
| 39 |
-
for pattern, rep in LEGAL_SPELL_MAP.items():
|
| 40 |
-
cleaned = re.sub(pattern, rep, cleaned, flags=re.IGNORECASE)
|
| 41 |
-
return cleaned
|
| 42 |
|
| 43 |
class HybridLegalRetriever:
|
| 44 |
def __init__(
|
| 45 |
self,
|
| 46 |
persist_dir: str = "data/index",
|
| 47 |
-
embedding_model: str = "
|
| 48 |
):
|
| 49 |
self.persist_dir = persist_dir
|
| 50 |
self.embedding_model = embedding_model
|
|
@@ -53,7 +30,17 @@ class HybridLegalRetriever:
|
|
| 53 |
self.cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
|
| 54 |
self.cf_account_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
|
| 55 |
|
| 56 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
self.chroma_client = None
|
| 58 |
self.collection = None
|
| 59 |
chroma_path = os.path.join(persist_dir, "chroma")
|
|
@@ -64,7 +51,7 @@ class HybridLegalRetriever:
|
|
| 64 |
metadata={"hnsw:space": "cosine"}
|
| 65 |
)
|
| 66 |
except Exception as e:
|
| 67 |
-
print(f"Notice: Persistent ChromaDB init encountered {e}. Using in-memory client
|
| 68 |
try:
|
| 69 |
self.chroma_client = chromadb.Client()
|
| 70 |
self.collection = self.chroma_client.get_or_create_collection(
|
|
@@ -72,7 +59,7 @@ class HybridLegalRetriever:
|
|
| 72 |
metadata={"hnsw:space": "cosine"}
|
| 73 |
)
|
| 74 |
except Exception as inner_e:
|
| 75 |
-
print(f"Notice: Vector collection unavailable ({inner_e}). Operating in
|
| 76 |
self.collection = None
|
| 77 |
|
| 78 |
self.bm25_index_path = os.path.join(persist_dir, "bm25.pkl")
|
|
@@ -85,31 +72,34 @@ class HybridLegalRetriever:
|
|
| 85 |
def _tokenize(self, text: str) -> List[str]:
|
| 86 |
return [w.lower() for w in text.split() if w.isalnum()]
|
| 87 |
|
| 88 |
-
def
|
| 89 |
"""
|
| 90 |
-
Generates dense vector embeddings
|
| 91 |
-
|
| 92 |
"""
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
def _load_bm25_and_cache(self):
|
| 115 |
if os.path.exists(self.chunks_cache_path) and os.path.exists(self.bm25_index_path):
|
|
@@ -158,7 +148,7 @@ class HybridLegalRetriever:
|
|
| 158 |
"chunk_id": c["chunk_id"]
|
| 159 |
} for c in batch]
|
| 160 |
|
| 161 |
-
embeddings = self.
|
| 162 |
|
| 163 |
self.collection.upsert(
|
| 164 |
ids=ids,
|
|
@@ -168,11 +158,10 @@ class HybridLegalRetriever:
|
|
| 168 |
)
|
| 169 |
print(f"Indexed batch {i//batch_size + 1}/{(len(chunks)-1)//batch_size + 1}")
|
| 170 |
|
| 171 |
-
print("✔
|
| 172 |
|
| 173 |
def _tokenize(self, text: str) -> List[str]:
|
| 174 |
-
|
| 175 |
-
return [w.lower() for w in cleaned.split() if w.isalnum()]
|
| 176 |
|
| 177 |
def retrieve(
|
| 178 |
self,
|
|
@@ -185,27 +174,29 @@ class HybridLegalRetriever:
|
|
| 185 |
if not self.indexed_chunks:
|
| 186 |
return []
|
| 187 |
|
| 188 |
-
clean_query =
|
| 189 |
|
| 190 |
-
# 1. Dense Semantic Search via
|
| 191 |
vector_scores: Dict[str, float] = {}
|
| 192 |
if self.collection is not None:
|
| 193 |
try:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
except Exception as e:
|
| 208 |
-
|
| 209 |
vector_weight = 0.0
|
| 210 |
bm25_weight = 1.0
|
| 211 |
|
|
@@ -213,15 +204,16 @@ class HybridLegalRetriever:
|
|
| 213 |
bm25_scores: Dict[str, float] = {}
|
| 214 |
if self.bm25:
|
| 215 |
tokens = self._tokenize(clean_query)
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
| 225 |
|
| 226 |
# 3. Hybrid Merge (Weighted Rank + Normalized Score)
|
| 227 |
combined_scores: Dict[str, float] = {}
|
|
@@ -237,9 +229,13 @@ class HybridLegalRetriever:
|
|
| 237 |
sorted_ids = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)[:top_k]
|
| 238 |
|
| 239 |
results = []
|
|
|
|
|
|
|
|
|
|
| 240 |
for doc_id, score in sorted_ids:
|
| 241 |
chunk = chunk_dict.get(doc_id)
|
| 242 |
-
if chunk:
|
|
|
|
| 243 |
results.append({
|
| 244 |
**chunk,
|
| 245 |
"retrieval_score": round(score, 4),
|
|
@@ -247,4 +243,22 @@ class HybridLegalRetriever:
|
|
| 247 |
"bm25_score": round(bm25_scores.get(doc_id, 0.0), 4)
|
| 248 |
})
|
| 249 |
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
+
try:
|
| 15 |
+
from fastembed import TextEmbedding
|
| 16 |
+
HAS_FASTEMBED = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
HAS_FASTEMBED = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
class HybridLegalRetriever:
|
| 21 |
def __init__(
|
| 22 |
self,
|
| 23 |
persist_dir: str = "data/index",
|
| 24 |
+
embedding_model: str = "BAAI/bge-small-en-v1.5"
|
| 25 |
):
|
| 26 |
self.persist_dir = persist_dir
|
| 27 |
self.embedding_model = embedding_model
|
|
|
|
| 30 |
self.cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
|
| 31 |
self.cf_account_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
|
| 32 |
|
| 33 |
+
# Local HuggingFace CPU Embedding Model (ONNX accelerated, 0 rate-limits, highest accuracy)
|
| 34 |
+
self.hf_embedder = None
|
| 35 |
+
if HAS_FASTEMBED:
|
| 36 |
+
try:
|
| 37 |
+
self.hf_embedder = TextEmbedding(model_name="BAAI/bge-small-en-v1.5")
|
| 38 |
+
print("✔ Local HuggingFace CPU Embedding engine loaded (BAAI/bge-small-en-v1.5)")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"Notice: Local fastembed initialization failed: {e}. Falling back to Cloudflare/BM25.")
|
| 41 |
+
self.hf_embedder = None
|
| 42 |
+
|
| 43 |
+
# Initialize ChromaDB client with persistent local vector storage
|
| 44 |
self.chroma_client = None
|
| 45 |
self.collection = None
|
| 46 |
chroma_path = os.path.join(persist_dir, "chroma")
|
|
|
|
| 51 |
metadata={"hnsw:space": "cosine"}
|
| 52 |
)
|
| 53 |
except Exception as e:
|
| 54 |
+
print(f"Notice: Persistent ChromaDB init encountered {e}. Using in-memory client.")
|
| 55 |
try:
|
| 56 |
self.chroma_client = chromadb.Client()
|
| 57 |
self.collection = self.chroma_client.get_or_create_collection(
|
|
|
|
| 59 |
metadata={"hnsw:space": "cosine"}
|
| 60 |
)
|
| 61 |
except Exception as inner_e:
|
| 62 |
+
print(f"Notice: Vector collection unavailable ({inner_e}). Operating in BM25 retrieval mode.")
|
| 63 |
self.collection = None
|
| 64 |
|
| 65 |
self.bm25_index_path = os.path.join(persist_dir, "bm25.pkl")
|
|
|
|
| 72 |
def _tokenize(self, text: str) -> List[str]:
|
| 73 |
return [w.lower() for w in text.split() if w.isalnum()]
|
| 74 |
|
| 75 |
+
def _get_embeddings(self, texts: List[str]) -> List[List[float]]:
|
| 76 |
"""
|
| 77 |
+
Generates dense vector embeddings using local HuggingFace CPU ONNX model.
|
| 78 |
+
Falls back to Cloudflare Workers AI if fastembed is unavailable.
|
| 79 |
"""
|
| 80 |
+
if self.hf_embedder is not None:
|
| 81 |
+
embeddings = list(self.hf_embedder.embed(texts, batch_size=64))
|
| 82 |
+
return [e.tolist() for e in embeddings]
|
| 83 |
+
|
| 84 |
+
# Fallback to Cloudflare Workers AI API if local embedder is not loaded
|
| 85 |
+
if self.cf_account_id and self.cf_token:
|
| 86 |
+
url = f"https://api.cloudflare.com/client/v4/accounts/{self.cf_account_id}/ai/run/@cf/baai/bge-small-en-v1.5"
|
| 87 |
+
headers = {
|
| 88 |
+
"Authorization": f"Bearer {self.cf_token}",
|
| 89 |
+
"Content-Type": "application/json"
|
| 90 |
+
}
|
| 91 |
+
all_embeddings = []
|
| 92 |
+
batch_size = 20
|
| 93 |
+
for i in range(0, len(texts), batch_size):
|
| 94 |
+
batch = texts[i:i+batch_size]
|
| 95 |
+
resp = requests.post(url, headers=headers, json={"text": batch}, timeout=60)
|
| 96 |
+
data = resp.json()
|
| 97 |
+
if not data.get("success"):
|
| 98 |
+
raise RuntimeError(f"Cloudflare embedding failed: {data.get('errors')}")
|
| 99 |
+
all_embeddings.extend(data["result"]["data"])
|
| 100 |
+
return all_embeddings
|
| 101 |
+
|
| 102 |
+
raise RuntimeError("No embedding provider available.")
|
| 103 |
|
| 104 |
def _load_bm25_and_cache(self):
|
| 105 |
if os.path.exists(self.chunks_cache_path) and os.path.exists(self.bm25_index_path):
|
|
|
|
| 148 |
"chunk_id": c["chunk_id"]
|
| 149 |
} for c in batch]
|
| 150 |
|
| 151 |
+
embeddings = self._get_embeddings(texts)
|
| 152 |
|
| 153 |
self.collection.upsert(
|
| 154 |
ids=ids,
|
|
|
|
| 158 |
)
|
| 159 |
print(f"Indexed batch {i//batch_size + 1}/{(len(chunks)-1)//batch_size + 1}")
|
| 160 |
|
| 161 |
+
print("✔ Hybrid Indexing complete!")
|
| 162 |
|
| 163 |
def _tokenize(self, text: str) -> List[str]:
|
| 164 |
+
return [w.lower() for w in text.split() if w.isalnum()]
|
|
|
|
| 165 |
|
| 166 |
def retrieve(
|
| 167 |
self,
|
|
|
|
| 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] = {}
|
| 181 |
if self.collection is not None:
|
| 182 |
try:
|
| 183 |
+
query_embeddings = self._get_embeddings([clean_query])
|
| 184 |
+
if query_embeddings:
|
| 185 |
+
query_embedding = query_embeddings[0]
|
| 186 |
+
where_filter = {"chapter": chapter_filter} if chapter_filter and chapter_filter != "All" else None
|
| 187 |
+
|
| 188 |
+
vector_res = self.collection.query(
|
| 189 |
+
query_embeddings=[query_embedding],
|
| 190 |
+
n_results=min(top_k * 4, len(self.indexed_chunks)),
|
| 191 |
+
where=where_filter
|
| 192 |
+
)
|
| 193 |
|
| 194 |
+
if vector_res and vector_res["ids"] and vector_res["ids"][0]:
|
| 195 |
+
for doc_id, dist in zip(vector_res["ids"][0], vector_res["distances"][0]):
|
| 196 |
+
similarity = 1.0 - dist
|
| 197 |
+
vector_scores[doc_id] = max(0.0, similarity)
|
| 198 |
except Exception as e:
|
| 199 |
+
print(f"Notice: Dense vector retrieval fallback: {e}")
|
| 200 |
vector_weight = 0.0
|
| 201 |
bm25_weight = 1.0
|
| 202 |
|
|
|
|
| 204 |
bm25_scores: Dict[str, float] = {}
|
| 205 |
if self.bm25:
|
| 206 |
tokens = self._tokenize(clean_query)
|
| 207 |
+
if tokens:
|
| 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][:top_k * 4]
|
| 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:
|
| 215 |
+
continue
|
| 216 |
+
bm25_scores[chunk["chunk_id"]] = float(doc_scores[idx] / max_bm25)
|
| 217 |
|
| 218 |
# 3. Hybrid Merge (Weighted Rank + Normalized Score)
|
| 219 |
combined_scores: Dict[str, float] = {}
|
|
|
|
| 229 |
sorted_ids = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)[:top_k]
|
| 230 |
|
| 231 |
results = []
|
| 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 sorted_ids:
|
| 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 |
results.append({
|
| 240 |
**chunk,
|
| 241 |
"retrieval_score": round(score, 4),
|
|
|
|
| 243 |
"bm25_score": round(bm25_scores.get(doc_id, 0.0), 4)
|
| 244 |
})
|
| 245 |
|
| 246 |
+
# Include contiguous neighbor chunks (preceding and succeeding chunks in statutory sequence)
|
| 247 |
+
c_idx = chunk_idx_map.get(doc_id)
|
| 248 |
+
if c_idx is not None:
|
| 249 |
+
for offset in [-1, 1, 2]:
|
| 250 |
+
target_idx = c_idx + offset
|
| 251 |
+
if 0 <= target_idx < len(self.indexed_chunks):
|
| 252 |
+
nbr_chunk = self.indexed_chunks[target_idx]
|
| 253 |
+
nbr_id = nbr_chunk["chunk_id"]
|
| 254 |
+
if nbr_chunk.get("chapter") == chunk.get("chapter") and nbr_id not in seen_chunk_ids and len(results) < top_k + 4:
|
| 255 |
+
seen_chunk_ids.add(nbr_id)
|
| 256 |
+
decay = 0.96 ** abs(offset)
|
| 257 |
+
results.append({
|
| 258 |
+
**nbr_chunk,
|
| 259 |
+
"retrieval_score": round(score * decay, 4),
|
| 260 |
+
"vector_score": 0.0,
|
| 261 |
+
"bm25_score": round(score * decay, 4)
|
| 262 |
+
})
|
| 263 |
+
|
| 264 |
+
return results[:top_k]
|