Skip to content

A fast, helpful, and open-source document parser

add is_complex functionality

Logan Markewich9bc2f47e8314
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index a4085a0..872faea 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -5,6 +5,7 @@ use liteparse::extract;
use liteparse::output::{json, text};
use liteparse::parser::LiteParse;
use liteparse::render;
+use liteparse::types::PdfInput;
#[derive(Parser, Debug)]
#[command(
@@ -25,6 +26,8 @@ enum Commands {
Screenshot(ScreenshotCommand),
/// Parse multiple documents in batch mode
BatchParse(BatchParseCommand),
+ /// Check if a document is "complex" enough to require OCR or other advanced parsing
+ IsComplex(IsComplexCommand),
/// Extract raw text items from a PDF file (no grid projection) [dev tool]
#[command(hide = true)]
Extract(ExtractCommand),
@@ -217,6 +220,32 @@ struct ExtractCommand {
page_num: Option<u32>,
}
+#[derive(Args, Debug)]
+struct IsComplexCommand {
+ /// Input file path
+ file: String,
+
+ /// Whether to output the result as JSON (true/false) or plain text (true/false)
+ #[arg(long)]
+ json: bool,
+
+ /// Max pages to parse
+ #[arg(long, default_value = "1000")]
+ max_pages: usize,
+
+ /// Target pages (e.g., "1-5,10,15-20")
+ #[arg(long)]
+ target_pages: Option<String>,
+
+ /// Password for encrypted/protected documents
+ #[arg(long)]
+ password: Option<String>,
+
+ /// Suppress progress output
+ #[arg(short, long)]
+ quiet: bool,
+}
+
fn parse_output_format(s: &str) -> Result<OutputFormat, String> {
match s.to_lowercase().as_str() {
"json" => Ok(OutputFormat::Json),
@@ -474,6 +503,59 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Commands::ImageBounds(cmd) => {
render::image_bounds(&cmd.pdf_path, cmd.page_num)?;
}
+
+ Commands::IsComplex(cmd) => {
+ let config = LiteParseConfig {
+ max_pages: cmd.max_pages,
+ target_pages: cmd.target_pages,
+ password: cmd.password,
+ quiet: cmd.quiet,
+ ..Default::default()
+ };
+ let lp = LiteParse::new(config);
+ let is_complex = lp.is_complex(PdfInput::Path(cmd.file)).await?;
+
+ let complex_pages = is_complex.iter().filter(|c| c.needs_ocr).count();
+
+ if cmd.json {
+ let json = serde_json::to_string(&is_complex)?;
+ println!("{}", json);
+ } else {
+ let verdict = if complex_pages > 0 { "COMPLEX" } else { "SIMPLE" };
+ println!(
+ "{} — {}/{} page(s) need OCR",
+ verdict,
+ complex_pages,
+ is_complex.len()
+ );
+ println!(
+ "{:>4} {:>7} {:>5} {:>6} {:>7} {:>7} {:>5}",
+ "page", "text", "cov", "images", "garbled", "vector", "ocr"
+ );
+ for c in &is_complex {
+ let vector = match c.uncovered_vector_area {
+ Some(area) => format!("{:.0}", area),
+ None => "-".to_string(),
+ };
+ println!(
+ "{:>4} {:>7} {:>5.2} {:>6} {:>7} {:>7} {:>5}",
+ c.page_number,
+ c.text_length,
+ c.text_coverage,
+ if c.has_substantial_images { "yes" } else { "no" },
+ if c.is_garbled { "yes" } else { "no" },
+ vector,
+ if c.needs_ocr { "yes" } else { "no" },
+ );
+ }
+ }
+
+ // Exit non-zero when any page needs OCR, so the command is usable as
+ // a shell predicate (e.g. `is-complex doc.pdf && parse --disable-ocr`).
+ if complex_pages > 0 {
+ std::process::exit(1);
+ }
+ }
}
Ok(())
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index da58813..d3521e5 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -4,6 +4,7 @@ use crate::error::LiteParseError;
use crate::ocr::{OcrEngine, OcrOptions, OcrResult};
use crate::types::{Page, TextItem};
use pdfium::{Document, ImageBounds};
+use serde::Serialize;
/// Minimum dark filled-path area (pt², ~72 DPI page space) not covered by
/// native text before a page is sent to OCR. 400 pt² is roughly one word at
@@ -22,6 +23,87 @@ pub(crate) struct RenderedPage {
pub height: u32,
}
+#[derive(Debug, Serialize)]
+pub struct PageComplexityStats {
+ pub page_number: usize,
+ pub text_length: usize,
+ pub text_coverage: f32,
+ pub has_substantial_images: bool,
+ /// Filled vector-outline area not covered by native text, in pt². `None`
+ /// when a cheaper predicate already flagged the page for OCR, so this
+ /// expensive page-object walk was skipped (it wasn't the deciding signal).
+ pub uncovered_vector_area: Option<f32>,
+ pub is_garbled: bool,
+ pub page_area: f32,
+ pub needs_ocr: bool,
+}
+
+pub(crate) fn calculate_page_complexity(
+ page: &Page,
+ page_obj: &pdfium::Page,
+) -> Result<PageComplexityStats, LiteParseError> {
+ // Count only usable native text. Substitution-cipher-style corrupt
+ // encodings (e.g. PDFs with a broken cmap) produce long "text" that looks
+ // populated but is unreadable — without this, such pages bypass OCR
+ // because text_length >= 20 and coverage looks fine. The same applies to
+ // unmappable items (Type3 fonts with no ToUnicode), whose text is a
+ // char-code fallback and whose bounding boxes come from deceptive
+ // declared metrics.
+ let text_length: usize = page
+ .text_items
+ .iter()
+ .filter(|item| !is_unusable_native(item))
+ .map(|item| item.text.len())
+ .sum();
+ let has_images = !page_obj.image_bounds(25.0, 0.9).is_empty();
+
+ let page_area = page.page_width * page.page_height;
+ let text_bbox_area: f32 = page
+ .text_items
+ .iter()
+ .filter(|item| !is_unusable_native(item))
+ .map(|item| item.width * item.height)
+ .sum();
+ let text_coverage = if page_area > 0.0 {
+ text_bbox_area / page_area
+ } else {
+ 0.0
+ };
+
+ // Low spatial coverage only signals a scan/sparse page when there also
+ // isn't much native text. A text-dense page (e.g. a ruled table with
+ // wide intra-cell whitespace) is spatially sparse but needs no OCR.
+ let sparse_text = text_length < 2000 && text_coverage < 0.15;
+ let is_garbled = page_is_garbled(page);
+ let mut needs_ocr = text_length < 20 || sparse_text || has_images || is_garbled;
+
+ // Text drawn as filled vector outlines lives outside the text layer
+ // entirely: no text items, no image XObjects, so none of the cheap
+ // predicates fire on such a text-dense page. Detect it by measuring filled
+ // path area that native text doesn't account for. Checked last so this
+ // relatively expensive page-object walk only runs when the cheap predicates
+ // all pass; when they don't, the area is left unmeasured (`None`).
+ let uncovered_vector_area = if !needs_ocr {
+ let path_bounds = page_obj.filled_path_bounds(3.0, 0.9);
+ let uncovered = uncovered_path_area(&path_bounds, &page.text_items);
+ needs_ocr = uncovered >= UNCOVERED_VECTOR_AREA_THRESHOLD;
+ Some(uncovered)
+ } else {
+ None
+ };
+
+ Ok(PageComplexityStats {
+ page_number: page.page_number,
+ text_length,
+ text_coverage,
+ has_substantial_images: has_images,
+ uncovered_vector_area,
+ is_garbled,
+ page_area,
+ needs_ocr,
+ })
+}
+
/// Render pages that need OCR from an already-open document.
///
/// The pdfium `Document` holds raw pointers that are not `Send`, so callers must
@@ -33,54 +115,10 @@ pub(crate) fn render_pages_for_ocr(
) -> Result<Vec<RenderedPage>, LiteParseError> {
let mut rendered = Vec::new();
for (idx, page) in pages.iter().enumerate() {
- // Count only usable native text. Substitution-cipher-style corrupt
- // encodings (e.g. PDFs with a broken cmap) produce long "text" that looks
- // populated but is unreadable — without this, such pages bypass OCR
- // because text_length >= 20 and coverage looks fine. The same applies to
- // unmappable items (Type3 fonts with no ToUnicode), whose text is a
- // char-code fallback and whose bounding boxes come from deceptive
- // declared metrics.
- let text_length: usize = page
- .text_items
- .iter()
- .filter(|item| !is_unusable_native(item))
- .map(|item| item.text.len())
- .sum();
let page_obj = document.page((page.page_number - 1) as i32)?;
- let has_images = !page_obj.image_bounds(25.0, 0.9).is_empty();
-
- let page_area = page.page_width * page.page_height;
- let text_bbox_area: f32 = page
- .text_items
- .iter()
- .filter(|item| !is_unusable_native(item))
- .map(|item| item.width * item.height)
- .sum();
- let text_coverage = if page_area > 0.0 {
- text_bbox_area / page_area
- } else {
- 0.0
- };
-
- // Low spatial coverage only signals a scan/sparse page when there also
- // isn't much native text. A text-dense page (e.g. a ruled table with
- // wide intra-cell whitespace) is spatially sparse but needs no OCR.
- let sparse_text = text_length < 2000 && text_coverage < 0.15;
- let mut needs_ocr = text_length < 20 || sparse_text || has_images || page_is_garbled(page);
-
- // Text drawn as filled vector outlines lives outside the text layer
- // entirely: no text items, no image XObjects, so none of the above
- // triggers fire on a text-dense page. Detect it by measuring filled
- // path area that native text doesn't account for. Checked last so the
- // page-object walk only runs when the cheap predicates all pass.
- if !needs_ocr {
- let path_bounds = page_obj.filled_path_bounds(3.0, 0.9);
- let uncovered = uncovered_path_area(&path_bounds, &page.text_items);
-
- needs_ocr = uncovered >= UNCOVERED_VECTOR_AREA_THRESHOLD;
- }
+ let page_complexity = calculate_page_complexity(page, &page_obj)?;
- if !needs_ocr {
+ if !page_complexity.needs_ocr {
continue;
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index e345a30..2bfce22 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -80,6 +80,81 @@ impl LiteParse {
self
}
+ /// Parse the configured `target_pages` string (e.g. `"1-5,10"`) into an
+ /// explicit page list, or `None` when no selection was configured.
+ fn resolve_target_pages(&self) -> Result<Option<Vec<u32>>, LiteParseError> {
+ self.config
+ .target_pages
+ .as_ref()
+ .map(|s| parse_target_pages(s))
+ .transpose()
+ .map_err(|e| format!("invalid --target-pages: {}", e).into())
+ }
+
+ /// Determine the complexity of each page in a document, returning a vector
+ /// of `PageComplexityStats` for each page. This is useful for deciding
+ /// whether to enable OCR on a per-page basis, or for other heuristics.
+ pub async fn is_complex(
+ &self,
+ input: PdfInput,
+ ) -> Result<Vec<ocr_merge::PageComplexityStats>, LiteParseError> {
+ let log = |msg: &str| {
+ if !self.config.quiet {
+ eprintln!("{}", msg);
+ }
+ };
+
+ let t0 = web_time::Instant::now();
+
+ #[cfg(not(target_arch = "wasm32"))]
+ let (validated_input, _guard) =
+ conversion::resolve_pdf_input(input, self.config.password.as_deref(), false).await?;
+
+ #[cfg(target_arch = "wasm32")]
+ let validated_input = input;
+
+ // Determine which pages to extract
+ let target_pages = self.resolve_target_pages()?;
+
+ // Load the document and extract text items. Complexity signals derive
+ // from the text layer and page objects only — embedded image rasters
+ // and hyperlinks are irrelevant here, so both are skipped to keep this
+ // pass fast (its whole purpose is a cheap pre-OCR check).
+ let password = self.config.password.as_deref();
+
+ let lib = Library::init();
+ let document = extract::load_document_from_input(&lib, &validated_input, password)?;
+
+ let (pages, _) = extract::extract_pages_and_images(
+ &document,
+ target_pages.as_deref(),
+ self.config.max_pages,
+ false, // render_images: image rasters not needed for complexity
+ false, // extract_links: irrelevant for complexity stats
+ )?;
+ let t_extract = web_time::Instant::now();
+ log(&format!(
+ "[liteparse] extract: {:.1}ms ({} pages)",
+ t_extract.duration_since(t0).as_secs_f64() * 1000.0,
+ pages.len()
+ ));
+
+ let t_complexity = web_time::Instant::now();
+ let page_complexities = pages
+ .iter()
+ .map(|page| {
+ let page_obj = document.page((page.page_number - 1) as i32)?;
+ ocr_merge::calculate_page_complexity(page, &page_obj)
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ log(&format!(
+ "[liteparse] complexity: {:.1}ms",
+ t_complexity.duration_since(t_extract).as_secs_f64() * 1000.0
+ ));
+
+ Ok(page_complexities)
+ }
+
/// Parse a document from a file path, returning structured results.
///
/// Non-PDF files are automatically converted to PDF first (requires
@@ -113,13 +188,7 @@ impl LiteParse {
let validated_input = input;
// Determine which pages to extract
- let target_pages = self
- .config
- .target_pages
- .as_ref()
- .map(|s| parse_target_pages(s))
- .transpose()
- .map_err(|e| format!("invalid --target-pages: {}", e))?;
+ let target_pages = self.resolve_target_pages()?;
// 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