Skip to main content

paper/core/extract/
ocr.rs

1//! OCR for scanned pages and standalone images.
2//!
3//! Engine: PaddleOCR PP-OCRv4 detection + recognition ONNX models
4//! (Apache-2.0), executed by `tract-onnx` — pure Rust, no C/C++ runtime and no
5//! system binaries. The ~16 MB of weights and the character dictionary are
6//! downloaded on first use, exactly like the embedding models.
7//!
8//! Why not Tesseract: it needs a C++ toolchain and a system library, which
9//! breaks the static musl build and the "one binary, no dependencies" promise.
10//! Why not `ocrs`: its weights inherit CC BY-SA 4.0 from HierText, which is
11//! copyleft and cannot be redistributed or auto-downloaded by this project.
12//!
13//! OCR is best-effort by design: a missing model, an unreadable page or a
14//! failed decode downgrades to "no text" and never fails an index run.
15
16use std::path::PathBuf;
17use std::sync::OnceLock;
18
19use anyhow::{anyhow, bail, Context, Result};
20use image::{DynamicImage, GenericImageView, RgbImage};
21use sha2::{Digest, Sha256};
22use tract_onnx::prelude::*;
23
24use super::{single, Block, ExtractedDocument, Extractor, MAX_EXTRACTED_BYTES};
25
26pub const DET_FILE: &str = "det.onnx";
27pub const REC_FILE: &str = "rec.onnx";
28pub const DICT_FILE: &str = "ppocr_keys_v1.txt";
29
30/// Detection input is a fixed square canvas; a single shape keeps `tract`
31/// fast and lets us cache one optimised plan for the whole process.
32const DET_SIDE: usize = 960;
33const REC_HEIGHT: u32 = 48;
34const REC_WIDTH: u32 = 960;
35/// Longest edge kept from a source image before OCR (memory/latency cap).
36const MAX_LONG_EDGE: u32 = 2000;
37const DET_PIXEL_THRESHOLD: f32 = 0.3;
38const DET_BOX_SCORE: f32 = 0.5;
39const DET_MIN_AREA: u32 = 6;
40/// DB outputs shrink by ~2x, so expand each box before cropping.
41const DET_UNCLIP_RATIO: f32 = 1.6;
42
43const MEAN: [f32; 3] = [0.485, 0.456, 0.406];
44const STD: [f32; 3] = [0.229, 0.224, 0.225];
45
46/// One recognised line of text.
47pub struct OcrLine {
48    pub text: String,
49    pub confidence: f32,
50}
51
52/// Where the OCR weights live: `$PAPER_HOME/models/paddleocr`.
53pub fn model_dir() -> PathBuf {
54    crate::core::paths::Paths::new()
55        .model_cache_dir()
56        .join("paddleocr")
57}
58
59/// True when every model file is on disk.
60pub fn models_present() -> bool {
61    let dir = model_dir();
62    dir.join(DET_FILE).is_file() && dir.join(REC_FILE).is_file() && dir.join(DICT_FILE).is_file()
63}
64
65/// OCR is on by default when the weights are here; `PAPER_NO_OCR=1` wins.
66pub fn available() -> bool {
67    if std::env::var("PAPER_NO_OCR").is_ok_and(|v| !v.is_empty() && v != "0") {
68        return false;
69    }
70    models_present()
71}
72
73/// Resolve whether a command should run OCR.
74pub fn enabled(explicit: bool) -> bool {
75    if std::env::var("PAPER_NO_OCR").is_ok_and(|v| !v.is_empty() && v != "0") {
76        return false;
77    }
78    explicit || models_present()
79}
80
81/// Recognise text in encoded image bytes (PNG, JPEG, TIFF, WebP, BMP, GIF).
82pub fn recognize_bytes(bytes: &[u8]) -> Result<String> {
83    let image = image::load_from_memory(bytes).context("decode image for OCR")?;
84    recognize_image(&image)
85}
86
87/// Recognise text in an already-decoded image.
88pub fn recognize_image(image: &DynamicImage) -> Result<String> {
89    let image = lift_small_image(&clamp_long_edge(image, MAX_LONG_EDGE), 1600);
90    let engine = engine()?;
91    let lines = engine.recognize(&image)?;
92    let mut text = lines
93        .into_iter()
94        .filter(|l| !l.text.trim().is_empty())
95        .map(|l| l.text)
96        .collect::<Vec<_>>()
97        .join("\n")
98        .trim()
99        .to_string();
100    if text.len() > MAX_EXTRACTED_BYTES {
101        let mut cut = MAX_EXTRACTED_BYTES;
102        while cut > 0 && !text.is_char_boundary(cut) {
103            cut -= 1;
104        }
105        text.truncate(cut);
106    }
107    Ok(text)
108}
109
110/// Bring very small images up to a size the detector can read.
111///
112/// A PDF page image saved at 72 dpi is often under 1000 px on the long edge,
113/// where thin letters and word gaps collapse. Upscaling costs little and
114/// measurably improves spacing; it never pretends to recover missing detail.
115fn lift_small_image(image: &DynamicImage, min_edge: u32) -> DynamicImage {
116    let (w, h) = image.dimensions();
117    let long = w.max(h);
118    if long == 0 || long >= min_edge {
119        return image.clone();
120    }
121    let factor = (min_edge as f32 / long as f32).ceil().clamp(1.0, 3.0);
122    let nw = (w as f32 * factor).round().max(1.0) as u32;
123    let nh = (h as f32 * factor).round().max(1.0) as u32;
124    image.resize(nw, nh, image::imageops::FilterType::Lanczos3)
125}
126
127fn clamp_long_edge(image: &DynamicImage, max_edge: u32) -> DynamicImage {
128    let (w, h) = image.dimensions();
129    let long = w.max(h);
130    if long <= max_edge || long == 0 {
131        return image.clone();
132    }
133    let scale = max_edge as f32 / long as f32;
134    let nw = ((w as f32 * scale).round() as u32).max(1);
135    let nh = ((h as f32 * scale).round() as u32).max(1);
136    image.resize(nw, nh, image::imageops::FilterType::Triangle)
137}
138
139static ENGINE: OnceLock<Result<PaddleEngine, String>> = OnceLock::new();
140
141fn engine() -> Result<&'static PaddleEngine> {
142    match ENGINE.get_or_init(|| PaddleEngine::load().map_err(|err| format!("{err:#}"))) {
143        Ok(engine) => Ok(engine),
144        Err(message) => Err(anyhow!("OCR engine unavailable: {message}")),
145    }
146}
147
148type Plan = std::sync::Arc<RunnableModel<TypedFact, Box<dyn TypedOp>>>;
149
150struct PaddleEngine {
151    det: Plan,
152    rec: Plan,
153    dict: Vec<String>,
154}
155
156impl PaddleEngine {
157    fn load() -> Result<Self> {
158        let dir = model_dir();
159        let det = load_plan(&dir.join(DET_FILE), [1, 3, DET_SIDE, DET_SIDE])
160            .context("load text-detection model")?;
161        let rec = load_plan(
162            &dir.join(REC_FILE),
163            [1, 3, REC_HEIGHT as usize, REC_WIDTH as usize],
164        )
165        .context("load text-recognition model")?;
166        let raw = std::fs::read_to_string(dir.join(DICT_FILE)).context("read OCR dictionary")?;
167        // PaddleOCR's CTC classes are `blank + dictionary + space`.
168        let mut dict = raw.lines().map(|line| line.to_string()).collect::<Vec<_>>();
169        dict.push(" ".to_string());
170        Ok(Self { det, rec, dict })
171    }
172}
173
174fn load_plan(path: &std::path::Path, shape: [usize; 4]) -> Result<Plan> {
175    if !path.is_file() {
176        bail!("missing model file {}", path.display());
177    }
178    let plan = tract_onnx::onnx()
179        .model_for_path(path)?
180        .with_input_fact(0, f32::fact(shape).into())?
181        .into_optimized()?
182        .into_runnable()?;
183    Ok(plan)
184}
185
186impl PaddleEngine {
187    fn recognize(&self, image: &DynamicImage) -> Result<Vec<OcrLine>> {
188        let (width, height) = image.dimensions();
189        if width == 0 || height == 0 {
190            return Ok(Vec::new());
191        }
192
193        // --- detection on a letterboxed 960x960 canvas -------------------
194        let scale = (DET_SIDE as f32 / width as f32).min(DET_SIDE as f32 / height as f32);
195        let scaled_w = ((width as f32 * scale).round() as u32).max(1);
196        let scaled_h = ((height as f32 * scale).round() as u32).max(1);
197        let resized = image
198            .resize_exact(scaled_w, scaled_h, image::imageops::FilterType::Triangle)
199            .to_rgb8();
200        let pad_x = (DET_SIDE as u32 - scaled_w) / 2;
201        let pad_y = (DET_SIDE as u32 - scaled_h) / 2;
202
203        let mut canvas = vec![1.0f32; 3 * DET_SIDE * DET_SIDE];
204        let plane = DET_SIDE * DET_SIDE;
205        for (x, y, px) in resized.enumerate_pixels() {
206            let cx = pad_x as usize + x as usize;
207            let cy = pad_y as usize + y as usize;
208            let idx = cy * DET_SIDE + cx;
209            for c in 0..3 {
210                let value = px.0[c] as f32 / 255.0;
211                canvas[c * plane + idx] = (value - MEAN[c]) / STD[c];
212            }
213        }
214        let input = Tensor::from_shape(&[1, 3, DET_SIDE, DET_SIDE], &canvas)?;
215        let outputs = self.det.run(tvec!(input.into()))?;
216        let probability = output_view(&outputs[0])?;
217        if probability.shape()[2] != DET_SIDE || probability.shape()[3] != DET_SIDE {
218            bail!(
219                "unexpected detection output shape {:?}",
220                probability.shape()
221            );
222        }
223
224        let boxes = detect_boxes(&probability);
225        if boxes.is_empty() {
226            return Ok(Vec::new());
227        }
228
229        let rgb = image.to_rgb8();
230        let mut lines = Vec::new();
231        for b in boxes {
232            // Map the box back through the letterbox transform.
233            let left = ((b.x0 as f32 - pad_x as f32) / scale).max(0.0);
234            let top = ((b.y0 as f32 - pad_y as f32) / scale).max(0.0);
235            let right = ((b.x1 as f32 - pad_x as f32) / scale).min(width as f32);
236            let bottom = ((b.y1 as f32 - pad_y as f32) / scale).min(height as f32);
237            let x = left.round() as u32;
238            let y = top.round() as u32;
239            let w = (right - left).round().max(1.0) as u32;
240            let h = (bottom - top).round().max(1.0) as u32;
241            if w < 4 || h < 4 || x >= width || y >= height {
242                continue;
243            }
244            let w = w.min(width - x);
245            let h = h.min(height - y);
246            let crop = image::imageops::crop_imm(&rgb, x, y, w, h).to_image();
247            let (text, confidence) = self.recognize_line(&crop)?;
248            if !text.trim().is_empty() {
249                lines.push(OcrLine { text, confidence });
250            }
251        }
252        Ok(lines)
253    }
254
255    fn recognize_line(&self, crop: &RgbImage) -> Result<(String, f32)> {
256        let (cw, ch) = crop.dimensions();
257        let ratio = cw as f32 / ch.max(1) as f32;
258        // Preserve the aspect ratio and pad the canvas, never squash it: a long
259        // line forced into a narrow width loses spaces and thin letters, which
260        // is exactly the damage that makes OCR output uncitable.
261        let wanted_w = (REC_HEIGHT as f32 * ratio).round().max(8.0) as u32;
262        let (rw, rh) = if wanted_w <= REC_WIDTH {
263            (wanted_w.max(1), REC_HEIGHT)
264        } else {
265            let scaled_h = ((REC_HEIGHT as f32 * REC_WIDTH as f32 / wanted_w as f32).round()
266                as u32)
267                .clamp(1, REC_HEIGHT);
268            (REC_WIDTH, scaled_h)
269        };
270        let resized = image::imageops::resize(crop, rw, rh, image::imageops::FilterType::Triangle);
271
272        let plane = (REC_HEIGHT as usize) * (REC_WIDTH as usize);
273        // Padding is a black pixel after normalisation: (0/255 - 0.5) / 0.5.
274        let mut data = vec![-1.0f32; 3 * plane];
275        for (x, y, px) in resized.enumerate_pixels() {
276            let idx = y as usize * REC_WIDTH as usize + x as usize;
277            for c in 0..3 {
278                let value = px.0[c] as f32 / 255.0;
279                data[c * plane + idx] = (value - 0.5) / 0.5;
280            }
281        }
282        let input = Tensor::from_shape(&[1, 3, REC_HEIGHT as usize, REC_WIDTH as usize], &data)?;
283        let outputs = self.rec.run(tvec!(input.into()))?;
284        let probabilities = output_view(&outputs[0])?;
285        let shape = probabilities.shape();
286        let (steps, classes) = (shape[1], shape[2]);
287
288        let mut text = String::new();
289        let mut score_sum = 0.0f32;
290        let mut score_n = 0usize;
291        let mut previous = usize::MAX;
292        for step in 0..steps {
293            let mut best = 0usize;
294            let mut best_p = 0.0f32;
295            for class in 0..classes {
296                let p = probabilities[[0, step, class]];
297                if p > best_p {
298                    best_p = p;
299                    best = class;
300                }
301            }
302            if best == 0 || best == previous {
303                previous = best;
304                continue;
305            }
306            previous = best;
307            if let Some(ch) = self.dict.get(best - 1) {
308                text.push_str(ch);
309                score_sum += best_p;
310                score_n += 1;
311            }
312        }
313        let confidence = if score_n == 0 {
314            0.0
315        } else {
316            score_sum / score_n as f32
317        };
318        Ok((text, confidence))
319    }
320}
321
322struct DecodedBox {
323    x0: i32,
324    y0: i32,
325    x1: i32,
326    y1: i32,
327}
328
329/// Connected components over the detection probability map, converted to
330/// reading-ordered boxes. This is the DB post-process, simplified: rectangles
331/// are close enough for document scans and avoid a polygon-offset dependency.
332/// Borrow a run output as an ndarray view for shape-aware indexing.
333fn output_view<'a>(value: &'a TValue) -> Result<tract_ndarray::ArrayViewD<'a, f32>> {
334    let view = value.view();
335    let slice = view.as_slice::<f32>()?;
336    Ok(tract_ndarray::ArrayViewD::from_shape(view.shape(), slice)?)
337}
338
339fn detect_boxes(probability: &tract_ndarray::ArrayViewD<f32>) -> Vec<DecodedBox> {
340    const SIDE: usize = DET_SIDE;
341    let mut mask = vec![false; SIDE * SIDE];
342    for y in 0..SIDE {
343        for x in 0..SIDE {
344            mask[y * SIDE + x] = probability[[0, 0, y, x]] >= DET_PIXEL_THRESHOLD;
345        }
346    }
347
348    let mut labels = vec![0u32; SIDE * SIDE];
349    let mut boxes: Vec<(i32, i32, i32, i32, u32, f32)> = Vec::new();
350    let mut next_label = 1u32;
351    let mut stack = Vec::new();
352
353    for start in 0..SIDE * SIDE {
354        if !mask[start] || labels[start] != 0 {
355            continue;
356        }
357        let label = next_label;
358        next_label += 1;
359        stack.clear();
360        stack.push(start);
361        labels[start] = label;
362
363        let (mut min_x, mut min_y, mut max_x, mut max_y) = (SIDE as i32, SIDE as i32, -1i32, -1i32);
364        let mut area = 0u32;
365        let mut score = 0.0f32;
366
367        while let Some(index) = stack.pop() {
368            let y = index / SIDE;
369            let x = index % SIDE;
370            area += 1;
371            score += probability[[0, 0, y, x]];
372            min_x = min_x.min(x as i32);
373            max_x = max_x.max(x as i32);
374            min_y = min_y.min(y as i32);
375            max_y = max_y.max(y as i32);
376
377            let neighbours = [
378                (x.wrapping_sub(1), y),
379                (x + 1, y),
380                (x, y.wrapping_sub(1)),
381                (x, y + 1),
382                (x.wrapping_sub(1), y.wrapping_sub(1)),
383                (x + 1, y.wrapping_sub(1)),
384                (x.wrapping_sub(1), y + 1),
385                (x + 1, y + 1),
386            ];
387            for (nx, ny) in neighbours {
388                if nx < SIDE && ny < SIDE {
389                    let ni = ny * SIDE + nx;
390                    if mask[ni] && labels[ni] == 0 {
391                        labels[ni] = label;
392                        stack.push(ni);
393                    }
394                }
395            }
396        }
397
398        if area < DET_MIN_AREA {
399            continue;
400        }
401        let mean = score / area as f32;
402        if mean < DET_BOX_SCORE {
403            continue;
404        }
405
406        let w = (max_x - min_x + 1) as f32;
407        let h = (max_y - min_y + 1) as f32;
408        if w < 3.0 || h < 3.0 {
409            continue;
410        }
411        let delta = ((w * h * DET_UNCLIP_RATIO) / (2.0 * (w + h))).ceil() as i32;
412        boxes.push((
413            min_x - delta,
414            min_y - delta,
415            max_x + delta,
416            max_y + delta,
417            area,
418            mean,
419        ));
420    }
421
422    boxes.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
423    boxes
424        .into_iter()
425        .map(|(x0, y0, x1, y1, _, _)| DecodedBox {
426            x0: x0.clamp(0, SIDE as i32 - 1),
427            y0: y0.clamp(0, SIDE as i32 - 1),
428            x1: x1.clamp(0, SIDE as i32 - 1),
429            y1: y1.clamp(0, SIDE as i32 - 1),
430        })
431        .collect()
432}
433
434/// Extractor for standalone images. Registered only while the OCR weights are
435/// present, so a keyword-only or model-less install does not claim to support
436/// images it cannot read.
437pub struct ImageOcr;
438
439const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "webp", "bmp", "gif"];
440
441impl Extractor for ImageOcr {
442    fn name(&self) -> &'static str {
443        "image-ocr"
444    }
445
446    fn extensions(&self) -> &'static [&'static str] {
447        if models_present() {
448            IMAGE_EXTENSIONS
449        } else {
450            &[]
451        }
452    }
453
454    fn sniff(&self, bytes: &[u8]) -> bool {
455        models_present() && looks_like_image(bytes)
456    }
457
458    fn capabilities(&self) -> super::Capabilities {
459        super::Capabilities {
460            max_file_bytes: 25 * 1024 * 1024,
461            max_pages: 1,
462            max_entries: 1,
463            streaming: false,
464            thread_safe: true,
465            requires_external: false,
466        }
467    }
468
469    fn extract(&self, name: &str, bytes: &[u8]) -> Result<Option<Vec<ExtractedDocument>>> {
470        if !models_present() {
471            return Ok(None);
472        }
473        let text = match recognize_bytes(bytes) {
474            Ok(text) => text,
475            Err(err) => {
476                return Ok(Some(single(
477                    name,
478                    "image-ocr",
479                    Vec::new(),
480                    vec![format!("OCR failed: {err:#}")],
481                )))
482            }
483        };
484        if text.trim().is_empty() {
485            return Ok(Some(single(
486                name,
487                "image-ocr",
488                Vec::new(),
489                vec!["no text recognised in image".to_string()],
490            )));
491        }
492        let line_end = text.lines().count().max(1) as i64;
493        Ok(Some(single(
494            name,
495            "image-ocr",
496            vec![Block {
497                text,
498                page: 1,
499                anchor: Some("image (OCR)".to_string()),
500                section: Some("OCR".to_string()),
501                line_start: 1,
502                line_end,
503            }],
504            Vec::new(),
505        )))
506    }
507}
508
509fn looks_like_image(bytes: &[u8]) -> bool {
510    bytes.starts_with(b"\x89PNG\r\n\x1a\n")
511        || bytes.starts_with(&[0xFF, 0xD8, 0xFF])
512        || bytes.starts_with(b"GIF87a")
513        || bytes.starts_with(b"GIF89a")
514        || bytes.starts_with(b"II*\x00")
515        || bytes.starts_with(b"MM\x00*")
516        || (bytes.len() > 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
517        || bytes.starts_with(b"BM")
518}
519
520/// Model files, with the SHA-256 of the exact bytes we ship against.
521///
522/// Pinning the hash means a compromised or mutated upstream mirror cannot feed
523/// the OCR engine different weights than the ones this release was tested with.
524const MODEL_FILES: [(&str, &str, u64, &str); 3] = [
525    (
526        DET_FILE,
527        "d2a7720d45a54257208b1e13e36a8479894cb74155a5efe29462512d42f49da9",
528        4_745_517,
529        "https://huggingface.co/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_PP-OCRv4_det_infer.onnx",
530    ),
531    (
532        REC_FILE,
533        "48fc40f24f6d2a207a2b1091d3437eb3cc3eb6b676dc3ef9c37384005483683b",
534        10_857_958,
535        "https://huggingface.co/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_PP-OCRv4_rec_infer.onnx",
536    ),
537    (
538        DICT_FILE,
539        "a1c84d9bdb9ab29043c58896224d32941783eb821629618416dcb08f12886492",
540        26_250,
541        "https://raw.githubusercontent.com/PaddlePaddle/PaddleOCR/main/ppocr/utils/ppocr_keys_v1.txt",
542    ),
543];
544
545/// Download any missing OCR weights into [`model_dir`].
546///
547/// Called from the first-run bootstrap, so OCR is available without the user
548/// knowing a model exists — the same contract as the embedding models. Offline
549/// runs return an error and OCR silently stays disabled for that run.
550pub async fn ensure_models() -> Result<()> {
551    if models_present() {
552        return Ok(());
553    }
554    if offline() {
555        bail!("OCR models are missing and PAPER_OFFLINE is set");
556    }
557    let dir = model_dir();
558    tokio::fs::create_dir_all(&dir).await?;
559    let client = reqwest::Client::builder()
560        .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
561        .build()?;
562    for (name, expected, size, url) in MODEL_FILES {
563        let dest = dir.join(name);
564        if dest.is_file() && sha256_of(&dest).ok().as_deref() == Some(expected) {
565            continue;
566        }
567        tracing::info!("downloading OCR model {name} ({size} bytes)");
568        let bytes = client
569            .get(url)
570            .send()
571            .await
572            .with_context(|| format!("download {url}"))?
573            .error_for_status()
574            .with_context(|| format!("download {url}"))?
575            .bytes()
576            .await
577            .with_context(|| format!("read {url}"))?;
578        if bytes.len() as u64 != size {
579            bail!(
580                "{name}: expected {size} bytes from {url}, received {}",
581                bytes.len()
582            );
583        }
584        let digest = hex::encode(Sha256::digest(&bytes));
585        if digest != expected {
586            bail!("{name}: checksum mismatch (expected {expected}, got {digest})");
587        }
588        // Write via a temporary file so an interrupted download can never be
589        // mistaken for a complete model by the next run.
590        let tmp = dest.with_extension("part");
591        tokio::fs::write(&tmp, &bytes).await?;
592        tokio::fs::rename(&tmp, &dest).await?;
593    }
594    Ok(())
595}
596
597fn offline() -> bool {
598    std::env::var_os("PAPER_OFFLINE")
599        .map(|value| !value.is_empty() && value != "0")
600        .unwrap_or(false)
601}
602
603fn sha256_of(path: &std::path::Path) -> Result<String> {
604    use std::io::Read;
605    let mut file = std::fs::File::open(path)?;
606    let mut hasher = Sha256::new();
607    let mut buffer = [0u8; 64 * 1024];
608    loop {
609        let read = file.read(&mut buffer)?;
610        if read == 0 {
611            break;
612        }
613        hasher.update(&buffer[..read]);
614    }
615    Ok(hex::encode(hasher.finalize()))
616}
617
618#[cfg(test)]
619mod tests {
620
621    use super::*;
622
623    #[test]
624    fn image_magic_is_recognised() {
625        assert!(looks_like_image(b"\x89PNG\r\n\x1a\nrest"));
626        assert!(looks_like_image(&[0xFF, 0xD8, 0xFF, 0xE0]));
627        assert!(!looks_like_image(b"%PDF-1.7"));
628    }
629
630    #[test]
631    fn extensions_hidden_without_models() {
632        // The test environment has no weights, so the extractor must not
633        // advertise image support.
634        if !models_present() {
635            assert!(ImageOcr.extensions().is_empty());
636        }
637    }
638}