"""Retrieval backends: exact BM25 (sparse) and exact cosine search over dense embeddings. Every backend exposes ``scores(query) -> np.ndarray`` over the indexed groups, so ranking, exclusion and result formatting are shared and identical across methods. """ from __future__ import annotations import re from collections import Counter import numpy as np from scipy import sparse from app.data import SentenceGroup, normalize _TOKEN_RE = re.compile(r"\w+") def tokenize(text: str) -> list[str]: return _TOKEN_RE.findall(normalize(text)) class BM25Backend: """Okapi BM25 with Lucene-style non-negative IDF, scored exactly via a sparse matrix.""" method = "bm25" def __init__(self, texts: list[str], k1: float = 1.5, b: float = 0.75): docs = [tokenize(t) for t in texts] self.vocab: dict[str, int] = {} rows, cols, tfs = [], [], [] for i, doc in enumerate(docs): for term, tf in Counter(doc).items(): rows.append(i) cols.append(self.vocab.setdefault(term, len(self.vocab))) tfs.append(tf) n_docs = len(docs) tf = sparse.csr_matrix((tfs, (rows, cols)), shape=(n_docs, len(self.vocab)), dtype=np.float64) doc_len = np.array([len(d) for d in docs], dtype=np.float64) df = np.bincount(cols, minlength=len(self.vocab)) self.idf = np.log1p((n_docs - df + 0.5) / (df + 0.5)) # Precompute the saturated term weight for every (doc, term) pair. tf = tf.tocoo() norm = k1 * (1 - b + b * doc_len[tf.row] / doc_len.mean()) weights = tf.data * (k1 + 1) / (tf.data + norm) self.matrix = sparse.csc_matrix((weights, (tf.row, tf.col)), shape=tf.shape) def scores(self, query: str) -> np.ndarray: q = np.zeros(len(self.vocab)) for term, count in Counter(tokenize(query)).items(): j = self.vocab.get(term) if j is not None: q[j] = count * self.idf[j] return np.asarray(self.matrix @ q).ravel() class MeanPoolingEncoder: """Transformer encoder with attention-mask-aware mean pooling + L2 normalization. This is the pooling configuration of all-MiniLM-L6-v2 and the pooling policy the plan prescribes for CONTRACTS-BERT, so both dense models share one code path. """ def __init__(self, model_path: str, max_length: int = 256, batch_size: int = 64): import torch from transformers import AutoModel, AutoTokenizer self._torch = torch self.tokenizer = AutoTokenizer.from_pretrained(model_path) self.model = AutoModel.from_pretrained(model_path).eval() self.max_length = max_length self.batch_size = batch_size def encode(self, texts: list[str]) -> np.ndarray: torch = self._torch # Batch texts of similar length together to minimise padding; restore order after. order = np.argsort([len(t) for t in texts], kind="stable") out = np.empty((len(texts), self.model.config.hidden_size), dtype=np.float32) with torch.inference_mode(): for start in range(0, len(texts), self.batch_size): idx = order[start:start + self.batch_size] batch = self.tokenizer( [texts[i] for i in idx], padding=True, truncation=True, max_length=self.max_length, return_tensors="pt", ) hidden = self.model(**batch).last_hidden_state mask = batch["attention_mask"].unsqueeze(-1).to(hidden.dtype) pooled = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1e-9) out[idx] = torch.nn.functional.normalize(pooled, p=2, dim=1).numpy() return out class DenseBackend: """Exact cosine search: embeddings are unit-norm, so cosine is a dot product.""" def __init__(self, method: str, encoder: MeanPoolingEncoder, embeddings: np.ndarray): self.method = method self.encoder = encoder self.embeddings = embeddings def scores(self, query: str) -> np.ndarray: q = self.encoder.encode([normalize(query)])[0] return self.embeddings @ q def rank(scores: np.ndarray, k: int, eligible: np.ndarray | None = None) -> np.ndarray: """Top-k indices by descending score; ties broken by ascending index (stable).""" s = scores.astype(np.float64, copy=True) if eligible is not None: s[~eligible] = -np.inf order = np.lexsort((np.arange(len(s)), -s)) order = order[np.isfinite(s[order])] return order[:k] def format_results(groups: list[SentenceGroup], scores: np.ndarray, indices: np.ndarray, method: str) -> list[dict]: return [ { "rank": r + 1, "group_id": groups[i].group_id, "text": groups[i].text, "score": round(float(scores[i]), 6), "method": method, "occurrences": [ {"contract": o.contract, "position": o.position, "original": o.original} for o in groups[i].occurrences ], } for r, i in enumerate(indices) ]