A fast, helpful, and open-source document parser
refactor into core lib
Logan Markewich2365679b5083
diff --git a/Cargo.lock b/Cargo.lockindex 2887c22..1162232 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2016,7 +2016,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"[[package]]name = "liteparse"-version = "2.11.0"+version = "2.11.1"dependencies = ["blake3","clap",@@ -2048,7 +2048,7 @@ dependencies = [[[package]]name = "liteparse-napi"-version = "2.11.0"+version = "2.11.1"dependencies = ["image","liteparse",@@ -2064,7 +2064,7 @@ dependencies = [[[package]]name = "liteparse-pdfium"-version = "1.5.0"+version = "1.6.0"dependencies = ["blake3","liteparse-pdfium-sys",@@ -2072,7 +2072,7 @@ dependencies = [[[package]]name = "liteparse-pdfium-sys"-version = "1.5.0"+version = "1.6.0"dependencies = ["bindgen","flate2",@@ -2083,7 +2083,7 @@ dependencies = [[[package]]name = "liteparse-python"-version = "2.11.0"+version = "2.11.1"dependencies = ["anyhow","clap",@@ -2099,7 +2099,7 @@ dependencies = [[[package]]name = "liteparse-wasm"-version = "2.11.0"+version = "2.11.1"dependencies = ["console_error_panic_hook","js-sys",diff --git a/crates/liteparse-napi/src/lib.rs b/crates/liteparse-napi/src/lib.rsindex 27a725a..ffcf0af 100644--- a/crates/liteparse-napi/src/lib.rs+++ b/crates/liteparse-napi/src/lib.rs@@ -4,8 +4,8 @@ use napi_derive::napi;mod types;use types::{- JsLiteParseConfig, JsPageComplexityStats, JsPageInput, JsParseResult, JsScreenshotResult,- JsTextItem,+ JsLiteParseConfig, JsPageComplexityStats, JsPageInput, JsParseBatch, JsParseResult,+ JsScreenshotResult, JsTextItem,};/// Main LiteParse parser class.@@ -48,6 +48,41 @@ impl LiteParse {Ok(JsParseResult::from_rust(&result, &self.config))}+ /// Open a document for bounded-memory batch parsing.+ ///+ /// Converts a non-PDF source once, then yields `batchSize` pages at a time+ /// via `nextBatch()` (default 25). Cross-page passes (repeated+ /// header/footer removal, image deduplication) see only the pages in their+ /// own batch, so output can differ from a whole-document `parse()`.+ #[napi]+ pub async fn open(+ &self,+ input: Either<String, Buffer>,+ batch_size: Option<u32>,+ ) -> Result<ParseSession> {+ use liteparse::types::PdfInput;++ let pdf_input = match input {+ Either::A(path) => PdfInput::Path(path),+ Either::B(buf) => PdfInput::Bytes(buf.to_vec()),+ };+ let batch_size = batch_size+ .map(|v| v as usize)+ .unwrap_or(liteparse::DEFAULT_PAGE_BATCH_SIZE);++ let session = self+ .inner+ .open(pdf_input, batch_size)+ .await+ .map_err(|e| Error::from_reason(e.to_string()))?;++ Ok(ParseSession {+ total_pages: session.total_pages(),+ inner: std::sync::Arc::new(tokio::sync::Mutex::new(session)),+ config: self.config.clone(),+ })+ }+/// Parse from pre-extracted pages, skipping PDFium text extraction.////// The caller supplies pages already populated with text items in viewport@@ -134,6 +169,48 @@ impl LiteParse {}}+/// A document opened once and parsed in bounded page batches.+///+/// Created by `LiteParse.open()`. The converted-PDF temporary file for a+/// non-PDF source lives as long as the session, so conversion is paid once no+/// matter how many batches are consumed.+#[napi]+pub struct ParseSession {+ /// The core session is `&mut` per batch, but napi hands out `&self`, so+ /// the mutation is serialized here. Concurrent `nextBatch()` calls queue+ /// rather than interleave, which also keeps batch order well-defined.+ inner: std::sync::Arc<tokio::sync::Mutex<liteparse::ParseSession>>,+ config: liteparse::config::LiteParseConfig,+ total_pages: u32,+}++#[napi]+impl ParseSession {+ /// Total pages in the source document, before `maxPages` or batching.+ #[napi(getter)]+ pub fn total_pages(&self) -> u32 {+ self.total_pages+ }++ /// Parse and return the next batch, or `null` once every page within+ /// `maxPages` has been yielded.+ #[napi]+ pub async fn next_batch(&self) -> Result<Option<JsParseBatch>> {+ let inner = self.inner.clone();+ let mut session = inner.lock().await;+ let batch = session+ .next_batch()+ .await+ .map_err(|e| Error::from_reason(e.to_string()))?;++ Ok(batch.map(|batch| JsParseBatch {+ start_page: batch.start_page,+ end_page: batch.end_page,+ result: JsParseResult::from_rust(&batch.result, &self.config),+ }))+ }+}+/// Search text items for phrase matches, returning merged items with combined bounding boxes.#[napi]pub fn search_items(diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex 91a78eb..1504abc 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -899,6 +899,17 @@ pub struct JsParseResult {pub xfa_packets: Option<Vec<JsXfaPacket>>,}+/// One batch of pages from a `ParseSession`.+#[napi(object)]+pub struct JsParseBatch {+ /// First source page in this batch, 1-indexed.+ pub start_page: u32,+ /// Last source page in this batch, 1-indexed and inclusive.+ pub end_page: u32,+ /// The pages in `startPage..=endPage`, as an ordinary parse result.+ pub result: JsParseResult,+}+#[napi(object)]#[derive(Clone)]pub struct JsDocumentMetadata {diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rsindex 10a15a5..2be21e6 100644--- a/crates/liteparse-python/src/lib.rs+++ b/crates/liteparse-python/src/lib.rs@@ -1168,6 +1168,72 @@ impl PyLiteParseConfig {}}+// ---------------------------------------------------------------------------+// Batch parsing+// ---------------------------------------------------------------------------++/// One batch of pages from a `ParseSession`.+#[pyclass(frozen, name = "ParseBatch")]+#[derive(Clone)]+struct PyParseBatch {+ /// First source page in this batch (1-indexed).+ #[pyo3(get)]+ start_page: u32,+ /// Last source page in this batch (1-indexed, inclusive).+ #[pyo3(get)]+ end_page: u32,+ /// The pages in `start_page..=end_page`, as an ordinary parse result.+ #[pyo3(get)]+ result: PyParseResult,+}++/// A document opened once and parsed in bounded page batches.+///+/// Iterate it directly to consume every batch:+///+/// for batch in parser.open("large.pdf", batch_size=20):+/// handle(batch.result.pages)+#[pyclass(name = "ParseSession", unsendable)]+struct PyParseSession {+ inner: liteparse::ParseSession,+ runtime: std::sync::Arc<tokio::runtime::Runtime>,+ extract_text_metadata: bool,+}++#[pymethods]+impl PyParseSession {+ /// Total pages in the source document, before `max_pages` or batching.+ #[getter]+ fn total_pages(&self) -> u32 {+ self.inner.total_pages()+ }++ /// Parse and return the next batch, or `None` once every page within+ /// `max_pages` has been yielded.+ fn next_batch(&mut self, py: Python<'_>) -> PyResult<Option<PyParseBatch>> {+ // Releasing the GIL keeps other Python threads running while PDFium+ // extraction and grid projection execute, matching `parse()`.+ let batch = py+ .detach(|| self.runtime.block_on(self.inner.next_batch()))+ .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;++ Ok(batch.map(|batch| PyParseBatch {+ start_page: batch.start_page,+ end_page: batch.end_page,+ result: PyParseResult::from_rust(batch.result, self.extract_text_metadata),+ }))+ }++ fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {+ slf+ }++ /// Returning `None` raises `StopIteration`, ending the loop.+ fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<PyParseBatch>> {+ self.next_batch(py)+ }+}+// ---------------------------------------------------------------------------// Main LiteParse class// ---------------------------------------------------------------------------@@ -1176,7 +1242,7 @@ impl PyLiteParseConfig {struct LiteParse {inner: liteparse::parser::LiteParse,config: LiteParseConfig,- runtime: tokio::runtime::Runtime,+ runtime: std::sync::Arc<tokio::runtime::Runtime>,}#[pymethods]@@ -1373,8 +1439,10 @@ impl LiteParse {}let inner = liteparse::parser::LiteParse::new(cfg.clone());- let runtime = tokio::runtime::Runtime::new()- .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;+ let runtime = std::sync::Arc::new(+ tokio::runtime::Runtime::new()+ .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?,+ );Ok(Self {inner,@@ -1395,6 +1463,33 @@ impl LiteParse {))}+ /// Open a document from a file path for bounded-memory batch parsing.+ ///+ /// Converts a non-PDF source once and returns a `ParseSession` yielding+ /// `batch_size` pages at a time. Cross-page passes (repeated header/footer+ /// removal, image deduplication) see only the pages in their own batch, so+ /// output can differ from a whole-document `parse()`.+ #[pyo3(signature = (input, batch_size = None))]+ fn open(+ &self,+ py: Python<'_>,+ input: String,+ batch_size: Option<usize>,+ ) -> PyResult<PyParseSession> {+ self.open_session(py, PdfInput::Path(input), batch_size)+ }++ /// Open a document from raw bytes for bounded-memory batch parsing.+ #[pyo3(signature = (data, batch_size = None))]+ fn open_bytes(+ &self,+ py: Python<'_>,+ data: Vec<u8>,+ batch_size: Option<usize>,+ ) -> PyResult<PyParseSession> {+ self.open_session(py, PdfInput::Bytes(data), batch_size)+ }+/// Parse a document from raw bytes.fn parse_bytes(&self, py: Python<'_>, data: Vec<u8>) -> PyResult<PyParseResult> {let pdf_input = PdfInput::Bytes(data);@@ -1487,6 +1582,28 @@ impl LiteParse {}}+impl LiteParse {+ /// Shared body of `open` / `open_bytes`. Not a `#[pymethods]` entry, so it+ /// stays off the Python surface.+ fn open_session(+ &self,+ py: Python<'_>,+ input: PdfInput,+ batch_size: Option<usize>,+ ) -> PyResult<PyParseSession> {+ let batch_size = batch_size.unwrap_or(liteparse::DEFAULT_PAGE_BATCH_SIZE);+ let session = py+ .detach(|| self.runtime.block_on(self.inner.open(input, batch_size)))+ .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;++ Ok(PyParseSession {+ inner: session,+ runtime: self.runtime.clone(),+ extract_text_metadata: self.config.extract_text_metadata,+ })+ }+}+// ---------------------------------------------------------------------------// Module// ---------------------------------------------------------------------------@@ -1559,6 +1676,8 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_class::<LiteParse>()?;m.add_class::<PyLiteParseConfig>()?;m.add_class::<PyParseResult>()?;+ m.add_class::<PyParseBatch>()?;+ m.add_class::<PyParseSession>()?;m.add_class::<PyDocumentMetadata>()?;m.add_class::<PyExtractedImage>()?;m.add_class::<PyImageRect>()?;diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rsindex b5c0d4a..cce034f 100644--- a/crates/liteparse-wasm/src/lib.rs+++ b/crates/liteparse-wasm/src/lib.rs@@ -911,168 +911,181 @@ impl LiteParse {.await.map_err(|e| JsError::new(&format!("parse failed: {}", e)))?;- let extract_text_metadata = self.inner.config().extract_text_metadata;- let pages: Vec<ParsedPage> = result- .pages- .iter()- .map(|p| ParsedPage {- page_num: p.page_number,- width: p.page_width,- height: p.page_height,- content_bounds: p.content_bounds.as_ref().map(|b| VectorRect {- x: b.x,- y: b.y,- width: b.width,- height: b.height,- }),- text: p.text.clone(),- markdown: p.markdown.clone(),- text_items: p- .text_items+ Ok(to_js_result(+ &result,+ self.inner.config().extract_text_metadata,+ ))+ }+}++/// Convert a core [`CoreParseResult`] into the wasm-bindgen view.+///+/// Shared by `parse()` and `ParseSession::nextBatch()` so a batch is mapped+/// exactly the same way a whole-document result is.+fn to_js_result(result: &liteparse::ParseResult, extract_text_metadata: bool) -> ParseResult {+ let pages: Vec<ParsedPage> = result+ .pages+ .iter()+ .map(|p| ParsedPage {+ page_num: p.page_number,+ width: p.page_width,+ height: p.page_height,+ content_bounds: p.content_bounds.as_ref().map(|b| VectorRect {+ x: b.x,+ y: b.y,+ width: b.width,+ height: b.height,+ }),+ text: p.text.clone(),+ markdown: p.markdown.clone(),+ text_items: p+ .text_items+ .iter()+ .map(|i| {+ // Core-gated metadata view; `TextMetadata` defines+ // which fields `extractTextMetadata` covers.+ let meta = i.text_metadata(extract_text_metadata);+ TextItem {+ text: i.text.clone(),+ x: i.x,+ y: i.y,+ width: i.width,+ height: i.height,+ font_name: i.font_name.clone(),+ font_size: i.font_size,+ confidence: i.confidence,+ rotation: i.rotation,+ font_height: meta.font_height,+ font_ascent: meta.font_ascent,+ font_descent: meta.font_descent,+ font_weight: meta.font_weight,+ text_width: meta.text_width,+ font_is_buggy: meta.font_is_buggy,+ mcid: meta.mcid,+ fill_color: meta.fill_color.map(str::to_owned),+ stroke_color: meta.stroke_color.map(str::to_owned),+ char_codes: meta+ .char_codes+ .filter(|codes| !codes.is_empty())+ .map(<[u32]>::to_vec),+ trailing_space_generated: meta.trailing_space_generated,+ words: if i.words.is_empty() {+ None+ } else {+ Some(+ i.words+ .iter()+ .map(|w| WordBox {+ text: w.text.clone(),+ x: w.x,+ y: w.y,+ width: w.width,+ height: w.height,+ })+ .collect(),+ )+ },+ }+ })+ .collect(),+ complexity: p.complexity.as_ref().map(PageComplexityStats::from_rust),+ vector_graphics: p.vector_graphics.as_ref().map(|v| VectorGraphics {+ shapes: v+ .shapes.iter()- .map(|i| {- // Core-gated metadata view; `TextMetadata` defines- // which fields `extractTextMetadata` covers.- let meta = i.text_metadata(extract_text_metadata);- TextItem {- text: i.text.clone(),- x: i.x,- y: i.y,- width: i.width,- height: i.height,- font_name: i.font_name.clone(),- font_size: i.font_size,- confidence: i.confidence,- rotation: i.rotation,- font_height: meta.font_height,- font_ascent: meta.font_ascent,- font_descent: meta.font_descent,- font_weight: meta.font_weight,- text_width: meta.text_width,- font_is_buggy: meta.font_is_buggy,- mcid: meta.mcid,- fill_color: meta.fill_color.map(str::to_owned),- stroke_color: meta.stroke_color.map(str::to_owned),- char_codes: meta- .char_codes- .filter(|codes| !codes.is_empty())- .map(<[u32]>::to_vec),- trailing_space_generated: meta.trailing_space_generated,- words: if i.words.is_empty() {- None- } else {- Some(- i.words- .iter()- .map(|w| WordBox {- text: w.text.clone(),- x: w.x,- y: w.y,- width: w.width,- height: w.height,- })- .collect(),- )- },- }+ .map(|s| VectorShape {+ bbox: VectorRect {+ x: s.bbox.x,+ y: s.bbox.y,+ width: s.bbox.width,+ height: s.bbox.height,+ },+ stroke: s.stroke,+ stroke_color: s.stroke_color.clone(),+ fill: s.fill,+ fill_color: s.fill_color.clone(),+ has_curve: s.has_curve,}).collect(),- complexity: p.complexity.as_ref().map(PageComplexityStats::from_rust),- vector_graphics: p.vector_graphics.as_ref().map(|v| VectorGraphics {- shapes: v- .shapes- .iter()- .map(|s| VectorShape {- bbox: VectorRect {- x: s.bbox.x,- y: s.bbox.y,- width: s.bbox.width,- height: s.bbox.height,- },- stroke: s.stroke,- stroke_color: s.stroke_color.clone(),- fill: s.fill,- fill_color: s.fill_color.clone(),- has_curve: s.has_curve,- })- .collect(),- lines: v- .lines- .iter()- .map(|l| VectorLine {- x1: l.x1,- y1: l.y1,- x2: l.x2,- y2: l.y2,- stroke: l.stroke,- stroke_width: l.stroke_width,- stroke_color: l.stroke_color.clone(),- fill: l.fill,- fill_color: l.fill_color.clone(),- })- .collect(),- }),- annotations: p.annotations.as_ref().map(|annotations| {- annotations- .iter()- .map(DocumentAnnotation::from_rust)- .collect()- }),- form_fields: p- .form_fields- .as_ref()- .map(|fields| fields.iter().map(FormField::from_rust).collect()),- structure_tree: p.structure_tree.as_ref().map(StructureTree::from_rust),- })- .collect();-- let images: Vec<ExtractedImage> = result- .images- .iter()- .map(|img| ExtractedImage {- id: img.id.clone(),- name: img.name.clone(),- path: img.path.clone(),- page: img.page,- bbox: ImageRect {- x: img.bbox.x,- y: img.bbox.y,- width: img.bbox.width,- height: img.bbox.height,- },- width: img.width,- height: img.height,- rotation: img.rotation,- format: img.format.clone(),- duplicate_of: img.duplicate_of.clone(),- bytes: img.bytes.as_slice().to_vec(),- })- .collect();-- Ok(ParseResult {- total_pages: result.total_pages,- pages,- text: result.text.clone(),- images,- image_error_count: result.image_error_count,- form_type: result.form_type,- creator: result.creator.clone(),- producer: result.producer.clone(),- doc_meta: result.doc_meta.as_ref().map(DocumentMetadata::from),- xfa_packets: result.xfa_packets.as_ref().map(|packets| {- packets+ lines: v+ .lines.iter()- .map(|packet| XfaPacket {- index: packet.index,- name: packet.name.clone(),- content_length: packet.content_length,- content: packet.content.clone(),+ .map(|l| VectorLine {+ x1: l.x1,+ y1: l.y1,+ x2: l.x2,+ y2: l.y2,+ stroke: l.stroke,+ stroke_width: l.stroke_width,+ stroke_color: l.stroke_color.clone(),+ fill: l.fill,+ fill_color: l.fill_color.clone(),})+ .collect(),+ }),+ annotations: p.annotations.as_ref().map(|annotations| {+ annotations+ .iter()+ .map(DocumentAnnotation::from_rust).collect()}),+ form_fields: p+ .form_fields+ .as_ref()+ .map(|fields| fields.iter().map(FormField::from_rust).collect()),+ structure_tree: p.structure_tree.as_ref().map(StructureTree::from_rust),+ })+ .collect();++ let images: Vec<ExtractedImage> = result+ .images+ .iter()+ .map(|img| ExtractedImage {+ id: img.id.clone(),+ name: img.name.clone(),+ path: img.path.clone(),+ page: img.page,+ bbox: ImageRect {+ x: img.bbox.x,+ y: img.bbox.y,+ width: img.bbox.width,+ height: img.bbox.height,+ },+ width: img.width,+ height: img.height,+ rotation: img.rotation,+ format: img.format.clone(),+ duplicate_of: img.duplicate_of.clone(),+ bytes: img.bytes.as_slice().to_vec(),})+ .collect();++ ParseResult {+ total_pages: result.total_pages,+ pages,+ text: result.text.clone(),+ images,+ image_error_count: result.image_error_count,+ form_type: result.form_type,+ creator: result.creator.clone(),+ producer: result.producer.clone(),+ doc_meta: result.doc_meta.as_ref().map(DocumentMetadata::from),+ xfa_packets: result.xfa_packets.as_ref().map(|packets| {+ packets+ .iter()+ .map(|packet| XfaPacket {+ index: packet.index,+ name: packet.name.clone(),+ content_length: packet.content_length,+ content: packet.content.clone(),+ })+ .collect()+ }),}+}+#[wasm_bindgen]+impl LiteParse {/// Determine per-page complexity for the given PDF bytes. Returns/// `Promise<PageComplexityStats[]>` — a cheap pre-OCR check with per-page/// signals and a `needsOcr` verdict.@@ -1086,6 +1099,83 @@ impl LiteParse {Ok(stats.iter().map(PageComplexityStats::from_rust).collect())}++ /// Open PDF bytes for bounded-memory batch parsing. Returns+ /// `Promise<ParseSession>`.+ ///+ /// Yields `batchSize` pages at a time (default 25), which bounds both the+ /// Rust-side result and the JS objects built from it — the wasm heap has a+ /// hard ceiling, so a large document parsed whole can exhaust it.+ ///+ /// Cross-page passes (repeated header/footer removal, image deduplication)+ /// see only the pages in their own batch, so output can differ from a+ /// whole-document `parse()`.+ pub async fn open(+ &self,+ data: Vec<u8>,+ batch_size: Option<usize>,+ ) -> Result<ParseSession, JsError> {+ let batch_size = batch_size.unwrap_or(liteparse::DEFAULT_PAGE_BATCH_SIZE);+ let session = self+ .inner+ .open(PdfInput::Bytes(data), batch_size)+ .await+ .map_err(|e| JsError::new(&format!("open failed: {}", e)))?;++ Ok(ParseSession {+ extract_text_metadata: self.inner.config().extract_text_metadata,+ inner: session,+ })+ }+}++/// One batch of pages from a [`ParseSession`].+#[derive(Serialize, Tsify)]+#[tsify(into_wasm_abi)]+#[serde(rename_all = "camelCase")]+pub struct ParseBatch {+ /// First source page in this batch, 1-indexed.+ pub start_page: u32,+ /// Last source page in this batch, 1-indexed and inclusive.+ pub end_page: u32,+ /// The pages in `startPage..=endPage`, as an ordinary parse result.+ pub result: ParseResult,+}++/// A document opened once and parsed in bounded page batches.+///+/// Created by `LiteParse.open()`. Call `nextBatch()` until it returns+/// `undefined`.+#[wasm_bindgen]+pub struct ParseSession {+ inner: liteparse::ParseSession,+ extract_text_metadata: bool,+}++#[wasm_bindgen]+impl ParseSession {+ /// Total pages in the source document, before `maxPages` or batching.+ #[wasm_bindgen(getter, js_name = totalPages)]+ pub fn total_pages(&self) -> u32 {+ self.inner.total_pages()+ }++ /// Parse and return the next batch, or `undefined` once every page within+ /// `maxPages` has been yielded.+ #[wasm_bindgen(js_name = nextBatch)]+ pub async fn next_batch(&mut self) -> Result<Option<ParseBatch>, JsError> {+ let batch = self+ .inner+ .next_batch()+ .await+ .map_err(|e| JsError::new(&format!("batch parse failed: {}", e)))?;++ Ok(batch.map(|batch| ParseBatch {+ start_page: batch.start_page,+ end_page: batch.end_page,+ result: to_js_result(&batch.result, self.extract_text_metadata),+ }))+ }}#[derive(Serialize, Tsify)]diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rsindex a33db5e..972a5e1 100644--- a/crates/liteparse/src/config.rs+++ b/crates/liteparse/src/config.rs@@ -259,6 +259,12 @@ fn default_num_workers() -> usize {/// input.const MAX_TARGET_PAGES: u64 = 100_000;+/// Pages per batch when a caller of [`crate::parser::LiteParse::open`] does+/// not pick a size. Small enough to keep the materialized result bounded;+/// large enough that the per-batch document reopen stays modest (it costs+/// roughly 13% at this size on a 457-page document, ~4% at 50).+pub const DEFAULT_PAGE_BATCH_SIZE: usize = 25;+#[doc(hidden)]pub fn parse_target_pages(s: &str) -> Result<Vec<u32>, String> {let mut pages = Vec::new();diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rsindex 551c7ee..618ff39 100644--- a/crates/liteparse/src/lib.rs+++ b/crates/liteparse/src/lib.rs@@ -5,12 +5,12 @@//!// ── Public API re-exports ──────────────────────────────────────────────-pub use config::{LiteParseConfig, OutputFormat};+pub use config::{DEFAULT_PAGE_BATCH_SIZE, LiteParseConfig, OutputFormat};pub use error::LiteParseError;#[cfg(not(target_arch = "wasm32"))]pub use font_db_resolver::FontDbResolver;pub use glyph_resolver::{GLYPH_RESOLVER_FONT_SIZE, GlyphResolver};-pub use parser::{LiteParse, ParseResult, ScreenshotResult};+pub use parser::{LiteParse, ParseBatch, ParseResult, ParseSession, ScreenshotResult};pub use search::{SearchOptions, search_items};pub use types::{DocumentMetadata, ParsedPage, TextItem, WordBox};diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex a15f63a..7e20a4e 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -169,6 +169,33 @@ fn default_glyph_resolver() -> Option<std::sync::Arc<dyn crate::GlyphResolver>>None}+/// A document input already converted to PDF, if it needed converting.+///+/// Holds the [`conversion::PdfInputGuard`] so the temporary file produced for+/// a DOCX/XLSX/PPTX/image source stays alive for as long as the resolved input+/// is usable. Reusing one of these across several parses is what keeps batch+/// parsing from re-running LibreOffice for every batch.+pub(crate) struct ResolvedInput {+ input: PdfInput,+ #[cfg(not(target_arch = "wasm32"))]+ guard: conversion::PdfInputGuard,+}++impl ResolvedInput {+ /// True when `input` points at a temporary PDF we produced, so raw-file+ /// provenance describes the intermediate rather than the caller's document.+ fn is_converted(&self) -> bool {+ #[cfg(not(target_arch = "wasm32"))]+ {+ self.guard.is_converted()+ }+ #[cfg(target_arch = "wasm32")]+ {+ false+ }+ }+}+/// Main LiteParse orchestrator.////// ### Thread safety@@ -184,6 +211,7 @@ fn default_glyph_resolver() -> Option<std::sync::Arc<dyn crate::GlyphResolver>>/// safe but their PDFium portions run sequentially. The OCR pass and grid/// projection (which dominate runtime for OCR-heavy documents) run outside/// the lock and remain fully concurrent.+#[derive(Clone)]pub struct LiteParse {config: LiteParseConfig,/// Optional caller-provided OCR engine. When set, this overrides the@@ -362,6 +390,54 @@ impl LiteParse {/// Use `PdfInput::Path` for files on disk or `PdfInput::Bytes` for/// in-memory PDF data (e.g. from a network response or Node.js Buffer).pub async fn parse_input(&self, input: PdfInput) -> Result<ParseResult, LiteParseError> {+ self.validate_output_config()?;+ let resolved = self.resolve_input(input).await?;+ let target_pages = self.resolve_target_pages()?;+ self.parse_resolved(+ &resolved,+ target_pages.as_deref(),+ self.config.max_pages,+ None,+ )+ .await+ }++ /// Convert a non-PDF input to PDF (if needed) and return it alongside the+ /// guard that keeps any temporary file alive.+ ///+ /// Split out of [`LiteParse::parse_input`] so [`ParseSession`] can pay the+ /// conversion cost once and reuse the result for every page batch.+ async fn resolve_input(&self, input: PdfInput) -> Result<ResolvedInput, LiteParseError> {+ #[cfg(not(target_arch = "wasm32"))]+ {+ let (input, guard) =+ conversion::resolve_pdf_input(input, self.config.password.as_deref(), false)+ .await?;+ Ok(ResolvedInput { input, guard })+ }+ #[cfg(target_arch = "wasm32")]+ {+ Ok(ResolvedInput { input })+ }+ }++ /// Parse an already-resolved input over an explicit page selection.+ ///+ /// `target_pages` and `max_pages` are parameters rather than config reads+ /// so batch parsing can narrow the selection per batch.+ ///+ /// `outline` lets a caller that already walked the bookmark tree supply it+ /// instead of paying for it again. The walk resolves a page destination per+ /// entry, which costs several times more than opening the document, so a+ /// batch parse that recomputed it per batch would spend most of its+ /// overhead there.+ async fn parse_resolved(+ &self,+ resolved: &ResolvedInput,+ target_pages: Option<&[u32]>,+ max_pages: usize,+ outline: Option<Vec<OutlineTarget>>,+ ) -> Result<ParseResult, LiteParseError> {let log = |msg: &str| {if !self.config.quiet {eprintln!("{}", msg);@@ -370,24 +446,11 @@ impl LiteParse {let t0 = web_time::Instant::now();- self.validate_output_config()?;-- #[cfg(not(target_arch = "wasm32"))]- let (validated_input, _guard) =- conversion::resolve_pdf_input(input, self.config.password.as_deref(), false).await?;-// Provenance facts describe the file on disk, so they are meaningless// for a PDF we generated ourselves from a DOCX/XLSX/image.- #[cfg(not(target_arch = "wasm32"))]- let want_doc_meta = self.config.extract_document_metadata && !_guard.is_converted();- #[cfg(target_arch = "wasm32")]- let want_doc_meta = self.config.extract_document_metadata;+ let want_doc_meta = self.config.extract_document_metadata && !resolved.is_converted();- #[cfg(target_arch = "wasm32")]- let validated_input = input;-- // Determine which pages to extract- let target_pages = self.resolve_target_pages()?;+ let validated_input = &resolved.input;// Extract text (and pre-render OCR pages in one PDF load when OCR is on).// The PDFium lock is acquired for this entire critical section and@@ -462,17 +525,13 @@ impl LiteParse {.config.extract_form_fields.then(|| {- crate::acroform_repair::repair_orphaned_widgets(- &lib,- &validated_input,- password,- )+ crate::acroform_repair::repair_orphaned_widgets(&lib, validated_input, password)}).flatten();#[cfg(not(target_arch = "wasm32"))]- let document_input = repaired_input.as_ref().unwrap_or(&validated_input);+ let document_input = repaired_input.as_ref().unwrap_or(validated_input);#[cfg(target_arch = "wasm32")]- let document_input = &validated_input;+ let document_input = validated_input;let document = extract::load_document_from_input(&lib, document_input, password)?;let total_pages = document.page_count().max(0) as u32;let form_type = self@@ -487,11 +546,11 @@ impl LiteParse {#[cfg(not(target_arch = "wasm32"))]if repaired_input.is_some()&& let Ok(source) =- extract::load_document_from_input(&lib, &validated_input, password)+ extract::load_document_from_input(&lib, validated_input, password){- return crate::document_metadata::extract(&validated_input, &source);+ return crate::document_metadata::extract(validated_input, &source);}- crate::document_metadata::extract(&validated_input, &document)+ crate::document_metadata::extract(validated_input, &document)});let xfa_packets = self.config.extract_xfa_packets.then(|| {document@@ -510,11 +569,11 @@ impl LiteParse {}).collect::<Vec<_>>()});- let outline = extract::extract_outline(&document);+ let outline = outline.unwrap_or_else(|| extract::extract_outline(&document));let extracted = extract::extract_pages_and_images(&document,- target_pages.as_deref(),- self.config.max_pages,+ target_pages,+ max_pages,self.config.extract_links&& self.config.output_format == crate::config::OutputFormat::Markdown,self.glyph_resolver.as_deref(),@@ -816,6 +875,139 @@ impl LiteParse {pub fn config(&self) -> &LiteParseConfig {&self.config}++ /// Open a document for bounded-memory batch parsing.+ ///+ /// Converts a non-PDF source once and returns a [`ParseSession`] that+ /// yields `batch_size` pages at a time. Each batch is an ordinary+ /// [`ParseResult`], so a caller that drops one before requesting the next+ /// never holds more than one batch of pages in memory.+ ///+ /// `batch_size` is an argument rather than a config field because it only+ /// means anything on this entry point — see+ /// [`crate::config::DEFAULT_PAGE_BATCH_SIZE`] for a reasonable value.+ ///+ /// Prefer [`LiteParse::parse_input`] unless the document is large enough+ /// that the materialized result is the problem: cross-page passes see only+ /// the pages in their own batch, so repeated header/footer removal and+ /// image deduplication are batch-local and the output can differ from a+ /// whole-document parse.+ ///+ /// Returns an error if `target_pages` is configured — an explicit page+ /// selection and generated batch ranges would be ambiguous together.+ pub async fn open(+ &self,+ input: PdfInput,+ batch_size: usize,+ ) -> Result<ParseSession, LiteParseError> {+ self.validate_output_config()?;+ if self.config.target_pages.is_some() {+ return Err(LiteParseError::Config(+ "batch parsing cannot be combined with target_pages".to_string(),+ ));+ }+ if batch_size == 0 {+ return Err(LiteParseError::Config(+ "batch size must be at least 1".to_string(),+ ));+ }++ let input = self.resolve_input(input).await?;+ // One cheap open (a few ms even for a 100 MB file — PDFium maps the+ // file and parses the xref rather than reading it) so the caller knows+ // the page count before the first batch is parsed, and so the+ // document-level bookmark walk is paid once instead of per batch.+ let (total_pages, outline) = {+ let lib = Library::init();+ let document = extract::load_document_from_input(+ &lib,+ &input.input,+ self.config.password.as_deref(),+ )?;+ (+ document.page_count().max(0) as u32,+ extract::extract_outline(&document),+ )+ };++ Ok(ParseSession {+ page_limit: total_pages.min(self.config.max_pages.min(u32::MAX as usize) as u32),+ parser: self.clone(),+ input,+ total_pages,+ outline,+ next_page: 1,+ batch_size,+ })+ }+}++/// A document opened once and parsed in bounded page batches.+///+/// Created by [`LiteParse::open`]. The converted-PDF temporary file (for+/// non-PDF sources) lives as long as the session, so conversion is paid once+/// no matter how many batches are consumed. The PDFium document itself is+/// reopened per batch, which measures at a few percent of a batch's extraction+/// cost and keeps the process-global PDFium lock free between batches.+pub struct ParseSession {+ parser: LiteParse,+ input: ResolvedInput,+ total_pages: u32,+ /// Walked once at open. Document-level, so every batch reports the same+ /// outline, and re-walking it per batch would dominate batching overhead.+ outline: Vec<OutlineTarget>,+ /// Last source page this session will parse: `min(total_pages, max_pages)`.+ page_limit: u32,+ /// Next source page to parse, 1-based.+ next_page: u32,+ batch_size: usize,+}++/// One batch of pages from a [`ParseSession`].+pub struct ParseBatch {+ /// First source page in this batch, 1-based.+ pub start_page: u32,+ /// Last source page in this batch, 1-based and inclusive.+ pub end_page: u32,+ /// The pages in `start_page..=end_page`, parsed as an ordinary result.+ pub result: ParseResult,+}++impl ParseSession {+ /// Total pages in the source document, before `max_pages` or batching.+ pub fn total_pages(&self) -> u32 {+ self.total_pages+ }++ /// Parse and return the next batch, or `None` once every page within+ /// `max_pages` has been yielded.+ pub async fn next_batch(&mut self) -> Result<Option<ParseBatch>, LiteParseError> {+ if self.next_page > self.page_limit {+ return Ok(None);+ }+ let start_page = self.next_page;+ let end_page = start_page+ .saturating_add(self.batch_size.min(u32::MAX as usize) as u32 - 1)+ .min(self.page_limit);+ let targets: Vec<u32> = (start_page..=end_page).collect();++ let result = self+ .parser+ .parse_resolved(+ &self.input,+ Some(&targets),+ targets.len(),+ Some(self.outline.clone()),+ )+ .await?;++ self.next_page = end_page.saturating_add(1);+ Ok(Some(ParseBatch {+ start_page,+ end_page,+ result,+ }))+ }}#[cfg(test)]diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rsindex 5ea3a86..f0eff78 100644--- a/crates/liteparse/tests/integration_test.rs+++ b/crates/liteparse/tests/integration_test.rs@@ -114,6 +114,136 @@ async fn test_total_pages_precedes_target_page_filtering() {assert_eq!(parsed.pages[0].page_number, 2);}+/// Batching must not change what any individual page parses to — only how many+/// pages are materialized at once.+#[tokio::test]+#[serial]+async fn test_batch_parse_matches_whole_document() {+ let config = || LiteParseConfig {+ ocr_enabled: false,+ quiet: true,+ ..LiteParseConfig::default()+ };+ let path = "../../integration_tests_data/filled_acroform.pdf";++ let whole = LiteParse::new(config())+ .parse(path)+ .await+ .expect("whole-document parse should succeed");++ let mut session = LiteParse::new(config())+ .open(PdfInput::Path(path.to_string()), 2)+ .await+ .expect("should open a session");+ assert_eq!(session.total_pages(), whole.total_pages);++ let mut batches = Vec::new();+ while let Some(batch) = session.next_batch().await.expect("batch should parse") {+ batches.push(batch);+ }++ // 3 pages at 2 per batch: [1-2], [3-3].+ assert_eq!(batches.len(), 2);+ assert_eq!((batches[0].start_page, batches[0].end_page), (1, 2));+ assert_eq!((batches[1].start_page, batches[1].end_page), (3, 3));++ let batched: Vec<_> = batches.iter().flat_map(|b| b.result.pages.iter()).collect();+ assert_eq!(batched.len(), whole.pages.len());+ for (got, want) in batched.iter().zip(&whole.pages) {+ assert_eq!(got.page_number, want.page_number);+ assert_eq!(got.text, want.text);+ }+ for batch in &batches {+ assert_eq!(batch.result.total_pages, whole.total_pages);+ }+}++/// `max_pages` bounds the session the same way it bounds a whole parse, and a+/// batch size larger than the document collapses to a single batch.+#[tokio::test]+#[serial]+async fn test_batch_parse_respects_max_pages() {+ let mut session = LiteParse::new(LiteParseConfig {+ ocr_enabled: false,+ quiet: true,+ max_pages: 2,+ ..LiteParseConfig::default()+ })+ .open(+ PdfInput::Path("../../integration_tests_data/filled_acroform.pdf".to_string()),+ 100,+ )+ .await+ .expect("should open a session");++ let first = session+ .next_batch()+ .await+ .expect("batch should parse")+ .expect("a first batch");+ assert_eq!(session.total_pages(), 3, "reports the source page count");+ assert_eq!((first.start_page, first.end_page), (1, 2));+ assert_eq!(first.result.pages.len(), 2);+ assert!(+ session.next_batch().await.expect("clean end").is_none(),+ "max_pages should end the session before page 3"+ );+}++/// An explicit page selection and generated batch ranges are ambiguous+/// together, so the combination is rejected up front.+#[tokio::test]+#[serial]+async fn test_batch_parse_rejects_target_pages() {+ let opened = LiteParse::new(LiteParseConfig {+ ocr_enabled: false,+ quiet: true,+ target_pages: Some("1-2".into()),+ ..LiteParseConfig::default()+ })+ .open(+ PdfInput::Path("../../integration_tests_data/filled_acroform.pdf".to_string()),+ 25,+ )+ .await;+ assert!(+ opened.is_err(),+ "target_pages + batching should be rejected"+ );+}++/// A non-PDF source is converted once when the session opens, not once per+/// batch — the whole reason batching lives in core rather than in a binding.+#[tokio::test]+#[serial]+async fn test_batch_parse_converts_office_source_once() {+ let env_var = std::env::var("SKIP_INTEGRATION_TESTS");+ if let Ok(v) = env_var+ && v == "yes"+ {+ return;+ }+ let mut session = LiteParse::new(LiteParseConfig {+ ocr_enabled: false,+ quiet: true,+ ..LiteParseConfig::default()+ })+ .open(+ PdfInput::Path("../../integration_tests_data/sample3.doc".to_string()),+ 1,+ )+ .await+ .expect("should convert and open a .doc");++ // The converted temporary PDF is owned by the session, so every batch+ // after the first resolves against a file that no longer needs LibreOffice.+ let mut pages = 0;+ while let Some(batch) = session.next_batch().await.expect("batch should parse") {+ pages += batch.result.pages.len();+ }+ assert_eq!(pages, 2);+}+#[tokio::test]#[serial]async fn test_parse_bytes_office_integration() {diff --git a/packages/node/README.md b/packages/node/README.mdindex 4b376a8..da2cc48 100644--- a/packages/node/README.md+++ b/packages/node/README.md@@ -38,8 +38,14 @@ for await (const batch of parser.parseBatches('large.pdf', { batchSize: 20 })) {}```-The document is reopened for each batch. Header/footer detection and image-deduplication are therefore batch-local.+Each batch is an ordinary parse result covering `batch.startPage` through+`batch.endPage`, and becomes collectible as soon as you advance the iterator.+A non-PDF source is converted once, not once per batch.++Cross-page passes only see the pages in their own batch, so repeated+header/footer removal and image deduplication are batch-local and the output+can differ from `parse()`. Prefer `parse()` unless the size of the+materialized result is the problem.## Markdown Outputdiff --git a/packages/node/native.d.ts b/packages/node/native.d.tsindex a37cbcd..dd0e4e3 100644--- a/packages/node/native.d.ts+++ b/packages/node/native.d.ts@@ -51,6 +51,11 @@ export interface JsLiteParseConfig {* (default true). Set false for plain anchor text.*/extractLinks?: boolean+ /**+ * Keep running headers/footers in markdown output instead of stripping+ * repeated page-band lines and page chrome (default false).+ */+ keepHeadersFooters?: boolean/** Extract all PDF annotations as page-scoped structured data. */extractAnnotations?: boolean/** Extract AcroForm widget fields and values. */@@ -62,6 +67,11 @@ export interface JsLiteParseConfig {* `ParseResult.xfaPackets`. Default false.*/extractXfaPackets?: boolean+ /**+ * Collect document provenance metadata into `ParseResult.docMeta`.+ * Default false: it streams the whole source file once. Absent for+ * inputs converted from a non-PDF format.+ */extractDocumentMetadata?: boolean/*** Emit each page's `contentBounds` (union bbox of top-level content@@ -73,7 +83,10 @@ export interface JsLiteParseConfig {* them to each screenshot result. Default false.*/detectScreenshotRects?: boolean- /** Draw AcroForm field appearances into rendered rasters (runs document open/JS actions). Default false. */+ /**+ * Draw AcroForm field appearances into rendered rasters (screenshots and+ * OCR inputs). Runs the document's open/JS actions. Default false.+ */renderFormFields?: boolean/*** Whether a systemic OCR failure aborts the whole parse (default true).@@ -156,6 +169,7 @@ export interface JsTextItem {charCodes?: Array<number>/** True when the trailing source space was synthesized by PDFium. */trailingSpaceGenerated?: boolean+ /** OCR confidence score (0.0-1.0). Undefined for native PDF text. */confidence?: number/** Rotation in degrees (viewport space). Defaults to 0 when omitted. */rotation?: number@@ -330,6 +344,15 @@ export interface JsParseResult {/** Raw XFA packets; present only when `extractXfaPackets` is enabled. */xfaPackets?: Array<JsXfaPacket>}+/** One batch of pages from a `ParseSession`. */+export interface JsParseBatch {+ /** First source page in this batch, 1-indexed. */+ startPage: number+ /** Last source page in this batch, 1-indexed and inclusive. */+ endPage: number+ /** The pages in `startPage..=endPage`, as an ordinary parse result. */+ result: JsParseResult+}export interface JsDocumentMetadata {creationDate?: stringmodDate?: string@@ -342,6 +365,7 @@ export interface JsDocumentMetadata {trailerIdPairDiffers?: booleanrawFileSize?: numberxmp?: string+ /** True when the catalog's XMP stream exceeded the 64 KiB cap. */xmpTruncated?: booleansignatureCount?: numbersignatureByteRangeReachesEof?: boolean@@ -415,9 +439,29 @@ export interface JsPageComplexityStats {textLength: numbertextCoverage: numberhasSubstantialImages: boolean+ /**+ * Number of counted raster images — inline figures only; full-page+ * backgrounds are excluded (see `fullPageImage`).+ */imageBlockCount: number+ /**+ * Summed image-bbox area over page area, clamped to 1. Counts inline+ * figures only: a full-page scan raster contributes 0 here — check+ * `fullPageImage` for that.+ */imageCoverage: number+ /**+ * Largest single counted image's area over page area, clamped to 1. Same+ * exclusion as `imageCoverage`: a full-page raster contributes 0.+ */largestImageCoverage: number+ /**+ * A single raster covering ≥90% of the page is present. Such full-page+ * backgrounds are excluded from `imageCoverage`/`largestImageCoverage`+ * (they're not inline figures), so this flag is the only signal that+ * distinguishes a scan from a genuinely blank page — both otherwise+ * report no text and no counted images.+ */fullPageImage: booleanuncoveredVectorArea?: numberisGarbled: boolean@@ -437,6 +481,15 @@ export declare class LiteParse {constructor(config?: JsLiteParseConfig | undefined | null)/** Parse a document. Accepts a file path (string) or raw PDF bytes (Buffer). */parse(input: string | Buffer): Promise<JsParseResult>+ /**+ * Open a document for bounded-memory batch parsing.+ *+ * Converts a non-PDF source once, then yields `batchSize` pages at a time+ * via `nextBatch()` (default 25). Cross-page passes (repeated+ * header/footer removal, image deduplication) see only the pages in their+ * own batch, so output can differ from a whole-document `parse()`.+ */+ open(input: string | Buffer, batchSize?: number | undefined | null): Promise<ParseSession>/*** Parse from pre-extracted pages, skipping PDFium text extraction.*@@ -464,3 +517,19 @@ export declare class LiteParse {/** Get the current configuration. */get config(): JsLiteParseConfig}+/**+ * A document opened once and parsed in bounded page batches.+ *+ * Created by `LiteParse.open()`. The converted-PDF temporary file for a+ * non-PDF source lives as long as the session, so conversion is paid once no+ * matter how many batches are consumed.+ */+export declare class ParseSession {+ /** Total pages in the source document, before `maxPages` or batching. */+ get totalPages(): number+ /**+ * Parse and return the next batch, or `null` once every page within+ * `maxPages` has been yielded.+ */+ nextBatch(): Promise<JsParseBatch | null>+}diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.tsindex e854f1b..33bd2a3 100644--- a/packages/node/src/lib.ts+++ b/packages/node/src/lib.ts@@ -371,21 +371,21 @@ export interface ParseResult {xfaPackets?: XfaPacket[];}+export interface ParseBatchOptions {+ /** Pages materialized in one batch. Default: 25. */+ batchSize?: number;+}+export interface ParseBatch {/** First source page in this batch (1-indexed). */startPage: number;- /** Last source page requested for this batch (1-indexed). */+ /** Last source page in this batch (1-indexed, inclusive). */endPage: number;/** Total source-document pages, before the parser's `maxPages` cap. */totalPages: number;result: ParseResult;}-export interface ParseBatchOptions {- /** Maximum pages materialized in one result. Default: 25. */- batchSize?: number;-}-/** Provenance and tamper-analysis facts extracted from the source PDF. */export interface DocumentMetadata {creationDate?: string;@@ -624,77 +624,44 @@ export class LiteParse {const nativeInput =typeof input === "string" ? input : Buffer.from(input);const result: NativeParseResult = await this._native.parse(nativeInput);- return {- totalPages: result.totalPages,- pages: result.pages.map(toPage),- text: result.text,- images: (result.images ?? []).map(toImage),- imageErrorCount: result.imageErrorCount ?? 0,- formType: result.formType,- creator: result.creator,- producer: result.producer,- docMeta: result.docMeta,- xfaPackets: result.xfaPackets,- };+ return toParseResult(result);}/**- * Parse a document in bounded-memory page batches.+ * Parse a document in bounded-memory page batches of `batchSize` pages.+ *+ * Each yielded result is independent and becomes collectible once the caller+ * advances the iterator, so a consumer that does not retain batches never+ * holds more than one batch of pages in memory. A non-PDF source is+ * converted once when the iterator starts, not once per batch.*- * Each yielded result is independent and becomes collectible when the- * caller advances the iterator. The document is reopened for each batch;- * this trades a small amount of repeated setup for a bounded JS object- * graph on documents with many text items. Do not retain prior results if- * bounded memory is required.+ * Cross-page passes see only the pages in their own batch, so repeated+ * header/footer removal and image deduplication are batch-local and the+ * output can differ from `parse()`. Prefer `parse()` unless the size of the+ * materialized result is the problem.*- * Batch-local layout operations (including repeated header/footer removal- * and image deduplication) do not see pages outside their batch. A parser- * configured with `targetPages` is rejected because its selection would be- * ambiguous with the ranges generated here.+ * Throws if the parser is configured with `targetPages` — an explicit page+ * selection and generated batch ranges are ambiguous together.*/async *parseBatches(input: LiteParseInput,options: ParseBatchOptions = {},): AsyncGenerator<ParseBatch> {- if (this._config.targetPages != null) {- throw new Error(- "parseBatches cannot be used when targetPages is configured",- );- }- const batchSize = options.batchSize ?? 25;- if (- !Number.isSafeInteger(batchSize) ||- batchSize <= 0 ||- batchSize > 100_000- ) {- throw new RangeError("batchSize must be an integer between 1 and 100000");- }+ const nativeInput = typeof input === "string" ? input : Buffer.from(input);+ const session = await this._native.open(nativeInput, options.batchSize);+ const totalPages = session.totalPages;- let startPage = 1;- let pageLimit = this._config.maxPages;- while (startPage <= pageLimit) {- const requestedEndPage = Math.min(- startPage + batchSize - 1,- pageLimit,- );- const batchParser = new LiteParse({- ...this._config,- maxPages: batchSize,- targetPages: `${startPage}-${requestedEndPage}`,- });- const result = await batchParser.parse(input);- if (!Number.isSafeInteger(result.totalPages)) {- throw new Error(- "parseBatches requires a native LiteParse binary that exposes totalPages",- );- }- pageLimit = Math.min(result.totalPages, this._config.maxPages);- if (result.pages.length === 0) {+ for (;;) {+ const batch = await session.nextBatch();+ if (batch == null) {return;}- const endPage = Math.min(requestedEndPage, pageLimit);- yield { startPage, endPage, totalPages: result.totalPages, result };- startPage = endPage + 1;+ yield {+ startPage: batch.startPage,+ endPage: batch.endPage,+ totalPages,+ result: toParseResult(batch.result),+ };}}@@ -791,6 +758,21 @@ function toComplexity(s: NativePageComplexityStats): PageComplexityStats {};}+function toParseResult(result: NativeParseResult): ParseResult {+ return {+ totalPages: result.totalPages,+ pages: result.pages.map(toPage),+ text: result.text,+ images: (result.images ?? []).map(toImage),+ imageErrorCount: result.imageErrorCount ?? 0,+ formType: result.formType,+ creator: result.creator,+ producer: result.producer,+ docMeta: result.docMeta,+ xfaPackets: result.xfaPackets,+ };+}+function toPage(p: NativeParsedPage): ParsedPage {return {pageNum: p.pageNum,diff --git a/packages/node/src/native.ts b/packages/node/src/native.tsindex fb3108c..ea5f602 100644--- a/packages/node/src/native.ts+++ b/packages/node/src/native.ts@@ -316,8 +316,23 @@ export interface NativePageComplexityStats {layout?: NativeLayoutComplexityStats;}+export interface NativeParseBatch {+ startPage: number;+ endPage: number;+ result: NativeParseResult;+}++export interface NativeParseSession {+ nextBatch(): Promise<NativeParseBatch | null>;+ readonly totalPages: number;+}+export interface LiteParseNative {parse(input: string | Buffer): Promise<NativeParseResult>;+ open(+ input: string | Buffer,+ batchSize?: number,+ ): Promise<NativeParseSession>;parsePages(pages: NativePageInput[]): NativeParseResult;isComplex(input: string | Buffer): Promise<NativePageComplexityStats[]>;screenshot(diff --git a/packages/python/liteparse/__init__.py b/packages/python/liteparse/__init__.pyindex ef7adc6..5ba62d1 100644--- a/packages/python/liteparse/__init__.py+++ b/packages/python/liteparse/__init__.py@@ -13,6 +13,7 @@ from .types import (LiteParseConfig,PageComplexityStats,ParseResult,+ ParseBatch,DocumentMetadata,XfaPacket,ParsedPage,@@ -39,6 +40,7 @@ __all__ = ["StructureTreeElement","LiteParseConfig","ParseResult",+ "ParseBatch","DocumentMetadata","XfaPacket","ParsedPage",diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex df64e90..43b4982 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -1,7 +1,7 @@"""LiteParse Python wrapper - native Rust bindings via PyO3."""from pathlib import Path-from typing import Any, Dict, List, Optional, Tuple, Union+from typing import Any, Dict, Iterator, List, Optional, Tuple, Unionfrom liteparse._liteparse import LiteParse as _NativeLiteParsefrom liteparse._liteparse import search_items as _native_search_items@@ -18,6 +18,7 @@ from .types import (LiteParseConfig,PageComplexityStats,ParsedPage,+ ParseBatch,ParseError,ParseResult,DocumentMetadata,@@ -586,6 +587,65 @@ class LiteParse:except Exception as e:raise ParseError(str(e)) from e+ def parse_batches(+ self,+ file_data: Union[str, Path, bytes],+ batch_size: Optional[int] = None,+ ) -> Iterator[ParseBatch]:+ """+ Parse a document in bounded-memory page batches.++ Each yielded batch is an ordinary :class:`ParseResult` covering+ ``batch.start_page`` through ``batch.end_page``, and becomes+ collectible as soon as you advance the iterator — so a loop that does+ not retain batches never holds more than one batch of pages in memory.+ A non-PDF source is converted once, not once per batch.++ Cross-page passes see only the pages in their own batch, so repeated+ header/footer removal and image deduplication are batch-local and the+ output can differ from :meth:`parse`. Prefer :meth:`parse` unless the+ size of the materialized result is the problem.++ Args:+ file_data: Path to the document file, or raw PDF bytes.+ batch_size: Pages materialized per batch (default 25).++ Yields:+ ParseBatch for each page range, in document order.++ Raises:+ ParseError: If parsing fails, or if the parser was constructed+ with ``target_pages`` (ambiguous with generated batch ranges).+ FileNotFoundError: If the file doesn't exist.+ """+ try:+ if isinstance(file_data, bytes):+ session = self._native.open_bytes(file_data, batch_size)+ else:+ file_path = Path(file_data)+ if not file_path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")+ session = self._native.open(str(file_path.absolute()), batch_size)+ except FileNotFoundError:+ raise+ except Exception as e:+ raise ParseError(str(e)) from e++ total_pages = session.total_pages+ while True:+ try:+ batch = session.next_batch()+ except Exception as e:+ raise ParseError(str(e)) from e+ if batch is None:+ return+ yield ParseBatch(+ start_page=batch.start_page,+ end_page=batch.end_page,+ total_pages=total_pages,+ result=_convert_native_result(batch.result),+ )+def is_complex(self,file_data: Union[str, Path, bytes],diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.pyindex 1dc5746..10eff2c 100644--- a/packages/python/liteparse/types.py+++ b/packages/python/liteparse/types.py@@ -265,6 +265,19 @@ class ParseResult:#: Raw XFA packets; present only when ``extract_xfa_packets=True``.xfa_packets: Optional[List[XfaPacket]] = None++@dataclass+class ParseBatch:+ """One batch of pages from :meth:`LiteParse.parse_batches`."""+ #: First source page in this batch (1-indexed).+ start_page: int+ #: Last source page in this batch (1-indexed, inclusive).+ end_page: int+ #: Total source-document pages, before the parser's ``max_pages`` cap.+ total_pages: int+ #: The pages in ``start_page..end_page``, as an ordinary parse result.+ result: ParseResult+@propertydef num_pages(self) -> int:return len(self.pages)diff --git a/packages/python/uv.lock b/packages/python/uv.lockindex b5308fa..215882b 100644--- a/packages/python/uv.lock+++ b/packages/python/uv.lock@@ -128,7 +128,7 @@ wheels = [[[package]]name = "liteparse"-version = "2.0.5"+version = "2.11.1"source = { editable = "." }[package.optional-dependencies]