A fast, helpful, and open-source document parser
Markdown formatting without structural changes: style pieces on merged items; script runs keep their host's band
Logan Markewichd55372b16ae0
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rsindex 4fb1e44..dbbd18b 100644--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@ -360,9 +360,7 @@ fn extract_single_page(&text_page,&view_box,glyph_resolver,- output_options.emit_word_boxes,- output_options.extract_text_metadata,- output_options.split_scripts,+ output_options,&consumed,)?;items.extend(emitted.into_iter().map(math_item));@@ -1588,11 +1586,15 @@ fn extract_page_text_items(text_page: &TextPage,view_box: &RectF,glyph_resolver: Option<&dyn crate::GlyphResolver>,- emit_word_boxes: bool,- extract_text_metadata: bool,- split_scripts: bool,+ output_options: &ExtractionOutputOptions,math_chars: &std::collections::HashSet<i32>,) -> Result<Vec<TextItem>, LiteParseError> {+ let ExtractionOutputOptions {+ emit_word_boxes,+ extract_text_metadata,+ split_scripts,+ ..+ } = *output_options;let char_count = text_page.char_count();if char_count <= 0 {return Ok(Vec::new());@@ -1908,6 +1910,15 @@ fn extract_page_text_items(});if !y_overlap || line_changed || gap >= MAX_INLINE_GAP || dot_leader_break || size_break{+ // A break for the size step alone into smaller type: the run keeps its host's band.+ let host = (size_break+ && y_overlap+ && !line_changed+ && gap < MAX_INLINE_GAP+ && !dot_leader_break+ && (vp_loose.bottom - vp_loose.top).abs()+ < 0.85 * (seg.vp_bottom - seg.vp_top).abs())+ .then_some((seg.vp_top, seg.vp_bottom));seg.flush(&mut items);let meta = obj_meta.meta_for(&ch, cv.text_object());seg.start(@@ -1919,6 +1930,7 @@ fn extract_page_text_items(page_rotation,&meta,);+ seg.host_band = host;seg.append_ligature_tail(ligature_tail);} else if seg.pending_space {let avg_cw = seg.avg_char_width();@@ -3356,6 +3368,12 @@ struct SegmentBuilder {emit_words: bool,// When false, source-code/trailing-space metadata is not accumulated.extract_text_metadata: bool,+ // Set on a run split off at a size step into smaller raised / lowered type: the host+ // segment's (top, bottom), which the item takes as its band (see `TextItem::script_geom`).+ host_band: Option<(f32, f32)>,+ // The last run that took a host band: (top, bottom, right edge), so a later small-type+ // segment continuing it ("LC" "50" ... "(mg/L)", other cells drawn in between) takes it too.+ last_script: Option<(f32, f32, f32)>,}impl SegmentBuilder {@@ -3403,6 +3421,8 @@ impl SegmentBuilder {word_has: false,emit_words,extract_text_metadata,+ host_band: None,+ last_script: None,}}@@ -3518,6 +3538,26 @@ impl SegmentBuilder {page_rotation: i32,meta: &ObjTextMeta,) {+ // a run in smaller raised / lowered type keeps its host's band past a space or other+ // break while it stays in that type on that line; full-size type ends it+ let small_inside = |top: f32, bottom: f32| {+ // line-box (loose) heights on both sides: a full-size `(` has less ink than the+ // host's box, but the same box+ let mid = (vp_loose.top + vp_loose.bottom) * 0.5;+ mid > top+ && mid < bottom+ && (vp_loose.bottom - vp_loose.top).abs() < 0.85 * (bottom - top).abs()+ };+ self.host_band = self+ .host_band+ .filter(|&(top, bottom)| small_inside(top, bottom))+ .or_else(|| {+ self.last_script.and_then(|(top, bottom, right)| {+ let near = vp_loose.left >= right - 1.0+ && vp_loose.left - right < 2.0 * (bottom - top).abs();+ (near && small_inside(top, bottom)).then_some((top, bottom))+ })+ });self.text.clear();self.text.push(c);self.vp_left = vp_loose.left;@@ -3737,12 +3777,19 @@ impl SegmentBuilder {let trimmed = self.text.trim();if !trimmed.is_empty() {let width = self.vp_right - self.vp_left;- let height = self.vp_bottom - self.vp_top;+ let (band_top, band_bottom) = self.host_band.unwrap_or((self.vp_top, self.vp_bottom));+ if let Some((t, b)) = self.host_band {+ self.last_script = Some((t, b, self.vp_right));+ }+ let script_geom = self+ .host_band+ .map(|_| (self.vp_top, self.vp_bottom - self.vp_top));+ let height = band_bottom - band_top;items.push(TextItem {text: trimmed.to_string(),x: self.vp_left,- y: self.vp_top,+ y: band_top,width,height,rotation: self.rotation_deg,@@ -3777,6 +3824,8 @@ impl SegmentBuilder {underline: false,sup: false,sub: false,+ style_pieces: Vec::new(),+ script_geom,math: false,words: std::mem::take(&mut self.words),});diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rsindex 0dfc3dc..d925479 100644--- a/crates/liteparse/src/markdown_layout/inline.rs+++ b/crates/liteparse/src/markdown_layout/inline.rs@@ -216,12 +216,24 @@ fn apply_style(inner: &str, style: SpanStyle) -> String {////// Falls back to `collapse_whitespace(line.text)` when the line has no usable/// spans (e.g. OCR-only lines where TextItem styling isn't populated).-pub(super) fn render_line_inline(line: &ProjectedLine) -> String {- let spans: Vec<&TextItem> = line- .spans+/// A line's spans as the renderer styles them: a merged item that kept its differently-styled+/// pieces (`TextItem::style_pieces`) contributes those pieces.+fn styled_spans(line: &ProjectedLine) -> Vec<&TextItem> {+ line.spans.iter()+ .flat_map(|s| {+ if s.style_pieces.is_empty() {+ std::slice::from_ref(s)+ } else {+ s.style_pieces.as_slice()+ }+ }).filter(|s| !s.text.trim().is_empty())- .collect();+ .collect()+}++pub(super) fn render_line_inline(line: &ProjectedLine) -> String {+ let spans: Vec<&TextItem> = styled_spans(line);if spans.is_empty() {return collapse_whitespace(&line.text);}@@ -416,11 +428,7 @@ pub(super) fn line_uniform_style(line: &ProjectedLine) -> Option<SpanStyle> {{return None;}- let mut iter = line- .spans- .iter()- .filter(|s| !s.text.trim().is_empty())- .map(SpanStyle::from_item);+ let mut iter = styled_spans(line).into_iter().map(SpanStyle::from_item);let first = iter.next()?;for s in iter {if s != first {diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex e64283e..82a65ed 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -569,6 +569,11 @@ fn form_lines(y_tolerance: f32,h_tolerance: f32,) -> bool {+ // a super/subscript run shares its host's band (`TextItem::script_geom`) but must reach+ // script flagging on its own; the later word merge joins it, keeping it as a piece+ if prev.item.script_geom.is_some() || cur.item.script_geom.is_some() {+ return false;+ }if (cur.item.y - prev.item.y).abs() <= y_tolerance&& (cur.item.height - prev.item.height).abs() <= h_tolerance{@@ -847,17 +852,20 @@ fn form_lines(.chars().next().is_some_and(|c| c.is_alphabetic());- // For markdown, an emphasis change (bold / italic / struck / monospace) keeps- // the items apart: a merged item carries one font, so the second run would render- // in the first one's style. Plain text has no emphasis, and its grid places- // columns from the merged items, so it keeps merging across style changes.- let style_change = style_runs && !same_emphasis(&prev.item, &item.item);+ // Items merge whatever their emphasis, so lines, tables and blocks see the same+ // items in every output; for markdown a merge across an emphasis change keeps+ // the pieces, so each renders in its own style (`record_style_piece`).+ let keep_pieces = style_runs+ && (!prev.item.style_pieces.is_empty()+ || !same_emphasis(&prev.item, &item.item));if y_compatible&& !both_are_numbers&& !alpha_alpha_gap- && !style_change&& delta_x <= MERGE_THRESHOLD{+ if keep_pieces {+ record_style_piece(&mut prev.item, &item.item);+ }prev.item.width = item.item.x + item.item.width - prev.item.x;join_in_reading_order(&mut prev.item.text, &item.item.text, "");prev.item.words.append(&mut item.item.words);@@ -867,7 +875,10 @@ fn form_lines(let prev_len = prev.item.text.chars().count().max(1) as f32;let avg_char_width = prev.item.width / prev_len;- if y_compatible && !both_are_numbers && !style_change && delta_x < avg_char_width {+ if y_compatible && !both_are_numbers && delta_x < avg_char_width {+ if keep_pieces {+ record_style_piece(&mut prev.item, &item.item);+ }prev.item.width = item.item.x + item.item.width - prev.item.x;join_in_reading_order(&mut prev.item.text, &item.item.text, " ");prev.item.words.append(&mut item.item.words);@@ -3081,12 +3092,14 @@ fn name_contains_any(name: &str, hints: &[&str]) -> bool {/// (OCR boxes are too loose to tell a raised glyph from jitter).fn mark_script_items(line: &mut [ProjectedTextItem]) {let native = |p: &ProjectedTextItem| p.item.confidence.is_none() && !p.item.math;+ // an item's own glyph box: a run split off at a size step carries its host's band+ let geom = |it: &TextItem| it.script_geom.unwrap_or((it.y, it.height));let mut hs: Vec<(f32, usize)> = line.iter()- .filter(|p| native(p) && p.item.height > 0.0)+ .filter(|p| native(p) && geom(&p.item).1 > 0.0).map(|p| {(- p.item.height,+ geom(&p.item).1,p.item.text.chars().filter(|c| !c.is_whitespace()).count(),)})@@ -3106,8 +3119,8 @@ fn mark_script_items(line: &mut [ProjectedTextItem]) {}let mut bottoms: Vec<f32> = line.iter()- .filter(|p| native(p) && p.item.height >= body_h * 0.9)- .map(|p| p.item.y + p.item.height)+ .filter(|p| native(p) && geom(&p.item).1 >= body_h * 0.9)+ .map(|p| geom(&p.item).0 + geom(&p.item).1).collect();if bottoms.is_empty() || body_h <= 0.0 {return;@@ -3117,13 +3130,14 @@ fn mark_script_items(line: &mut [ProjectedTextItem]) {for p in line.iter_mut().filter(|p| native(p)) {let it = &mut p.item;let n = it.text.trim().chars().count();- if n == 0 || n > 6 || it.height > body_h * 0.78 {+ let (gy, gh) = geom(it);+ if n == 0 || n > 6 || gh > body_h * 0.78 {continue;}- let bottom = it.y + it.height;+ let bottom = gy + gh;if bottom <= base - body_h * 0.2 {it.sup = true;- } else if bottom >= base + body_h * 0.1 && it.y >= base - body_h * 0.6 {+ } else if bottom >= base + body_h * 0.1 && gy >= base - body_h * 0.6 {it.sub = true;}}@@ -3179,6 +3193,23 @@ fn mark_script_items(line: &mut [ProjectedTextItem]) {}}+/// Before `next` merges into `prev`: keep both as styled pieces (`TextItem::style_pieces`), `prev`+/// as it was before any merge and `next` with its own pieces flattened in.+fn record_style_piece(prev: &mut TextItem, next: &TextItem) {+ if prev.style_pieces.is_empty() {+ let mut first = prev.clone();+ first.words.clear();+ prev.style_pieces.push(first);+ }+ if next.style_pieces.is_empty() {+ let mut piece = next.clone();+ piece.words.clear();+ prev.style_pieces.push(piece);+ } else {+ prev.style_pieces.extend(next.style_pieces.iter().cloned());+ }+}+/// Whether two items render with the same inline emphasis.fn same_emphasis(a: &TextItem, b: &TextItem) -> bool {is_bold_item(a) == is_bold_item(b)diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rsindex ec19a39..48a83b2 100644--- a/crates/liteparse/src/types.rs+++ b/crates/liteparse/src/types.rs@@ -134,6 +134,16 @@ pub struct TextItem {pub sup: bool,#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub sub: bool,+ /// The pieces an item was merged from, when their emphasis differs (bold / italic / struck /+ /// monospace / underline / script): the markdown renderer styles each piece, while lines,+ /// tables and blocks see the one merged item. Empty otherwise. Internal.+ #[serde(skip)]+ pub style_pieces: Vec<TextItem>,+ /// A super/subscript run split from its line at a size step: its own glyph box `(y, height)`.+ /// `y` / `height` then hold the host text's band, so lines and tables group the run with its+ /// host as before the split; script detection reads this box. Internal.+ #[serde(skip)]+ pub script_geom: Option<(f32, f32)>,/// Whether this item is LaTeX rebuilt from TeX math fonts (`$…$`)./// Populated in `extract.rs`.#[serde(default, skip_serializing_if = "std::ops::Not::not")]