Skip to content

A fast, helpful, and open-source document parser

feat: improve ocr handling for complex docs

Logan Markewich622fb3d36ace
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 390eb5b..b8fedf6 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -549,6 +549,9 @@ struct SegmentBuilder {
last_char_bottom: f32,
// Count of non-space characters (for avg width calculation)
char_count: usize,
+ // Count of characters whose Unicode came from PDFium's char-code fallback
+ // (no usable ToUnicode / glyph-name mapping, e.g. Type3 fonts).
+ unmapped_char_count: usize,
// Font metadata (captured from the first character)
font_name: Option<String>,
font_size: f32,
@@ -580,6 +583,7 @@ impl SegmentBuilder {
last_char_right: f32::MIN,
last_char_bottom: f32::MIN,
char_count: 0,
+ unmapped_char_count: 0,
font_name: None,
font_size: 0.0,
font_height: None,
@@ -633,6 +637,7 @@ impl SegmentBuilder {
self.last_char_right = vp_strict.right;
self.last_char_bottom = vp_strict.bottom;
self.char_count = 1;
+ self.unmapped_char_count = if ch.has_unicode_map_error() { 1 } else { 0 };
self.has_content = true;
self.pending_space = false;
self.text_width = 0.0;
@@ -726,6 +731,9 @@ impl SegmentBuilder {
self.last_char_right = vp_strict.right;
self.last_char_bottom = vp_strict.bottom;
self.char_count += 1;
+ if ch.has_unicode_map_error() {
+ self.unmapped_char_count += 1;
+ }
// Accumulate glyph width
if let Some(ref font) = self.font {
@@ -811,6 +819,9 @@ impl SegmentBuilder {
None
},
font_is_buggy: self.font_is_buggy,
+ // Majority vote: a stray mapped char (e.g. a space) inside an
+ // otherwise unmappable Type3 run must not rescue the item.
+ has_unicode_map_error: self.unmapped_char_count * 2 >= self.char_count.max(1),
mcid: self.mcid,
fill_color: self.fill_color.clone(),
stroke_color: self.stroke_color.clone(),
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index 38825b1..7bbc8a0 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -3,7 +3,16 @@ use std::sync::Arc;
use crate::error::LiteParseError;
use crate::ocr::{OcrEngine, OcrOptions, OcrResult};
use crate::types::{Page, TextItem};
-use pdfium::Document;
+use pdfium::{Document, ImageBounds};
+
+/// 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
+/// a 10–12pt size; anything smaller is likely a bullet, icon, dot leader, or
+/// decoration whose loss is acceptable. A false trigger only costs an extra
+/// OCR pass (the overlap filter discards OCR results that duplicate native
+/// text); measured on a 121-page financial report, the trigger fires on ~3
+/// pages at this threshold.
+const UNCOVERED_VECTOR_AREA_THRESHOLD: f32 = 400.0;
/// Owned page bitmap prepared for OCR. Indices refer to positions in the `pages` slice.
pub(crate) struct RenderedPage {
@@ -24,14 +33,17 @@ 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 non-garbled native text. Substitution-cipher-style corrupt
+ // 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.
+ // 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_likely_garbled(&item.text))
+ .filter(|item| !is_unusable_native(item))
.map(|item| item.text.len())
.sum();
let page_obj = document.page((page.page_number - 1) as i32)?;
@@ -41,7 +53,7 @@ pub(crate) fn render_pages_for_ocr(
let text_bbox_area: f32 = page
.text_items
.iter()
- .filter(|item| !is_likely_garbled(&item.text))
+ .filter(|item| !is_unusable_native(item))
.map(|item| item.width * item.height)
.sum();
let text_coverage = if page_area > 0.0 {
@@ -50,8 +62,37 @@ pub(crate) fn render_pages_for_ocr(
0.0
};
- let needs_ocr =
+ let mut needs_ocr =
text_length < 20 || text_coverage < 0.15 || 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;
+ if std::env::var("LITEPARSE_DEBUG").is_ok() {
+ eprintln!(
+ "[ocr-debug] page {}: {} filled paths, uncovered area {:.0} -> vector trigger {}",
+ page.page_number,
+ path_bounds.len(),
+ uncovered,
+ needs_ocr
+ );
+ if needs_ocr {
+ for p in &path_bounds {
+ eprintln!(
+ "[ocr-debug] path x={:.0} y={:.0} w={:.0} h={:.0}",
+ p.x, p.y, p.width, p.height
+ );
+ }
+ }
+ }
+ }
+
if !needs_ocr {
continue;
}
@@ -163,17 +204,17 @@ pub(crate) async fn ocr_and_merge_rendered(
}
let page = &mut pages[idx];
- // Drop garbled native items (e.g. substitution-cipher cmap corruption) so
- // OCR can replace them. Without this, garbled-but-spatially-present native
- // text suppresses every OCR result that overlaps it via the overlap check
- // below, leaving the output stuck with unreadable cipher text. We apply
- // both per-item and per-page checks: short garbled labels ("GDWH",
- // "XVG") can't be flagged alone, but their host page can.
+ // Drop unusable native items (substitution-cipher cmap corruption, or
+ // unmappable Type3 text) so OCR can replace them. Without this,
+ // garbled-but-spatially-present native text suppresses every OCR
+ // result that overlaps it via the overlap check below, leaving the
+ // output stuck with unreadable text. We apply both per-item and
+ // per-page checks: short garbled labels ("GDWH", "XVG") can't be
+ // flagged alone, but their host page can.
if page_is_garbled(page) {
page.text_items.clear();
} else {
- page.text_items
- .retain(|item| !is_likely_garbled(&item.text));
+ page.text_items.retain(|item| !is_unusable_native(item));
}
// Only check overlap against native (already-extracted) PDF text. Comparing
@@ -295,14 +336,14 @@ fn page_has_sparse_native_text(page: &Page) -> bool {
let text_length: usize = page
.text_items
.iter()
- .filter(|item| !is_likely_garbled(&item.text))
+ .filter(|item| !is_unusable_native(item))
.map(|item| item.text.len())
.sum();
let page_area = page.page_width * page.page_height;
let text_bbox_area: f32 = page
.text_items
.iter()
- .filter(|item| !is_likely_garbled(&item.text))
+ .filter(|item| !is_unusable_native(item))
.map(|item| item.width * item.height)
.sum();
let text_coverage = if page_area > 0.0 {
@@ -314,6 +355,44 @@ fn page_has_sparse_native_text(page: &Page) -> bool {
text_length < 20 || text_coverage < 0.15
}
+/// A native text item that cannot be trusted as a text source: either its
+/// Unicode mapping failed outright (Type3 fonts with no ToUnicode — the text
+/// is a char-code fallback and the bbox comes from deceptive declared
+/// metrics), or its content looks substitution-cipher garbled.
+fn is_unusable_native(item: &TextItem) -> bool {
+ item.has_unicode_map_error || is_likely_garbled(&item.text)
+}
+
+/// Total area of filled vector paths not accounted for by native text items.
+/// Glyph outlines drawn as paths produce filled regions with no overlapping
+/// text item; rules and table borders are stroke-only and already excluded
+/// upstream, and shading rects behind real text are subtracted away by the
+/// text overlap. Coverage is approximated by summing per-item intersections
+/// (clamped to the path's own area), which can only over-estimate coverage —
+/// i.e. err toward not triggering OCR.
+fn uncovered_path_area(paths: &[ImageBounds], items: &[TextItem]) -> f32 {
+ let mut uncovered = 0.0f32;
+ for p in paths {
+ let p_area = p.width * p.height;
+ if p_area <= 0.0 {
+ continue;
+ }
+ let mut covered = 0.0f32;
+ for item in items {
+ let ix = (p.x + p.width).min(item.x + item.width) - p.x.max(item.x);
+ let iy = (p.y + p.height).min(item.y + item.height) - p.y.max(item.y);
+ if ix > 0.0 && iy > 0.0 {
+ covered += ix * iy;
+ if covered >= p_area {
+ break;
+ }
+ }
+ }
+ uncovered += (p_area - covered).max(0.0);
+ }
+ uncovered
+}
+
/// Heuristic for substitution-cipher / broken-cmap garbling: real Latin-script
/// text has a vowel ratio of roughly 30–45%, but a substitution permutation
/// almost always maps the original A/E/I/O/U onto non-vowel letters, driving
@@ -556,6 +635,58 @@ mod tests {
assert!(!overlaps_existing_text(&[], 0.0, 0.0, 1.0, 1.0, 0.0));
}
+ fn pb(x: f32, y: f32, w: f32, h: f32) -> ImageBounds {
+ ImageBounds {
+ x,
+ y,
+ width: w,
+ height: h,
+ }
+ }
+
+ #[test]
+ fn test_uncovered_path_area_no_text() {
+ // A sentence-sized outlined region with no native text at all.
+ let paths = vec![pb(50.0, 300.0, 200.0, 12.0)];
+ let area = uncovered_path_area(&paths, &[]);
+ assert!((area - 2400.0).abs() < 1.0);
+ assert!(area >= UNCOVERED_VECTOR_AREA_THRESHOLD);
+ }
+
+ #[test]
+ fn test_uncovered_path_area_fully_covered_by_text() {
+ // Shading rect behind real text: fully covered, must not trigger.
+ let paths = vec![pb(50.0, 300.0, 200.0, 12.0)];
+ let items = vec![make_item(40.0, 295.0, 250.0, 25.0)];
+ let area = uncovered_path_area(&paths, &items);
+ assert_eq!(area, 0.0);
+ }
+
+ #[test]
+ fn test_uncovered_path_area_partial_coverage() {
+ // Half the outlined region is covered by a text item.
+ let paths = vec![pb(0.0, 0.0, 100.0, 10.0)];
+ let items = vec![make_item(0.0, 0.0, 50.0, 10.0)];
+ let area = uncovered_path_area(&paths, &items);
+ assert!((area - 500.0).abs() < 1.0);
+ }
+
+ #[test]
+ fn test_uncovered_path_area_small_decoration_below_threshold() {
+ // A few bullet-sized filled paths shouldn't reach the threshold.
+ let paths = vec![pb(10.0, 10.0, 8.0, 8.0), pb(10.0, 30.0, 8.0, 8.0)];
+ let area = uncovered_path_area(&paths, &[]);
+ assert!(area < UNCOVERED_VECTOR_AREA_THRESHOLD);
+ }
+
+ #[test]
+ fn test_unusable_native_unicode_map_error() {
+ let mut item = make_item(0.0, 0.0, 10.0, 10.0);
+ assert!(!is_unusable_native(&item));
+ item.has_unicode_map_error = true;
+ assert!(is_unusable_native(&item));
+ }
+
#[test]
fn test_clean_ocr_keeps_whitespace_trimmed() {
assert_eq!(clean_ocr_table_artifacts(" "), "");
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index cd371d2..8f34879 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -41,6 +41,11 @@ pub struct TextItem {
/// Whether the font has buggy encoding (private-use codepoints, TT subset, etc.)
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub font_is_buggy: bool,
+ /// Whether most characters in this item could not be mapped to Unicode
+ /// (e.g. a Type3 font with no ToUnicode map). The text content is
+ /// PDFium's char-code fallback and does not reflect the rendered glyphs.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub has_unicode_map_error: bool,
/// Marked content ID from the PDF structure tree.
#[serde(skip_serializing_if = "Option::is_none")]
pub mcid: Option<i32>,
diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rs
index 761ab80..a8f2a91 100644
--- a/crates/pdfium-sys/src/dynamic.rs
+++ b/crates/pdfium-sys/src/dynamic.rs
@@ -72,6 +72,22 @@ pub struct PdfiumBindings {
unsafe extern "C" fn(FPDF_PAGEOBJECT) -> std::os::raw::c_int,
pub FPDFImageObj_GetRenderedBitmap:
unsafe extern "C" fn(FPDF_DOCUMENT, FPDF_PAGE, FPDF_PAGEOBJECT) -> FPDF_BITMAP,
+ pub FPDFPageObj_GetMatrix: unsafe extern "C" fn(FPDF_PAGEOBJECT, *mut FS_MATRIX) -> FPDF_BOOL,
+ pub FPDFPageObj_GetFillColor: unsafe extern "C" fn(
+ FPDF_PAGEOBJECT,
+ *mut std::os::raw::c_uint,
+ *mut std::os::raw::c_uint,
+ *mut std::os::raw::c_uint,
+ *mut std::os::raw::c_uint,
+ ) -> FPDF_BOOL,
+ pub FPDFPath_GetDrawMode: unsafe extern "C" fn(
+ FPDF_PAGEOBJECT,
+ *mut std::os::raw::c_int,
+ *mut FPDF_BOOL,
+ ) -> FPDF_BOOL,
+ pub FPDFFormObj_CountObjects: unsafe extern "C" fn(FPDF_PAGEOBJECT) -> std::os::raw::c_int,
+ pub FPDFFormObj_GetObject:
+ unsafe extern "C" fn(FPDF_PAGEOBJECT, std::os::raw::c_ulong) -> FPDF_PAGEOBJECT,
// -- TextPage --
pub FPDFText_LoadPage: unsafe extern "C" fn(FPDF_PAGE) -> FPDF_TEXTPAGE,
@@ -232,6 +248,11 @@ impl PdfiumBindings {
FPDFPageObj_GetBounds: load_fn!(lib, "FPDFPageObj_GetBounds"),
FPDFPageObj_GetMarkedContentID: load_fn!(lib, "FPDFPageObj_GetMarkedContentID"),
FPDFImageObj_GetRenderedBitmap: load_fn!(lib, "FPDFImageObj_GetRenderedBitmap"),
+ FPDFPageObj_GetMatrix: load_fn!(lib, "FPDFPageObj_GetMatrix"),
+ FPDFPageObj_GetFillColor: load_fn!(lib, "FPDFPageObj_GetFillColor"),
+ FPDFPath_GetDrawMode: load_fn!(lib, "FPDFPath_GetDrawMode"),
+ FPDFFormObj_CountObjects: load_fn!(lib, "FPDFFormObj_CountObjects"),
+ FPDFFormObj_GetObject: load_fn!(lib, "FPDFFormObj_GetObject"),
FPDFText_LoadPage: load_fn!(lib, "FPDFText_LoadPage"),
FPDFText_ClosePage: load_fn!(lib, "FPDFText_ClosePage"),
FPDFText_CountChars: load_fn!(lib, "FPDFText_CountChars"),
diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rs
index 6fcec1f..9322e30 100644
--- a/crates/pdfium/src/page.rs
+++ b/crates/pdfium/src/page.rs
@@ -215,6 +215,39 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
results
}
+ /// Extract bounding boxes of filled vector path objects on this page,
+ /// recursing into form XObjects (with each form's transform applied).
+ /// Returns coordinates in viewport space (Y-down, top-left origin) in PDF
+ /// points. Stroke-only paths (rules, borders) are skipped, as are paths
+ /// smaller than `min_size_pt` in either dimension and paths covering more
+ /// than `max_page_coverage` fraction of the page in both dimensions
+ /// (full-page background rects).
+ pub fn filled_path_bounds(&self, min_size_pt: f32, max_page_coverage: f32) -> Vec<ImageBounds> {
+ let page_width = self.width();
+ let page_height = self.height();
+ let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
+ let mut results = Vec::new();
+
+ for i in 0..obj_count {
+ let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
+ if obj.is_null() {
+ continue;
+ }
+ collect_filled_paths(
+ obj,
+ None,
+ page_width,
+ page_height,
+ min_size_pt,
+ max_page_coverage,
+ 0,
+ &mut results,
+ );
+ }
+
+ results
+ }
+
/// Get the rendered bitmap of a specific embedded image object by index.
/// The index corresponds to the order from iterating page objects (image objects only).
pub fn render_image_object(&self, image_obj_index: usize) -> Result<Bitmap<'lib>, PdfiumError> {
@@ -252,6 +285,173 @@ impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
}
}
+/// Recursion limit for nested form XObjects in `filled_path_bounds`.
+const MAX_FORM_DEPTH: u32 = 4;
+
+/// Compose two FS_MATRIX transforms: the result applies `inner` first,
+/// then `outer` (i.e. `outer ∘ inner`).
+fn compose_matrices(
+ outer: &pdfium_sys::FS_MATRIX,
+ inner: &pdfium_sys::FS_MATRIX,
+) -> pdfium_sys::FS_MATRIX {
+ pdfium_sys::FS_MATRIX {
+ a: outer.a * inner.a + outer.c * inner.b,
+ b: outer.b * inner.a + outer.d * inner.b,
+ c: outer.a * inner.c + outer.c * inner.d,
+ d: outer.b * inner.c + outer.d * inner.d,
+ e: outer.a * inner.e + outer.c * inner.f + outer.e,
+ f: outer.b * inner.e + outer.d * inner.f + outer.f,
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn collect_filled_paths(
+ obj: pdfium_sys::FPDF_PAGEOBJECT,
+ transform: Option<&pdfium_sys::FS_MATRIX>,
+ page_width: f32,
+ page_height: f32,
+ min_size_pt: f32,
+ max_page_coverage: f32,
+ depth: u32,
+ out: &mut Vec<ImageBounds>,
+) {
+ let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };
+
+ if obj_type == pdfium_sys::FPDF_PAGEOBJ_FORM as i32 {
+ if depth >= MAX_FORM_DEPTH {
+ return;
+ }
+ // Child bounds are reported in the form's coordinate space, so the
+ // form matrix (composed with any outer form transforms) must be
+ // applied to map them into page space.
+ let mut m = pdfium_sys::FS_MATRIX {
+ a: 1.0,
+ b: 0.0,
+ c: 0.0,
+ d: 1.0,
+ e: 0.0,
+ f: 0.0,
+ };
+ let has_m = unsafe { ffi!(FPDFPageObj_GetMatrix(obj, &mut m)) } != 0;
+ let combined = match (transform, has_m) {
+ (Some(outer), true) => Some(compose_matrices(outer, &m)),
+ (Some(outer), false) => Some(*outer),
+ (None, true) => Some(m),
+ (None, false) => None,
+ };
+
+ let child_count = unsafe { ffi!(FPDFFormObj_CountObjects(obj)) };
+ for i in 0..child_count {
+ let child = unsafe { ffi!(FPDFFormObj_GetObject(obj, i as std::os::raw::c_ulong)) };
+ if child.is_null() {
+ continue;
+ }
+ collect_filled_paths(
+ child,
+ combined.as_ref(),
+ page_width,
+ page_height,
+ min_size_pt,
+ max_page_coverage,
+ depth + 1,
+ out,
+ );
+ }
+ return;
+ }
+
+ if obj_type != pdfium_sys::FPDF_PAGEOBJ_PATH as i32 {
+ return;
+ }
+
+ // Only filled paths can be glyph outlines; skip stroke-only paths
+ // (table borders, rules, underlines).
+ let mut fill_mode: std::os::raw::c_int = 0;
+ let mut stroke: pdfium_sys::FPDF_BOOL = 0;
+ let ok = unsafe { ffi!(FPDFPath_GetDrawMode(obj, &mut fill_mode, &mut stroke)) };
+ if ok == 0 || fill_mode == pdfium_sys::FPDF_FILLMODE_NONE as i32 {
+ return;
+ }
+
+ // Skip light or transparent fills: glyph outlines are drawn in ink-like
+ // (dark, opaque) colors, while table zebra striping and section shading
+ // use light pastels. Light-on-dark text still gets caught because the
+ // dark background rect itself is a dark filled path. Paths whose fill
+ // color can't be read (pattern/shading fills) are kept conservatively.
+ let mut r: std::os::raw::c_uint = 0;
+ let mut g: std::os::raw::c_uint = 0;
+ let mut b: std::os::raw::c_uint = 0;
+ let mut a: std::os::raw::c_uint = 0;
+ let ok = unsafe {
+ ffi!(FPDFPageObj_GetFillColor(
+ obj, &mut r, &mut g, &mut b, &mut a
+ ))
+ };
+ if ok != 0 {
+ if a < 128 {
+ return;
+ }
+ let luminance = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
+ if luminance > 140.0 {
+ return;
+ }
+ }
+
+ let mut left: f32 = 0.0;
+ let mut bottom: f32 = 0.0;
+ let mut right: f32 = 0.0;
+ let mut top: f32 = 0.0;
+ let ok = unsafe {
+ ffi!(FPDFPageObj_GetBounds(
+ obj,
+ &mut left,
+ &mut bottom,
+ &mut right,
+ &mut top
+ ))
+ };
+ if ok == 0 {
+ return;
+ }
+
+ if let Some(m) = transform {
+ let corners = [(left, bottom), (right, bottom), (left, top), (right, top)];
+ let mut min_x = f32::INFINITY;
+ let mut max_x = f32::NEG_INFINITY;
+ let mut min_y = f32::INFINITY;
+ let mut max_y = f32::NEG_INFINITY;
+ for (x, y) in corners {
+ let tx = m.a * x + m.c * y + m.e;
+ let ty = m.b * x + m.d * y + m.f;
+ min_x = min_x.min(tx);
+ max_x = max_x.max(tx);
+ min_y = min_y.min(ty);
+ max_y = max_y.max(ty);
+ }
+ left = min_x;
+ right = max_x;
+ bottom = min_y;
+ top = max_y;
+ }
+
+ let w = right - left;
+ let h = top - bottom;
+
+ if w < min_size_pt || h < min_size_pt {
+ return;
+ }
+ if w > page_width * max_page_coverage && h > page_height * max_page_coverage {
+ return;
+ }
+
+ out.push(ImageBounds {
+ x: left,
+ y: page_height - top,
+ width: w,
+ height: h,
+ });
+}
+
/// Pre-computed affine transform from PDF page space to viewport space.
/// Avoids repeated FFI calls to `FPDF_PageToDevice` by probing 3 points
/// once and deriving the 6 affine coefficients.