Spaces:
Sleeping
Sleeping
Download src/coveragecheck/index/hybrid.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/index/hybrid.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/index/hybrid.py
-
curl -L -o hybrid.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/index/hybrid.py
12.9 kB
| """Step 3c: System B's hybrid search: filters, then BM25 + dense, fused by rank. | |
| 1. Filters decide which documents a query may see, BEFORE ranking (so k results | |
| always come from allowed documents): | |
| - version filter (SPEC Step 3): a document is excluded only when it is NOT in force | |
| on the policy date while another version of the same form IS (SABS-2025 vs | |
| SABS-2026; OPCF 47 vs 47R, linked by the manifest's `supersedes`). A kept document | |
| that is not in force is "flagged": the answer may cite the wrong version. | |
| No date -> today. | |
| - form filter (optional): only the named forms, each with all its versions. | |
| 2. Each retriever returns its top CANDIDATE_K allowed chunks; Reciprocal Rank Fusion | |
| adds 1 / (RRF_K + rank) per list. Ranks, not scores: BM25 scores and cosines are on | |
| different scales, and the cosines sit in a narrow 0.65-0.83 band (3b audit). | |
| 3. Version twins (identical text, same form family, different documents) keep only | |
| their best-ranked copy. Identical text across different forms or sections is NOT | |
| merged: OAP 1 Sections 3-7 share an opening sentence but are different rules. | |
| Latency (owner's priority): everything that depends only on the corpus (documents, | |
| families, each row's document, twin groups) is computed once in Retriever.load(); | |
| a query costs one query embedding (~10 ms), two sub-millisecond searches, and array | |
| lookups. Filter masks are cached per (date, forms). | |
| """ | |
| import functools | |
| from collections.abc import Iterable | |
| from dataclasses import dataclass | |
| from datetime import date, datetime | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from coveragecheck import config | |
| from coveragecheck.index import dense, lexical | |
| from coveragecheck.index.store import StaleIndexError, load_table | |
| # --- documents and versions -------------------------------------------------------------- | |
| class Doc: | |
| doc_id: str | |
| form_id: str | |
| effective_from: date | None | |
| effective_to: date | None | |
| supersedes: str | None | |
| def documents(chunks: pd.DataFrame) -> list[Doc]: | |
| """One Doc per document, in table order, from the per-document columns that every | |
| chunk row carries (Step 2 copies them from the manifest). Expects load_table()'s | |
| output (None, not NaN, for a missing date). Raises if a document's rows disagree, | |
| since only its first row is read.""" | |
| columns = ["form_id", "effective_from", "effective_to", "supersedes"] | |
| varying = chunks.groupby("doc_id")[columns].nunique(dropna=False).max(axis=1) | |
| if (varying > 1).any(): | |
| raise ValueError(f"rows of one document disagree: {sorted(varying[varying > 1].index)}") | |
| first = chunks.drop_duplicates("doc_id") | |
| def day(value: str | None) -> date | None: | |
| return None if value is None else date.fromisoformat(value) | |
| return [ | |
| Doc(r.doc_id, r.form_id, day(r.effective_from), day(r.effective_to), r.supersedes) | |
| for r in first.itertuples() | |
| ] | |
| def families(docs: list[Doc]) -> dict[str, str]: | |
| """doc_id -> family: the versions of one form. Same form_id = same family, and | |
| `supersedes` joins two form_ids (OPCF 47R replaces OPCF 47). Similar names never | |
| join by themselves: OPCF 43 / 43A, 28 / 28A ... are different forms in force at | |
| the same time (3c corpus study). The family name is its smallest form_id.""" | |
| parent = {d.form_id: d.form_id for d in docs} | |
| def root(form: str) -> str: | |
| while parent[form] != form: | |
| form = parent[form] | |
| return form | |
| form_of = {d.doc_id: d.form_id for d in docs} | |
| for d in docs: | |
| if d.supersedes is not None: | |
| if d.supersedes not in form_of: | |
| raise ValueError(f"{d.doc_id} supersedes {d.supersedes}: not in the corpus") | |
| a, b = root(d.form_id), root(form_of[d.supersedes]) | |
| parent[max(a, b)] = min(a, b) | |
| return {d.doc_id: root(d.form_id) for d in docs} | |
| def in_force(doc: Doc, day: date) -> bool: | |
| """In force on day: no start date or started, and no end date or not yet ended. | |
| An undated document is always in force (22 of 36 have no dates).""" | |
| started = doc.effective_from is None or doc.effective_from <= day | |
| not_ended = doc.effective_to is None or day <= doc.effective_to | |
| return started and not_ended | |
| def version_filter( | |
| docs: list[Doc], family: dict[str, str], day: date | |
| ) -> tuple[frozenset[str], frozenset[str]]: | |
| """(allowed, flagged) doc_ids for a policy date. Excluded: not in force while a | |
| family sibling is (owner's reading of the SPEC rule: two overlapping versions both | |
| in force are both kept). Flagged: kept although not in force (no sibling is).""" | |
| live = {family[d.doc_id] for d in docs if in_force(d, day)} | |
| allowed, flagged = set(), set() | |
| for d in docs: | |
| if in_force(d, day): | |
| allowed.add(d.doc_id) | |
| elif family[d.doc_id] not in live: | |
| allowed.add(d.doc_id) | |
| flagged.add(d.doc_id) | |
| return frozenset(allowed), frozenset(flagged) | |
| def form_filter(docs: list[Doc], family: dict[str, str], form_ids: Iterable[str]) -> frozenset[str]: | |
| """doc_ids of the named forms and of every version in their families ("OPCF 47" | |
| also allows OPCF 47R; the version filter then picks by date). An unknown form_id | |
| raises: a typo must not silently return nothing.""" | |
| by_form = {d.form_id: family[d.doc_id] for d in docs} | |
| unknown = sorted(set(form_ids) - set(by_form)) | |
| if unknown: | |
| raise ValueError(f"unknown form_id(s): {unknown}") | |
| wanted = {by_form[f] for f in form_ids} | |
| return frozenset(d.doc_id for d in docs if family[d.doc_id] in wanted) | |
| # --- fusion ------------------------------------------------------------------------------ | |
| def rrf(rankings: list[list[int]], k: int = config.RRF_K) -> list[tuple[int, float]]: | |
| """Reciprocal Rank Fusion: score(row) = sum over rankings of 1 / (k + rank), rank | |
| from 1. Best first; equal scores keep the order rows were first seen (ranking 0's | |
| order first), so the result is deterministic.""" | |
| scores: dict[int, float] = {} | |
| for ranking in rankings: | |
| for rank, row in enumerate(ranking, start=1): | |
| scores[row] = scores.get(row, 0.0) + 1.0 / (k + rank) | |
| return sorted(scores.items(), key=lambda item: -item[1]) # sorted() is stable | |
| def twin_groups(chunks: pd.DataFrame, family: dict[str, str]) -> np.ndarray: | |
| """Per row, a group number shared by its version twins (same family, identical | |
| text, different documents), or -1. Real corpus: the 120 SABS-2025/2026 pairs.""" | |
| groups = np.full(len(chunks), -1, dtype=np.int64) | |
| rows_by_key: dict[tuple[str, str], list[int]] = {} | |
| for row, (doc_id, text) in enumerate(zip(chunks.doc_id, chunks.text, strict=True)): | |
| rows_by_key.setdefault((family[doc_id], text), []).append(row) | |
| for number, rows in enumerate(r for r in rows_by_key.values() if len(r) > 1): | |
| if len({chunks.doc_id.iat[r] for r in rows}) > 1: # same doc twice = 2 sections | |
| groups[rows] = number | |
| return groups | |
| def dedupe(fused: list[tuple[int, float]], groups: np.ndarray) -> list[tuple[int, float]]: | |
| """Keep the first (best-ranked) row of each twin group. This also "prefers the | |
| in-force version": the version filter never keeps a not-in-force twin next to an | |
| in-force one, so kept twins are either all in force or all flagged.""" | |
| seen: set[int] = set() | |
| out = [] | |
| for row, score in fused: | |
| group = int(groups[row]) | |
| if group >= 0: | |
| if group in seen: | |
| continue | |
| seen.add(group) | |
| out.append((row, score)) | |
| return out | |
| # --- the retriever ----------------------------------------------------------------------- | |
| class Candidate: | |
| row: int | |
| chunk_id: str | |
| doc_id: str | |
| source_id: str # the citable section (Step 4 metrics, Step 8 citations) | |
| score: float # RRF score | |
| lexical_rank: int | None # 1-based rank in BM25's list, None if not in it | |
| dense_rank: int | None | |
| class Result: | |
| candidates: list[Candidate] | |
| day: date # the policy date the version filter used | |
| flagged: frozenset[str] # doc_ids among the candidates that may be the wrong version | |
| class Retriever: | |
| """System B's search over one chunks table and its two indexes. Build it once per | |
| process (Retriever.load); search() is then cheap. self.chunks keeps the table, so | |
| later steps read a candidate's text, heading_path or xrefs by its row.""" | |
| def __init__( | |
| self, | |
| chunks: pd.DataFrame, | |
| lexical_index: lexical.LexicalIndex, | |
| dense_index: dense.DenseIndex, | |
| embedder: dense.Embedder, | |
| ): | |
| ids = list(chunks.chunk_id) | |
| if lexical_index.ids != ids or dense_index.ids != ids: | |
| raise StaleIndexError("the indexes and the chunks table have different rows") | |
| if lexical_index.input_hash != dense_index.input_hash: | |
| raise StaleIndexError("the lexical and dense indexes were built from different texts") | |
| self.chunks = chunks | |
| self.chunk_ids = ids | |
| self.doc_ids, self.source_ids = list(chunks.doc_id), list(chunks.source_id) | |
| self.lexical, self.dense, self.embedder = lexical_index, dense_index, embedder | |
| self.docs = documents(chunks) | |
| self.family = families(self.docs) | |
| doc_index = {d.doc_id: i for i, d in enumerate(self.docs)} | |
| self.row_doc = np.array([doc_index[d] for d in chunks.doc_id], dtype=np.int64) | |
| self.groups = twin_groups(chunks, self.family) | |
| self.mask = functools.lru_cache(maxsize=256)(self._mask) | |
| def load( | |
| cls, | |
| embedder: dense.Embedder, | |
| index_dir: Path = config.INDEX_DIR, | |
| bm25_dir: Path = config.BM25_DIR, | |
| dense_dir: Path = config.DENSE_B_DIR, | |
| ) -> "Retriever": | |
| """Read chunks.parquet and load both saved indexes, each checked against it.""" | |
| chunks = load_table(index_dir / "chunks.parquet") | |
| ids, texts = list(chunks.chunk_id), list(chunks.embed_text) | |
| return cls( | |
| chunks, lexical.load(bm25_dir, ids, texts), dense.load(dense_dir, ids, texts), embedder | |
| ) | |
| def _mask( | |
| self, day: date, form_ids: frozenset[str] | None | |
| ) -> tuple[np.ndarray, frozenset[str]]: | |
| """(bool mask over rows, flagged doc_ids) for a date and an optional form set. | |
| The mask is cached and shared between searches, so it is made read-only.""" | |
| allowed, flagged = version_filter(self.docs, self.family, day) | |
| if form_ids is not None: | |
| allowed = allowed & form_filter(self.docs, self.family, form_ids) | |
| doc_allowed = np.array([d.doc_id in allowed for d in self.docs]) | |
| mask = doc_allowed[self.row_doc] | |
| mask.flags.writeable = False | |
| return mask, flagged | |
| def search( | |
| self, | |
| query: str, | |
| day: date | datetime | None = None, | |
| form_ids: str | Iterable[str] | None = None, | |
| k: int = config.CANDIDATE_K, | |
| ) -> Result: | |
| """Fused, deduped candidates for a query (each retriever contributes its top k | |
| allowed chunks, so at most 2k candidates). day: the policy date (a datetime is | |
| cut to its date; None = today). form_ids: None = every form; one form_id or a | |
| non-empty list of them (an empty list raises: it would silently find nothing). | |
| A query with no searchable word (blank, stopwords, punctuation) returns none: | |
| dense search has no score floor and would return arbitrary chunks.""" | |
| day = date.today() if day is None else day | |
| day = day.date() if isinstance(day, datetime) else day | |
| if isinstance(form_ids, str): | |
| form_ids = [form_ids] | |
| forms = None if form_ids is None else frozenset(form_ids) | |
| if forms is not None and not forms: | |
| raise ValueError("form_ids is empty; pass None for no form filter") | |
| if not lexical.tokenize(query): | |
| return Result([], day, frozenset()) | |
| mask, flagged = self.mask(day, forms) | |
| lex = [row for row, _ in lexical.search(self.lexical, query, k, mask)] | |
| query_vector = dense.embed_query(query, self.embedder) | |
| den = [row for row, _ in dense.search(self.dense, query_vector, k, mask)] | |
| lex_rank = {row: rank for rank, row in enumerate(lex, start=1)} | |
| den_rank = {row: rank for rank, row in enumerate(den, start=1)} | |
| candidates = [ | |
| Candidate( | |
| row, | |
| self.chunk_ids[row], | |
| self.doc_ids[row], | |
| self.source_ids[row], | |
| score, | |
| lex_rank.get(row), | |
| den_rank.get(row), | |
| ) | |
| for row, score in dedupe(rrf([lex, den]), self.groups) | |
| ] | |
| used = {c.doc_id for c in candidates} | |
| return Result(candidates, day, flagged & used) | |