Skip to content

A fast, helpful, and open-source document parser

perf: OCR page bitmaps in grayscale for engines that binarize internally

jmho1bb8010188d3
diff --git a/crates/liteparse/src/ocr/mod.rs b/crates/liteparse/src/ocr/mod.rs
index 05026e1..b860b11 100644
--- a/crates/liteparse/src/ocr/mod.rs
+++ b/crates/liteparse/src/ocr/mod.rs
@@ -37,6 +37,11 @@ pub struct OcrOptions {
#[cfg(not(target_arch = "wasm32"))]
pub trait OcrEngine: Send + Sync {
fn name(&self) -> &str;
+ /// Whether this engine prefers a single-channel grayscale buffer: engines
+ /// that binarize internally (Tesseract) do; color-trained engines want RGB.
+ fn prefers_grayscale(&self) -> bool {
+ false
+ }
fn recognize<'a, 'b: 'a, 'c: 'a>(
&'a self,
image_data: &'c [u8],
@@ -55,6 +60,11 @@ pub trait OcrEngine: Send + Sync {
#[cfg(target_arch = "wasm32")]
pub trait OcrEngine: Send + Sync {
fn name(&self) -> &str;
+ /// Whether this engine prefers a single-channel grayscale buffer: engines
+ /// that binarize internally (Tesseract) do; color-trained engines want RGB.
+ fn prefers_grayscale(&self) -> bool {
+ false
+ }
fn recognize<'a, 'b: 'a, 'c: 'a>(
&'a self,
image_data: &'c [u8],
diff --git a/crates/liteparse/src/ocr/tesseract.rs b/crates/liteparse/src/ocr/tesseract.rs
index 14aa814..c41570f 100644
--- a/crates/liteparse/src/ocr/tesseract.rs
+++ b/crates/liteparse/src/ocr/tesseract.rs
@@ -42,6 +42,12 @@ impl OcrEngine for TesseractOcrEngine {
"tesseract"
}
+ // Tesseract binarizes internally (Leptonica/Otsu on luma), so a grayscale
+ // buffer is equivalent input at a third of the memory.
+ fn prefers_grayscale(&self) -> bool {
+ true
+ }
+
fn recognize<'a, 'b: 'a, 'c: 'a>(
&'a self,
image_data: &'c [u8],
@@ -76,8 +82,12 @@ impl OcrEngine for TesseractOcrEngine {
// uniform block of text and performs poorly on full-page layouts.
api.set_page_seg_mode(TessPageSegMode::PSM_AUTO)?;
- // Set image from raw RGB bytes (3 bytes per pixel)
- let bytes_per_pixel = 3;
+ // Channels inferred from the buffer: 1 = grayscale, 3 = RGB.
+ let bytes_per_pixel = if width > 0 && height > 0 {
+ (image_data.len() / (width as usize * height as usize)).clamp(1, 4) as i32
+ } else {
+ 3
+ };
let bytes_per_line = width as i32 * bytes_per_pixel;
api.set_image(
image_data,
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index da58813..bd4c532 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -17,7 +17,8 @@ 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 {
pub idx: usize,
- pub rgb_bytes: Vec<u8>,
+ /// Tightly-packed pixels: 1 byte/px (grayscale) or 3 (RGB).
+ pub pixels: Vec<u8>,
pub width: u32,
pub height: u32,
}
@@ -30,6 +31,7 @@ pub(crate) fn render_pages_for_ocr(
document: &Document,
pages: &[Page],
dpi: f32,
+ grayscale: bool,
) -> Result<Vec<RenderedPage>, LiteParseError> {
let mut rendered = Vec::new();
for (idx, page) in pages.iter().enumerate() {
@@ -87,13 +89,16 @@ pub(crate) fn render_pages_for_ocr(
let bitmap = page_obj.render(dpi)?;
let width = bitmap.width() as u32;
let height = bitmap.height() as u32;
- // RGB is what OCR consumes; converting straight from BGRA avoids an
- // intermediate full-frame RGBA buffer per page.
- let rgb_bytes = bitmap.to_rgb();
+ // Grayscale or RGB per the engine; see `OcrEngine::prefers_grayscale`.
+ let pixels = if grayscale {
+ bitmap.to_luma()
+ } else {
+ bitmap.to_rgb()
+ };
rendered.push(RenderedPage {
idx,
- rgb_bytes,
+ pixels,
width,
height,
});
@@ -149,7 +154,7 @@ pub(crate) async fn ocr_and_merge_rendered(
// leaving the rest of the pool free for the HTTP client's
// internal DNS resolution.
match tokio::task::spawn_blocking(move || {
- rt_handle.block_on(engine.recognize(&r.rgb_bytes, r.width, r.height, &options))
+ rt_handle.block_on(engine.recognize(&r.pixels, r.width, r.height, &options))
})
.await
{
@@ -743,8 +748,8 @@ mod tests {
fn make_rendered(idx: usize) -> RenderedPage {
RenderedPage {
idx,
- // 1x1 RGB pixel; the engine never inspects it.
- rgb_bytes: vec![0u8, 0u8, 0u8],
+ // 1x1 grayscale pixel; the engine never inspects it.
+ pixels: vec![0u8],
width: 1,
height: 1,
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index e345a30..c4e35b4 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -128,6 +128,45 @@ impl LiteParse {
// concurrently with other `LiteParse` calls.
let password = self.config.password.as_deref();
let render_images = matches!(self.config.image_mode, crate::config::ImageMode::Embed);
+
+ // Build the OCR engine up front so the renderer knows whether to emit a
+ // grayscale buffer (cheaper, for engines that binarize internally) or RGB.
+ let ocr_engine: Option<std::sync::Arc<dyn OcrEngine>> = if self.config.ocr_enabled {
+ Some(if let Some(e) = self.ocr_engine_override.clone() {
+ e
+ } else {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ if let Some(ref url) = self.config.ocr_server_url {
+ std::sync::Arc::new(HttpOcrEngine::with_headers(
+ url.clone(),
+ self.config.ocr_server_headers.clone(),
+ ))
+ } else {
+ #[cfg(feature = "tesseract")]
+ {
+ std::sync::Arc::new(TesseractOcrEngine::new(
+ self.config.tessdata_path.clone(),
+ ))
+ }
+ #[cfg(not(feature = "tesseract"))]
+ {
+ return Err("OCR enabled but no --ocr-server-url provided and tesseract feature is disabled".into());
+ }
+ }
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ return Err(
+ "OCR enabled but no `ocrEngine` callback was provided (WASM builds have no built-in OCR engine)".into(),
+ );
+ }
+ })
+ } else {
+ None
+ };
+ let ocr_grayscale = ocr_engine.as_ref().is_some_and(|e| e.prefers_grayscale());
+
let (pages, ocr_rendered, outline, images) = {
let lib = Library::init();
let document = extract::load_document_from_input(&lib, &validated_input, password)?;
@@ -147,7 +186,12 @@ impl LiteParse {
pages.len()
));
let rendered = if self.config.ocr_enabled {
- let r = ocr_merge::render_pages_for_ocr(&document, &pages, self.config.dpi)?;
+ let r = ocr_merge::render_pages_for_ocr(
+ &document,
+ &pages,
+ self.config.dpi,
+ ocr_grayscale,
+ )?;
log(&format!(
"[liteparse] ocr render: {:.1}ms ({} pages)",
web_time::Instant::now()
@@ -166,40 +210,8 @@ impl LiteParse {
let mut pages = pages;
let t1 = web_time::Instant::now();
- // OCR pass
- if self.config.ocr_enabled {
- let engine: std::sync::Arc<dyn OcrEngine> = if let Some(e) =
- self.ocr_engine_override.clone()
- {
- e
- } else {
- #[cfg(not(target_arch = "wasm32"))]
- {
- if let Some(ref url) = self.config.ocr_server_url {
- std::sync::Arc::new(HttpOcrEngine::with_headers(
- url.clone(),
- self.config.ocr_server_headers.clone(),
- ))
- } else {
- #[cfg(feature = "tesseract")]
- {
- std::sync::Arc::new(TesseractOcrEngine::new(
- self.config.tessdata_path.clone(),
- ))
- }
- #[cfg(not(feature = "tesseract"))]
- {
- return Err("OCR enabled but no --ocr-server-url provided and tesseract feature is disabled".into());
- }
- }
- }
- #[cfg(target_arch = "wasm32")]
- {
- return Err(
- "OCR enabled but no `ocrEngine` callback was provided (WASM builds have no built-in OCR engine)".into(),
- );
- }
- };
+ // OCR pass (engine resolved before the render block above).
+ if let Some(engine) = ocr_engine {
ocr_merge::ocr_and_merge_rendered(
&mut pages,
ocr_rendered,
diff --git a/crates/pdfium/src/bitmap.rs b/crates/pdfium/src/bitmap.rs
index 2d4833f..e96b466 100644
--- a/crates/pdfium/src/bitmap.rs
+++ b/crates/pdfium/src/bitmap.rs
@@ -137,6 +137,26 @@ impl<'lib> Bitmap<'lib> {
rgb
}
+
+ /// Convert the BGRA buffer to tightly-packed 8-bit grayscale (1 byte/px)
+ /// using Rec. 601 luma weights.
+ pub fn to_luma(&self) -> Vec<u8> {
+ let width = self.width() as usize;
+ let height = self.height() as usize;
+ let stride = self.stride() as usize;
+ let src = self.buffer();
+ let mut luma = Vec::with_capacity(width * height);
+
+ for y in 0..height {
+ let row = &src[y * stride..y * stride + width * 4];
+ for pixel in row.chunks_exact(4) {
+ let (b, g, r) = (pixel[0] as u32, pixel[1] as u32, pixel[2] as u32);
+ luma.push(((77 * r + 150 * g + 29 * b) >> 8) as u8);
+ }
+ }
+
+ luma
+ }
}
impl Drop for Bitmap<'_> {