File size: 9,758 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""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)