| """ |
| BM25-based sparse vector encoder for Qdrant hybrid search. |
| |
| Workflow |
| -------- |
| 1. fit(corpus) — build vocab + IDF from a list of texts, persist to disk. |
| 2. encode(text) — per-document sparse vector (BM25 term weights). |
| 3. encode_query(text) — per-query sparse vector (IDF weights only, standard pattern). |
| 4. load(path) — restore a previously fitted encoder. |
| |
| Sparse vector format matches Qdrant's SparseVector: |
| {"indices": [int, ...], "values": [float, ...]} |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import math |
| import re |
| from collections import Counter |
| from pathlib import Path |
| from typing import Any, Dict, List, Tuple |
|
|
| from src.generators.rag_config import BM25_K1, BM25_B, BM25_MIN_DF, BM25_MAX_VOCAB, BM25_VOCAB_PATH |
|
|
|
|
| def _tokenize(text: str) -> List[str]: |
| """Lowercase, split on non-alphanumeric, keep tokens ≥ 2 chars.""" |
| return [t for t in re.split(r"[^a-z0-9]+", text.lower()) if len(t) >= 2] |
|
|
|
|
| class BM25SparseEncoder: |
| """ |
| Corpus-level BM25 sparse encoder. |
| |
| Attributes |
| ---------- |
| vocab : token → integer token_id |
| idf : token → IDF weight (Robertson–Spärck Jones) |
| avgdl : average document length in tokens |
| """ |
|
|
| def __init__(self) -> None: |
| self.vocab: Dict[str, int] = {} |
| self.idf: Dict[str, float] = {} |
| self.avgdl: float = 0.0 |
|
|
| |
|
|
| def fit(self, corpus: List[str]) -> "BM25SparseEncoder": |
| """ |
| Build vocab and IDF from a list of raw texts. |
| Persists the fitted state to BM25_VOCAB_PATH automatically. |
| """ |
| tokenized = [_tokenize(text) for text in corpus] |
| N = len(tokenized) |
| df: Counter = Counter() |
|
|
| for tokens in tokenized: |
| for t in set(tokens): |
| df[t] += 1 |
|
|
| self.avgdl = sum(len(t) for t in tokenized) / max(1, N) |
|
|
| |
| filtered = [(t, f) for t, f in df.items() if f >= BM25_MIN_DF] |
| filtered.sort(key=lambda x: -x[1]) |
| filtered = filtered[:BM25_MAX_VOCAB] |
|
|
| self.vocab = {t: idx for idx, (t, _) in enumerate(filtered)} |
| self.idf = { |
| t: math.log((N - f + 0.5) / (f + 0.5) + 1.0) |
| for t, f in filtered |
| } |
|
|
| self.save() |
| return self |
|
|
| |
|
|
| def encode(self, text: str) -> Dict[str, Any]: |
| """BM25 document vector — term-frequency weighted.""" |
| tokens = _tokenize(text) |
| dl = len(tokens) |
| tf = Counter(tokens) |
|
|
| indices: List[int] = [] |
| values: List[float] = [] |
|
|
| for token, count in tf.items(): |
| tid = self.vocab.get(token) |
| if tid is None: |
| continue |
| idf = self.idf[token] |
| |
| tf_norm = count * (BM25_K1 + 1) / ( |
| count + BM25_K1 * (1 - BM25_B + BM25_B * dl / max(1, self.avgdl)) |
| ) |
| w = idf * tf_norm |
| if w > 0: |
| indices.append(tid) |
| values.append(round(w, 6)) |
|
|
| return {"indices": indices, "values": values} |
|
|
| def encode_query(self, text: str) -> Dict[str, Any]: |
| """Query vector — IDF weights only (asymmetric BM25 pattern).""" |
| tokens = set(_tokenize(text)) |
| indices: List[int] = [] |
| values: List[float] = [] |
|
|
| for token in tokens: |
| tid = self.vocab.get(token) |
| if tid is None: |
| continue |
| indices.append(tid) |
| values.append(round(self.idf[token], 6)) |
|
|
| return {"indices": indices, "values": values} |
|
|
| |
|
|
| def save(self, path: str | Path | None = None) -> None: |
| path = Path(path or BM25_VOCAB_PATH) |
| path.parent.mkdir(parents=True, exist_ok=True) |
| state = { |
| "vocab": self.vocab, |
| "idf": self.idf, |
| "avgdl": self.avgdl, |
| } |
| with open(path, "w", encoding="utf-8") as f: |
| json.dump(state, f) |
|
|
| @classmethod |
| def load(cls, path: str | Path | None = None) -> "BM25SparseEncoder": |
| path = Path(path or BM25_VOCAB_PATH) |
| with open(path, encoding="utf-8") as f: |
| state = json.load(f) |
| enc = cls() |
| enc.vocab = state["vocab"] |
| enc.idf = state["idf"] |
| enc.avgdl = state["avgdl"] |
| return enc |
|
|
| @classmethod |
| def load_or_none(cls, path: str | Path | None = None) -> "BM25SparseEncoder | None": |
| import logging |
| _logger = logging.getLogger(__name__) |
|
|
| p = Path(path or BM25_VOCAB_PATH) |
| if not p.exists(): |
| _logger.warning( |
| "BM25 vocabulary not found at %s. Hybrid search will fall back to " |
| "dense-only (sparse vectors empty). Run --build to create the index.", |
| p, |
| ) |
| return None |
|
|
| try: |
| enc = cls.load(p) |
| if len(enc.vocab) < 10: |
| _logger.warning( |
| "BM25 vocabulary at %s contains only %d tokens — sparse search " |
| "will be effectively disabled. Run --build to rebuild with full corpus.", |
| p, len(enc.vocab), |
| ) |
| return enc |
| except Exception as e: |
| _logger.warning("Failed to load BM25 vocabulary from %s: %s", p, e) |
| return None |
|
|