feat(propose): the PDF shipped a structure index and the build discarded it unopened

`okf build` recovers a PDF's boundaries from the shape of its page text and
never opens the file's own `/Outlines` bookmark tree. On a 701-page process
code whose publisher also ships a NISO-STS structure for it, measured outside
this repository and reproduced here exactly: the shipped default finds 1967 of
2761 titled sections, 0 of its 28 chapters, and 794 of 794 misses have their
heading text PRESENT in the extracted text. The line was read; the boundary
was never opened. The same file's bookmark tree matches 2761 of 2761 of those
titles exactly after normalisation.

`--pdf-outline`, OFF, cuts a PDF at the boundaries its tree declares.

  boundaries                 1967 of 2761  ->  2759 of 2761  (gate was 2700)
  depth 1                       0 of 28    ->     28 of 28
  titles identical to source        --     ->   2761 of 2761
  false positives             163 of 2182  ->      3 of 2762
  directories with two files  132 of 2050  ->      2 of 2738
  front-matter concepts        72 of 2182  ->      2 of 2762
  consumption fasit present       4 of 7   ->        7 of 7
  hit@1 / hit@8 / hit@50      1/6 2/6 4/6  ->   3/6 5/6 6/6

It is a SEGMENTATION arm, not a reader option: the extracted text is byte for
byte the same either way. A PDF with no tree builds byte-identically with the
flag on -- `diff -r` empty across the pre-change tree, the arm off and the arm
on. An unresolvable `/Dest` is dropped and COUNTED, never fabricated into a
boundary and never a refusal of the file.

The bridge from (page, y) to a line index is the whole risk, so both routes
are measured. `extract_text_lines` splits lines identically to `extract_text`
on 701 of 701 pages, and is CHECKED per page rather than assumed. The y route
and the title route disagree on 0 of 2762 nodes, flat from a 0pt tolerance to
8pt and collapsing at 12pt, so the rule ships with no tolerance constant. The
naive "nearest line" rule was wrong on 1840 of 2762, one line early every time.

The orphan check is not applied to a bookmark mark: it asks whether anything
stands under a candidate's first line, which is the right question for a
heuristic's guess and the wrong one for a publisher's declaration. 683 of 2762
marks are container sections; applying it scores 2079 instead of 2759.

No new dependency and no second parse of the pages: `pdfminer.six` already
ships under `pdfplumber` in `[extract]`. 119.22s -> 183.31s wall, peak RSS
3252 -> 3251 MiB. The default does not move; 1 of the 8 reference PDFs carries
a usable tree at all.

`.pdf` also gains its `_EVIDENCE` row, as `measured` -- it was the row with the
most measurement behind it and no entry in the table.

Report: docs/2026-09-10-k3-runde12-pdf-outlines.md

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-09-10 02:27:41 +02:00
commit e1f4faa098
12 changed files with 1261 additions and 15 deletions

View file

@ -56,13 +56,14 @@ import json
import re
import sys
import unicodedata
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
from .errors import IngestError
from .extract import extract_text, strip_converter_attribute
from .extract import OutlineMark, extract_text, strip_converter_attribute
from .extract import pdf_outline as extract_pdf_outline
from .materialize import reduce_to_id_grammar
from .segmentation import observed_extractor_version
@ -135,6 +136,12 @@ RULE_SHEET_SECTION = "rule:sheet-section"
#: readable documents, that gate is what takes the false-positive count to 0
#: of the 31 that declare.
RULE_BOLD_TITLE = "rule:bold-title"
#: The PDF's own `/Outlines` tree. NOT `RULE_OUTLINE`: that one is Arm D, a
#: TEXT heuristic over numbered lines in the extracted text, and this one opens
#: a structure index the file already carries. A reader who cannot tell the two
#: apart in an artifact cannot tell a recovered heading from a declared one.
RULE_PDF_OUTLINE = "rule:pdf-outline"
RULE_NAMES = (
RULE_HEADING,
RULE_TABLE_BLOCK,
@ -144,6 +151,7 @@ RULE_NAMES = (
RULE_TABLE_GRID,
RULE_SHEET_SECTION,
RULE_BOLD_TITLE,
RULE_PDF_OUTLINE,
)
#: How many characters of context each side of a quote anchor carries. Enough
@ -597,6 +605,34 @@ def _sheet_section_rows(lines: list[str]) -> dict[int, tuple[str, str]]:
return sections
#: Rules the orphan check is not asked about. D3 because a sheet row carries
#: its content in its own cells, and the bookmark arm because the check judges
#: whether a GUESS was a heading -- a question a publisher's own tree has
#: already answered, and one that deletes every container section if asked.
_ORPHAN_EXEMPT = (RULE_SHEET_SECTION, RULE_PDF_OUTLINE)
def _split_outline_title(title: str) -> tuple[str | None, str]:
"""`("14.121", "Langsg\u00e5ende sikring T1")` -- the number becomes the directory.
Two grammars, both already in this module and neither invented here:
`_NUMBERED` for a dotted section number, then `_OUTLINE`'s bare one- or
two-digit form. The second matters because a document's TOP level is where
the dot has not appeared yet -- on the corpus this arm was measured
against, 59 of 2 761 titled sections carry a dotless token and all 28 of
its chapter-level sections are among them. Without it the whole top level
would land with no section number at all, in a bundle whose every other
level has one.
"""
dotted = _NUMBERED.match(title)
if dotted is not None:
return (dotted.group("number"), dotted.group("title"))
bare = _OUTLINE.match(title)
if bare is not None:
return (bare.group("number"), bare.group("title"))
return (None, title.strip())
def find_candidates(
text: str,
*,
@ -611,6 +647,7 @@ def find_candidates(
close_span_gaps: bool = False,
contents_name: bool = False,
bold_title: bool = False,
outline_marks: Sequence[OutlineMark] | None = None,
) -> list[Candidate]:
"""Every boundary the mechanical rules propose, in document order.
@ -682,6 +719,22 @@ def find_candidates(
before spans are closed, so the text they opened is carried by the mark
above rather than lost.
`outline_marks` is the PDF bookmark arm, and it is the only input here that
REPLACES the rules rather than gating one of them. A non-empty list is the
publisher's own declaration of the document's structure, so nothing below
votes against it: the text heuristics, the two gates and Arm F's fold are
all skipped, and the orphan check is not applied to its marks. An EMPTY
list means "this file carries no index" and leaves every rule untouched --
the two are different answers and must not collapse into one.
THE ORPHAN EXEMPTION IS THE ONE JUDGEMENT CALL HERE, and it is the same
shape as D3's. The check asks whether anything stands UNDER a candidate's
first line, which is the right question for a heading a heuristic GUESSED
and the wrong one for a section a publisher DECLARED: a chapter followed
immediately by its first subsection is a container, not a false positive.
Measured on a 701-page process code: 683 of 2 762 marks are containers, and
applying the check scores 2 079 of 2 761 boundaries instead of 2 762.
`sheet_section_rows` is D3's gate and it is OFF at False, where the scan is
not run at all. On, a RUN of numbered rows inside an open table block cuts
it: each such row opens a candidate that reaches the next section row, or
@ -717,6 +770,41 @@ def find_candidates(
# ordering rather than a property of this corpus.
admitted = {index: title for index, _, title in runs[-1]}
# The bookmark arm, and it is computed here for the same reason `admitted`
# is: the marks must be known and SORTED before the loop. They arrive
# already deduplicated by line, so `marked` stays ordered by construction
# and no span can close before it opens.
if outline_marks:
declared: list[tuple[int, Candidate]] = [
(
mark.line,
Candidate(
title=title,
level=mark.level,
number=number,
rule=RULE_PDF_OUTLINE,
start=offsets[mark.line],
end=end_of_text,
),
)
for mark in outline_marks
if mark.line < len(offsets)
for number, title in (_split_outline_title(mark.title),)
]
return _close_candidates(
text,
declared,
offsets,
end_of_text,
joined=set(),
absorbed=set(),
contents_run=set(),
unit_fold=False,
contents_name=False,
first_span_from_zero=first_span_from_zero,
close_span_gaps=close_span_gaps,
)
# D3's input, and the same whole-text reasoning as `admitted` above: a run
# is a property of the line list, not of a line.
sections = _sheet_section_rows(lines) if sheet_section_rows else {}
@ -887,6 +975,49 @@ def find_candidates(
if outline_gate:
marked, joined = _gate_outline(marked, joined, end_of_text, len(text))
absorbed = _absorbed_tables(text, marked, offsets, end_of_text) if keep_table_heading else set()
# Arm F clause 1's input, and it must be read HERE: the orphan pass below
# deletes every bodiless heading, which is every entry of a contents list
# but the last, and a run of one is below `CONTENTS_RUN`.
contents_run = (
_contents_run_positions(marked, contents_name=contents_name) if unit_fold else set()
)
return _close_candidates(
text,
marked,
offsets,
end_of_text,
joined=joined,
absorbed=absorbed,
contents_run=contents_run,
unit_fold=unit_fold,
contents_name=contents_name,
first_span_from_zero=first_span_from_zero,
close_span_gaps=close_span_gaps,
)
def _close_candidates(
text: str,
marked: list[tuple[int, Candidate]],
offsets: list[int],
end_of_text: int,
*,
joined: set[int],
absorbed: set[int],
contents_run: set[int],
unit_fold: bool,
contents_name: bool,
first_span_from_zero: bool,
close_span_gaps: bool,
) -> list[Candidate]:
"""`marked` -> the candidate list: orphan check, fold, then span closing.
Carved out of `find_candidates` when the bookmark arm arrived, unchanged in
behaviour: the arm produces its `marked` from a structure index instead of
from the line grammar, and every step from here down is the same question
for both. Duplicating it would be two orphan checks to keep in agreement.
"""
candidates: list[Candidate] = []
# The name an orphaned heading leaves behind, and the ONE candidate allowed
# to pick it up.
@ -909,13 +1040,6 @@ def find_candidates(
# empty, so the orphan check below stops firing on it by itself and no
# branch is needed there. Computed only when the caller asked, so every
# other arm's `marked` -> `candidates` mapping is untouched code.
absorbed = _absorbed_tables(text, marked, offsets, end_of_text) if keep_table_heading else set()
# Arm F clause 1's input, and it must be read HERE: the orphan pass below
# deletes every bodiless heading, which is every entry of a contents list
# but the last, and a run of one is below `CONTENTS_RUN`.
contents_run = (
_contents_run_positions(marked, contents_name=contents_name) if unit_fold else set()
)
for position_in_list, (_, candidate) in enumerate(marked):
if position_in_list in absorbed:
continue
@ -936,7 +1060,7 @@ def find_candidates(
# the rule could not fire at all. It is the same shape as a contents
# list without dot leaders, and it is the reason that one needed
# `Candidate.contents`.
orphan = candidate.rule != RULE_SHEET_SECTION and (
orphan = candidate.rule not in _ORPHAN_EXEMPT and (
not body.splitlines()[1:] or not "".join(body.splitlines()[1:]).strip()
)
if orphan:
@ -1329,6 +1453,7 @@ def build_plan(
close_span_gaps: bool = False,
contents_name: bool = False,
bold_title: bool = False,
outline_marks: Sequence[OutlineMark] | None = None,
) -> dict[str, Any]:
"""The artifact. Every entry PROPOSED, the plan itself never adjudicated."""
taken: set[str] = set()
@ -1347,6 +1472,7 @@ def build_plan(
close_span_gaps=close_span_gaps,
contents_name=contents_name,
bold_title=bold_title,
outline_marks=outline_marks,
)
for candidate in subdivide(text, candidates, max_segment_chars):
entries.append(
@ -1428,6 +1554,7 @@ def run(
pdf_headings: bool = False,
pdf_headings_reserve: bool = False,
ocr: bool = False,
pdf_outline: bool = False,
) -> int:
if max_segment_chars < 0:
raise ProposerError(
@ -1472,6 +1599,7 @@ def run(
# against another is refused by `assert_plan_applies`, which is the
# right outcome and a confusing one to debug.
text = extract_text(source.name, source_bytes, pdf_headings=pdf_headings, ocr=ocr)
reading_fonts = pdf_headings
# The reserve, and the reason it re-extracts rather than post-processes:
# the font reader works on the PDF's glyph geometry, which the joined
# text no longer carries. Skipped outright when the font reader is
@ -1480,6 +1608,18 @@ def run(
if pdf_headings_reserve and not pdf_headings:
if heading_reserve_applies(text, outline_run=outline_run):
text = extract_text(source.name, source_bytes, pdf_headings=True, ocr=ocr)
reading_fonts = True
# LAST, and against the text that is final: a plan indexes one exact
# string, so marks bridged onto the pre-reserve rendering would name
# the right words at the wrong offsets. `reading_fonts` is what the
# reserve may have changed, and the marks follow it.
marks = (
extract_pdf_outline(
source.name, source_bytes, pdf_headings=reading_fonts, ocr=ocr
).marks
if pdf_outline
else ()
)
except IngestError as exc:
raise ProposerError(f"cannot extract text from {source.name}: {exc}") from exc
@ -1502,6 +1642,7 @@ def run(
close_span_gaps=close_span_gaps,
contents_name=contents_name,
bold_title=bold_title,
outline_marks=marks,
)
# Nothing to propose is an OUTCOME, and it is not an artifact. An empty
# plan cannot be replayed -- `process_inbox` refuses one, because a plan