File size: 13,567 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""Step 2b: convert every document in the manifest into a DoclingDocument (JSON).

Two paths, one output format:
- FSRA PDFs go through Docling's PDF pipeline (no OCR: every PDF has a text layer).
- e-Laws laws (.docx) are read paragraph by paragraph with python-docx. e-Laws marks
  the legal structure with its own paragraph style names ("section-e", "headnote-e",
  ...), which Docling ignores, so law_role() maps each style to a role and
  law_to_docling() builds the DoclingDocument from those roles.

Both paths save data/parsed/<doc_id>.json, so the chunker (Step 2c) treats every
document the same way. Results are cached: a document is re-parsed only when anything
that produced it changes (see cache_key).

Run:  uv run python -m coveragecheck.ingest.parse   [--force]
"""

import hashlib
import json
import os
import re
import sys
import time
from collections.abc import Iterator
from functools import cache
from importlib.metadata import version
from pathlib import Path

import docx
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import HeadingHierarchyOptions, PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption
from docling_core.types.doc import DocItemLabel, DoclingDocument
from docx.table import Table
from docx.text.paragraph import Paragraph

from coveragecheck import config
from coveragecheck.ingest.download import read_manifest, sha256_bytes

CACHE_FILE = "_cache.json"

# --- e-Laws laws: paragraph style -> role ----------------------------------------------
# Style names as e-Laws writes them, without the "-e" suffix the regulations add
# ("section-e") and the Insurance Act doesn't ("section").

LAW_PART_STYLES = {"partnum", "partheading"}  # "PART VI AUTOMOBILE INSURANCE" -> level 1
LAW_GROUP_STYLES = {"heading1", "Pheadingx"}  # "Income Replacement Benefits" -> level 2
LAW_SECTION_STYLES = {"section"}  # first paragraph of a section: "268 (1) ..." -> level 3
LAW_HEADNOTE_STYLES = {"headnote", "headnoteind", "headnoteitalic"}  # a section's title
LAW_SKIP_STYLES = {
    "Normal",  # web-page leftovers: "Français", "Back to top"
    "shorttitle", "regnumber", "regtitle", "chapter",  # title block (title is in manifest)
    "ConsolidationPeriod", "comment", "version", "Notice",  # e-Laws metadata
    "footnoteLeft", "footnote",  # amendment history ("O. Reg. 34/10, s. 8 (1).")
    "toc", "scanned", "line",  # contents heading, images, rules
    "heading3",  # the word "Diagram" above each Fault Determination Rules diagram
    "partnumRevoked",  # "Part VIII (ss. 330-333) Repealed"
}  # fmt: skip
# Wording that is NOT in force: e-Laws announces a future change with a note ("Note: On
# July 1, 2026, ..." or "Note: On a day to be named by proclamation ...") and prints
# the new wording in styles whose names start with "Y" (Ysection, Ysubsection, ...).
# Both the notes and the Y-styled wording are dropped.
FUTURE_CHANGE_NOTE = re.compile(r"^Note: On (?:a day to be named|[A-Z][a-z]+ \d{1,2}, \d{4})")
SECTION_NUMBER = re.compile(r"^(\d+(?:\.\d+)*(?:-\d+(?:\.\d+)*)?)")  # 3 / 268 / 267.5 / 2-5


def style_base(name: str) -> str:
    """Style name without e-Laws' "-e" language suffix: "section-e" -> "section"."""
    return name[:-2] if name.endswith("-e") else name


def section_number(text: str) -> str | None:
    """Section number at the start of a section paragraph: "268 (1) Every..." -> "268"."""
    m = SECTION_NUMBER.match(text.strip())
    return m.group(1) if m else None


def law_role(style: str, text: str) -> str:
    """Decide what one law paragraph is. Returns one of:

    "part", "group", "headnote", "section", "text", "skip".
    """
    if style in LAW_PART_STYLES:
        return "part"
    if style.startswith("Y"):
        # Every Y-style is wording not yet in force. That includes Part headings
        # ("Ypartheading"): they announce a future renaming of the current Part, and
        # the paragraphs after them are still in force, so they must NOT end the Part.
        return "skip"
    if not text or style in LAW_SKIP_STYLES or FUTURE_CHANGE_NOTE.match(text):
        return "skip"
    if style in LAW_HEADNOTE_STYLES:
        return "headnote"
    if style in LAW_GROUP_STYLES:
        return "group"
    if style in LAW_SECTION_STYLES and section_number(text):
        return "section"
    return "text"


def one_line(text: str) -> str:
    """Headings like "PART VI\\nAUTOMOBILE INSURANCE" read better on one line."""
    return re.sub(r"\s+", " ", text).strip()


def iter_body(document: docx.document.Document) -> Iterator[Paragraph | Table]:
    """Paragraphs and tables in reading order (python-docx lists them separately)."""
    for child in document.element.body.iterchildren():
        if child.tag.endswith("}p"):
            yield Paragraph(child, document)
        elif child.tag.endswith("}tbl"):
            yield Table(child, document)


def is_contents_table(table: Table) -> bool:
    """e-Laws tables of contents use TOC* paragraph styles in their cells."""
    return any(
        p.style is not None and p.style.name.startswith("TOC")
        for row in table.rows
        for cell in row.cells
        for p in cell.paragraphs
    )


def law_to_docling(path: Path, name: str, scope: str = "") -> DoclingDocument:
    """Build a DoclingDocument from an e-Laws .docx, using law_role() per paragraph.

    scope: keep only one Part (e.g. "Part VI"); empty keeps the whole law.
    A headnote is held until we see what follows it: before a section it becomes the
    section's title ("Section 268: Priority"); before anything else (a subsection's
    "Same" or "Exception") it stays as a caption (text).
    """
    doc = DoclingDocument(name=name)
    # "Part VI" must not match "PART VI.1" or "PART VII": no letter, digit or dot after.
    scope_re = re.compile(rf"^{re.escape(scope)}(?![\w.])", re.I) if scope else None
    in_scope = scope_re is None
    headnote: str | None = None

    def flush_headnote() -> None:
        """A held headnote that didn't title a section stays where it was, labelled
        CAPTION (a short title for what follows: "Choice of insurer" before a
        subsection) so the chunker keeps it with that subsection."""
        nonlocal headnote
        if headnote:
            doc.add_text(label=DocItemLabel.CAPTION, text=headnote)
            headnote = None

    def add_text(text: str) -> None:
        flush_headnote()
        doc.add_text(label=DocItemLabel.TEXT, text=text)

    for block in iter_body(docx.Document(str(path))):
        if isinstance(block, Table):
            if in_scope and not is_contents_table(block):
                for row in block.rows:  # one text line per row keeps exact wording
                    add_text(" | ".join(cell.text.strip() for cell in row.cells))
            continue

        text = block.text.strip()
        style = style_base(block.style.name) if block.style is not None else "Normal"
        role = law_role(style, text)

        if role == "part":  # a new Part also switches scope
            flush_headnote()
            in_scope = scope_re is None or bool(scope_re.match(text))
            if in_scope:
                doc.add_heading(one_line(text), level=1)
        elif not in_scope or role == "skip":
            continue
        elif role == "headnote":
            flush_headnote()  # two headnotes in a row: the first one stays a caption
            headnote = one_line(text)
        elif role == "group":
            flush_headnote()
            doc.add_heading(one_line(text), level=2)
        elif role == "section":
            number = section_number(text)
            doc.add_heading(f"Section {number}" + (f": {headnote}" if headnote else ""), level=3)
            headnote = None
            doc.add_text(label=DocItemLabel.TEXT, text=text)
        else:  # "text"
            add_text(text)
    flush_headnote()
    return doc


# --- PDFs -----------------------------------------------------------------------------


# The Docling settings we choose. Everything else is Docling's default, which is
# covered by recording Docling's version in the cache key.
PDF_SETTINGS = {
    "do_ocr": False,  # every FSRA PDF has a text layer
    "do_table_structure": True,  # OAP 1 has a few real tables
    "heading_hierarchy": True,  # rebuild heading levels from numbering: 6 > 6.2 > 6.2.1
}


def pdf_options() -> PdfPipelineOptions:
    return PdfPipelineOptions(
        do_ocr=PDF_SETTINGS["do_ocr"],
        do_table_structure=PDF_SETTINGS["do_table_structure"],
        heading_hierarchy_options=HeadingHierarchyOptions(
            enabled=PDF_SETTINGS["heading_hierarchy"]
        ),
    )


@cache
def pdf_converter() -> DocumentConverter:
    """Docling PDF converter, created once (loading its layout model takes seconds)."""
    return DocumentConverter(
        format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pdf_options())}
    )


def parse_file(row: dict[str, str], raw_dir: Path) -> DoclingDocument:
    """Convert one manifest row's file into a DoclingDocument."""
    path = raw_dir / row["filename"]
    suffix = path.suffix.lower()
    if suffix == ".docx":
        return law_to_docling(path, name=row["doc_id"], scope=row["scope"])
    if suffix == ".pdf":
        doc = pdf_converter().convert(path).document
        doc.name = row["doc_id"]
        return doc
    raise ValueError(f"{row['doc_id']}: don't know how to parse {suffix!r} files")


# --- cache ------------------------------------------------------------------------------


def cache_key(row: dict[str, str], sha256: str) -> dict[str, str]:
    """Everything that determines a parse result. If any of it changes, re-parse."""
    if Path(row["filename"]).suffix.lower() == ".docx":
        # The law rules live in this file, so its fingerprint changes whenever they do:
        # no version number to remember to bump. (Laws re-parse in seconds.)
        rules = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()[:12]
        settings = {"rules": rules, "python-docx": version("python-docx"),
                    "scope": row["scope"]}  # fmt: skip
    else:
        settings = {
            "docling": version("docling"),
            "docling-core": version("docling-core"),
            # Only our own settings: Docling's full options object contains an unordered
            # set, so its JSON (and any hash of it) changes from one run to the next.
            "settings": json.dumps(PDF_SETTINGS, sort_keys=True),
        }
    return {"sha256": sha256, **settings}


def load_cache(parsed_dir: Path) -> dict[str, dict[str, str]]:
    """Read the cache index; a missing or corrupt index just means "re-parse"."""
    try:
        return json.loads((parsed_dir / CACHE_FILE).read_text(encoding="utf-8"))
    except (FileNotFoundError, json.JSONDecodeError):
        return {}


def write_atomic(path: Path, text: str) -> None:
    """Write to a temp file, then swap it in: a crash never leaves a half-written file."""
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(text, encoding="utf-8")
    os.replace(tmp, path)


def is_fresh(entry: dict[str, str] | None, key: dict[str, str], json_path: Path) -> bool:
    """A cached parse is reusable only if its key matches and its JSON file exists."""
    return entry == key and json_path.exists()


# --- command --------------------------------------------------------------------------


def heading_count(doc: DoclingDocument) -> int:
    return sum(
        1 for item, _ in doc.iterate_items()
        if item.label in (DocItemLabel.SECTION_HEADER, DocItemLabel.TITLE)
    )  # fmt: skip


def run(manifest: Path, raw_dir: Path, parsed_dir: Path, force: bool = False) -> int:
    """Parse every manifest document that isn't already cached; print a table.

    One failing document doesn't stop the others; failures are listed at the end and
    the exit code is 1.
    """
    parsed_dir.mkdir(parents=True, exist_ok=True)
    cache_index = load_cache(parsed_dir)
    failed: list[str] = []
    print(f"{'doc_id':<18} {'status':<8} {'items':>6} {'headings':>9} {'seconds':>8}")
    for row in read_manifest(manifest):
        json_path = parsed_dir / f"{row['doc_id']}.json"
        try:
            key = cache_key(row, sha256_bytes((raw_dir / row["filename"]).read_bytes()))
            start = time.perf_counter()
            if not force and is_fresh(cache_index.get(row["doc_id"]), key, json_path):
                doc, status = DoclingDocument.load_from_json(json_path), "cached"
            else:
                doc, status = parse_file(row, raw_dir), "parsed"
                write_atomic(json_path, json.dumps(doc.export_to_dict()))
                cache_index[row["doc_id"]] = key
                write_atomic(parsed_dir / CACHE_FILE, json.dumps(cache_index, indent=1))
            seconds = time.perf_counter() - start
        except Exception as e:  # report and carry on with the next document
            failed.append(row["doc_id"])
            print(f"{row['doc_id']:<18} FAILED   {type(e).__name__}: {e}")
            continue
        n_items = sum(1 for _ in doc.iterate_items())
        print(
            f"{row['doc_id']:<18} {status:<8} {n_items:>6} {heading_count(doc):>9} {seconds:>8.1f}"
        )
    if failed:
        print(f"\nFAILED: {', '.join(failed)}")
    return 1 if failed else 0


def main() -> None:
    sys.exit(run(config.MANIFEST_PATH, config.RAW_DIR, config.PARSED_DIR, "--force" in sys.argv))


if __name__ == "__main__":
    main()