Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewichd40fd17c9196
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index bb467dd..a528d56 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -458,12 +458,10 @@ fn extract_page_text_items(
let debug = std::env::var("LITEPARSE_DEBUG").is_ok();
let dbg_gaps = std::env::var("LITEPARSE_DEBUG_GAPS").is_ok();
- let space_fix = std::env::var("LITEPARSE_NO_SPACE_FIX").is_err();
// Empirical per-font space calibration: for fonts that expose no
// space-glyph metric, recover the genuine inter-word gap from the spaces
// PDFium *does* emit for that font (normalized by rendered em height) and
// feed it through the same threshold rule the metric path uses.
- let space_cal = std::env::var("LITEPARSE_NO_SPACE_CAL").is_err();
let mut font_space_cal: std::collections::HashMap<String, Vec<f32>> =
std::collections::HashMap::new();
@@ -643,9 +641,9 @@ fn extract_page_text_items(
// are spaced apart, unlike periods in abbreviations like "U.S.").
// A loosely-kerned abbreviation/sentence period sits at ~1x the
// average char width; genuine no-space dot leaders run far wider
- // (2x+). The earlier 0.4x cutoff sheared the trailing period off
- // abbreviations like "Sci."/"Chem." whenever the font kerned the
- // period a hair loose, dropping it entirely downstream.
+ // (2x+). The 2x cutoff avoids shearing the trailing period off
+ // abbreviations like "Sci."/"Chem." when the font kerns the
+ // period a hair loose, which would drop it entirely downstream.
c == '.' && seg.has_non_dot_content() && gap > seg.avg_char_width() * 2.0
};
@@ -694,21 +692,19 @@ fn extract_page_text_items(
// Genuine inline space PDFium emitted: sample its size
// (loose gap / em height) per font, alpha-alpha only, to
// calibrate the no-space-metric recovery below.
- if space_cal {
- if let Some(fk) = seg.font_name.as_ref() {
- let prev_alnum = seg
- .text
- .chars()
- .last()
- .is_some_and(|p| p.is_ascii_alphanumeric());
- if prev_alnum && c.is_ascii_alphanumeric() {
- let em_vp = (vp_loose.bottom - vp_loose.top).abs();
- let loose_gap = vp_strict.left - seg.last_char_loose_right;
- if em_vp > 0.0 && loose_gap > 0.0 {
- let s = font_space_cal.entry(fk.clone()).or_default();
- if s.len() < 512 {
- s.push(loose_gap / em_vp);
- }
+ if let Some(fk) = seg.font_name.as_ref() {
+ let prev_alnum = seg
+ .text
+ .chars()
+ .last()
+ .is_some_and(|p| p.is_ascii_alphanumeric());
+ if prev_alnum && c.is_ascii_alphanumeric() {
+ let em_vp = (vp_loose.bottom - vp_loose.top).abs();
+ let loose_gap = vp_strict.left - seg.last_char_loose_right;
+ if em_vp > 0.0 && loose_gap > 0.0 {
+ let s = font_space_cal.entry(fk.clone()).or_default();
+ if s.len() < 512 {
+ s.push(loose_gap / em_vp);
}
}
}
@@ -744,19 +740,16 @@ fn extract_page_text_items(
// em height) run through the same 0.7 factor as the metric
// path; fall back to a fixed em fraction when we lack
// enough samples for the font.
- let calibrated = if space_cal {
- seg.font_name
- .as_ref()
- .and_then(|fk| font_space_cal.get(fk))
- .filter(|s| s.len() >= MIN_SPACE_CAL_SAMPLES)
- .and_then(|s| median_f32(s))
- .map(|ratio| 0.7 * ratio * em_vp)
- } else {
- None
- };
+ let calibrated = seg
+ .font_name
+ .as_ref()
+ .and_then(|fk| font_space_cal.get(fk))
+ .filter(|s| s.len() >= MIN_SPACE_CAL_SAMPLES)
+ .and_then(|s| median_f32(s))
+ .map(|ratio| 0.7 * ratio * em_vp);
calibrated.unwrap_or(0.35 * em_vp)
};
- if space_fix && both_alnum && thresh > 0.0 && loose_gap > thresh {
+ if both_alnum && thresh > 0.0 && loose_gap > thresh {
seg.text.push(' ');
}
seg.push_char(c, &vp_loose, &vp_strict, &ch);
@@ -777,14 +770,12 @@ fn extract_page_text_items(
let vb_w = (view_box.right - view_box.left).abs();
let vb_h = (view_box.top - view_box.bottom).abs();
let pre_clip_count = items.len();
- if std::env::var("LITEPARSE_DISABLE_OFFPAGE_CLIP").is_err() {
- items.retain(|it| {
- it.x < vb_w
- && it.x + it.width.max(0.1) > 0.0
- && it.y < vb_h
- && it.y + it.height.max(0.1) > 0.0
- });
- }
+ items.retain(|it| {
+ it.x < vb_w
+ && it.x + it.width.max(0.1) > 0.0
+ && it.y < vb_h
+ && it.y + it.height.max(0.1) > 0.0
+ });
if debug && items.len() < pre_clip_count {
eprintln!(
"[extract-debug] off-page clip removed {} items",
@@ -851,21 +842,12 @@ fn dedup_overlapping_items(items: &mut Vec<TextItem>, debug: bool) {
if items[i].text == items[j].text {
// Exact text match: require strong bounding-box overlap before
- // dedup. Originally this fired on *any* overlap on the theory
- // that overlapping identical text is two layers of the same
- // content (re-stamped redactions, etc). But the same word
- // routinely appears more than once on a page in different
- // positions; if the items' bboxes happen to share even a sliver
- // of area (e.g. one column's word vertically adjacent to
- // another column's identical word with a slack loose-box), we
- // were silently dropping the legitimate first occurrence.
- //
- // Reproducer: olmocr 0083fb21…page_8 — column 1 has the word
- // "source" in row 2 and again in row 3; the dedup nuked the
- // row 2 "source" in favor of the row 3 one (which later merged
- // into "source income is reduced (the"), making the row 2
- // sentence read as "made to U.S. \n . In situations…" with
- // "source income" missing.
+ // dedup. The same word routinely appears more than once on a
+ // page in different positions; firing on any overlap would drop
+ // a legitimate occurrence when two identical words' bboxes share
+ // even a sliver of area (e.g. one column's word vertically
+ // adjacent to another column's identical word with a slack
+ // loose-box), corrupting that line.
//
// Require ≥50% overlap of the smaller item — same threshold
// as the non-exact branch. True duplicate stamps overlap
@@ -1036,8 +1018,6 @@ struct GlyphDecoder {
/// fraction of control/PUA unicodes across the page).
garbage_fonts: std::collections::HashSet<usize>,
debug: bool,
- /// Kill-switch for A/B benching: LITEPARSE_DISABLE_GLYPH_NAMES=1
- disabled: bool,
}
struct FontGlyphInfo {
@@ -1061,7 +1041,6 @@ impl GlyphDecoder {
last_obj: 0,
last_key: 0,
debug,
- disabled: std::env::var("LITEPARSE_DISABLE_GLYPH_NAMES").is_ok(),
}
}
@@ -1069,9 +1048,6 @@ impl GlyphDecoder {
/// and the current unicode is suspicious (control/PUA/sentinel/map-error)
/// or the font's unicode mapping is untrusted altogether.
fn decode(&mut self, ch: &pdfium::TextChar, unicode: u32) -> Option<&str> {
- if self.disabled {
- return None;
- }
let cheap_suspicious = matches!(unicode, 0 | 0xFFFE | 0xFFFF)
|| (unicode < 0x20 && !matches!(unicode, 0x09 | 0x0A | 0x0D))
|| (0xE000..=0xF8FF).contains(&unicode);
diff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rs
index 62a007d..7453618 100644
--- a/crates/liteparse/src/markdown_layout/classify.rs
+++ b/crates/liteparse/src/markdown_layout/classify.rs
@@ -156,78 +156,73 @@ pub fn classify_page_with_filters(
// mostly-empty. Run it once over all lines, pull the consumed lines out of
// the region pipeline, and emit each table as a y-positioned interruption.
// Runs before cross-region merge so that pass (and the region indices its
- // runs carry) operate on the already-filtered line list. Disable with
- // LITEPARSE_DISABLE_GLOBAL_RULED=1.
+ // runs carry) operate on the already-filtered line list.
let mut global_ruled_tables: Vec<(f32, Block)> = Vec::new();
let mut global_ruled_consumed: std::collections::HashSet<usize> =
std::collections::HashSet::new();
- if !*super::flags::DISABLE_GLOBAL_RULED {
- for (run, consumed) in super::tables::detect_ruled_tables_global(
- lines,
- &page.graphics,
- page.page_width,
- page.page_height,
- ) {
- // Only rescue tables the per-region path can't see whole: those
- // whose rows scatter across ≥2 xy_cut leaves. A table living in a
- // single region is already handled (often better) by per-region
- // detection — replacing it here only risks regressions.
- let mut groups: std::collections::HashMap<&Vec<u16>, Vec<usize>> =
- std::collections::HashMap::new();
- for &i in &consumed {
- groups.entry(&lines[i].region_path).or_default().push(i);
- }
- if groups.len() < 2 {
- continue;
+ for (run, consumed) in super::tables::detect_ruled_tables_global(
+ lines,
+ &page.graphics,
+ page.page_width,
+ page.page_height,
+ ) {
+ // Only rescue tables the per-region path can't see whole: those
+ // whose rows scatter across ≥2 xy_cut leaves. A table living in a
+ // single region is already handled (often better) by per-region
+ // detection — replacing it here only risks regressions.
+ let mut groups: std::collections::HashMap<&Vec<u16>, Vec<usize>> =
+ std::collections::HashMap::new();
+ for &i in &consumed {
+ groups.entry(&lines[i].region_path).or_default().push(i);
+ }
+ if groups.len() < 2 {
+ continue;
+ }
+ // If any single leaf's share of these lines already forms a table
+ // on its own, the per-region path handles this content — don't
+ // override (a decorative frame can span a data table plus surrounding
+ // prose; the data region tables cleanly by itself, while the frame
+ // would fuse prose into garbage cells).
+ let already_handled = groups.values().any(|idxs| {
+ if idxs.len() < 2 {
+ return false;
}
- // If any single leaf's share of these lines already forms a table
- // on its own, the per-region path handles this content — don't
- // override (e.g. doc 127: a decorative frame spans the data table
- // plus surrounding prose; the data region tables cleanly by
- // itself, the frame would fuse prose into garbage cells).
- let already_handled = groups.values().any(|idxs| {
- if idxs.len() < 2 {
- return false;
- }
- let sub: Vec<ProjectedLine> = idxs.iter().map(|&i| lines[i].clone()).collect();
- !super::tables::detect_ruled_tables(
- &sub,
- &page.graphics,
- page.page_width,
- page.page_height,
- )
- .is_empty()
- || !super::tables::detect_tables(&sub).is_empty()
- });
- if already_handled {
+ let sub: Vec<ProjectedLine> = idxs.iter().map(|&i| lines[i].clone()).collect();
+ !super::tables::detect_ruled_tables(
+ &sub,
+ &page.graphics,
+ page.page_width,
+ page.page_height,
+ )
+ .is_empty()
+ || !super::tables::detect_tables(&sub).is_empty()
+ });
+ if already_handled {
+ continue;
+ }
+ // Single-column gate. A decorative banner/frame around a prose
+ // column (just a left+right border, no interior verticals) unions
+ // into a 1-column "grid" whose lone cell is the whole paragraph
+ // block. A real data table always has ≥2 columns; a 1-col ruled
+ // region is a framed text box, never tabular. Word-count gating can't
+ // be used here: genuine scattered description grids have equally long
+ // cells.
+ if let Block::Table { header, rows } = &run.block {
+ let cols = header
+ .as_ref()
+ .map(|h| h.len())
+ .or_else(|| rows.first().map(Vec::len))
+ .unwrap_or(0);
+ if cols < 2 {
continue;
}
- // Single-column gate. A decorative banner/frame around a prose
- // column (just a left+right border, no interior verticals) unions
- // into a 1-column "grid" whose lone cell is the whole paragraph
- // block. A real data table always has ≥2 columns; a 1-col ruled
- // region is a framed text box, never tabular. (Catches docs 028649
- // and 06ba2a90 — both emitted a 1-col table of paragraph blobs.
- // Word-count gating can't be used here: the genuine scattered
- // tables this pass rescues on opendataloader — competence/legal
- // description grids — have equally long cells.)
- if let Block::Table { header, rows } = &run.block {
- let cols = header
- .as_ref()
- .map(|h| h.len())
- .or_else(|| rows.first().map(Vec::len))
- .unwrap_or(0);
- if cols < 2 {
- continue;
- }
- }
- let top_y = consumed
- .iter()
- .map(|&i| lines[i].bbox.y)
- .fold(f32::INFINITY, f32::min);
- global_ruled_tables.push((top_y, run.block));
- global_ruled_consumed.extend(consumed);
}
+ let top_y = consumed
+ .iter()
+ .map(|&i| lines[i].bbox.y)
+ .fold(f32::INFINITY, f32::min);
+ global_ruled_tables.push((top_y, run.block));
+ global_ruled_consumed.extend(consumed);
}
let global_ruled_owned: Option<Vec<ProjectedLine>> = if global_ruled_consumed.is_empty() {
None
@@ -275,10 +270,10 @@ pub fn classify_page_with_filters(
// leaf as its own mini-page. Paragraph / list / code / heading state is
// scoped per leaf so a column-wrap can't silently fuse two leaves into one
// paragraph, and table detection runs per-leaf so a misfired borderless
- // table can't consume lines from a different leaf (the dominant Mode 15
- // cause: a spurious table starting in one column's footnote area was
- // eating the first lines of the next column, dropping those words from
- // any block). Cross-leaf merges happen only in `stitch_regions` at the
+ // table can't consume lines from a different leaf (otherwise a spurious
+ // table starting in one column's footnote area eats the first lines of the
+ // next column, dropping those words from any block). Cross-leaf merges
+ // happen only in `stitch_regions` at the
// end, where the rule is explicit and inspectable.
let mut region_ranges: Vec<(usize, usize)> = Vec::new();
{
@@ -397,10 +392,9 @@ pub fn classify_page_with_filters(
/// Mutable per-line flow state threaded through `classify_region`: the active
/// paragraph accumulator, the active code run, and the current list run. The
-/// flush/reset/emit methods live here so the (previously 8-parameter) closures
-/// and the six copy-pasted "reset list state" blocks collapse to method calls;
-/// methods on the struct also sidestep the borrow-checker friction of threading
-/// five `&mut Option<…>` cells through a free closure.
+/// flush/reset/emit methods live here so list-state resets collapse to method
+/// calls; methods on the struct also sidestep the borrow-checker friction of
+/// threading five `&mut Option<…>` cells through a free closure.
#[derive(Default)]
struct FlowState {
paragraph: Option<ParaAccum>,
@@ -593,8 +587,9 @@ fn classify_region(
let toc_suppress = toc_page && !is_first_toc_title;
// Outline entries on a TOC page are the TOC itself — every entry
// prefix-matches an outline target ("Introduction", "Part I", ...).
- // Promoting them to `##` shreds the GT MHS structure (which has just
- // `# Contents`). Tagged-PDF struct levels are explicit and still win.
+ // Promoting them to `##` shreds the document's heading structure (a
+ // TOC page is just `# Contents`). Tagged-PDF struct levels are explicit
+ // and still win.
let outline_level = tagged_level.or_else(|| {
if toc_suppress {
None
@@ -623,8 +618,7 @@ fn classify_region(
// A previous line ending in a mid-word hyphen wrap means this
// line is its continuation regardless of capitalization
// ("…SOLAR 10.7 Billion-" / "Parameter Model: We have…").
- let prev_hyphen_wrap = !*super::flags::DISABLE_HEADING_GUARDS
- && prev.is_some_and(|p| ends_hyphenated(&p.text));
+ let prev_hyphen_wrap = prev.is_some_and(|p| ends_hyphenated(&p.text));
!((starts_lower || prev_hyphen_wrap)
&& prev.is_some_and(|p| continues_paragraph(p, line)))
});
@@ -913,7 +907,7 @@ fn classify_region(
/// info-string. Conservative: returns `Some` only when the body carries
/// strong, language-specific signals; otherwise `None` (bare fence). This
/// feeds markdown consumers that key off the language tag (e.g. syntax
-/// highlighting, ParseBench's `is_code_block` rule).
+/// highlighting).
fn detect_code_language(lines: &[String]) -> Option<String> {
let body = lines.join("\n");
let trimmed = body.trim_start();
@@ -981,18 +975,18 @@ fn detect_code_language(lines: &[String]) -> Option<String> {
/// - **Paragraph → Paragraph**: same cross-region rule as
/// `continues_paragraph`'s `region_path != region_path` arm: the previous
/// paragraph ends mid-sentence (no terminal punctuation) and the next
-/// starts lowercase. Heals the dominant Mode 15 shape (column wrap losing
-/// its tail to a separate block).
+/// starts lowercase. Heals a column wrap losing its tail to a separate
+/// block.
/// - **Hyphen splice**: previous paragraph ends `<letter>-` and next starts
/// ASCII-lowercase. Already handled in `render_blocks` for the adjacent
/// case, but doing it here too lets the merged block flow through the
/// uniform paragraph-rendering path and avoids a `\n\n` slipping in when
/// the renderer sees an intervening non-paragraph block.
///
-/// Lists, code blocks, headings, and tables are *not* fused across regions
-/// in v1. A bullet point split across columns is rare and a false merge is
-/// worse than a true split; a table split across leaves indicates a
-/// projection-side issue better fixed there than papered over here.
+/// Lists, code blocks, headings, and tables are *not* fused across regions.
+/// A bullet point split across columns is rare and a false merge is worse
+/// than a true split; a table split across leaves indicates a projection-side
+/// issue better fixed there than papered over here.
fn stitch_regions(blocks: Vec<Block>, region_starts: &[usize]) -> Vec<Block> {
if region_starts.len() <= 1 {
return blocks;
diff --git a/crates/liteparse/src/markdown_layout/cross_region.rs b/crates/liteparse/src/markdown_layout/cross_region.rs
index d67d76f..a0472ce 100644
--- a/crates/liteparse/src/markdown_layout/cross_region.rs
+++ b/crates/liteparse/src/markdown_layout/cross_region.rs
@@ -415,9 +415,6 @@ fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Opti
/// Callers may re-invoke on the spliced result to catch multiple sliced
/// tables per page.
pub(super) fn find_cross_region_table_merge(lines: &[ProjectedLine]) -> Option<CrossRegionMerge> {
- if *super::flags::DISABLE_CROSS_REGION_TABLES {
- return None;
- }
let debug = *super::flags::DEBUG_CROSS_REGION;
let leaves = build_leaves(lines);
if debug {
@@ -463,7 +460,7 @@ pub(super) fn find_cross_region_table_merge(lines: &[ProjectedLine]) -> Option<C
// Extend the pair to every leaf living inside the overlap band and
// entirely on one side of the cut (a side may itself be H-cut into
- // multiple leaves — doc 146's Area column is).
+ // multiple leaves).
let mut set_leaves: Vec<usize> = Vec::new();
for (k, leaf) in leaves.iter().enumerate() {
let leaf_h = (leaf.y1 - leaf.y0).max(1.0);
diff --git a/crates/liteparse/src/markdown_layout/flags.rs b/crates/liteparse/src/markdown_layout/flags.rs
index 7dc61d6..3fdab7e 100644
--- a/crates/liteparse/src/markdown_layout/flags.rs
+++ b/crates/liteparse/src/markdown_layout/flags.rs
@@ -1,10 +1,8 @@
-//! Process-wide debug / kill-switch flags, read once from the environment.
+//! Debug-logging flags, read once from the environment.
//!
-//! Each flag mirrors a `LITEPARSE_*` env var. `env::var` scans the process
-//! environment table and allocates on a miss, so per-line hot paths cache the
-//! lookup in a `LazyLock` instead of re-reading on every call. Each static is
-//! `true` when the variable is **set** (matching the historical
-//! `env::var(..).is_ok()`); "disable" call sites negate it.
+//! Each flag mirrors a `LITEPARSE_*` env var and is `true` when the variable is
+//! set. `env::var` allocates on every call, so these cache the lookup in a
+//! `LazyLock` rather than re-reading on per-line hot paths.
use std::sync::LazyLock;
@@ -20,11 +18,3 @@ env_set_flag!(DEBUG_MD, "LITEPARSE_DEBUG_MD");
env_set_flag!(DEBUG_TABLE, "LITEPARSE_DEBUG_TABLE");
env_set_flag!(DEBUG_RULED, "LITEPARSE_DEBUG_RULED");
env_set_flag!(DEBUG_CROSS_REGION, "LITEPARSE_DEBUG_CROSS_REGION");
-env_set_flag!(DISABLE_GLOBAL_RULED, "LITEPARSE_DISABLE_GLOBAL_RULED");
-env_set_flag!(DISABLE_HEADING_GUARDS, "LITEPARSE_DISABLE_HEADING_GUARDS");
-env_set_flag!(
- DISABLE_CROSS_REGION_TABLES,
- "LITEPARSE_DISABLE_CROSS_REGION_TABLES"
-);
-env_set_flag!(DISABLE_CLUSTER_MERGE, "LITEPARSE_DISABLE_CLUSTER_MERGE");
-env_set_flag!(DISABLE_STRADDLE_GUARD, "LITEPARSE_DISABLE_STRADDLE_GUARD");
diff --git a/crates/liteparse/src/markdown_layout/headings.rs b/crates/liteparse/src/markdown_layout/headings.rs
index d8b15c9..79ebfaf 100644
--- a/crates/liteparse/src/markdown_layout/headings.rs
+++ b/crates/liteparse/src/markdown_layout/headings.rs
@@ -383,11 +383,10 @@ pub(super) fn looks_like_bold_heading(
// - ≥3 space-separated words after the break
// - line ends with mid-word "-" (wrap continuation) OR is >50 chars
// - first char after the break is uppercase ASCII letter
- let colon_ok = !*super::flags::DISABLE_HEADING_GUARDS;
let run_in_break = text
.find(". ")
.map(|p| (p, 2))
- .or_else(|| text.find(": ").map(|p| (p, 2)).filter(|_| colon_ok));
+ .or_else(|| text.find(": ").map(|p| (p, 2)));
if let Some((pos, sep_len)) = run_in_break {
let before = &text[..pos];
// Section-number prefix exemption: when the segment before ". " is a
diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rs
index ab90f07..b3a39a6 100644
--- a/crates/liteparse/src/markdown_layout/inline.rs
+++ b/crates/liteparse/src/markdown_layout/inline.rs
@@ -27,8 +27,7 @@ impl SpanStyle {
/// Escape characters that would otherwise be interpreted as markdown emphasis.
/// Deliberately narrow: only `*`, `_`, and backslash. Aggressive escaping
-/// (`#`, `[`, backticks, etc.) breaks more output than it saves in practice —
-/// pymupdf4llm takes the same conservative stance.
+/// (`#`, `[`, backticks, etc.) breaks more output than it saves in practice.
pub(super) fn escape_inline(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
@@ -81,8 +80,7 @@ fn apply_style(inner: &str, style: SpanStyle) -> String {
///
/// Per-line shortcut: when every non-whitespace span shares the same style,
/// emit one outer wrap around the collapsed line text instead of run-by-run
-/// (matches pymupdf4llm; avoids `**foo** **bar** **baz**` noise on uniformly
-/// styled lines).
+/// (avoids `**foo** **bar** **baz**` noise on uniformly styled lines).
///
/// Falls back to `collapse_whitespace(line.text)` when the line has no usable
/// spans (e.g. OCR-only lines where TextItem styling isn't populated).
diff --git a/crates/liteparse/src/markdown_layout/paragraphs.rs b/crates/liteparse/src/markdown_layout/paragraphs.rs
index 768f048..09a2d65 100644
--- a/crates/liteparse/src/markdown_layout/paragraphs.rs
+++ b/crates/liteparse/src/markdown_layout/paragraphs.rs
@@ -223,7 +223,7 @@ pub(super) fn continues_paragraph(prev: &ProjectedLine, cur: &ProjectedLine) ->
/// - `raw` — plain text (no emphasis markers). Used for the paragraph-uniform
/// shortcut: if every contributing line had the same uniform style, we wrap
/// the whole paragraph once with `wrap_emphasis(raw, …)` to avoid the
-/// `**foo** **bar** **baz**` per-line noise pymupdf4llm warns about.
+/// `**foo** **bar** **baz**` per-line noise.
/// - `inline` — per-line markdown with emphasis baked in via
/// `render_line_inline`. Used when the paragraph contains mid-line emphasis
/// shifts or lines with differing uniform styles.
diff --git a/crates/liteparse/src/markdown_layout/repetition.rs b/crates/liteparse/src/markdown_layout/repetition.rs
index 5e11bdb..273ba64 100644
--- a/crates/liteparse/src/markdown_layout/repetition.rs
+++ b/crates/liteparse/src/markdown_layout/repetition.rs
@@ -488,7 +488,7 @@ mod tests {
#[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.
+ // hint, and font-size delta alone is not a chrome signal.
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),
diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rs
index 1035fbe..1c54bfa 100644
--- a/crates/liteparse/src/markdown_layout/tables.rs
+++ b/crates/liteparse/src/markdown_layout/tables.rs
@@ -266,9 +266,8 @@ fn row_spacing_cv(rows: &[(usize, &ProjectedLine, Vec<TableCell>)]) -> f32 {
/// - 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.
+/// Accepting any of these (rather than start_x alone) 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;
@@ -839,8 +838,8 @@ fn try_detect_table_inferred(
// 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
+ // header-seeded path of the real table below it. 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());
@@ -919,8 +918,8 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
// 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
+ // (c) break-run. Order matters — the wrap path runs first so
+ // tightly-stacked continuation baselines fold into the prior row; 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() {
@@ -944,9 +943,9 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
// 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).
+ // the missing tracks. This catches a sparse data row following a
+ // wide header (e.g. `"1.0 April 30, Original"` under a 5-column
+ // header), which a naive wrap path would merge into the header.
if all_align_track
&& cells.len() >= 2
&& bottom_gap >= line_height * TABLE_SPARSE_ROW_MIN_BOTTOM_GAP_FRAC
@@ -1046,8 +1045,8 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
}
// Promote the first body row to header iff every cell in it is bold
- // (matches pymupdf4llm's "bold-or-filled" heuristic; fills require fork
- // data). Skipped inside `finalize_table_run` when a header was absorbed.
+ // (a bold-or-filled heuristic; fills require fork data). Skipped inside
+ // `finalize_table_run` when a header was absorbed.
let bold_eligible = rows[0].2.iter().all(|c| c.bold);
finalize_table_run(
lines,
@@ -1435,10 +1434,9 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
}
// 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.
+ // *not* description-list tables: TOC entries (col 1 = page number) and
+ // footnote lists (col 0 = footnote number). 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())
});
@@ -1601,7 +1599,7 @@ const TABLE_CLUSTER_MAX_FAILED_ROW_FRAC: f32 = 0.3;
const TABLE_CLUSTER_MAX_HEADER_LINES: usize = 4;
fn merge_fragmented_table_clusters(runs: Vec<TableRun>, lines: &[ProjectedLine]) -> Vec<TableRun> {
- if runs.len() < 2 || *super::flags::DISABLE_CLUSTER_MERGE {
+ if runs.len() < 2 {
return runs;
}
let dbgt = *super::flags::DEBUG_TABLE;
@@ -1975,12 +1973,12 @@ fn build_union_table(
}
// NOTE: no vertical wrap-merge here. Gap-based merging of multi-line
- // cells was tried and reverted — inside uniformly-leaded tables the gap
- // between a wrapped cell line and a genuine next row is identical, so
- // any threshold either shreds multi-line cells (no merge) or fuses
- // adjacent logical rows (merge). Re-extracted clusters keep one row per
- // line; multi-line-cell recovery needs a stronger signal (ruled-grid row
- // boundaries, or label-column row anchoring).
+ // cells doesn't work — inside uniformly-leaded tables the gap between a
+ // wrapped cell line and a genuine next row is identical, so any threshold
+ // either shreds multi-line cells (no merge) or fuses adjacent logical rows
+ // (merge). Re-extracted clusters keep one row per line; multi-line-cell
+ // recovery needs a stronger signal (ruled-grid row boundaries, or
+ // label-column row anchoring).
let mut rows: Vec<Vec<String>> = Vec::new();
let mut failed_count = 0usize;
for line in &lines[window_start..window_end] {
@@ -2363,11 +2361,11 @@ const TABLE_CROSS_TOLERANCE_PT: f32 = 3.0;
const TABLE_COL_BOUNDARY_CLUSTER_PT: f32 = 6.0;
/// Reject ruled-table candidates whose empty-cell fraction exceeds this.
-/// NOTE: this can't be loosened to recover blank worksheets/forms — a real
-/// sparse table (doc 180, a 4-col Version History, ~75% empty) and a spurious
-/// grid from decorative layout boxes (doc 198, a TOC, also ~75% empty) are
-/// indistinguishable on empty-fraction, and relaxing it net-regressed TEDS by
-/// ~0.09 on the bench (more false tables than real forms recovered).
+/// This can't be loosened to recover blank worksheets/forms: a real sparse
+/// table (e.g. a 4-col version history, ~75% empty) and a spurious grid from
+/// decorative layout boxes (e.g. a TOC, also ~75% empty) are indistinguishable
+/// on empty-fraction, and relaxing it surfaces 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
@@ -2700,9 +2698,10 @@ impl CellGrid {
.collect();
}
- /// Drop "phantom rows" produced by stacked thin border-strip rects (doc 149
- /// rules each visual row as top-strip ~1pt / body ~22pt / bottom-strip ~5pt,
- /// each surviving the 2pt clustering as its own grid row). A row is dropped
+ /// Drop "phantom rows" produced by stacked thin border-strip rects (some
+ /// generators rule each visual row as top-strip ~1pt / body ~22pt /
+ /// bottom-strip ~5pt, each surviving the 2pt clustering as its own grid
+ /// row). A row is dropped
/// iff it has no text in any cell AND its height is < 80% of the median
/// non-empty row height — the height gate preserves real fill-in-the-blank
/// forms whose empty body rows are full height. `ys` are the row boundaries
@@ -2737,8 +2736,8 @@ impl CellGrid {
kept_row_heights
}
- /// Mirror `collapse_phantom_rows` on columns: some ruled tables (doc 149)
- /// draw left/right borders as thin strip rects ~5pt wide, which become
+ /// Mirror `collapse_phantom_rows` on columns: some ruled tables draw
+ /// left/right borders as thin strip rects ~5pt wide, which become
/// phantom text-less columns. Drop a column iff it is both empty AND
/// narrower than 30% of the median text-bearing column. `xs` are the column
/// boundaries (length `n_cols + 1`).
@@ -2794,7 +2793,7 @@ fn assign_cells(
// Straddle census: spans that cross an interior column boundary by a
// clear margin on both sides. A real ruled table keeps text inside cells
// (the occasional PDFium merged run aside); decorative slide/layout boxes
- // over flowing prose slice through most runs (doc 198, a TOC slide).
+ // over flowing prose slice through most runs.
const STRADDLE_MARGIN_PT: f32 = 3.0;
let mut span_total = 0usize;
let mut span_straddle = 0usize;
@@ -2937,7 +2936,7 @@ fn assign_cells(
if dbg {
eprintln!("[ruled] straddle {span_straddle}/{span_total} = {straddle_frac:.2}");
}
- if span_total >= 6 && straddle_frac > 0.45 && !*super::flags::DISABLE_STRADDLE_GUARD {
+ if span_total >= 6 && straddle_frac > 0.45 {
if dbg {
eprintln!("[ruled] REJECT straddle-frac {straddle_frac:.2}");
}
@@ -2947,13 +2946,13 @@ fn assign_cells(
Some((grid, consumed_indices))
}
-/// Colspan header-band flattening (Mode 5 / TRM): a sparse top row whose alpha
-/// spanning label covers several columns ("North America" over its
-/// Revenue/Units sub-columns) followed by a dense label row is a stacked
-/// header. Flatten rows `0..=b` from the colspan-semantics (`repl`) grid into
-/// one header row (per-column top-to-bottom join), so each column carries its
-/// full layer chain ("North America Revenue") — that chain is what header-keyed
-/// evals (and readers) need. Returns `(header_row, body_start)` or `None`.
+/// Colspan header-band flattening: a sparse top row whose alpha spanning label
+/// covers several columns ("North America" over its Revenue/Units sub-columns)
+/// followed by a dense label row is a stacked header. Flatten rows `0..=b` from
+/// the colspan-semantics (`repl`) grid into one header row (per-column
+/// top-to-bottom join), so each column carries its full layer chain ("North
+/// America Revenue") — that chain is what header-keyed consumers (and readers)
+/// need. Returns `(header_row, body_start)` or `None`.
fn flatten_header_band(
cells: &[Vec<String>],
cell_has_text: &[Vec<bool>],
@@ -3011,7 +3010,7 @@ fn flatten_header_band(
})
}
-/// Stacked-header merge (Mode 5): some generators rule every text baseline of a
+/// Stacked-header merge: some generators rule every text baseline of a
/// wrapped header cell, slicing one logical header row into several thin sparse
/// rows ("Rated" / "Voltage" / "(VDC)" each in its own band). When the top
/// `k ≥ 2` rows are individually sparse but their union covers most columns AND
@@ -3099,7 +3098,7 @@ fn merge_stacked_header(
/// - **long-prose table**: a large (≥5×3) grid with a bold header band covering
/// ≥3 columns and a dense (≥70%-fill) inner description column — a
/// multi-line legal/reference table whose description wraps over many empty
-/// continuation rows (docs 088/089/090).
+/// continuation rows.
/// - **flattened header**: a fired colspan header flatten is table evidence on
/// par with a spine.
/// With a spine but above the higher WITH_SPINE ceiling, still reject (unless a
@@ -3283,9 +3282,9 @@ fn build_ruled_table(
// Collapse phantom rows (text-less thin border-strip rects) then phantom
// columns (text-less narrow border strips). A real table with one phantom
- // border-strip column (doc 149) drops exactly one; a chart whose vertical
- // grid-lines merged with text data (doc 078) collapses to 1 col and is
- // rejected below, letting the borderless detector handle it.
+ // border-strip column drops exactly one; a chart whose vertical grid-lines
+ // merged with text data collapses to 1 col and is rejected below, letting
+ // the borderless detector handle it.
let kept_row_heights = grid.collapse_phantom_rows(&ys);
let n_rows = grid.n_rows();
if n_rows < 2 {
@@ -3451,7 +3450,7 @@ fn find_bucket(boundaries: &[f32], val: f32) -> Option<usize> {
/// 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
+/// column-major reading order). 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.
@@ -3592,11 +3591,11 @@ fn run_filled_cells(run: &TableRun) -> usize {
/// ranges overlap the ruled run normally wins (path-based geometry is a
/// stronger signal than text-alignment heuristics), with two exceptions:
/// 1. A single-column ruled run yields to a multi-column borderless run
-/// covering the same range (vertical separators may be implicit; doc 078).
+/// covering the same range (vertical separators may be implicit).
/// 2. A sparse ruled run yields to a denser borderless run — decorative
/// vector boxes around titles / callout banners produce ruled "tables"
/// with few filled cells; when a borderless detector finds a much denser
-/// real table in the same region, prefer it (doc 051).
+/// real table in the same region, prefer it.
pub(super) fn merge_table_runs(
mut ruled: Vec<TableRun>,
borderless: Vec<TableRun>,
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 4d8d883..c525918 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -1,12 +1,5 @@
use crate::types::*;
use std::collections::{BTreeMap, HashMap, HashSet};
-use std::sync::LazyLock;
-
-/// Kill-switch for using the matrix-derived `font_height` as the size signal
-/// on matrix-baked-size lines (raw `font_size ≈ 1.0`). When set, fall back to
-/// the legacy char-weighted bbox-height estimate.
-static DISABLE_FONT_HEIGHT_SIZE: LazyLock<bool> =
- LazyLock::new(|| std::env::var("LITEPARSE_DISABLE_FONT_HEIGHT_SIZE").is_ok());
const FLOATING_SPACES: usize = 2;
const COLUMN_SPACES: usize = 4;
@@ -3424,7 +3417,6 @@ fn xy_find_column_cut(
// aligns with a column peak that has strict evidence.
let mut near_starts: Vec<f32> = Vec::new();
let near_gap_floor = gutter_gap * 0.6;
- let disable_rescue = std::env::var("LITEPARSE_DISABLE_NEARSTART_RESCUE").is_ok();
let mut k = 0;
while k < sorted.len() {
let band_y = items[sorted[k]].item.y;
@@ -3497,7 +3489,7 @@ fn xy_find_column_cut(
// prose. Require near-exact agreement with at least 2 strict starts.
let mut rescued = 0usize;
let mut counted_starts: Vec<f32> = line_starts.clone();
- if !near_starts.is_empty() && !disable_rescue {
+ if !near_starts.is_empty() {
const RESCUE_ALIGN_TOL_PT: f32 = 1.5;
for &x in &near_starts {
let support = line_starts
@@ -3563,9 +3555,9 @@ fn xy_find_column_cut(
// body region with ~36 lines split across 2 columns, each peak only
// carries 5–6 line-starts after the histogram spreads them across the
// page width — well under 10. Use `max(line_starts / 6, 4)`: still rules
- // out the tiny indent peaks, but a 2-column region with ~5 lines/peak now
- // qualifies. Capped by the original `XY_COLUMN_MIN_LINES_PER_PEAK` to
- // preserve behavior on large regions.
+ // out the tiny indent peaks, but a 2-column region with ~5 lines/peak
+ // qualifies. Capped by `XY_COLUMN_MIN_LINES_PER_PEAK` so large regions
+ // keep the stricter floor.
let adaptive_min = (n_starts / 6).clamp(4, XY_COLUMN_MIN_LINES_PER_PEAK);
peaks.retain(|(_, c)| *c >= adaptive_min);
if peaks.len() < 2 {
@@ -3708,9 +3700,7 @@ fn xy_find_column_cut(
// 1. min_fill floor (MIN_FILL_HARD_FLOOR = 0.38) — rejects
// pages where any column has narrow text in many bands
// (e.g. table with numeric column). Real tables have
- // at least one column with fill ≤ 0.36 (verified on
- // Coca Cola 10-k page 1, Apple 10-k page 1, BRWS, SERFF,
- // Goldman Sachs, etc.).
+ // at least one column with fill ≤ 0.36.
// 2. Band-count-weighted avg_fill ≥ XY_COLUMN_MIN_FILL —
// catches table layouts where ALL columns are uniformly
// narrow (no column dominates the weighted average).
@@ -3862,10 +3852,7 @@ fn xy_find_column_cut(
}
}
}
- let cut_x = if gutter_left.is_finite()
- && gutter_left > peaks[li].0
- && std::env::var("LITEPARSE_DISABLE_GUTTER_CUT").is_err()
- {
+ let cut_x = if gutter_left.is_finite() && gutter_left > peaks[li].0 {
(gutter_left + boundary) * 0.5
} else {
mid_centers
@@ -4050,8 +4037,7 @@ fn xy_cut_rec(
// Run the histogram probe unconditionally: besides being a fallback cut
// source, its fill gate is the region-level table detector — when it
// rejects with "tabular", density V-cuts must not slice the table's
- // inter-column gutters either (the dominant column-major-table failure:
- // SERFF_CA page2024 et al).
+ // inter-column gutters either (the dominant column-major-table failure).
let mut region_tabular = false;
let column_full = xy_find_column_cut(items, &idxs, &bbox, median_h, &mut region_tabular);
let column = if v.is_none() && h.is_none() {
@@ -4108,7 +4094,7 @@ fn xy_cut_rec(
}
// Build a priority-ordered candidate list.
//
- // **Primary** is the cut the original logic would have picked
+ // **Primary** is the cut chosen by the main resolution order
// (banner → column → H/V resolved by score margin). **Fallback** is
// the column-histogram probe — but ONLY that, not density V or the
// other density axis. The column histogram has strong discriminators
@@ -4138,7 +4124,7 @@ fn xy_cut_rec(
// When the histogram fill gate classified this region as tabular, a
// density V valley here is a table gutter, not a column boundary —
// suppress it so the table reaches the table detectors row-major.
- let v = if region_tabular && std::env::var("LITEPARSE_DISABLE_TABULAR_V_SUPPRESS").is_err() {
+ let v = if region_tabular {
if debug_xy && v.is_some() {
let pad = " ".repeat(depth as usize);
eprintln!("[xy d={depth}]{pad} -> SUPPRESS density V (region tabular)");
@@ -4703,8 +4689,7 @@ fn build_one_line(
.unwrap_or(0.0);
// Fallback: when PDFium reports font_size ≤ 1.5 (size baked into the text
// matrix), use char-weighted bbox height so the size-dependent grouping
- // (tables, paragraphs) keeps its well-tuned behavior. Documented in
- // MARKDOWN_PROGRESS.md.
+ // (tables, paragraphs) keeps its well-tuned behavior.
let (dominant_font_size, font_size_is_estimated) = if dominant_size_from_font > 1.5 {
(dominant_size_from_font, false)
} else {
@@ -4721,8 +4706,9 @@ fn build_one_line(
// jitter-free on-page size, far better than the bbox-height estimate above
// for separating headings from body. Routed only to body-size + heading-map
// (see `heading_font_size` doc on ProjectedLine); table/paragraph grouping
- // deliberately keeps the bbox-height value to avoid regressing TEDS.
- let heading_font_size = if dominant_size_from_font > 1.5 || *DISABLE_FONT_HEIGHT_SIZE {
+ // deliberately keeps the bbox-height value to avoid regressing table
+ // structure.
+ let heading_font_size = if dominant_size_from_font > 1.5 {
None
} else {
font_height_weights