A fast, helpful, and open-source document parser
fix(ocr): classify low-coverage OCR failures as sparse
Aldo694044b1e80a
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rsindex e91b98c..293f420 100644--- a/crates/liteparse/src/ocr_merge.rs+++ b/crates/liteparse/src/ocr_merge.rs@@ -114,28 +114,24 @@ pub(crate) async fn ocr_and_merge_rendered(// from incidental per-page failures. Without this, every page logs the same// error and `parse()` still returns "success" with no OCR text.//- // We additionally track whether any *text-starved* page failed: a page is- // rendered for OCR if it is text-starved OR merely contains an image+ // We additionally track whether any *sparse-text* page failed: a page is+ // rendered for OCR if it has sparse native text OR merely contains an image// (`needs_ocr = text_length < 20 || text_coverage < 0.15 || has_images`).// A native-text PDF with a logo on every page is rendered for OCR// enrichment but already has all its text. We must only fail loud when OCR- // failure actually destroyed a page's *only* text source — i.e. a page that- // had essentially no native text — otherwise a broken OCR setup would abort- // perfectly good native-text documents.+ // failure destroyed a sparse page's likely primary text source — otherwise+ // a broken OCR setup would abort perfectly good native-text documents.let total_tasks = handles.len();let mut failed_tasks = 0usize;- let mut failed_text_starved = false;+ let mut failed_sparse_text_page = false;let mut first_error: Option<String> = None;- // Matches the `text_length < 20` threshold in `render_pages_for_ocr`.- const TEXT_STARVED_LEN: usize = 20;-for (idx, page_number, handle) in handles {let ocr_results: Vec<OcrResult> = match handle.await {Ok(Ok(results)) => results,Ok(Err(e)) => {failed_tasks += 1;- failed_text_starved |= page_native_text_len(&pages[idx]) < TEXT_STARVED_LEN;+ failed_sparse_text_page |= page_has_sparse_native_text(&pages[idx]);// Only log the first failure to avoid flooding stderr with an// identical message for every page.if first_error.is_none() {@@ -147,7 +143,7 @@ pub(crate) async fn ocr_and_merge_rendered(}Err(e) => {failed_tasks += 1;- failed_text_starved |= page_native_text_len(&pages[idx]) < TEXT_STARVED_LEN;+ failed_sparse_text_page |= page_has_sparse_native_text(&pages[idx]);if first_error.is_none() {let msg = e.to_string();eprintln!("[ocr] task panicked for page {}: {}", page_number, msg);@@ -196,14 +192,15 @@ pub(crate) async fn ocr_and_merge_rendered(}// If every OCR task failed *and* at least one of those failures was on a- // text-starved page (one that had essentially no native text), treat it as- // a systemic failure: that page now has no text at all. Returning an error- // surfaces the root cause (e.g. missing language data) instead of silently- // emitting an empty page. We deliberately do NOT fail when the only failures- // were on pages that already had native text and were merely rendered for- // image-based OCR enrichment — a broken OCR setup must not abort an- // otherwise-good native-text document.- if total_tasks > 0 && failed_tasks == total_tasks && failed_text_starved {+ // sparse-text page (the same length/coverage predicate that sends pages to+ // OCR as text-poor in `render_pages_for_ocr`), treat it as a systemic+ // failure. Returning an error surfaces the root cause (e.g. missing language+ // data) instead of silently emitting an empty or mostly-empty page. We+ // deliberately do NOT fail when the only failures were on pages that already+ // had substantial native text and were merely rendered for image-based OCR+ // enrichment — a broken OCR setup must not abort an otherwise-good+ // native-text document.+ if total_tasks > 0 && failed_tasks == total_tasks && failed_sparse_text_page {let detail = first_error.unwrap_or_else(|| "unknown error".to_string());return Err(LiteParseError::Ocr(format!("OCR failed for all {} page(s): {}",@@ -222,9 +219,26 @@ pub(crate) async fn ocr_and_merge_rendered(Ok(())}-/// Total length of a page's native (already-extracted) text, in bytes.-fn page_native_text_len(page: &Page) -> usize {- page.text_items.iter().map(|item| item.text.len()).sum()+/// True when the page's native (already-extracted) text is sparse enough that+/// OCR is likely its primary text source. Mirrors the non-image predicates in+/// `render_pages_for_ocr` (`text_length < 20 || text_coverage < 0.15`) so the+/// systemic-failure guard matches the same pages that were rendered because+/// their native text was insufficient.+fn page_has_sparse_native_text(page: &Page) -> bool {+ let text_length: usize = page.text_items.iter().map(|item| item.text.len()).sum();+ let page_area = page.page_width * page.page_height;+ let text_bbox_area: f32 = page+ .text_items+ .iter()+ .map(|item| item.width * item.height)+ .sum();+ let text_coverage = if page_area > 0.0 {+ text_bbox_area / page_area+ } else {+ 0.0+ };++ text_length < 20 || text_coverage < 0.15}/// Check if an OCR bounding box overlaps with any existing text item.@@ -387,9 +401,9 @@ mod tests {}}- // A page that already has plenty of native text (>= TEXT_STARVED_LEN bytes),- // as would be the case for a native-text PDF page that was only rendered for- // OCR because it also contains an image.+ // A page that already has substantial native text coverage, as would be the+ // case for a native-text PDF page that was only rendered for OCR because it+ // also contains an image.fn make_native_text_page(page_number: usize) -> Page {Page {page_number,@@ -400,7 +414,27 @@ mod tests {x: 0.0,y: 0.0,width: 50.0,- height: 10.0,+ height: 50.0,+ ..Default::default()+ }],+ }+ }++ // A page with >20 bytes of native text but very low page coverage. These+ // are still text-poor enough that `render_pages_for_ocr` sends them to OCR+ // (`text_coverage < 0.15`), so a systemic OCR failure should not be silently+ // swallowed.+ fn make_low_coverage_text_page(page_number: usize) -> Page {+ Page {+ page_number,+ page_width: 100.0,+ page_height: 100.0,+ text_items: vec![TextItem {+ text: "small native header that is not enough".into(),+ x: 0.0,+ y: 0.0,+ width: 10.0,+ height: 5.0,..Default::default()}],}@@ -460,10 +494,11 @@ mod tests {assert_eq!(pages[1].text_items.len(), 1);}- // When failures span both a text-starved page and a native-text page, the- // text-starved page lost its only text source, so we still fail loud.+ // When failures span both a sparse-text page and a native-text page, the+ // sparse-text page lost its likely primary text source, so we still fail+ // loud.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn test_mixed_failure_with_text_starved_page_returns_error() {+ async fn test_mixed_failure_with_sparse_text_page_returns_error() {let mut pages = vec![make_native_text_page(1), make_blank_page(2)];let rendered = vec![make_rendered(0), make_rendered(1)];let engine: Arc<dyn OcrEngine> = Arc::new(FailingEngine);@@ -476,4 +511,22 @@ mod tests {"unexpected error message: {err}");}++ // Regression guard for the review finding: low-coverage pages are rendered+ // for OCR even when their native text length is >20 bytes. A systemic OCR+ // failure on such pages must still surface as an error.+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn test_low_coverage_text_page_failure_returns_error() {+ let mut pages = vec![make_low_coverage_text_page(1)];+ let rendered = vec![make_rendered(0)];+ let engine: Arc<dyn OcrEngine> = Arc::new(FailingEngine);++ let result = ocr_and_merge_rendered(&mut pages, rendered, 72.0, engine, "eng", 2).await;++ let err = result.expect_err("low-coverage text page losing OCR must surface an error");+ assert!(+ err.to_string().contains("OCR failed for all 1 page(s)"),+ "unexpected error message: {err}"+ );+ }}