Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewichd1c2240ba61d
diff --git a/MARKDOWN_PROGRESS.md b/MARKDOWN_PROGRESS.md
index 38bfca2..1d88c6e 100644
--- a/MARKDOWN_PROGRESS.md
+++ b/MARKDOWN_PROGRESS.md
@@ -2,6 +2,18 @@
Tracks build-order progress against [MARKDOWN_PLAN.md](MARKDOWN_PLAN.md). Update as steps complete.
+> **2026-06-12 decimal-fragment merge + body-seeded inferred tables — opendataloader Overall 0.8710 → 0.8719 (TEDS 0.6877 → 0.6929 (+0.0052), NID 0.9120 → 0.9125, MHS flat 0.8036); ParseBench table grits_con 0.5647 → 0.5737 (+0.0090), composite 0.4040 → 0.4079, TRM 0.2213 → 0.2196 (−0.0016); olmOCR table_tests 47.3 → 48.7% (+1.4pp), multi_column 63.6% (noise).** Targeted the 2026-06-11 audit's Tier-1 #3 "table label-column drop" content-loss defect, reproduced on doc `01030000000082` Table 29 (state names Gujarat/Punjab/… silently dropped, table emitted 3-col instead of 4-col). Two compounding root causes, both in the markdown/projection layers (the names extract fine — verified in the `--format text` grid):
+>
+> 1. **Decimal fragmentation (`projection.rs` word-merge pass).** PDFium emits `15.6` / `200.4` as two x-contiguous items `"15"`+`".6"`; `looks_like_table_number` flags both, so the `both_are_numbers` guard kept them apart, leaving `15 .6` / `21 .3%` in rendered cells *and* injecting spurious close-spaced column tracks. **Fix:** a decimal-continuation carve-out — when the next run begins with `.`+digit and butts directly against a digit-terminated run (`delta_x ∈ [−2, 1]`, y-compatible), merge silently. A real pair of adjacent table numbers always shows a visible inter-cell gap, never a digit against a leading-decimal run, so this is safe. Clean win on its own (fixes the `X .Y` artifact across many numeric/financial docs; NID +0.0005, zero regressions).
+>
+> 2. **Header-seeded tracks drop the left column (`tables.rs::try_detect_table_inferred`).** The inferred-track path captured the State column (`x≈104`) but **bailed** (`min_gap < TABLE_MIN_TRACK_GAP`) because the stacked header (`"Number of"`@271.8 / `"clauses"`@280.8) and the decimal fragments injected close phantom tracks; it then fell to the header-seeded `try_detect_table`, which seeds tracks from the first line (the 3-cell header `"Number of | GSDP | GSDP"`) and **silently discards** every data row's `Gujarat`@103 in the `cells.len() > column_count` keep-filter. **Fix, two parts:** (a) **support-filter the inferred tracks** in `infer_tracks_from_raw_items` — each cluster carries its item-support; when a clear multi-row body exists (some cluster supported by ≥3 items) prune the single-item phantom clusters (header cells offset from their data column). For Table 29 this leaves exactly the 4 data columns (104/289/369/444, min_gap 75 ≫ threshold). (b) **seed the body at the first strong row, not `start_idx`** — a strong row single-covers every track with a distinct span; the *seeding* line may be a stacked/partial header, so scan forward for the first strong row, seed there, and let `finalize_table_run`/`absorb_header_lines` absorb the header lines above.
+>
+> **The load-bearing narrowing (caught by A/B byte-diff).** The first cut of (2b) fired the inferred path *eagerly* on short header bands — a strong row found inside a 2-line header anchored a pseudo-table that consumed the lead lines and starved the header-seeded path of the real table below (docs **117/187** lost their tables entirely → loose text; opendataloader TEDS regressed −0.0058). Guard: **only advance `body_start` past `start_idx` when the resulting body has ≥3 rows** (`body_start > start_idx && rows.len() < 3 → bail`). Already-strong seeds (`body_start == start_idx`) keep the standard `TABLE_MIN_ROWS` threshold and are byte-unaffected. This flipped opendataloader TEDS from −0.0058 to **+0.0052** while keeping the doc-082/083/084 column recoveries; 117/187 restored byte-identical to baseline. Blast radius 10/200 opendataloader docs, all wins/neutral.
+>
+> **A/B method:** snapshotted the pre-change binary as `target/release/lit-base`, byte-diffed all 200 opendataloader docs to bound blast radius, then ran same-harness evals for both binaries (opendataloader via `LITEPARSE_BIN` override; ParseBench by swapping `target/release/lit`). olmOCR rebuilt the root-venv Python binding and ran as regression-check only.
+>
+> **Residuals / known limitations:** (a) **recovered tables get an empty header row** (ParseBench TRM −0.0016) — a *centered* header label (`"State"`@166) can't bind to a *left-aligned* data column (names@103) under point-tracks, so `absorb_header_lines` breaks and the header text spills into a loose line above; the body content is recovered but the header is imperfect. Proper fix is nearest-track header binding (separate, riskier). (b) The audit's other content-loss docs **046/121/122** are untouched — different root cause (party-name / in-table-prose extraction in the projection layer), separate follow-up. 204 lib tests pass.
+>
> **2026-06-12 code-block language tag — ParseBench `is_code_block` 0.0 → 0.2 (per-doc avg; 0/10 → 5/10 individual tests, all five python cases).** Code blocks were already detected and fenced correctly with intact content, but emitted as bare ` ``` ` with no info-string, so `rules_formatting.py`'s `is_code_block` (which requires a fence whose lang matches the expected language, then checks the snippet is in that block's body) scored a hard 0.0. Added `lang: Option<String>` to `Block::CodeBlock` and a conservative `detect_code_language` (`markdown_layout/classify.rs`) called from `flush_code`: JSON (brace/bracket opener + quoted keys), C/C++ (≥2 of `#include`/`std::`/`int main`/`nullptr`/`->`/`::`/`template<`), Python (≥2 keyword/f-string/`self.`/comprehension signals, or ≥1 plus a colon-terminated control line). Returns `None` (bare fence) when unsure, so docs with other-language tests can't be mis-tagged. Emitter writes the info-string after the fence (` ```python `).
>
> **Win is python-only.** `text_misc__justcode` now emits four ` ```python ` blocks whose bodies contain the rule snippets (whitespace-normalized match tolerates lost indentation) → 5/5 on that doc. The other 5 tests are **detection-layer gaps, out of scope for the tag**: `text_misc__json` / `text_simple__paper` (cpp) never emit code blocks at all because their content isn't flagged `all_mono` upstream; `text_ocr__code` (fortran) is OCR-gated; `text_simple__hex` has a junk language string (`mki@mki:~/...>`). The overall `text_formatting` `avg_rule_pass_rate` read 0.3683 vs the 0.371 reference — within documented recorded-score/binary drift, **not a regression**: the change is strictly additive (only appends a language word to ` ``` ` fences in code-block docs), so the thousands of `is_title`/`is_bold`/`is_italic` tests on non-code docs are byte-identical. 204 lib tests pass (1 new: `detect_code_language_classifies_common_langs`). No olmOCR/opendataloader impact (code blocks ~absent there).
diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rs
index e56261a..1035fbe 100644
--- a/crates/liteparse/src/markdown_layout/tables.rs
+++ b/crates/liteparse/src/markdown_layout/tables.rs
@@ -369,7 +369,12 @@ fn infer_tracks_from_raw_items(lines: &[ProjectedLine], start_idx: usize) -> Vec
rows_used += 1;
}
xs.sort_by(f32::total_cmp);
- let mut clusters: Vec<f32> = Vec::new();
+ // Each cluster carries its support = how many raw item x's fell into it.
+ // A genuine column recurs once per body row, so its support ≈ the row
+ // count; a header line sitting a few points off the data anchor (a
+ // centered "Number of" above a right-aligned numeric column) injects a
+ // separate cluster supported by a single item.
+ let mut clusters: Vec<(f32, usize)> = Vec::new();
let mut current_sum = 0.0f32;
let mut current_count = 0usize;
let mut current_anchor = f32::NEG_INFINITY;
@@ -379,16 +384,27 @@ fn infer_tracks_from_raw_items(lines: &[ProjectedLine], start_idx: usize) -> Vec
current_count += 1;
current_anchor = current_sum / current_count as f32;
} else {
- clusters.push(current_sum / current_count as f32);
+ clusters.push((current_sum / current_count as f32, current_count));
current_sum = x;
current_count = 1;
current_anchor = x;
}
}
if current_count > 0 {
- clusters.push(current_sum / current_count as f32);
+ clusters.push((current_sum / current_count as f32, current_count));
}
- clusters
+ // Prune single-item phantom tracks when there is a clear multi-row body
+ // (some cluster supported by ≥3 items). Without this, header cells offset
+ // from their data column manufacture extra close-spaced tracks that
+ // collapse `min_gap` and force the inferred path to bail, dropping back to
+ // the header-seeded path that silently discards an unaligned column.
+ // Conservative: only prunes when a strong body signal exists, and only the
+ // weakest (single-item) clusters, so small/sparse tables are untouched.
+ let max_support = clusters.iter().map(|c| c.1).max().unwrap_or(0);
+ if max_support >= 3 {
+ clusters.retain(|c| c.1 >= 2);
+ }
+ clusters.into_iter().map(|c| c.0).collect()
}
/// Build a row's cells against a fixed set of column anchors. Each raw item
@@ -731,39 +747,63 @@ fn try_detect_table_inferred(
// shred-on-whitespace seed that's indistinguishable from a real
// table. Subsequent rows can still have merged spans recovered via
// the multi-cover split path.
+ //
+ // The strong row need not be `start_idx` itself: a stacked or partial
+ // header (a centered "Number of" above a right-aligned numeric column,
+ // fewer cells than the body) legitimately leads the table. Scan forward
+ // for the first strong row and seed the body there; `finalize_table_run`
+ // absorbs the header lines above it. Without this the body would be seeded
+ // on the header, the run would break at the first unalignable header cell,
+ // and the table would fall to the header-seeded path that drops a column.
let tol = TABLE_TRACK_TOLERANCE_PT;
- let seed_spans: Vec<&TextItem> = lines[start_idx]
- .spans
- .iter()
- .filter(|s| !s.text.trim().is_empty())
- .collect();
- if seed_spans.len() < tracks.len() {
- bail!("seed_spans {} < tracks {}", seed_spans.len(), tracks.len());
- }
- for s in &seed_spans {
- let x0 = s.x;
- let x1 = s.x + s.width.max(0.0);
- let covered = tracks
+ let is_strong_row = |line: &ProjectedLine| -> bool {
+ let spans: Vec<&TextItem> = line
+ .spans
.iter()
- .filter(|&&t| t >= x0 - tol && t <= x1 + tol)
- .count();
- if covered > 1 {
- bail!(
- "seed span \"{:.20}\" covers {covered} tracks",
- s.text.trim()
- );
+ .filter(|s| !s.text.trim().is_empty())
+ .collect();
+ if spans.len() < tracks.len() {
+ return false;
+ }
+ spans.iter().all(|s| {
+ let x0 = s.x;
+ let x1 = s.x + s.width.max(0.0);
+ tracks
+ .iter()
+ .filter(|&&t| t >= x0 - tol && t <= x1 + tol)
+ .count()
+ == 1
+ })
+ };
+ let mut body_start = None;
+ {
+ let mut k = start_idx;
+ let mut used = 0;
+ while k < lines.len() && used < TABLE_TRACK_INFERENCE_MAX_ROWS {
+ if k > start_idx && !table_rows_adjacent(&lines[k - 1], &lines[k]) {
+ break;
+ }
+ if is_strong_row(&lines[k]) {
+ body_start = Some(k);
+ break;
+ }
+ k += 1;
+ used += 1;
}
}
- let Some(first) = cells_from_raw_items_with_tracks(&lines[start_idx], &tracks) else {
- bail!("seed row cells unassignable");
+ let Some(body_start) = body_start else {
+ bail!("no strong body row in window");
+ };
+ let Some(first) = cells_from_raw_items_with_tracks(&lines[body_start], &tracks) else {
+ bail!("body row cells unassignable");
};
if first.iter().filter(|c| !c.text.is_empty()).count() < TABLE_MIN_COLUMNS {
- bail!("seed populated cells < MIN_COLUMNS");
+ bail!("body populated cells < MIN_COLUMNS");
}
let mut rows: Vec<(usize, &ProjectedLine, Vec<TableCell>)> =
- vec![(start_idx, &lines[start_idx], first)];
+ vec![(body_start, &lines[body_start], first)];
- let mut j = start_idx + 1;
+ let mut j = body_start + 1;
while j < lines.len() {
if lines[j].bbox.x > tracks_right_edge {
j += 1;
@@ -795,6 +835,16 @@ fn try_detect_table_inferred(
if rows.len() < TABLE_MIN_ROWS {
bail!("rows {} < MIN_ROWS", rows.len());
}
+ // When the body was seeded below `start_idx` (the lead line was a header
+ // we skipped over to find a strong row), demand a clearly multi-row body
+ // before committing. A strong row found inside a header band can otherwise
+ // anchor a 2-row pseudo-table that consumes the lead lines and starves the
+ // header-seeded path of the real table below it (doc 117/187 lost their
+ // tables this way). Already-strong seeds (body_start == start_idx) keep the
+ // standard MIN_ROWS threshold and are unaffected.
+ if body_start > start_idx && rows.len() < 3 {
+ bail!("advanced body_start but only {} rows", rows.len());
+ }
let cv = row_spacing_cv(&rows);
if cv > TABLE_ROW_SPACING_MAX_CV {
// Defer to the existing path, which can fall back to GridFallback.
@@ -805,7 +855,7 @@ fn try_detect_table_inferred(
let bold_eligible = rows[0].2.iter().all(|c| c.bold && !c.text.is_empty());
finalize_table_run(
lines,
- start_idx,
+ body_start,
floor,
&rows,
&track_ranges,
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index bae0ace..e33d33d 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -727,6 +727,35 @@ fn form_lines(
let y_diff = (item.item.y - prev.item.y).abs();
let y_compatible = y_diff <= 1.5;
+ // Decimal-fragment continuation: PDFium sometimes emits the
+ // fractional part of a number ("15.6", "200.4") as a separate,
+ // x-contiguous run beginning with the decimal point (".6").
+ // `both_are_numbers` below treats them as two distinct table
+ // values and keeps them apart, leaving "15 .6" in the rendered
+ // cell and injecting a spurious column track between them. A
+ // real pair of adjacent table numbers always has a visible
+ // inter-cell gap, never a digit butted directly against a
+ // leading-decimal run, so this is safe to join silently.
+ let is_decimal_continuation = y_compatible
+ && delta_x <= 1.0
+ && delta_x >= -2.0
+ && prev
+ .item
+ .text
+ .chars()
+ .last()
+ .is_some_and(|c| c.is_ascii_digit())
+ && {
+ let mut cs = item.item.text.chars();
+ cs.next() == Some('.') && cs.next().is_some_and(|c| c.is_ascii_digit())
+ };
+ if is_decimal_continuation {
+ prev.item.width = item.item.x + item.item.width - prev.item.x;
+ prev.item.text.push_str(&item.item.text);
+ merge_orig_bbox(prev, &item);
+ continue;
+ }
+
// Word-boundary guard: when prev ends with an alphabetic
// character and item starts with one, a positive delta_x is
// very likely a missing-space gap (PDFium omitted the space