import os import re import json import pickle import numpy as np import requests from typing import List, Dict, Any, Optional import chromadb from rank_bm25 import BM25Okapi from dotenv import load_dotenv load_dotenv() try: from fastembed import TextEmbedding HAS_FASTEMBED = True except ImportError: HAS_FASTEMBED = False class HybridLegalRetriever: def __init__( self, persist_dir: str = "data/index", embedding_model: str = "BAAI/bge-small-en-v1.5" ): self.persist_dir = persist_dir self.embedding_model = embedding_model os.makedirs(persist_dir, exist_ok=True) self.cf_token = os.getenv("CLOUDFLARE_API_TOKEN") self.cf_account_id = os.getenv("CLOUDFLARE_ACCOUNT_ID") # Local HuggingFace CPU Embedding Model (ONNX accelerated, 0 rate-limits, highest accuracy) self.hf_embedder = None if HAS_FASTEMBED: try: self.hf_embedder = TextEmbedding(model_name="BAAI/bge-small-en-v1.5") print("✔ Local HuggingFace CPU Embedding engine loaded (BAAI/bge-small-en-v1.5)") except Exception as e: print(f"Notice: Local fastembed initialization failed: {e}. Falling back to Cloudflare/BM25.") self.hf_embedder = None # Initialize ChromaDB client with persistent local vector storage self.chroma_client = None self.collection = None chroma_path = os.path.join(persist_dir, "chroma") try: self.chroma_client = chromadb.PersistentClient(path=chroma_path) self.collection = self.chroma_client.get_or_create_collection( name="icai_business_laws", metadata={"hnsw:space": "cosine"} ) except Exception as e: print(f"Notice: Persistent ChromaDB init encountered {e}. Using in-memory client.") try: self.chroma_client = chromadb.Client() self.collection = self.chroma_client.get_or_create_collection( name="icai_business_laws", metadata={"hnsw:space": "cosine"} ) except Exception as inner_e: print(f"Notice: Vector collection unavailable ({inner_e}). Operating in BM25 retrieval mode.") self.collection = None self.bm25_index_path = os.path.join(persist_dir, "bm25.pkl") self.chunks_cache_path = os.path.join(persist_dir, "chunks_cache.json") self.bm25: Optional[BM25Okapi] = None self.indexed_chunks: List[Dict[str, Any]] = [] self._load_bm25_and_cache() def _tokenize(self, text: str) -> List[str]: return [w.lower() for w in text.split() if w.isalnum()] def _get_embeddings(self, texts: List[str]) -> List[List[float]]: """ Generates dense vector embeddings using local HuggingFace CPU ONNX model. Falls back to Cloudflare Workers AI if fastembed is unavailable. """ if self.hf_embedder is not None: embeddings = list(self.hf_embedder.embed(texts, batch_size=64)) return [e.tolist() for e in embeddings] # Fallback to Cloudflare Workers AI API if local embedder is not loaded if self.cf_account_id and self.cf_token: url = f"https://api.cloudflare.com/client/v4/accounts/{self.cf_account_id}/ai/run/@cf/baai/bge-small-en-v1.5" headers = { "Authorization": f"Bearer {self.cf_token}", "Content-Type": "application/json" } all_embeddings = [] batch_size = 20 for i in range(0, len(texts), batch_size): batch = texts[i:i+batch_size] resp = requests.post(url, headers=headers, json={"text": batch}, timeout=60) data = resp.json() if not data.get("success"): raise RuntimeError(f"Cloudflare embedding failed: {data.get('errors')}") all_embeddings.extend(data["result"]["data"]) return all_embeddings raise RuntimeError("No embedding provider available.") def _load_bm25_and_cache(self): if os.path.exists(self.chunks_cache_path) and os.path.exists(self.bm25_index_path): try: with open(self.chunks_cache_path, "r", encoding="utf-8") as f: self.indexed_chunks = json.load(f) with open(self.bm25_index_path, "rb") as f: self.bm25 = pickle.load(f) except Exception as e: print(f"Warning: Failed to load existing BM25 cache: {e}") def index_chunks(self, chunks: List[Dict[str, Any]], batch_size: int = 50, force_reindex: bool = False): if len(self.indexed_chunks) > 0 and not force_reindex: return print(f"Indexing {len(chunks)} legal chunks with Cloudflare Workers AI Embeddings...") self.indexed_chunks = chunks # 1. BM25 Indexing tokenized_corpus = [self._tokenize(c["text"]) for c in chunks] self.bm25 = BM25Okapi(tokenized_corpus) with open(self.bm25_index_path, "wb") as f: pickle.dump(self.bm25, f) with open(self.chunks_cache_path, "w", encoding="utf-8") as f: json.dump(chunks, f, ensure_ascii=False, indent=2) # 2. ChromaDB Dense Vector Indexing with Cloudflare Embeddings if force_reindex: try: self.chroma_client.delete_collection("icai_business_laws") self.collection = self.chroma_client.create_collection("icai_business_laws", metadata={"hnsw:space": "cosine"}) except Exception: pass for i in range(0, len(chunks), batch_size): batch = chunks[i:i+batch_size] ids = [c["chunk_id"] for c in batch] texts = [c["text"] for c in batch] metadatas = [{ "pdf_filename": c["pdf_filename"], "title": c["title"], "chapter": c["chapter"], "page_number": c["page_number"], "total_pages": c["total_pages"], "chunk_id": c["chunk_id"] } for c in batch] embeddings = self._get_embeddings(texts) self.collection.upsert( ids=ids, documents=texts, embeddings=embeddings, metadatas=metadatas ) print(f"Indexed batch {i//batch_size + 1}/{(len(chunks)-1)//batch_size + 1}") print("✔ Hybrid Indexing complete!") def _tokenize(self, text: str) -> List[str]: return [w.lower() for w in text.split() if w.isalnum()] def retrieve( self, query: str, top_k: int = 6, vector_weight: float = 0.55, bm25_weight: float = 0.45, chapter_filter: Optional[str] = None ) -> List[Dict[str, Any]]: if not self.indexed_chunks: return [] clean_query = query.strip() candidate_k = min(max(top_k * 10, 60), len(self.indexed_chunks)) # 1. Dense Semantic Search via HuggingFace CPU embedding (fastembed BAAI/bge-small-en-v1.5) vector_scores: Dict[str, float] = {} if self.collection is not None: try: query_embeddings = self._get_embeddings([clean_query]) if query_embeddings: query_embedding = query_embeddings[0] where_filter = {"chapter": chapter_filter} if chapter_filter and chapter_filter != "All" else None vector_res = self.collection.query( query_embeddings=[query_embedding], n_results=candidate_k, where=where_filter ) if vector_res and vector_res["ids"] and vector_res["ids"][0]: for doc_id, dist in zip(vector_res["ids"][0], vector_res["distances"][0]): similarity = 1.0 - dist vector_scores[doc_id] = max(0.0, similarity) except Exception as e: print(f"Notice: Dense vector retrieval fallback: {e}") vector_weight = 0.0 bm25_weight = 1.0 # 2. Sparse BM25 Search bm25_scores: Dict[str, float] = {} if self.bm25: tokens = self._tokenize(clean_query) if tokens: doc_scores = self.bm25.get_scores(tokens) max_bm25 = np.max(doc_scores) if len(doc_scores) > 0 and np.max(doc_scores) > 0 else 1.0 top_bm25_indices = np.argsort(doc_scores)[::-1][:candidate_k] for idx in top_bm25_indices: chunk = self.indexed_chunks[idx] if chapter_filter and chapter_filter != "All" and chunk["chapter"] != chapter_filter: continue bm25_scores[chunk["chunk_id"]] = float(doc_scores[idx] / max_bm25) # 3. Hybrid Merge (Weighted Rank + Normalized Score) combined_scores: Dict[str, float] = {} all_candidate_ids = set(vector_scores.keys()).union(set(bm25_scores.keys())) chunk_dict = {c["chunk_id"]: c for c in self.indexed_chunks} for doc_id in all_candidate_ids: v_score = vector_scores.get(doc_id, 0.0) b_score = bm25_scores.get(doc_id, 0.0) combined_scores[doc_id] = (vector_weight * v_score) + (bm25_weight * b_score) sorted_candidates = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True) # Primary distinct highest-scoring chunks primary_results = [] seen_chunk_ids = set() chunk_idx_map = {c["chunk_id"]: i for i, c in enumerate(self.indexed_chunks)} for doc_id, score in sorted_candidates: if len(primary_results) >= top_k: break chunk = chunk_dict.get(doc_id) if chunk and doc_id not in seen_chunk_ids: seen_chunk_ids.add(doc_id) primary_results.append({ **chunk, "retrieval_score": round(score, 4), "vector_score": round(vector_scores.get(doc_id, 0.0), 4), "bm25_score": round(bm25_scores.get(doc_id, 0.0), 4) }) # Neighbor expansion: enrich the top primary results with their preceding and succeeding statutory chunks results = list(primary_results) for chunk in primary_results[:3]: c_idx = chunk_idx_map.get(chunk["chunk_id"]) if c_idx is not None: for offset in [-1, 1, 2]: target_idx = c_idx + offset if 0 <= target_idx < len(self.indexed_chunks): nbr_chunk = self.indexed_chunks[target_idx] nbr_id = nbr_chunk["chunk_id"] if nbr_chunk.get("chapter") == chunk.get("chapter") and nbr_id not in seen_chunk_ids and len(results) < top_k + 4: seen_chunk_ids.add(nbr_id) decay = 0.96 ** abs(offset) results.append({ **nbr_chunk, "retrieval_score": round(chunk["retrieval_score"] * decay, 4), "vector_score": 0.0, "bm25_score": round(chunk["retrieval_score"] * decay, 4) }) return results