Spaces:
Sleeping
Sleeping
Download src/coveragecheck/index/lexical.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 9.84 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/index/lexical.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/index/lexical.py
-
curl -L -o lexical.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/index/lexical.py
9.84 kB
| """Step 3a: BM25 keyword search over System B's chunks (embed_text). | |
| BM25 ranks a chunk by how many of the query's words it contains, weighting rare words | |
| more. It is only as good as its tokenizer, and the bm25s default tokenizer breaks the | |
| words that matter most in insurance text: "$1,000,000" becomes "1" + "000" + "000", | |
| "6.2.1" becomes "6" + "2" + "1", single characters vanish (so "s. 3" loses "3") and | |
| "O. Reg. 34/10" turns into "34" + "10", which then matches every "s. 10". So index | |
| and queries share one tokenizer of our own (tokenize()), and bm25s only scores. | |
| search() scores every chunk with get_scores() and applies the filter mask itself | |
| (owner's decision): bm25s.retrieve(weight_mask=...) still returns masked-out or | |
| non-matching chunks with score 0 to fill k, and raises when k exceeds the number of | |
| unmasked chunks. With ~900 chunks, scoring them all costs well under a millisecond. | |
| """ | |
| import hashlib | |
| import json | |
| import re | |
| import unicodedata | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import bm25s | |
| import numpy as np | |
| from coveragecheck import config | |
| from coveragecheck.index.store import StaleIndexError, check_mask, content_hash | |
| # Small on purpose (owner's decision). Kept although frequent: "a" (clause marker, | |
| # "clause 3 (a)"), "s" ("s. 3"), and negations / quantifiers ("not", "no", "any") | |
| # that exclusions depend on. | |
| STOPWORDS = frozenset( | |
| "the of and or to in for on by with is are be as at an this that from it".split() | |
| ) | |
| _APOSTROPHES = str.maketrans({"\u2018": "'", "\u2019": "'", "\u02bc": "'", "`": "'"}) | |
| _POSSESSIVE = re.compile(r"'s\b") # owner's / person's -> owner / person | |
| _CENTS = re.compile(r"(\$\s?\d[\d,]*)\.00\b") # "$1,000.00" -> "$1,000" (amounts only) | |
| _THOUSANDS = re.compile(r"(?<=\d),(?=\d{3}\b)") # "1,000,000" -> "1000000" | |
| _FORM_CODE = re.compile(r"\b(opcf|oap)(?=\d)") # "opcf44r" -> "opcf 44r", "oap1" -> "oap 1" | |
| _TOKEN = re.compile( | |
| r""" | |
| \d+(?:\.\d+)+ # dotted number: 6.2.1, 267.5 (a sentence's final "." is left out) | |
| | \d+/\d+ # regulation number: 34/10 | |
| | [^\W_]+(?:-[^\W_]+)+ # hyphenated word: hit-and-run, non-earner, DC-PD | |
| | [^\W_]+ # word, integer or code: insured, 3, 44r | |
| """, | |
| re.VERBOSE, | |
| ) | |
| # One sentence that exercises every tokenizer rule (see tokenizer_fingerprint()). | |
| PROBE = ( | |
| "The owner\u2019s Insurers' won't: $1,000,000.00, $ 2,500.00, 4,500 km, (6,7), " | |
| "s. 3 (a), section 6.2.1., O. Reg. 34/10, hit-and-run, OPCF44R, OAP1, " | |
| "not any no, 25% ___ ... \uff11\uff10 snake_case" | |
| ) | |
| def normalize(text: str) -> str: | |
| """NFKC, lowercase, every apostrophe straight, possessive "'s" dropped, other | |
| apostrophes deleted ("won't" -> "wont", "Insurers'" -> "insurers"), money cleaned: | |
| "$1,000.00" -> "$1000". Commas between digits go only before exactly three digits, | |
| so a list like "251, 265" keeps its comma (it has a space). Form codes typed | |
| without a space ("OPCF44R", "OAP1") are split the way the corpus writes them.""" | |
| text = unicodedata.normalize("NFKC", text).lower().translate(_APOSTROPHES) | |
| text = _POSSESSIVE.sub("", text).replace("'", "") | |
| text = _CENTS.sub(r"\1", text) | |
| text = _THOUSANDS.sub("", text) | |
| return _FORM_CODE.sub(r"\1 ", text) | |
| def dotted_ancestors(number: str) -> list[str]: | |
| """ "6.2.1" -> ["6.2", "6"]: the sections that contain it, nearest first.""" | |
| parts = number.split(".") | |
| return [".".join(parts[:i]) for i in range(len(parts) - 1, 0, -1)] | |
| def tokenize(text: str, with_ancestors: bool = False) -> list[str]: | |
| """The tokens BM25 sees, for chunks and queries alike. No stemming: Snowball | |
| merges insured / insurer / insurance (opposite parties in a policy) into "insur". | |
| Underscores and punctuation produce no token, so form blanks ("___") and leaders | |
| ("...") vanish, and "%" / "$" are dropped from "25%" / "$500". A hyphenated word | |
| emits itself and its parts, so "non-earner" matches "non-earner" exactly and | |
| "earner" alone. Stopwords go, except inside a hyphenated whole ("hit-and-run"). | |
| with_ancestors (chunks only, never queries) adds "6.2" and "6" after "6.2.1", so a | |
| query for "6.2" also finds text that cites 6.2.1.""" | |
| tokens: list[str] = [] | |
| for match in _TOKEN.finditer(normalize(text)): | |
| token = match.group() | |
| if "-" in token: | |
| tokens.append(token) | |
| tokens += [p for p in token.split("-") if p not in STOPWORDS] | |
| elif token not in STOPWORDS: | |
| tokens.append(token) | |
| if with_ancestors and "." in token: | |
| tokens += dotted_ancestors(token) | |
| return tokens | |
| def tokenizer_fingerprint() -> str: | |
| """A short hash of the tokenizer: its patterns, its stopwords and its output on | |
| PROBE. Stored with a saved index, so an edited tokenizer makes the old index stale | |
| without anyone having to remember to bump a version number. (A change that alters | |
| no pattern, no stopword and no PROBE token goes unnoticed: extend PROBE with it.)""" | |
| patterns = [p.pattern for p in (_POSSESSIVE, _CENTS, _THOUSANDS, _FORM_CODE, _TOKEN)] | |
| parts = [patterns, sorted(STOPWORDS), tokenize(PROBE, with_ancestors=True)] | |
| return hashlib.sha256(json.dumps(parts).encode("utf-8")).hexdigest()[:16] | |
| def settings(with_ancestors: bool) -> dict: | |
| """Everything that must be the same between a saved index and the current code: | |
| the tokenizer, the ancestor flag and the BM25 parameters (from config).""" | |
| return { | |
| "tokenizer": tokenizer_fingerprint(), | |
| "with_ancestors": with_ancestors, | |
| "k1": config.BM25_K1, | |
| "b": config.BM25_B, | |
| "method": "lucene", | |
| } | |
| class LexicalIndex: | |
| """A BM25 index plus what it was built from. Row i of every search result is ids[i].""" | |
| bm25: bm25s.BM25 | |
| ids: list[str] | |
| input_hash: str | |
| with_ancestors: bool | |
| def build(ids: list[str], texts: list[str], with_ancestors: bool | None = None) -> LexicalIndex: | |
| """Tokenize every text and build a Lucene-variant BM25 index (k1, b from config). | |
| with_ancestors defaults to config.BM25_DOTTED_ANCESTORS, read at call time. | |
| A text with no tokens stays a row (bm25s's empty token) so rows stay aligned.""" | |
| if len(ids) != len(texts) or len(set(ids)) != len(ids): | |
| raise ValueError("ids must be unique and aligned with texts") | |
| if with_ancestors is None: | |
| with_ancestors = config.BM25_DOTTED_ANCESTORS | |
| params = settings(with_ancestors) | |
| bm25 = bm25s.BM25(k1=params["k1"], b=params["b"], method=params["method"]) | |
| bm25.index([tokenize(t, with_ancestors) for t in texts], show_progress=False) | |
| return LexicalIndex(bm25, list(ids), content_hash(ids, texts), with_ancestors) | |
| def save(index: LexicalIndex, directory: Path) -> None: | |
| """bm25s's own files plus meta.json (settings and input hash). The ids are not | |
| stored: they are part of the hash, and load() takes them from the caller.""" | |
| directory.mkdir(parents=True, exist_ok=True) | |
| index.bm25.save(directory, show_progress=False) | |
| meta = settings(index.with_ancestors) | {"input_hash": index.input_hash} | |
| (directory / "meta.json").write_text(json.dumps(meta, indent=1), encoding="utf-8") | |
| def load(directory: Path, ids: list[str], texts: list[str]) -> LexicalIndex: | |
| """Load a saved index after checking it was built from exactly these (ids, texts) | |
| with the current tokenizer, ancestor flag and BM25 settings, and that bm25s's files | |
| hold one row per id. Any mismatch, or a missing / damaged meta.json, raises | |
| StaleIndexError: a stale index is never searched (owner's decision).""" | |
| meta_path = directory / "meta.json" | |
| if not meta_path.exists(): | |
| raise StaleIndexError(f"no lexical index at {directory}; build it first") | |
| meta = json.loads(meta_path.read_text(encoding="utf-8")) | |
| current = settings(config.BM25_DOTTED_ANCESTORS) | |
| problems = [ | |
| f"{key}: saved {meta.get(key)!r}, current {value!r}" | |
| for key, value in current.items() | |
| if meta.get(key) != value | |
| ] | |
| if meta.get("input_hash") != content_hash(ids, texts): | |
| problems.append("the chunks changed since the index was built") | |
| if not problems: | |
| bm25 = bm25s.BM25.load(directory, load_corpus=False, show_progress=False) | |
| if bm25.scores["num_docs"] != len(ids): | |
| problems.append(f"bm25s files hold {bm25.scores['num_docs']} rows, not {len(ids)}") | |
| if problems: | |
| raise StaleIndexError(f"stale lexical index at {directory}: " + "; ".join(problems)) | |
| return LexicalIndex(bm25, list(ids), meta["input_hash"], meta["with_ancestors"]) | |
| def search( | |
| index: LexicalIndex, query: str, k: int, mask: np.ndarray | None = None | |
| ) -> list[tuple[int, float]]: | |
| """Top-k (row, score) pairs, best first, ties in row order. mask (bool, one per | |
| row) removes rows BEFORE ranking, so a filter never leaves fewer than k results | |
| when enough allowed rows match. Rows scoring 0 (no query token, or masked) are | |
| never returned, so the list can be shorter than k, or empty. Repeated query words | |
| count once: bm25s adds a word's score once per occurrence, and a reworded query | |
| (System C) shouldn't weight a word just because it was repeated.""" | |
| check_mask(mask, len(index.ids)) | |
| tokens = list(dict.fromkeys(tokenize(query))) | |
| if not tokens or k <= 0: | |
| return [] | |
| scores = np.asarray(index.bm25.get_scores(tokens), dtype=np.float64) | |
| if mask is not None: | |
| scores = np.where(mask, scores, 0.0) | |
| order = np.argsort(-scores, kind="stable")[:k] | |
| return [(int(i), float(scores[i])) for i in order if scores[i] > 0] | |