Skip to content

A fast, helpful, and open-source document parser

add back num-workers

Logan Markewiche1c3e5e7a3f0
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 058563e..9955dd6 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -33,6 +33,8 @@ pub struct JsLiteParseConfig {
pub password: Option<String>,
/// Suppress progress output.
pub quiet: Option<bool>,
+ /// Number of concurrent OCR workers (default: CPU cores - 1).
+ pub num_workers: Option<u32>,
}
impl JsLiteParseConfig {
@@ -74,6 +76,9 @@ impl JsLiteParseConfig {
if let Some(v) = self.quiet {
cfg.quiet = v;
}
+ if let Some(v) = self.num_workers {
+ cfg.num_workers = v as usize;
+ }
cfg
}
@@ -93,6 +98,7 @@ impl JsLiteParseConfig {
preserve_very_small_text: Some(cfg.preserve_very_small_text),
password: cfg.password.clone(),
quiet: Some(cfg.quiet),
+ num_workers: Some(cfg.num_workers as u32),
}
}
}
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index 2d329bd..192d87d 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -58,6 +58,8 @@ struct ParseCommand {
password: Option<String>,
#[arg(short, long)]
quiet: bool,
+ #[arg(long)]
+ num_workers: Option<usize>,
}
#[derive(Args, Debug)]
@@ -101,6 +103,8 @@ struct BatchParseCommand {
password: Option<String>,
#[arg(short, long)]
quiet: bool,
+ #[arg(long)]
+ num_workers: Option<usize>,
}
#[derive(Args, Debug)]
@@ -127,7 +131,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
match cli.command {
Commands::Parse(cmd) => {
let format = parse_output_format(&cmd.format)?;
- let config = LiteParseConfig {
+ let mut config = LiteParseConfig {
ocr_language: cmd.ocr_language,
ocr_enabled: !cmd.no_ocr,
tessdata_path: cmd.tessdata_path,
@@ -139,7 +143,11 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
password: cmd.password,
quiet: cmd.quiet,
ocr_server_url: cmd.ocr_server_url,
+ ..Default::default()
};
+ if let Some(n) = cmd.num_workers {
+ config.num_workers = n;
+ }
let lp = LiteParse::new(config);
let result = rt.block_on(lp.parse(&cmd.file))?;
let formatted = match lp.config().output_format {
@@ -200,7 +208,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
}
});
- let config = LiteParseConfig {
+ let mut config = LiteParseConfig {
ocr_language: cmd.ocr_language,
ocr_enabled: !cmd.no_ocr,
tessdata_path: cmd.tessdata_path,
@@ -212,7 +220,11 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
password: cmd.password,
quiet: cmd.quiet,
ocr_server_url: cmd.ocr_server_url,
+ ..Default::default()
};
+ if let Some(n) = cmd.num_workers {
+ config.num_workers = n;
+ }
let lp = LiteParse::new(config);
let out_ext = if format == OutputFormat::Json {
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index c6696e3..873134a 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -188,6 +188,7 @@ impl LiteParse {
preserve_very_small_text = None,
password = None,
quiet = None,
+ num_workers = None,
))]
fn new(
ocr_language: Option<String>,
@@ -201,6 +202,7 @@ impl LiteParse {
preserve_very_small_text: Option<bool>,
password: Option<String>,
quiet: Option<bool>,
+ num_workers: Option<usize>,
) -> PyResult<Self> {
let mut cfg = LiteParseConfig::default();
if let Some(v) = ocr_language {
@@ -239,6 +241,9 @@ impl LiteParse {
if let Some(v) = quiet {
cfg.quiet = v;
}
+ if let Some(v) = num_workers {
+ cfg.num_workers = v;
+ }
let inner = liteparse::parser::LiteParse::new(cfg.clone());
let runtime = tokio::runtime::Runtime::new()
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index bb4137f..a134e11 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -92,6 +92,7 @@ impl JsLiteParseConfig {
if let Some(v) = self.quiet {
cfg.quiet = v;
}
+ cfg.num_workers = 1;
Ok(cfg)
}
@@ -186,8 +187,12 @@ impl OcrEngine for JsOcrEngine {
width: u32,
height: u32,
options: &'b OcrOptions,
- ) -> Pin<Box<dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error>>> + '_>>
- {
+ ) -> Pin<
+ Box<
+ dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>>
+ + '_,
+ >,
+ > {
// Copy bytes into a JS Uint8Array up-front (must happen on the
// current thread anyway in wasm).
let arr = Uint8Array::new_with_length(image_data.len() as u32);
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index fb35a15..82287ce 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -25,6 +25,8 @@ pub struct LiteParseConfig {
pub password: Option<String>,
/// Suppress progress output.
pub quiet: bool,
+ /// Number of concurrent OCR workers. Defaults to (number of CPU cores - 1), minimum 1.
+ pub num_workers: usize,
}
/// Supported output formats.
@@ -49,10 +51,18 @@ impl Default for LiteParseConfig {
preserve_very_small_text: false,
password: None,
quiet: false,
+ num_workers: default_num_workers(),
}
}
}
+/// Returns the default number of OCR workers: CPU cores - 1, minimum 1.
+fn default_num_workers() -> usize {
+ std::thread::available_parallelism()
+ .map(|n| n.get().saturating_sub(1).max(1))
+ .unwrap_or(1)
+}
+
/// Parse a target pages string like "1-5,10,15-20" into a sorted list of page numbers.
pub fn parse_target_pages(s: &str) -> Result<Vec<u32>, String> {
let mut pages = Vec::new();
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index d131e59..a7b8a99 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -83,6 +83,10 @@ struct ParseCommand {
/// Suppress progress output
#[arg(short, long)]
quiet: bool,
+
+ /// Number of concurrent OCR workers (default: CPU cores - 1)
+ #[arg(long)]
+ num_workers: Option<usize>,
}
#[derive(Args, Debug)]
@@ -162,6 +166,10 @@ struct BatchParseCommand {
/// Suppress progress output
#[arg(short, long)]
quiet: bool,
+
+ /// Number of concurrent OCR workers (default: CPU cores - 1)
+ #[arg(long)]
+ num_workers: Option<usize>,
}
#[derive(Args, Debug)]
@@ -191,7 +199,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Commands::Parse(cmd) => {
let format = parse_output_format(&cmd.format)?;
- let config = LiteParseConfig {
+ let mut config = LiteParseConfig {
ocr_language: cmd.ocr_language,
ocr_enabled: !cmd.no_ocr,
tessdata_path: cmd.tessdata_path,
@@ -203,7 +211,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
password: cmd.password,
quiet: cmd.quiet,
ocr_server_url: cmd.ocr_server_url,
+ ..Default::default()
};
+ if let Some(n) = cmd.num_workers {
+ config.num_workers = n;
+ }
let lp = LiteParse::new(config);
let result = lp.parse(&cmd.file).await?;
@@ -271,7 +283,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
});
- let config = LiteParseConfig {
+ let mut config = LiteParseConfig {
ocr_language: cmd.ocr_language,
ocr_enabled: !cmd.no_ocr,
tessdata_path: cmd.tessdata_path,
@@ -283,7 +295,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
password: cmd.password,
quiet: cmd.quiet,
ocr_server_url: cmd.ocr_server_url,
+ ..Default::default()
};
+ if let Some(n) = cmd.num_workers {
+ config.num_workers = n;
+ }
let lp = LiteParse::new(config);
let out_ext = if format == OutputFormat::Json {
diff --git a/crates/liteparse/src/ocr/http_simple.rs b/crates/liteparse/src/ocr/http_simple.rs
index d44cea7..7368041 100644
--- a/crates/liteparse/src/ocr/http_simple.rs
+++ b/crates/liteparse/src/ocr/http_simple.rs
@@ -51,8 +51,13 @@ impl OcrEngine for HttpOcrEngine {
_width: u32,
_height: u32,
options: &'b OcrOptions,
- ) -> Pin<Box<dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error>>> + Send + '_>>
- {
+ ) -> Pin<
+ Box<
+ dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>>
+ + Send
+ + '_,
+ >,
+ > {
Box::pin(async move {
let client = Client::new();
let form = Form::new()
diff --git a/crates/liteparse/src/ocr/mod.rs b/crates/liteparse/src/ocr/mod.rs
index 687e3b9..3e280ee 100644
--- a/crates/liteparse/src/ocr/mod.rs
+++ b/crates/liteparse/src/ocr/mod.rs
@@ -33,7 +33,13 @@ pub trait OcrEngine: Send + Sync {
width: u32,
height: u32,
options: &'b OcrOptions,
- ) -> Pin<Box<dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error>>> + Send + '_>>;
+ ) -> Pin<
+ Box<
+ dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>>
+ + Send
+ + '_,
+ >,
+ >;
}
#[cfg(target_arch = "wasm32")]
@@ -45,7 +51,12 @@ pub trait OcrEngine {
width: u32,
height: u32,
options: &'b OcrOptions,
- ) -> Pin<Box<dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error>>> + '_>>;
+ ) -> Pin<
+ Box<
+ dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>>
+ + '_,
+ >,
+ >;
}
#[cfg(test)]
@@ -65,7 +76,10 @@ mod tests {
options: &'b OcrOptions,
) -> Pin<
Box<
- dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error>>> + Send + '_,
+ dyn Future<
+ Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>,
+ > + Send
+ + '_,
>,
> {
Box::pin(async move {
diff --git a/crates/liteparse/src/ocr/tesseract.rs b/crates/liteparse/src/ocr/tesseract.rs
index f33e464..dfcaff0 100644
--- a/crates/liteparse/src/ocr/tesseract.rs
+++ b/crates/liteparse/src/ocr/tesseract.rs
@@ -45,8 +45,13 @@ impl OcrEngine for TesseractOcrEngine {
width: u32,
height: u32,
options: &'b OcrOptions,
- ) -> Pin<Box<dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error>>> + Send + '_>>
- {
+ ) -> Pin<
+ Box<
+ dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>>
+ + Send
+ + '_,
+ >,
+ > {
Box::pin(async move {
let language = Self::normalize_language(&options.language);
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index ab300a4..b2455af 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -1,5 +1,7 @@
+use std::sync::Arc;
+
use crate::error::LiteParseError;
-use crate::ocr::{OcrEngine, OcrOptions};
+use crate::ocr::{OcrEngine, OcrOptions, OcrResult};
use crate::types::{Page, PdfInput, TextItem};
use image::{ImageBuffer, Rgba};
use pdfium::Library;
@@ -12,8 +14,9 @@ pub async fn ocr_and_merge_pages(
pages: &mut [Page],
pdf_path: &str,
dpi: f32,
- ocr_engine: &dyn OcrEngine,
+ ocr_engine: Arc<dyn OcrEngine>,
ocr_language: &str,
+ num_workers: usize,
) -> Result<(), LiteParseError> {
ocr_and_merge_pages_from_input(
pages,
@@ -21,18 +24,22 @@ pub async fn ocr_and_merge_pages(
dpi,
ocr_engine,
ocr_language,
+ num_workers,
)
.await
}
/// Run OCR on pages that need it and merge results into text_items.
/// Accepts a `PdfInput` for either file path or in-memory bytes.
+///
+/// `num_workers` controls how many pages are OCR'd concurrently.
pub async fn ocr_and_merge_pages_from_input(
pages: &mut [Page],
input: &PdfInput,
dpi: f32,
- ocr_engine: &dyn OcrEngine,
+ ocr_engine: Arc<dyn OcrEngine>,
ocr_language: &str,
+ num_workers: usize,
) -> Result<(), LiteParseError> {
// Phase 1: render all pages that need OCR. The pdfium `Document` holds raw
// pointers that are not `Send`, so we must not hold it across an `.await`.
@@ -62,11 +69,6 @@ pub async fn ocr_and_merge_pages_from_input(
continue;
}
- eprintln!(
- "[ocr] page {} needs OCR (text_length={}, has_images={})",
- page.page_number, text_length, has_images
- );
-
let bitmap = page_obj.render(dpi)?;
let width = bitmap.width() as u32;
let height = bitmap.height() as u32;
@@ -90,27 +92,47 @@ pub async fn ocr_and_merge_pages_from_input(
// `document` and `lib` are dropped here before any `.await`
};
- // Phase 2: run OCR (async) on rendered pages and merge results back.
+ // Phase 2: spawn OCR tasks onto the tokio runtime so they run on
+ // separate threads. A semaphore limits concurrency to `num_workers`.
+ let num_workers = num_workers.max(1);
+ let semaphore = Arc::new(tokio::sync::Semaphore::new(num_workers));
+ let mut handles = Vec::with_capacity(rendered.len());
+
+ let handle = tokio::runtime::Handle::current();
+
for r in rendered {
- let RenderedPage {
- idx,
- rgb_bytes,
- width,
- height,
- } = r;
- let page = &mut pages[idx];
+ let engine = ocr_engine.clone();
+ let sem = semaphore.clone();
+ let language = ocr_language.to_string();
+ let page_number = pages[r.idx].page_number;
+ let rt_handle = handle.clone();
+
+ handles.push((
+ r.idx,
+ page_number,
+ tokio::task::spawn_blocking(move || {
+ // Block this thread until a permit is available.
+ let _permit = rt_handle
+ .block_on(sem.acquire_owned())
+ .expect("semaphore closed");
+ let options = OcrOptions { language };
+ rt_handle.block_on(engine.recognize(&r.rgb_bytes, r.width, r.height, &options))
+ }),
+ ));
+ }
- let options = OcrOptions {
- language: ocr_language.to_string(),
- };
+ // Phase 3: collect results and merge into pages.
+ let scale_factor = 72.0 / dpi;
- let ocr_results = match ocr_engine
- .recognize(&rgb_bytes, width, height, &options)
- .await
- {
- Ok(results) => results,
+ for (idx, page_number, handle) in handles {
+ let ocr_results: Vec<OcrResult> = match handle.await {
+ Ok(Ok(results)) => results,
+ Ok(Err(e)) => {
+ eprintln!("[ocr] failed for page {}: {}", page_number, e);
+ continue;
+ }
Err(e) => {
- eprintln!("[ocr] failed for page {}: {}", page.page_number, e);
+ eprintln!("[ocr] task panicked for page {}: {}", page_number, e);
continue;
}
};
@@ -119,12 +141,8 @@ pub async fn ocr_and_merge_pages_from_input(
continue;
}
- // Scale OCR pixel coordinates to PDF points (72 DPI)
- let scale_factor = 72.0 / dpi;
-
- let mut added = 0;
+ let page = &mut pages[idx];
for r in &ocr_results {
- // Filter low confidence
if r.confidence <= 0.1 {
continue;
}
@@ -134,7 +152,6 @@ pub async fn ocr_and_merge_pages_from_input(
let ocr_w = (r.bbox[2] - r.bbox[0]) * scale_factor;
let ocr_h = (r.bbox[3] - r.bbox[1]) * scale_factor;
- // Skip if overlaps with existing PDF text (2pt tolerance)
if overlaps_existing_text(&page.text_items, ocr_x, ocr_y, ocr_w, ocr_h, 2.0) {
continue;
}
@@ -155,14 +172,6 @@ pub async fn ocr_and_merge_pages_from_input(
confidence: Some((r.confidence * 1000.0).round() / 1000.0),
..Default::default()
});
- added += 1;
- }
-
- if added > 0 {
- eprintln!(
- "[ocr] added {} text items from OCR on page {}",
- added, page.page_number
- );
}
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 12c49af..6d4899b 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -137,8 +137,9 @@ impl LiteParse {
&mut pages,
&input,
self.config.dpi,
- engine.as_ref(),
+ engine,
&self.config.ocr_language,
+ self.config.num_workers,
)
.await?;
}
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index a85fc79..8d64808 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -65,8 +65,6 @@ export declare class LiteParse {
parse(input: string | Buffer): Promise<JsParseResult>
/** Take screenshots of document pages. Returns PNG image buffers. */
screenshot(input: string, pageNumbers?: Array<number> | undefined | null): Array<JsScreenshotResult>
- /** Format a parse result according to the configured output format. */
- format(result: JsParseResult): string
/** Get the current configuration. */
get config(): JsLiteParseConfig
}
diff --git a/packages/node/package-lock.json b/packages/node/package-lock.json
index df9bc7e..21e5daf 100644
--- a/packages/node/package-lock.json
+++ b/packages/node/package-lock.json
@@ -25,11 +25,8 @@
},
"optionalDependencies": {
"@llamaindex/liteparse-darwin-arm64": "2.0.0",
- "@llamaindex/liteparse-darwin-x64": "2.0.0",
"@llamaindex/liteparse-linux-arm64-gnu": "2.0.0",
- "@llamaindex/liteparse-linux-arm64-musl": "2.0.0",
"@llamaindex/liteparse-linux-x64-gnu": "2.0.0",
- "@llamaindex/liteparse-linux-x64-musl": "2.0.0",
"@llamaindex/liteparse-win32-x64-msvc": "2.0.0"
}
},
diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.ts
index f0ac9ca..435b798 100644
--- a/packages/node/src/cli.ts
+++ b/packages/node/src/cli.ts
@@ -29,6 +29,7 @@ program
.option("--password <password>", "Password for encrypted documents")
.option("--config <file>", "JSON config file path")
.option("-q, --quiet", "Suppress progress output")
+ .option("--num-workers <n>", "Number of concurrent OCR workers", parseInt)
.action(async (file: string, opts: Record<string, unknown>) => {
try {
const config: Partial<LiteParseConfig> = {};
@@ -53,6 +54,7 @@ program
if (opts.preserveSmallText) config.preserveVerySmallText = true;
if (opts.password) config.password = opts.password as string;
if (opts.quiet) config.quiet = true;
+ if (opts.numWorkers) config.numWorkers = opts.numWorkers as number;
// Default CLI output to text (library defaults to json)
if (!config.outputFormat) config.outputFormat = "text";
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index 49e3a8f..eb4acc9 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -26,6 +26,7 @@ export interface LiteParseConfig {
preserveVerySmallText: boolean;
password?: string;
quiet: boolean;
+ numWorkers: number;
}
export interface TextItem {
@@ -80,6 +81,7 @@ export class LiteParse {
preserveVerySmallText: userConfig.preserveVerySmallText,
password: userConfig.password,
quiet: userConfig.quiet,
+ numWorkers: userConfig.numWorkers,
};
this._native = new native.LiteParse(nativeConfig);
@@ -98,6 +100,7 @@ export class LiteParse {
preserveVerySmallText: resolved.preserveVerySmallText ?? false,
password: resolved.password ?? undefined,
quiet: resolved.quiet ?? false,
+ numWorkers: resolved.numWorkers ?? 1,
};
}
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index f89cdae..698b1bd 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -26,6 +26,7 @@ export interface LiteParseNativeConfig {
preserveVerySmallText?: boolean;
password?: string;
quiet?: boolean;
+ numWorkers?: number;
}
export interface NativeTextItem {
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index ca041bf..91edd9f 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -73,6 +73,7 @@ class LiteParse:
preserve_very_small_text: Optional[bool] = None,
password: Optional[str] = None,
quiet: Optional[bool] = None,
+ num_workers: Optional[int] = None,
):
"""
Initialize LiteParse parser.
@@ -88,6 +89,7 @@ class LiteParse:
preserve_very_small_text: Whether to preserve very small text
password: Password for encrypted/protected documents
quiet: Suppress progress output
+ num_workers: Number of concurrent OCR workers (default: CPU cores - 1)
"""
kwargs = {}
if ocr_enabled is not None:
@@ -110,6 +112,8 @@ class LiteParse:
kwargs["password"] = password
if quiet is not None:
kwargs["quiet"] = quiet
+ if num_workers is not None:
+ kwargs["num_workers"] = num_workers
self._native = _NativeLiteParse(**kwargs)