Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewichad3fa2bdacb1
diff --git a/MARKDOWN_PROGRESS.md b/MARKDOWN_PROGRESS.md
index 1488435..a8eab07 100644
--- a/MARKDOWN_PROGRESS.md
+++ b/MARKDOWN_PROGRESS.md
@@ -2,6 +2,246 @@
Tracks build-order progress against [MARKDOWN_PLAN.md](MARKDOWN_PLAN.md). Update as steps complete.
+> **2026-06-04 description-list 2-col table detector — opendataloader TEDS 0.5527 → 0.6028 (+0.050), Overall 0.7953 → 0.8000 (+0.005); olmOCR-bench table_tests 35.8% → 38.8% (+3.0pp, +31 tests), Overall 34.7% → 35.2%; ParseBench unchanged.** Targeted the 9 opendataloader docs at TEDS=0 — borderless 2-column "label | description" tables that the existing `try_detect_table` rejected because `TABLE_MIN_COLUMNS = 3`. Five of the nine zeros (132 species, 146 framework, 150 competence, 166 CEC, 197 task names) have this shape; 110 is OCR-gated, 121/122 are upstream PDFium item-order garble, 165 is a sparse fill-in worksheet with one-cell body rows.
+>
+> **New `try_detect_description_list` (`markdown_layout/tables.rs`).** Runs after `try_detect_table` in the `detect_tables` loop. Conditions:
+> 1. **Layout shape**: exactly 2 cells, stable col-0 / col-1 anchors (±`DESC_LIST_TRACK_TOL_PT = 8pt`), inter-column gap ≥ `DESC_LIST_MIN_COL_GAP_PT = 12pt`.
+> 2. **Col-0 label discriminator (`is_label_like`)**: 1-4 words, ≤40 chars, no internal `". X"` sentence boundary, not a pure bullet glyph (`•`, `●`, `*`, `-`, `‣`, `⮚`, …), not a list marker (`1.`, `(1)`, `i.`, `IV.`). Filters bulleted lists (doc 056 biomass categories) and prose-mid-sentence false positives.
+> 3. **≥2 real 2-cell rows** (`real_two_cell_rows`). A run extended *only* via the merged-span split path almost always slices body prose where a heading like `7 Variants of sj Observer Models` happens to have a tab-stopped section number — that anchored a fake table on docs 001-014 in the first cut. Real description-list tables have ≥2 baselines where PDFium emitted two distinct spans.
+> 4. **Cadence OR asymmetry**: ≥3 rows OR one row's col 1 is ≥ 2× col 0. A single 2-row pair of symmetric short cells is too close to projection-merged adjacent-column text.
+> 5. **At least one alpha+alpha row**: filters footnote lists where col 0 is always a digit (doc 008's `25 | Wiliam Beckford, …`).
+> 6. **Not all-page-ref**: `is_page_ref` rejects runs where every col 1 is a digit or roman numeral (doc 171/016 TOC entries). Required because TOC items like `Acknowledgments | vii` pass the alpha+alpha check (`vii` is alphabetic).
+> 7. **Caption guard**: `looks_like_caption` breaks the run before a line beginning `Figure N` / `Table N` (doc 132's `Table 6.1: Four fish species…` was being whitespace-split into a bogus row in v1). Combined with a **cadence guard** (next y-gap > 1.6× the run's max prior gap) so the visually-detached caption never gets absorbed.
+>
+> **PDFium tight-kerning recovery (`split_merged_at_anchor`).** Doc 132's middle rows (`La Palma Pupfish Cyprinodon longidorsalis` / `Butterfly Splitfin Ameca splendens`) emit as a single PDFium text item spanning both columns — kerning between col-0 end and col-1 start is tighter than the gap threshold. When a 1-cell line sits at col-0's anchor and extends past col-1's anchor (`end_x > col1_x + tol`), split on the whitespace position whose linear x-estimate is closest to col-1's anchor. Recovered cells must themselves be label-like to be accepted (prevents lossy splits of prose body lines that happen to straddle).
+>
+> **Per-doc deltas on opendataloader-bench**: doc 132 0.000 → 0.867 (+0.867), doc 166 0.000 → 0.849 (+0.849), doc 150 0.000 → 0.387 (+0.387). Zero regressions ≤ -0.03 across all 200 docs. Aggregate: NID 0.8807 → 0.8808, TEDS 0.5527 → **0.6028**, MHS 0.6275 → **0.6307**, Overall 0.7953 → **0.8000**.
+>
+> **olmOCR-bench delta**: table_tests 35.8% (366/1022) → 38.8% (397/1022). Multi-column / headers_footers / long_tiny_text / baseline all held. The +31 tests are mostly borderless 2-col definition/glossary shapes in `table_tests.jsonl` that the column-alignment detector previously skipped.
+>
+> **Why ParseBench was byte-identical**: its `table` evaluator scores GriTS + Table Record Match on multi-column enterprise tables (financial statements, insurance forms, government reports). Description-list shape doesn't match the eval's expected output structure, so the detector firing or not firing on those PDFs doesn't change the metric.
+>
+> **Remaining TEDS=0 docs (4 of original 9)**: 110 (OCR-gated — table is a raster image, no text extraction possible), 121/122 (PDFium item-order garbled — `extract.rs` / projection issue, not classifier), 165 (sparse fill-in worksheet: every body row has only the col-0 label cell populated, right cells blank — the `cells.len() == 2` guard rejects all body rows; would need a "label-column spine" bypass like ruled-table sparse handling but for borderless). Plus 146/197 still TEDS=0 — 146's "Area | Competence" table has col-1 anchor that drifts between rows because of bullet indenting; 197 is a 1-column list rendered as a 1-col table in GT, different shape entirely.
+>
+> 168 lib tests still pass; no new tests added yet (will follow up with unit tests covering the 132 merged-span case, the 150 paragraph-cell wrap, the 001 false-positive guard, and the 171 TOC filter).
+
+> **2026-06-03 heading/caption shredding — olmOCR-bench multi_column 48.4% → 49.5% (+1.1, ~+10 tests), order pass-rate 40.3% → 41.3%, overall 34.6% → 34.8%.** Targeted the `heading/caption shredding 72` sub-bucket left after the spanning-line fix. Two distinct sub-causes, two fixes:
+>
+> **(a) body-size mis-detection (`compute_body_size`, `headings.rs`).** `compute_body_size` char-weights font sizes and picks the single mode. On dense pages where a small-print block (references / acknowledgments) out-weighs the narrative by raw char count, the mode lands on the *small* size, so all real body prose measures *above* body and every line is promoted to `##`. Example: `multi_column/02e31…page_5` has ~60 lines at 7pt (refs: "We are grateful to Trevor Ireland…", "Armstrong, J.T. (1988)…") vs ~58 lines at 9pt body; char-weighting picked 7pt. **Fix:** added `BODY_CODOMINANT_FRACTION = 0.5` — instead of the single mode, take the *largest* size whose char-weight is ≥ 50% of the top weight. The 9pt narrative now wins (or ties) and stays body. Verified `test_heading_and_paragraph` still holds (body 10pt, title 18pt: 18pt weight far under 50%, doesn't qualify).
+>
+> **(b) caption shredding (`classify.rs`).** Photo captions set one size above body (e.g. 15pt over 11pt body in `multi_column/0b045…page_18`: "ABOVE: Maj Gen Michael Ramantswana, Chief / Military Policy, Strategy and Planning, laid a / wreath on behalf of…") are genuinely heading-sized, so each *wrapped* line became its own `###` block — a 4-line caption shredded into 4 headings. **Fix:** a heading-emit branch now merges a wrapped continuation into the heading directly above when (1) same level, (2) the heading is still `blocks.last()` (adjacency — never reaches across an intervening block), and (3) `continues_paragraph(prev, line)`. A real section heading is followed by body text, which breaks the run; only a genuinely multi-line heading/caption merges. Joined via the existing `append_inline_continuation` (de-hyphenates). New `heading_run: Option<(u8, ProjectedLine)>` state. Bonus: legitimate 2-line wrapped *titles* now also collapse to one heading instead of two. The caption now emits as one `### ABOVE: Maj Gen … laid a wreath on behalf of the Chief of the SANDF, Gen Solly Shoke.`
+>
+> **Bench (1403 PDFs, no OCR): multi_column 428→438/884, order 40.3%→41.3%, overall 34.6%→34.8%, no regressions** (baseline 100%, table_tests 35.8%, headers_footers 58.6%, long_tiny_text 21.0%, old_scans 13.3% all held). 168 lib tests pass. **Remaining multi_column both_missing levers:** the OCR-gated 43 (image-only PDFs, need OCR pass) and garbled-extraction 18.
+>
+> **2026-06-03 spanning-line H-cut rescue — olmOCR-bench multi_column 44.3% → 48.4% (+4.1, +36 tests), overall 34.1% → 34.6%.** Targeted the dominant multi_column failure: `both_missing` order tests (269 of 492 failures). Triage of that bucket: **interleaving 136** (XY-cut never split the columns, reading order zigzags col1+col2 line-by-line), **heading/caption shredding 72**, image-only/OCR-gated 43, garbled-extraction 18. This entry fixes the interleaving 136.
+>
+> **Root cause.** On 2-column papers a *centered full-width line* (authors / affiliation) sits above the body inside one region leaf. Its x-extent straddles the gutter, so the density V-cut sees no valley and can't split the columns; `build_projected_lines` then merges col1+col2 on shared baselines (e.g. "Abstract—This paper considers the problem of designing **surface in the presence of bounded** …"). The H-cut that would *peel* the spanning line exists, but `xy_cut_rec`'s `XY_MIN_LINES_PER_H_SIDE` guard rejects it because the spanning line is a single line, and the depth-0 banner bypass doesn't apply mid-recursion. Critically, the spanning line is often *just under* the 60% banner-width threshold (the IEEE authors line measured 290pt vs a 303pt threshold), so it's not even classified as a banner — the peeling H-cut has a **finite** density score.
+>
+> **Fix (`projection.rs`).** Added a `spanning_rescue` branch to the min-lines guard in `xy_cut_rec`: when one side of an H-cut is a single line (`thin`) and the other side (`wide`) genuinely splits into columns (`column_cut_x` — density V-cut OR `xy_find_column_cut` histogram returns a gutter x), AND the thin line's x-extent *crosses* that gutter, allow the cut despite the min-lines guard. The "thin line crosses the gutter" test is the discriminator that distinguishes a column-straddling banner (peel it) from a single-column caption in running prose (leave it) — a caption sitting inside one column never crosses the revealed gutter. Not gated on infinite banner score, so it catches the sub-banner-width case. New helpers `column_cut_x` (returns the gutter position) and `x_extent`. 2 new unit tests (`spanning_line_above_columns_is_peeled_to_reveal_gutter`, `single_column_caption_is_not_peeled_into_columns`); 168 lib tests pass.
+>
+> **Verified on `multi_column/0c6c8f76…page_1` (IEEE 2-col paper):** before, the entire body was one region leaf `[1,1]` with every line reading col1+col2 interleaved; after, the recursion peels the authors line at depth 2 then V-cuts the body into two column leaves at depth 3, and the Introduction reads as contiguous prose ("In continuous time, a sliding mode is generated by means of discontinuities in the control signals about a surface in the state space [27]…" — the bench's `before` string). **Bench (1403 PDFs, no OCR): multi_column 392→428/884, order pass-rate 36.9%→40.3%, no regressions** (table_tests 364→366, headers_footers 445, long_tiny_text 92, old_scans 70, baseline 100% all held). **Remaining multi_column both_missing levers:** heading/caption shredding (72, classify layer — captions like "ABOVE: …" promoted to `###` and block-split), then the OCR-gated 43.
+>
+> **2026-06-03 estimated-font-size heading guard — olmOCR-bench multi_column 43.4% → 44.3% (+0.9, +8 tests), overall 34.0% → 34.1%.** Targeted the multi_column "text missing" cluster (both_missing 274, before_missing 117, after_missing 106). Root cause was `dominant_font_size` bbox-height jitter: when PDFium bakes the font size into the text matrix (Tf operator reports ~1.0), `build_projected_lines` falls back to char-weighted `bbox.height`, which jitters a point or two line-to-line on the *same* body paragraph (9.0 vs 10.0). That jitter manufactured a bogus heading level in `build_heading_map`, which shredded body paragraphs into per-line `####` headings and blocked de-hyphenation, so the bench's contiguous `before`/`after` strings never matched.
+>
+> **Two-part fix.** (a) **`font_size_is_estimated` flag** (`types.rs` + `projection.rs`): the height-fallback path now tags the line so downstream code knows the size is approximate. `build_heading_map` (`headings.rs`) uses a wider margin over body for estimated sizes (`ESTIMATED_HEADING_SIZE_MARGIN = 1.5pt`) vs the tight `HEADING_SIZE_EPSILON` for real Tf-reported sizes — a 1pt height wobble no longer clears the bar. (b) **continuation+lowercase guard** (`classify.rs`): font-size heading promotion is suppressed when the line starts lowercase AND `continues_paragraph(prev, line)` holds, so a wrapped body line that happens to measure a hair taller can't become a heading mid-paragraph. Real headings (larger by a clear margin, or not mid-paragraph) survive both guards.
+>
+> **Verified on `multi_column/09f90a8fad0997f7cf454cbcbe79cab3bc0f_page_1_pg1.pdf`:** paragraphs now read as coherent prose ("Textual Question Answering (Q/A) aims at identifying the answer of a question in large collections…" — the bench's exact `before` string) with de-hyphenation restored and `####` shredding gone, while real headings (`# Experiments…`, `### 1 Background`, `### 2 The NLP Techniques`) are preserved. **Bench (1403 PDFs, no OCR): multi_column 384→392/884, no regressions elsewhere** (table_tests 364, headers_footers 445, long_tiny_text 92, baseline 100% all held). Overall moves only +0.1 because multi_column is one of 8 per-JSONL categories and the big residual buckets (math 0% — no LaTeX emission; old_scans/long_tiny_text — OCR-gated image-only PDFs) are untouched by this layout fix. 166 lib tests pass. Also dropped an unused `mut` warning in `tables.rs:591` that surfaced during the rebuild.
+>
+> **2026-06-03 absorb_header_lines relaxation attempt — reverted (small regression).** Tried two extensions of `absorb_header_lines` to chase the `fa18a15c` NASS-style multi-level header that Step 1's merge couldn't fully reach. (a) When a candidate header row has `cells.len() > column_count` (e.g. an embedded `|` token splits off as an extra cell), filter to the subset whose centers map to distinct body tracks and accept if `>= 2` survive. Direct unit tests on `absorb_header_lines` pass — the filter correctly drops the off-track `|` and absorbs the remaining 3 cells. **Bench regressed by 2 tests** (table_tests 364 → 362). The real-world failure mode: some PDFs have a "wider" line above the body whose 4-5 cells happen to align to 3 body tracks but is actually prose / a different table fragment / a sub-title, and folding it as a header changes downstream cell relationships. Reverted. (b) Allow single-cell header absorption when the cell maps to a track (the "Item" col-0 header case). Broke the pre-existing `does_not_absorb_single_cell_title_above_body` test — page titles like `"Results"` above a body where the body's track 0 sits at the same x as the title would get folded as a header. Reverted. The fundamental problem: the lines above a body table look statistically very similar to legitimate single-cell column headers vs page titles / prose / unrelated content — no robust heuristic. **Conclusion: header-absorption alone can't bridge the multi-level-header case** because the date row above the `(percent)`/`2011` chain in `fa18a15c` is in a *different XY-cut leaf* (the body's region and the title-area region were split early in projection), so absorption can't even reach it sequentially.
+>
+> **Next leverage candidates** (changed from prior pass):
+> 1. **B2 vertical wrapped-row split** — `recover_merged_cell`'s vertical analog for the Apple-earnings `Q3 | $448 $427 7% | 5%` case (3 cells where 5 expected, because PDFium merged 3 stacked baselines into one span). Detection: cells whose text contains internal baseline-gap signatures, OR cells whose width / token-count ratio is much higher than peers in the same column.
+> 2. **Description-list → 2-col table** — `af3fd8e2…pg15` (`Option Description` header + `**Term**` body + paragraph) shape. Detection: consecutive lines where col 0 is short + bold + indent-stable and col 1 is a paragraph at a stable x0. Lower architectural risk; targets the no_table_cell_in_text bucket (154 tests).
+> 3. **Region-aware header absorption** — let `absorb_header_lines` walk past a layout-boundary line if the line above it (in projection y-order, ignoring region) aligns to body tracks. Higher risk but the only way to bridge the date-row case in `fa18a15c`.
+>
+> **2026-06-03 cross-run table merging — bench-neutral but structural cleanup.** Added `merge_consecutive_table_runs` post-pass to `detect_tables` in `markdown_layout/tables.rs`. Targets the dominant table_test failure bucket (~252 wrong_neighbors out of 589 non-image table failures): when `try_detect_table` breaks the run at a column-count change, the adjacent runs are merged in two cases. **Case Same**: identical column count + per-column track centers within `TABLE_TRACK_TOLERANCE_PT` → concat rows, keep A's header. **Case Subset**: `|A| + 1 == |B|` and A's tracks are a column-subset of B's tracks under a looser `TABLE_SUBSET_TRACK_TOLERANCE_PT = 12pt` (header cells often have different content widths than body cells) → fold A as B's header layers, joined per-column top-to-bottom with adjacent-dedup, padded with empty at the missing B-column index. Tries every possible "skip one B column" assignment and picks the lowest-total-error mapping; uses min(start_diff, end_diff, interior-half center-in-range) as the per-column score so a narrow header sitting at the edge of a wide row-label cell doesn't spuriously match. Allows up to 1 interstitial "absorbable" line between A.end and B.start (single-cell label, ≤60 chars, not ending in sentence punctuation) — preserved as a body row in col 0 of the merged table so no content is lost. Track derivation in `run_body_tracks` aggregates min/max across all body rows so tight numeric per-row cells still produce track ranges wide enough to match wider headers. Guarded by `TABLE_HEADER_MAX_ABSORB_ROWS = 3` (don't fold a real 5-row table as a header), `TABLE_MERGE_MAX_Y_GAP_LINES = 2.0` (visually distinct tables don't merge), and "don't merge two complete-looking tables across a gap" for Case Same. 7 new tests cover the matrix (same-cols, subset, distant, large-prior, 2-col-diff, GridFallback-untouched, multi-cell interstitial reject, absorbable interstitial as body row). 166 lib + 10 integration tests pass.
+>
+> **Smoke result on `fa18a15c1dbbfcb71b1f1ea1b8f116e24b8a_pg2_pg1.pdf` (NASS crop weather):** confirmed the merge fires — 4-col `2011×4` + `(percent)×4` header table previously emitted standalone is now folded into the 5-col body table as a composite header `| | 2011 (percent) | 2011 (percent) | 2010 (percent) | Average (percent) |` with `Topsoil` preserved as the next body row.
+>
+> **Bench result on olmOCR-bench (1403 PDFs, no OCR): table_tests unchanged at 35.6% (364/1022).** Compared identical builds with merge enabled vs disabled (LITEPARSE_DISABLE_MERGE env flag, since removed). Per-category: every category byte-identical. The merge is correct and fires on the targeted layouts but doesn't flip any test predicates because the bench's `top_heading`/`left_heading`/`right`/`up`/`down` lookups need a *full* multi-level header. On `fa18a15c`, the column-header chain in the source is *3 lines* (`Aug 21,`/`Aug 14,`/`Aug 21,`/`2006-2010` → `2011`/`2011`/`2010`/`Average` → `(percent)×4`), my merge folds 2 of them; the topmost date row sits above the first detected run and is rejected by `absorb_header_lines` (it splits to 5 cells because of an embedded `|` token, exceeding the 4-col body's column count). The bench expects `top_heading='Aug 21, 2011'` but gets `top_heading='2011 (percent)'` — failure reasons changed but pass/fail did not. Same pattern across other wrong_neighbors PDFs sampled. Kept the merge: zero regressions, fires correctly on targeted layouts, the rendered tables ARE structurally cleaner (one table instead of fragmented two), and the infrastructure (`subset_mapping`, `run_body_tracks`, `is_absorbable_interstitial`) is reusable when we tackle multi-level header absorption next.
+>
+> **What would actually move table_tests** (deferred):
+> 1. **Upward header extension past `absorb_header_lines`'s break.** Today the function bails on the first line that has `cells.len() > column_count` or doesn't align all-tracks. The date row case has 5 cells (one extra from an embedded `|` token) so it bails. Need either (a) tolerance for "all cells except 1 align" — same `misaligned <= 1` slack the body-row loop already allows, OR (b) a `recover_merged_cell`-style split-on-whitespace for header rows that have more cells than expected. Plausibly +30–60 wrong_neighbors.
+> 2. **B2 wrapped-row split (vertical analog of `recover_merged_cell`)** — `a769f9a3…pg2` (Apple earnings) has `Q3 | $448 $427 7% | 5%` because PDFium merged 3 baselines into one span. Symmetric to lateral-merge recovery but harder to detect: need a "this cell has visible internal baseline boundaries" signal. Plausibly +40–80 wrong_neighbors.
+> 3. **Description-list / definition-list as 2-col table** — `af3fd8e2…pg15` shape: `**Term**` (bold prefix at col-0 anchor) + paragraph at col-1 anchor → 2-col table. ~30–50 no_table_cell_in_text. Cheapest of the three.
+>
+> **2026-06-03 single-page chrome detector — olmOCR-bench headers_footers 38.9% → 58.6% (+19.7), overall 31.2% → 34.0% (+2.8).** The existing `compute_header_footer_set` is structurally inadequate on the bench's single-page inputs — cross-page repetition can't fire when there's only one page. Added a complementary single-page detector in `markdown_layout/repetition.rs::detect_single_page_chrome(page, body_size) -> HashSet<line_idx>` that runs *additively* alongside the cross-page set. Wired through `format_markdown` → `classify_page_with_filters` as a 6th param so the filter step strips both cross-page-matched lines AND per-page chrome before table detection / heading promotion runs.
+>
+> **Detection signal:** position band (top 15% OR bottom 15% of page) + isolation gap (≥ 1.0 × body_size to the nearest non-chrome-pattern neighbor in y-order) + chrome pattern signature. Patterns covered in `matches_chrome_pattern`: URL/DOI prefixes (`http://`, `https://`, `www.`, `doi:`, `doi.org/`, `dx.doi.org`), journal banner phrases (`please cite this article`, `contents lists available at`, `available online at`, `downloaded from`), copyright (`©`, `copyright `, `all rights reserved`), `Page N`/`Page N of M`/lone-digit page numbers (≤4 digits), `Vol.`/`Vol`/`Vol,` + digit (ASCII byte-scan, not regex), and journal-cite-style (4-digit year `19xx`/`20xx` + numeric `N-M` / `N–M` / `N—M` page range + ≤120 chars). 200-char ceiling on candidate strip so a body paragraph that happens to start with a URL isn't nuked. No regex dep — manual char/byte scans (one bug found and fixed during dev: byte-indexing into `&lower[i..]` panics on non-ASCII `–` in `Cell Chemical Biology 24, 1–9, …` — replaced with explicit ASCII-byte check).
+>
+> **Crucial isolation refinement:** the first attempt filtered isolation-neighbor candidates by "must be outside the position band," which made tightly-stacked top text always-isolated (no out-of-band neighbor exists). Real body chrome would then strip even when followed immediately by body content. Fix: filter by "must not match a chrome pattern itself," so multi-line chrome groups (e.g. `Please cite this article in press as: ... \n Cell Chemical Biology (2017), http://dx.doi.org/...`) are treated as one unit (both lines pattern-match), and isolation is measured against the first non-chrome body line. False-positive guard: required the pattern hint as a hard gate — initially also accepted a font-size delta from body, but dropped that because real headings/titles routinely satisfy it, and the bench has too many "preserve the title" cases to risk it.
+>
+> **Bench result (1403 PDFs, no OCR):**
+>
+> | Category | Pre | Post | Δ |
+> |---|---|---|---|
+> | **Overall** | 31.2% ± 0.9% | **34.0% ± 0.9%** | **+2.8** |
+> | headers_footers | 38.9% | **58.6%** | **+19.7** |
+> | table_tests | 32.3% | 35.6% | +3.3 |
+> | multi_column | 43.2% | 43.4% | +0.2 |
+> | long_tiny_text | 21.9% | 20.8% | -1.1 (noise on 442-test category) |
+> | baseline | 100.0% | 100.0% | 0 |
+>
+> The +3.3 bonus on `table_tests` is the indirect win — running header/footer chrome was previously being absorbed as fake H3 headings above tables, fragmenting them or polluting cell context. Stripping it leaves cleaner table boundaries.
+>
+> **Why the unlock is smaller than the failure-triage projection (~98% of `headers_footers`).** The triage observed "98% of failures are emitted_verbatim chrome" — meaning the chrome was present in output, not that the chrome was *pattern-matchable*. Post-fix `emitted_verbatim` still owns 97.8% of the residual 315 failures (308 cases). Two families fall through the pattern catalog:
+> 1. **Letterhead / institutional disclaimers as prose** — e.g. `Este documento será custodiado por la Agencia de Tecnología y Certificación Electrónica - ISTEC Pista de Ademuz S/N. 46100 Burjassot (Valencia). Tel. 902 482 481 Correo-e: [email protected]`. Plain Spanish prose with embedded phone/email. No URL / DOI / Page-N / journal signature. Pattern catalog miss.
+> 2. **Bold short-line company chrome** — e.g. `MIDWIFERY xxx (xxxx) xxx–xxx` style placeholders, journal letterheads. Some are caught by the journal-cite regex; others aren't.
+>
+> **Next leverage on this category** (deferred — would push 58.6% → ~75-80% but with non-trivial false-positive risk on bench `present` tests):
+> - Tel/email pattern (`\bTel[. :]\s*\d` + `[a-z]+@[a-z]+\.`).
+> - "Bottom-of-page short line + font-size delta from body" — gated on being the very last line in the page band, since real body conclusions usually have follow-on text.
+> - Loosen position band slightly (12% → 18%) to catch banner-style chrome that sits 13-15% from the top.
+>
+> **Tests added** (5 unit tests in `repetition.rs`): `chrome_pattern_recognizes_common_signatures` (URL/`Please cite`/Page N/©/journal-cite all positive; prose / `Acme Annual Report 2023` / `Introduction` all negative), `detects_top_url_chrome_on_single_page`, `detects_bottom_journal_citation_chrome`, `preserves_title_at_top_without_chrome_pattern` (no pattern → no strip, the load-bearing false-positive guard), `chrome_with_no_isolation_gap_is_not_stripped` (URL at top followed by body within 1× body height → no strip). 158 lib + 10 integration tests pass.
+>
+> **2026-06-03 olmOCR-bench baseline + failure triage.** Wired liteparse into `olmocr/bench` via a new `runners/run_liteparse.py` (single-page `target_pages=str(page_num)`, threaded `_pdfium_lock` since PDFium isn't thread-safe under the harness's `ThreadPoolExecutor`). Registered as `liteparse` in `convert.py`. Build/run gotcha: build the wheel from `packages/python/` (`maturin develop --release`), not the raw `crates/liteparse-python` crate — the latter ships only the `_liteparse` extension and the bench's `from liteparse import LiteParse` import fails. Bench harness Python: 3.13 (3.14's argparse rejects `%` in `benchmark.py` help strings). Convert runs at ~158 it/s on 1403 PDFs with `--parallel 1`; higher `--parallel` triggers "PDF error: invalid PDF format" from concurrent PDFium use even with the lock (harness re-instantiates parsers per task).
+>
+> **Headline result (no OCR, baseline markdown emitter):** Overall **20.3% ± 0.8%** (average of per-JSONL).
+>
+> | Category | Pass | Tests |
+> |---|---|---|
+> | baseline | 87.3% | 1394 |
+> | headers_footers | 34.5% | 760 |
+> | long_tiny_text | 16.7% | 442 |
+> | multi_column | 10.2% | 884 |
+> | old_scans | 13.3% | 526 (OCR-gated; ignore for now) |
+> | arxiv_math | 0.0% | 2927 (LaTeX not emitted; ignore) |
+> | old_scans_math | 0.0% | 458 (OCR + LaTeX; ignore) |
+> | table_tests | 0.1% | 1022 |
+>
+> **Failure triage script:** `dataset_eval_utils/olmocr_failure_analysis.py` (replays each test's predicate against the existing `liteparse/<subdir>/<basename>_pg<N>_repeat1.md` outputs, buckets failures with snippets). Skipping math + OCR-only categories, four dominant failure modes account for nearly every miss:
+>
+> 1. **Column interleaving** — touches multi_column (~85% of failures), long_tiny_text (33% — newspaper-style ≥3-col layouts row-merged), and leaks into headers_footers `first_n` window misses. Reproducers: `multi_column/09f90a8fad…_page_1_pg1.md` (2-col paper; "Surprising quality is achieved when several lightweight knowledge-based NLP techniques complement…" — the second half is spliced from col 2 mid-sentence), `long_tiny_text/20_pg42_pg1.md` (Guardian books page, 4 cols interleaved row-wise). Estimated unlock: ~550 tests. Same root cause as the long-tracked `paper.pdf` page-1 banner case and as the opendataloader-bench column-interleaving residual on docs 029/038/039/077/189. **Picking this up first.**
+> 2. **No `\|` markdown table emitted on borderless layouts** — 80% of table_tests failures have the cell text present as space-aligned columns but no pipes/HTML. Estimated unlock: ~800 tests. Highest absolute count but lower architectural value than (1).
+> 3. **75 PDFs produce 0-byte `.md`** — concentrated in long_tiny_text (40.7% of its tests, 180 cases). All `Producer: pypdf`, not encrypted, normal MediaBox. Reproducer: `bench_data/pdfs/long_tiny_text/14a_pg1.pdf`. Likely a content-stream / subset-font edge case in our pdfium-rs path; needs a focused dump. Estimated unlock: ~180 tests.
+> 4. **No header/footer suppression at all** — 98% of headers_footers failures emit the header verbatim at char 0. A repeating-y-band detector (or top/bottom 5–10% strip on the single-page subset) would push headers_footers from 34.5% → ~97% in <100 LOC. Nearly free; deferred only because (1) is more valuable.
+>
+> Baseline category (87.3%) and order tests inside multi_column where columns happen to be single-column-shaped are the only places we're already strong. Math (0%) and old_scans (OCR-gated) deliberately ignored.
+>
+> **2026-06-03 runner bug — was returning projection grid, not markdown (+10.9 overall).** The runner returned `result.pages[0].text`, which is the per-page projection grid (ASCII column layout), not the markdown emitter's output. `result.text` carries the rendered markdown. One-line fix in `runners/run_liteparse.py`: `return result.text`. Re-running convert+benchmark on the same wheel produced the *actual* baseline — and obsoleted the failure analysis above, which had been reading interleaved projection output and concluding "no columns / no tables / 0-byte mds" when the real markdown output had columns serialized, tables emitted with `|` pipes, and content present.
+>
+> | Category | Pre (projection) | Post (markdown) | Δ |
+> |---|---|---|---|
+> | Overall | 20.3% ± 0.8% | **31.2% ± 0.9%** | **+10.9** |
+> | baseline | 87.3% | **100.0%** | +12.7 |
+> | headers_footers | 34.5% | 38.9% | +4.4 |
+> | long_tiny_text | 16.7% | 21.9% | +5.2 |
+> | multi_column | 10.2% | **43.2%** | +33.0 |
+> | table_tests | 0.1% | **32.3%** | +32.2 |
+>
+> By test type: `absent` 39.6→43.6, `order` 8.5→**36.0**, `present` 10.3→13.5, `table` 0.0→**32.2**. Baseline at 100% (1394/1394) confirms basic single-column reading works end-to-end. Tables jumping from 0 → 32% confirms the borderless + ruled-grid detectors do fire on this corpus; the remaining 68% is cell-match precision / multi-line headers / sparse forms — the same residuals we've been tracking against opendataloader-bench. Multi-column 43% means XY-cut serializes most 2-column layouts correctly; the remaining 57% is where banner-title / figure-straddle / 3+ column / extreme density cases still trip the recursion.
+>
+> **Real priorities going forward** (post-correction):
+> 1. **headers_footers absent tests** — still only 39%. The repeating-y-band detector (`compute_header_footer_set`) is firing but isn't catching most of these. On single-page bench inputs there's no cross-page repetition to detect, so the existing approach is structurally inadequate here. Needs a single-page heuristic: top/bottom 5–10% band + font-size delta + isolation gap, or a tagged-PDF artifact-role check when struct tree is present.
+> 2. **multi_column 43% → push toward 70%+** — remaining failures cluster on layouts where banner-title detection or figure-rect-as-obstacle don't fully isolate the columns (same family as `paper.pdf` page 1).
+> 3. **table_tests 32% → push toward 60%+** — current detector lands the *shape*; cell matching fails on multi-line headers, merged cells, and sparse forms. Same Pattern B/D residuals as opendataloader-bench.
+> 4. **long_tiny_text 22%** — dense ≥3-column newspaper/dictionary pages. XY-cut conservative thresholds bail on these because density valleys are noisy. Probably needs a separate "tiny-font dense layout" mode or column-histogram fallback tuning.
+> 5. **0-byte MDs are not a liteparse bug — they're image-only scanned PDFs (OCR-gated).** Verified 2026-06-03 — original hypothesis ("content-stream / subset-font edge case in pdfium-rs") was wrong. All 23 zero-byte outputs in `long_tiny_text` (10a/b/c, 14a-e, 15a-e, 16a-c, 17_pg{2,4,17,24,33,34,86}) are single embedded JPEGs with no text objects. `pdftotext` returns 1 byte on every one; `pdfimages -list` shows 1 raster image per page. Same shape across categories: ~13/18 headers_footers, 11/11 multi_column, 12/14 tables, and 98/98 old_scans empties. Deferred until paddleOCR (or another higher-quality engine) is wired up — Tesseract output would tank the `present` tests and isn't worth the integration time now. **The real long_tiny_text residual** beyond these is dense ≥3-column newspaper/dictionary layouts (`11_pg*`, `20_pg42`, etc.) where extraction works but XY-cut bails — same family as the multi_column residual, not a new failure mode. Genuine non-image extraction misses (~5 in headers_footers, 2 in tables) have small but real `pdftotext` output; their content is chrome-shaped (journal banners, "Notes", page numbers) — likely chrome-detector over-strip on pages whose entire content is chrome. Worth a follow-up to confirm.
+
+> **2026-06-02 sparse-new-row path in borderless detector.** Targeted the "first data row gets eaten by the header" failure mode (doc 180, 045, 088/089/090, 127, 083, 084 …). Old logic in `try_detect_table` (`markdown_layout/tables.rs`) only had one branch for partial-cell lines — a wrap-merge that fired any time `centroid_dy ≤ 1.5 × line_height AND all_align_track`. That ate any data row whose cell count was less than the header's into the header itself, fragmenting tables with sparse columns.
+> - **New branch** runs *before* the wrap path: when (a) all cells map to distinct column tracks, (b) `cells.len() >= 2`, and (c) `bottom_gap >= 0.5 × line_height` (clear inter-row spacing, not a stacked continuation), promote the partial line to a new row with empty `TableCell`s at the missing track positions.
+> - **`cells.len() >= 2` is the load-bearing guard.** Without it, single-cell continuations like `"2022"` 5pt below `"1.0 April 30,"` get promoted to standalone rows (gap signal is noisy on a single cell). With it, 1-cell partial lines always fall through to the existing wrap-merge path (which is what we want — those are real continuations). The first attempt without this guard regressed TEDS by 0.04 across docs 130/051/082/090/147; adding it converted the net into +0.049.
+> - **`bottom_gap >= 0.5 × line_height` discriminates "clear new row" from "wrap"** — a wrap typically overlaps the prior baseline (negative gap) or sits within ~0.3 × line_height of it. The 0.5 floor leaves a dead-zone (0.3, 0.5) that falls through to the existing wrap path, which is correct for the in-between cases.
+> - **Wrap path unchanged.** First attempt tightened the wrap path's gap condition simultaneously, which regressed previously-clean tables (doc 130 0.84 → 0.10) because the existing wrap-merge was load-bearing for tightly-stacked multi-line cells. Reverted and reordered — sparse-new-row runs first, wrap path runs second with original conditions.
+>
+> **Bench result on opendataloader-bench (200 docs):**
+>
+> | Metric | Pre-sparse | Post-sparse | Δ |
+> |---|---|---|---|
+> | NID | 0.8848 | **0.8851** | +0.0003 |
+> | TEDS | 0.4905 | **0.5394** | **+0.0489** |
+> | MHS | 0.5911 | 0.5927 | +0.0016 |
+> | Overall | 0.7829 | **0.7874** | +0.0045 |
+>
+> **Per-doc wins (no regressions on the watch list):**
+> - doc 180: 0.000 → 1.000
+> - doc 127: 0.692 → 0.831
+> - doc 083: 0.555 → 0.757
+> - doc 088: 0.278 → 0.437
+> - doc 090: 0.357 → 0.438
+> - doc 089: 0.115 → 0.204
+> - doc 045: 0.784 → 0.892
+> - doc 084: 0.694 → 0.775
+> - doc 128: 0.521 → 0.622
+>
+> **Preserved:** docs 130 / 051 / 052 / 082 stay at their post-Pattern-A values (0.84 / 0.87 / 0.86 / 0.81).
+>
+> **Cumulative session totals on TEDS:** 0.4144 → 0.5394 (+0.125 absolute, +30% relative). NID 0.8820 → 0.8851. Overall 0.7737 → 0.7874.
+>
+> **Hard-won lesson (added to `project_table_detector` memory):** When relaxing a partial-line-row decision, the cell *count* matters more than the cell *position*. Single-cell partial lines are almost always wraps or noise; multi-cell partial lines with distinct-track mapping and clear gap are almost always real sparse rows. Don't tighten an existing working path — *add* a sibling branch that runs first.
+
+> **2026-06-02 hard-reject XY-cuts through obstacles (defensive).** Added `cut_line_passes_through_obstacle` check in `xy_find_best_cut` (`projection.rs`) to complement the existing density-stamping. The hypothesis (and the user's ask): density-stamping makes the recursion *prefer* cuts around obstacles but doesn't *forbid* cuts through them, so a sparsely-filled table's inter-cell gutter could still score best despite obstacle stamping. The check refuses any candidate cut whose midpoint position lands inside an obstacle rect (with 1pt edge tolerance so a cut at an obstacle's edge stays legal — obstacle edges are themselves natural cut lines).
+>
+> **Bench result on opendataloader-bench (200 docs):** identical to the pre-hard-reject run. NID 0.8848 / TEDS 0.4905 / MHS 0.5911 / Overall 0.7829. Zero change.
+>
+> **Why it didn't move the needle on docs 120 / 180 / 150** — these turned out *not* to be XY-cut failures. Dumped projection for both: the table region is already a single leaf with clean row-major lines (doc 120 `region=[1,1]`: `"Normal hemoglobin dissolves in Disk-shaped red blood cells can"`, etc. — one baseline holds two columns of text). The Pattern A obstacle pass was already preventing the column-slice. The real blocker is the **borderless detector**:
+> - Doc 120: ≥3-cell-per-row requirement fails because column 1 (`Normal hemoglobin…`/`2 copies…`/etc.) appears on every other baseline while the wider right column wraps to 2-3 baselines per cell. Most rows show 2 cells.
+> - Doc 180: same shape — `"1.0 April 30, Original"` then `"2022"` on the next baseline. Each logical row spans 2 baselines, and the second baseline has 1-2 cells. The detector closes the run after one row.
+>
+> Kept the hard-reject change anyway as defensive (no regression, principled "never slice through a detected table" guarantee, may matter on docs we haven't seen). The follow-up that *would* move 120/180/150 is **borderless detector multi-baseline row merging** — when a "row" has fewer cells than the established track count but every present cell aligns to a track AND the y-gap to the previous row is ≤ ~1.5× line height, *append* it to the previous row instead of treating it as a row of its own. The 2026-06-01 "wrap merge" change already does something like this for borderless tables but only when the run is *already* a table; it'd need to relax the establishment condition so a run can start from a row that has fewer cells than the final track count.
+
+> **2026-06-02 fill-in-form spine bypass for sparse ruled grids.** Targeted docs 119/120/180/150 where `TABLE_MAX_EMPTY_CELL_FRACTION=0.30` rejects legitimate fill-in-blank forms (comparison charts with a row-label column + header row but mostly empty body cells). The plan-doc note already flagged this; raising the empty-cell ceiling unconditionally backfires (prior attempt regressed TEDS by ~0.09). The fix needed a signature that distinguishes real fill-in forms from decorative wrappers / fragmented borderless tables that the ruled detector would otherwise grab on the relaxation.
+> - **Signature** (`build_ruled_table` in `markdown_layout/tables.rs`): when `empty_frac > 0.30`, accept iff (a) **col 0** is well-populated (`col0_fill ≥ TABLE_SPINE_FILL_FRACTION=0.7`) AND (b) col-0 cells are *short* (`col0_max_chars ≤ TABLE_SPINE_MAX_CELL_CHARS=60`). Real labels are 1-5 words; multi-sentence prose stuffed into a column is the false-positive signature. Hard ceiling at `TABLE_MAX_EMPTY_CELL_FRACTION_WITH_SPINE=0.75` even on bypass — past that, even a strong spine isn't enough.
+> - **Why col 0 only, not row 0?** Tried both. Row-0 bypass passes doc 051's multi-line header (every cell populated by happenstance of header text spanning columns), then the body fragments badly because the cells are filled per x-band — net regression on doc 051 from 0.874 → 0.303. Col-0 label-column signature is far rarer in body prose and far more universal in fill-in forms (every form I checked has col 0 = labels).
+> - **Why area-cap and max-fill-anywhere fell over (intermediate attempts):**
+> - `max_col_fill ≥ 0.7` (any column): fires on doc 130 where the rightmost column has a long prose chunk = 80% col-fill. Dropped 130: 0.840 → 0.103.
+> - + area cap (≤ 0.5 page): trims 130 but the borderless detector still produced a fragmented output that beat the cleaner borderless result via `merge_table_runs`. Net: 130 stayed bad.
+> - col-0 + short-cells together separate the two cases cleanly without needing area or per-doc tuning.
+>
+> **Bench result on opendataloader-bench (200 docs, image_mode=off):**
+>
+> | Metric | Pre-spine | Post-spine | Δ vs pre-spine | Δ vs session start (pre Pattern A) |
+> |---|---|---|---|---|
+> | NID | 0.8845 | **0.8848** | +0.0003 | +0.0028 |
+> | TEDS | 0.4737 | **0.4905** | +0.0168 | **+0.0761** |
+> | MHS | 0.5911 | 0.5911 | 0 | -0.0011 |
+> | Overall | 0.7810 | **0.7829** | +0.0019 | +0.0092 |
+>
+> **Per-doc:** doc 119 0.000 → 0.708 (+0.708). All previously-good docs preserved (130: 0.84, 045: 0.78, 051: 0.87, 052: 0.86, 082: 0.81, 084: 0.69, 047: 0.75, 083: 0.56, 127: 0.69). Net session gain of +0.076 absolute TEDS (~18% relative).
+>
+> **Still TEDS=0 — root cause is upstream of the table detector now:**
+> - **docs 120 / 180 / 150** — same comparison-chart layout as 119. `detect_table_rects` *does* return a candidate rect (cov=0.84×0.49 on doc 120), the obstacle *is* passed to XY-cut, but XY-cut **still slices the table column-wise** and the output shows column-major reading order through the table region. The obstacle is being overridden — likely the inter-column gaps in the table are so dominant in the density projection that even with the obstacle's perpendicular-extent weight stamped in, the gutter still scores best. Worth instrumenting `xy_find_best_cut` on doc 120 specifically and seeing what the density profile looks like with and without the obstacle. Possible fixes: (a) bump figure-obstacle stamp weight when the obstacle is a table-rect specifically, (b) hard-reject any V-cut whose position falls inside an obstacle rect (instead of just biasing density), (c) detect "table-like column stacks" and reject V-cuts that would slice through them.
+> - **doc 121** — different problem entirely. PDFium reports items in a garbled order (item-extraction quirk, not layout). Not a table-detection issue.
+> - **docs 132 / 146 / 166 / 197** — no significant graphics, would need borderless-detector improvements (Pattern B / Pattern D from the earlier audit).
+> - **docs 088 / 089 / 090 / 128 / 182** — multi-line wrapped header collapse (Pattern B). Header absorption pass is the next big lever here (~0.04 TEDS potential).
+>
+> **Hard-won lesson (saved to memory):** Just dropping `TABLE_MAX_EMPTY_CELL_FRACTION` regresses net — the relaxation creates false-positive ruled tables that beat legitimate borderless tables via `merge_table_runs`, fragmenting them. Any bypass needs a *positive* fill-in-form signature, not just a relaxed threshold.
+
+> **2026-06-02 ruled-table-rects as XY-cut obstacles.** Targeted the dominant TEDS=0 failure mode on the bench: XY-cut treating inter-cell gaps inside a ruled table as page-level column gutters, slicing the table into per-column leaves and producing column-major reading order (docs 083, 127, 130, 047, 082, 147 …). Same machinery `figure_cluster::detect_figure_rects` already uses — figures stamped as density obstacles in `xy_find_best_cut` — extended to ruled-grid bboxes.
+> - **New `markdown_layout::detect_table_rects(graphics, page_w, page_h) -> Vec<Rect>`** (`markdown_layout/tables.rs`) — graphics-only sibling of `detect_ruled_tables`. Reuses `extract_h_v_segments` → `cluster_h_segments` → `cluster_v_segments` → `find_grid_components`, but skips the lines-assignment + empty-cell-fraction + header-bold-detection steps and returns the *bbox* of each H/V grid component. Empty-cell filter deliberately omitted: we want the bbox even of sparse forms (doc 119) for obstacle purposes. Only filters: ≥5pt on both axes, and `w/page_w ≥ TABLE_MAX_PAGE_COVERAGE` ∧ `h/page_h ≥ TABLE_MAX_PAGE_COVERAGE` (the page-border guard, same constant as the post-projection detector). Re-exported as `pub(crate) use tables::detect_table_rects;` from `markdown_layout/mod.rs`.
+> - **`projection.rs::to_parsed_pages`** computes `table_rects` alongside the existing `figures`, concatenates into a single `obstacles: Vec<Rect>`, and passes that to `build_projected_lines` (parameter still named `figures` but the call site is the only public interface — the obstacle pipeline doesn't distinguish, all rects stamp density into perpendicular buckets identically).
+> - **No new tests added** — `detect_table_rects` is mechanically a subset of `detect_ruled_tables` which already has 5 tests covering the segment/cluster/component pipeline. 153 lib tests still pass.
+>
+> **Bench result on opendataloader-bench (200 docs, image_mode=off):**
+>
+> | Metric | Pre-fix | Post-fix | Δ |
+> |---|---|---|---|
+> | NID | 0.8820 | **0.8845** | +0.0025 |
+> | TEDS | 0.4144 | **0.4737** | **+0.0593** |
+> | MHS | 0.5922 | 0.5911 | -0.0011 (noise) |
+> | Overall | 0.7737 | **0.7810** | +0.0073 |
+>
+> **Per-doc TEDS wins** (from the prior-pass watch list):
+> - doc 130: 0.000 → 0.840 (+0.840) — the carry-forward "column-major reading order" case
+> - doc 047: 0.086 → 0.750 (+0.664)
+> - doc 127: 0.194 → 0.692 (+0.498)
+> - doc 083: 0.253 → 0.555 (+0.302)
+> - doc 147: 0.000 → 0.124 (+0.124, partial — multi-line header still merges)
+> - doc 082: 0.749 → 0.811 (+0.062)
+>
+> No watch-list regressions.
+>
+> **Still TEDS=0 after this pass** — these don't have ruled grids the segment extractor sees, OR have grids but other failure modes dominate:
+> - docs 119/120/121/180 — pages where every cell is a stroked Rect rather than shared H/V lines; the dump shows 90+ stroke_rects each, so `extract_h_v_segments` *should* be turning each rect into 4 edges and clustering them. Worth instrumenting `detect_table_rects` on doc 119 to see whether the grid component is being built but the bbox not surfacing, or whether the rects are getting filtered by the page-coverage guard.
+> - docs 132/146/150/166/197 — small graphics counts; mostly Pattern B (multi-line wrapped header collapses) territory, not Pattern A.
+> - docs 088/089/090/128/182 — the cluster of multi-line wrapped headers; needs header absorption (walk back from detected body table to grab unaligned header baselines above).
+>
+> **Next leverage candidates** (rough priority):
+> - **Pattern B: multi-line header absorption** — would lift 088/089/090/128/182/166 from ~0.1–0.4 to ~0.7+. The body table now lands cleanly thanks to this pass; the merge logic needs to walk N lines back from the detected table top and absorb any line whose cells fit the established column tracks (or fragments thereof).
+> - **Why don't 119/120/121/180 benefit?** Either (a) per-cell stroked rects aren't producing H/V clusters dense enough to form a component, or (b) the rects exist but they form one ≥95% page-coverage component that gets filtered. Worth a 10-minute debug on doc 119.
+> - **Pattern D: 2-column tables + sparse grids** — once 119 is unblocked by the above, lowering `TABLE_MIN_COLUMNS` to 2 (with a stricter row-count gate) and raising the empty-cell threshold for ruled-grid detection only would pick up docs 132, 146, 150.
+
> **2026-06-01 module split — `markdown_layout.rs` → `markdown_layout/`.** The single 3819-line file got broken up into a directory of focused submodules; pure move-only refactor, no logic changes. New layout: `mod.rs` (24 lines, re-exports the 5 external API symbols + `Block`), `blocks.rs` (347 — `Block`, `render_blocks`, `wrap_emphasis`, `paragraph_from_accum`), `classify.rs` (783 — `classify_page_with_filters`, `classify_page`, `is_rotated_line`, orchestration), `headings.rs` (526 — body-size histogram, heading map, struct/outline level resolution, bold-heading heuristics, caption rejection), `tables.rs` (1118 — borderless + ruled-grid table detection, `escape_table_cell`, `merge_table_runs`), `inline.rs` (319 — `SpanStyle`, emphasis rendering, list-item text), `paragraphs.rs` (214 — `ParaAccum`, `continues_paragraph`, `collapse_whitespace`), `repetition.rs` (170 — running header/footer detection), `hr.rs` (132 — `detect_horizontal_rules`), `lists.rs` (96 — `parse_list_marker`), `tests_common.rs` (202, `#[cfg(test)]` only — shared `line`/`page`/`styled_line` fixtures so per-module test modules don't duplicate them). Visibility: only `build_heading_map`, `classify_page_with_filters`, `compute_body_size`, `compute_header_footer_set`, `render_blocks`, and `Block` are `pub` (re-exported from `mod.rs`); everything else is `pub(super)` within the submodule tree. External consumer (`output/markdown.rs`) and `lib.rs` unchanged. 147 lib tests still pass; `cargo check -p liteparse` clean. Companion plan to also split `projection.rs` (4050 lines) deferred — too load-bearing while heading/layout work is still iterating.
>
> **2026-05-30 rebuild note.** Branch had been cleaned during a branch switch — `markdown_layout.rs` / `output/markdown.rs` were sitting untracked, the supporting types (`ProjectedLine`, `Rect`, `Anchor::Floating`, `ParsedPage.projected_lines`) didn't exist, `OutputFormat::Markdown` wasn't on the enum, and nothing was wired into `lib.rs` / `output/mod.rs`. Restored from `stash@{0}` (which had the plumbing diff) + reimplemented step 2 (`build_projected_lines` in `projection.rs` derives per-line metadata from the projected items). Tests pass; smoke on `paper.pdf` emits headings + bold + page separators end-to-end via `cargo run -p liteparse -- parse <pdf> --format markdown`. Steps 3–6 in the table below are status-accurate again as of this note.
@@ -189,6 +429,17 @@ Steps 1–8 = usable v1. Steps 9–11 = quality bumps for specific doc classes.
> - **MHS** — remaining MHS=0 docs are dominated by 2-column section headings being eaten by adjacent-column body text (docs 7, 13, 38, 77, 118, 148, 177, 178, 189, 198). Same root cause as the long-tracked `paper.pdf` page-1 banner issue: layout decomposition can't isolate single-line bold section heads that sit at the same y-band as content in the other column. Needs the wide-banner / figure-rect-aware XY-cut refinements.
> - **TEDS multi-line header absorption** is the highest-leverage table fix — would lift docs 47, 89, 182, 88, 90 from 0.1–0.4 to ~0.7+. Approach: when ruled-grid detection or borderless detection finds a body table, walk back N lines (where N matches the detected column count's track positions) and check if those upper lines have cells aligning to the same column tracks → absorb as header rows.
+> **2026-06-02 projection layer investigation — height cap, table-blocker categorization.** A diagnostic example `crates/liteparse/examples/dump_projection.rs` was added to compare raw `TextItem` y/x/height/font_size against the projected lines. Used it to characterize where the TEDS=0 docs are actually blocked. The investigation reshaped my earlier intuition that "the projection layer is the bottleneck for tables":
+>
+> - **Doc 132** (2-col simple table): projection gives 5 clean separate lines for the 5 table rows at y=60.4/76.4/92.8/109.1/125.4 — not projection-blocked. Blocker is `TABLE_MIN_COLUMNS=3` rejecting 2-cell rows, then `continues_paragraph` merging the lines.
+> - **Doc 119** (3-col fill-in-blank): projection gives 6 clean lines for the 6 row labels at y=164/211/243/269/296/323 — not projection-blocked. Blocker is `TABLE_MAX_EMPTY_CELL_FRACTION=0.30` rejecting the sparse ruled grid (≈67% empty body).
+> - **Doc 130** (3-col financial): genuinely projection-blocked. XY-cut splits the table into three per-column leaves (`region_path = [1,0,0]`, `[1,0,1,0]`, `[1,0,1,1]`), producing column-major reading order. No table heuristic can fix this without re-assembling rows across leaves.
+> - **Doc 121, 122** (lab worksheets): partly projection-blocked. PDFium reports anomalously large heights (h=50–80pt for ~13pt-tall glyphs — the font's bbox/lineheight got baked into the text-matrix scale). The y-band rule `(y - current_y).abs() < current_h.max(h) * 0.5` then has 25–40pt tolerance, merging distinct baselines.
+>
+> Single-line targeted fix in `projection.rs::build_projected_lines`: clamp item height at 24pt only for the y-banding tolerance computation. The stored `bbox.height` on `ProjectedLine` is unchanged. Bench result on 200 docs: **essentially neutral** (NID 0.8819 → 0.8820, TEDS 0.4144 → 0.4144, MHS 0.5928 → 0.5922, Overall 0.7738 → 0.7737). The cap separates a few previously-merged baselines on docs 121/122 (visible in dumps) but those docs have additional reading-order issues that prevent the recovered baselines from being usable for table detection.
+>
+> **The actual takeaway** for the user's original question: of the 14 TEDS=0 docs, **projection is a real blocker for ~3 of them (130, 121, 122)** and a contributing factor for ~2 more (146 ruled-grid component merging is upstream of build_projected_lines but in `find_grid_components`). The other 9 are markdown_layout heuristic blockers — specifically `TABLE_MIN_COLUMNS` rejecting 2-col tables (132, 165, 166, 150, 121, 197) and `TABLE_MAX_EMPTY_CELL_FRACTION` rejecting sparse ruled grids (119, 146, 180). Two attempts to relax those thresholds in this session (TABLE_MIN_COLUMNS to 2 with guards; TABLE_MAX_EMPTY_CELL_FRACTION to 85% for high-evidence grids) both went net-negative because the relaxation hijacks previously-correct borderless detections — needs an independent cell-content-quality signal (e.g. text x-position matches grid boundaries tightly) before retrying. See the next sub-note for the specific path-dependence.
+>
> **2026-06-02 ruled-grid single-column tables (`tables.rs`).** Targeted the largest TEDS=0 cluster (15 docs with GT tables we emitted 0 columns for). Single-col GT table was 1 doc (149), but the same code path also unblocked thin-border-strip docs whose true content column was wedged between two phantom rule-strip columns. Three coordinated changes in `build_ruled_table`:
>
> - **Threshold relaxation:** `xs.len() >= 3` → `xs.len() >= 2`. Allows the detector to produce 1-column tables when the geometry only gives a single content column between borders.
diff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rs
index fe0ad7a..fafdd3e 100644
--- a/crates/liteparse/src/markdown_layout/classify.rs
+++ b/crates/liteparse/src/markdown_layout/classify.rs
@@ -37,6 +37,7 @@ pub(super) fn classify_page(page: &ParsedPage, heading_map: &[(f32, u8)]) -> Vec
&std::collections::HashSet::new(),
&[],
crate::config::ImageMode::Placeholder,
+ &std::collections::HashSet::new(),
)
}
@@ -54,6 +55,7 @@ pub fn classify_page_with_filters(
header_footer: &std::collections::HashSet<String>,
outline: &[OutlineTarget],
image_mode: crate::config::ImageMode,
+ chrome_indices: &std::collections::HashSet<usize>,
) -> Vec<Block> {
let mut blocks: Vec<Block> = Vec::new();
let mut paragraph: Option<ParaAccum> = None;
@@ -69,6 +71,12 @@ pub fn classify_page_with_filters(
// Most recent ProjectedLine appended to the active list item, for
// gap/font-size checks on continuation lines.
let mut last_list_line: Option<ProjectedLine> = None;
+ // (level, last line) of a heading block currently being accumulated. Lets a
+ // multi-line wrapped heading/caption (e.g. a photo caption set one size
+ // above body) merge into one Heading block instead of shredding into one
+ // `###` per wrapped line. Adjacency is enforced by checking `blocks.last()`,
+ // so this never reaches across an intervening block.
+ let mut heading_run: Option<(u8, ProjectedLine)> = None;
let flush_paragraph = |blocks: &mut Vec<Block>, p: Option<ParaAccum>| {
if let Some(acc) = p
@@ -98,16 +106,20 @@ pub fn classify_page_with_filters(
// Strip running header/footer lines up-front so they don't leak into
// table detection (a repeating two-column footer would otherwise look
// like a 2-row table) or paragraph grouping.
- let filtered_owned: Vec<ProjectedLine> = if header_footer.is_empty() {
+ let need_filter = !header_footer.is_empty() || !chrome_indices.is_empty();
+ let filtered_owned: Vec<ProjectedLine> = if !need_filter {
Vec::new()
} else {
page.projected_lines
.iter()
- .filter(|l| !is_header_or_footer(l, page, header_footer))
- .cloned()
+ .enumerate()
+ .filter(|(idx, l)| {
+ !chrome_indices.contains(idx) && !is_header_or_footer(l, page, header_footer)
+ })
+ .map(|(_, l)| l.clone())
.collect()
};
- let lines: &[ProjectedLine] = if header_footer.is_empty() {
+ let lines: &[ProjectedLine] = if !need_filter {
&page.projected_lines
} else {
&filtered_owned
@@ -353,6 +365,20 @@ pub fn classify_page_with_filters(
} else {
heading_level_for(line.dominant_font_size, heading_map)
};
+ // Guard against height-jitter false headings: a line that flows from
+ // the previous line (same paragraph) AND starts lowercase is a
+ // mid-paragraph continuation, not a heading — even if its
+ // height-estimated size jittered into a heading slot. A real heading
+ // has a break above it and is capitalized, so it won't satisfy both.
+ // Outline / struct-tree levels are explicit and bypass this guard.
+ let size_level = size_level.filter(|_| {
+ let starts_lower = text.chars().next().is_some_and(|c| c.is_lowercase());
+ let prev = paragraph
+ .as_ref()
+ .map(|p| &p.last)
+ .or(last_list_line.as_ref());
+ !(starts_lower && prev.is_some_and(|p| continues_paragraph(p, line)))
+ });
// A standalone "Contents" / "Table of Contents" / "Index" line is
// almost always a real H1, even when `page_is_toc` is false — many
// TOCs list entries without inline trailing page numbers, so the
@@ -368,6 +394,24 @@ pub fn classify_page_with_filters(
.or(toc_title_level)
.map(|l| l.clamp(1, MAX_HEADING_LEVELS as u8));
if let Some(level) = level {
+ // Merge a wrapped continuation into the heading directly above when
+ // it flows as one block: same level, the heading is still the last
+ // emitted block, and the line continues the paragraph. A real
+ // section heading is followed by body text (which breaks the run),
+ // so only a genuinely multi-line heading/caption merges here.
+ if let Some((run_level, run_line)) = heading_run.as_ref()
+ && *run_level == level
+ && continues_paragraph(run_line, line)
+ && let Some(Block::Heading {
+ level: last_level,
+ text: htext,
+ }) = blocks.last_mut()
+ && *last_level == level
+ {
+ append_inline_continuation(htext, text, &collapse_whitespace(text));
+ heading_run = Some((level, line.clone()));
+ continue;
+ }
flush_paragraph(&mut blocks, paragraph.take());
list_base_indent = None;
last_list_item_idx = None;
@@ -376,6 +420,7 @@ pub fn classify_page_with_filters(
level,
text: collapse_whitespace(text),
});
+ heading_run = Some((level, line.clone()));
continue;
}
@@ -722,6 +767,7 @@ mod tests {
&set,
&[],
crate::config::ImageMode::Placeholder,
+ &std::collections::HashSet::new(),
);
let s = render_blocks(&blocks);
assert!(!s.contains("Acme Confidential"), "got: {s}");
diff --git a/crates/liteparse/src/markdown_layout/headings.rs b/crates/liteparse/src/markdown_layout/headings.rs
index 003bf25..4b80be5 100644
--- a/crates/liteparse/src/markdown_layout/headings.rs
+++ b/crates/liteparse/src/markdown_layout/headings.rs
@@ -8,6 +8,16 @@ use super::tables::{TABLE_MIN_COLUMNS, split_cells};
/// Tolerance in points for "is this size larger than the body size".
pub(super) const HEADING_SIZE_EPSILON: f32 = 0.5;
+/// Margin (points) a *height-estimated* size must clear over body before it
+/// counts as a heading size. When PDFium bakes the font size into the text
+/// matrix, `dominant_font_size` falls back to bbox height, which jitters ±1pt
+/// line-to-line (descenders, parens, capitals). The small `HEADING_SIZE_EPSILON`
+/// then admits jittered body lines as a bogus heading level (e.g. 10pt over a
+/// 9pt body), promoting every tall-glyph body line to a heading. Real headings
+/// in these docs are ≥2pt over body, so a wider margin filters the jitter while
+/// keeping genuine headings.
+pub(super) const ESTIMATED_HEADING_SIZE_MARGIN: f32 = 1.5;
+
/// Cap on heading levels (matches plan: H1..H6).
pub(super) const MAX_HEADING_LEVELS: usize = 6;
@@ -391,6 +401,13 @@ pub(super) fn looks_like_numbered_bold_heading(
/// all pages. Rotated lines are excluded so a long rotated sidebar can't
/// pull the body estimate. Falls back to `0.0` when no font-size info is
/// available.
+/// A size whose char-weight is at least this fraction of the top size's weight
+/// is considered a co-dominant body block. When two sizes are co-dominant, the
+/// larger one is the body: dense small-print blocks (references,
+/// acknowledgments, footnotes) routinely out-weigh the main narrative by raw
+/// char count, but the body is never *smaller* than its own footnotes.
+const BODY_CODOMINANT_FRACTION: f32 = 0.5;
+
pub fn compute_body_size(pages: &[ParsedPage]) -> f32 {
use std::collections::HashMap;
let mut weights: HashMap<u32, (f32, usize)> = HashMap::new();
@@ -409,11 +426,19 @@ pub fn compute_body_size(pages: &[ParsedPage]) -> f32 {
entry.1 += chars;
}
}
+ let max_weight = weights.values().map(|(_, n)| *n).max().unwrap_or(0);
+ if max_weight == 0 {
+ return 0.0;
+ }
+ let threshold = (max_weight as f32 * BODY_CODOMINANT_FRACTION) as usize;
+ // Among sizes that are co-dominant with the heaviest size, pick the
+ // largest. This rescues the true body when a dense references/footnote
+ // block at a smaller size would otherwise win the raw char-weight vote.
weights
.values()
- .max_by_key(|(_, n)| *n)
+ .filter(|(_, n)| *n >= threshold)
.map(|(s, _)| *s)
- .unwrap_or(0.0)
+ .fold(0.0_f32, f32::max)
}
/// Minimum total non-whitespace characters across all occurrences at a font
@@ -463,7 +488,12 @@ pub fn build_heading_map(pages: &[ParsedPage], body_size: f32) -> Vec<(f32, u8)>
continue;
}
let size = line.dominant_font_size;
- if size > body_size + HEADING_SIZE_EPSILON {
+ let margin = if line.font_size_is_estimated {
+ ESTIMATED_HEADING_SIZE_MARGIN
+ } else {
+ HEADING_SIZE_EPSILON
+ };
+ if size > body_size + margin {
let key = (size * 100.0).round() as u32;
let entry = sizes.entry(key).or_insert((size, 0, 0, 0));
entry.1 += 1;
diff --git a/crates/liteparse/src/markdown_layout/mod.rs b/crates/liteparse/src/markdown_layout/mod.rs
index 9ccf865..ade82bc 100644
--- a/crates/liteparse/src/markdown_layout/mod.rs
+++ b/crates/liteparse/src/markdown_layout/mod.rs
@@ -18,7 +18,8 @@ mod tables;
pub use blocks::{Block, render_blocks};
pub use classify::classify_page_with_filters;
pub use headings::{build_heading_map, compute_body_size};
-pub use repetition::compute_header_footer_set;
+pub use repetition::{compute_header_footer_set, detect_single_page_chrome};
+pub use tables::detect_table_rects;
#[cfg(test)]
pub(crate) mod test_helpers;
diff --git a/crates/liteparse/src/markdown_layout/repetition.rs b/crates/liteparse/src/markdown_layout/repetition.rs
index 1b8a678..0bf4ca6 100644
--- a/crates/liteparse/src/markdown_layout/repetition.rs
+++ b/crates/liteparse/src/markdown_layout/repetition.rs
@@ -98,6 +98,275 @@ pub fn compute_header_footer_set(pages: &[ParsedPage]) -> std::collections::Hash
set
}
+/// Fraction of page height treated as the top band for the single-page
+/// chrome detector (slightly wider than the cross-page band — single-page
+/// chrome can sit a bit deeper, e.g. a citation block above a paper title).
+const SP_TOP_BAND_FRACTION: f32 = 0.15;
+/// Fraction of page height for the bottom band of the single-page detector.
+const SP_BOTTOM_BAND_FRACTION: f32 = 0.15;
+/// Minimum gap (in multiples of body line height) between candidate chrome
+/// and the rest of the page content. A real header/footer is visually
+/// separated; body lines that happen to sit near the top/bottom are not.
+const SP_ISOLATION_GAP_RATIO: f32 = 1.0;
+/// Font-size delta threshold: lines whose size differs from body by this
+/// fraction (smaller OR larger) are size-suspicious chrome candidates. The
+/// 0.15 floor admits typical 8/9pt chrome on 10pt body and 12+pt banner
+/// chrome on 10pt body without sweeping in sub-headings (which usually
+/// differ by ≥ 25%).
+const SP_FONT_DELTA: f32 = 0.15;
+
+/// Heuristic check: does the line text match a known running-chrome
+/// signature? URLs/DOIs, journal-article preamble ("Please cite this
+/// article…"), `Page N of M`, copyright marks, volume/issue markers, and
+/// journal citation lines (year + page range + ≤ ~120 chars).
+///
+/// Returns true only for unambiguous chrome patterns — false-positive
+/// recall on body prose is the main risk to guard.
+pub(super) fn matches_chrome_pattern(text: &str) -> bool {
+ let t = text.trim();
+ if t.is_empty() {
+ return false;
+ }
+ let lower = t.to_lowercase();
+
+ // URL / DOI prefixes — chrome lines are very often a citation URL.
+ if lower.contains("http://")
+ || lower.contains("https://")
+ || lower.starts_with("www.")
+ || lower.contains(" www.")
+ || lower.contains("doi:")
+ || lower.contains("doi.org/")
+ || lower.contains("dx.doi.org")
+ {
+ return true;
+ }
+
+ // Common journal-paper top-banner phrases.
+ if lower.contains("please cite this article")
+ || lower.contains("contents lists available at")
+ || lower.contains("available online at")
+ || lower.contains("downloaded from")
+ {
+ return true;
+ }
+
+ // Copyright / trademark chrome.
+ if t.contains('©') || lower.contains("copyright ") || lower.contains("all rights reserved")
+ {
+ return true;
+ }
+
+ // "Page N", "Page N of M", standalone page numbers.
+ if let Some(rest) = lower.strip_prefix("page ") {
+ let head: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
+ if !head.is_empty() {
+ return true;
+ }
+ }
+ // Lone page number (≤4 digits, possibly with a leading "p." or similar).
+ if t.chars().all(|c| c.is_ascii_digit()) && t.len() <= 4 {
+ return true;
+ }
+
+ // Volume / Issue markers ("Vol. 24" / "Vol 24" / "No. 3").
+ let lb = lower.as_bytes();
+ for i in 0..lb.len().saturating_sub(4) {
+ // ASCII-only check — safe to byte-index because the prefix we look
+ // for ("vol") is pure ASCII and we test bytes one at a time.
+ let starts_word = i == 0 || !lb[i - 1].is_ascii_alphanumeric();
+ if !starts_word {
+ continue;
+ }
+ if lb[i] == b'v' && lb[i + 1] == b'o' && lb[i + 2] == b'l' {
+ let sep = lb[i + 3];
+ if sep == b'.' || sep == b' ' || sep == b',' {
+ // any digit later in the line is enough
+ if lb[i + 4..].iter().any(|b| b.is_ascii_digit()) {
+ return true;
+ }
+ }
+ }
+ }
+ // Journal-cite-style: contains a 4-digit year (19xx/20xx) AND a numeric
+ // page range (digits[-–]digits) AND short enough to plausibly be chrome.
+ if t.len() <= 120 && has_year(&lower) && has_digit_range(t) {
+ return true;
+ }
+
+ false
+}
+
+fn has_year(lower: &str) -> bool {
+ let bytes = lower.as_bytes();
+ for i in 0..bytes.len().saturating_sub(3) {
+ let starts_word = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
+ if !starts_word {
+ continue;
+ }
+ if (bytes[i] == b'1' && bytes[i + 1] == b'9')
+ || (bytes[i] == b'2' && bytes[i + 1] == b'0')
+ {
+ if bytes[i + 2].is_ascii_digit() && bytes[i + 3].is_ascii_digit() {
+ let ends_word = i + 4 >= bytes.len() || !bytes[i + 4].is_ascii_alphanumeric();
+ if ends_word {
+ return true;
+ }
+ }
+ }
+ }
+ false
+}
+
+fn has_digit_range(t: &str) -> bool {
+ // Look for digit, optional spaces, '-' or '–', optional spaces, digit.
+ let chars: Vec<char> = t.chars().collect();
+ let mut i = 0;
+ while i < chars.len() {
+ if chars[i].is_ascii_digit() {
+ let mut j = i + 1;
+ while j < chars.len() && chars[j].is_ascii_digit() {
+ j += 1;
+ }
+ // Skip optional spaces.
+ let mut k = j;
+ while k < chars.len() && chars[k] == ' ' {
+ k += 1;
+ }
+ if k < chars.len() && (chars[k] == '-' || chars[k] == '–' || chars[k] == '—') {
+ let mut m = k + 1;
+ while m < chars.len() && chars[m] == ' ' {
+ m += 1;
+ }
+ if m < chars.len() && chars[m].is_ascii_digit() {
+ return true;
+ }
+ }
+ i = j;
+ } else {
+ i += 1;
+ }
+ }
+ false
+}
+
+/// Detect running header/footer chrome on a single page using position +
+/// isolation + (pattern hint OR font-size delta from body). Returns the set
+/// of `projected_lines` indices to strip before classification.
+///
+/// Designed to complement `compute_header_footer_set`: the cross-page
+/// detector needs ≥2 pages and matching repetition; this one fires on
+/// single-page docs or on multi-page docs where chrome doesn't repeat
+/// consistently (e.g. per-page citation tags). Conservative by design —
+/// requires a strong signature (pattern OR clear size delta) plus an
+/// isolation gap, so real titles and section headings are preserved.
+pub fn detect_single_page_chrome(
+ page: &ParsedPage,
+ body_size: f32,
+) -> std::collections::HashSet<usize> {
+ use std::collections::HashSet;
+ let mut out: HashSet<usize> = HashSet::new();
+ if page.projected_lines.is_empty() {
+ return out;
+ }
+ let h = page.page_height;
+ if h <= 0.0 {
+ return out;
+ }
+ let top_cutoff = h * SP_TOP_BAND_FRACTION;
+ let bottom_cutoff = h * (1.0 - SP_BOTTOM_BAND_FRACTION);
+ // Use body size as the gap reference when known; otherwise fall back to
+ // the line's own height.
+ let body_gap_ref = if body_size > 0.0 { body_size } else { 0.0 };
+
+ // Cache line top/bottom so isolation checks are straightforward.
+ let tops: Vec<f32> = page.projected_lines.iter().map(|l| l.bbox.y).collect();
+ let bots: Vec<f32> = page
+ .projected_lines
+ .iter()
+ .map(|l| l.bbox.y + l.bbox.height)
+ .collect();
+
+ for (idx, line) in page.projected_lines.iter().enumerate() {
+ let text = line.text.trim();
+ if text.is_empty() {
+ continue;
+ }
+ let in_top = bots[idx] <= top_cutoff;
+ let in_bottom = tops[idx] >= bottom_cutoff;
+ if !(in_top || in_bottom) {
+ continue;
+ }
+
+ // Isolation: gap to the nearest non-band neighbor must be ≥ the
+ // configured ratio of body line height. For a top header we look
+ // *down*; for a bottom footer we look *up*.
+ let gap_ref = if body_gap_ref > 0.0 {
+ body_gap_ref
+ } else {
+ line.bbox.height.max(1.0)
+ };
+ let required_gap = SP_ISOLATION_GAP_RATIO * gap_ref;
+ // Isolation: gap to the nearest neighbor line (by y) on the body
+ // side must be ≥ required_gap. Multi-line chrome counts as one
+ // unit — we check the gap from this group's outer edge to the
+ // nearest *non-chrome-candidate* line. As a simple proxy, look
+ // at the nearest line in y-order whose pattern doesn't match.
+ let isolated = if in_top {
+ page.projected_lines
+ .iter()
+ .enumerate()
+ .filter(|(j, l)| {
+ *j != idx
+ && tops[*j] > bots[idx]
+ && !matches_chrome_pattern(l.text.trim())
+ })
+ .map(|(j, _)| tops[j] - bots[idx])
+ .min_by(|a, b| a.partial_cmp(b).unwrap())
+ .map(|gap| gap >= required_gap)
+ .unwrap_or(true)
+ } else {
+ page.projected_lines
+ .iter()
+ .enumerate()
+ .filter(|(j, l)| {
+ *j != idx
+ && bots[*j] < tops[idx]
+ && !matches_chrome_pattern(l.text.trim())
+ })
+ .map(|(j, _)| tops[idx] - bots[j])
+ .min_by(|a, b| a.partial_cmp(b).unwrap())
+ .map(|gap| gap >= required_gap)
+ .unwrap_or(true)
+ };
+ if !isolated {
+ continue;
+ }
+
+ // Require a chrome pattern signature — drops the false-positive risk
+ // of nuking real titles/headings that happen to sit in the band.
+ // Font-size delta alone is too coarse: section titles routinely
+ // differ from body by ≥15% but are not chrome.
+ if !matches_chrome_pattern(text) {
+ continue;
+ }
+ // SP_FONT_DELTA reserved for a future size-aware pass; keep the
+ // constant so the threshold stays documented.
+ let _ = SP_FONT_DELTA;
+
+ // Length guard: avoid stripping long paragraphs that happen to sit in
+ // the band and start with a URL — chrome lines are short. 200 char
+ // ceiling accommodates the 'Please cite' preamble (often 100-150
+ // chars) without admitting body paragraphs.
+ if text.chars().count() > 200 {
+ continue;
+ }
+
+ out.insert(idx);
+ }
+
+ out
+}
+
/// Returns true if `line` (located on `page`) matches the running
/// header/footer set: the line sits in the top or bottom band AND its
/// normalized text is in `header_footer`.
@@ -167,4 +436,108 @@ mod tests {
// "shared body text" sits mid-page — never matched.
assert!(!set.contains("shared body text"));
}
+
+ // ----- single-page chrome detector tests -----
+
+ use super::super::test_helpers::{line, page};
+
+ #[test]
+ fn chrome_pattern_recognizes_common_signatures() {
+ assert!(matches_chrome_pattern("http://example.com/foo"));
+ assert!(matches_chrome_pattern("www.nature.com/scientificreports/"));
+ assert!(matches_chrome_pattern("Please cite this article in press as: ..."));
+ assert!(matches_chrome_pattern("Page 12 of 24"));
+ assert!(matches_chrome_pattern("9"));
+ assert!(matches_chrome_pattern("© 2023 Acme Corp"));
+ assert!(matches_chrome_pattern(
+ "Cell Chemical Biology 24, 1–9, November 16, 2017"
+ ));
+ // Not chrome
+ assert!(!matches_chrome_pattern(
+ "The quick brown fox jumps over the lazy dog."
+ ));
+ assert!(!matches_chrome_pattern("Introduction"));
+ // Title with year but no range — should not be stripped as chrome.
+ assert!(!matches_chrome_pattern("Acme Annual Report 2023"));
+ }
+
+ #[test]
+ fn detects_top_url_chrome_on_single_page() {
+ // 792pt page; top band = 0..118pt.
+ let lines = vec![
+ // Chrome line at y=20 (in top band)
+ line(
+ "www.nature.com/scientificreports/",
+ 50.0,
+ 20.0,
+ 10.0,
+ 10.0,
+ ),
+ // Body title well below chrome (clear gap)
+ line("Main Body Title", 50.0, 200.0, 14.0, 14.0),
+ line("Body prose line one.", 50.0, 220.0, 10.0, 10.0),
+ line("Body prose line two.", 50.0, 232.0, 10.0, 10.0),
+ ];
+ let p = page(lines);
+ let strip = detect_single_page_chrome(&p, 10.0);
+ assert!(strip.contains(&0), "top-band URL should strip");
+ assert!(!strip.contains(&1));
+ assert!(!strip.contains(&2));
+ }
+
+ #[test]
+ fn detects_bottom_journal_citation_chrome() {
+ let lines = vec![
+ line("Body line.", 50.0, 300.0, 10.0, 10.0),
+ line("More body.", 50.0, 312.0, 10.0, 10.0),
+ // Footer at y=770 (page height 792, bottom band 673..792)
+ line(
+ "Cell Chemical Biology 24, 1–9, November 16, 2017",
+ 50.0,
+ 770.0,
+ 10.0,
+ 10.0,
+ ),
+ ];
+ let p = page(lines);
+ let strip = detect_single_page_chrome(&p, 10.0);
+ assert!(strip.contains(&2), "bottom journal-cite should strip");
+ assert!(!strip.contains(&0));
+ }
+
+ #[test]
+ fn preserves_title_at_top_without_chrome_pattern() {
+ // A document title at the top should NOT be stripped — no pattern
+ // hint AND we no longer fall back on font-size delta.
+ let lines = vec![
+ line("My Important Document", 50.0, 30.0, 18.0, 18.0),
+ line("Author Name", 50.0, 60.0, 10.0, 10.0),
+ line("Body prose here.", 50.0, 200.0, 10.0, 10.0),
+ ];
+ let p = page(lines);
+ let strip = detect_single_page_chrome(&p, 10.0);
+ assert!(
+ strip.is_empty(),
+ "title without chrome pattern must survive, got {:?}",
+ strip
+ );
+ }
+
+ #[test]
+ fn chrome_with_no_isolation_gap_is_not_stripped() {
+ // URL at top followed *immediately* by body — no gap → don't strip.
+ let lines = vec![
+ line("http://example.com/foo", 50.0, 20.0, 10.0, 10.0),
+ // Next line within 1× body size below — no isolation.
+ line("Body line right after.", 50.0, 32.0, 10.0, 10.0),
+ line("Continuing body.", 50.0, 44.0, 10.0, 10.0),
+ ];
+ let p = page(lines);
+ let strip = detect_single_page_chrome(&p, 10.0);
+ assert!(
+ strip.is_empty(),
+ "no isolation gap means it's part of body, got {:?}",
+ strip
+ );
+ }
}
diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rs
index 8506974..0e9f154 100644
--- a/crates/liteparse/src/markdown_layout/tables.rs
+++ b/crates/liteparse/src/markdown_layout/tables.rs
@@ -1,4 +1,4 @@
-use crate::types::{GraphicPrimitive, ProjectedLine, TextItem};
+use crate::types::{GraphicPrimitive, ProjectedLine, Rect, TextItem};
use super::blocks::Block;
use super::inline::is_bold_span;
@@ -18,6 +18,12 @@ const TABLE_CELL_GAP_FONT_MULTIPLIER: f32 = 1.0;
/// track when extending a candidate table run.
const TABLE_TRACK_TOLERANCE_PT: f32 = 6.0;
+/// Floor for the sparse-new-row path: a partial-cell line whose bottom-gap
+/// exceeds this fraction qualifies as a real new row (with empty cells at
+/// missing tracks) instead of being treated as a wrap continuation. Below
+/// this fraction, the existing wrap-merge path runs unchanged.
+const TABLE_SPARSE_ROW_MIN_BOTTOM_GAP_FRAC: f32 = 0.5;
+
/// Maximum vertical gap between consecutive table rows, expressed in multiples
/// of the line height. Looser than the paragraph rule because table rows often
/// have more vertical padding than prose lines.
@@ -277,6 +283,76 @@ fn row_spacing_cv(rows: &[(usize, &ProjectedLine, Vec<TableCell>)]) -> f32 {
var.sqrt() / mean
}
+/// Test whether a candidate cell aligns with the column at index `k` in
+/// `track_ranges`. Track ranges are the `(start_x, end_x)` of the header
+/// (first-row) cell that defined the column. A body cell aligns to column `k`
+/// if any of these hold:
+///
+/// - its centroid sits inside the header cell's x-range (handles centered or
+/// wider body cells like `Offset Binary` under a narrower `OUTPUT FORMAT`);
+/// - its start_x matches the header start_x within tolerance (left alignment);
+/// - its end_x matches the header end_x within tolerance (right alignment).
+///
+/// This is significantly more permissive than the historical pure-start_x
+/// match and recovers tables whose body cells are center- or right-aligned
+/// within the column.
+fn cell_aligns_track(cell: &TableCell, track_range: (f32, f32)) -> bool {
+ let (ts, te) = track_range;
+ let tol = TABLE_TRACK_TOLERANCE_PT;
+ let center = (cell.start_x + cell.end_x) * 0.5;
+ if center >= ts - tol && center <= te + tol {
+ return true;
+ }
+ if (cell.start_x - ts).abs() <= tol {
+ return true;
+ }
+ if (cell.end_x - te).abs() <= tol {
+ return true;
+ }
+ false
+}
+
+/// Pick the best matching column index for `cell`, preferring center
+/// containment, then start_x match, then end_x match. Returns `None` when no
+/// column aligns.
+fn match_track_idx(cell: &TableCell, track_ranges: &[(f32, f32)]) -> Option<usize> {
+ let tol = TABLE_TRACK_TOLERANCE_PT;
+ let center = (cell.start_x + cell.end_x) * 0.5;
+ // Prefer centroid-in-range.
+ if let Some((i, _)) = track_ranges
+ .iter()
+ .enumerate()
+ .filter(|(_, (s, e))| center >= s - tol && center <= e + tol)
+ .min_by(|(_, (s1, e1)), (_, (s2, e2))| {
+ let c1 = (s1 + e1) * 0.5;
+ let c2 = (s2 + e2) * 0.5;
+ (center - c1).abs().total_cmp(&(center - c2).abs())
+ })
+ {
+ return Some(i);
+ }
+ // Fall back to nearest start_x within tolerance.
+ if let Some((i, _)) = track_ranges
+ .iter()
+ .enumerate()
+ .filter(|(_, (s, _))| (cell.start_x - s).abs() <= tol)
+ .min_by(|(_, (s1, _)), (_, (s2, _))| {
+ (cell.start_x - s1).abs().total_cmp(&(cell.start_x - s2).abs())
+ })
+ {
+ return Some(i);
+ }
+ // Fall back to nearest end_x within tolerance (right-aligned cells).
+ track_ranges
+ .iter()
+ .enumerate()
+ .filter(|(_, (_, e))| (cell.end_x - e).abs() <= tol)
+ .min_by(|(_, (_, e1)), (_, (_, e2))| {
+ (cell.end_x - e1).abs().total_cmp(&(cell.end_x - e2).abs())
+ })
+ .map(|(i, _)| i)
+}
+
/// Try to extend a candidate table starting at `start_idx`. On success returns
/// a `TableRun` with `Block::Table` or `Block::GridFallback`; on failure
/// returns `None` (and the caller should fall through to per-line
@@ -291,9 +367,30 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
vec![(start_idx, &lines[start_idx], first_cells.clone())];
let column_count = first_cells.len();
let tracks: Vec<f32> = first_cells.iter().map(|c| c.start_x).collect();
+ let track_ranges: Vec<(f32, f32)> =
+ first_cells.iter().map(|c| (c.start_x, c.end_x)).collect();
+
+ // Right edge of the established column tracks (last track + a track-width
+ // worth of slack). Used to identify lines that sit entirely in a different
+ // page column and should be skipped over rather than breaking the run —
+ // common on two-column pages where the projection interleaves left and
+ // right column lines in y-order.
+ let track_max_x = first_cells
+ .iter()
+ .map(|c| c.end_x.max(c.start_x))
+ .fold(f32::NEG_INFINITY, f32::max);
+ let tracks_right_edge = track_max_x + TABLE_TRACK_TOLERANCE_PT.max(8.0);
let mut j = start_idx + 1;
while j < lines.len() {
+ // Skip lines that sit entirely to the right of the table's column
+ // tracks — almost certainly content from a different page column.
+ // Use the line's leftmost span x; if it's past the table's right edge
+ // we won't break the run, just step over.
+ if lines[j].bbox.x > tracks_right_edge {
+ j += 1;
+ continue;
+ }
if !table_rows_adjacent(rows.last().unwrap().1, &lines[j]) {
break;
}
@@ -308,29 +405,63 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
cells = patched;
}
}
- // Wrapped-continuation merge: a partial-cell line that sits tight
- // beneath (or overlaps) the previous row AND whose cells all align
- // with existing column tracks is a *wrap* of the prior row, not a
- // new row. Common in borderless tables where one column has a
- // multi-line cell while neighbouring columns stay on one line. Merge
- // each wrap cell into its matching track's text rather than
- // breaking the run.
+ // Partial-cell line handling: when a line has *fewer* cells than the
+ // established column count, decide between (a) wrap of prior row's
+ // multi-line cell, (b) sparse new row (some columns just empty),
+ // (c) break-run. Order matters — wrap path first preserves the
+ // original behavior for tightly-stacked continuation baselines; the
+ // sparse-row path only triggers when there's a clear inter-row gap
+ // *AND* every cell maps to a distinct column track.
if cells.len() < column_count && !cells.is_empty() {
- let line_height = lines[j].bbox.height.max(1.0);
- let prev_y_top = rows.last().unwrap().1.bbox.y;
+ let prev_line = rows.last().unwrap().1;
+ let prev_y_top = prev_line.bbox.y;
+ let prev_bottom = prev_line.bbox.y + prev_line.bbox.height;
+ let line_height = prev_line.bbox.height.max(lines[j].bbox.height).max(1.0);
let centroid_dy = lines[j].bbox.y - prev_y_top;
- let all_align_track = cells.iter().all(|c| {
- tracks
+ let bottom_gap = lines[j].bbox.y - prev_bottom;
+ let all_align_track = cells
+ .iter()
+ .all(|c| track_ranges.iter().any(|r| cell_aligns_track(c, *r)));
+ // Sparse-new-row path runs FIRST. When the line sits a clear
+ // inter-row gap below the previous row AND its cells map to
+ // distinct tracks, treat it as a new row with empty cells at
+ // the missing tracks. This catches doc 180's `"1.0 April 30,
+ // Original"` data row following a 5-column header (the older
+ // wrap path used to merge it into the header).
+ if all_align_track
+ && cells.len() >= 2
+ && bottom_gap >= line_height * TABLE_SPARSE_ROW_MIN_BOTTOM_GAP_FRAC
+ {
+ let mapping: Vec<usize> = cells
.iter()
- .any(|t| (c.start_x - *t).abs() <= TABLE_TRACK_TOLERANCE_PT)
- });
+ .map(|c| match_track_idx(c, &track_ranges).unwrap())
+ .collect();
+ let mut distinct = mapping.clone();
+ distinct.sort_unstable();
+ distinct.dedup();
+ if distinct.len() == mapping.len() {
+ let mut padded: Vec<TableCell> = (0..column_count)
+ .map(|i| TableCell {
+ start_x: tracks[i],
+ end_x: tracks[i],
+ text: String::new(),
+ bold: false,
+ })
+ .collect();
+ for (c, &idx) in cells.iter().zip(&mapping) {
+ padded[idx] = c.clone();
+ }
+ rows.push((j, &lines[j], padded));
+ j += 1;
+ continue;
+ }
+ }
+ // Wrap path (existing, unchanged): tight stack against prior
+ // row, multi-line cell continuation.
if centroid_dy <= line_height * 1.5 && all_align_track {
let prev_cells = &mut rows.last_mut().unwrap().2;
for c in &cells {
- if let Some(idx) = tracks
- .iter()
- .position(|t| (c.start_x - *t).abs() <= TABLE_TRACK_TOLERANCE_PT)
- {
+ if let Some(idx) = match_track_idx(c, &track_ranges) {
if !prev_cells[idx].text.is_empty() && !c.text.is_empty() {
prev_cells[idx].text.push(' ');
}
@@ -341,6 +472,23 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
continue;
}
}
+ // If the row has *more* cells than column_count, it likely picked up
+ // content from an adjacent page column that the projection placed on
+ // the same line (e.g. left-table-row + right-column body text). Try
+ // to recover by keeping only the cells whose center lands inside one
+ // of our established column tracks; drop the rest.
+ if cells.len() > column_count {
+ let kept: Vec<TableCell> = cells
+ .iter()
+ .filter(|c| match_track_idx(c, &track_ranges).is_some())
+ .cloned()
+ .collect();
+ if kept.len() == column_count {
+ cells = kept;
+ } else {
+ break;
+ }
+ }
if cells.len() != column_count {
break;
}
@@ -351,8 +499,8 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
// single indented label fragments a 6-row table into three 2-row chunks.
let misaligned = cells
.iter()
- .zip(tracks.iter())
- .filter(|(c, t)| (c.start_x - **t).abs() > TABLE_TRACK_TOLERANCE_PT)
+ .zip(track_ranges.iter())
+ .filter(|(c, r)| !cell_aligns_track(c, **r))
.count();
if misaligned > 1 {
break;
@@ -387,7 +535,7 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
// the same column tracks but weren't includable as body rows (merged /
// partial header cells). Multiple wrapped header lines collapse into one
// markdown header row, joined per-column top-to-bottom.
- let absorbed = absorb_header_lines(lines, start_idx, &tracks, column_count, floor);
+ let absorbed = absorb_header_lines(lines, start_idx, &track_ranges, column_count, floor);
// Promote the first body row to header iff every cell in it is bold
// (matches pymupdf4llm's "bold-or-filled" heuristic; fills require fork
@@ -432,7 +580,7 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
fn absorb_header_lines(
lines: &[ProjectedLine],
start_idx: usize,
- tracks: &[f32],
+ track_ranges: &[(f32, f32)],
column_count: usize,
floor: usize,
) -> Option<(usize, Vec<String>)> {
@@ -441,21 +589,20 @@ fn absorb_header_lines(
while j > floor {
let cand = j - 1;
let cells = split_cells(&lines[cand]);
- // A header line must carry at least two track-aligned cells (a single
- // cell is a title/caption, not a header), no more than column_count,
- // sit tight above the row below it, and have every cell land on a
- // known column track.
- if cells.len() < 2 || cells.len() > column_count {
+ // A header line must carry at least two cells (a single cell is a
+ // title/caption, not a header) and sit tight above the row below it.
+ if cells.len() < 2 {
break;
}
if !table_rows_adjacent(&lines[cand], &lines[j]) {
break;
}
- let all_align = cells.iter().all(|c| {
- tracks
- .iter()
- .any(|t| (c.start_x - *t).abs() <= TABLE_TRACK_TOLERANCE_PT)
- });
+ if cells.len() > column_count {
+ break;
+ }
+ let all_align = cells
+ .iter()
+ .all(|c| track_ranges.iter().any(|r| cell_aligns_track(c, *r)));
if !all_align {
break;
}
@@ -470,15 +617,7 @@ fn absorb_header_lines(
let mut header = vec![String::new(); column_count];
for cells in &absorbed {
for c in cells {
- let Some(idx) = tracks
- .iter()
- .enumerate()
- .filter(|(_, t)| (c.start_x - **t).abs() <= TABLE_TRACK_TOLERANCE_PT)
- .min_by(|(_, a), (_, b)| {
- (c.start_x - **a).abs().total_cmp(&(c.start_x - **b).abs())
- })
- .map(|(i, _)| i)
- else {
+ let Some(idx) = match_track_idx(c, track_ranges) else {
continue;
};
if !header[idx].is_empty() && !c.text.is_empty() {
@@ -502,13 +641,700 @@ pub(super) fn detect_tables(lines: &[ProjectedLine]) -> Vec<TableRun> {
floor = run.end;
i = run.end;
out.push(run);
+ } else if let Some(run) = try_detect_description_list(lines, i) {
+ floor = run.end;
+ i = run.end;
+ out.push(run);
} else {
i += 1;
}
}
+ merge_consecutive_table_runs(out, lines)
+}
+
+// ── Description-list 2-column table detector ──────────────────────────────
+//
+// Catches borderless 2-column tables that the main `try_detect_table` rejects
+// because `TABLE_MIN_COLUMNS = 3`. Signature:
+//
+// - ≥ DESC_LIST_MIN_ROWS rows where col 0 is a short label (≤ DESC_LIST_LABEL_MAX_CHARS)
+// and col 1 is anything (typically a paragraph or bullet list).
+// - Stable x-anchors for both columns (within DESC_LIST_TRACK_TOL_PT).
+// - Clear inter-column gap (col1.start_x - col0.end_x ≥ DESC_LIST_MIN_COL_GAP_PT).
+// - Asymmetric content: at least one row's col 1 is meaningfully longer than
+// its col 0 — rules out symmetric two-column body prose / newspaper layouts.
+//
+// Handles two PDFium quirks:
+// - Wrap continuations: a single-cell line at col 1's anchor extends the
+// previous row's col 1.
+// - Merged-span rows: PDFium occasionally emits both columns of a row as a
+// single text item starting at col 0's anchor (kerning happens to be tight
+// across the column gap). We split on the whitespace position closest to
+// col 1's anchor and treat the result as a normal 2-cell row.
+
+const DESC_LIST_MIN_ROWS: usize = 2;
+const DESC_LIST_LABEL_MAX_CHARS: usize = 40;
+const DESC_LIST_LABEL_MAX_WORDS: usize = 4;
+const DESC_LIST_TRACK_TOL_PT: f32 = 8.0;
+const DESC_LIST_MIN_COL_GAP_PT: f32 = 12.0;
+
+/// Discriminates "label-like" col-0 text from prose fragments. Real
+/// description-list labels are short noun-phrases (1-4 words, no terminal
+/// sentence punctuation, no internal sentence boundary). Body prose that
+/// happens to be projection-merged with a right-column line tends to fail at
+/// least one of these.
+fn is_label_like(text: &str) -> bool {
+ let trimmed = text.trim();
+ if trimmed.is_empty() {
+ return false;
+ }
+ if trimmed.chars().count() > DESC_LIST_LABEL_MAX_CHARS {
+ return false;
+ }
+ // Pure bullet glyph (or bullet+digit like "1.") is not a label — that's a
+ // list item, which the list classifier handles. Lets us avoid claiming
+ // bulleted lists as 2-col description tables.
+ if is_bullet_only(trimmed) {
+ return false;
+ }
+ let word_count = trimmed.split_whitespace().count();
+ if word_count == 0 || word_count > DESC_LIST_LABEL_MAX_WORDS {
+ return false;
+ }
+ // Internal sentence boundary ("foo. Bar") = prose, not a label.
+ // A trailing period is fine ("Item.") and a trailing colon is fine
+ // ("Note:"); both are common in real labels.
+ let bytes = trimmed.as_bytes();
+ for i in 0..bytes.len().saturating_sub(2) {
+ if bytes[i] == b'.' && bytes[i + 1] == b' ' {
+ let next = bytes[i + 2];
+ if next.is_ascii_uppercase() {
+ return false;
+ }
+ }
+ }
+ true
+}
+
+/// Cell text reads as a page number reference: pure digits, pure roman
+/// numerals (i, ii, iv, …, IX, X), or a digit followed by trivial punctuation.
+fn is_page_ref(text: &str) -> bool {
+ let t = text.trim();
+ if t.is_empty() {
+ return false;
+ }
+ if t.chars().all(|c| c.is_ascii_digit()) {
+ return true;
+ }
+ let lower = t.to_ascii_lowercase();
+ if lower.chars().all(|c| matches!(c, 'i' | 'v' | 'x' | 'l' | 'c' | 'd' | 'm')) {
+ // Cap length so multi-word lowercase Latin words don't pass (e.g.
+ // "mix", "civil" would all be made of roman-numeral letters).
+ if t.chars().count() <= 6 {
+ return true;
+ }
+ }
+ false
+}
+
+fn is_bullet_only(text: &str) -> bool {
+ let t = text.trim();
+ if t.is_empty() {
+ return false;
+ }
+ let only_glyph = t.chars().all(|c| {
+ matches!(
+ c,
+ '•' | '●' | '○' | '◦' | '▪' | '■' | '□' | '‣' | '⁃' | '*' | '-' | '–' | '—' | '⮚' | '►' | '▶'
+ )
+ });
+ if only_glyph {
+ return true;
+ }
+ // Numeric list marker: "1.", "1)", "(1)", "i.", "ii." etc. — all are list
+ // markers, not table labels.
+ let chars: Vec<char> = t.chars().collect();
+ let is_paren_num = chars.first() == Some(&'(')
+ && chars.last() == Some(&')')
+ && chars[1..chars.len() - 1].iter().all(|c| c.is_ascii_digit());
+ if is_paren_num && chars.len() <= 5 {
+ return true;
+ }
+ let trailing = chars.last().copied();
+ if matches!(trailing, Some('.') | Some(')')) {
+ let body: String = chars[..chars.len() - 1].iter().collect();
+ if !body.is_empty()
+ && (body.chars().all(|c| c.is_ascii_digit())
+ || body.chars().all(|c| matches!(c, 'i' | 'v' | 'x' | 'I' | 'V' | 'X')))
+ {
+ return true;
+ }
+ }
+ false
+}
+
+/// Heuristic: line text reads like a figure or table caption.
+/// Used to break a description-list run before absorbing a caption that
+/// happens to straddle the table's column anchors.
+fn looks_like_caption(text: &str) -> bool {
+ let trimmed = text.trim_start();
+ let lower = trimmed.to_ascii_lowercase();
+ for prefix in ["figure ", "fig. ", "fig ", "table ", "tab. ", "tab "] {
+ if let Some(rest) = lower.strip_prefix(prefix) {
+ // Require a digit (or roman) right after to avoid matching prose
+ // sentences that happen to start with "Table" / "Figure".
+ if rest.chars().next().is_some_and(|c| c.is_ascii_digit()) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Option<TableRun> {
+ let first = split_cells(&lines[start_idx]);
+ if first.len() != 2 {
+ return None;
+ }
+ let col0_x = first[0].start_x;
+ let col0_end = first[0].end_x;
+ let col1_x = first[1].start_x;
+ if col1_x - col0_end < DESC_LIST_MIN_COL_GAP_PT {
+ return None;
+ }
+ if !is_label_like(&first[0].text) {
+ return None;
+ }
+
+ let mut rows: Vec<(usize, String, String)> = vec![(
+ start_idx,
+ first[0].text.clone(),
+ first[1].text.clone(),
+ )];
+ // Track how many rows came from the *actual* 2-cell path (i.e. PDFium
+ // emitted two distinct spans with a clear gap). The merged-span split path
+ // is a recovery hack for tight-kerning cases — when it's the only thing
+ // extending the run, we're almost certainly slicing prose, not a table.
+ let mut real_two_cell_rows: usize = 1;
+
+ let mut j = start_idx + 1;
+ while j < lines.len() {
+ let prev_line = &lines[rows.last().unwrap().0];
+ if !table_rows_adjacent(prev_line, &lines[j]) {
+ break;
+ }
+ // Caption / divider guard: a line whose text begins with a figure or
+ // table caption marker is never a row in the *current* description
+ // list — it's the caption sitting below it. Stop here rather than
+ // greedily splitting it on whitespace into a bogus row.
+ if looks_like_caption(&lines[j].text) {
+ break;
+ }
+ // Spacing guard: if rows have a clear inter-row cadence and this line
+ // sits markedly farther below than the run's typical row gap, treat
+ // it as a different block (caption / next paragraph) even though
+ // `table_rows_adjacent` is generous up to 2.5× line height.
+ if rows.len() >= 2 {
+ let prev_y = prev_line.bbox.y;
+ let cur_y = lines[j].bbox.y;
+ let cur_gap = cur_y - prev_y;
+ let prior_gaps: Vec<f32> = rows
+ .windows(2)
+ .map(|w| lines[w[1].0].bbox.y - lines[w[0].0].bbox.y)
+ .collect();
+ if let Some(&max_prior) = prior_gaps
+ .iter()
+ .max_by(|a, b| a.total_cmp(b))
+ && cur_gap > max_prior * 1.6
+ && cur_gap > lines[j].bbox.height.max(prev_line.bbox.height)
+ {
+ break;
+ }
+ }
+ let cells = split_cells(&lines[j]);
+ match cells.len() {
+ 2 => {
+ let c0_aligned = (cells[0].start_x - col0_x).abs() <= DESC_LIST_TRACK_TOL_PT;
+ let c1_aligned = (cells[1].start_x - col1_x).abs() <= DESC_LIST_TRACK_TOL_PT;
+ if c0_aligned && c1_aligned && is_label_like(&cells[0].text) {
+ rows.push((j, cells[0].text.clone(), cells[1].text.clone()));
+ real_two_cell_rows += 1;
+ j += 1;
+ continue;
+ }
+ break;
+ }
+ 1 => {
+ let cell = &cells[0];
+ let c0_aligned = (cell.start_x - col0_x).abs() <= DESC_LIST_TRACK_TOL_PT;
+ let c1_aligned = (cell.start_x - col1_x).abs() <= DESC_LIST_TRACK_TOL_PT;
+ if c1_aligned {
+ if !rows.last().unwrap().2.is_empty() {
+ rows.last_mut().unwrap().2.push(' ');
+ }
+ rows.last_mut().unwrap().2.push_str(&cell.text);
+ j += 1;
+ continue;
+ }
+ // Merged-span row: single cell starts at col 0 but extends past
+ // col 1's anchor. Split on the whitespace closest to col 1.
+ let straddles =
+ c0_aligned && cell.end_x > col1_x + DESC_LIST_TRACK_TOL_PT;
+ if straddles {
+ if let Some((left, right)) =
+ split_merged_at_anchor(&cell.text, cell.start_x, cell.end_x, col1_x)
+ && is_label_like(&left)
+ {
+ rows.push((j, left, right));
+ j += 1;
+ continue;
+ }
+ }
+ break;
+ }
+ _ => break,
+ }
+ }
+
+ if rows.len() < DESC_LIST_MIN_ROWS {
+ return None;
+ }
+
+ // Anti-false-positive #1: require ≥2 rows that came from the actual
+ // 2-cell path. A run extended entirely by the merged-span split is almost
+ // certainly slicing body prose where a heading happens to have a section
+ // number cleanly tab-stopped left of the title.
+ if real_two_cell_rows < 2 {
+ return None;
+ }
+ // Anti-false-positive #1b: at least one row must have BOTH columns
+ // containing alphabetic characters. Filters two common shapes that are
+ // *not* description-list tables: TOC entries (col 1 = page number, e.g.
+ // doc 016/171) and footnote lists (col 0 = footnote number, e.g. doc
+ // 008). Real description-list tables have at least one row of
+ // word-on-word.
+ let has_alpha_pair = rows.iter().any(|(_, c0, c1)| {
+ c0.chars().any(|c| c.is_alphabetic()) && c1.chars().any(|c| c.is_alphabetic())
+ });
+ if !has_alpha_pair {
+ return None;
+ }
+ // Anti-false-positive #1c: if *every* col 1 reads as a page-number
+ // (digits or roman numerals), the run is a TOC. TOCs match the alpha
+ // pair check only when one of the page refs happens to be a roman
+ // numeral like "v" or "vi" alongside an alpha col 0.
+ let all_page_refs = rows
+ .iter()
+ .all(|(_, _, c1)| is_page_ref(c1));
+ if all_page_refs {
+ return None;
+ }
+ // Anti-false-positive #2: at least one of
+ // (a) ≥3 rows (cadence is the signal — short symmetric pairs that
+ // repeat 3+ times are tabular),
+ // (b) one row's col 1 is substantially longer than col 0 (paragraph
+ // cell next to a label cell — the classic description-list shape).
+ let asymmetric = rows
+ .iter()
+ .any(|(_, c0, c1)| c1.chars().count() >= c0.chars().count().saturating_mul(2).max(20));
+ if rows.len() < 3 && !asymmetric {
+ return None;
+ }
+
+ let body: Vec<Vec<String>> = rows
+ .iter()
+ .map(|(_, c0, c1)| vec![c0.clone(), c1.clone()])
+ .collect();
+ Some(TableRun {
+ start: start_idx,
+ end: j,
+ block: Block::Table {
+ header: None,
+ rows: body,
+ },
+ })
+}
+
+/// Split a merged-column text item on the whitespace position whose linear
+/// x-estimate is closest to `anchor_x`. Returns trimmed (left, right) halves,
+/// or `None` if no usable whitespace split exists.
+fn split_merged_at_anchor(
+ text: &str,
+ start_x: f32,
+ end_x: f32,
+ anchor_x: f32,
+) -> Option<(String, String)> {
+ let width = (end_x - start_x).max(1.0);
+ let ratio = ((anchor_x - start_x) / width).clamp(0.0, 1.0);
+ let chars: Vec<char> = text.chars().collect();
+ if chars.is_empty() {
+ return None;
+ }
+ let target = ((chars.len() as f32) * ratio) as usize;
+ let mut best: Option<usize> = None;
+ let mut best_dist = usize::MAX;
+ for (i, c) in chars.iter().enumerate() {
+ if c.is_whitespace() {
+ let d = i.abs_diff(target);
+ if d < best_dist {
+ best_dist = d;
+ best = Some(i);
+ }
+ }
+ }
+ let split = best?;
+ let left: String = chars[..split].iter().collect();
+ let right: String = chars[split + 1..].iter().collect();
+ let left = left.trim().to_string();
+ let right = right.trim().to_string();
+ if left.is_empty() || right.is_empty() {
+ return None;
+ }
+ Some((left, right))
+}
+
+// ── Cross-run merging (post-pass over `detect_tables` output) ──────────────
+//
+// `try_detect_table` walks lines top-to-bottom and breaks the run whenever the
+// column count or track alignment changes. That breaks two common shapes into
+// separate runs:
+//
+// B1 — multi-line header with row-label-column missing. The header rows have
+// N cells aligned to body tracks 2..N+1; the body rows have N+1 cells
+// including a leading row-label. Detect_tables emits an N-col "header"
+// run + an (N+1)-col body run.
+//
+// B4 — a single table interrupted by a category divider that fragments it
+// into two sibling runs with identical column structure.
+//
+// The pass below walks adjacent run pairs and merges them when they're
+// vertically immediate (A.end == B.start), reasonably close in y, and share
+// either identical tracks (Case Same) or A's tracks are a 1-column-shorter
+// subset of B's tracks (Case Subset). Subset merges fold A into B's header.
+//
+// Guards:
+// - Only merge `Block::Table` pairs (skip `GridFallback`).
+// - A.end must equal B.start so no non-table content between the runs
+// gets dropped.
+// - A's body row count is capped (`TABLE_HEADER_MAX_ABSORB_ROWS`) so a
+// real standalone table that happens to neighbor another isn't absorbed.
+// - Vertical gap between A's last line and B's first line is capped by a
+// small multiple of the line height.
+
+/// A run with this many or fewer body rows can be folded as header content of
+/// a following table. Above this we treat A as its own complete table.
+const TABLE_HEADER_MAX_ABSORB_ROWS: usize = 3;
+
+/// Cap on the y-gap between two consecutive runs for them to be merge
+/// candidates, in multiples of line height. Larger gaps mean visually
+/// distinct tables.
+const TABLE_MERGE_MAX_Y_GAP_LINES: f32 = 2.0;
+
+fn merge_consecutive_table_runs(
+ runs: Vec<TableRun>,
+ lines: &[ProjectedLine],
+) -> Vec<TableRun> {
+ if runs.len() < 2 {
+ return runs;
+ }
+ let mut out: Vec<TableRun> = Vec::with_capacity(runs.len());
+ for run in runs {
+ if let Some(prev) = out.last() {
+ if let Some(merged) = try_merge_pair(prev, &run, lines) {
+ out.pop();
+ out.push(merged);
+ continue;
+ }
+ }
+ out.push(run);
+ }
out
}
+fn run_column_count(run: &TableRun) -> Option<usize> {
+ match &run.block {
+ Block::Table { header, rows } => header
+ .as_ref()
+ .map(|h| h.len())
+ .or_else(|| rows.first().map(|r| r.len())),
+ _ => None,
+ }
+}
+
+/// Re-derive column tracks from the run's source lines. Aggregates min start_x
+/// and max end_x across *every* line whose `split_cells` count matches the
+/// run's declared column count, so a column with tight per-row content (e.g.
+/// a right-aligned numeric body cell) still produces a track wide enough to
+/// match a wider header cell that aligns to the same column.
+fn run_body_tracks(run: &TableRun, lines: &[ProjectedLine]) -> Option<Vec<(f32, f32)>> {
+ let n_cols = run_column_count(run)?;
+ let mut acc: Option<Vec<(f32, f32)>> = None;
+ for idx in run.start..run.end.min(lines.len()) {
+ let cells = split_cells(&lines[idx]);
+ if cells.len() != n_cols {
+ continue;
+ }
+ let row: Vec<(f32, f32)> = cells.iter().map(|c| (c.start_x, c.end_x)).collect();
+ acc = Some(match acc {
+ None => row,
+ Some(prev) => prev
+ .into_iter()
+ .zip(row)
+ .map(|((ps, pe), (s, e))| (ps.min(s), pe.max(e)))
+ .collect(),
+ });
+ }
+ acc
+}
+
+fn tracks_align_same(a: &[(f32, f32)], b: &[(f32, f32)]) -> bool {
+ if a.len() != b.len() {
+ return false;
+ }
+ a.iter().zip(b.iter()).all(|(ta, tb)| {
+ let ca = (ta.0 + ta.1) * 0.5;
+ let cb = (tb.0 + tb.1) * 0.5;
+ (ca - cb).abs() <= TABLE_TRACK_TOLERANCE_PT
+ })
+}
+
+/// Score the alignment between two tracks. Returns `None` if they don't align.
+/// Distance is `min(start_diff, end_diff, center_interior_match)` so a header
+/// cell sitting at the edge of a wide body cell doesn't spuriously match.
+fn subset_match_score(ta: (f32, f32), tb: (f32, f32), tol: f32) -> Option<f32> {
+ let d_start = (ta.0 - tb.0).abs();
+ let d_end = (ta.1 - tb.1).abs();
+ let ca = (ta.0 + ta.1) * 0.5;
+ // Center-in-range only counts when a's center falls in b's interior
+ // half — guards against a narrow header touching the edge of a wide
+ // row-label cell next door.
+ let interior_lo = tb.0 + (tb.1 - tb.0) * 0.25;
+ let interior_hi = tb.1 - (tb.1 - tb.0) * 0.25;
+ let d_center = if ca >= interior_lo && ca <= interior_hi {
+ 0.0
+ } else {
+ f32::INFINITY
+ };
+ let d = d_start.min(d_end).min(d_center);
+ if d <= tol {
+ Some(d)
+ } else {
+ None
+ }
+}
+
+/// Looser tolerance for cross-run subset matching. Header cells and body
+/// cells often have different content widths (e.g. `(percent)` header is
+/// 65pt wide while the body's `12` is 10pt wide), so the per-row track
+/// tolerance is too tight here. Combined with the interior-only center
+/// check in `subset_match_score`, this stays conservative.
+const TABLE_SUBSET_TRACK_TOLERANCE_PT: f32 = 12.0;
+
+/// Map A's tracks to B's tracks (requires `|A| + 1 == |B|`). Tries every
+/// possible "skip one B column" assignment and picks the lowest-total-error
+/// option. Returns `None` when no skip yields a fully-aligned mapping.
+fn subset_mapping(a: &[(f32, f32)], b: &[(f32, f32)]) -> Option<Vec<usize>> {
+ if a.len() + 1 != b.len() {
+ return None;
+ }
+ let tol = TABLE_SUBSET_TRACK_TOLERANCE_PT;
+ let mut best: Option<(Vec<usize>, f32)> = None;
+ for skip in 0..b.len() {
+ let mut mapping = Vec::with_capacity(a.len());
+ let mut total = 0.0f32;
+ let mut ok = true;
+ for i in 0..a.len() {
+ let bi = if i < skip { i } else { i + 1 };
+ match subset_match_score(a[i], b[bi], tol) {
+ Some(d) => {
+ mapping.push(bi);
+ total += d;
+ }
+ None => {
+ ok = false;
+ break;
+ }
+ }
+ }
+ if ok && best.as_ref().map_or(true, |(_, e)| total < *e) {
+ best = Some((mapping, total));
+ }
+ }
+ best.map(|(m, _)| m)
+}
+
+/// Insert empty strings into `row` so that its content lands at the mapped
+/// columns in a `target_len`-wide row.
+fn pad_row_to_layout(row: &[String], mapping: &[usize], target_len: usize) -> Vec<String> {
+ let mut out: Vec<String> = vec![String::new(); target_len];
+ for (a_idx, &b_idx) in mapping.iter().enumerate() {
+ if b_idx < target_len && a_idx < row.len() {
+ out[b_idx] = row[a_idx].clone();
+ }
+ }
+ out
+}
+
+/// Maximum number of non-table lines allowed between two runs being merged.
+/// Each interstitial line must be a short single-cell label (category
+/// divider, group header) to qualify — anything longer or multi-cell is
+/// real content and rejects the merge.
+const TABLE_MERGE_MAX_INTERSTITIAL: usize = 1;
+
+/// Cap on the character count of an interstitial label line that the merge
+/// will absorb as a body row.
+const TABLE_MERGE_MAX_INTERSTITIAL_CHARS: usize = 60;
+
+fn is_absorbable_interstitial(line: &ProjectedLine) -> bool {
+ let cells = split_cells(line);
+ if cells.len() > 1 {
+ return false;
+ }
+ let text = line.text.trim();
+ if text.len() > TABLE_MERGE_MAX_INTERSTITIAL_CHARS {
+ return false;
+ }
+ // Reject sentence-shaped prose: ends in . ! ? (a real label rarely does)
+ if let Some(last) = text.chars().last() {
+ if matches!(last, '.' | '!' | '?') && text.len() > 6 {
+ return false;
+ }
+ }
+ true
+}
+
+fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option<TableRun> {
+ // Allow up to `TABLE_MERGE_MAX_INTERSTITIAL` short label lines between
+ // A's end and B's start. Each interstitial gets preserved as a body
+ // row of the merged table so no content is dropped.
+ let interstitial = b.start.saturating_sub(a.end);
+ if interstitial > TABLE_MERGE_MAX_INTERSTITIAL {
+ return None;
+ }
+ let interstitial_texts: Vec<String> = if interstitial == 0 {
+ Vec::new()
+ } else {
+ let slice = &lines[a.end..b.start];
+ if !slice.iter().all(is_absorbable_interstitial) {
+ return None;
+ }
+ slice.iter().map(|l| l.text.trim().to_string()).collect()
+ };
+ let (a_header, a_rows) = match &a.block {
+ Block::Table { header, rows } => (header.clone(), rows.clone()),
+ _ => return None,
+ };
+ let (b_header, b_rows) = match &b.block {
+ Block::Table { header, rows } => (header.clone(), rows.clone()),
+ _ => return None,
+ };
+ let a_cols = run_column_count(a)?;
+ let b_cols = run_column_count(b)?;
+ let a_tracks = run_body_tracks(a, lines)?;
+ let b_tracks = run_body_tracks(b, lines)?;
+
+ if a.end == 0 || a.end > lines.len() || b.start >= lines.len() {
+ return None;
+ }
+ let a_last = &lines[a.end - 1];
+ let b_first = &lines[b.start];
+ let line_height = a_last.bbox.height.max(b_first.bbox.height).max(1.0);
+ let gap = b_first.bbox.y - (a_last.bbox.y + a_last.bbox.height);
+ if gap > line_height * TABLE_MERGE_MAX_Y_GAP_LINES {
+ return None;
+ }
+ if gap < -line_height {
+ return None;
+ }
+
+ // Case Same: identical tracks, concat rows.
+ if a_cols == b_cols && tracks_align_same(&a_tracks, &b_tracks) {
+ // Don't merge two complete-looking tables across a noticeable gap.
+ let both_complete = a_header.is_some()
+ && b_header.is_some()
+ && a_rows.len() >= 3
+ && b_rows.len() >= 3;
+ if both_complete && gap > line_height * 1.0 {
+ return None;
+ }
+ let header = a_header.clone().or_else(|| b_header.clone());
+ let mut rows = a_rows.clone();
+ // Preserve interstitial label lines as body rows, content in col 0.
+ for text in &interstitial_texts {
+ let mut row = vec![String::new(); b_cols];
+ row[0] = text.clone();
+ rows.push(row);
+ }
+ // If both runs had explicit headers, we kept A's; preserve B's
+ // header text as a body row so its content isn't dropped.
+ if a_header.is_some() && b_header.is_some() {
+ if let Some(bh) = b_header.clone() {
+ rows.push(bh);
+ }
+ }
+ rows.extend(b_rows.iter().cloned());
+ return Some(TableRun {
+ start: a.start,
+ end: b.end,
+ block: Block::Table { header, rows },
+ });
+ }
+
+ // Case Subset: A has 1 fewer column; fold A into B's header.
+ if a_cols + 1 == b_cols && a_rows.len() <= TABLE_HEADER_MAX_ABSORB_ROWS {
+ let mapping = subset_mapping(&a_tracks, &b_tracks)?;
+
+ // Compose header rows top-to-bottom: A.header -> A.rows -> B.header.
+ let mut header_layers: Vec<Vec<String>> = Vec::new();
+ if let Some(h) = &a_header {
+ header_layers.push(pad_row_to_layout(h, &mapping, b_cols));
+ }
+ for row in &a_rows {
+ header_layers.push(pad_row_to_layout(row, &mapping, b_cols));
+ }
+ if let Some(h) = &b_header {
+ header_layers.push(h.clone());
+ }
+ if header_layers.is_empty() {
+ return None;
+ }
+ let merged_header: Vec<String> = (0..b_cols)
+ .map(|col| {
+ let mut parts: Vec<String> = Vec::new();
+ for layer in &header_layers {
+ let s = layer.get(col).map(|s| s.as_str()).unwrap_or("");
+ if s.is_empty() {
+ continue;
+ }
+ if parts.last().map(|p| p.as_str()) == Some(s) {
+ continue;
+ }
+ parts.push(s.to_string());
+ }
+ parts.join(" ")
+ })
+ .collect();
+ // Preserve interstitial label lines as body rows ahead of B's rows.
+ let mut merged_rows: Vec<Vec<String>> = Vec::new();
+ for text in &interstitial_texts {
+ let mut row = vec![String::new(); b_cols];
+ row[0] = text.clone();
+ merged_rows.push(row);
+ }
+ merged_rows.extend(b_rows.iter().cloned());
+ return Some(TableRun {
+ start: a.start,
+ end: b.end,
+ block: Block::Table {
+ header: Some(merged_header),
+ rows: merged_rows,
+ },
+ });
+ }
+
+ None
+}
+
// ── Ruled-grid table detection ─────────────────────────────────────────────
//
// Detect tables drawn with explicit horizontal + vertical rules (the "Strong"
@@ -562,6 +1388,24 @@ const TABLE_CROSS_TOLERANCE_PT: f32 = 3.0;
/// ~0.09 on the bench (more false tables than real forms recovered).
const TABLE_MAX_EMPTY_CELL_FRACTION: f32 = 0.30;
+/// Fraction of a row or column that must be populated to qualify the grid as
+/// a structural fill-in form (e.g. comparison charts with row labels + header
+/// row but otherwise empty cells). When this signature is met, the empty-cell
+/// fraction filter relaxes to `TABLE_MAX_EMPTY_CELL_FRACTION_WITH_SPINE`.
+const TABLE_SPINE_FILL_FRACTION: f32 = 0.7;
+
+/// Max characters in any single col-0 or row-0 cell when applying the spine
+/// bypass. Real labels and headers are short (1-5 words ≈ 50 chars); a column
+/// of multi-sentence prose triggers `col0_fill` but isn't a structural label
+/// column.
+const TABLE_SPINE_MAX_CELL_CHARS: usize = 60;
+
+/// Ceiling on empty-cell fraction even when a spine is detected. Caps how
+/// aggressively the fill-in-form bypass can override the base filter — past
+/// 75% empty, even a strong spine isn't enough to distinguish from decorative
+/// page chrome.
+const TABLE_MAX_EMPTY_CELL_FRACTION_WITH_SPINE: f32 = 0.75;
+
/// Reject candidates whose grid covers nearly the whole page — almost always
/// a page border, not a real table.
const TABLE_MAX_PAGE_COVERAGE: f32 = 0.95;
@@ -945,8 +1789,36 @@ fn build_ruled_table(
.flatten()
.filter(|filled| !**filled)
.count();
- if (empty_count as f32) / (total as f32) > TABLE_MAX_EMPTY_CELL_FRACTION {
- return None;
+ let empty_frac = (empty_count as f32) / (total as f32);
+ if empty_frac > TABLE_MAX_EMPTY_CELL_FRACTION {
+ // Fill-in-blank forms (docs 119/120/180) have a column of row labels
+ // OR a row of column headers but most body cells empty by design.
+ // Two filters together distinguish real forms from layout wrappers
+ // that happen to have a dense column (doc 130's right-side prose
+ // column trips a naive max-fill check):
+ // 1. The dense band must be col 0 or row 0 — that's where labels
+ // and headers actually live; a dense column anywhere else is
+ // almost always body prose, not a structural label spine.
+ // 2. Spine cells must be short (≤ TABLE_SPINE_MAX_CELL_CHARS) —
+ // labels are 1-5 words, not multi-sentence prose.
+ // Restrict to the col-0 case only. row-0 spines turn out to be too
+ // permissive — doc 051 has a multi-line header that lands across all
+ // columns (row0_fill = 1.0) but its body is badly fragmented, so the
+ // row-0 signal misleads. Col-0 label columns are the much stronger
+ // fill-in-form signature: rare in body prose, near-universal in
+ // forms.
+ let col0_fill =
+ (0..n_rows).filter(|r| cell_has_text[*r][0]).count() as f32 / n_rows as f32;
+ let col0_max_chars = (0..n_rows)
+ .filter(|r| cell_has_text[*r][0])
+ .map(|r| cells[r][0].len())
+ .max()
+ .unwrap_or(0);
+ let col0_spine = col0_fill >= TABLE_SPINE_FILL_FRACTION
+ && col0_max_chars <= TABLE_SPINE_MAX_CELL_CHARS;
+ if !col0_spine || empty_frac > TABLE_MAX_EMPTY_CELL_FRACTION_WITH_SPINE {
+ return None;
+ }
}
// Header = first row iff every non-empty cell in it is bold.
@@ -1012,6 +1884,60 @@ fn find_bucket(boundaries: &[f32], val: f32) -> Option<usize> {
None
}
+/// Detect candidate ruled-table bounding rectangles from page graphics alone.
+///
+/// Unlike `detect_ruled_tables`, this runs *before* projection and ignores text
+/// content entirely — its only job is to find the bbox of every H/V grid
+/// component so the XY-cut layout pass can treat those regions as obstacles
+/// and avoid slicing tables column-wise (the failure mode that produces
+/// column-major reading order on docs 083/120/130/etc.). Empty-cell-fraction
+/// and other quality filters are deliberately skipped here: we want the bbox
+/// even of sparse forms or partially-filled grids, because the obstacle
+/// machinery only cares about geometry.
+pub fn detect_table_rects(
+ graphics: &[GraphicPrimitive],
+ page_width: f32,
+ page_height: f32,
+) -> Vec<Rect> {
+ let (hs, vs) = extract_h_v_segments(graphics);
+ let hs = cluster_h_segments(hs);
+ let vs = cluster_v_segments(vs);
+ if hs.len() < 2 || vs.len() < 2 {
+ return Vec::new();
+ }
+ let components = find_grid_components(&hs, &vs);
+ let mut out = Vec::new();
+ for (h_idx, v_idx) in components {
+ let ys: Vec<f32> = h_idx.iter().map(|&i| hs[i].y).collect();
+ let xs: Vec<f32> = v_idx.iter().map(|&i| vs[i].x).collect();
+ let y_min = ys.iter().copied().fold(f32::INFINITY, f32::min);
+ let y_max = ys.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let x_min = xs.iter().copied().fold(f32::INFINITY, f32::min);
+ let x_max = xs.iter().copied().fold(f32::NEG_INFINITY, f32::max);
+ let w = x_max - x_min;
+ let h = y_max - y_min;
+ if w < 5.0 || h < 5.0 {
+ continue;
+ }
+ // Skip whole-page borders — same rationale as `TABLE_MAX_PAGE_COVERAGE`
+ // in the post-projection detector.
+ if page_width > 0.0
+ && page_height > 0.0
+ && w / page_width >= TABLE_MAX_PAGE_COVERAGE
+ && h / page_height >= TABLE_MAX_PAGE_COVERAGE
+ {
+ continue;
+ }
+ out.push(Rect {
+ x: x_min,
+ y: y_min,
+ width: w,
+ height: h,
+ });
+ }
+ out
+}
+
/// Detect ruled-grid tables on a page from its vector graphics. Returns runs
/// in document order (sorted by `start`).
pub(super) fn detect_ruled_tables(
@@ -1208,7 +2134,7 @@ mod tests {
}
}
- #[test]
+#[test]
fn does_not_absorb_single_cell_title_above_body() {
// A one-cell title/caption above a table is NOT a header row and must
// not be absorbed.
@@ -1387,4 +2313,360 @@ mod tests {
assert_eq!(merged.len(), 1);
assert!(matches!(&merged[0].block, Block::Table { .. }));
}
+
+ // ── merge_consecutive_table_runs ─────────────────────────────────────
+ //
+ // Lines fixtures used by these tests are synthetic 3-cell and 4-cell
+ // rows at known x positions so the re-derived tracks match the runs we
+ // construct manually.
+
+ fn three_col_line(label: &str, y: f32) -> ProjectedLine {
+ line_with_spans(&[(label, 50.0), (label, 150.0), (label, 250.0)], y, 10.0)
+ }
+
+ fn four_col_line(label: &str, y: f32) -> ProjectedLine {
+ line_with_spans(
+ &[(label, 50.0), (label, 150.0), (label, 250.0), (label, 350.0)],
+ y,
+ 10.0,
+ )
+ }
+
+ // A row whose three cells sit at tracks 2..4 of a 4-col layout
+ // (subset of the 4-col tracks: missing leftmost column at x=50).
+ fn three_col_subset_line(label: &str, y: f32) -> ProjectedLine {
+ line_with_spans(&[(label, 150.0), (label, 250.0), (label, 350.0)], y, 10.0)
+ }
+
+ #[test]
+ fn merge_same_column_count_concatenates_rows() {
+ let lines = vec![
+ three_col_line("h1", 10.0),
+ three_col_line("h2", 25.0),
+ three_col_line("b1", 40.0),
+ three_col_line("b2", 55.0),
+ three_col_line("b3", 70.0),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: Some(vec!["A".into(), "B".into(), "C".into()]),
+ rows: vec![vec!["1".into(), "2".into(), "3".into()]],
+ },
+ };
+ let b = TableRun {
+ start: 2,
+ end: 5,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["x".into(), "y".into(), "z".into()],
+ vec!["p".into(), "q".into(), "r".into()],
+ vec!["m".into(), "n".into(), "o".into()],
+ ],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 1, "expected single merged run");
+ match &merged[0].block {
+ Block::Table { header, rows } => {
+ assert_eq!(header.as_deref().map(|h| h.len()), Some(3));
+ assert_eq!(rows.len(), 4);
+ assert_eq!(rows[0], vec!["1", "2", "3"]);
+ assert_eq!(rows[3], vec!["m", "n", "o"]);
+ }
+ other => panic!("expected Block::Table, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn merge_subset_columns_folds_into_header() {
+ // A is a 2-row 3-col "header" whose tracks land on columns 2..4 of
+ // B's 4-col body (i.e. the row-label column is missing in A). After
+ // merge: one 4-col table whose header has empty col 0 and B's body
+ // rows.
+ let lines = vec![
+ three_col_subset_line("2011", 10.0),
+ three_col_subset_line("(pct)", 25.0),
+ four_col_line("body", 40.0),
+ four_col_line("body", 55.0),
+ four_col_line("body", 70.0),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["2011".into(), "2010".into(), "Avg".into()],
+ vec!["(pct)".into(), "(pct)".into(), "(pct)".into()],
+ ],
+ },
+ };
+ let b = TableRun {
+ start: 2,
+ end: 5,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["Q3".into(), "10".into(), "20".into(), "30".into()],
+ vec!["Q4".into(), "11".into(), "21".into(), "31".into()],
+ vec!["YR".into(), "12".into(), "22".into(), "32".into()],
+ ],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 1);
+ match &merged[0].block {
+ Block::Table { header, rows } => {
+ let h = header.as_deref().expect("expected header");
+ assert_eq!(h.len(), 4);
+ assert_eq!(h[0], "");
+ // Adjacent identical pieces are deduped per column.
+ assert_eq!(h[1], "2011 (pct)");
+ assert_eq!(h[2], "2010 (pct)");
+ assert_eq!(h[3], "Avg (pct)");
+ assert_eq!(rows.len(), 3);
+ assert_eq!(rows[0], vec!["Q3", "10", "20", "30"]);
+ }
+ other => panic!("expected Block::Table, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn merge_skips_distant_runs() {
+ // Same shape as the same-column test but B is far below A.
+ let lines = vec![
+ three_col_line("h1", 10.0),
+ three_col_line("h2", 25.0),
+ three_col_line("b1", 200.0), // ~16× line height below
+ three_col_line("b2", 215.0),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: Some(vec!["A".into(), "B".into(), "C".into()]),
+ rows: vec![vec!["1".into(), "2".into(), "3".into()]],
+ },
+ };
+ let b = TableRun {
+ start: 2,
+ end: 4,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["x".into(), "y".into(), "z".into()],
+ vec!["p".into(), "q".into(), "r".into()],
+ ],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 2, "distant runs should not merge");
+ }
+
+ #[test]
+ fn merge_skips_large_prior_run() {
+ // A has 5 body rows — large enough that it's a real standalone
+ // table, not a header to fold into B.
+ let lines: Vec<ProjectedLine> = (0..10)
+ .map(|i| three_col_subset_line("x", 10.0 + i as f32 * 15.0))
+ .chain((0..3).map(|i| four_col_line("y", 160.0 + i as f32 * 15.0)))
+ .collect();
+ let a = TableRun {
+ start: 0,
+ end: 10,
+ block: Block::Table {
+ header: None,
+ rows: (0..10)
+ .map(|_| vec!["a".into(), "b".into(), "c".into()])
+ .collect(),
+ },
+ };
+ let b = TableRun {
+ start: 10,
+ end: 13,
+ block: Block::Table {
+ header: None,
+ rows: (0..3)
+ .map(|_| vec!["1".into(), "2".into(), "3".into(), "4".into()])
+ .collect(),
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 2, "large prior run should not be absorbed");
+ }
+
+ #[test]
+ fn merge_skips_two_col_diff() {
+ // A is 3-col, B is 5-col — too large a column-count delta to be a
+ // header-vs-body relationship.
+ let lines = vec![
+ three_col_subset_line("x", 10.0),
+ three_col_subset_line("y", 25.0),
+ line_with_spans(
+ &[
+ ("a", 50.0),
+ ("b", 150.0),
+ ("c", 250.0),
+ ("d", 350.0),
+ ("e", 450.0),
+ ],
+ 40.0,
+ 10.0,
+ ),
+ line_with_spans(
+ &[
+ ("a", 50.0),
+ ("b", 150.0),
+ ("c", 250.0),
+ ("d", 350.0),
+ ("e", 450.0),
+ ],
+ 55.0,
+ 10.0,
+ ),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["x".into(), "y".into(), "z".into()],
+ vec!["x".into(), "y".into(), "z".into()],
+ ],
+ },
+ };
+ let b = TableRun {
+ start: 2,
+ end: 4,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["1".into(), "2".into(), "3".into(), "4".into(), "5".into()],
+ vec!["1".into(), "2".into(), "3".into(), "4".into(), "5".into()],
+ ],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 2, "2-col difference should not merge");
+ }
+
+ #[test]
+ fn merge_grid_fallback_left_alone() {
+ let lines = vec![
+ three_col_line("a", 10.0),
+ three_col_line("b", 25.0),
+ three_col_line("c", 40.0),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["a".into(), "b".into(), "c".into()],
+ vec!["a".into(), "b".into(), "c".into()],
+ ],
+ },
+ };
+ let b = TableRun {
+ start: 2,
+ end: 3,
+ block: Block::GridFallback {
+ lines: vec!["fallback".into()],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 2, "grid fallback should not be merged");
+ }
+
+ #[test]
+ fn merge_rejects_long_prose_interstitial() {
+ // A multi-cell or long prose line between runs must not be silently
+ // dropped by a merge.
+ let lines = vec![
+ three_col_line("h", 10.0),
+ three_col_line("h", 25.0),
+ line_with_spans(
+ &[("This", 50.0), ("is", 150.0), ("real", 250.0), ("content", 350.0)],
+ 40.0,
+ 10.0,
+ ),
+ three_col_line("b", 55.0),
+ three_col_line("b", 70.0),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: Some(vec!["A".into(), "B".into(), "C".into()]),
+ rows: vec![vec!["1".into(), "2".into(), "3".into()]],
+ },
+ };
+ let b = TableRun {
+ start: 3,
+ end: 5,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["x".into(), "y".into(), "z".into()],
+ vec!["p".into(), "q".into(), "r".into()],
+ ],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 2, "multi-cell interstitial should not merge");
+ }
+
+ #[test]
+ fn merge_absorbs_single_cell_interstitial_as_body_row() {
+ // Apple-earnings / NASS shape: 4-col header rows + a single-cell
+ // category divider ("Topsoil") + 5-col body. Divider must be
+ // preserved as a body row in the merged table.
+ let lines = vec![
+ three_col_subset_line("h", 10.0),
+ three_col_subset_line("h", 25.0),
+ line_with_spans(&[("Topsoil", 50.0)], 40.0, 10.0),
+ four_col_line("body", 55.0),
+ four_col_line("body", 70.0),
+ four_col_line("body", 85.0),
+ ];
+ let a = TableRun {
+ start: 0,
+ end: 2,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["2011".into(), "2010".into(), "Avg".into()],
+ vec!["(pct)".into(), "(pct)".into(), "(pct)".into()],
+ ],
+ },
+ };
+ let b = TableRun {
+ start: 3,
+ end: 6,
+ block: Block::Table {
+ header: None,
+ rows: vec![
+ vec!["Q3".into(), "10".into(), "20".into(), "30".into()],
+ vec!["Q4".into(), "11".into(), "21".into(), "31".into()],
+ vec!["YR".into(), "12".into(), "22".into(), "32".into()],
+ ],
+ },
+ };
+ let merged = merge_consecutive_table_runs(vec![a, b], &lines);
+ assert_eq!(merged.len(), 1);
+ match &merged[0].block {
+ Block::Table { header, rows } => {
+ assert!(header.is_some());
+ assert_eq!(rows.len(), 4, "interstitial + 3 body rows");
+ assert_eq!(rows[0][0], "Topsoil");
+ assert_eq!(rows[1], vec!["Q3", "10", "20", "30"]);
+ }
+ other => panic!("expected Block::Table, got {other:?}"),
+ }
+ }
}
diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rs
index 4a91968..ec7d062 100644
--- a/crates/liteparse/src/markdown_layout/test_helpers.rs
+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs
@@ -14,6 +14,7 @@ pub(crate) fn line(text: &str, x: f32, y: f32, h: f32, size: f32) -> ProjectedLi
anchor: Anchor::Left,
indent_x: x,
dominant_font_size: size,
+ font_size_is_estimated: false,
dominant_font_name: Some("Arial".into()),
all_bold: false,
all_italic: false,
@@ -83,6 +84,7 @@ pub(crate) fn line_with_spans(cells: &[(&str, f32)], y: f32, size: f32) -> Proje
anchor: Anchor::Left,
indent_x: min_x,
dominant_font_size: size,
+ font_size_is_estimated: false,
dominant_font_name: Some("Arial".into()),
all_bold: false,
all_italic: false,
@@ -135,6 +137,7 @@ pub(crate) fn styled_line(
anchor: Anchor::Left,
indent_x: min_x,
dominant_font_size: size,
+ font_size_is_estimated: false,
dominant_font_name: Some("Arial".into()),
all_bold: false,
all_italic: false,
diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rs
index e6aebcb..1dc9504 100644
--- a/crates/liteparse/src/output/markdown.rs
+++ b/crates/liteparse/src/output/markdown.rs
@@ -1,7 +1,7 @@
use crate::config::ImageMode;
use crate::markdown_layout::{
build_heading_map, classify_page_with_filters, compute_body_size, compute_header_footer_set,
- render_blocks,
+ detect_single_page_chrome, render_blocks,
};
use crate::types::{OutlineTarget, ParsedPage};
@@ -56,12 +56,14 @@ pub fn format_markdown(
.filter(|e| e.page_index == target_index)
.cloned()
.collect();
+ let chrome_indices = detect_single_page_chrome(page, body_size);
let blocks = classify_page_with_filters(
page,
&heading_map,
&header_footer,
&page_outline,
image_mode,
+ &chrome_indices,
);
out.push_str(&render_blocks(&blocks));
}
@@ -85,6 +87,7 @@ mod tests {
anchor: Anchor::Left,
indent_x: x,
dominant_font_size: size,
+ font_size_is_estimated: false,
dominant_font_name: Some("Arial".into()),
all_bold: false,
all_italic: false,
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index b592308..f63847d 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -2664,11 +2664,24 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
page.page_width,
page.page_height,
);
+ // Pre-projection ruled-table detection. Feeds XY-cut as obstacles
+ // so a table's inter-column gaps don't get picked as page-level
+ // V-cuts (column-major reading order is the dominant TEDS=0
+ // failure mode on the bench: docs 083/120/130/etc.).
+ let table_rects = crate::markdown_layout::detect_table_rects(
+ &page.graphics,
+ page.page_width,
+ page.page_height,
+ );
+ let mut obstacles: Vec<Rect> =
+ Vec::with_capacity(figures.len() + table_rects.len());
+ obstacles.extend(figures.iter().cloned());
+ obstacles.extend(table_rects.iter().cloned());
let (projected_lines, regions) = build_projected_lines(
&projected_items,
page.page_width,
page.page_height,
- &figures,
+ &obstacles,
);
ParsedPage {
page_number: page.page_number,
@@ -3035,12 +3048,19 @@ fn xy_find_best_cut(
let score = width as f32 * depth;
let mid = (s as f32 + e as f32) * 0.5;
let position = origin + mid * XY_BUCKET_PT;
- if best.as_ref().is_none_or(|b| score > b.score) {
- best = Some(CutCandidate {
- axis,
- position,
- score,
- });
+ // Density-stamping alone isn't always enough to push the
+ // gutter inside a table region below threshold — the
+ // inter-cell gaps win on tables with sparsely-filled cells
+ // (docs 120/180/150). Hard-reject any cut line that passes
+ // strictly through an obstacle rect intersecting `bbox`.
+ if !cut_line_passes_through_obstacle(axis, position, bbox, figures) {
+ if best.as_ref().is_none_or(|b| score > b.score) {
+ best = Some(CutCandidate {
+ axis,
+ position,
+ score,
+ });
+ }
}
}
} else {
@@ -3050,6 +3070,45 @@ fn xy_find_best_cut(
best
}
+/// Hard-reject companion to the density-stamping in `xy_find_best_cut`.
+/// Density-stamping makes the recursion *prefer* cuts around obstacles, but
+/// sparsely-filled tables (docs 120/180/150) have inter-cell gaps that still
+/// score better than the stamped obstacle band. Returns true iff the cut
+/// line at `position` strictly passes through any obstacle that intersects
+/// `bbox`.
+fn cut_line_passes_through_obstacle(
+ axis: CutAxis,
+ position: f32,
+ bbox: &Rect,
+ obstacles: &[Rect],
+) -> bool {
+ // Tolerance: a cut whose position lands within ~1pt of an obstacle's
+ // edge is allowed (the obstacle's edge is itself a natural cut line).
+ const EDGE_TOLERANCE_PT: f32 = 1.0;
+ for ob in obstacles {
+ // Skip obstacles that don't intersect bbox at all.
+ let ox0 = ob.x.max(bbox.x);
+ let oy0 = ob.y.max(bbox.y);
+ let ox1 = (ob.x + ob.width).min(bbox.x + bbox.width);
+ let oy1 = (ob.y + ob.height).min(bbox.y + bbox.height);
+ if ox1 <= ox0 || oy1 <= oy0 {
+ continue;
+ }
+ let through = match axis {
+ CutAxis::Vertical => {
+ position > ox0 + EDGE_TOLERANCE_PT && position < ox1 - EDGE_TOLERANCE_PT
+ }
+ CutAxis::Horizontal => {
+ position > oy0 + EDGE_TOLERANCE_PT && position < oy1 - EDGE_TOLERANCE_PT
+ }
+ };
+ if through {
+ return true;
+ }
+ }
+ false
+}
+
fn xy_split_bbox(bbox: &Rect, cut: &CutCandidate) -> (Rect, Rect) {
match cut.axis {
CutAxis::Horizontal => {
@@ -3255,6 +3314,34 @@ fn xy_find_column_cut(
})
}
+/// X position of the vertical gutter that splits `idxs` (within `bbox`) into
+/// columns — from the density V-cut or the column-start histogram fallback.
+/// `None` when the region is single-column. Used to decide whether peeling a
+/// wide spanning line above this region is productive.
+fn column_cut_x(
+ items: &[ProjectedTextItem],
+ idxs: &[usize],
+ bbox: &Rect,
+ median_h: f32,
+ figures: &[Rect],
+) -> Option<f32> {
+ xy_find_best_cut(items, idxs, bbox, CutAxis::Vertical, median_h, figures)
+ .or_else(|| xy_find_column_cut(items, idxs, bbox, median_h))
+ .map(|c| c.position)
+}
+
+/// Union horizontal extent (min x, max x) of `idxs`.
+fn x_extent(items: &[ProjectedTextItem], idxs: &[usize]) -> (f32, f32) {
+ let mut lo = f32::INFINITY;
+ let mut hi = f32::NEG_INFINITY;
+ for &i in idxs {
+ let it = &items[i].item;
+ lo = lo.min(it.x);
+ hi = hi.max(it.x + it.width.max(0.0));
+ }
+ (lo, hi)
+}
+
fn xy_find_banner_cut(
items: &[ProjectedTextItem],
idxs: &[usize],
@@ -3437,6 +3524,8 @@ fn xy_cut_rec(
kind: RegionKind::Leaf { item_indices: all },
};
}
+ let (left_bbox, right_bbox) = xy_split_bbox(&bbox, &cut);
+
// Banner cuts (score = ∞) at the page root are explicitly meant to
// isolate single-line wide headers like titles, so skip the min-lines
// guard for them. At deeper recursion levels we keep the guard — an
@@ -3449,7 +3538,34 @@ fn xy_cut_rec(
if cut.axis == CutAxis::Horizontal && !allow_single_line {
let lc = xy_distinct_lines(items, &left, median_h);
let rc = xy_distinct_lines(items, &right, median_h);
- if lc < XY_MIN_LINES_PER_H_SIDE || rc < XY_MIN_LINES_PER_H_SIDE {
+ // Rescue: a single wide spanning line (e.g. a centered authors /
+ // affiliation line above a two-column body) is worth isolating even
+ // mid-recursion when peeling it reveals the column gutter underneath.
+ // Otherwise the spanning line straddles the gutter, the V-cut can
+ // never fire, and the whole body interleaves column-by-column. The
+ // density H-cut that peels it has a finite score (the line is often
+ // just under the banner width threshold), so this is NOT gated on a
+ // banner cut. Discriminator vs. carving a single-column caption out of
+ // running prose: the thin side must be one line whose x-extent crosses
+ // the gutter revealed on the other (multi-line) side.
+ let spanning_rescue = {
+ let thin_wide = if lc < XY_MIN_LINES_PER_H_SIDE && rc >= XY_MIN_LINES_PER_H_SIDE {
+ Some(((&left, lc), (&right, &right_bbox)))
+ } else if rc < XY_MIN_LINES_PER_H_SIDE && lc >= XY_MIN_LINES_PER_H_SIDE {
+ Some(((&right, rc), (&left, &left_bbox)))
+ } else {
+ None
+ };
+ thin_wide.is_some_and(|((thin, thin_lines), (wide, wide_bbox))| {
+ thin_lines <= 1
+ && column_cut_x(items, wide, wide_bbox, median_h, figures)
+ .is_some_and(|gx| {
+ let (tx0, tx1) = x_extent(items, thin);
+ tx0 < gx - 1.0 && tx1 > gx + 1.0
+ })
+ })
+ };
+ if (lc < XY_MIN_LINES_PER_H_SIDE || rc < XY_MIN_LINES_PER_H_SIDE) && !spanning_rescue {
let mut all = left;
all.extend(right);
return Region {
@@ -3459,7 +3575,7 @@ fn xy_cut_rec(
}
}
- let (left_bbox, right_bbox) = xy_split_bbox(&bbox, &cut);
+
let left_region = xy_cut_rec(items, left, left_bbox, depth + 1, median_h, figures);
let right_region = xy_cut_rec(items, right, right_bbox, depth + 1, median_h, figures);
Region {
@@ -3561,9 +3677,17 @@ pub(crate) fn build_projected_lines(
let mut current: Vec<usize> = Vec::new();
let mut current_y: f32 = 0.0;
let mut current_h: f32 = 0.0;
+ // PDFium occasionally reports anomalously large item heights (e.g.
+ // 56pt for a single-word run whose real glyph height is ~13pt) when
+ // the font's bounding box / line-height is baked into the text-matrix
+ // scale. Without a cap, the y-band tolerance `max(h) * 0.5` swallows
+ // multiple distinct baselines into one projected line (visible on
+ // docs 121, 122 — fill-in-the-blank lab worksheets). Clamp at 24pt
+ // for the banding decision; the actual stored line bbox is unchanged.
+ const Y_BAND_HEIGHT_CAP: f32 = 24.0;
for idx in sorted {
let y = items[idx].item.y;
- let h = items[idx].item.height.max(1.0);
+ let h = items[idx].item.height.max(1.0).min(Y_BAND_HEIGHT_CAP);
if current.is_empty() {
current.push(idx);
current_y = y;
@@ -3713,14 +3837,15 @@ fn build_one_line(
// Fallback: when PDFium reports font_size ≤ 1.5 (size baked into the text
// matrix), use char-weighted bbox height instead so heading detection has
// something to chew on. Documented in MARKDOWN_PROGRESS.md.
- let dominant_font_size = if dominant_size_from_font > 1.5 {
- dominant_size_from_font
+ let (dominant_font_size, font_size_is_estimated) = if dominant_size_from_font > 1.5 {
+ (dominant_size_from_font, false)
} else {
- height_weights
+ let h = height_weights
.values()
.max_by_key(|(_, n)| *n)
.map(|(h, _)| *h)
- .unwrap_or(0.0)
+ .unwrap_or(0.0);
+ (h, true)
};
let dominant_font_name = name_weights
@@ -3766,6 +3891,7 @@ fn build_one_line(
// this for paragraph/list-indent comparisons within a single column.
indent_x: bbox.x,
dominant_font_size,
+ font_size_is_estimated,
dominant_font_name,
all_bold: majority(bold_chars),
all_italic: majority(italic_chars),
@@ -4029,6 +4155,59 @@ mod tests {
let _ = region_no_fig;
}
+ fn has_vertical_split(region: &Region) -> bool {
+ match &region.kind {
+ RegionKind::Split { axis, children } => {
+ *axis == CutAxis::Vertical
+ || children.iter().any(has_vertical_split)
+ }
+ RegionKind::Leaf { .. } => false,
+ }
+ }
+
+ fn two_column_body(items: &mut Vec<ProjectedTextItem>, y0: f32) {
+ // Left column at x≈50..280, right column at x≈320..550, sharing y-bands.
+ for row in 0..8 {
+ let y = y0 + row as f32 * 14.0;
+ items.push(item_at("left column body text here", 50.0, y, 230.0, 12.0));
+ items.push(item_at("right column body text here", 320.0, y, 230.0, 12.0));
+ }
+ }
+
+ #[test]
+ fn spanning_line_above_columns_is_peeled_to_reveal_gutter() {
+ // A single centered line that crosses the gutter (x 160..450, gutter
+ // ≈300) sits above a clean two-column body. The spanning line straddles
+ // the gutter so the body can't V-cut until it's peeled. The rescue in
+ // the min-lines guard must allow the (finite-score) H-cut that isolates
+ // the spanning line, after which the body splits into columns.
+ let mut items = vec![item_at("Centered Spanning Author Line", 160.0, 100.0, 290.0, 12.0)];
+ two_column_body(&mut items, 140.0);
+ let region = xy_cut(&items, 612.0, 792.0, &[]);
+ assert!(
+ has_vertical_split(&region),
+ "spanning line should be peeled so the two-column body V-cuts"
+ );
+ }
+
+ #[test]
+ fn single_column_caption_is_not_peeled_into_columns() {
+ // A short centered line that sits entirely within the left column
+ // (x 60..200, never crossing the gutter) must NOT trigger the spanning
+ // rescue — it's a caption in running prose, not a column-straddling
+ // banner. The body below it is genuinely single-column.
+ let mut items = vec![item_at("Short caption", 60.0, 100.0, 140.0, 12.0)];
+ for row in 0..8 {
+ let y = 140.0 + row as f32 * 14.0;
+ items.push(item_at("single column running body text", 50.0, y, 230.0, 12.0));
+ }
+ let region = xy_cut(&items, 612.0, 792.0, &[]);
+ assert!(
+ !has_vertical_split(&region),
+ "single-column caption must not be carved into columns"
+ );
+ }
+
#[test]
fn project_pages_to_grid_handles_page_with_no_text_items() {
let pages = vec![Page {
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index b48c8c0..0bf1eb0 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -237,6 +237,12 @@ pub struct ProjectedLine {
pub anchor: Anchor,
pub indent_x: f32,
pub dominant_font_size: f32,
+ /// True when `dominant_font_size` was derived from bbox height (PDFium
+ /// reported the font size baked into the text matrix, ~1.0) rather than a
+ /// real font-size value. Height-derived sizes jitter ±1pt line-to-line
+ /// based on glyph content (descenders, parens, capitals), so heading
+ /// detection must use a wider margin over body for these lines.
+ pub font_size_is_estimated: bool,
pub dominant_font_name: Option<String>,
pub all_bold: bool,
pub all_italic: bool,