Spaces:
Sleeping
Sleeping
Download src/coveragecheck/verify/citations.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/verify/citations.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/verify/citations.py
-
curl -L -o citations.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/verify/citations.py
20.2 kB
| """Step 8: check that each citation's quote is really in the text it names. | |
| checker = Checker.load() | |
| result = checker.check(citation, shown_chunk_ids) # one CitationCheck | |
| Used to score Systems A, B and C (evals/metrics.py: hallucinated citation rates) and | |
| by System C's verify node, which sends a failed check's problems back to the model. | |
| Rules (SPEC Step 8, refined after the Step 2a review, which measured that | |
| partial_ratio >= 90 alone accepted 100% of quotes with one number changed or "not" | |
| inserted, and rejected honest "..." elisions): | |
| - Tiers. "exact": after text.normalize_for_match (no whitespace, no case, look-alike | |
| quotes and dashes unified), the quote is a substring of the cited section (its | |
| heading path + full subtree text). "approximate": a fallback, reported separately: | |
| every fragment has fuzz.partial_ratio >= CITATION_MIN_RATIO against the section, | |
| compared with text.normalize_words (words kept, so the aligned span is real). | |
| - A quote is split on "..." / the ellipsis character; the fragments must be found in | |
| order (an honest elision passes; fragments swapped do not). | |
| - Guards. Numbers, exact tier: each fragment's numbers, in order, must be a run of | |
| consecutive numbers of the section (normalize_for_match joins "$1 000" and "$10 00", | |
| and a set check let "within 1 4 days" pass because "1" and "4" occur elsewhere in | |
| OAP 1: 8 audit). Approximate tier: every number of a fragment must be in its aligned | |
| span, NOT widened: widening it to catch an edge number the alignment clips ("47. | |
| (1)" lost its "47") let "subsection (1)" -> "(2)" pass beside "20. (2)". Known cost: | |
| ~3 of 122 one-word-changed quotes with numbers are rejected; the tier is the lenient | |
| bound, so strict wins. Negations ("not/no/except/unless"), approximate tier: the | |
| same counts as the aligned span, so none added and none dropped (8 audit: a deleted | |
| "not" and "no" -> "on" passed). An exact match contains them already. Quote >= | |
| CITATION_MIN_QUOTE_CHARS; not longer than the section. | |
| - Besides the cited section, each check says whether the quote is in the passages | |
| SHOWN with that source_id (the shown chunks inside the cited section, joined in | |
| document order so a quote across two chunks still matches; A's overlapping windows | |
| are merged) and in the cited document at all (a quote from the right document but | |
| the wrong section). 5b handoff: a model can quote a version it was never shown. | |
| - Citing a version not in force on the policy date is NOT flagged: it can be | |
| legitimate (5b: Q052 cites SABS-2026's start date to show it does not apply). | |
| Measured on the official runs (8 survey): A 137 of 138 citations exact in the shown | |
| text (the miss quoted the passage HEADER, a label we add, not source text); B 196 of | |
| 196. No quote used "..." and none was under 30 characters. | |
| Plain Python + rapidfuzz, no LangGraph or eval import: C and the app use it. | |
| """ | |
| import re | |
| from collections import Counter | |
| from collections.abc import Iterable, Sequence | |
| from dataclasses import dataclass | |
| from functools import cached_property | |
| from typing import Protocol | |
| import pandas as pd | |
| from rapidfuzz import fuzz | |
| from coveragecheck import config | |
| from coveragecheck.text import match_map, normalize_for_match, normalize_words | |
| ELLIPSIS = re.compile(r"\.{3,}|\u2026") | |
| NUMBER = re.compile(r"\d+(?:[.,]\d+)*") | |
| NEGATION = re.compile(r"\b(?:not|no|except|unless)\b") | |
| WORD = re.compile(r"[^\W_]") # a letter or digit | |
| class Quoted(Protocol): | |
| """Anything with a source_id and a quote (agent.schemas.Citation, test stand-ins).""" | |
| source_id: str | |
| quote: str | |
| def fragments(quote: str) -> list[str]: | |
| """The quote's pieces between elisions ("..." or the ellipsis character), raw and | |
| in order, keeping only pieces with a letter or digit (a quote that starts with | |
| "..." has no first piece; " . . " between elisions is not text to look for).""" | |
| return [p for p in ELLIPSIS.split(quote) if WORD.search(p)] | |
| def numbers(words: str) -> list[str]: | |
| """The numbers in normalize_words text, commas dropped ("1,000" == "1000"), so a | |
| reformatted thousands separator does not count as a changed number.""" | |
| return [n.replace(",", "") for n in NUMBER.findall(words)] | |
| def negations(words: str) -> Counter: | |
| """How many times each negation word occurs in normalize_words text.""" | |
| return Counter(NEGATION.findall(words)) | |
| class Text: | |
| """One text to search, in both normalized forms, computed once.""" | |
| raw: str | |
| def tight(self) -> str: # normalize_for_match: the exact tier | |
| return normalize_for_match(self.raw) | |
| def words(self) -> str: # normalize_words: the approximate tier and its guards | |
| return normalize_words(self.raw) | |
| def numbers(self) -> tuple[str, ...]: # in text order, for has_run | |
| return tuple(numbers(self.words)) | |
| def has_run(sequence: Sequence[str], run: Sequence[str]) -> bool: | |
| """True when run occurs in sequence as consecutive items (an empty run always | |
| does). A verbatim quote's numbers are a consecutive run of its source's numbers.""" | |
| n = len(run) | |
| return any(tuple(sequence[i : i + n]) == tuple(run) for i in range(len(sequence) - n + 1)) | |
| def find_in_order(parts: list[str], text: str) -> bool: | |
| """True when every part occurs in text, each after the end of the previous one.""" | |
| position = 0 | |
| for part in parts: | |
| found = text.find(part, position) | |
| if found < 0: | |
| return False | |
| position = found + len(part) | |
| return True | |
| def exact_problems(pieces: list[str], text: Text) -> list[str]: | |
| """Why the exact tier fails (empty = the fragments occur in order and each | |
| fragment's numbers occur together, in order, in the text).""" | |
| if not find_in_order([normalize_for_match(p) for p in pieces], text.tight): | |
| return ["not found word for word"] | |
| for piece in pieces: | |
| run = numbers(normalize_words(piece)) | |
| if not has_run(text.numbers, run): | |
| return [f"numbers {run} do not appear like this in the cited text"] | |
| return [] | |
| def approximate_problems(pieces: list[str], text: Text, min_ratio: float) -> list[str]: | |
| """Why the fuzzy fallback fails (empty = it passes): each fragment, in order, must | |
| align with score >= min_ratio, its numbers must be in the aligned span, and its | |
| negation words must be exactly those of the span (none added, none dropped). A | |
| fuzzy match tolerates one changed word; these are the words that must not be the | |
| one. The span is never widened: a number or "not" just outside it would excuse a | |
| changed one (8 audit).""" | |
| position = 0 | |
| for piece in pieces: | |
| words = normalize_words(piece) | |
| rest = text.words[position:] | |
| if len(words) > len(rest): | |
| return [f"fragment {piece.strip()[:60]!r} is not in the cited text"] | |
| aligned = fuzz.partial_ratio_alignment(words, rest) | |
| if aligned is None or aligned.score < min_ratio: | |
| return [f"fragment {piece.strip()[:60]!r} is not in the cited text"] | |
| span = rest[aligned.dest_start : aligned.dest_end] | |
| missing = sorted(set(numbers(words)) - set(numbers(span))) | |
| if missing: | |
| return [f"numbers {missing} are not in the matching text"] | |
| if negations(words) != negations(span): | |
| changed = sorted( | |
| (negations(words) - negations(span)) | (negations(span) - negations(words)) | |
| ) | |
| return [f"negation words {changed} differ from the matching text"] | |
| position += aligned.dest_end | |
| return [] | |
| def match(quote: str, text: Text, min_ratio: float = config.CITATION_MIN_RATIO): | |
| """(tier, problems) of a quote against one text: ("exact", []), ("approximate", | |
| []) or (None, the reasons the approximate tier failed, which are the most specific | |
| ones: "numbers [...]" rather than "not found word for word").""" | |
| pieces = fragments(quote) | |
| if not pieces: | |
| return None, ["the quote has no words"] | |
| if not exact_problems(pieces, text): | |
| return "exact", [] | |
| fuzzy = approximate_problems(pieces, text, min_ratio) | |
| if not fuzzy: | |
| return "approximate", [] | |
| return None, fuzzy | |
| class Located: | |
| """Where a quote sits in a raw text: one (start, end) character span per fragment, | |
| in order, and how it was found ("exact" or "approximate").""" | |
| spans: tuple[tuple[int, int], ...] | |
| tier: str | |
| def locate( | |
| quote: str, | |
| raw: str, | |
| mapped: tuple[str, list[int]] | None = None, | |
| min_ratio: float = config.CITATION_MIN_RATIO, | |
| ) -> Located | None: | |
| """The quote's place in raw, for the app to highlight (Step 9; the checker keeps no | |
| offsets). Each fragment is searched in the normalized text (text.match_map, which | |
| remembers where each character came from), in order: word for word first, else | |
| the best fuzzy alignment scoring >= min_ratio. None when a fragment can't be | |
| placed. It only POINTS at the text: whether the citation passes is Checker.check's | |
| verdict (with its number and negation guards), which the app shows beside it. | |
| mapped: match_map(raw), when the caller caches it (0.28 s on the longest law).""" | |
| pieces = [p for p in (normalize_for_match(f) for f in fragments(quote)) if p] | |
| if not pieces: | |
| return None | |
| tight, origin = mapped or match_map(raw) | |
| for tier in ("exact", "approximate"): | |
| spans, position = [], 0 | |
| for piece in pieces: | |
| found = _find(piece, tight, position, tier, min_ratio) | |
| if found is None: | |
| break | |
| start, end = found | |
| span = (origin[start], origin[end - 1] + 1) | |
| spans.append(span if tier == "exact" else whole_words(raw, *span)) | |
| position = end | |
| else: | |
| return Located(tuple(spans), tier) | |
| return None | |
| def whole_words(raw: str, start: int, end: int) -> tuple[int, int]: | |
| """The span widened to whole words: a fuzzy alignment's edges can fall inside a | |
| word ("e is no coverage" for "there is no coverage"), which reads as a bug when | |
| highlighted. Only for the approximate tier: an exact span is what was quoted.""" | |
| while 0 < start < len(raw) and raw[start - 1].isalnum() and raw[start].isalnum(): | |
| start -= 1 | |
| while 0 < end < len(raw) and raw[end - 1].isalnum() and raw[end].isalnum(): | |
| end += 1 | |
| return start, end | |
| def _find(piece: str, tight: str, position: int, tier: str, min_ratio: float): | |
| """(start, end) of piece in tight[position:] (normalized offsets), or None. The | |
| fuzzy tier refuses a piece longer than the rest of the text: rapidfuzz would swap | |
| the two strings and align the text inside the piece (Step 8 found this).""" | |
| if tier == "exact": | |
| start = tight.find(piece, position) | |
| return None if start < 0 else (start, start + len(piece)) | |
| rest = tight[position:] | |
| if len(piece) > len(rest): | |
| return None | |
| aligned = fuzz.partial_ratio_alignment(piece, rest) | |
| if aligned is None or aligned.score < min_ratio or aligned.dest_end <= aligned.dest_start: | |
| return None | |
| return position + aligned.dest_start, position + aligned.dest_end | |
| class CitationCheck: | |
| """One citation's verdict. tier: how the quote matched the CITED SECTION ("exact", | |
| "approximate" or None). problems: why it fails at that tier (empty = it passes): | |
| when neither tier matched, the approximate tier's reason (the most specific one); | |
| plus the length guards. in_shown: found (either tier) in the passages shown with | |
| that source_id (None = no shown list given). in_doc: found in the cited document | |
| (True whenever the section matched). feedback() is the strict verdict for System | |
| C's verify node.""" | |
| source_id: str | |
| quote: str | |
| tier: str | None | |
| problems: tuple[str, ...] | |
| in_shown: bool | None | |
| in_doc: bool | |
| def exact(self) -> bool: | |
| """Passes the strict tier: the headline hallucinated-citation rate counts the rest.""" | |
| return self.tier == "exact" and not self.problems | |
| def grounded(self) -> bool: | |
| """Passes the exact or the approximate tier.""" | |
| return self.tier is not None and not self.problems | |
| def feedback(self) -> list[str]: | |
| """Why this citation fails the STRICT check System C's verify node applies | |
| (exact, and in the passages shown), worded as instructions to the model; empty | |
| = it passes. An approximate match and an unshown quote have no problems at | |
| their own tier, so they get a reason here (8 audit: else a retry says nothing).""" | |
| out = list(self.problems) | |
| if self.tier == "approximate" and not self.problems: | |
| out.append("the quote is close to the text but not word for word: copy it exactly") | |
| if self.tier is not None and self.in_shown is False: | |
| out.append("the quote is not in the passages you were given: quote only from them") | |
| return out | |
| def retry_message(checks: Iterable[CitationCheck]) -> str | None: | |
| """One message for a retry of the answer, naming each failing citation by its | |
| source_id and the start of its quote, with its feedback; None when all pass.""" | |
| lines = [ | |
| f'- {c.source_id} "{c.quote.strip()[:60]}": {"; ".join(c.feedback())}' | |
| for c in checks | |
| if c.feedback() | |
| ] | |
| if not lines: | |
| return None | |
| return "These citations failed the check against the passages:\n" + "\n".join(lines) | |
| class Piece: | |
| """A chunk a system can show: its document, its section, its order in the corpus | |
| tables, and (A's naive windows only) its character range, to merge overlaps.""" | |
| doc_id: str | |
| source_id: str | |
| order: int | |
| text: str | |
| start: int | None = None | |
| end: int | None = None | |
| def join_pieces(pieces: Iterable[Piece]) -> str: | |
| """Shown pieces as one text in document order, duplicates dropped. Consecutive | |
| naive windows of a document overlap by NAIVE_CHUNK_OVERLAP characters: a window | |
| that overlaps or touches the previous one continues it, glued on with no separator | |
| and without the overlap, so a quote (or a word) across the seam is whole. Other | |
| pieces are separate blocks, one per line.""" | |
| out: list[str] = [] | |
| doc, end = None, None # the run of naive text the next window could continue | |
| for piece in sorted(set(pieces), key=lambda p: p.order): | |
| continues = piece.doc_id == doc and None not in (end, piece.start) and piece.start <= end | |
| if continues: | |
| out.append(piece.text[end - piece.start :]) | |
| else: | |
| out.append(("\n" if out else "") + piece.text) | |
| doc = piece.doc_id | |
| end = max(end, piece.end) if continues else piece.end | |
| return "".join(out) | |
| def ancestry(sections: pd.DataFrame) -> dict[str, frozenset[str]]: | |
| """source_id -> itself and its ancestors (parent_source_id chain). The same walk | |
| as evals.hits.ancestry, repeated because verify must not import evals.""" | |
| parent = dict(zip(sections.source_id, sections.parent_source_id, strict=True)) | |
| out = {} | |
| for source in parent: | |
| chain, node = set(), source | |
| while node is not None and node not in chain: | |
| chain.add(node) | |
| node = parent.get(node) | |
| out[source] = frozenset(chain) | |
| return out | |
| class Checker: | |
| """The citation checker over the corpus tables. Build once (load()); normalized | |
| section texts are computed on first use and kept.""" | |
| def __init__(self, sections: pd.DataFrame, pieces: dict[str, Piece]): | |
| self.lineage = ancestry(sections) | |
| self.doc = dict(zip(sections.source_id, sections.doc_id, strict=True)) | |
| rows = zip(sections.source_id, sections.heading_path.fillna(""), sections.text, strict=True) | |
| self.raw = {source: f"{head}\n{text}" for source, head, text in rows} | |
| self.pieces = pieces | |
| self.texts: dict[str, Text] = {} | |
| def load(cls) -> "Checker": | |
| """sections.parquet, plus every chunk B/C can show (chunks.parquet: heading path | |
| + text, as the passages show them) and every window A can show | |
| (naive_chunks.parquet: raw text and its character range).""" | |
| from coveragecheck.index.store import load_table | |
| sections = load_table(config.INDEX_DIR / "sections.parquet") | |
| chunks = load_table(config.INDEX_DIR / "chunks.parquet") | |
| naive = load_table(config.INDEX_DIR / "naive_chunks.parquet") | |
| return cls(sections, pieces_from(chunks, naive)) | |
| def section(self, source_id: str) -> Text: | |
| """The cited section's heading path + full subtree text (cached).""" | |
| if source_id not in self.texts: | |
| self.texts[source_id] = Text(self.raw[source_id]) | |
| return self.texts[source_id] | |
| def shown(self, source_id: str, chunk_ids: Sequence[str]) -> Text: | |
| """The shown chunks that sit inside the cited section (A: inside the cited | |
| document), joined in document order. Unknown chunk ids are ignored.""" | |
| inside = [ | |
| p | |
| for c in chunk_ids | |
| if (p := self.pieces.get(c)) is not None | |
| and source_id in self.lineage.get(p.source_id, frozenset({p.source_id})) | |
| ] | |
| return Text(join_pieces(inside)) | |
| def check(self, citation: Quoted, shown: Sequence[str] | None = None) -> CitationCheck: | |
| """Check one citation against its section, the shown chunks (if given) and its | |
| document.""" | |
| source, quote = citation.source_id, citation.quote | |
| if source not in self.raw: | |
| return CitationCheck( | |
| source, | |
| quote, | |
| None, | |
| (f"source_id {source!r} does not exist: use only the source_ids shown",), | |
| False, | |
| False, | |
| ) | |
| section = self.section(source) | |
| tier, problems = match(quote, section) | |
| shortest = config.CITATION_MIN_QUOTE_CHARS | |
| if len(quote.strip()) < shortest: # fails even when found: it matches almost anything | |
| problems = [*problems, f"quote shorter than {shortest} characters"] | |
| if len(normalize_for_match(quote)) > len(section.tight): | |
| problems = [*problems, "quote longer than the cited section"] | |
| if tier is not None: | |
| in_doc = True | |
| else: | |
| in_doc = match(quote, self.section(self.doc[source]))[0] is not None | |
| in_shown = None | |
| if shown is not None: | |
| shown_text = self.shown(source, shown) | |
| in_shown = bool(shown_text.raw) and match(quote, shown_text)[0] is not None | |
| return CitationCheck(source, quote, tier, tuple(problems), in_shown, in_doc) | |
| def check_all( | |
| self, citations: Iterable[Quoted], shown: Sequence[str] | None = None | |
| ) -> list[CitationCheck]: | |
| """Every citation of one answer, in order.""" | |
| return [self.check(c, shown) for c in citations] | |
| def pieces_from(chunks: pd.DataFrame, naive: pd.DataFrame) -> dict[str, Piece]: | |
| """chunk_id -> Piece for both id spaces (structured "DOC#sec:n", naive "DOC~n"; | |
| they never overlap, 4d survey). Structured chunks carry their heading path, as B's | |
| passages show it; naive windows their character range.""" | |
| out = {} | |
| heads = chunks.heading_path.fillna("") | |
| for i, (cid, doc, source, head, text) in enumerate( | |
| zip(chunks.chunk_id, chunks.doc_id, chunks.source_id, heads, chunks.text, strict=True) | |
| ): | |
| out[cid] = Piece(doc, source, i, f"{head}\n{text}" if head else text) | |
| offset = len(chunks) | |
| for i, (cid, doc, source, text, start, end) in enumerate( | |
| zip( | |
| naive.chunk_id, | |
| naive.doc_id, | |
| naive.source_id, | |
| naive.text, | |
| naive.char_start, | |
| naive.char_end, | |
| strict=True, | |
| ) # fmt: skip | |
| ): | |
| out[cid] = Piece(doc, source, offset + i, text, int(start), int(end)) | |
| if len(out) != len(chunks) + len(naive): | |
| raise ValueError("chunk ids of chunks.parquet and naive_chunks.parquet overlap") | |
| return out | |