A fast, helpful, and open-source document parser
feat: add markdown field on page-level JSON output
Logan Markewich91ebb584e29e
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex 6dbde2f..7526ab7 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -365,6 +365,8 @@ pub struct JsParsedPage {pub width: f64,pub height: f64,pub text: String,+ /// Per-page markdown; empty unless the parse ran with markdown output.+ pub markdown: String,pub text_items: Vec<JsTextItem>,}@@ -375,6 +377,7 @@ impl JsParsedPage {width: page.page_width as f64,height: page.page_height as f64,text: page.text.clone(),+ markdown: page.markdown.clone(),text_items: page.text_items.iter().map(JsTextItem::from_rust).collect(),}}diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rsindex 90b4e26..9a9f9ca 100644--- a/crates/liteparse-python/src/lib.rs+++ b/crates/liteparse-python/src/lib.rs@@ -130,6 +130,9 @@ struct PyParsedPage {height: f64,#[pyo3(get)]text: String,+ /// Per-page markdown; empty unless the parse ran with markdown output.+ #[pyo3(get)]+ markdown: String,#[pyo3(get)]text_items: Vec<PyTextItem>,}@@ -154,6 +157,7 @@ impl PyParsedPage {width: page.page_width as f64,height: page.page_height as f64,text: page.text,+ markdown: page.markdown,text_items: page.text_items.into_iter()diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rsindex 04c68d2..026a36f 100644--- a/crates/liteparse-wasm/src/lib.rs+++ b/crates/liteparse-wasm/src/lib.rs@@ -207,6 +207,8 @@ struct JsParsedPage<'a> {width: f32,height: f32,text: &'a str,+ /// Per-page markdown; empty unless the parse ran with markdown output.+ markdown: &'a str,text_items: Vec<JsTextItem<'a>>,}@@ -390,6 +392,7 @@ impl LiteParse {width: p.page_width,height: p.page_height,text: &p.text,+ markdown: &p.markdown,text_items: p.text_items.iter()diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rsindex c167eb7..2fbe925 100644--- a/crates/liteparse/src/markdown_layout/test_helpers.rs+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs@@ -34,6 +34,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {page_width: 612.0,page_height: 792.0,text: String::new(),+ markdown: String::new(),text_items: vec![],projected_lines: lines,regions: crate::types::Region::default(),@@ -183,6 +184,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &stpage_width: 612.0,page_height: 100.0,text: String::new(),+ markdown: String::new(),text_items: vec![],projected_lines: lines,regions: crate::types::Region::default(),diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rsindex 1ac0482..442ec2a 100644--- a/crates/liteparse/src/output/json.rs+++ b/crates/liteparse/src/output/json.rs@@ -90,6 +90,7 @@ mod tests {page_width: 612.0,page_height: 792.0,text: "txt".into(),+ markdown: String::new(),text_items: items,projected_lines: vec![],regions: crate::types::Region::default(),diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rsindex 53cd69c..3d5caf1 100644--- a/crates/liteparse/src/output/markdown.rs+++ b/crates/liteparse/src/output/markdown.rs@@ -22,65 +22,78 @@ pub fn format_markdown(outline: &[OutlineTarget],image_mode: ImageMode,) -> String {+ format_markdown_pages(pages, outline, image_mode).join("\n\n-----\n\n")+}++/// Render each page to its own markdown string, returning one entry per input+/// page (in order). [`format_markdown`] joins these with page separators to+/// build the document output; callers wanting per-page markdown (e.g. to+/// populate `ParsedPage.markdown`) use this directly. Doc-level context+/// (body size, heading map, header/footer set) is still computed across all+/// pages so a single page renders identically whether requested alone or as+/// part of the document.+pub fn format_markdown_pages(+ pages: &[ParsedPage],+ outline: &[OutlineTarget],+ image_mode: ImageMode,+) -> Vec<String> {if pages.is_empty() {- return String::new();+ return Vec::new();}let body_size = compute_body_size(pages);let heading_map = build_heading_map(pages, body_size);let header_footer = compute_header_footer_set(pages);- let mut out = String::new();- for (i, page) in pages.iter().enumerate() {- if i > 0 {- out.push_str("\n\n-----\n\n");- }- if page.projected_lines.is_empty() {- // No structural metadata for this page — fall back to the- // projection text inside a fence so nothing is dropped.- out.push_str("```text\n");- out.push_str(&page.text);- if !page.text.ends_with('\n') {- out.push('\n');+ pages+ .iter()+ .map(|page| {+ if page.projected_lines.is_empty() {+ // No structural metadata for this page — fall back to the+ // projection text inside a fence so nothing is dropped.+ let mut out = String::from("```text\n");+ out.push_str(&page.text);+ if !page.text.ends_with('\n') {+ out.push('\n');+ }+ out.push_str("```");+ return out;}- out.push_str("```");- continue;- }- // Filter outline entries to this page so the classifier's y/title- // match is a O(entries_on_page) scan per line, not O(whole doc).- let target_index = (page.page_number as i32).saturating_sub(1);- let page_outline: Vec<OutlineTarget> = outline- .iter()- .filter(|e| e.page_index == target_index)- .cloned()- .collect();- let chrome_indices = detect_single_page_chrome(page, body_size);- let mut blocks = classify_page_with_filters(- page,- &heading_map,- &header_footer,- &page_outline,- image_mode,- &chrome_indices,- );- // A page whose only surviving blocks are horizontal rules (all its- // text was stripped as chrome) should render empty, not as a stack- // of bare `---` separators.- let has_content = blocks.iter().any(|b| {- !matches!(- b,- crate::markdown_layout::Block::HorizontalRule- | crate::markdown_layout::Block::Figure { .. }- )- });- if !has_content {- blocks.retain(|b| !matches!(b, crate::markdown_layout::Block::HorizontalRule));- }- dedupe_rules(&mut blocks);- out.push_str(&render_blocks(&blocks));- }- out+ // Filter outline entries to this page so the classifier's y/title+ // match is a O(entries_on_page) scan per line, not O(whole doc).+ let target_index = (page.page_number as i32).saturating_sub(1);+ let page_outline: Vec<OutlineTarget> = outline+ .iter()+ .filter(|e| e.page_index == target_index)+ .cloned()+ .collect();+ let chrome_indices = detect_single_page_chrome(page, body_size);+ let mut blocks = classify_page_with_filters(+ page,+ &heading_map,+ &header_footer,+ &page_outline,+ image_mode,+ &chrome_indices,+ );+ // A page whose only surviving blocks are horizontal rules (all its+ // text was stripped as chrome) should render empty, not as a stack+ // of bare `---` separators.+ let has_content = blocks.iter().any(|b| {+ !matches!(+ b,+ crate::markdown_layout::Block::HorizontalRule+ | crate::markdown_layout::Block::Figure { .. }+ )+ });+ if !has_content {+ blocks.retain(|b| !matches!(b, crate::markdown_layout::Block::HorizontalRule));+ }+ dedupe_rules(&mut blocks);+ render_blocks(&blocks)+ })+ .collect()}/// Collapse cosmetic horizontal-rule noise on a single page's block stream:@@ -137,6 +150,7 @@ mod tests {page_width: 612.0,page_height: 792.0,text: "fallback".into(),+ markdown: String::new(),text_items: vec![],projected_lines: lines,regions: crate::types::Region::default(),@@ -184,6 +198,7 @@ mod tests {page_width: 0.0,page_height: 0.0,text: "hello".into(),+ markdown: String::new(),text_items: vec![],projected_lines: vec![],regions: crate::types::Region::default(),@@ -235,4 +250,22 @@ mod tests {assert!(out.contains("-----"));assert!(out.find("A page.").unwrap() < out.find("B page.").unwrap());}++ #[test]+ fn test_per_page_matches_joined_document() {+ let a = page_with(1, vec![line("A page.", 50.0, 80.0, 10.0, 10.0)]);+ let b = page_with(2, vec![line("B page.", 50.0, 80.0, 10.0, 10.0)]);+ let pages = [a, b];+ let per_page = format_markdown_pages(&pages, &[], ImageMode::Placeholder);+ assert_eq!(per_page.len(), 2);+ assert!(per_page[0].contains("A page."));+ assert!(per_page[1].contains("B page."));+ // The per-page strings carry no separator on their own; the document+ // form is exactly the join.+ assert!(!per_page[0].contains("-----"));+ assert_eq!(+ format_markdown(&pages, &[], ImageMode::Placeholder),+ per_page.join("\n\n-----\n\n")+ );+ }}diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rsindex 196ce7b..64348b3 100644--- a/crates/liteparse/src/output/text.rs+++ b/crates/liteparse/src/output/text.rs@@ -19,6 +19,7 @@ mod tests {page_width: 0.0,page_height: 0.0,text: text.into(),+ markdown: String::new(),text_items: vec![],projected_lines: vec![],regions: crate::types::Region::default(),diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex 183100f..0d41929 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -350,7 +350,7 @@ impl LiteParse {));// Grid projection- let parsed_pages = projection::project_pages_to_grid(pages);+ let mut parsed_pages = projection::project_pages_to_grid(pages);let t2 = web_time::Instant::now();log(&format!("[liteparse] project: {:.1}ms",@@ -358,7 +358,12 @@ impl LiteParse {));let full_text = if self.config.output_format == crate::config::OutputFormat::Markdown {- let md = markdown::format_markdown(&parsed_pages, &outline, self.config.image_mode);+ let page_md =+ markdown::format_markdown_pages(&parsed_pages, &outline, self.config.image_mode);+ let md = page_md.join("\n\n-----\n\n");+ for (page, md) in parsed_pages.iter_mut().zip(page_md) {+ page.markdown = md;+ }let t3 = web_time::Instant::now();log(&format!("[liteparse] markdown: {:.1}ms",@@ -393,10 +398,16 @@ impl LiteParse {/// is fully synchronous. Used when an external extractor (e.g. with its/// own font-recovery pipeline) owns text extraction.pub fn parse_from_pages(&self, pages: Vec<Page>, outline: Vec<OutlineTarget>) -> ParseResult {- let parsed_pages = projection::project_pages_to_grid(pages);+ let mut parsed_pages = projection::project_pages_to_grid(pages);let full_text = if self.config.output_format == crate::config::OutputFormat::Markdown {- markdown::format_markdown(&parsed_pages, &outline, self.config.image_mode)+ let page_md =+ markdown::format_markdown_pages(&parsed_pages, &outline, self.config.image_mode);+ let md = page_md.join("\n\n-----\n\n");+ for (page, md) in parsed_pages.iter_mut().zip(page_md) {+ page.markdown = md;+ }+ md} else {parsed_pages.iter()diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex 28c1661..5253dae 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -2862,6 +2862,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {page_width: page.page_width,page_height: page.page_height,text,+ markdown: String::new(),text_items: projected_items.into_iter().map(|proj| TextItem {diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rsindex 5ddf9f5..dabfa8b 100644--- a/crates/liteparse/src/types.rs+++ b/crates/liteparse/src/types.rs@@ -148,6 +148,12 @@ pub struct ParsedPage {pub page_width: f32,pub page_height: f32,pub text: String,+ /// Per-page markdown, populated only when the parse runs with+ /// `OutputFormat::Markdown`; empty otherwise. `text` is always the plain+ /// projected layout, so this is the per-page counterpart to the document+ /// markdown on `ParseResult.text`.+ #[serde(skip_serializing_if = "String::is_empty")]+ pub markdown: String,pub text_items: Vec<TextItem>,/// Per-line structural metadata used by the markdown emitter. Not part of/// the JSON/text outputs (consumed internally) so it is `#[serde(skip)]`.diff --git a/packages/node/native.d.ts b/packages/node/native.d.tsindex f9fe03b..c0803e8 100644--- a/packages/node/native.d.ts+++ b/packages/node/native.d.ts@@ -136,6 +136,7 @@ export interface JsParsedPage {width: numberheight: numbertext: string+ markdown: stringtextItems: Array<JsTextItem>}export interface JsParseResult {diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.tsindex 9b0206c..2377f40 100644--- a/packages/node/src/lib.ts+++ b/packages/node/src/lib.ts@@ -134,6 +134,8 @@ export interface ParsedPage {width: number;height: number;text: string;+ /** Per-page markdown; empty unless parsed with `outputFormat: "markdown"`. */+ markdown: string;textItems: TextItem[];}@@ -343,6 +345,7 @@ function toPage(p: NativeParsedPage): ParsedPage {width: p.width,height: p.height,text: p.text,+ markdown: p.markdown,textItems: p.textItems.map(toTextItem),};}diff --git a/packages/node/src/native.ts b/packages/node/src/native.tsindex dd16ded..b565c30 100644--- a/packages/node/src/native.ts+++ b/packages/node/src/native.ts@@ -91,6 +91,7 @@ export interface NativeParsedPage {width: number;height: number;text: string;+ markdown: string;textItems: NativeTextItem[];}diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex 823a9a8..fa74753 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -53,6 +53,7 @@ def _convert_native_result(native_result: Any) -> ParseResult:width=native_page.width,height=native_page.height,text=native_page.text,+ markdown=native_page.markdown,text_items=text_items,))diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.pyindex d85e8e9..c9ca0d3 100644--- a/packages/python/liteparse/types.py+++ b/packages/python/liteparse/types.py@@ -41,6 +41,7 @@ class ParsedPage:width: floatheight: floattext: str+ markdown: str = ""text_items: List[TextItem] = field(default_factory=list)