File size: 11,746 Bytes
c49440d
13de702
c49440d
 
 
 
 
 
 
 
 
 
 
175d0fa
 
 
 
 
13de702
c49440d
 
 
 
175d0fa
c49440d
 
 
 
 
 
 
 
175d0fa
 
 
 
 
 
 
 
 
 
 
63dbfcd
 
 
 
 
 
 
 
 
 
175d0fa
63dbfcd
 
 
 
 
 
 
175d0fa
63dbfcd
c49440d
 
 
 
 
 
 
 
 
 
 
175d0fa
c49440d
175d0fa
 
c49440d
175d0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175d0fa
c49440d
 
 
 
 
 
 
 
 
175d0fa
c49440d
13de702
175d0fa
13de702
c49440d
 
 
 
2acfd4e
 
c49440d
 
 
 
 
175d0fa
2acfd4e
13de702
175d0fa
c49440d
63dbfcd
 
175d0fa
 
 
 
 
 
 
2acfd4e
175d0fa
 
c49440d
175d0fa
 
 
 
63dbfcd
175d0fa
63dbfcd
 
c49440d
 
 
 
13de702
175d0fa
 
 
 
2acfd4e
175d0fa
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
2acfd4e
c49440d
2acfd4e
 
175d0fa
 
 
2acfd4e
 
 
c49440d
175d0fa
 
2acfd4e
c49440d
 
 
 
 
 
2acfd4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175d0fa
2acfd4e
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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