Spaces:
Sleeping
Sleeping
Download src/coveragecheck/ingest/xref.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/ingest/xref.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/ingest/xref.py
-
curl -L -o xref.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/ingest/xref.py
18.4 kB
| """Step 2d: find cross-references in chunk text and resolve them to citable sections. | |
| A reference like "subsection 268 (2) of the Act" or 'Section 3, "Liability Coverage" | |
| of the Policy' points at another section. System B adds the sections a top chunk | |
| points to (SPEC Step 6: cross-reference expansion), and the OPCF -> OAP 1 references, | |
| inverted, tell it which change forms modify which policy sections. | |
| Three steps per chunk: | |
| 1. strip_history() removes e-Laws amendment notes ("O. Reg. 34/10, s. 21 (4)."). | |
| They end almost every law subsection and look exactly like references. | |
| 2. find_refs() finds the references: section / subsection / clause / "s." + | |
| number(s), "statutory condition N", "OPCF 44R". A relative reference such as | |
| "subsection (1)" or "clause (a)" points inside the same section and is skipped. | |
| 3. resolve() decides which document and section each number means (SPEC Step 2d | |
| rules, from the 2c design audit) and checks that the target exists. | |
| Every reference found is kept in data/index/xrefs.parquet with its status, so the | |
| rules can be audited; chunks.parquet gets only the resolved targets. | |
| """ | |
| import re | |
| from collections.abc import Iterable | |
| from dataclasses import dataclass, field | |
| from rapidfuzz import fuzz, process | |
| from coveragecheck import config | |
| OAP1_FORM = "OAP 1" | |
| ACT_FORM = "R.S.O. 1990, c. I.8" # Insurance Act (Part VI is in the corpus) | |
| SABS_FORM = "O. Reg. 34/10" # Statutory Accident Benefits Schedule (2 versions) | |
| # --- 1. amendment history --------------------------------------------------------------- | |
| # Where an amendment came from: a regulation, a revised statute, or an annual statute. | |
| _SOURCE = ( | |
| r"(?:O\. Reg\. \d+/\d+" # O. Reg. 34/10 | |
| r"|R\.R\.O\. 1990, Reg\. \d+" # R.R.O. 1990, Reg. 664 | |
| r"|R\.S\.O\. 1990, c\. [A-Z]\.\d+" # R.S.O. 1990, c. I.8 | |
| r"|\d{4}, c\. \d+(?:, Sched\. [\w.]+)?)" # 1993, c. 10 / 2014, c. 9, Sched. 3 | |
| ) | |
| # ", s. 21 (4)", ", ss. 3, 4", ", s 6" (one note lacks the dot), ", s. 3 (6, 7)" | |
| _PROVISION = r"[\d.]+(?: ?\([^)]*\))*" | |
| HISTORY = re.compile(rf"{_SOURCE}(?:, ss?\.? ?{_PROVISION}(?:(?:, | to | and ){_PROVISION})*)?") | |
| def strip_history(text: str) -> str: | |
| """Remove amendment-history notes and other citations of amending statutes. | |
| "... the insurer shall pay. O. Reg. 34/10, s. 21 (4); O. Reg. 251/15, s. 3." | |
| -> "... the insurer shall pay. ; ." Only text that names an amending source is | |
| removed, so a reference such as "subsection 21 (4)" is never touched. | |
| """ | |
| return HISTORY.sub(" ", text) | |
| # --- 2. finding references -------------------------------------------------------------- | |
| # A section number with optional subsection/clause brackets: 268 / 268 (2) / 263 (5) (b) | |
| # / 2.2.3 (6) / 1.2(c) / 267.12 (1) (a). The number must not be followed by "/" (a year | |
| # or regulation number) or by more digits. One space may follow a dot inside the | |
| # number: the PDF text of OPCF 23B breaks "232.1" as "232. 1" (never a line break, so | |
| # "Section 12.\n2. Subsection 17" stays two items). | |
| _BRACKET = r"\([0-9a-z.]{1,6}\)" | |
| _DOTTED = r"\d+(?:\.(?: (?=\d))?\d+)*" | |
| _NUM = rf"{_DOTTED}(?![\d/])(?:\s?{_BRACKET})*" | |
| _SEP = r"(?:\s*,\s*(?:and\s+|or\s+)?|\s+and\s+|\s+or\s+|\s+to\s+)" | |
| # A list item may be a bare bracket, a sub-part of the number before it: | |
| # "subsection 261 (1) or (1.1) or 263 (5.1)" cites ss. 261 and 263. | |
| _ITEM = rf"(?:{_NUM}|{_BRACKET}(?:\s?{_BRACKET})*)" | |
| REF = re.compile( | |
| rf"\b(?P<kind>statutory conditions?|sub-?sections?|sections?|clauses?|ss?\.)" | |
| rf"\s?(?P<nums>{_NUM}(?:{_SEP}{_ITEM})*)", | |
| re.I, | |
| ) | |
| OPCF_REF = re.compile(r"\bOPCF\s?(\d+[A-Z]?)\b") | |
| # A sub-section number written without a keyword, scoped by the Section after it: | |
| # "The limitation under 3.5.1 of Section 3, "Liability Coverage" of this Policy" | |
| # (OPCF 6B/6C; 6F writes "3.5.1. of Section 3"). Only this form: a bare "1.4.3" | |
| # elsewhere has no reliable scope. | |
| BARE_SUBSECTION = re.compile(r"(?<![\d.])(\d+\.\d+(?:\.\d+)*)\.? of Section (\d+)\b") | |
| _LEADING_NUMBER = re.compile(_DOTTED) | |
| class Ref: | |
| """One reference found in a text. | |
| numbers: section numbers ("268", "2.2.3"); a range "5 to 11" gives ("5", "11") | |
| with is_range. after: the text right after the reference, where a qualifier | |
| such as "of the Act" or ', "Liability Coverage" of the Policy' sits. | |
| """ | |
| match: str | |
| kind: str # "section", "statutory condition" or "opcf" | |
| numbers: tuple[str, ...] | |
| is_range: bool = False | |
| after: str = "" | |
| def _numbers(nums: str) -> tuple[tuple[str, ...], bool]: | |
| """ "251, 265 and 268" -> (("251", "265", "268"), False); "5 to 11" -> range. | |
| Brackets are dropped: "268 (2)" cites section 268, and a bare "(1.1)" item is a | |
| part of the number before it. A range needs two numbers: "3 (2) to (6)" is not.""" | |
| parts = [p for p in re.split(_SEP, nums) if not p.startswith("(")] | |
| leading = (_LEADING_NUMBER.match(p).group().replace(" ", "") for p in parts) | |
| numbers = tuple(dict.fromkeys(leading)) | |
| return numbers, bool(re.search(r"\s+to\s+\d", nums)) and len(numbers) == 2 | |
| def find_refs(text: str) -> list[Ref]: | |
| """References in one chunk's text, after removing amendment notes. | |
| Not references: a relative "subsection (1)" / "clause (a)" (no number before the | |
| bracket), "this section", and a paragraph/clause number of the form | |
| "paragraph 2 of subsection 25 (1)" (the "subsection 25" after it is matched). | |
| "clause 263 (5) (b)" names section 263, so a clause counts when a bracket follows. | |
| """ | |
| text = strip_history(text) | |
| refs: list[Ref] = [] | |
| for m in REF.finditer(text): | |
| kind = m.group("kind").lower() | |
| nums = m.group("nums") | |
| if kind.startswith("clause") and "(" not in nums: | |
| continue # "clause 2" alone is not a section number | |
| numbers, is_range = _numbers(nums) | |
| refs.append( | |
| Ref( | |
| match=m.group(0), | |
| kind="statutory condition" if kind.startswith("statutory") else "section", | |
| numbers=numbers, | |
| is_range=is_range, | |
| after=text[m.end() : m.end() + 120], | |
| ) | |
| ) | |
| for m in BARE_SUBSECTION.finditer(text): | |
| if m.group(1).split(".")[0] == m.group(2): # "3.5.1 of Section 3", not "of 4" | |
| after = text[m.end() : m.end() + 120] | |
| refs.append(Ref(match=m.group(0), kind="section", numbers=(m.group(1),), after=after)) | |
| for m in OPCF_REF.finditer(text): | |
| refs.append(Ref(match=m.group(0), kind="opcf", numbers=(m.group(1),))) | |
| return refs | |
| # --- 3. resolving ----------------------------------------------------------------------- | |
| # Qualifier right after a reference (and its list): which document it means. Between | |
| # the number and "of ..." only a quoted title ('Section 3, "Liability Coverage" of the | |
| # Policy') or a bracketed description ("section 268 (statutory accident benefits) of | |
| # the Act") may sit, so a later, unrelated "of the policy" never counts. | |
| _GAP = r'^\s*,?\s*(?:["β][^"β]{0,80}["β]\s*,?\s*)?(?:\([^)]{0,60}\)\s*)*' | |
| # Order matters: the first pattern that matches wins. | |
| QUALIFIERS: list[tuple[str, re.Pattern[str]]] = [ | |
| ("own", re.compile(_GAP + r"of this (?:change form|form|endorsement)\b", re.I)), | |
| # "of your policy", "of the Policy", "of Policy" (OPCF 3), also after | |
| # 'under Section 3, "Liability Coverage"' (OPCF 3: "Sections 3.3.1 ... under ...") | |
| ( | |
| "oap1", | |
| re.compile( | |
| _GAP + r'(?:under Section \d+,?\s*["β][^"β]{0,80}["β]\s*)?' | |
| r"of (?:(?:your|the|this) )?(?:automobile )?policy\b", | |
| re.I, | |
| ), | |
| ), | |
| ("self", re.compile(_GAP + r"of this Regulation\b")), | |
| ("act", re.compile(_GAP + r"of the (?:Insurance )?Act\b(?!,? \d)")), | |
| ( | |
| "sabs", | |
| re.compile( | |
| _GAP + r"of (?:the Statutory Accident Benefits Schedule\b" | |
| r"|(?:Ontario Regulation|O\. Reg\.) 34/10\b)" # the SABS by its number | |
| ), | |
| ), | |
| # anything else named after "of" is outside the corpus: another statute, code or | |
| # regulation, "that Act" (one just named), an old version of the Act, a Schedule of | |
| # an amending statute, the AMA Guides | |
| ( | |
| "out", | |
| re.compile( | |
| _GAP + r"of (?:" | |
| r"(?:the |Ontario )?(?:(?:[A-Z][\w'β-]*|of|and|to|the),? )+(?:Act|Code|Guides)\b" | |
| r"|(?:Ontario )?Regulation \d+/\d+" | |
| r"|the Old Regulation\b|that (?:Act|Regulation)\b|Schedule \d+" | |
| r"|the pre-[\w-]+(?: [\w-]+){0,3} Act\b" # an old version: "pre-1997 Act", | |
| # "pre-transition date Act" | |
| r")" | |
| ), | |
| ), | |
| ] | |
| # 'Section 3, "Liability Coverage"': a quoted title right after the number | |
| QUOTED_TITLE = re.compile(r'^\s*,?\s*["β]([^"β]{3,80})["β]') | |
| def qualifier(ref: Ref) -> str | None: | |
| """Which document the words after a reference point to, or None if they don't.""" | |
| for name, pattern in QUALIFIERS: | |
| if pattern.search(ref.after): | |
| return name | |
| return None | |
| def _norm(text: str) -> str: | |
| return re.sub(r"[^a-z0-9]+", " ", text.lower()).strip() | |
| class CorpusIndex: | |
| """What resolve() needs to know about the corpus, built from sections.parquet rows. | |
| sections: {doc_id: set of section numbers}; docs: {form_id: [doc_id, ...]}; | |
| form_of: {doc_id: form_id}; oap1_titles: normalized OAP 1 section titles. | |
| """ | |
| sections: dict[str, set[str]] = field(default_factory=dict) | |
| docs: dict[str, list[str]] = field(default_factory=dict) | |
| form_of: dict[str, str] = field(default_factory=dict) | |
| oap1_titles: set[str] = field(default_factory=set) | |
| dotted: dict[str, bool] = field(default_factory=dict) # do section numbers nest? | |
| def from_sections(cls, rows: Iterable[dict], laws: set[str]) -> "CorpusIndex": | |
| index = cls() | |
| for r in rows: | |
| doc_id, form = r["doc_id"], r["form_id"] | |
| if doc_id not in index.form_of: | |
| index.form_of[doc_id] = form | |
| index.docs.setdefault(form, []).append(doc_id) | |
| index.sections[doc_id] = set() | |
| index.dotted[doc_id] = doc_id not in laws | |
| if r["section_number"]: | |
| index.sections[doc_id].add(r["section_number"]) | |
| if form == OAP1_FORM: # "Section 3: Liability Coverage" -> "liability coverage" | |
| title = r["heading_path"].rsplit(" > ", 1)[-1].split(": ", 1)[-1] | |
| index.oap1_titles.add(_norm(re.sub(r"^[\d.]+\s+", "", title))) | |
| return index | |
| def is_oap1_title(self, quoted: str) -> bool: | |
| """Is a quoted name an OAP 1 Section title? Fuzzy, because the forms misquote: | |
| OPCF 27 writes "Accidents Benefits Coverage" for "Accident Benefits Coverage".""" | |
| best = process.extractOne(_norm(quoted), self.oap1_titles, scorer=fuzz.ratio) | |
| return best is not None and best[1] >= config.XREF_TITLE_MIN_RATIO | |
| def one(self, form: str) -> str | None: | |
| """The doc_id of a form with a single version (OAP 1, the Insurance Act).""" | |
| docs = self.docs.get(form, []) | |
| return docs[0] if len(docs) == 1 else None | |
| def find(self, doc_id: str, number: str) -> str | None: | |
| """The section a number cites in a document, walking up dotted numbers to the | |
| nearest one that exists ("1.10" -> "1" in OPCF 44R). Law numbers don't nest: | |
| s. 268.3 is not part of s. 268, so they must match exactly.""" | |
| have = self.sections.get(doc_id, set()) | |
| if number in have: | |
| return number | |
| parts = number.split(".") | |
| while self.dotted.get(doc_id) and len(parts) > 1: | |
| parts.pop() | |
| if ".".join(parts) in have: | |
| return ".".join(parts) | |
| # e-Laws prints a block of revoked sections as one: "22.1-25. Revoked: ..." | |
| for s in have: | |
| lo, sep, hi = s.partition("-") | |
| if sep and _key(lo) <= _key(number) <= _key(hi): | |
| return s | |
| return None | |
| def _key(number: str) -> list[int]: | |
| """Sort key for section numbers: "22.1" < "23" < "25".""" | |
| return [int(p) for p in re.findall(r"\d+", number)] | |
| class Link: | |
| """One resolved (or unresolvable) target of a reference. | |
| status: "resolved" (target exists), "missing" (the document is in the corpus but | |
| the section isn't, e.g. Insurance Act s. 121, outside Part VI), "out_of_corpus" | |
| (another statute), "self" (points at the chunk's own section). | |
| """ | |
| number: str | |
| target_doc: str | None | |
| target_source_id: str | None | |
| status: str | |
| def target_docs(ref: Ref, number: str, doc_id: str, index: CorpusIndex) -> list[str] | None: | |
| """The document(s) a section number refers to, from the reference's qualifier and | |
| the citing document's kind. None means outside the corpus. | |
| - A qualifier wins: "of this change form" -> the form itself; "of your Policy" or a | |
| quoted OAP 1 Section title -> OAP 1; "of the Act" -> Insurance Act; "of this | |
| Regulation" -> itself; another statute -> outside the corpus. | |
| - Without one: >= 200 means the Insurance Act (the forms and regulations cite it | |
| by number); an OPCF means its own section if it has one, else OAP 1; anything | |
| else means the citing document itself. | |
| - The SABS has two versions: from inside, its own version; from outside, both | |
| (the Step 3 date filter keeps the one in force). | |
| """ | |
| form = index.form_of[doc_id] | |
| act, oap1 = index.one(ACT_FORM), index.one(OAP1_FORM) | |
| q = qualifier(ref) | |
| quoted = QUOTED_TITLE.match(ref.after) | |
| if q is None and quoted and index.is_oap1_title(quoted.group(1)): | |
| q = "oap1" | |
| if q in ("own", "self"): | |
| return [doc_id] | |
| if q == "oap1": | |
| return [oap1] if oap1 else None | |
| if q == "act": | |
| return [act] if act else None | |
| if q == "sabs": | |
| return [doc_id] if form == SABS_FORM else index.docs.get(SABS_FORM) | |
| if q == "out": | |
| return None | |
| if int(number.split(".")[0]) >= 200 and form != ACT_FORM: | |
| return [act] if act else None | |
| if form.startswith("OPCF"): | |
| own = index.find(doc_id, number.split(".")[0]) | |
| return [doc_id] if own else ([oap1] if oap1 else None) | |
| return [doc_id] | |
| def _expand_range(lo: str, hi: str, doc_id: str, index: CorpusIndex) -> list[str]: | |
| """ "sections 5 to 11" -> the existing sections from 5 to 11, at most XREF_MAX_RANGE. | |
| Numbers compare part by part, so "266 to 267.1" is 266, 266.x, 267, 267.1 and not | |
| 267.2 (a law inserts 267.2 after 267.1). In a law every number is its own section, | |
| so 5.1 and 10.2 count in "5 to 11". In OAP 1 or a form, numbers nest, so only | |
| numbers as deep as the first endpoint count ("sections 1 to 3" -> 1, 2, 3; their | |
| sub-sections are already covered by their parents). | |
| """ | |
| depth = lo.count(".") | |
| found = sorted( | |
| ( | |
| s | |
| for s in index.sections.get(doc_id, set()) | |
| if _key(lo) <= _key(s) <= _key(hi) | |
| and (not index.dotted.get(doc_id) or s.count(".") == depth) | |
| ), | |
| key=_key, | |
| ) | |
| return found[: config.XREF_MAX_RANGE] | |
| def resolve(ref: Ref, doc_id: str, own_source_id: str, index: CorpusIndex) -> list[Link]: | |
| """All targets of one reference made in `doc_id` (from the chunk `own_source_id`).""" | |
| if ref.kind == "opcf": | |
| docs = index.docs.get(f"OPCF {ref.numbers[0]}") | |
| if not docs: | |
| return [Link(ref.numbers[0], None, None, "out_of_corpus")] | |
| return [Link(ref.numbers[0], d, d, "self" if d == doc_id else "resolved") for d in docs] | |
| if ref.kind == "statutory condition": # Section 8 of OAP 1 prints the conditions | |
| oap1 = index.one(OAP1_FORM) | |
| pairs = [(n, [oap1], f"8.{n.split('.')[0]}") for n in ref.numbers] | |
| else: | |
| pairs = [] | |
| for n in ref.numbers: | |
| docs = target_docs(ref, n, doc_id, index) | |
| pairs.append((n, docs, n)) | |
| links: list[Link] = [] | |
| for number, docs, lookup in pairs: | |
| if docs is None or None in docs: | |
| links.append(Link(number, None, None, "out_of_corpus")) | |
| continue | |
| for d in docs: | |
| wanted = [lookup] | |
| if ref.kind == "section" and ref.is_range: | |
| if number != ref.numbers[0]: | |
| continue # the range's upper end is covered by the expansion | |
| wanted = _expand_range(ref.numbers[0], ref.numbers[1], d, index) or [lookup] | |
| for w in wanted: | |
| section = index.find(d, w) | |
| if section is None: | |
| links.append(Link(w, d, None, "missing")) | |
| continue | |
| sid = f"{d}#{section}" | |
| links.append(Link(w, d, sid, "self" if sid == own_source_id else "resolved")) | |
| return links | |
| def link_chunks(chunks: list[dict], index: CorpusIndex) -> list[dict]: | |
| """Fill each chunk's "xrefs" (resolved targets, sorted, no duplicates, never its | |
| own section) and return one edge row per (reference, target) for xrefs.parquet.""" | |
| edges: list[dict] = [] | |
| for c in chunks: | |
| targets: set[str] = set() | |
| for ref in find_refs(c["text"]): | |
| for link in resolve(ref, c["doc_id"], c["source_id"], index): | |
| edges.append( | |
| { | |
| "chunk_id": c["chunk_id"], | |
| "doc_id": c["doc_id"], | |
| "source_id": c["source_id"], | |
| "match": ref.match, | |
| "kind": ref.kind, | |
| "number": link.number, | |
| "target_doc": link.target_doc, | |
| "target_source_id": link.target_source_id, | |
| "status": link.status, | |
| } | |
| ) | |
| if link.status == "resolved": | |
| targets.add(link.target_source_id) | |
| c["xrefs"] = sorted(targets) | |
| return edges | |