TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
9.76 kB
"""Text utilities shared by ingestion (Step 2) and citation checking (Step 8).
Standard library only, so the deployed app can import it without the `ingest`
dependency group.
Two different jobs, kept deliberately separate:
- clean_text / strip_furniture / is_junk / prepare_item: cleanup of the text we STORE
and show. Words are never changed, so stored text still reads like the source.
- normalize_for_match: aggressive normalization used only to COMPARE a quote with
the source. Its output is never stored or shown.
Tables of contents are NOT detected here: Docling labels the OAP 1 contents page as a
"document_index" table and e-Laws marks contents with "TOCid" paragraph styles, so the
chunker drops them by label/style. (A text-only TOC rule wrongly dropped fill-in lines
like "numbered ........ 3".)
"""
import functools
import re
import unicodedata
# --- clean_text ------------------------------------------------------------------------
# Invisible or meaningless characters: soft hyphen, zero-width characters, byte-order
# mark, the replacement character left by broken PDF glyphs, and the empty/ticked
# checkboxes drawn on blank forms.
_INVISIBLE = dict.fromkeys(map(ord, "\u00ad\u200b\u200c\u200d\u2060\ufeff\ufffdβ˜β˜‘β˜’β–‘"))
_PRIVATE_USE = re.compile("[\ue000-\uf8ff]") # font glyphs from PDF form fields
# Control characters (not tab/newline/carriage return): OPCF 5 draws its bullets
# with byte 0x83, which arrives as the C1 control character U+0083.
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
_SPACES = re.compile(r"[^\S\n]+") # any run of spaces/tabs/odd Unicode spaces, not newlines
_SPACE_AROUND_NEWLINE = re.compile(r" *\n *")
# Fill-in blanks on forms are drawn with runs of underscores or dots ("$_______",
# "numbered ........"). Each run is shortened to one short visible blank.
_BLANK_UNDERSCORES = re.compile(r"_{3,}")
_BLANK_DOTS = re.compile(r"(?:[.…][ \t]?){4,}") # 4+ dots/ellipses; a normal "..." is kept
def _short_dots(match: re.Match) -> str:
"""Replace a dotted blank with "...", keeping a following space if there was one."""
return "... " if match.group().endswith((" ", "\t")) else "..."
def clean_text(text: str) -> str:
"""Tidy stored text: invisible characters, odd spaces, long fill-in blanks.
Never changes words. Keeps line breaks. Running it twice gives the same result.
"""
text = text.translate(_INVISIBLE)
text = _PRIVATE_USE.sub("", text)
text = _CONTROL.sub("", text)
text = _SPACES.sub(" ", text) # before the blank rules, so ".... ...." is one run
text = _BLANK_UNDERSCORES.sub("___", text)
text = _BLANK_DOTS.sub(_short_dots, text)
text = _SPACE_AROUND_NEWLINE.sub("\n", text)
return text.strip()
# --- furniture and junk --------------------------------------------------------------
# Page furniture that leaks into body text on FSRA forms. Matched case-sensitively and
# exactly as printed, so ordinary words ("in print form", "a clear form") are safe.
_FURNITURE = [
re.compile(r"\b(?:Print|Save|Clear|Reset) Form\b"), # fillable-PDF buttons
re.compile(r"^(?:PRINT|SAVE|CLEAR|RESET)$"), # the same buttons as lone items (OPCF 5)
re.compile(r"\bPage \d+ of \d+\b"), # "Page 1 of 2" footer
re.compile(r"Β©?\s?King['’]s Printer for Ontario,?"), # copyright footer
re.compile(r"\bEffective \(\d{4}-\d{2}-\d{2}\)"), # edition footer on older OPCFs
# Form code with optional edition: "AF-074E", "AF-074E-p (2024)", "AF-090 (10/03)".
# The edition must contain a digit, so real words in brackets are never eaten.
re.compile(r"\bAF-\d{3}E?(?:-p)?\b(?: ?\((?=[^)]*\d)[\w/ -]{2,14}\))?"),
]
_EMPTY_BRACKETS = re.compile(r"\(\s*\)") # left behind by "(AF-137E)"
def strip_furniture(text: str) -> str:
"""Remove page furniture (form buttons, "Page x of y", form codes, copyright)."""
for pattern in _FURNITURE:
text = pattern.sub(" ", text)
return clean_text(_EMPTY_BRACKETS.sub(" ", text))
def is_junk(text: str) -> bool:
"""True for an extracted item with no content: empty, or furniture and nothing else.
Conservative on purpose: a short real item such as "(a)" or "$" is NOT junk.
"""
cleaned = clean_text(text)
if not cleaned:
return True
remaining = strip_furniture(cleaned)
was_only_furniture = remaining != cleaned and not re.search(r"[A-Za-z]{2,}", remaining)
return was_only_furniture
def prepare_item(text: str) -> str | None:
"""The one call the chunker needs: cleaned, furniture-free text, or None if junk."""
return None if is_junk(text) else strip_furniture(text)
# --- normalize_for_match ---------------------------------------------------------------
# Characters that look alike but have different codes: curly vs straight quotes,
# the many kinds of dash, and the fraction slash that NFKC produces for "Β½".
_LOOKALIKES = str.maketrans(
{
"β€˜": "'", "’": "'", "β€š": "'", "β€›": "'", "β€²": "'", "Β΄": "'", "ΚΌ": "'", "`": "'",
"β€œ": '"', "”": '"', "β€ž": '"', "β€Ÿ": '"', "β€³": '"', "Β«": '"', "Β»": '"',
"‐": "-", "‑": "-", "β€’": "-", "–": "-", "β€”": "-", "―": "-", "βˆ’": "-", "⁃": "-",
"⁄": "/",
}
) # fmt: skip
# Marks that carry no words: bullets, fill-in blanks, and "..." (an LLM may elide text).
_NO_WORDS = re.compile(r"[Β·β€’_]|\.{3,}")
_HYPHEN_IN_WORD = re.compile(r"(?<=[a-z])-(?=[a-z])") # "non-pecuniary", "auto-\nmobile"
def normalize_for_match(text: str) -> str:
"""Normalize text for comparing a quote against its source. Never store the result.
Removes ALL whitespace, so PDF extraction quirks compare equal:
"( i i i )" == "(iii)" and "WhereYou" == "Where You". Also lowercases, unifies
look-alike characters, and ignores bullets, blanks and hyphens inside words.
Known limit: digits split by spaces collide ("$1 000" == "$10 00"), so the
citation checker must compare numbers separately.
"""
# Map look-alikes both before NFKC (NFKC splits "Β΄" into a space plus an accent)
# and after it (NFKC creates "⁄" from "Β½" and "..." from "…").
text = unicodedata.normalize("NFKC", text.translate(_LOOKALIKES))
text = clean_text(text).translate(_LOOKALIKES).casefold()
text = _NO_WORDS.sub("", text)
text = re.sub(r"\s+", "", text)
return _HYPHEN_IN_WORD.sub("", text) # after whitespace removal: "auto-\nmobile" joins
@functools.cache
def _char_form(char: str) -> str:
"""One character as normalize_for_match turns it, before its rules that look at
neighbours (blanks, "...", spaces, in-word hyphens): look-alikes, NFKC, the
invisible/private/control characters clean_text deletes, case. May be "" or 2+
characters ("ß" -> "ss")."""
char = unicodedata.normalize("NFKC", char.translate(_LOOKALIKES))
char = _CONTROL.sub("", _PRIVATE_USE.sub("", char.translate(_INVISIBLE)))
return char.translate(_LOOKALIKES).casefold()
def _drop(chars: str, origin: list[int], pattern: re.Pattern) -> tuple[str, list[int]]:
"""chars with every match of pattern deleted (one pass, like re.sub), and the
origin of each character that is kept."""
keep = [True] * len(chars)
for found in pattern.finditer(chars):
keep[found.start() : found.end()] = [False] * (found.end() - found.start())
kept = [i for i, k in enumerate(keep) if k]
return "".join(chars[i] for i in kept), [origin[i] for i in kept]
# clean_text's dotted blank as it looks before spaces are collapsed (after NFKC "…" is
# already "..."); it becomes "...", which _NO_WORDS then deletes, so delete it whole.
_DOT_BLANK = re.compile(r"(?:\.[^\S\n]*){4,}")
_WHITESPACE = re.compile(r"\s+")
def match_map(text: str) -> tuple[str, list[int]]:
"""normalize_for_match(text) together with, for each of its characters, the index
in `text` it came from (Step 9: the app highlights a quote found in the normalized
form, so it needs the way back; normalize_for_match itself keeps no offsets).
Mirrors normalize_for_match step by step on a per-character stream: character
forms, then dotted blanks, bullets/underscores/"...", whitespace and in-word
hyphens deleted in the same order. A test pins the output equal to
normalize_for_match on every real section. Known gap: NFKC done per character
cannot compose a letter with a separate combining accent."""
chars, origin = [], []
for i, char in enumerate(text):
form = _char_form(char)
chars.append(form)
origin.extend([i] * len(form))
stream = "".join(chars)
for pattern in (_DOT_BLANK, _NO_WORDS, _WHITESPACE, _HYPHEN_IN_WORD):
stream, origin = _drop(stream, origin, pattern)
return stream, origin
_HYPHEN_BREAK = re.compile(r"(?<=[a-z])- ?(?=[a-z])") # "auto- mobile", "non-pecuniary"
def normalize_words(text: str) -> str:
"""normalize_for_match's lighter twin, for fuzzy matching (Step 8): the same
look-alikes, case, bullets, blanks and in-word hyphens, but whitespace runs become
ONE space instead of vanishing. Words stay separate, so a fuzzy alignment returns a
span whose words and numbers can be checked ("is not covered" vs "is covered"),
which the no-space form can't give. Never store the result."""
text = unicodedata.normalize("NFKC", text.translate(_LOOKALIKES))
text = clean_text(text).translate(_LOOKALIKES).casefold()
text = _NO_WORDS.sub(" ", text)
text = re.sub(r"\s+", " ", text).strip()
return _HYPHEN_BREAK.sub("", text)