Parser: a cross-reference split at the line end is not a new unit; synthetic PDF gold set (Atrium#53)

A line ending in "ust." / "pkt" / "lit." continues into the number opening the next
line ("§ 4 ust." + "1."), so that number is not a new unit, point or letter.

scripts/gold_synthetic.py builds 12 Polish contracts with known structure (fonts,
justification, marker gaps, hyphenation, NBSP, footers, headings at page end) and
measures extract_text + parse_structure against truth.json: 994 units, 0 missing,
0 extra (before the fix: 5 missing, 10 extra).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-28 19:15:12 +01:00
co-authored by Claude Opus 5.5
parent b040c89162
commit e20ff33d88
16 changed files with 1599 additions and 1 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -74,6 +74,16 @@ _LEVELS: list[tuple[NodeKind, re.Pattern[str]]] = [
]
# "... określonego w § 4 ust." + newline + "1." — the line-breaker split a cross-reference,
# and the number opening the next line belongs to it, not to a new unit (synthetic gold
# set, Atrium#53). The same for "pkt" + "2)" and "lit." + "a)".
_REFERENCE_TAIL = re.compile(rf"{_UNIT_KEYWORD}[ \t]*$")
def _continues_reference(region: str, hit: re.Match[str]) -> bool:
return bool(_REFERENCE_TAIL.search(region[: hit.start()].rstrip("\r\n")))
def _slice_children(
text: str,
region_start: int,
@@ -86,7 +96,7 @@ def _slice_children(
kind, pattern = levels[0]
region = text[region_start:region_end]
hits = list(pattern.finditer(region))
hits = [h for h in pattern.finditer(region) if not _continues_reference(region, h)]
if not hits and kind == "litera":
hits = _dot_letters(region)
@@ -245,3 +245,19 @@ def test_a_stray_marker_inside_a_run_stays_in_the_letter_before_it() -> None:
assert [c.number for c in unit.children] == ["a", "b"]
assert text[unit.children[1].start:unit.children[1].end].endswith("rozwiązaniach.\n")
def test_a_reference_split_at_the_line_end_is_not_a_new_unit() -> None:
# synthetic gold set (Atrium#53): "§ 4 ust." ends a line and "1." opens the next
text = (
"§ 2\n"
"1. Kary nie przekroczą 20% wynagrodzenia określonego w § 4 ust.\n"
"1. Spory rozstrzyga sąd, w szczególności:\n"
"1) sąd powszechny;\n"
"2. Termin wynosi 30 dni, o którym mowa w pkt\n"
"2) powyżej.\n"
)
(par,) = parse_structure(text)
assert [u.number for u in par.children] == ["1", "2"]
assert [p.number for p in par.children[0].children] == ["1"]
assert par.children[1].children == ()
+348
View File
@@ -0,0 +1,348 @@
"""A synthetic gold set for the PDF reader, and its measurement (Atrium#53, "Pomiar czytnika PDF").
The real gold set (12 client contracts) is not in the repository. This builds 12 Polish contracts
whose structure is KNOWN, typeset the ways that broke readers before (2026-09-11, S3: a point marker
with no space character after it, no line end before a paragraph heading), and measures what the
engine's reader (`text.extract_text`: pypdfium2 + `pdf_layout.compose`) and parser
(`structure.parse_structure`) recover - against the truth, not against another reader.
python scripts/gold_synthetic.py generate [--fonts DIR] # writes data/gold-synthetic/
python scripts/gold_synthetic.py measure # prints the table, exit 1 on a miss
reportlab (BSD) is a tool of this script only, never a dependency of a package. Fonts come from the
system (Windows: C:/Windows/Fonts; elsewhere pass --fonts with arial/times/georgia/verdana/calibri
TTFs, or DejaVu as a stand-in). The generated PDFs are committed, so `measure` needs no fonts.
"""
from __future__ import annotations
import argparse
import json
import random
import sys
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "data" / "gold-synthetic"
# ── content ──────────────────────────────────────────────────────────────────
TITLES = ["Przedmiot umowy", "Wynagrodzenie", "Termin wykonania", "Odbiór", "Kary umowne",
"Odpowiedzialność", "Poufność", "Prawa autorskie", "Rozwiązanie umowy", "Siła wyższa",
"Ochrona danych osobowych", "Postanowienia końcowe", "Gwarancja", "Zabezpieczenie"]
SENTENCES = [
"Wykonawca zobowiązuje się wykonać przedmiot umowy z należytą starannością, zgodnie z "
"obowiązującymi przepisami oraz zasadami wiedzy technicznej.",
"Zamawiający zapłaci wynagrodzenie w terminie 30 dni od dnia doręczenia prawidłowo "
"wystawionej faktury VAT.",
"Strony ustalają, że wszelkie zmiany niniejszej umowy wymagają formy pisemnej pod rygorem "
"nieważności.",
"W przypadku zwłoki w wykonaniu przedmiotu umowy Wykonawca zapłaci karę umowną w wysokości "
"0,2% wynagrodzenia brutto za każdy dzień zwłoki.",
"Żadna ze Stron nie ponosi odpowiedzialności za niewykonanie zobowiązań spowodowane siłą "
"wyższą, o ile niezwłocznie zawiadomi o niej drugą Stronę.",
"Informacje poufne mogą być wykorzystane wyłącznie w celu należytego wykonania umowy i nie "
"mogą być ujawnione osobom trzecim.",
"Zamawiający jest uprawniony do odstąpienia od umowy w terminie 14 dni od powzięcia "
"wiadomości o okolicznościach uzasadniających odstąpienie.",
"Wykonawca przenosi na Zamawiającego autorskie prawa majątkowe do utworów powstałych w "
"wykonaniu umowy na polach eksploatacji wskazanych w załączniku nr 2.",
"Spory wynikające z umowy rozstrzyga sąd właściwy miejscowo dla siedziby Zamawiającego.",
"Łączna wysokość kar umownych nie przekroczy 20% wynagrodzenia brutto określonego w § 4 ust. 1.",
]
POINT_SENT = ["dostarczenie dokumentacji powykonawczej", "przeszkolenie pracowników Zamawiającego",
"usunięcie wad stwierdzonych przy odbiorze", "przekazanie kodów źródłowych",
"uzyskanie wymaganych pozwoleń i uzgodnień", "zapewnienie serwisu gwarancyjnego"]
LETTER_SENT = ["w formie elektronicznej", "w formie pisemnej", "za pośrednictwem poczty kurierskiej",
"osobiście w siedzibie Strony"]
@dataclass
class Node:
kind: str # paragraph | unit | point | letter
number: str
title: str = ""
text: str = ""
children: list[Node] = field(default_factory=list)
def contract(seed: int, letters_dot: bool) -> list[Node]:
rnd = random.Random(seed)
out = []
for p in range(1, rnd.randint(6, 9) + 1):
par = Node("paragraph", str(p), title=rnd.choice(TITLES))
for u in range(1, rnd.randint(1, 4) + 1):
unit = Node("unit", str(u), text=" ".join(rnd.sample(SENTENCES, rnd.randint(1, 2))))
if rnd.random() < 0.5:
unit.text = unit.text.rstrip(".") + ", w szczególności:"
for k in range(1, rnd.randint(2, 4) + 1):
pt = Node("point", str(k), text=rnd.choice(POINT_SENT) + ";")
if rnd.random() < 0.35:
pt.text = pt.text.rstrip(";") + ", przy czym:"
for j, ch in enumerate("abcd"[: rnd.randint(2, 3)]):
pt.children.append(Node("letter", ch, text=rnd.choice(LETTER_SENT) + ";"))
unit.children.append(pt)
par.children.append(unit)
out.append(par)
# "a." convention is checked as runs a., b., ...; the parser accepts both
if letters_dot:
for n in _walk(out):
if n.kind == "letter":
n.title = "dot"
return out
def _walk(nodes):
for n in nodes:
yield n
yield from _walk(n.children)
def truth_paths(nodes, prefix=()) -> list[str]:
out = []
for n in nodes:
here = (*prefix, f"{KIND_PL[n.kind]}:{n.number}")
out.append("/".join(here))
out += truth_paths(n.children, here)
return out
# ── typesetting ──────────────────────────────────────────────────────────────
@dataclass
class Variant:
font: str
size: float
justify: bool = False # word by word at computed x: NO space characters in the content
marker_gap: bool = False # marker and text drawn apart, no space character between (S3)
heading_inline: bool = False # "§ 3. Wynagrodzenie" on one line instead of two
centered_heading: bool = False
hyphenate: bool = False # split long words at the line end with a hyphen
nbsp: bool = False # "§\u00a03", "art.\u00a0471"
no_space_after_unit: bool = False # "1.Okres" (a gold-set PDF did this)
letters_dot: bool = False # "a." instead of "a)"
footer: bool = False # "Strona n z m" at the foot of each page
heading_at_page_end: bool = False # force page breaks right after headings
columns_indent: float = 18.0
VARIANTS = [
Variant("times", 11),
Variant("arial", 10, heading_inline=True),
Variant("times", 11, marker_gap=True),
Variant("georgia", 10.5, justify=True),
Variant("arial", 10, hyphenate=True, justify=True),
Variant("verdana", 9.5, nbsp=True, marker_gap=True),
Variant("times", 11, heading_at_page_end=True, footer=True),
Variant("calibri", 10, no_space_after_unit=True, letters_dot=True),
Variant("georgia", 10, centered_heading=True, footer=True),
Variant("calibri", 9, justify=True, marker_gap=True, heading_inline=True),
Variant("verdana", 9, hyphenate=True, nbsp=True, footer=True),
Variant("arial", 10.5, justify=True, centered_heading=True, heading_at_page_end=True),
]
KIND_PL = {"paragraph": "paragraf", "unit": "ustep", "point": "punkt", "letter": "litera"}
FONT_FILES = {"times": "times.ttf", "arial": "arial.ttf", "georgia": "georgia.ttf",
"verdana": "verdana.ttf", "calibri": "calibri.ttf"}
class Typesetter:
W, H, M = 595.0, 842.0, 64.0
def __init__(self, path: Path, v: Variant):
from reportlab.pdfgen import canvas
self.c = canvas.Canvas(str(path), pagesize=(self.W, self.H), invariant=1)
self.v, self.page = v, 1
self.lead = v.size * 1.45
self.y = self.H - self.M
self.pages_text: list[str] = []
def width(self, s: str) -> float:
from reportlab.pdfbase.pdfmetrics import stringWidth
return stringWidth(s, self.v.font, self.v.size)
def newpage(self):
if self.v.footer:
self.c.setFont(self.v.font, 8)
self.c.drawCentredString(self.W / 2, 30, f"Strona {self.page}")
self.c.showPage()
self.page += 1
self.y = self.H - self.M
def need(self, lines: int):
if self.y - lines * self.lead < self.M:
self.newpage()
def line(self, x: float, words: list[str], last: bool, right: float):
self.c.setFont(self.v.font, self.v.size)
if self.v.justify and not last and len(words) > 1:
total = sum(self.width(w) for w in words)
gap = (right - x - total) / (len(words) - 1)
for w in words:
self.c.drawString(x, self.y, w)
x += self.width(w) + gap
else:
self.c.drawString(x, self.y, " ".join(words))
self.y -= self.lead
def para(self, x: float, text: str, marker: str = "", first_x: float | None = None):
"""A block of text with an optional marker hanging at `first_x`."""
right = self.W - self.M
words = text.split(" ")
lines, cur = [], []
for w in words:
trial = " ".join([*cur, w])
if cur and self.width(trial) > right - x:
if self.v.hyphenate and len(w) > 9:
head = w[: len(w) // 2] + "-"
if self.width(" ".join([*cur, head])) <= right - x:
lines.append([*cur, head])
cur = [w[len(w) // 2:]]
continue
lines.append(cur)
cur = [w]
else:
cur.append(w)
if cur:
lines.append(cur)
self.need(1)
if marker:
self.c.setFont(self.v.font, self.v.size)
if self.v.marker_gap:
self.c.drawString(first_x if first_x is not None else x - 16, self.y, marker)
else: # marker and the first line in one string, a space character between
lines[0] = [marker, *lines[0]]
x0 = first_x if first_x is not None else x - 16
self.line(x0, lines[0], len(lines) == 1, right)
lines = lines[1:]
for i, ln in enumerate(lines):
self.need(1)
self.line(x, ln, i == len(lines) - 1, right)
return
for i, ln in enumerate(lines):
self.need(1)
self.line(x, ln, i == len(lines) - 1, right)
def heading(self, number: str, title: str):
v = self.v
sp = "\u00a0" if v.nbsp else " "
self.need(3)
self.y -= self.lead * 0.5
self.c.setFont(v.font, v.size)
if v.heading_inline:
s = f"§{sp}{number}. {title}"
(self.c.drawCentredString(self.W / 2, self.y, s) if v.centered_heading
else self.c.drawString(self.M, self.y, s))
self.y -= self.lead
else:
for s in (f"§{sp}{number}", title):
(self.c.drawCentredString(self.W / 2, self.y, s) if v.centered_heading
else self.c.drawString(self.M, self.y, s))
self.y -= self.lead
def save(self):
if self.v.footer:
self.c.setFont(self.v.font, 8)
self.c.drawCentredString(self.W / 2, 30, f"Strona {self.page}")
self.c.save()
def render(path: Path, nodes: list[Node], v: Variant, name: str):
t = Typesetter(path, v)
t.c.setTitle(name)
t.c.setFont(v.font, v.size + 3)
t.c.drawCentredString(t.W / 2, t.y, "UMOWA O ŚWIADCZENIE USŁUG")
t.y -= t.lead * 2
t.para(t.M, "zawarta w Warszawie pomiędzy Zamawiającym a Wykonawcą, zwanymi dalej łącznie "
"Stronami, o następującej treści:")
ind = v.columns_indent
for k, par in enumerate(nodes):
if v.heading_at_page_end and k % 3 == 2:
t.y = t.M + t.lead * 3.2 # the heading lands at the foot, its body on the next page
t.heading(par.number, par.title)
for unit in par.children:
m = f"{unit.number}."
text = unit.text
if v.no_space_after_unit: # "1.Wykonawca" - no space at all
t.need(1)
t.para(t.M, f"{unit.number}.{text}")
else:
t.para(t.M + ind, text, marker=m, first_x=t.M)
for pt in unit.children:
t.para(t.M + 2 * ind, pt.text, marker=f"{pt.number})", first_x=t.M + ind)
for le in pt.children:
mark = f"{le.number}." if le.title == "dot" else f"{le.number})"
t.para(t.M + 3 * ind, le.text, marker=mark, first_x=t.M + 2 * ind)
t.save()
def generate(fonts: Path):
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
for key, fn in FONT_FILES.items():
pdfmetrics.registerFont(TTFont(key, str(fonts / fn)))
OUT.mkdir(parents=True, exist_ok=True)
truth = {}
for i, v in enumerate(VARIANTS, 1):
name = f"syn-{i:02d}"
nodes = contract(1000 + i, v.letters_dot)
render(OUT / f"{name}.pdf", nodes, v, name)
truth[name] = {"variant": {k: getattr(v, k) for k in v.__dataclass_fields__},
"paths": truth_paths(nodes)}
(OUT / "truth.json").write_text(json.dumps(truth, ensure_ascii=False, indent=1), "utf-8")
print(f"{len(VARIANTS)} PDFs + truth.json in {OUT}")
# ── measurement ──────────────────────────────────────────────────────────────
def parsed_paths(nodes, prefix=()) -> list[str]:
out = []
for n in nodes:
here = (*prefix, f"{n.kind.value if hasattr(n.kind, 'value') else n.kind}:{n.number}")
out.append("/".join(here))
out += parsed_paths(n.children, here)
return out
def measure() -> int:
from collections import Counter
from compass_ingestion.structure import parse_structure
from compass_ingestion.text import extract_text
truth = json.loads((OUT / "truth.json").read_text("utf-8"))
rows, bad = [], 0
for name, t in truth.items():
doc = extract_text(OUT / f"{name}.pdf")
got = Counter(parsed_paths(parse_structure(doc.text)))
want = Counter(t["paths"])
missing = sum((want - got).values())
extra = sum((got - want).values())
bad += missing + extra
flags = ",".join(k for k, val in t["variant"].items() if val is True)
rows.append((name, t["variant"]["font"], flags, sum(want.values()), missing, extra,
sorted((want - got).elements())[:3], sorted((got - want).elements())[:3]))
print(f"{'plik':8} {'font':8} {'jednostek':>9} {'brak':>5} {'nadmiar':>7} warianty")
for r in rows:
print(f"{r[0]:8} {r[1]:8} {r[3]:9} {r[4]:5} {r[5]:7} {r[2]}")
if r[4] or r[5]:
print(f"{'':8} brak: {r[6]} nadmiar: {r[7]}")
total = sum(r[3] for r in rows)
print(f"\nrazem: {total} jednostek, {sum(r[4] for r in rows)} brak, {sum(r[5] for r in rows)} nadmiar")
return 1 if bad else 0
def main() -> int:
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
g = sub.add_parser("generate")
g.add_argument("--fonts", type=Path, default=Path("C:/Windows/Fonts"))
sub.add_parser("measure")
a = ap.parse_args()
if a.cmd == "generate":
generate(a.fonts)
return 0
return measure()
if __name__ == "__main__":
sys.exit(main())