A fast, helpful, and open-source document parser
fix: improve garble, deskew, math detection
Logan Markewich13a2adb0a76e
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex 97bdc36..c9ce145 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -612,6 +612,7 @@ pub struct JsPageInput {impl JsPageInput {pub fn to_rust(&self) -> Page {Page {+ ocr_deskew: None,page_number: self.page_number as usize,// Externally supplied pages carry no source PDF, so there is no// /PageLabels tree to read a label from.diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rsindex 0313142..49a5441 100644--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@ -352,14 +352,20 @@ fn extract_single_page(// walk — so the whole path costs one `form_type()` call for most files.let extract_text = |page: &Page| -> Result<Vec<TextItem>, LiteParseError> {let text_page = page.text()?;- extract_page_text_items(+ let spans = page_math_spans(page, &text_page, &view_box, &paths, glyph_resolver)+ .unwrap_or_default();+ let (emitted, consumed) = crate::tex_math::emitted(&spans);+ let mut items = extract_page_text_items(page,&text_page,&view_box,glyph_resolver,output_options.emit_word_boxes,output_options.extract_text_metadata,- )+ &consumed,+ )?;+ items.extend(emitted.into_iter().map(math_item));+ Ok(items)};let widget_text_rects = if document_has_form {page.form_widget_text_rects(&view_box)@@ -397,6 +403,7 @@ fn extract_single_page(Ok(PageExtraction {page: LitePage {+ ocr_deskew: None,page_number: page_number as usize,page_label: document.page_label(page_index),page_width,@@ -658,7 +665,8 @@ fn assign_strikethrough(items: &mut [TextItem], graphics: &[GraphicPrimitive]) {}for item in items.iter_mut() {- if item.width <= 0.0 || item.height <= 0.0 || item.text.trim().is_empty() {+ // A fraction bar runs through the middle of its math item.+ if item.math || item.width <= 0.0 || item.height <= 0.0 || item.text.trim().is_empty() {continue;}// Viewport space is top-left origin, so `y` is the top edge. The middle@@ -1491,6 +1499,7 @@ fn extract_page_text_items(glyph_resolver: Option<&dyn crate::GlyphResolver>,emit_word_boxes: bool,extract_text_metadata: bool,+ math_chars: &std::collections::HashSet<i32>,) -> Result<Vec<TextItem>, LiteParseError> {let char_count = text_page.char_count();if char_count <= 0 {@@ -1545,7 +1554,7 @@ fn extract_page_text_items(ch: &ch,rec: char_chunks.as_mut().and_then(|chunks| chunks.record(i)),};- if clips.hides(&cv) {+ if clips.hides(&cv) || math_chars.contains(&i) {seg.flush(&mut items);continue;}@@ -1944,6 +1953,179 @@ fn extract_page_text_items(Ok(items)}+/// Math spans for a page (see [`crate::tex_math`]), or None when the page+/// isn't set in TeX.+fn page_math_spans(+ page: &Page,+ text_page: &TextPage,+ view_box: &RectF,+ paths: &[PathObject],+ glyph_resolver: Option<&dyn crate::GlyphResolver>,+) -> Option<Vec<crate::tex_math::MathSpan>> {+ use crate::tex_math::{RawChar, RawText, Rule};+ let char_count = text_page.char_count();+ if char_count <= 0 {+ return None;+ }+ // Most pages have no TeX math font: check each text object's font once+ // before paying for glyph boxes and decoding.+ let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();+ let has_tex_font = (0..char_count).any(|i| {+ let ch = text_page.char_at_unchecked(i);+ let obj = ch.text_object();+ if !seen.insert(obj.map_or(0, |p| p as usize)) {+ return false;+ }+ obj.and_then(|o| unsafe { Font::from_text_object(o) })+ .and_then(|f| f.base_name())+ .or_else(|| ch.font_name())+ .is_some_and(|n| crate::tex_math::is_tex_math_font(&n))+ });+ if !has_tex_font {+ return None;+ }+ let clips = crate::text_clip::TextClip::new(page);+ let page_rotation = page.rotation();+ let vp_xform = page.viewport_transform(view_box);+ let (_, page_h) = page.viewport_size(view_box);+ let mut char_chunks = CharInfoChunks::new(text_page);+ // The same glyph-name recovery as the text pass: a Symbol font with no+ // ToUnicode otherwise reads as Latin ("t" for tau).+ let mut glyph_decoder =+ GlyphDecoder::new(false, std::collections::HashSet::new(), glyph_resolver);+ // Per text object: font name, effective size, descent at that size, and+ // the font when it has no ToUnicode.+ type ObjInfo = (std::rc::Rc<str>, f32, f32, Option<std::rc::Rc<Font>>);+ let mut objs: std::collections::HashMap<usize, ObjInfo> = std::collections::HashMap::new();+ // (font handle, char code) -> glyph-name text.+ let mut names: std::collections::HashMap<(usize, u32), Option<char>> =+ std::collections::HashMap::new();+ let mut chars = Vec::new();+ for i in 0..char_count {+ let ch = text_page.char_at_unchecked(i);+ let cv = CharView {+ ch: &ch,+ rec: char_chunks.as_mut().and_then(|chunks| chunks.record(i)),+ };+ if cv.is_generated() || cv.text_render_mode() == Some(3) || clips.hides(&cv) {+ continue;+ }+ // Upright glyphs only.+ let angle = adjust_angle_for_rotation(cv.ch.angle().max(0.0), page_rotation);+ if angle > 0.01 && angle < 2.0 * std::f32::consts::PI - 0.01 {+ continue;+ }+ let obj = cv.text_object();+ let key = obj.map_or(0, |p| p as usize);+ let (font_name, size, descent, no_tu_font) = objs+ .entry(key)+ .or_insert_with(|| {+ let font = obj.and_then(|o| unsafe { Font::from_text_object(o) });+ let name = font+ .as_ref()+ .and_then(|f| f.base_name())+ .or_else(|| ch.font_name())+ .unwrap_or_default();+ let fs = ch.font_size() as f32;+ let scale = ch.matrix().map_or(1.0, |m| decompose_scale(&m).1);+ let descent = font.as_ref().and_then(|f| f.descent(fs)).unwrap_or(0.0);+ let no_tu = font.filter(|f| !f.has_to_unicode()).map(std::rc::Rc::new);+ (name.into(), fs * scale, descent * scale, no_tu)+ })+ .clone();+ let unicode = cv.unicode();+ // Note: with no ToUnicode, the encoding's glyph name is the truth: a+ // Symbol font under WinAnsiEncoding + Differences names "tau" for+ // the code PDFium reads as "t".+ let named = no_tu_font.and_then(|f| {+ let code = cv.char_code();+ *names.entry((f.handle() as usize, code)).or_insert_with(|| {+ f.char_glyph_name(code)+ .as_deref()+ .and_then(resolve_glyph_name)+ .and_then(|r| {+ let mut cs = r.chars();+ cs.next().filter(|c| !c.is_control() && cs.next().is_none())+ })+ })+ });+ let text = if let Some(c) = named.or_else(|| {+ glyph_decoder+ .decode(&cv, unicode)+ .and_then(|d| d.chars().next())+ }) {+ RawText::Unicode(c)+ } else if cv.has_unicode_map_error() || unicode < 0x20 {+ RawText::Code(cv.char_code())+ } else {+ match char::from_u32(unicode) {+ Some(c) => RawText::Unicode(c),+ None => continue,+ }+ };+ let (Some((ox, oy)), Some(loose)) = (ch.origin(), cv.loose_char_box()) else {+ continue;+ };+ let (_, origin_y) = vp_xform.transform_point(ox as f32, oy as f32);+ let vp_loose = vp_xform.transform_bounds(&loose);+ let ink = cv.strict_char_box().map(|b| vp_xform.transform_bounds(&b));+ chars.push(RawChar {+ index: i,+ text,+ font_name,+ size: if size > 0.0 {+ size+ } else {+ vp_loose.bottom - vp_loose.top+ },+ descent,+ origin_y,+ x0: vp_loose.left,+ x1: vp_loose.right,+ ink: ink.map(|b| (b.top, b.bottom)),+ loose: (vp_loose.top, vp_loose.bottom),+ });+ }+ // Note: PDFium pads a stroked path's bounds by the stroke width on every+ // side (a 0.6pt fraction bar reads 1.2pt tall); take the geometric line.+ let mut rules: Vec<Rule> = paths+ .iter()+ .filter_map(|p| {+ let pad = if p.is_stroked {+ p.stroke_width.max(0.0)+ } else {+ 0.0+ };+ let b = &p.bbox;+ let (x0, x1) = (b.left + pad, (b.right - pad).max(b.left + pad));+ let (top, bottom) = (b.top + pad, (b.bottom - pad).max(b.top + pad));+ Rule::from_box(x0, x1, top, bottom, page_h)+ })+ .collect();+ // Note: some PDFs draw rules as stretched 1x1 images.+ rules.extend(+ page.image_bounds(0.0, f32::INFINITY)+ .into_iter()+ .filter_map(|b| Rule::from_box(b.x, b.x + b.width, b.y, b.y + b.height, page_h)),+ );+ crate::tex_math::page_math(&chars, &rules, page_h)+}++/// The text item a math span is spliced in as.+fn math_item(span: &crate::tex_math::MathSpan) -> TextItem {+ TextItem {+ text: format!("${}$", span.tex),+ x: span.x0,+ y: span.top,+ width: span.x1 - span.x0,+ height: span.bottom - span.top,+ font_size: Some(span.size),+ font_height: Some(span.size),+ math: true,+ ..Default::default()+ }+}+/// Remove duplicate text items: exact text matches with any bbox overlap,/// and near-duplicates (different text) with high bbox overlap (>50% area)./// Pair predicate for [`dedup_overlapping_items`]: should the *earlier* item@@ -3476,6 +3658,7 @@ impl SegmentBuilder {confidence: None,link: None,strike: false,+ math: false,words: std::mem::take(&mut self.words),});}@@ -4188,6 +4371,7 @@ mod tests {fn page_with(items: Vec<TextItem>) -> LitePage {LitePage {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 100.0,diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rsindex 1719d80..10dcfed 100644--- a/crates/liteparse/src/lib.rs+++ b/crates/liteparse/src/lib.rs@@ -28,6 +28,7 @@ pub mod parser;pub mod raw_text;pub mod search;pub mod stages;+mod tex_math;mod text_clip;pub mod types;diff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rsindex 2969741..a6fc106 100644--- a/crates/liteparse/src/markdown_layout/classify.rs+++ b/crates/liteparse/src/markdown_layout/classify.rs@@ -16,8 +16,9 @@ use super::lists::{split_ordered_marker_for_emit,};use super::paragraphs::{- ParaAccum, append_to_paragraph, collapse_whitespace, continues_heading, continues_list_item,- continues_paragraph, ends_hyphenated, ends_sentence_final, is_soft_hyphen_break,+ ParaAccum, append_to_paragraph, collapse_whitespace, continues_heading, continues_hyphen_wrap,+ continues_list_item, continues_paragraph, ends_hyphenated, ends_open_hyphen,+ ends_sentence_final, is_soft_hyphen_break,};use super::repetition::is_header_or_footer;use super::tables::{detect_ruled_tables, detect_tables_banded, merge_table_runs};@@ -780,6 +781,12 @@ fn classify_region(let mid_word_wrap = text.trim_end().ends_with('-');!(has_mid_sentence && mid_word_wrap)});+ // On a page whose sizes are estimated from box heights (scans, OCR) a line ending in an+ // attached hyphen is the first half of a token, not a finished heading: promoted, it+ // splits the token across a heading and the paragraph below ("…pyridine-3-" /+ // "carbonitrile 4a …"). Left in the paragraph, the join keeps it whole.+ let open_hyphen_scan = line.font_size_is_estimated && ends_open_hyphen(text);+ let size_level = size_level.filter(|_| !open_hyphen_scan);// 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@@ -1058,7 +1065,10 @@ fn classify_region(}match state.paragraph.as_mut() {- Some(acc) if continues_paragraph(&acc.last, line) => {+ Some(acc)+ if continues_paragraph(&acc.last, line)+ || continues_hyphen_wrap(&acc.last, line) =>+ {append_to_paragraph(acc, line);}_ => {@@ -1257,6 +1267,15 @@ fn stitch_regions(blocks: Vec<PositionedBlock>, region_starts: &[usize]) -> Vec<prev.bbox = merged_bbox;continue;}+ // A hard hyphen (`pyridine-3-` + `carbonitrile`): one token, hyphen kept.+ if ends_open_hyphen(prev_text) && starts_lower {+ while prev_text.ends_with(|c: char| c.is_whitespace()) {+ prev_text.pop();+ }+ prev_text.push_str(cur_text.trim_start());+ prev.bbox = merged_bbox;+ continue;+ }let ends_open = !prev_trim.ends_with(|c: char| {matches!(c,diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rsindex 797755a..db2576f 100644--- a/crates/liteparse/src/markdown_layout/inline.rs+++ b/crates/liteparse/src/markdown_layout/inline.rs@@ -30,20 +30,80 @@ 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.+/// An `_` between two letters or digits stays bare: CommonMark never reads an+/// intraword underscore as emphasis, and `snake_case`, `[email protected]`+/// or a URL path should survive verbatim (`mcc\_compliance` splits the token+/// for any consumer that doesn't unescape). Inline math (`$…$`, see+/// [`math_runs`]) passes through untouched.pub fn escape_inline(s: &str) -> String {let mut out = String::with_capacity(s.len());- for c in s.chars() {- match c {- '\\' | '*' | '_' => {- out.push('\\');- out.push(c);+ for (is_math, run) in math_runs(s) {+ if is_math {+ out.push_str(run);+ continue;+ }+ let chars: Vec<char> = run.chars().collect();+ for (i, &c) in chars.iter().enumerate() {+ let intraword = c == '_'+ && i > 0+ && chars[i - 1].is_alphanumeric()+ && chars.get(i + 1).is_some_and(|n| n.is_alphanumeric());+ match c {+ '\\' | '*' | '_' if !intraword => {+ out.push('\\');+ out.push(c);+ }+ _ => out.push(c),}- _ => out.push(c),}}out}+/// Split `s` into runs, flagging the `$…$` spans a renderer reads as inline+/// math under pandoc's `tex_math_dollars` rule: the opening `$` is followed+/// by a non-space, the closing `$` follows a non-space and isn't followed by+/// a digit (so "$5 to $10" stays text) unless the span is plainly LaTeX+/// (`\`, `^`, `_` or `{`: "$\mathbb{R}$3" from a split script). The math+/// pass (`tex_math`) emits its LaTeX this way, and it must reach the output+/// unescaped.+pub(crate) fn math_runs(s: &str) -> Vec<(bool, &str)> {+ let b = s.as_bytes();+ let mut runs = Vec::new();+ let (mut lit, mut i) = (0, 0);+ while i < b.len() {+ let opens = b[i] == b'$'+ && (i == 0 || b[i - 1] != b'\\')+ && b.get(i + 1)+ .is_some_and(|c| !c.is_ascii_whitespace() && *c != b'$');+ let close = opens+ .then(|| {+ let j = i + 1 + s[i + 1..].find('$')?;+ let latex = s[i + 1..j].contains(['\\', '^', '_', '{']);+ let ok = !b[j - 1].is_ascii_whitespace()+ && b[j - 1] != b'\\'+ && (latex || !b.get(j + 1).is_some_and(u8::is_ascii_digit));+ ok.then_some(j)+ })+ .flatten();+ match close {+ Some(j) => {+ if lit < i {+ runs.push((false, &s[lit..i]));+ }+ runs.push((true, &s[i..=j]));+ i = j + 1;+ lit = i;+ }+ None => i += 1,+ }+ }+ if lit < s.len() {+ runs.push((false, &s[lit..]));+ }+ runs+}+/// Escape `text` for use as the body of a span with `style`. Backslash escapes/// are inert inside code spans per CommonMark, so mono text is passed through/// verbatim.@@ -335,6 +395,37 @@ mod tests {assert_eq!(out.matches("**").count(), 2, "got: {out}");}+ #[test]+ fn escape_inline_leaves_dollar_math_alone() {+ assert_eq!(+ escape_inline(r"where $x_{i}\in \mathbb{R}$ and a*b"),+ r"where $x_{i}\in \mathbb{R}$ and a\*b"+ );+ // Currency is not math: the closing `$` is followed by a digit.+ assert_eq!(+ escape_inline("costs $5 to $10 a*b"),+ r"costs $5 to $10 a\*b"+ );+ assert_eq!(escape_inline("$ x*1$"), r"$ x\*1$");+ // A script split off after the span still leaves the LaTeX intact.+ assert_eq!(escape_inline(r"M×$\mathbb{R}$3"), r"M×$\mathbb{R}$3");+ }++ #[test]+ fn escape_inline_keeps_intraword_underscores() {+ // CommonMark never reads an underscore between alphanumerics as emphasis.+ assert_eq!(+ escape_inline("[email protected]"),+ );+ assert_eq!(escape_inline("snake_case and x_1"), "snake_case and x_1");+ // At a word edge it can open or close emphasis, so it stays escaped.+ assert_eq!(+ escape_inline("_lead and trail_ and __init__"),+ r"\_lead and trail\_ and \_\_init\_\_"+ );+ }+#[test]fn render_line_inline_escapes_emphasis_chars() {let l = styled_line(&[("5*4=20", 50.0, Some("Arial"))], 100.0, 10.0);diff --git a/crates/liteparse/src/markdown_layout/paragraphs.rs b/crates/liteparse/src/markdown_layout/paragraphs.rsindex e98fbf5..0722627 100644--- a/crates/liteparse/src/markdown_layout/paragraphs.rs+++ b/crates/liteparse/src/markdown_layout/paragraphs.rs@@ -68,6 +68,36 @@ pub(super) fn ends_hyphenated(text: &str) -> bool {t.ends_with('-') && t.chars().rev().nth(1).is_some_and(|c| c.is_alphabetic())}+/// True when `text` ends with a hyphen attached to a letter or digit (`architec-`,+/// `pyridine-3-`, `Billion-`): the token continues on the next line. A detached ` -`+/// (a dash, a list marker) does not.+pub(super) fn ends_open_hyphen(text: &str) -> bool {+ let t = text.trim_end();+ t.ends_with('-') && t.chars().rev().nth(1).is_some_and(|c| c.is_alphanumeric())+}++/// A token broken over a line end (`…pyridine-3-` / `carbonitrile 4a …`): `prev` ends in an+/// attached hyphen and `cur` starts lowercase, in the same region, no more than two line+/// heights below. The token joins whatever the indent or gap says about paragraphs, since+/// a break there would split one word or identifier into two.+pub(super) fn continues_hyphen_wrap(prev: &ProjectedLine, cur: &ProjectedLine) -> bool {+ if !ends_open_hyphen(&prev.text) || prev.region_path != cur.region_path {+ return false;+ }+ if !cur+ .text+ .trim_start()+ .chars()+ .next()+ .is_some_and(|c| c.is_lowercase())+ {+ return false;+ }+ let gap = cur.bbox.y - (prev.bbox.y + prev.bbox.height);+ let line_height = prev.bbox.height.max(cur.bbox.height).max(1.0);+ (-0.5 * line_height..=2.0 * line_height).contains(&gap)+}+/// True when `text` ends a sentence: its last non-space character (ignoring a/// trailing closing quote / bracket) is `.`, `!`, or `?`. The heading/// lowercase-continuation guard uses the negation — a previous line that does@@ -120,6 +150,13 @@ pub(super) fn dehyphenate_join(prev: &mut String, check: &str, to_append: &str)}prev.pop(); // the soft hyphenprev.push_str(to_append.trim_start());+ } else if ends_open_hyphen(prev) {+ // a hard hyphen at the break (`pyridine-3-` + `carbonitrile`, `well-` + `Known`): one+ // token, hyphen kept, no space+ while prev.ends_with(|c: char| c.is_whitespace()) {+ prev.pop();+ }+ prev.push_str(to_append.trim_start());} else {prev.push(' ');prev.push_str(to_append);@@ -316,14 +353,28 @@ pub(super) fn append_to_paragraph(accum: &mut ParaAccum, next_line: &ProjectedLimod tests {use super::*;+ #[test]+ fn dehyphenate_join_keeps_hard_hyphen_without_space() {+ let mut s = String::from("2-Chloro-5-ethyl-6-methylpyridine-3-");+ dehyphenate_join(&mut s, "carbonitrile 4a", "carbonitrile 4a");+ assert_eq!(s, "2-Chloro-5-ethyl-6-methylpyridine-3-carbonitrile 4a");+ let mut s = String::from("a well-");+ dehyphenate_join(&mut s, "Known case", "Known case");+ assert_eq!(s, "a well-Known case");+ let mut s = String::from("ranges 5 -");+ dehyphenate_join(&mut s, "10", "10");+ assert_eq!(s, "ranges 5 - 10");+ }+#[test]fn dehyphenate_join_only_strips_before_lowercase() {let mut s = String::from("co-");dehyphenate_join(&mut s, "operate", "operate");assert_eq!(s, "cooperate");+ // a capitalized continuation is a real compound: the hyphen stays, with no spacelet mut s = String::from("Vitamin-");dehyphenate_join(&mut s, "A", "A");- assert_eq!(s, "Vitamin- A");+ assert_eq!(s, "Vitamin-A");}}diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rsindex bce2221..6abcf85 100644--- a/crates/liteparse/src/markdown_layout/tables.rs+++ b/crates/liteparse/src/markdown_layout/tables.rs@@ -5795,9 +5795,19 @@ fn cell_continues(prev: &str, cur: &str) -> bool {/// stays valid. Newlines should be impossible inside a single cell (we built/// cells from spans on the same projected line) but guard anyway.pub(super) fn escape_table_cell(s: &str) -> String {- s.replace('\\', "\\\\")- .replace('|', "\\|")- .replace('\n', " ")+ super::inline::math_runs(s)+ .into_iter()+ .map(|(is_math, run)| {+ // Inline math keeps its backslashes; only the pipe is escaped+ // (GFM splits cells before parsing inlines).+ let run = if is_math {+ run.to_string()+ } else {+ run.replace('\\', "\\\\")+ };+ run.replace('|', "\\|").replace('\n', " ")+ })+ .collect()}#[cfg(test)]@@ -6792,6 +6802,11 @@ mod tests {assert!(runs.is_empty());}+ #[test]+ fn escapes_math_cell_pipes_but_keeps_backslashes() {+ assert_eq!(escape_table_cell(r"$\|x\|_{2}$ a\b"), r"$\\|x\\|_{2}$ a\\b");+ }+#[test]fn escapes_pipe_inside_cell() {assert_eq!(escape_table_cell("a|b"), "a\\|b");diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rsindex 65dcd15..9a100d7 100644--- a/crates/liteparse/src/ocr_merge.rs+++ b/crates/liteparse/src/ocr_merge.rs@@ -70,6 +70,10 @@ pub struct OcrRaster {/// backgrounds), so the merge can judge each figure's OCR output as a/// group — a chart's axis/legend labels are dropped together.pub image_rects: Vec<Rect>,+ /// The page's native text is an invisible OCR layer the new OCR replaces+ /// ([`ComplexityReason::InvisibleTextLayer`]).+ #[serde(default)]+ pub replace_native: bool,}/// How [`render_pages_for_ocr`] picks and rasterizes pages.@@ -143,6 +147,7 @@ impl PageOcrOutcome {dpi: raster.dpi,has_native_text: raster.has_native_text,image_rects: raster.image_rects.clone(),+ replace_native: raster.replace_native,results: Vec::new(),error: None,}@@ -360,6 +365,11 @@ pub enum ComplexityReason {/// by `NoText` or `Scanned`; it tells a genuinely blank page apart from/// one whose body text simply lives out of reach.AnnotationText,+ /// A scanned page (full-page raster) whose native text is an invisible+ /// layer (render mode 3) - an earlier OCR pass baked into the PDF. Its+ /// misreads cost as much as missing text, so the page is OCR'd again and+ /// the new OCR replaces the layer.+ InvisibleTextLayer,}impl ComplexityReason {@@ -372,6 +382,7 @@ impl ComplexityReason {ComplexityReason::Garbled => "garbled",ComplexityReason::VectorText => "vector-text",ComplexityReason::AnnotationText => "annotation-text",+ ComplexityReason::InvisibleTextLayer => "invisible-text-layer",}}}@@ -421,6 +432,70 @@ pub struct PageComplexityStats {pub layout: Option<LayoutComplexityStats>,}+/// Share of a page's visible-glyph characters (whitespace and generated+/// characters aside) at or above which its text counts as an invisible layer.+const INVISIBLE_LAYER_MIN_SHARE: f32 = 0.9;++/// Fraction of the page's top-level text objects painted before (under) its first+/// full-page raster. Archive scans often carry their OCR text in render mode 0 but+/// hidden beneath the page image, which the reader never sees; born-digital pages+/// with a background image paint their text on top of it.+fn hidden_under_scan_share(page_obj: &pdfium::Page) -> f32 {+ let (pw, ph) = (page_obj.width(), page_obj.height());+ let mut text_before = 0usize;+ let mut text_total = 0usize;+ let mut seen_scan = false;+ for i in 0..page_obj.object_count() {+ let Some(obj) = page_obj.object(i) else {+ continue;+ };+ match obj.kind() {+ pdfium::PageObjectKind::Image if !seen_scan => {+ if let Some(b) = obj.bounds() {+ seen_scan = (b.right - b.left) > pw * MAX_IMAGE_PAGE_COVERAGE+ && (b.top - b.bottom).abs() > ph * MAX_IMAGE_PAGE_COVERAGE;+ }+ }+ pdfium::PageObjectKind::Text => {+ text_total += 1;+ if !seen_scan {+ text_before += 1;+ }+ }+ _ => {}+ }+ }+ if !seen_scan || text_total == 0 {+ 0.0+ } else {+ text_before as f32 / text_total as f32+ }+}++/// Fraction of the page's characters drawn invisibly (text render mode 3).+fn invisible_text_share(page_obj: &pdfium::Page) -> f32 {+ let Ok(tp) = page_obj.text() else {+ return 0.0;+ };+ let (mut invisible, mut total) = (0usize, 0usize);+ for ch in tp.chars() {+ if ch.is_generated()+ || char::from_u32(ch.unicode()).is_none_or(|c| c.is_whitespace() || c.is_control())+ {+ continue;+ }+ total += 1;+ if ch.text_render_mode() == Some(3) {+ invisible += 1;+ }+ }+ if total == 0 {+ 0.0+ } else {+ invisible as f32 / total as f32+ }+}+pub(crate) fn calculate_page_complexity(page: &Page,page_obj: &pdfium::Page,@@ -513,6 +588,13 @@ pub(crate) fn calculate_page_complexity(if is_garbled {reasons.push(ComplexityReason::Garbled);}+ if full_page_image+ && text_length >= MIN_NATIVE_TEXT_LEN+ && (invisible_text_share(page_obj) >= INVISIBLE_LAYER_MIN_SHARE+ || hidden_under_scan_share(page_obj) >= INVISIBLE_LAYER_MIN_SHARE)+ {+ reasons.push(ComplexityReason::InvisibleTextLayer);+ }let mut needs_ocr = !reasons.is_empty();// Text drawn as filled vector outlines lives outside the text layer@@ -945,6 +1027,7 @@ pub(crate) fn render_pages_for_ocr_capped(// caller's decision, so the page-object walk in// `calculate_page_complexity` is skipped and the signal is derived// from the text items alone (which is all those reasons read).+ let mut replace_native = false;let has_native_text = match selection {Some(_) => {native_text_length(page) >= MIN_NATIVE_TEXT_LEN && !page_is_garbled(page)@@ -954,6 +1037,9 @@ pub(crate) fn render_pages_for_ocr_capped(if !page_complexity.needs_ocr {return Ok(None);}+ replace_native = page_complexity+ .reasons+ .contains(&ComplexityReason::InvisibleTextLayer);!page_complexity.reasons.iter().any(|r| {matches!(r,@@ -961,6 +1047,7 @@ pub(crate) fn render_pages_for_ocr_capped(| ComplexityReason::NoText| ComplexityReason::Garbled| ComplexityReason::AnnotationText+ | ComplexityReason::InvisibleTextLayer)})}@@ -1015,6 +1102,7 @@ pub(crate) fn render_pages_for_ocr_capped(dpi: eff_dpi,has_native_text,image_rects,+ replace_native,}))})();match page_render {@@ -1054,6 +1142,9 @@ pub struct PageOcrOutcome {pub dpi: f32,pub has_native_text: bool,pub image_rects: Vec<Rect>,+ /// See [`OcrRaster::replace_native`].+ #[serde(default)]+ pub replace_native: bool,/// Engine output in raster pixel coordinates. Empty when the engine/// failed (see `error`) or found nothing.#[serde(default, skip_serializing_if = "Vec::is_empty")]@@ -1135,6 +1226,7 @@ pub fn merge_ocr_results(dpi: page_dpi,has_native_text,image_rects,+ replace_native,results: ocr_results,error,} = outcome;@@ -1170,7 +1262,14 @@ pub fn merge_ocr_results(// output stuck with unreadable text. We apply per-item, per-font, and// per-page checks: short garbled labels ("GDWH", "XVG") can't be// flagged alone, but their font group or host page can.- match garbled_scope(page) {+ // An invisible OCR layer on a scan steps aside for the new OCR (which+ // came back non-empty, so the page keeps text either way).+ let scope = if replace_native {+ GarbledScope::WholePage+ } else {+ garbled_scope(page)+ };+ match scope {GarbledScope::None => page.text_items.retain(|item| !is_unusable_native(item)),GarbledScope::WholePage => page.text_items.clear(),// Only the corrupt font's items go; text in the page's healthy@@ -1188,6 +1287,23 @@ pub fn merge_ocr_results(// other, dropping every second line on scanned pages.let native_count = page.text_items.len();let debug_ocr = std::env::var_os("LITEPARSE_DEBUG_OCR").is_some();+ // A skewed scan: when all of the page's text is OCR, rotate the items upright about the+ // page centre. Axis-aligned boxes of tilted lines overlap the lines above and below,+ // and the projection then merges and reorders them. The tilt is recorded on the page+ // and the output boxes are rotated back after layout (parser.rs).+ let deskew = if native_count == 0 {+ ocr_page_skew(&ocr_results)+ } else {+ None+ };+ page.ocr_deskew = deskew;+ let (cx, cy) = (page.page_width / 2.0, page.page_height / 2.0);+ let upright = |x: f32, y: f32| -> (f32, f32) {+ match deskew {+ Some(deg) => rotate_about(x, y, cx, cy, -deg),+ None => (x, y),+ }+ };// Judge each embedded figure's OCR output as a group: a figure whose// recognised text is mostly numbers and short tokens is a chart// (axes, ticks, legend keys), and none of it belongs in the text flow.@@ -1217,28 +1333,51 @@ pub fn merge_ocr_results(// reading-order handler instead of mistaking it for body text.let (ocr_x, ocr_y, ocr_w, ocr_h, rotation) = match r.polygon {Some(poly) => {- let xs = [poly[0][0], poly[1][0], poly[2][0], poly[3][0]];- let ys = [poly[0][1], poly[1][1], poly[2][1], poly[3][1]];- let x_min = xs.iter().copied().fold(f32::INFINITY, f32::min);- let x_max = xs.iter().copied().fold(f32::NEG_INFINITY, f32::max);- let y_min = ys.iter().copied().fold(f32::INFINITY, f32::min);- let y_max = ys.iter().copied().fold(f32::NEG_INFINITY, f32::max);+ // without a deskew the points stay in image pixels until the bounds are+ // taken, so the boxes match the un-deskewed arithmetic exactly+ let (s, pts) = match deskew {+ Some(_) => (+ 1.0,+ poly.map(|[x, y]| upright(x * scale_factor, y * scale_factor)),+ ),+ None => (scale_factor, poly.map(|[x, y]| (x, y))),+ };+ let x_min = pts.iter().map(|p| p.0).fold(f32::INFINITY, f32::min);+ let x_max = pts.iter().map(|p| p.0).fold(f32::NEG_INFINITY, f32::max);+ let y_min = pts.iter().map(|p| p.1).fold(f32::INFINITY, f32::min);+ let y_max = pts.iter().map(|p| p.1).fold(f32::NEG_INFINITY, f32::max);let rot = polygon_rotation_deg(&poly);(- x_min * scale_factor,- y_min * scale_factor,- (x_max - x_min) * scale_factor,- (y_max - y_min) * scale_factor,+ x_min * s,+ y_min * s,+ (x_max - x_min) * s,+ (y_max - y_min) * s,rot,)}- None => (- r.bbox[0] * scale_factor,- r.bbox[1] * scale_factor,- (r.bbox[2] - r.bbox[0]) * scale_factor,- (r.bbox[3] - r.bbox[1]) * scale_factor,- 0.0,- ),+ None => {+ let (w, h) = (+ (r.bbox[2] - r.bbox[0]) * scale_factor,+ (r.bbox[3] - r.bbox[1]) * scale_factor,+ );+ match deskew {+ // the box moves with its centre; its size is kept+ Some(_) => {+ let (mx, my) = upright(+ (r.bbox[0] + r.bbox[2]) / 2.0 * scale_factor,+ (r.bbox[1] + r.bbox[3]) / 2.0 * scale_factor,+ );+ (mx - w / 2.0, my - h / 2.0, w, h, 0.0)+ }+ None => (+ r.bbox[0] * scale_factor,+ r.bbox[1] * scale_factor,+ w,+ h,+ 0.0,+ ),+ }+ }};// On pages that already have native text, OCR only enriches:@@ -1302,10 +1441,16 @@ pub fn merge_ocr_results(// which for 90/270° rotations corresponds to the *narrow* screen// dimension. Use the perpendicular extent for rotated OCR text so// downstream font-size heuristics stay sane.+ // A tilted line's axis-aligned box is taller than its glyphs (a 3° tilt over a+ // 400 px line adds 20 px), which reads as a larger font and promotes body lines+ // to headings; the polygon's own side is the line height.+ let poly_h = r+ .polygon+ .map(|p| (p[3][0] - p[0][0]).hypot(p[3][1] - p[0][1]) * scale_factor);let font_size_hint = if rotation == 90.0 || rotation == 270.0 {ocr_w.max(1.0)} else {- ocr_h+ poly_h.filter(|h| *h > 0.0).map_or(ocr_h, |h| h.min(ocr_h))};// The engine already segmented this result as a single word, so@@ -1337,6 +1482,9 @@ pub fn merge_ocr_results(..Default::default()});}+ if !has_native_text {+ upright_rotated_scan(page);+ }}// If every OCR task failed *and* at least one of those failures was on a@@ -1376,6 +1524,98 @@ pub fn merge_ocr_results(Ok(())}+/// Tilt range a page is deskewed over: below it rows already group correctly, above it the+/// "tilt" is more likely rotated or curved text than a skewed scan.+const DESKEW_MIN_DEG: f32 = 0.3;+const DESKEW_MAX_DEG: f32 = 10.0;++/// Share of a page's OCR text (by characters) that must share one quarter-turn rotation for the+/// page to be read as a scan turned on its side or upside down.+const ROTATED_SCAN_MIN_SHARE: f32 = 0.7;++/// A scan whose text all runs one way other than upright (a page fed sideways or upside down):+/// re-express every item in the upright page's frame and clear its rotation, so reading order and+/// layout work on the page as written. The rotation handler in projection is built for a few+/// rotated labels on an upright page (pin labels, margin stamps), not a whole rotated page, which+/// came out reversed (180) or shredded into fake tables (90 / 270). Item boxes, and for quarter+/// turns the page size, are then in the upright frame.+fn upright_rotated_scan(page: &mut Page) {+ let mut chars = [0usize; 4];+ for it in &page.text_items {+ chars[(canonical_quarter(it.rotation) / 90) as usize] += it.text.chars().count();+ }+ let total: usize = chars.iter().sum();+ let (q, &top) = chars.iter().enumerate().max_by_key(|&(_, c)| *c).unwrap();+ if q == 0 || total < 20 || (top as f32) < total as f32 * ROTATED_SCAN_MIN_SHARE {+ return;+ }+ let (w, h) = (page.page_width, page.page_height);+ for it in &mut page.text_items {+ let (x, y, iw, ih) = (it.x, it.y, it.width, it.height);+ (it.x, it.y, it.width, it.height) = match q {+ // reading bottom-to-top: the page's top edge is on the left+ 1 => (h - (y + ih), x, ih, iw),+ 2 => (w - (x + iw), h - (y + ih), iw, ih),+ // reading top-to-bottom: the page's top edge is on the right+ _ => (y, w - (x + iw), ih, iw),+ };+ it.rotation = 0.0;+ for wb in &mut it.words {+ (wb.x, wb.y, wb.width, wb.height) = (it.x, it.y, it.width, it.height);+ }+ }+ if q != 2 {+ (page.page_width, page.page_height) = (h, w);+ }+}++/// 0, 90, 180 or 270 for an item rotation in degrees.+fn canonical_quarter(rot: f32) -> u32 {+ ((rot.rem_euclid(360.0) / 90.0).round() as u32 % 4) * 90+}++/// The page's tilt in degrees (image frame, y down: positive = lines descend to the right),+/// as the length-weighted median angle of its long, near-horizontal OCR lines (length >= 4x+/// height): a long line's angle is reliable, a short piece's (a list marker, one word) is+/// often 0 or noise, and a plain median of a page with few long lines lands between the two.+/// `None` below three such lines or outside the deskew range.+fn ocr_page_skew(results: &[OcrResult]) -> Option<f32> {+ let mut lines: Vec<(f32, f32)> = results+ .iter()+ .filter_map(|r| {+ let p = r.polygon?;+ let (dx, dy) = (p[1][0] - p[0][0], p[1][1] - p[0][1]);+ let len = dx.hypot(dy);+ let h = (p[3][0] - p[0][0]).hypot(p[3][1] - p[0][1]);+ let deg = dy.atan2(dx).to_degrees();+ (len >= 4.0 * h && len > 0.0 && deg.abs() <= 45.0).then_some((deg, len))+ })+ .collect();+ if lines.len() < 3 {+ return None;+ }+ lines.sort_by(|a, b| a.0.total_cmp(&b.0));+ let half = lines.iter().map(|l| l.1).sum::<f32>() / 2.0;+ let mut acc = 0.0;+ let mid = lines+ .iter()+ .find(|l| {+ acc += l.1;+ acc >= half+ })+ .map_or(0.0, |l| l.0);+ (DESKEW_MIN_DEG..=DESKEW_MAX_DEG)+ .contains(&mid.abs())+ .then_some(mid)+}++/// Rotate (x, y) by `deg` degrees about (cx, cy), in the y-down page frame.+pub(crate) fn rotate_about(x: f32, y: f32, cx: f32, cy: f32, deg: f32) -> (f32, f32) {+ let (s, c) = deg.to_radians().sin_cos();+ let (dx, dy) = (x - cx, y - cy);+ (cx + dx * c - dy * s, cy + dx * s + dy * c)+}+/// True when the page's native (already-extracted) text is sparse enough that/// OCR is likely its primary text source. Mirrors the non-image predicates in/// `render_pages_for_ocr` (`text_length < 20 || text_coverage < 0.15`) so the@@ -1550,25 +1790,101 @@ fn garbled_scope(page: &Page) -> GarbledScope {let mut total_vowels = 0usize;// Keyed by font name, so text sharing a ToUnicode map is judged together.let mut per_font: HashMap<Option<&str>, (usize, usize)> = HashMap::new();+ // Complex-script text with unmapped conjunct / ligature glyphs (see `script_intrusions`).+ let mut per_font_script: HashMap<Option<&str>, (usize, usize)> = HashMap::new();+ let (mut total_script, mut total_intrusions) = (0usize, 0usize);+ // Legacy-encoded Indic fonts and cipher-like maps (see `symbol_intrusions`).+ let mut per_font_symbol: HashMap<Option<&str>, (usize, usize)> = HashMap::new();+ let (mut total_sym_letters, mut total_sym) = (0usize, 0usize);+ // Control characters and malformed tokens (see `control_chars`, `token_is_malformed`).+ let mut per_font_ctrl: HashMap<Option<&str>, (usize, usize)> = HashMap::new();+ let (mut total_ctrl, mut total_chars) = (0usize, 0usize);+ let mut per_font_tok: HashMap<Option<&str>, (usize, usize)> = HashMap::new();+ let (mut total_judged, mut total_malformed) = (0usize, 0usize);for it in &page.text_items {+ // math items carry the TeX pass's own LaTeX (and its fonts' control-position glyphs)+ if !it.math && !is_symbol_font(it.font_name.as_deref()) {+ let (c, n) = control_chars(&it.text);+ total_ctrl += c;+ total_chars += n;+ let e = per_font_ctrl+ .entry(it.font_name.as_deref())+ .or_insert((0, 0));+ e.0 += c;+ e.1 += n;+ let (j, m) = malformed_tokens(&it.text);+ total_judged += j;+ total_malformed += m;+ let e = per_font_tok+ .entry(it.font_name.as_deref())+ .or_insert((0, 0));+ e.0 += j;+ e.1 += m;+ }let (l, v) = count_letters_and_vowels(&it.text);total_letters += l;total_vowels += v;let entry = per_font.entry(it.font_name.as_deref()).or_insert((0, 0));entry.0 += l;entry.1 += v;- }-- if ratio_is_garbled(total_letters, total_vowels) {+ let (sc, intr) = script_intrusions(&it.text);+ total_script += sc;+ total_intrusions += intr;+ let e = per_font_script+ .entry(it.font_name.as_deref())+ .or_insert((0, 0));+ e.0 += sc;+ e.1 += intr;+ let (lt, sy) = symbol_intrusions(&it.text);+ total_sym_letters += lt;+ total_sym += sy;+ let e = per_font_symbol+ .entry(it.font_name.as_deref())+ .or_insert((0, 0));+ e.0 += lt;+ e.1 += sy;+ }++ if ratio_is_garbled(total_letters, total_vowels)+ || intrusions_are_garbled(total_script, total_intrusions)+ || symbols_are_garbled(total_sym_letters, total_sym)+ || controls_are_garbled(total_ctrl, total_chars)+ || tokens_are_garbled(total_judged, total_malformed)+ {return GarbledScope::WholePage;}let min_share = (total_letters as f32 * GARBLE_MIN_FONT_SHARE).ceil() as usize;- let fonts: HashSet<Option<String>> = per_font+ let mut fonts: HashSet<Option<String>> = per_font.into_iter().filter(|&(_, (letters, vowels))| letters >= min_share && ratio_is_garbled(letters, vowels)).map(|(font, _)| font.map(str::to_string)).collect();+ fonts.extend(+ per_font_script+ .into_iter()+ .filter(|&(_, (sc, intr))| intrusions_are_garbled(sc, intr))+ .map(|(font, _)| font.map(str::to_string)),+ );+ fonts.extend(+ per_font_symbol+ .into_iter()+ .filter(|&(_, (lt, sy))| symbols_are_garbled(lt, sy))+ .map(|(font, _)| font.map(str::to_string)),+ );++ fonts.extend(+ per_font_ctrl+ .into_iter()+ .filter(|&(_, (c, n))| controls_are_garbled(c, n))+ .map(|(font, _)| font.map(str::to_string)),+ );+ fonts.extend(+ per_font_tok+ .into_iter()+ .filter(|&(_, (j, m))| tokens_are_garbled(j, m))+ .map(|(font, _)| font.map(str::to_string)),+ );if fonts.is_empty() {GarbledScope::None@@ -1577,6 +1893,225 @@ fn garbled_scope(page: &Page) -> GarbledScope {}}+/// Fewest stray ASCII characters inside complex-script words, and their least rate per script+/// character, for a font's text to count as garbled (see [`script_intrusions`]).+const INTRUSION_MIN: usize = 5;+const INTRUSION_MIN_RATE: f32 = 0.015;++/// Complex scripts whose shaped forms (Indic conjuncts and matras, Arabic / Hebrew joining+/// forms and ligatures, Thai / Khmer / Myanmar clusters) a subset font draws from glyphs that+/// often lack a ToUnicode entry.+fn is_complex_script(c: char) -> bool {+ matches!(c as u32,+ 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0x0900..=0x0DFF+ | 0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF)+}++/// (complex-script characters, ASCII intrusions) in `text`. An intrusion is a printable ASCII+/// character wedged between two complex-script characters with no space: where a conjunct+/// or ligature glyph has no Unicode mapping, PDF text extraction yields a stray `(`, `@`, `/`+/// or Latin letter inside the word ("आ(का", "ب)مه", "خر/داران"). Correctly encoded text in+/// these scripts essentially never mixes ASCII into a word.+fn script_intrusions(text: &str) -> (usize, usize) {+ let cs: Vec<char> = text.chars().collect();+ let script = cs.iter().filter(|&&c| is_complex_script(c)).count();+ let intrusions = (1..cs.len().saturating_sub(1))+ .filter(|&i| {+ cs[i].is_ascii_graphic() && is_complex_script(cs[i - 1]) && is_complex_script(cs[i + 1])+ })+ .count();+ (script, intrusions)+}++/// Fewest symbol intrusions, and their least rate per letter, for text to count as garbled+/// (see [`symbol_intrusions`]). On ParseBench v2 the garbled pages sit at 5.2-8.0%, the+/// highest clean one at 2.2%.+const SYMBOL_MIN: usize = 20;+const SYMBOL_MIN_RATE: f32 = 0.03;++/// (letters, symbol intrusions) in `text`: a symbol such as `$ ¥ © « @ § ¶ ®` wedged+/// between two letters. Text drawn with a legacy 8-bit Indic font (the glyph codes are ASCII /+/// Latin-1 positions, "H¥$VrH$m`©H«$_mMr") or a cipher-like ToUnicode map ("PFDKFCF@") is+/// full of them; real text, code and URLs included, rarely puts them inside a word.+fn symbol_intrusions(text: &str) -> (usize, usize) {+ // Only symbols legacy / cipher fonts produce and real text doesn't put inside words. LaTeX and+ // math symbols (^ { } \ ` ~ | ± × ÷ ° ² ³ µ ·) are out: the TeX math path writes `x^{2}`,+ // `\alpha` into text items before this check runs, and with them every math page read as+ // garbled (OPB math 53.6 -> 33.2, 2026-10-30).+ const SYM: &str = "$¥©«»@¢£¤¦§¨ª¬®¯¶¸º¼½¾¿";+ let cs: Vec<char> = text.chars().collect();+ let letters = cs.iter().filter(|c| c.is_alphabetic()).count();+ let n = (1..cs.len().saturating_sub(1))+ .filter(|&i| SYM.contains(cs[i]) && cs[i - 1].is_alphabetic() && cs[i + 1].is_alphabetic())+ .count();+ (letters, n)+}++/// Dingbat / symbol fonts map their glyphs (bullets, arrows, checkboxes) to control and+/// private codes by design; that is not a broken map, so they never count as garbled.+fn is_symbol_font(name: Option<&str>) -> bool {+ name.is_some_and(|n| {+ let n = n.to_ascii_lowercase();+ let base = n.split_once('+').map_or(n.as_str(), |(_, b)| b);+ ["wingding", "webding", "dingbat", "symbol", "zapf", "math", "sym", "greekwith"]+ .iter()+ .any(|s| base.contains(s))+ // TeX math fonts (Computer Modern / AMS / txfonts / xy-pic): glyph codes for+ // operators and delimiters map to control positions by design.+ || ["cmex", "cmsy", "cmmi", "msam", "msbm", "rtxm", "rtxs", "txex", "txsy", "xyatip",+ "xydash", "eufm", "esint", "stmary", "wasy"]+ .iter()+ .any(|p| base.starts_with(p))+ })+}++/// Control characters (other than tab / newline / carriage return) in extracted text. A+/// correct ToUnicode map never yields them; a cipher-like or truncated map does, often as the+/// space glyph (`\x03`), digits (`\x13\x14`) or punctuation ("$SULO \x15\x15\x0f" = "April 22,").+fn control_chars(text: &str) -> (usize, usize) {+ let mut ctrl = 0;+ let mut visible = 0;+ for c in text.chars() {+ if c.is_control() && !matches!(c, '\t' | '\n' | '\r') {+ ctrl += 1;+ } else if !c.is_whitespace() {+ visible += 1;+ }+ }+ (ctrl, visible + ctrl)+}++const CONTROL_MIN: usize = 5;+const CONTROL_MIN_RATE: f32 = 0.02;++fn controls_are_garbled(ctrl: usize, chars: usize) -> bool {+ ctrl >= CONTROL_MIN && ctrl as f32 >= chars as f32 * CONTROL_MIN_RATE+}++/// Coarse script of a letter for [`token_is_malformed`]: 0 Latin, 1 CJK (Han, kana, Hangul and+/// their fullwidth forms, which share tokens with Latin and each other in unspaced text),+/// otherwise an id per script from a table of the scripts we can tell apart (so Tamil and Telugu+/// differ, while the blocks of one script agree); unlisted scripts share one id.+fn script_of(c: char) -> u32 {+ let o = c as u32;+ match o {+ 0..=0x24F | 0x1E00..=0x1EFF | 0x2C60..=0x2C7F | 0xA720..=0xA7FF => 0,+ 0x1100..=0x11FF+ | 0x3000..=0x30FF+ | 0x3400..=0x9FFF+ | 0xAC00..=0xD7AF+ | 0xF900..=0xFAFF+ | 0xFF00..=0xFFEF => 1,+ // Scripts whose letters span several blocks are one script each: polytonic Greek and+ // Coptic, Cyrillic extensions, Hebrew / Arabic presentation forms, Ethiopic, Georgian.+ 0x0370..=0x03FF | 0x1F00..=0x1FFF | 0x2C80..=0x2CFF => 0x370,+ 0x0400..=0x052F | 0x1C80..=0x1C8F | 0x2DE0..=0x2DFF | 0xA640..=0xA69F => 0x400,+ 0x0590..=0x05FF | 0xFB1D..=0xFB4F => 0x590,+ 0x0600..=0x06FF | 0x0750..=0x077F | 0x0860..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => {+ 0x600+ }+ 0x1200..=0x139F | 0x2D80..=0x2DDF | 0xAB00..=0xAB2F => 0x1200,+ 0x10A0..=0x10FF | 0x1C90..=0x1CBF | 0x2D00..=0x2D2F => 0x10A0,+ 0x1780..=0x17FF | 0x19E0..=0x19FF => 0x1780,+ 0x1000..=0x109F | 0xA9E0..=0xA9FF | 0xAA60..=0xAA7F => 0x1000,+ 0x0530..=0x058F | 0xFB13..=0xFB17 => 0x530,+ 0x0700..=0x074F => 0x700,+ // Indic scripts sit in exact 128-codepoint blocks+ 0x0900..=0x0DFF => o & !0x7F,+ 0x0E00..=0x0E7F => 0xE00,+ 0x0E80..=0x0EFF => 0xE80,+ 0x0F00..=0x0FFF => 0xF00,+ // anything else is one bucket: never counted as a script mix+ _ => 2,+ }+}++/// A token whose shape no correctly decoded text has (see [`garbled_scope`]):+/// - a case flip into a short lowercase run, or two flips, inside a word ("hZeY", "cVdaVTe",+/// "ÞkusLkkykuÚke"); camelCase starts a real sub-word ("DataEncoder", "iPhone") and+/// identifiers with `_` `.` `/` are skipped;+/// - `;` or `=` between letters ("iNdm;s;=udf.a", legacy Sinhala / Tamil fonts);+/// - letters of two different non-Latin, non-CJK scripts ("ࡶڜటర"), or an accented Latin letter+/// glued to one ("ประสงคŤ", Thai tone marks mapped into Latin Extended).+///+/// `None` when the token is too short to judge.+fn token_is_malformed(tok: &str) -> Option<bool> {+ if tok.contains('$') || tok.contains('\\') {+ return None; // LaTeX written by the TeX math pass+ }+ let t = tok.trim_matches(|c: char| !c.is_alphanumeric());+ let cs: Vec<char> = t.chars().collect();+ if cs.len() < 3 || cs.iter().filter(|c| c.is_alphabetic()).count() < 2 {+ return None;+ }+ if !cs.iter().any(|&c| matches!(c, '_' | '.' | '/' | '@')) {+ let mut flips = 0;+ let mut short = false;+ for i in 1..cs.len().saturating_sub(1) {+ if cs[i - 1].is_lowercase() && cs[i].is_uppercase() && cs[i + 1].is_lowercase() {+ flips += 1;+ let run = cs[i + 1..].iter().take_while(|c| c.is_lowercase()).count();+ short |= run < 3;+ }+ }+ if flips >= 2 || short {+ return Some(true);+ }+ }+ if (1..cs.len().saturating_sub(1)).any(|i| {+ matches!(cs[i], ';' | '=') && cs[i - 1].is_alphabetic() && cs[i + 1].is_alphabetic()+ }) {+ return Some(true);+ }+ let other =+ |c: char| c.is_alphabetic() && !(0x300..=0x36F).contains(&(c as u32)) && script_of(c) > 1;+ let mut seen: Option<u32> = None;+ for &c in &cs {+ if other(c) {+ let s = script_of(c);+ if seen.is_some_and(|p| p != s) {+ return Some(true);+ }+ seen = Some(s);+ }+ }+ let accented = |c: char| c.is_alphabetic() && (0xC0..=0x24F).contains(&(c as u32));+ if cs+ .windows(2)+ .any(|w| (accented(w[0]) && other(w[1])) || (other(w[0]) && accented(w[1])))+ {+ return Some(true);+ }+ Some(false)+}++/// (judged tokens, malformed tokens) in `text`, control characters read as spaces.+fn malformed_tokens(text: &str) -> (usize, usize) {+ let clean: String = text+ .chars()+ .map(|c| if c.is_control() { ' ' } else { c })+ .collect();+ clean+ .split_whitespace()+ .filter_map(token_is_malformed)+ .fold((0, 0), |(n, b), m| (n + 1, b + m as usize))+}++const MALFORMED_MIN: usize = 10;+const MALFORMED_MIN_RATE: f32 = 0.2;++fn tokens_are_garbled(judged: usize, malformed: usize) -> bool {+ malformed >= MALFORMED_MIN && malformed as f32 >= judged as f32 * MALFORMED_MIN_RATE+}++fn symbols_are_garbled(letters: usize, intrusions: usize) -> bool {+ intrusions >= SYMBOL_MIN && intrusions as f32 >= letters as f32 * SYMBOL_MIN_RATE+}++fn intrusions_are_garbled(script: usize, intrusions: usize) -> bool {+ intrusions >= INTRUSION_MIN && intrusions as f32 >= script as f32 * INTRUSION_MIN_RATE+}+/// Page-level garbled signal: substitution-cipher text (see [`garbled_scope`])/// or a substantial share of text whose Unicode mapping failed outright.fn page_is_garbled(page: &Page) -> bool {@@ -1817,6 +2352,59 @@ mod tests {use super::*;use crate::types::Rect;+ #[test]+ fn malformed_tokens_flag_cipher_and_legacy_fonts() {+ // Shifted / cipher ToUnicode maps (ParseBench v2 att10k, financial tables, legacy Indic).+ for t in [+ "hZeY",+ "cVdaVTe",+ "bViZgAVah",+ "ÞkusLkkykuÚke",+ "iNdm;s;=udf.a",+ "ࡶڜటర",+ "ประสงคŤ",+ ] {+ assert_eq!(token_is_malformed(t), Some(true), "{t}");+ }+ // camelCase, brand casing, identifiers, CJK with Latin, ordinary words and codes.+ for t in [+ "DataEncoder",+ "ShannonOverbrook",+ "iPhone",+ "McDonald",+ "fact_api.FactApi",+ "ExpRatio_Excluded",+ "iPhone発売",+ "Washington",+ "1G1FJ3D6&H",+ "W3GG",+ "ἀρχῇ",+ "ⲁⲣⲭⲏ",+ "ሀገርሰላም",+ "Ϣⲁⲣⲉ",+ "հոկտեմբերի",+ "Հանրապետությունում",+ "བསྟན་པའི",+ ] {+ assert_eq!(token_is_malformed(t), Some(false), "{t}");+ }+ assert_eq!(token_is_malformed("ab"), None);+ }++ #[test]+ fn control_chars_flag_broken_maps_not_dingbats() {+ // "April 22, 2025 - Page" through a -3 shift with digits mapped to control codes.+ let (c, n) = control_chars("$SULO \u{15}\u{15}\u{f} \u{15}\u{13}\u{15}\u{18} \u{10} 3DJH");+ assert!(controls_are_garbled(c, n));+ assert_eq!(control_chars("Plain text\twith tabs\n"), (0, 17));+ assert!(is_symbol_font(Some("ZQNKFZ+Wingdings2")));+ assert!(is_symbol_font(Some("VTJFIN+Webdings")));+ assert!(!is_symbol_font(Some("ArialMT")));+ assert!(is_symbol_font(Some("ABCDEF+CMEX10")));+ assert!(is_symbol_font(Some("Universal-GreekwithMathPi")));+ assert!(!is_symbol_font(Some("TimesNewRomanPS-ItalicMT")));+ }+#[test]fn rule_artifact_catches_bars_and_decoration() {// Tesseract reading a table border / hairline.@@ -1980,6 +2568,7 @@ mod tests {fn page(items: Vec<TextItem>) -> Page {Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 612.0,@@ -2278,6 +2867,7 @@ mod tests {fn make_blank_page(page_number: usize) -> Page {Page {+ ocr_deskew: None,page_number,page_label: None,page_width: 100.0,@@ -2493,6 +3083,7 @@ mod tests {OcrRaster {has_native_text: false,image_rects: Vec::new(),+ replace_native: false,page_number: idx + 1,// 1x1 grayscale pixel; the engine never inspects it.pixels: vec![0u8],@@ -2522,6 +3113,7 @@ mod tests {// also contains an image.fn make_native_text_page(page_number: usize) -> Page {Page {+ ocr_deskew: None,page_number,page_label: None,page_width: 100.0,@@ -2551,6 +3143,7 @@ mod tests {// swallowed.fn make_low_coverage_text_page(page_number: usize) -> Page {Page {+ ocr_deskew: None,page_number,page_label: None,page_width: 100.0,@@ -2762,6 +3355,7 @@ mod tests {dpi: 72.0,has_native_text: false,image_rects: Vec::new(),+ replace_native: false,results: vec![OcrResult {text: "hello".into(),diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex 253b10f..6cf7a9f 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -193,6 +193,52 @@ pub struct LiteParse {glyph_resolver: Option<std::sync::Arc<dyn crate::GlyphResolver>>,}+/// Undo the OCR merge's deskew (`Page::ocr_deskew`) on a page's output geometry: projection+/// and layout ran on upright OCR items, but the boxes a caller reads must match the image.+/// Each box becomes the axis-aligned bound of itself rotated back by `deg` about the page+/// centre. Only OCR items move (native items were never rotated); layout blocks and their+/// table cells are built from those items, so they move too.+fn rotate_back_ocr_boxes(page: &mut ParsedPage, deg: f32) {+ let (cx, cy) = (page.page_width / 2.0, page.page_height / 2.0);+ let back = |x: f32, y: f32, w: f32, h: f32| -> (f32, f32, f32, f32) {+ let pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]+ .map(|(px, py)| crate::ocr_merge::rotate_about(px, py, cx, cy, deg));+ let x0 = pts.iter().map(|p| p.0).fold(f32::INFINITY, f32::min);+ let x1 = pts.iter().map(|p| p.0).fold(f32::NEG_INFINITY, f32::max);+ let y0 = pts.iter().map(|p| p.1).fold(f32::INFINITY, f32::min);+ let y1 = pts.iter().map(|p| p.1).fold(f32::NEG_INFINITY, f32::max);+ (x0, y0, x1 - x0, y1 - y0)+ };+ let rect = |r: &mut crate::types::Rect| {+ (r.x, r.y, r.width, r.height) = back(r.x, r.y, r.width, r.height);+ };+ for item in page+ .text_items+ .iter_mut()+ .filter(|i| i.confidence.is_some())+ {+ (item.x, item.y, item.width, item.height) = back(item.x, item.y, item.width, item.height);+ for w in &mut item.words {+ (w.x, w.y, w.width, w.height) = back(w.x, w.y, w.width, w.height);+ }+ }+ for block in page.blocks.iter_mut().flatten() {+ if let Some(r) = block.bbox.as_mut() {+ rect(r);+ }+ for cell in block+ .header+ .iter_mut()+ .flatten()+ .chain(block.rows.iter_mut().flatten().flatten())+ {+ if let Some(r) = cell.bbox.as_mut() {+ rect(r);+ }+ }+ }+}+/// Run block classification once and fan the result out to everything that/// needs it: the rendered per-page markdown (when Markdown is the output/// format) and each page's `blocks` (when `extract_blocks` is on).@@ -848,6 +894,12 @@ impl LiteParse {// crop region, and before projection so filtered items never surface.stages::apply_content_filters(&mut pages, &self.content_filters());+ // Pages the OCR merge deskewed: their output boxes are rotated back after layout.+ let deskews: Vec<(usize, f32)> = pages+ .iter()+ .filter_map(|p| p.ocr_deskew.map(|deg| (p.page_number, deg)))+ .collect();+// Grid projectionlet mut parsed_pages = stages::project(pages);@@ -888,6 +940,14 @@ impl LiteParse {if self.config.output_format == crate::config::OutputFormat::Markdown {stages::canonicalize_image_refs(&mut parsed_pages, &mut full_text, &images);}+ for (page_number, deg) in &deskews {+ if let Some(page) = parsed_pages+ .iter_mut()+ .find(|p| p.page_number == *page_number)+ {+ rotate_back_ocr_boxes(page, *deg);+ }+ }let total = web_time::Instant::now().duration_since(t0).as_secs_f64() * 1000.0;log(&format!("[liteparse] total: {:.1}ms", total));@@ -1237,6 +1297,7 @@ mod tests {fn page_with_text_metadata() -> Page {Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 100.0,diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex 414b569..5309c50 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -119,6 +119,25 @@ fn canonical_rotation(rotation: f32) -> i32 {}}+/// Append `right` (the item to the right on the page) to `left` in reading order: after it for+/// a left-to-right pair, before it when the pair reads right to left (Hebrew / Arabic words+/// PDFium emitted as separate runs). Joining in x order reversed RTL word order.+fn join_in_reading_order(left: &mut String, right: &str, sep: &str) {+ if crate::bidi::is_rtl_pieces([left.as_str(), right]) {+ let mut joined = right.trim_end().to_string();+ if !sep.is_empty() && !joined.is_empty() {+ joined.push_str(sep);+ }+ joined.push_str(left.trim_start());+ *left = joined;+ } else {+ if !sep.is_empty() && !left.ends_with(' ') {+ left.push_str(sep);+ }+ left.push_str(right);+ }+}+fn handle_rotation_reading_order(items: &mut [ProjectedTextItem], page_height: f32) {if !items.iter()@@ -829,7 +848,7 @@ fn form_lines(&& delta_x <= MERGE_THRESHOLD{prev.item.width = item.item.x + item.item.width - prev.item.x;- prev.item.text.push_str(&item.item.text);+ join_in_reading_order(&mut prev.item.text, &item.item.text, "");prev.item.words.append(&mut item.item.words);merge_orig_bbox(prev, &item);continue;@@ -839,10 +858,7 @@ fn form_lines(let avg_char_width = prev.item.width / prev_len;if y_compatible && !both_are_numbers && delta_x < avg_char_width {prev.item.width = item.item.x + item.item.width - prev.item.x;- if !prev.item.text.ends_with(' ') {- prev.item.text.push(' ');- }- prev.item.text.push_str(&item.item.text);+ join_in_reading_order(&mut prev.item.text, &item.item.text, " ");prev.item.words.append(&mut item.item.words);merge_orig_bbox(prev, &item);continue;@@ -3167,6 +3183,31 @@ const XY_COLUMN_PEAK_BALANCE_RATIO: f32 = 0.4;/// detector) on sparse tabular layouts.const XY_COLUMN_MIN_FILL: f32 = 0.55;+/// An equation number set at a column edge: "(22)", "(3.14)", "(A.2)".+fn is_equation_number(text: &str) -> bool {+ let t = text.trim();+ let Some(inner) = t.strip_prefix('(').and_then(|r| r.strip_suffix(')')) else {+ return false;+ };+ !inner.is_empty()+ && inner.len() <= 6+ && inner.chars().any(|c| c.is_ascii_digit())+ && inner.chars().all(|c| c.is_ascii_alphanumeric() || c == '.')+}++/// Text with no run of three letters: a matrix entry, a bracket piece or an+/// accent the math pass left behind ("0", "¯", ", B =").+fn is_formula_fragment(text: &str) -> bool {+ let mut run = 0;+ for c in text.chars() {+ run = if c.is_alphabetic() { run + 1 } else { 0 };+ if run >= 3 {+ return false;+ }+ }+ !text.trim().is_empty()+}+/// A peak whose band count is below this fraction of the most-banded column's/// is treated as a figure-scatter "phantom" (axis tick labels, a point cloud/// spread across x) rather than a real column. Real table columns have one@@ -3585,15 +3626,8 @@ fn xy_find_column_cut(median_h: f32,tabular: &mut bool,) -> Option<CutCandidate> {- let dbg = std::env::var("LITEPARSE_DEBUG_XY").is_ok();- macro_rules! reject {- ($($t:tt)*) => {{- if dbg { eprintln!("[xy col-reject] {}", format!($($t)*)); }- return None;- }};- }if bbox.width <= 1.0 || idxs.len() < 8 {- reject!("preflight: width={:.1} items={}", bbox.width, idxs.len());+ return None;}// Identify "line-start" items: within each y-band, the first item of@@ -3605,7 +3639,20 @@ fn xy_find_column_cut(// column) because the inter-column gutter exceeds `gutter_gap`, so we// don't collapse a band to its single leftmost item.let band_tol = (median_h * 0.5).max(2.0);- let gutter_gap = median_h.max(4.0);+ // OCR items are whole detected lines, not PDF word fragments: two of them in one band+ // are split at a column gutter (or a cell boundary, which the fill gate below handles),+ // never at a word space. Scans' tight gutters (~0.6-0.8 line heights on newspaper pages)+ // fail the native one-line-height test, and the near-start rescue needs sub-point edge+ // alignment that OCR boxes don't have, so N-column scans were read row by row.+ let ocr_items = idxs+ .iter()+ .filter(|&&i| items[i].item.confidence.is_some())+ .count();+ let gutter_gap = if ocr_items * 2 > idxs.len() {+ (median_h * 0.5).max(4.0)+ } else {+ median_h.max(4.0)+ };let mut sorted: Vec<usize> = idxs.to_vec();sorted.sort_by(|&a, &b| {@@ -3653,11 +3700,7 @@ fn xy_find_column_cut(}if line_starts.len() < 8 {- reject!(- "line_starts={} < 8 (items={})",- line_starts.len(),- idxs.len()- );+ return None;}// Histogram extent uses full item bounds so `XY_COLUMN_MIN_GAP_FRACTION`@@ -3673,7 +3716,7 @@ fn xy_find_column_cut(}}if !min_x.is_finite() || max_x <= min_x + 1.0 {- reject!("degenerate extent min_x={min_x:.1} max_x={max_x:.1}");+ return None;}let total_w = max_x - min_x;let bucket_pt = XY_COLUMN_BUCKET_PT;@@ -3712,11 +3755,6 @@ fn xy_find_column_cut(}}}- if dbg && rescued > 0 {- eprintln!(- "[xy col-rescue] {rescued} near-gap starts (gap in [{near_gap_floor:.1},{gutter_gap:.1}]) exactly aligned to >=2 strict starts"- );- }}let n_starts = line_starts.len() + rescued;@@ -3753,7 +3791,6 @@ fn xy_find_column_cut(// Keep only "strong" peaks. A real column edge is sat-stacked by many// lines at the same left x; spurious peaks (a stray indented quote, a// numbered marker, etc.) carry only a few lines.- let strong_before = peaks.len();let raw_counts: Vec<(f32, usize)> = peaks.clone();// Adaptive minimum: scale with how many line-starts the band actually has.// The static `XY_COLUMN_MIN_LINES_PER_PEAK = 10` floor is meant to drop@@ -3795,31 +3832,8 @@ fn xy_find_column_cut(if sparse {*tabular = true;}- if dbg {- eprintln!(- "[xy col-weak-peaks] {} balanced raw peaks (min={raw_min} max={raw_max}) dominance={dominance:.2} min_fill={min_fill:.2} avg_fill={avg_fill:.2} — {}",- raw_counts.len(),- if sparse {- "tabular, no cut"- } else {- "filled (prose), not tabular"- }- );- }}}- if dbg {- let preview: Vec<String> = raw_counts- .iter()- .take(8)- .map(|(x, c)| format!("({x:.0}:{c})"))- .collect();- eprintln!(- "[xy col-reject] peaks<2 after min_per_peak={adaptive_min} (raw={strong_before} strong={}): {}",- peaks.len(),- preview.join(",")- );- }return None;}peaks.sort_by(|a, b| a.0.total_cmp(&b.0));@@ -3854,40 +3868,17 @@ fn xy_find_column_cut(// whose cells don't tightly left-cluster (numeric columns are// typically right-aligned / centered, so they never form// strong left-edge peaks and fail dominance here).- let before = peaks.len();peaks.retain(|(_, c)| {largest <= 0.0 || (*c as f32) / largest >= XY_COLUMN_PEAK_BALANCE_RATIO});if peaks.len() < 2 {- reject!("peaks>2 but <2 balanced (largest={largest})");- }- if dbg {- eprintln!(- "[xy col-keep-N] kept {} of {} balanced peaks (N-column); xs=[{}]",- peaks.len(),- before,- peaks- .iter()- .map(|(x, c)| format!("{x:.0}:{c}"))- .collect::<Vec<_>>()- .join(",")- );+ return None;}} else {// Top-2 dominate → assume real columns + weak floats. Keep// top-2 (re-sorted left→right) and continue.let mut top2 = vec![by_count[0], by_count[1]];top2.sort_by(|a, b| a.0.total_cmp(&b.0));- if dbg {- eprintln!(- "[xy col-keep-top2] dropped {} weak peaks; kept xs=[{:.0}:{},{:.0}:{}]",- peaks.len() - 2,- top2[0].0,- top2[0].1,- top2[1].0,- top2[1].1- );- }peaks = top2;}}@@ -3902,6 +3893,11 @@ fn xy_find_column_cut(let mut n = peaks.len();let mut covered_sum = vec![0.0f32; n];let mut band_count = vec![0usize; n];+ // Bands where everything in the column is display math or an+ // equation number (`math_bands`), or that plus formula fragments the+ // math pass left as text (`formula_bands`).+ let mut math_bands = vec![0usize; n];+ let mut formula_bands = vec![0usize; n];let mut kk = 0;while kk < sorted.len() {let by = items[sorted[kk]].item.y;@@ -3911,6 +3907,8 @@ fn xy_find_column_cut(}let mut lo_x = vec![f32::INFINITY; n];let mut hi_x = vec![f32::NEG_INFINITY; n];+ let mut all_math = vec![true; n];+ let mut all_formula = vec![true; n];for &idx in &sorted[kk..jj] {let it = &items[idx].item;if !it.x.is_finite() {@@ -3926,6 +3924,9 @@ fn xy_find_column_cut(}lo_x[c] = lo_x[c].min(it.x);hi_x[c] = hi_x[c].max(it.x + it.width.max(0.0));+ let math = it.math || is_equation_number(&it.text);+ all_math[c] &= math;+ all_formula[c] &= math || is_formula_fragment(&it.text);}for c in 0..n {if hi_x[c] > lo_x[c] {@@ -3937,6 +3938,12 @@ fn xy_find_column_cut(if col_w > 1.0 {covered_sum[c] += ((hi_x[c] - lo_x[c]) / col_w).min(1.0);band_count[c] += 1;+ if all_math[c] {+ math_bands[c] += 1;+ }+ if all_formula[c] {+ formula_bands[c] += 1;+ }}}}@@ -3977,21 +3984,6 @@ fn xy_find_column_cut(} else {f32::INFINITY};- if dbg {- eprintln!(- "[xy col-fill] avg_fill={avg_fill:.2} min_fill={min_fill:.2} (gate={XY_COLUMN_MIN_FILL}) per_col=[{}] band_counts=[{}]",- per_col_fill- .iter()- .map(|f| format!("{f:.2}"))- .collect::<Vec<_>>()- .join(","),- band_count- .iter()- .map(|c| c.to_string())- .collect::<Vec<_>>()- .join(",")- );- }const MIN_FILL_HARD_FLOOR: f32 = 0.38;// Figure-scatter phantom column: on a 2-column page with an embedded// plot (scatter cloud, axis tick labels), the plot's x-spread items@@ -4014,9 +4006,20 @@ fn xy_find_column_cut(0.0}};- let survivors: Vec<usize> = (0..n)- .filter(|&c| !(band_count[c] < band_floor && col_fill(c) < MIN_FILL_HARD_FLOOR))- .collect();+ // Note: display equations and their numbers inside a prose+ // column line up into the same sparse, low-fill peak (a+ // two-column paper read as a table); a column made mostly+ // of math bands is a phantom at any band count.+ // Dropping still needs the surviving columns to read as+ // prose, so a numeric table column keeps the region tabular.+ let display_math = |c: usize| {+ math_bands[c] * 3 >= band_count[c] && formula_bands[c] * 3 >= band_count[c] * 2+ };+ let phantom = |c: usize| {+ col_fill(c) < MIN_FILL_HARD_FLOOR+ && (band_count[c] < band_floor || display_math(c))+ };+ let survivors: Vec<usize> = (0..n).filter(|&c| !phantom(c)).collect();let survivors_filled = survivors.iter().all(|&c| col_fill(c) >= MIN_FILL_HARD_FLOOR);@@ -4031,16 +4034,6 @@ fn xy_find_column_cut(wsum += f * band_count[c] as f32;wn += band_count[c] as f32;}- if dbg {- eprintln!(- "[xy col-phantom] dropped {} sparse low-fill peak(s) (band_floor={band_floor}); kept xs=[{}]",- n - survivors.len(),- kept.iter()- .map(|(x, _)| format!("{x:.0}"))- .collect::<Vec<_>>()- .join(",")- );- }peaks = kept;n = peaks.len();min_fill = new_min;@@ -4056,14 +4049,11 @@ fn xy_find_column_cut(// needed column split AND the density V via the tabular flag.if n > 2 && min_fill.is_finite() && min_fill < MIN_FILL_HARD_FLOOR {*tabular = true;- reject!("N-column min fill {min_fill:.2} < {MIN_FILL_HARD_FLOOR} (tabular column)");+ return None;}if avg_fill.is_finite() && avg_fill < XY_COLUMN_MIN_FILL {*tabular = true;- reject!(- "N-column avg fill {avg_fill:.2} < {} (tabular)",- XY_COLUMN_MIN_FILL- );+ return None;}}// Require the two peaks to together dominate the histogram — a real@@ -4073,10 +4063,7 @@ fn xy_find_column_cut(let peak_sum: usize = peaks.iter().map(|(_, c)| *c).sum();let dominance = (peak_sum as f32) / (n_starts as f32);if dominance < XY_COLUMN_PEAK_DOMINANCE {- reject!(- "dominance {dominance:.2} < {} (peak_sum={peak_sum} line_starts={n_starts})",- XY_COLUMN_PEAK_DOMINANCE- );+ return None;}// Require the peaks to be roughly balanced in size. A real multi-column// layout has comparable line counts in each column; a long-single-column@@ -4092,11 +4079,7 @@ fn xy_find_column_cut(0.0};if balance < XY_COLUMN_PEAK_BALANCE_RATIO {- reject!(- "balance {balance:.2} < {} (min={smallest} max={largest} npeaks={})",- XY_COLUMN_PEAK_BALANCE_RATIO,- peaks.len()- );+ return None;}// Cut at the leftmost gutter that clears `XY_COLUMN_MIN_GAP_FRACTION ×@@ -4116,14 +4099,7 @@ fn xy_find_column_cut(}let li = match best {Some((_, li)) => li,- None => reject!(- "no gap >= {:.0} (min_gap_frac={} total_w={total_w:.0}); peak_xs=[{:.0},{:.0}] gap={:.0}",- min_gap,- XY_COLUMN_MIN_GAP_FRACTION,- peaks[0].0,- peaks[1].0,- peaks[1].0 - peaks[0].0- ),+ None => return None,};// Place the cut at the actual gutter, not midway between peak centers.// Peaks mark column LEFT edges, so the center midpoint lands inside the@@ -4163,7 +4139,7 @@ fn xy_find_column_cut(// off the items (some PDFs have content with negative x), fall back to// an item-relative midpoint check.if cut_x <= min_x + 1.0 || cut_x >= max_x - 1.0 {- reject!("cut_x {cut_x:.0} outside extent [{min_x:.0},{max_x:.0}]");+ return None;}// High finite score so this beats every density cut but stays below// banner's infinity.@@ -4349,54 +4325,7 @@ fn xy_cut_rec(} else {None};- let debug_xy = std::env::var("LITEPARSE_DEBUG_XY").is_ok();let disable_vcut_minlines = std::env::var("LITEPARSE_DISABLE_VCUT_MINLINES").is_ok();- if debug_xy && depth == 0 && std::env::var("LITEPARSE_DEBUG_ITEMS").is_ok() {- for &i in &idxs {- let it = &items[i].item;- eprintln!(- "[xy item] x={:.1} w={:.1} y={:.1} h={:.1} text={:?}",- it.x,- it.width,- it.y,- it.height,- &it.text.chars().take(80).collect::<String>()- );- }- }- if debug_xy {- // Also probe what the column histogram WOULD return if we ran it- // unconditionally — this is the diagnostic that tells us whether- // reordering V/H/column priority would unlock more column splits.- let column_probe = column_full;- let pad = " ".repeat(depth as usize);- let fmt = |c: &Option<CutCandidate>| {- c.as_ref()- .map(|c| format!("{:?}@{:.1}/{:.3}", c.axis, c.position, c.score))- .unwrap_or_else(|| "-".to_string())- };- let fmt_pos = |p: &Option<f32>| {- p.as_ref()- .map(|p| format!("{p:.1}"))- .unwrap_or_else(|| "-".to_string())- };- let (ex0, ex1) = x_extent(items, &idxs);- let lines = xy_distinct_lines(items, &idxs, median_h);- eprintln!(- "[xy d={depth}]{pad} bbox=({:.0},{:.0} {:.0}x{:.0}) items={} lines={} x_ext=[{ex0:.1},{ex1:.1}] banner={} h={} v={} col={} col_probe={}",- bbox.x,- bbox.y,- bbox.width,- bbox.height,- idxs.len(),- lines,- fmt(&banner),- fmt(&h),- fmt(&v),- fmt_pos(&column.as_ref().map(|c| c.position)),- fmt_pos(&column_probe.as_ref().map(|c| c.position)),- );- }// Build a priority-ordered candidate list.//// **Primary** is the cut chosen by the main resolution order@@ -4429,20 +4358,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 effective_tabular {- if debug_xy && v.is_some() {- let pad = " ".repeat(depth as usize);- let reason = if region_tabular {- "region tabular"- } else {- "region tabular, inherited"- };- eprintln!("[xy d={depth}]{pad} -> SUPPRESS density V ({reason})");- }- None- } else {- v- };+ let v = if effective_tabular { None } else { v };if prefer_h_over_v {if let Some(hc) = h {candidates.push(hc);@@ -4470,13 +4386,6 @@ fn xy_cut_rec(}for cut in candidates {- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!(- "[xy d={depth}]{pad} -> TRY {:?}@{:.1}/{:.3}",- cut.axis, cut.position, cut.score- );- }let mut left: Vec<usize> = Vec::new();let mut right: Vec<usize> = Vec::new();// Column-histogram V-cuts (score = 1.0e9) split between two column@@ -4557,15 +4466,6 @@ fn xy_cut_rec(const STRADDLE_PARTITION_FRACTION: f32 = 0.25;let partition_by_item = rows_total > 0&& (rows_straddle as f32) / (rows_total as f32) >= STRADDLE_PARTITION_FRACTION;- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!(- "[xy d={depth}]{pad} hist-v straddle={}/{} → partition_by_{}",- rows_straddle,- rows_total,- if partition_by_item { "item" } else { "row" }- );- }if partition_by_item {for &i in &idxs {@@ -4615,19 +4515,7 @@ fn xy_cut_rec(}}}- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!(- "[xy d={depth}]{pad} partition: left={} right={}",- left.len(),- right.len()- );- }if left.is_empty() || right.is_empty() {- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!("[xy d={depth}]{pad} -> degenerate, try next");- }continue;}let (left_bbox, right_bbox) = xy_split_bbox(&bbox, &cut);@@ -4676,12 +4564,6 @@ fn xy_cut_rec(})};if (lc < XY_MIN_LINES_PER_H_SIDE || rc < XY_MIN_LINES_PER_H_SIDE) && !spanning_rescue {- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!(- "[xy d={depth}]{pad} -> min-lines fail (lc={lc} rc={rc}), try next"- );- }continue;}}@@ -4699,23 +4581,10 @@ fn xy_cut_rec(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 {- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!(- "[xy d={depth}]{pad} -> v-cut min-lines fail (lc={lc} rc={rc}), try next"- );- }continue;}}- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!(- "[xy d={depth}]{pad} -> COMMIT {:?}@{:.1}",- cut.axis, cut.position- );- }let child_inherited_tabular = effective_tabular && cut.axis == CutAxis::Horizontal;let left_region = xy_cut_rec(items,@@ -4744,10 +4613,6 @@ fn xy_cut_rec(};}- if debug_xy {- let pad = " ".repeat(depth as usize);- eprintln!("[xy d={depth}]{pad} -> LEAF (no valid cut)");- }Region {bbox,kind: RegionKind::Leaf { item_indices: idxs },@@ -5237,6 +5102,19 @@ fn build_one_line(mod tests {use super::*;+ #[test]+ fn equation_numbers_and_formula_fragments() {+ assert!(is_equation_number("(22)"));+ assert!(is_equation_number(" (3.14) "));+ assert!(is_equation_number("(A.2)"));+ assert!(!is_equation_number("(see above)"));+ assert!(!is_equation_number("(a)"));+ assert!(is_formula_fragment("0"));+ assert!(is_formula_fragment(", B ="));+ assert!(!is_formula_fragment("which defines the"));+ assert!(!is_formula_fragment(" "));+ }+#[test]fn compress_wide_spaces_preserves_utf8_text() {assert_eq!(@@ -5293,6 +5171,7 @@ mod tests {#[test]fn project_to_grid_handles_text_sparse_zero_width_items() {let page = Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 612.0,@@ -5811,6 +5690,7 @@ mod tests {#[test]fn project_pages_to_grid_handles_page_with_no_text_items() {let pages = vec![Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 612.0,@@ -5837,6 +5717,7 @@ mod tests {fn project_pages_to_grid_unions_original_bbox_when_word_items_merge() {let y = 50.25;let pages = vec![Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 612.0,@@ -5889,6 +5770,7 @@ mod tests {// second item's `words` were silently dropped, truncating `words`.let y = 50.25;let pages = vec![Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 612.0,@@ -5949,6 +5831,7 @@ mod tests {#[test]fn project_pages_to_grid_unions_original_bbox_when_continuous_items_merge() {let pages = vec![Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 612.0,diff --git a/crates/liteparse/src/tex_math/encodings.rs b/crates/liteparse/src/tex_math/encodings.rsnew file mode 100644index 0000000..6564c78--- /dev/null+++ b/crates/liteparse/src/tex_math/encodings.rs@@ -0,0 +1,273 @@+//! TeX math font encodings (OMS = cmsy, OMX = cmex, OML = cmmi, msam):+//! glyph code -> LaTeX, for glyphs PDFium could not map to Unicode.++/// The fixed encoding a TeX math font follows.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum Enc {+ Oml,+ Oms,+ Omx,+ Msam,+}++fn oms(code: u32) -> Option<&'static str> {+ Some(match code {+ 0 => "-",+ 1 => r"\cdot",+ 2 => r"\times",+ 3 => r"\ast",+ 4 => r"\div",+ 5 => r"\diamond",+ 6 => r"\pm",+ 7 => r"\mp",+ 8 => r"\oplus",+ 9 => r"\ominus",+ 10 => r"\otimes",+ 11 => r"\oslash",+ 12 => r"\odot",+ 13 => r"\bigcirc",+ 14 => r"\circ",+ 15 => r"\bullet",+ 16 => r"\asymp",+ 17 => r"\equiv",+ 18 => r"\subseteq",+ 19 => r"\supseteq",+ 20 => r"\leq",+ 21 => r"\geq",+ 22 => r"\preceq",+ 23 => r"\succeq",+ 24 => r"\sim",+ 25 => r"\approx",+ 26 => r"\subset",+ 27 => r"\supset",+ 28 => r"\ll",+ 29 => r"\gg",+ 30 => r"\prec",+ 31 => r"\succ",+ 32 => r"\leftarrow",+ 33 => r"\to",+ 34 => r"\uparrow",+ 35 => r"\downarrow",+ 36 => r"\leftrightarrow",+ 37 => r"\nearrow",+ 38 => r"\searrow",+ 39 => r"\simeq",+ 40 => r"\Leftarrow",+ 41 => r"\Rightarrow",+ 42 => r"\Uparrow",+ 43 => r"\Downarrow",+ 44 => r"\Leftrightarrow",+ 45 => r"\nwarrow",+ 46 => r"\swarrow",+ 47 => r"\propto",+ 48 => "'",+ 49 => r"\infty",+ 50 => r"\in",+ 51 => r"\ni",+ 52 => r"\triangle",+ 53 => r"\triangledown",+ 54 => "NOT",+ 55 => "MAPSTO",+ 56 => r"\forall",+ 57 => r"\exists",+ 58 => r"\neg",+ 59 => r"\emptyset",+ 60 => r"\Re",+ 61 => r"\Im",+ 62 => r"\top",+ 63 => r"\perp",+ 64 => r"\aleph",+ 91 => r"\cup",+ 92 => r"\cap",+ 93 => r"\uplus",+ 94 => r"\wedge",+ 95 => r"\vee",+ 96 => r"\vdash",+ 97 => r"\dashv",+ 98 => r"\lfloor",+ 99 => r"\rfloor",+ 100 => r"\lceil",+ 101 => r"\rceil",+ 102 => r"\{",+ 103 => r"\}",+ 104 => r"\langle",+ 105 => r"\rangle",+ 106 => "|",+ 107 => r"\|",+ 108 => r"\updownarrow",+ 109 => r"\Updownarrow",+ 110 => r"\setminus",+ 111 => r"\wr",+ 112 => r"\surd",+ 113 => r"\amalg",+ 114 => r"\nabla",+ 115 => r"\int",+ 116 => r"\sqcup",+ 117 => r"\sqcap",+ 118 => r"\sqsubseteq",+ 119 => r"\sqsupseteq",+ 120 => r"\S",+ 121 => r"\dagger",+ 122 => r"\ddagger",+ 123 => r"\P",+ 124 => r"\clubsuit",+ 125 => r"\diamondsuit",+ 126 => r"\heartsuit",+ 127 => r"\spadesuit",+ _ => return None,+ })+}++/// cmex: big delimiters read as their plain selves (KaTeX renders `\big(`+/// as "("). Extension pieces of tall delimiters: the top piece stands for+/// the delimiter, the rest map to "".+fn omx(code: u32) -> Option<&'static str> {+ const D: [&str; 16] = [+ "(",+ ")",+ "[",+ "]",+ r"\lfloor",+ r"\rfloor",+ r"\lceil",+ r"\rceil",+ r"\{",+ r"\}",+ r"\langle",+ r"\rangle",+ "|",+ r"\|",+ "/",+ r"\backslash",+ ];+ if code < 16 {+ return Some(D[code as usize]);+ }+ Some(match code {+ 16 | 18 | 32 | 48 => "(",+ 17 | 19 | 33 | 49 => ")",+ 20 | 34 | 50 | 104 => "[",+ 21 | 35 | 51 | 105 => "]",+ 22 | 36 | 106 => r"\lfloor",+ 23 | 37 | 107 => r"\rfloor",+ 24 | 38 | 108 => r"\lceil",+ 25 | 39 | 109 => r"\rceil",+ 26 | 40 | 56 | 110 => r"\{",+ 27 | 41 | 57 | 111 => r"\}",+ 28 | 42 | 68 => r"\langle",+ 29 | 43 | 69 => r"\rangle",+ 30 | 44 | 46 => "/",+ 31 | 45 | 47 => r"\backslash",+ 52..=55 | 58..=67 => "",+ 70 | 71 => r"\bigsqcup",+ 72 | 73 => r"\oint",+ 74 | 75 => r"\bigodot",+ 76 | 77 => r"\bigoplus",+ 78 | 79 => r"\bigotimes",+ 80 | 88 => r"\sum",+ 81 | 89 => r"\prod",+ 82 | 90 => r"\int",+ 83 | 91 => r"\bigcup",+ 84 | 92 => r"\bigcap",+ 85 | 93 => r"\biguplus",+ 86 | 94 => r"\bigwedge",+ 87 | 95 => r"\bigvee",+ 96 | 97 => r"\coprod",+ 98..=100 => "ACC:widehat",+ 101..=103 => "ACC:widetilde",+ 112..=116 => "SQRT",+ _ => return None,+ })+}++/// cmmi non-letters.+fn oml(code: u32) -> Option<&'static str> {+ const GREEK: [&str; 40] = [+ r"\Gamma",+ r"\Delta",+ r"\Theta",+ r"\Lambda",+ r"\Xi",+ r"\Pi",+ r"\Sigma",+ r"\Upsilon",+ r"\Phi",+ r"\Psi",+ r"\Omega",+ r"\alpha",+ r"\beta",+ r"\gamma",+ r"\delta",+ r"\epsilon",+ r"\zeta",+ r"\eta",+ r"\theta",+ r"\iota",+ r"\kappa",+ r"\lambda",+ r"\mu",+ r"\nu",+ r"\xi",+ r"\pi",+ r"\rho",+ r"\sigma",+ r"\tau",+ r"\upsilon",+ r"\phi",+ r"\chi",+ r"\psi",+ r"\omega",+ r"\varepsilon",+ r"\vartheta",+ r"\varpi",+ r"\varrho",+ r"\varsigma",+ r"\varphi",+ ];+ if (code as usize) < GREEK.len() {+ return Some(GREEK[code as usize]);+ }+ Some(match code {+ 58 => ".",+ 59 => ",",+ 60 => "<",+ 61 => "/",+ 62 => ">",+ 63 => r"\star",+ 64 => r"\partial",+ 91 => r"\flat",+ 92 => r"\natural",+ 93 => r"\sharp",+ 96 => r"\ell",+ 123 => r"\imath",+ 124 => r"\jmath",+ 125 => r"\wp",+ 126 => "ACC:vec",+ _ => return None,+ })+}++fn msam(code: u32) -> Option<&'static str> {+ Some(match code {+ 3 => r"\square",+ 4 => r"\blacksquare",+ 6 => r"\Diamond",+ 54 | 44 => r"\leqslant",+ 62 => r"\geqslant",+ 38 => r"\gtrsim",+ 45 => r"\eqslantless",+ 46 => r"\lesssim",+ _ => return None,+ })+}++/// LaTeX for the raw char code of a glyph PDFium gave no Unicode for, in a+/// font following `enc`; None when the encoding has no entry.+pub(crate) fn decode(enc: Enc, code: u32) -> Option<&'static str> {+ match enc {+ Enc::Oms => oms(code),+ Enc::Omx => omx(code),+ Enc::Oml => oml(code),+ Enc::Msam => msam(code),+ }+}diff --git a/crates/liteparse/src/tex_math/mod.rs b/crates/liteparse/src/tex_math/mod.rsnew file mode 100644index 0000000..0f86e52--- /dev/null+++ b/crates/liteparse/src/tex_math/mod.rs@@ -0,0 +1,1341 @@+//! LaTeX from the glyphs of TeX-generated PDF pages, without a model.+//!+//! Math glyphs are recognised by their font (Computer Modern / Latin Modern /+//! tx / px / AMS / Euler / rsfs math fonts); glyphs with no Unicode are read+//! through TeX's fixed encodings (OML / OMS / OMX); sub/superscripts come+//! from glyph size and baseline shift; fractions, overlines and square roots+//! come from thin rules (see [`structures`]).+//!+//! Only born-digital TeX is covered: a page needs a TeX-encoded math font+//! before anything is emitted. Ported from the `bench/math_proto` prototype;+//! comments marked "Note:" carry its traps.++mod encodings;+mod structures;++use std::collections::HashSet;++pub(crate) use encodings::Enc;+pub(crate) use structures::Rule;++/// What PDFium reported for one glyph's text.+#[derive(Debug, Clone, Copy)]+pub(crate) enum RawText {+ /// A clean Unicode mapping.+ Unicode(char),+ /// No Unicode for the glyph (PDFium's map error): the raw char code.+ Code(u32),+}++/// One page glyph, as collected by `extract.rs`. Coordinates are viewport+/// space (y down); `origin_y` is the baseline.+#[derive(Debug, Clone)]+pub(crate) struct RawChar {+ pub(crate) index: i32,+ pub(crate) text: RawText,+ /// Font base name as in the PDF (subset prefix included).+ pub(crate) font_name: std::rc::Rc<str>,+ /// Effective size (font size x text-matrix scale).+ pub(crate) size: f32,+ /// Font descent at `size` (negative, points).+ pub(crate) descent: f32,+ pub(crate) origin_y: f32,+ pub(crate) x0: f32,+ pub(crate) x1: f32,+ /// Tight glyph box (top, bottom), viewport y.+ pub(crate) ink: Option<(f32, f32)>,+ /// Font box (top, bottom), viewport y: the box text items use.+ pub(crate) loose: (f32, f32),+}++/// One math span found on a page.+#[derive(Debug, Clone)]+pub(crate) struct MathSpan {+ pub(crate) tex: String,+ /// Viewport-space box over every glyph in the span.+ pub(crate) x0: f32,+ pub(crate) x1: f32,+ pub(crate) top: f32,+ pub(crate) bottom: f32,+ /// Size of the span's base glyphs.+ pub(crate) size: f32,+ /// Char indices the span consumed.+ pub(crate) chars: Vec<i32>,+}++impl MathSpan {+ /// Whether the span carries structure plain text can't show: scripts,+ /// fractions, roots, accents, or a math alphabet. Note: a lone ± or μ+ /// (or plain Greek) stays text, so table cells like "0.11 ± 0.02" keep+ /// their form.+ pub(crate) fn has_structure(&self) -> bool {+ const MARKS: [&str; 19] = [+ r"\frac",+ r"\sqrt",+ r"\overline",+ r"\mathbb",+ r"\mathcal",+ r"\mathfrak",+ r"\mathscr",+ r"\hat",+ r"\tilde",+ r"\bar",+ r"\dot",+ r"\ddot",+ r"\acute",+ r"\grave",+ r"\check",+ r"\breve",+ r"\vec",+ r"\widehat",+ r"\widetilde",+ ];+ self.tex.contains(['_', '^']) || MARKS.iter().any(|m| self.tex.contains(m))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum Role {+ Mi,+ Sy,+ Bb,+ Ex,+ Frak,+ Scr,+ Cal,+}++/// `prefix` + `rest` where the prefix is one of the tx / px font families.+fn tx_px<'a>(f: &'a str, prefixes: &[&str]) -> impl Iterator<Item = &'a str> {+ prefixes+ .iter()+ .filter_map(move |p| f.strip_prefix(p))+ .collect::<Vec<_>>()+ .into_iter()+}++/// Math font families (subset prefix and size stripped, upper case), checked+/// in order: (role, encoding). The encoding is set when the font follows+/// cmmi / cmsy / cmex (OML / OMS / OMX): a glyph without Unicode is then read+/// through that table, and a capital in an OMS font is `\mathcal`.+fn font_info(f: &str) -> (Option<Role>, Option<Enc>) {+ const TXPX: [&str; 4] = ["TX", "RTX", "PX", "RPX"];+ const TXPX_NEW: [&str; 5] = ["TX", "RTX", "PX", "RPX", "NEWTX"];+ const TXPX_MI: [&str; 7] = ["TX", "RTX", "PX", "RPX", "NEWTX", "ZX", "NTX"];+ let mi_oml = matches!(+ f,+ "CMMI" | "CMMIB" | "LMMATHITALIC" | "MLMMATHITALIC" | "CMBRMI"+ ) || tx_px(f, &TXPX_MI).any(|r| r.starts_with("MI") || r.starts_with("BMI"));+ if mi_oml {+ return (Some(Role::Mi), Some(Enc::Oml));+ }+ if matches!(f, "EURM" | "EURB" | "PAZOMATH-ITALIC" | "STIXMATH-ITALIC")+ || f.contains("MATHITALIC")+ {+ return (Some(Role::Mi), None);+ }+ if matches!(f, "CMSY" | "CMBSY" | "LMMATHSYMBOLS" | "TXBSY" | "TXBSYS")+ || tx_px(f, &TXPX_NEW).any(|r| r == "SY" || r == "SYS")+ {+ return (Some(Role::Sy), Some(Enc::Oms));+ }+ if tx_px(f, &TXPX).any(|r| r == "SYB")+ || matches!(f, "MSBM" | "BBOLD")+ || ["DSROM", "BBM", "PAZOMATHBLACKBOARDBOLD"]+ .iter()+ .any(|p| f.starts_with(p))+ {+ return (Some(Role::Bb), None);+ }+ if matches!(f, "CMEX" | "LMMATHEXTENSION" | "EUEX" | "YHCMEX")+ || f.contains("EXTENSION")+ || tx_px(f, &TXPX_NEW).any(|r| matches!(r, "EX" | "EXA" | "EXS" | "EXAS"))+ {+ return (Some(Role::Ex), Some(Enc::Omx));+ }+ if f == "MSAM" {+ return (Some(Role::Sy), Some(Enc::Msam));+ }+ if matches!(f, "EUFM" | "EUFB") {+ return (Some(Role::Frak), None);+ }+ if f.starts_with("RSFS") || f.starts_with("STIXMATHSCRIPT") {+ return (Some(Role::Scr), None);+ }+ if matches!(f, "EUSM" | "EUSB") {+ return (Some(Role::Cal), None);+ }+ let sy = tx_px(f, &TXPX).any(|r| r == "SYA" || r == "SYC")+ || matches!(+ f,+ "TEX-MATH"+ | "TEX-MATHA"+ | "TEX-MATHB"+ | "TEX-MATHC"+ | "TEX-MATHX"+ | "LASY"+ | "WASY"+ | "OAMATHSYMBOLS"+ | "STIXMATH-REGULAR"+ )+ || ["MNSYMBOL", "STANDARDSYML", "ESINT", "STMARY"]+ .iter()+ .any(|p| f.starts_with(p))+ || f.ends_with("SYMBOL")+ || f.ends_with("SYMBOL-")+ || f.strip_prefix("MATHDESIGN")+ .is_some_and(|r| r.contains("SYMBOL"));+ if sy {+ return (Some(Role::Sy), None);+ }+ (None, None)+}++/// Font family: subset prefix, a `-Regular` suffix and size digits stripped,+/// upper case ("ABCDEF+CMMI10" -> "CMMI").+fn family(font_name: &str) -> String {+ let name = font_name.rsplit_once('+').map_or(font_name, |(_, n)| n);+ let mut up = name.to_uppercase();+ if up.ends_with("-REGULAR") {+ up.truncate(up.len() - "-REGULAR".len());+ }+ let trimmed = up.trim_end_matches(|c: char| c.is_ascii_digit()).len();+ up.truncate(trimmed);+ up+}++const TEXT_FAMS: [&str; 4] = ["CMR", "CMBX", "CMSL", "CMTI"];++/// Prefix marking a glyph text that is already LaTeX (decoded from a TeX+/// encoding, or a folded structure).+const PRE: char = '\0';++const OPERATORS: [&str; 35] = [+ "sin", "cos", "tan", "log", "ln", "exp", "max", "min", "arg", "lim", "det", "tr", "sup", "inf",+ "ker", "dim", "deg", "mod", "sgn", "sinh", "cosh", "tanh", "arcsin", "arccos", "arctan",+ "liminf", "limsup", "Pr", "gcd", "lcm", "Re", "Im", "diag", "rank", "span",+];++fn is_operator(w: &str) -> bool {+ OPERATORS.contains(&w)+}++fn greek(t: &str) -> Option<&'static str> {+ Some(match t {+ "α" => "alpha",+ "β" => "beta",+ "γ" => "gamma",+ "δ" => "delta",+ "ϵ" => "epsilon",+ "ε" => "varepsilon",+ "ǫ" => "epsilon",+ "ζ" => "zeta",+ "η" => "eta",+ "θ" => "theta",+ "ϑ" => "vartheta",+ "ι" => "iota",+ "κ" => "kappa",+ "λ" => "lambda",+ "µ" | "μ" => "mu",+ "ν" => "nu",+ "ξ" => "xi",+ "π" => "pi",+ "ϖ" => "varpi",+ "ρ" => "rho",+ "ϱ" => "varrho",+ "σ" => "sigma",+ "ς" => "varsigma",+ "τ" => "tau",+ "υ" => "upsilon",+ "φ" | "ϕ" => "phi",+ "χ" => "chi",+ "ψ" => "psi",+ "ω" => "omega",+ "Γ" => "Gamma",+ "∆" | "Δ" => "Delta",+ "Θ" => "Theta",+ "Λ" => "Lambda",+ "Ξ" => "Xi",+ "Π" => "Pi",+ "Σ" => "Sigma",+ "Υ" => "Upsilon",+ "Φ" => "Phi",+ "Ψ" => "Psi",+ "Ω" | "\u{2126}" => "Omega",+ _ => return None,+ })+}++fn symbol(t: &str) -> Option<&'static str> {+ Some(match t {+ "∈" => r"\in",+ "∉" => r"\notin",+ "≤" | "⩽" => r"\leq",+ "≥" | "⩾" => r"\geq",+ "≠" => r"\neq",+ "≈" => r"\approx",+ "∼" | "~" => r"\sim",+ "≃" => r"\simeq",+ "≡" => r"\equiv",+ "∝" => r"\propto",+ "≪" => r"\ll",+ "≫" => r"\gg",+ "⊂" => r"\subset",+ "⊆" => r"\subseteq",+ "⊃" => r"\supset",+ "⊇" => r"\supseteq",+ "∪" => r"\cup",+ "∩" => r"\cap",+ "∞" => r"\infty",+ "∂" => r"\partial",+ "∇" => r"\nabla",+ "±" => r"\pm",+ "∓" => r"\mp",+ "×" => r"\times",+ "·" | "⋅" => r"\cdot",+ "÷" => r"\div",+ "∗" | "˚" => r"\ast",+ "◦" | "∘" => r"\circ",+ "→" => r"\to",+ "←" => r"\leftarrow",+ "↔" => r"\leftrightarrow",+ "⇒" => r"\Rightarrow",+ "⇐" => r"\Leftarrow",+ "⇔" => r"\Leftrightarrow",+ "↦" => r"\mapsto",+ "∀" => r"\forall",+ "∃" => r"\exists",+ "¬" => r"\neg",+ "∧" => r"\wedge",+ "∨" => r"\vee",+ "∅" => r"\emptyset",+ "∑" => r"\sum",+ "∏" => r"\prod",+ "∫" => r"\int",+ "∮" => r"\oint",+ "⊗" => r"\otimes",+ "⊕" => r"\oplus",+ "∥" | "‖" => r"\|",+ "⟨" => r"\langle",+ "⟩" => r"\rangle",+ "⌊" => r"\lfloor",+ "⌋" => r"\rfloor",+ "⌈" => r"\lceil",+ "⌉" => r"\rceil",+ "…" => r"\ldots",+ "⋯" => r"\cdots",+ "−" => "-",+ "′" => "'",+ "{" => r"\{",+ "}" => r"\}",+ "\\" | "∖" => r"\setminus",+ "†" => r"\dagger",+ "⊤" => r"\top",+ "⊥" => r"\perp",+ "ℓ" => r"\ell",+ "ı" => r"\imath",+ "ȷ" => r"\jmath",+ "≺" => r"\prec",+ "≻" => r"\succ",+ "⪯" | "≼" => r"\preceq",+ "♯" | "#" => r"\#",+ "%" => r"\%",+ "&" => r"\&",+ "_" => r"\_",+ "^" => r"\hat{}",+ "⊢" => r"\vdash",+ "|" => "|",+ "√" => r"\surd",+ "ℝ" => r"\mathbb{R}",+ "ℕ" => r"\mathbb{N}",+ "ℤ" => r"\mathbb{Z}",+ "ℚ" => r"\mathbb{Q}",+ "ℂ" => r"\mathbb{C}",+ "⊊" => r"\subsetneq",+ "≜" => r"\triangleq",+ "≔" => ":=",+ "⟶" => r"\longrightarrow",+ "⟹" => r"\Longrightarrow",+ "↪" => r"\hookrightarrow",+ "⇀" => r"\rightharpoonup",+ "\u{0338}" => "NOT",+ "\u{f8eb}" => "(",+ "\u{f8ee}" => "[",+ "\u{f8f1}" => r"\{",+ "\u{f8f6}" => ")",+ "\u{f8f9}" => "]",+ "\u{f8fc}" => r"\}",+ "\u{f8ec}" | "\u{f8ed}" | "\u{f8ef}" | "\u{f8f0}" | "\u{f8f2}" | "\u{f8f3}"+ | "\u{f8f4}" | "\u{f8f5}" | "\u{f8f7}" | "\u{f8f8}" | "\u{f8fa}" | "\u{f8fb}"+ | "\u{f8fd}" | "\u{f8fe}" | "\u{f8e5}" => "",+ "⋆" => r"\star",+ "⋄" => r"\diamond",+ "□" => r"\square",+ "△" => r"\triangle",+ _ => return None,+ })+}++const TEXT_MATH_OK: &str = "0123456789()[]{}=+-−,;:!/|.'<>*′";++/// One glyph in the math pass. `top` / `bottom` are viewport y (down),+/// `base` is the baseline in y-up page space (`page height - y`), as in the+/// prototype.+#[derive(Debug, Clone)]+pub(crate) struct G {+ pub(crate) t: String,+ pub(crate) role: Option<Role>,+ pub(crate) fam: String,+ pub(crate) size: f32,+ pub(crate) base: f32,+ pub(crate) x0: f32,+ pub(crate) x1: f32,+ pub(crate) top: f32,+ pub(crate) bottom: f32,+ /// Font box (top, bottom), viewport y, for the span's item box.+ pub(crate) loose: (f32, f32),+ /// Accent commands opened before this glyph, and closed after it.+ pub(crate) pre: String,+ pub(crate) post: String,+ /// Source char indices (several for a folded structure).+ pub(crate) src: Vec<i32>,+}++impl G {+ fn cx(&self) -> f32 {+ (self.x0 + self.x1) / 2.0+ }+ fn enc(&self) -> Option<Enc> {+ font_info(&self.fam).1+ }+}++/// Python `str.isalpha` on a glyph text.+fn is_alpha(t: &str) -> bool {+ !t.is_empty() && t.chars().all(char::is_alphabetic)+}++fn is_ascii_upper(t: &str) -> bool {+ !t.is_empty()+ && t.is_ascii()+ && t.chars().any(|c| c.is_ascii_uppercase())+ && !t.chars().any(|c| c.is_ascii_lowercase())+}++/// Python `statistics.median`.+pub(crate) fn median(mut v: Vec<f32>) -> f32 {+ v.sort_by(f32::total_cmp);+ let n = v.len();+ if n == 0 {+ return 0.0;+ }+ if n % 2 == 1 {+ v[n / 2]+ } else {+ (v[n / 2 - 1] + v[n / 2]) / 2.0+ }+}++fn max_size(gs: &[G], idx: &[usize]) -> f32 {+ idx.iter().map(|&i| gs[i].size).fold(f32::MIN, f32::max)+}++/// Turn collected chars into math-pass glyphs.+fn glyphs(chars: &[RawChar], page_h: f32) -> Vec<G> {+ let mut out = Vec::new();+ let mut fam_cache: std::collections::HashMap<*const u8, (String, Option<Role>, Option<Enc>)> =+ std::collections::HashMap::new();+ for c in chars {+ let (fam, role, enc) = fam_cache+ .entry(c.font_name.as_ptr())+ .or_insert_with(|| {+ let fam = family(&c.font_name);+ let (r, e) = font_info(&fam);+ (fam, r, e)+ })+ .clone();+ // Note: PDFium flags glyphs it could not map; only those are read+ // through the TeX encoding (a ToUnicode'd "{" must stay "{").+ let t = match c.text {+ RawText::Unicode(ch) => {+ if ch.is_whitespace() {+ continue;+ }+ ch.to_string()+ }+ // Note: letters and the ASCII a cmmi font draws as itself stay+ // plain text.+ RawText::Code(code)+ if enc == Some(Enc::Oml)+ && char::from_u32(code)+ .is_some_and(|ch| ch.is_ascii_alphabetic() || ".,</>".contains(ch)) =>+ {+ char::from_u32(code).expect("ascii").to_string()+ }+ RawText::Code(code) => match enc.and_then(|e| encodings::decode(e, code)) {+ Some(dec) => format!("{PRE}{dec}"),+ None => match char::from_u32(code).filter(|ch| ch.is_ascii_graphic()) {+ Some(ch) => ch.to_string(),+ None => continue,+ },+ },+ };+ if t.is_empty() {+ continue;+ }+ let mut role = role;+ if role.is_none() && TEXT_FAMS.contains(&fam.as_str()) && greek(&t).is_some() {+ role = Some(Role::Mi); // upright capital Greek is set in the roman font+ }+ let base = page_h - c.origin_y;+ // Note: the ink box, not an em box. TeX sets \hat{x}'s accent on+ // x's own baseline, so only ink tells the accent sits above; a+ // radical's ink top is where its rule starts. (+4 points over the+ // prototype's font-descriptor boxes on the arXiv math tests.)+ let (top, bottom) = c.ink.unwrap_or_else(|| {+ let bottom_up = base + c.descent;+ (page_h - (bottom_up + c.size), page_h - bottom_up)+ });+ out.push(G {+ t,+ role,+ fam,+ size: c.size,+ base,+ x0: c.x0,+ x1: c.x1,+ top,+ bottom,+ loose: c.loose,+ pre: String::new(),+ post: String::new(),+ src: vec![c.index],+ });+ }+ out+}++struct Base {+ y: f32,+ size: f32,+ gs: Vec<usize>,+ ext: Option<(f32, f32)>,+}++/// Group glyphs into lines: full-size glyphs set the line baselines, smaller+/// ones (scripts) attach to the nearest line whose band they fall in.+fn lines(all: &mut [G], live: &[usize]) -> Vec<Vec<usize>> {+ if live.is_empty() {+ return Vec::new();+ }+ let body = median(live.iter().map(|&i| all[i].size).collect());+ let mut big: Vec<usize> = live+ .iter()+ .copied()+ .filter(|&i| all[i].size >= 0.85 * body)+ .collect();+ big.sort_by(|&a, &b| all[b].base.total_cmp(&all[a].base));+ let mut bases: Vec<Base> = Vec::new();+ for &g in &big {+ let gb = all[g].base;+ let gsz = all[g].size;+ match bases.iter_mut().find(|b| (b.y - gb).abs() < 0.25 * gsz) {+ Some(b) => b.gs.push(g),+ None => bases.push(Base {+ y: gb,+ size: gsz,+ gs: vec![g],+ ext: None,+ }),+ }+ }+ // Scripts attach to the nearest baseline among the rows whose x-extent+ // holds them (one baseline can hold a row of each column on a+ // two-column page).+ for b in &mut bases {+ let x0 = b.gs.iter().map(|&i| all[i].x0).fold(f32::MAX, f32::min);+ let x1 = b.gs.iter().map(|&i| all[i].x1).fold(f32::MIN, f32::max);+ b.ext = Some((x0 - 1.0 * b.size, x1 + 1.5 * b.size));+ }+ for &g in live {+ if all[g].role != Some(Role::Ex) {+ continue;+ }+ // Note: a cmex glyph hangs from its origin; its line is the nearest+ // baseline below that.+ let xc = all[g].cx();+ let (gb, gs) = (all[g].base, all[g].size);+ let mut row: Option<usize> = None;+ for (k, b) in bases.iter().enumerate() {+ let Some((e0, e1)) = b.ext else { continue };+ let ok = e0 <= xc+ && xc <= e1+ && gb - 3.0 * gs <= b.y+ && b.y <= gb + 0.3 * gs+ && b.gs.first().is_some_and(|&f| all[f].role != Some(Role::Ex));+ if ok && row.is_none_or(|r| b.y > bases[r].y) {+ row = Some(k);+ }+ }+ if let Some(r) = row {+ for b in &mut bases {+ if let Some(p) = b.gs.iter().position(|&x| x == g) {+ b.gs.remove(p);+ }+ }+ all[g].base = bases[r].y;+ all[g].size = bases[r].size;+ bases[r].gs.push(g);+ }+ }+ bases.retain(|b| !b.gs.is_empty());+ for &g in live {+ if all[g].size >= 0.85 * body || all[g].role == Some(Role::Ex) {+ continue;+ }+ let xc = all[g].cx();+ let gb = all[g].base;+ let mut best: Option<usize> = None;+ for (k, b) in bases.iter().enumerate() {+ let Some((e0, e1)) = b.ext else { continue };+ let d = gb - b.y;+ if !(-0.6 * b.size < d && d < 0.8 * b.size && e0 <= xc && xc <= e1) {+ continue;+ }+ if best.is_none_or(|r| (gb - b.y).abs() < (gb - bases[r].y).abs()) {+ best = Some(k);+ }+ }+ match best {+ Some(k) => bases[k].gs.push(g),+ None => bases.push(Base {+ y: gb,+ size: all[g].size,+ gs: vec![g],+ ext: None,+ }),+ }+ }+ // Note: then split each row at wide gaps nothing fills: the gutter+ // between two columns.+ let mut split: Vec<(f32, Vec<usize>)> = Vec::new();+ for b in &bases {+ let mut row = b.gs.clone();+ row.sort_by(|&a, &c| all[a].x0.total_cmp(&all[c].x0));+ let mut cur = vec![row[0]];+ let mut right = all[row[0]].x1;+ for &g in &row[1..] {+ if all[g].x0 - right > 1.5 * b.size {+ split.push((b.y, std::mem::take(&mut cur)));+ }+ cur.push(g);+ right = right.max(all[g].x1);+ }+ split.push((b.y, cur));+ }+ split.sort_by(|a, b| {+ b.0.total_cmp(&a.0)+ .then(all[a.1[0]].x0.total_cmp(&all[b.1[0]].x0))+ });+ split+ .into_iter()+ .map(|(_, mut gs)| {+ gs.sort_by(|&a, &b| all[a].x0.total_cmp(&all[b].x0));+ gs+ })+ .collect()+}++fn accent_name(t: &str) -> Option<&'static str> {+ Some(match t {+ "ˆ" | "^" => "hat",+ "˜" | "~" => "tilde",+ "¯" => "bar",+ "˙" => "dot",+ "¨" => "ddot",+ "´" => "acute",+ "`" => "grave",+ "ˇ" => "check",+ "˘" => "breve",+ "\u{20d7}" => "vec",+ _ => return None,+ })+}++fn accent_of(g: &G) -> Option<String> {+ if let Some(rest) = g.t.strip_prefix("\0ACC:") {+ return Some(rest.to_string());+ }+ if (g.role.is_none() || g.role == Some(Role::Mi))+ && let Some(a) = accent_name(&g.t)+ && (g.role.is_none() || "˜¯˙¨ˆ\u{20d7}".contains(g.t.as_str()))+ {+ return Some(a.to_string());+ }+ None+}++/// Drop accent glyphs from a span, wrapping the glyphs under each in+/// `\hat{..}` etc.+fn attach_accents(all: &mut [G], sp: &[usize]) -> Vec<usize> {+ let accs: Vec<usize> = sp+ .iter()+ .copied()+ .filter(|&i| accent_of(&all[i]).is_some())+ .collect();+ if accs.is_empty() {+ return sp.to_vec();+ }+ let rest: Vec<usize> = sp+ .iter()+ .copied()+ .filter(|&i| accent_of(&all[i]).is_none())+ .collect();+ for &a in &accs {+ let (ax0, ax1, atop, asz) = (all[a].x0, all[a].x1, all[a].top, all[a].size);+ let cx = (ax0 + ax1) / 2.0;+ let name = accent_of(&all[a]).unwrap_or_default();+ let wide = name.starts_with("wide");+ let mut under: Vec<usize> = if wide {+ let rest_max = max_size(all, &rest);+ rest.iter()+ .copied()+ .filter(|&g| {+ let gg = &all[g];+ gg.top > atop+ && ax0 - 0.1 * asz <= gg.cx()+ && gg.cx() <= ax1 + 0.1 * asz+ && gg.size >= 0.9 * rest_max+ })+ .collect()+ } else {+ rest.iter()+ .copied()+ .filter(|&g| {+ let gg = &all[g];+ gg.top > atop + 0.1 * asz+ && gg.x0 - 0.15 * asz <= cx+ && cx <= gg.x1 + 0.15 * asz+ })+ .collect()+ };+ if under.is_empty() {+ continue;+ }+ under.sort_by(|&a, &b| all[a].x0.total_cmp(&all[b].x0));+ if !wide {+ let pick = under+ .iter()+ .copied()+ .reduce(|best, g| {+ if (all[g].cx() - cx).abs() < (all[best].cx() - cx).abs() {+ g+ } else {+ best+ }+ })+ .expect("non-empty");+ under = vec![pick];+ }+ let first = under[0];+ let last = *under.last().expect("non-empty");+ all[first].pre.push_str(&format!("\\{name}{{"));+ all[last].post = format!("}}{}", all[last].post);+ }+ rest+}++fn tex_char(g: &G) -> String {+ format!("{}{}{}", g.pre, tex_char_inner(g), g.post)+}++fn cmd_space(s: &str) -> String {+ if s.starts_with('\\') && s.chars().last().is_some_and(char::is_alphabetic) {+ format!("{s} ")+ } else {+ s.to_string()+ }+}++fn tex_char_inner(g: &G) -> String {+ let t = g.t.as_str();+ if let Some(s) = t.strip_prefix(PRE) {+ return cmd_space(s);+ }+ if TEXT_FAMS.contains(&g.fam.as_str())+ && let Some(n) = greek(t)+ {+ return format!("\\{n} ");+ }+ if g.role == Some(Role::Bb) && is_alpha(t) {+ return format!(r"\mathbb{{{}}}", t.to_uppercase());+ }+ if g.role == Some(Role::Frak) && is_alpha(t) {+ return format!(r"\mathfrak{{{t}}}");+ }+ if g.role == Some(Role::Scr) && is_alpha(t) {+ return format!(r"\mathscr{{{t}}}");+ }+ if ((g.role == Some(Role::Sy) && g.enc() == Some(Enc::Oms)) || g.role == Some(Role::Cal))+ && is_ascii_upper(t)+ {+ return format!(r"\mathcal{{{t}}}");+ }+ if let Some(n) = greek(t) {+ return format!("\\{n} ");+ }+ if let Some(s) = symbol(t) {+ return cmd_space(s);+ }+ t.to_string()+}++fn in_text_math_ok(t: &str) -> bool {+ let mut cs = t.chars();+ matches!((cs.next(), cs.next()), (Some(c), None) if TEXT_MATH_OK.contains(c))+}++/// Glyphs a footnote marker is made of: digits and the reference symbols;+/// commas only between them.+fn is_marker(t: &str, first: bool) -> bool {+ let mut cs = t.chars();+ matches!((cs.next(), cs.next()), (Some(c), None)+ if c.is_ascii_digit() || "∗*†‡§¶⋆".contains(c) || (!first && c == ','))+}++/// Drops a text-font bracket at either end of a span that has no partner+/// inside it (the `)` of "(q and q̇)" belongs to the sentence).+fn trim_unmatched_brackets(all: &[G], sp: &mut Vec<usize>) {+ let mut unmatched = vec![false; sp.len()];+ // Note: any opener closes with any closer: half-open intervals ([0, ∞)).+ let mut stack: Vec<usize> = Vec::new();+ for (k, &x) in sp.iter().enumerate() {+ if all[x].role.is_some() {+ continue;+ }+ match all[x].t.as_str() {+ "(" | "[" => stack.push(k),+ ")" | "]" => {+ if stack.pop().is_none() {+ unmatched[k] = true;+ }+ }+ _ => {}+ }+ }+ for k in stack {+ unmatched[k] = true;+ }+ let lo = unmatched.iter().take_while(|&&u| u).count();+ let hi = sp.len() - unmatched[lo..].iter().rev().take_while(|&&u| u).count();+ sp.truncate(hi);+ sp.drain(..lo);+}++/// Runs of math glyphs in a line, extended over text-font digits /+/// punctuation / operator names that sit between or next to math glyphs.+fn spans_in_line(all: &[G], ln: &[usize]) -> Vec<Vec<usize>> {+ let n = ln.len();+ if n == 0 {+ return Vec::new();+ }+ let g = |k: usize| &all[ln[k]];+ let body = max_size(all, ln);+ let mut math: Vec<bool> = (0..n)+ .map(|k| g(k).role.is_some() || g(k).size < 0.85 * body)+ .collect();+ // Note: a small text-font glyph is a script only when the line also has+ // math-font glyphs.+ if !(0..n).any(|k| g(k).role.is_some()) {+ return Vec::new();+ }+ // Note: a raised small run set tight after a text-font word or sentence+ // punctuation is a footnote marker (Kim∗, Lee∗†, b.³), not a superscript.+ // Operator names keep their scripts (sin²).+ let mut k = 1;+ while k < n {+ let prev = g(k - 1);+ let after_text = prev.role.is_none()+ && prev.size >= 0.85 * body+ && (is_alpha(&prev.t) || ".,;:".contains(prev.t.as_str()))+ && g(k).x0 - prev.x1 < 0.3 * prev.size;+ let raised = |m: usize| g(m).size < 0.85 * body && g(m).base > prev.base + 0.2 * prev.size;+ if !(after_text && raised(k) && is_marker(&g(k).t, true)) {+ k += 1;+ continue;+ }+ let mut w = k - 1;+ while w > 0 && g(w - 1).role.is_none() && is_alpha(&g(w - 1).t) {+ w -= 1;+ }+ let word: String = (w..k).map(|m| g(m).t.as_str()).collect();+ let mut j = k;+ while j < n && raised(j) && is_marker(&g(j).t, false) {+ j += 1;+ }+ // Note: a word whose script is set tight against a bracket or math is+ // a function name (Aut⁰(X)).+ let tight_after =+ j < n && g(j).x0 - g(j - 1).x1 < 0.15 * g(j).size && (math[j] || g(j).t == "(");+ if !is_operator(&word) && !tight_after {+ for m in math.iter_mut().take(j).skip(k) {+ *m = false;+ }+ }+ k = j;+ }+ // Operator names in text font: a run of letters matching OPERATORS next+ // to math.+ let mut i = 0;+ while i < n {+ if g(i).role.is_none() && is_alpha(&g(i).t) {+ let mut j = i;+ while j < n+ && g(j).role.is_none()+ && is_alpha(&g(j).t)+ && (j == i || g(j).x0 - g(j - 1).x1 < 0.15 * g(j).size)+ {+ j += 1;+ }+ let word: String = (i..j).map(|k| g(k).t.as_str()).collect();+ let near = (i > 0 && math[i - 1]) || (j < n && math[j]);+ let em = g(i).size;+ let tight_l = i > 0 && math[i - 1] && g(i).x0 - g(i - 1).x1 < 0.2 * em;+ let tight_r = j < n && g(j).x0 - g(j - 1).x1 < 0.12 * em && (math[j] || g(j).t == "(");+ // Note: a bold letter against math is a vector (\mathbf{x}); a+ // word set tight against a bracket or math is a function name+ // (Hom(A, B)).+ let bold_letter =+ j - i == 1 && (g(i).fam == "CMBX" || g(i).fam == "CMB") && (tight_l || tight_r);+ if (is_operator(&word) && near) || bold_letter || (j - i >= 2 && tight_r && near) {+ for m in math.iter_mut().take(j).skip(i) {+ *m = true;+ }+ }+ i = j;+ } else {+ i += 1;+ }+ }+ for k in 0..n {+ if !math[k] && accent_of(g(k)).is_some() {+ let cx = g(k).cx();+ math[k] = (k.saturating_sub(3)..(k + 4).min(n))+ .any(|m| math[m] && g(m).x0 - 1.0 <= cx && cx <= g(m).x1 + 1.0);+ }+ }+ // Grow over text-font digits / punctuation adjacent to math, both+ // directions, until stable.+ let mut changed = true;+ while changed {+ changed = false;+ for k in 0..n {+ if math[k] || !in_text_math_ok(&g(k).t) {+ continue;+ }+ let sz = g(k).size;+ let left = k > 0 && math[k - 1] && g(k).x0 - g(k - 1).x1 < 0.6 * sz;+ let right = k + 1 < n && math[k + 1] && g(k + 1).x0 - g(k).x1 < 0.6 * sz;+ if left || right {+ // Note: a sentence's full stop or comma after math stays text.+ if ".,;:".contains(g(k).t.as_str()) && !right {+ continue;+ }+ math[k] = true;+ changed = true;+ }+ }+ }+ let mut out: Vec<Vec<usize>> = Vec::new();+ let mut cur: Vec<usize> = Vec::new();+ for k in 0..n {+ if math[k] {+ // Note: TeX's widest math space is ~0.3em; a wider gap before a+ // text-font number is a table column (3.6→ | 18.7→), not math.+ let gap = cur.last().map(|&last| g(k).x0 - all[last].x1);+ let numeral = g(k).role.is_none() && g(k).t.chars().all(|c| c.is_ascii_digit());+ if gap.is_some_and(|d| d > 1.5 * body || (numeral && d > 0.6 * body)) {+ out.push(std::mem::take(&mut cur));+ }+ cur.push(ln[k]);+ } else if !cur.is_empty() {+ out.push(std::mem::take(&mut cur));+ }+ }+ if !cur.is_empty() {+ out.push(cur);+ }+ for sp in out.iter_mut() {+ trim_unmatched_brackets(all, sp);+ }+ out.retain(|s| s.iter().any(|&x| all[x].role.is_some()) || s.len() > 1);+ out+}++/// Note: a small glyph back on the baseline is a script's script (the l of+/// `\|g\|_{C^l}`).+fn on_base(g: &G, base: f32, size: f32) -> bool {+ g.size >= 0.92 * size || ((g.base - base).abs() <= 0.12 * size && g.size >= 0.8 * size)+}++const OPERATORNAME: [&str; 6] = ["diag", "rank", "span", "sgn", "Re", "Im"];++/// LaTeX for glyphs on baseline `base` at `size`, with sub/superscripts+/// recursively.+fn build(all: &[G], gs: &[usize], base: f32, size: f32) -> String {+ let mut out = String::new();+ let n = gs.len();+ let mut i = 0;+ while i < n {+ let g = &all[gs[i]];+ if on_base(g, base, size) {+ if g.role.is_none() && is_alpha(&g.t) {+ let mut j = i;+ while j < n+ && all[gs[j]].role.is_none()+ && is_alpha(&all[gs[j]].t)+ && on_base(&all[gs[j]], base, size)+ {+ j += 1;+ }+ let word: String = gs[i..j].iter().map(|&x| all[x].t.as_str()).collect();+ if is_operator(&word) {+ if OPERATORNAME.contains(&word.as_str()) {+ out.push_str(&format!(r"\operatorname{{{word}}}"));+ } else {+ out.push_str(&format!("\\{word} "));+ }+ i = j;+ continue;+ }+ }+ out.push_str(&tex_char(g));+ i += 1;+ continue;+ }+ // A script run: consecutive glyphs off the baseline.+ let mut j = i;+ while j < n && !on_base(&all[gs[j]], base, size) {+ j += 1;+ }+ let run = &gs[i..j];+ let top = max_size(all, run);+ // Note: first-level script glyphs pick sub or sup by their baseline;+ // smaller (second-level) glyphs go with the first-level glyph before+ // them (E_{g^{-1}}: the -1 rides on the g).+ let mut sub: Vec<usize> = Vec::new();+ let mut sup: Vec<usize> = Vec::new();+ let mut last_sup: Option<bool> = None;+ // Baselines of the latest first-level sub and sup glyphs.+ let (mut sub_base, mut sup_base): (Option<f32>, Option<f32>) = (None, None);+ for &x in run {+ if all[x].size >= 0.9 * top || last_sup.is_none() {+ let up = all[x].base > base;+ last_sup = Some(up);+ if up {+ sup_base = Some(all[x].base);+ } else {+ sub_base = Some(all[x].base);+ }+ } else if let (Some(lo), Some(hi)) = (sub_base, sup_base) {+ // Note: with both scripts open, a smaller glyph rides the one+ // whose baseline is nearer (\Phi_{B_s}^{ren}: the s is B's).+ last_sup = Some((all[x].base - hi).abs() < (all[x].base - lo).abs());+ }+ if last_sup == Some(true) {+ sup.push(x);+ } else {+ sub.push(x);+ }+ }+ for (grp, mark, is_sup) in [(&sub, '_', false), (&sup, '^', true)] {+ if grp.is_empty() {+ continue;+ }+ let mut lvl1: Vec<usize> = grp+ .iter()+ .copied()+ .filter(|&x| all[x].size >= 0.9 * top)+ .collect();+ if lvl1.is_empty() {+ lvl1 = grp.clone();+ }+ let b = median(lvl1.iter().map(|&x| all[x].base).collect());+ let mut body = build(all, grp, b, max_size(all, &lvl1));+ if is_sup {+ // Note: primes are written f', not f^{'} (a double+ // superscript in KaTeX).+ let k = body.len() - body.trim_start_matches('\'').len();+ if k > 0 {+ out.push_str(&"'".repeat(k));+ body = body[k..].trim().to_string();+ }+ }+ if !body.is_empty() {+ out.push(mark);+ out.push('{');+ out.push_str(&body);+ out.push('}');+ }+ }+ i = j;+ }+ tidy(out.trim())+}++fn tidy(s: &str) -> String {+ let mut s = s+ .replace("...", r"\ldots ")+ .replace(r"\cdot \cdot \cdot ", r"\cdots ");+ s = s+ .replace("NOT=", r"\neq ")+ .replace("NOT", r"\not ")+ .replace(r"MAPSTO\to ", r"\mapsto ")+ .replace("MAPSTO", "");+ for tok in ["HAT", "TILDE", "SQRT"] {+ s = s.replace(tok, "");+ }+ s+}++/// Whether a font can make its page a TeX page (see [`page_math`]): a math+/// font in a TeX encoding, or an AMS / Euler / rsfs alphabet. A cheap gate+/// that lets callers skip collecting glyphs on every other page.+pub(crate) fn is_tex_math_font(font_name: &str) -> bool {+ let (role, enc) = font_info(&family(font_name));+ enc.is_some()+ || matches!(+ role,+ Some(Role::Bb) | Some(Role::Frak) | Some(Role::Cal) | Some(Role::Scr)+ )+}++/// The item box for a span on baseline `base`: the font box of the real+/// glyphs on that baseline (the span's own, else its line's), so the item sits+/// in its line like text does.+///+/// Note: neither scripts' ink nor a fraction's stacked parts may set it: an+/// item that rises above its line drops out of the line's band in layout,+/// and the text after it then reads as a new column start (a two-column page+/// turned "tabular").+fn line_box(+ all: &[G],+ ln: &[usize],+ kept: &[usize],+ base: f32,+ size: f32,+ page_h: f32,+) -> (f32, f32) {+ let real = |x: &&usize| {+ let g = &all[**x];+ g.fam != structures::STAND_IN_FAM+ && (g.base - base).abs() <= 0.1 * size+ && g.size >= 0.8 * size+ };+ let boxes: Vec<(f32, f32)> = match kept+ .iter()+ .filter(real)+ .map(|&x| all[x].loose)+ .collect::<Vec<_>>()+ {+ b if !b.is_empty() => b,+ _ => ln.iter().filter(real).map(|&x| all[x].loose).collect(),+ };+ if boxes.is_empty() {+ // Typical font box: 0.78 em above the baseline, 0.22 em below.+ let y = page_h - base;+ return (y - 0.78 * size, y + 0.22 * size);+ }+ (+ boxes.iter().map(|b| b.0).fold(f32::MAX, f32::min),+ boxes.iter().map(|b| b.1).fold(f32::MIN, f32::max),+ )+}++/// Math spans of one page, or None when the page isn't set in TeX.+pub(crate) fn page_math(chars: &[RawChar], rules: &[Rule], page_h: f32) -> Option<Vec<MathSpan>> {+ let mut all = glyphs(chars, page_h);+ // Note: only pages set by TeX (a math font in a TeX encoding, or an AMS /+ // Euler / rsfs font) get math: Word's Symbol font and table rules+ // elsewhere would otherwise read as math.+ let tex_page = all.iter().any(|g| {+ g.enc().is_some()+ || matches!(+ g.role,+ Some(Role::Bb) | Some(Role::Frak) | Some(Role::Cal) | Some(Role::Scr)+ )+ });+ if !tex_page {+ return None;+ }+ let mut live: Vec<usize> = (0..all.len()).collect();+ live = structures::fold(&mut all, live, rules, page_h);+ let mut res = Vec::new();+ for ln in lines(&mut all, &live) {+ for sp in spans_in_line(&all, &ln) {+ let kept = attach_accents(&mut all, &sp);+ if kept.is_empty() {+ continue;+ }+ let big = max_size(&all, &kept);+ let base = median(+ kept.iter()+ .filter(|&&x| all[x].size >= 0.92 * big)+ .map(|&x| all[x].base)+ .collect(),+ );+ let tex = build(&all, &kept, base, big);+ if tex.is_empty() {+ continue;+ }+ let (top, bottom) = line_box(&all, &ln, &kept, base, big, page_h);+ let mut chars: Vec<i32> = sp+ .iter()+ .flat_map(|&x| all[x].src.iter().copied())+ .collect();+ chars.sort_unstable();+ chars.dedup();+ res.push(MathSpan {+ tex,+ x0: sp.iter().map(|&x| all[x].x0).fold(f32::MAX, f32::min),+ x1: sp.iter().map(|&x| all[x].x1).fold(f32::MIN, f32::max),+ top,+ bottom,+ size: big,+ chars,+ });+ }+ }+ Some(res)+}++/// The spans to splice into the page text, and the char indices they+/// replace.+pub(crate) fn emitted(spans: &[MathSpan]) -> (Vec<&MathSpan>, HashSet<i32>) {+ let keep: Vec<&MathSpan> = spans.iter().filter(|s| s.has_structure()).collect();+ let consumed = keep.iter().flat_map(|s| s.chars.iter().copied()).collect();+ (keep, consumed)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn family_strips_prefix_size_and_regular() {+ assert_eq!(family("ABCDEF+CMMI10"), "CMMI");+ assert_eq!(family("LMMathItalic10-Regular"), "LMMATHITALIC");+ assert_eq!(family("MSBM10"), "MSBM");+ }++ #[test]+ fn font_rules_match_prototype_roles() {+ assert_eq!(font_info("CMMI"), (Some(Role::Mi), Some(Enc::Oml)));+ assert_eq!(font_info("CMSY"), (Some(Role::Sy), Some(Enc::Oms)));+ assert_eq!(font_info("CMEX"), (Some(Role::Ex), Some(Enc::Omx)));+ assert_eq!(font_info("MSBM"), (Some(Role::Bb), None));+ assert_eq!(font_info("MSAM"), (Some(Role::Sy), Some(Enc::Msam)));+ assert_eq!(font_info("CMR"), (None, None));+ assert_eq!(font_info("TIMES-ROMAN"), (None, None));+ }++ fn glyph(t: &str, role: Option<Role>, fam: &str, size: f32, base: f32, x0: f32, x1: f32) -> G {+ G {+ t: t.to_string(),+ role,+ fam: fam.to_string(),+ size,+ base,+ x0,+ x1,+ top: 800.0 - (base + size * 0.75),+ bottom: 800.0 - (base - size * 0.25),+ loose: (800.0 - (base + size * 0.75), 800.0 - (base - size * 0.25)),+ pre: String::new(),+ post: String::new(),+ src: vec![],+ }+ }++ #[test]+ fn build_writes_sub_and_superscripts() {+ let all = vec![+ glyph("x", Some(Role::Mi), "CMMI", 10.0, 100.0, 0.0, 5.0),+ glyph("i", Some(Role::Mi), "CMMI", 7.0, 98.0, 5.0, 8.0),+ glyph("2", None, "CMR", 7.0, 104.0, 8.0, 11.0),+ ];+ // The 2 is a fresh first-level glyph above the baseline.+ assert_eq!(build(&all, &[0, 1, 2], 100.0, 10.0), "x_{i}^{2}");+ }++ #[test]+ fn primes_stay_outside_superscript_braces() {+ let all = vec![+ glyph("f", Some(Role::Mi), "CMMI", 10.0, 100.0, 0.0, 5.0),+ glyph("\0'", Some(Role::Sy), "CMSY", 7.0, 104.0, 5.0, 7.0),+ ];+ assert_eq!(build(&all, &[0, 1], 100.0, 10.0), "f'");+ }++ #[test]+ fn footnote_markers_after_words_stay_text() {+ // "Kim∗": a raised CMSY star tight after a roman word.+ let all = vec![+ glyph("K", None, "CMR", 10.0, 100.0, 0.0, 7.0),+ glyph("i", None, "CMR", 10.0, 100.0, 7.0, 10.0),+ glyph("m", None, "CMR", 10.0, 100.0, 10.0, 18.0),+ glyph("∗", Some(Role::Sy), "CMSY", 7.0, 104.0, 18.0, 22.0),+ ];+ assert!(spans_in_line(&all, &[0, 1, 2, 3]).is_empty());+ // "Aut⁰(X)": the same shape tight against a bracket is a function.+ let all = vec![+ glyph("A", None, "CMR", 10.0, 100.0, 0.0, 7.0),+ glyph("u", None, "CMR", 10.0, 100.0, 7.0, 12.0),+ glyph("t", None, "CMR", 10.0, 100.0, 12.0, 16.0),+ glyph("0", None, "CMR", 7.0, 104.0, 16.0, 20.0),+ glyph("(", None, "CMR", 10.0, 100.0, 20.0, 23.0),+ glyph("X", Some(Role::Mi), "CMMI", 10.0, 100.0, 23.0, 31.0),+ glyph(")", None, "CMR", 10.0, 100.0, 31.0, 34.0),+ ];+ assert_eq!(+ spans_in_line(&all, &[0, 1, 2, 3, 4, 5, 6]),+ vec![vec![0, 1, 2, 3, 4, 5, 6]]+ );+ }++ #[test]+ fn unmatched_end_brackets_are_trimmed() {+ let g = |t: &str, x: f32| glyph(t, None, "CMR", 10.0, 100.0, x, x + 3.0);+ let all = vec![+ g("q", 0.0),+ g(")", 3.0),+ g("[", 6.0),+ g("0", 9.0),+ g(")", 12.0),+ ];+ let mut sp = vec![0, 1];+ trim_unmatched_brackets(&all, &mut sp);+ assert_eq!(sp, vec![0]);+ // A half-open interval [0) is matched.+ let mut sp = vec![2, 3, 4];+ trim_unmatched_brackets(&all, &mut sp);+ assert_eq!(sp, vec![2, 3, 4]);+ }++ #[test]+ fn structure_rule_keeps_plain_symbols_as_text() {+ let span = |tex: &str| MathSpan {+ tex: tex.to_string(),+ x0: 0.0,+ x1: 0.0,+ top: 0.0,+ bottom: 0.0,+ size: 0.0,+ chars: vec![],+ };+ assert!(!span(r"\pm ").has_structure());+ assert!(!span(r"\alpha ").has_structure());+ assert!(span("x_{i}").has_structure());+ assert!(span(r"\mathcal{O}(2^{M}\cdot K)").has_structure());+ }+}diff --git a/crates/liteparse/src/tex_math/structures.rs b/crates/liteparse/src/tex_math/structures.rsnew file mode 100644index 0000000..9732eb3--- /dev/null+++ b/crates/liteparse/src/tex_math/structures.rs@@ -0,0 +1,319 @@+//! Two-dimensional math from rules: fractions, overlines and square roots.+//!+//! A rule is a thin horizontal rect, line, or stretched image (some PDFs draw+//! TeX's `\vrule` as a 1x1 image). Rules are taken narrowest first, so an+//! inner fraction is folded before the one holding it: its glyphs become one+//! stand-in glyph whose text is the finished LaTeX.++use std::collections::HashSet;++use super::{G, PRE, Role, attach_accents, build, is_alpha, is_operator, max_size, median};++/// A thin horizontal rule. `y` is y-up page space (`page height - y`).+#[derive(Debug, Clone, Copy)]+pub(crate) struct Rule {+ pub(crate) x0: f32,+ pub(crate) x1: f32,+ pub(crate) y: f32,+ pub(crate) w: f32,+}++impl Rule {+ /// A rule from a viewport-space box (y down), when the box is thin and+ /// wide enough to be one.+ pub(crate) fn from_box(x0: f32, x1: f32, top: f32, bottom: f32, page_h: f32) -> Option<Rule> {+ (bottom - top <= 1.2 && x1 - x0 >= 1.5).then(|| Rule {+ x0,+ x1,+ y: page_h - (top + bottom) / 2.0,+ w: x1 - x0,+ })+ }+}++fn tex_of(all: &mut [G], gs: &[usize]) -> String {+ let mut sorted = gs.to_vec();+ sorted.sort_by(|&a, &b| all[a].x0.total_cmp(&all[b].x0));+ let kept = attach_accents(all, &sorted);+ if kept.is_empty() {+ return String::new();+ }+ let big = max_size(all, &kept);+ let base = median(+ kept.iter()+ .filter(|&&g| all[g].size >= 0.92 * big)+ .map(|&g| all[g].base)+ .collect(),+ );+ build(all, &kept, base, big)+}++#[allow(clippy::too_many_arguments)]+/// Family of a folded structure's stand-in glyph.+pub(crate) const STAND_IN_FAM: &str = "SYN";++fn stand_in(all: &[G], tex: String, parts: &[usize], x0: f32, x1: f32, base: f32, size: f32) -> G {+ G {+ t: format!("{PRE}{tex}"),+ role: Some(Role::Mi),+ fam: STAND_IN_FAM.to_string(),+ size,+ base,+ x0,+ x1,+ top: parts.iter().map(|&g| all[g].top).fold(f32::MAX, f32::min),+ bottom: parts+ .iter()+ .map(|&g| all[g].bottom)+ .fold(f32::MIN, f32::max),+ loose: (+ parts+ .iter()+ .map(|&g| all[g].loose.0)+ .fold(f32::MAX, f32::min),+ parts+ .iter()+ .map(|&g| all[g].loose.1)+ .fold(f32::MIN, f32::max),+ ),+ pre: String::new(),+ post: String::new(),+ src: parts+ .iter()+ .flat_map(|&g| all[g].src.iter().copied())+ .collect(),+ }+}++/// The glyphs stacked right above (or below) a rule, within its width: the+/// baseline nearest the rule and the scripts riding on it. Glyphs much+/// larger than the nearest ones are a neighbouring text line, not the+/// fraction (a text-style fraction is set at script size).+fn stack(all: &[G], live: &[usize], r: &Rule, h: f32, above: bool) -> Vec<usize> {+ let near = live+ .iter()+ .copied()+ .filter(|&g| r.x0 - 0.8 <= all[g].cx() && all[g].cx() <= r.x1 + 0.8);+ let (cand, s, nb) = if above {+ let cand: Vec<usize> = near+ .filter(|&g| (h - all[g].bottom) >= r.y - 0.6 && all[g].base - r.y < 1.6 * all[g].size)+ .collect();+ let Some(g0) = cand+ .iter()+ .copied()+ .reduce(|a, b| if all[b].base < all[a].base { b } else { a })+ else {+ return Vec::new();+ };+ let s = cand+ .iter()+ .filter(|&&g| all[g].base <= all[g0].base + 0.4 * all[g].size)+ .map(|&g| all[g].size)+ .fold(f32::MIN, f32::max);+ let nb = cand+ .iter()+ .filter(|&&g| all[g].size >= 0.85 * s)+ .map(|&g| all[g].base)+ .fold(f32::MAX, f32::min);+ (cand, s, nb)+ } else {+ let cand: Vec<usize> = near+ .filter(|&g| {+ (h - all[g].top) <= r.y + 0.6 && r.y - (h - all[g].top) < 0.9 * all[g].size+ })+ .collect();+ let Some(g0) = cand.iter().copied().reduce(|a, b| {+ if (h - all[b].top) > (h - all[a].top) {+ b+ } else {+ a+ }+ }) else {+ return Vec::new();+ };+ let s = cand+ .iter()+ .filter(|&&g| (h - all[g].top) >= (h - all[g0].top) - 0.4 * all[g].size)+ .map(|&g| all[g].size)+ .fold(f32::MIN, f32::max);+ let nb = cand+ .iter()+ .filter(|&&g| all[g].size >= 0.85 * s)+ .map(|&g| all[g].base)+ .fold(f32::MIN, f32::max);+ (cand, s, nb)+ };+ cand.into_iter()+ .filter(|&g| {+ all[g].size <= 1.15 * s && nb - 0.45 * s <= all[g].base && all[g].base <= nb + 0.6 * s+ })+ .collect()+}++/// Whether glyphs hold a word of running text (3+ text-font letters that+/// aren't an operator name): table cells over and under a rule, not a+/// fraction.+fn wordy(all: &[G], gs: &[usize]) -> bool {+ let mut sorted = gs.to_vec();+ sorted.sort_by(|&a, &b| all[a].x0.total_cmp(&all[b].x0));+ let mut run = String::new();+ let mut run_len = 0usize;+ for g in sorted.iter().map(Some).chain(std::iter::once(None)) {+ if let Some(&g) = g+ && all[g].role.is_none()+ && is_alpha(&all[g].t)+ {+ run.push_str(&all[g].t);+ run_len += 1;+ continue;+ }+ if run_len >= 3 && !is_operator(&run) {+ return true;+ }+ run.clear();+ run_len = 0;+ }+ false+}++fn width(all: &[G], gs: &[usize]) -> (f32, f32) {+ (+ gs.iter().map(|&g| all[g].x0).fold(f32::MAX, f32::min),+ gs.iter().map(|&g| all[g].x1).fold(f32::MIN, f32::max),+ )+}++fn is_radical(t: &str) -> bool {+ matches!(t, "\0SQRT" | "\0\\surd " | "√" | "\0\\surd")+}++/// Replace `parts` in `live` with a new stand-in glyph.+fn replace(all: &mut Vec<G>, live: Vec<usize>, parts: &[usize], sy: G) -> Vec<usize> {+ let gone: HashSet<usize> = parts.iter().copied().collect();+ all.push(sy);+ let new = all.len() - 1;+ live.into_iter()+ .filter(|g| !gone.contains(g))+ .chain(std::iter::once(new))+ .collect()+}++/// Fold fractions, square roots and overlines into stand-in glyphs. Returns+/// the live glyph list; stand-ins are appended to `all`.+pub(super) fn fold(all: &mut Vec<G>, mut live: Vec<usize>, rules: &[Rule], h: f32) -> Vec<usize> {+ if live.is_empty() || rules.is_empty() {+ return live;+ }+ let body = median(live.iter().map(|&g| all[g].size).collect());+ let mut rules = rules.to_vec();+ rules.sort_by(|a, b| a.w.total_cmp(&b.w));+ for r in &rules {+ if r.w > 0.6 * 612.0 {+ continue;+ }+ // Square root: a radical glyph whose top-right meets the rule's left+ // end.+ let rad: Vec<usize> = live+ .iter()+ .copied()+ .filter(|&g| {+ is_radical(&all[g].t)+ && (all[g].x1 - r.x0).abs() < 1.5+ && ((h - all[g].top) - r.y).abs() < 0.35 * all[g].size + 1.5+ })+ .collect();+ if !rad.is_empty() {+ let under: Vec<usize> = live+ .iter()+ .copied()+ .filter(|g| !rad.contains(g))+ .filter(|&g| {+ r.x0 - 0.5 <= all[g].cx()+ && all[g].cx() <= r.x1 + 0.5+ && (h - all[g].top) <= r.y + 0.6+ && r.y - (h - all[g].top) < 1.6 * all[g].size+ })+ .collect();+ if !under.is_empty() {+ let s = max_size(all, &under);+ let nb = median(+ under+ .iter()+ .filter(|&&g| all[g].size >= 0.85 * s)+ .map(|&g| all[g].base)+ .collect(),+ );+ let under: Vec<usize> = under+ .into_iter()+ .filter(|&g| nb - 0.6 * s <= all[g].base && all[g].base <= nb + 0.8 * s)+ .collect();+ let tex = format!(r"\sqrt{{{}}}", tex_of(all, &under));+ let parts: Vec<usize> = under.iter().chain(rad.iter()).copied().collect();+ let sy = stand_in(all, tex, &parts, all[rad[0]].x0, r.x1, nb, s);+ live = replace(all, live, &parts, sy);+ continue;+ }+ }+ let num = stack(all, &live, r, h, true);+ let den = stack(all, &live, r, h, false);+ let tol = (0.3 * body).max(3.0);+ if !num.is_empty() && !den.is_empty() {+ let (nx0, nx1) = width(all, &num);+ let (dx0, dx1) = width(all, &den);+ let wide = (nx1 - nx0).max(dx1 - dx0);+ let rc = (r.x0 + r.x1) / 2.0;+ let centred = ((nx0 + nx1) / 2.0 - rc).abs() < 0.15 * r.w + 1.5+ && ((dx0 + dx1) / 2.0 - rc).abs() < 0.15 * r.w + 1.5;+ if r.w - tol <= wide+ && wide <= r.w + 1.0+ && centred+ && !wordy(all, &num)+ && !wordy(all, &den)+ {+ let tex = format!(r"\frac{{{}}}{{{}}}", tex_of(all, &num), tex_of(all, &den));+ let parts: Vec<usize> = num.iter().chain(den.iter()).copied().collect();+ let part = max_size(all, &parts);+ // Note: display fractions set their parts at full size,+ // text-style ones at script size (so the fraction's own size+ // is ~1/0.7 of its parts').+ let size = if part >= 0.92 * body {+ part+ } else {+ body.min(part / 0.7)+ };+ let sy = stand_in(all, tex, &parts, r.x0, r.x1, r.y - 0.25 * size, size);+ live = replace(all, live, &parts, sy);+ continue;+ }+ }+ // Overline: math glyphs right under the rule, as wide as it.+ if !den.is_empty() {+ let (dx0, dx1) = width(all, &den);+ let close = den+ .iter()+ .any(|&g| r.y - (h - all[g].top) < 0.45 * all[g].size + 1.0);+ let top_g = den+ .iter()+ .copied()+ .reduce(|a, b| if all[b].top < all[a].top { b } else { a })+ .expect("non-empty");+ if close+ && den.iter().any(|&g| all[g].role.is_some())+ && ((dx1 - dx0) - r.w).abs() < (0.3 * body).max(2.5)+ && r.y - (h - all[top_g].top) < 0.5 * body+ {+ let tex = format!(r"\overline{{{}}}", tex_of(all, &den));+ let s = max_size(all, &den);+ let nb = median(+ den.iter()+ .filter(|&&g| all[g].size >= 0.85 * s)+ .map(|&g| all[g].base)+ .collect(),+ );+ let sy = stand_in(all, tex, &den, dx0, dx1, nb, s);+ live = replace(all, live, &den, sy);+ }+ }+ }+ live+}diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rsindex c3ffb32..7103560 100644--- a/crates/liteparse/src/types.rs+++ b/crates/liteparse/src/types.rs@@ -122,6 +122,10 @@ pub struct TextItem {/// markdown emitter to wrap the text in `~~…~~`.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub strike: bool,+ /// Whether this item is LaTeX rebuilt from TeX math fonts (`$…$`).+ /// Populated in `extract.rs`.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub math: bool,/// Per-word sub-boxes within this item, split on the inter-word spaces seen/// during segment building. A segment groups several words together (it only/// breaks at line/column boundaries), so this exposes the finer word-level@@ -214,6 +218,11 @@ pub struct WordBox {#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Page {pub page_number: usize,+ /// Tilt (degrees) the OCR merge removed from this page's OCR items: on a skewed scan the+ /// items are rotated upright about the page centre so lines group into rows correctly,+ /// and their output boxes are rotated back after layout (`ParsedPage::ocr_deskew`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub ocr_deskew: Option<f32>,/// The document's `/PageLabels` entry for this page ("iv", "A-1"), when/// the PDF defines one. This is what a reader displays for the page and/// is not always its position in the document; `None` means the PDF has@@ -853,6 +862,7 @@ mod tests {#[test]fn page_serializes() {let p = Page {+ ocr_deskew: None,page_number: 1,page_label: None,page_width: 100.0,diff --git a/crates/liteparse/tests/stages_compose.rs b/crates/liteparse/tests/stages_compose.rsindex 6e46b95..334bcbc 100644--- a/crates/liteparse/tests/stages_compose.rs+++ b/crates/liteparse/tests/stages_compose.rs@@ -663,6 +663,7 @@ fn merge_ocr_rejects_outcome_for_unknown_page() {dpi: 150.0,has_native_text: false,image_rects: Vec::new(),+ replace_native: false,results: vec![OcrResult {text: "x".into(),bbox: [0.0, 0.0, 10.0, 10.0],