Skip to main content

docling_pdf/
picture.rs

1//! OCR for a standalone picture (#645): the text the recognizer reads off an
2//! image embedded in a non-PDF document — a DOCX/PPTX screenshot, an HTML
3//! figure, a sampled video frame — so the picture-OCR enrichment in
4//! `docling` can attach it to the picture as docling's description
5//! annotation. The models are the ML pipeline's own (the recognizer pair,
6//! the text detector, Tesseract under `ocr_engine`), loaded lazily on the
7//! first picture exactly as they are for a scanned page, so a converter that
8//! OCRs pictures and scans alike holds one set of sessions.
9//!
10//! The picture is treated as the image input `Pipeline::convert_image` sees:
11//! its own scale-1.0 page whose one text region is the whole image, read at
12//! docling's effective OCR resolution for images (3 px/pt shrunk to
13//! RapidOCR's 2000 px longer side, #570) — no layout pass, since the caller
14//! already knows the whole image is the picture. The detector's boxes are
15//! the line crops when `ocr_det.onnx` is installed (#570); the ink-projection
16//! strips otherwise. Lines under `DOCLING_RS_OCR_TEXT_SCORE` are dropped by
17//! the recognizer, as on a page.
18
19use image::RgbImage;
20
21use crate::layout::Region;
22use docling_core::{Node, PictureDescription};
23
24use crate::pdfium_backend::{PdfPage, TextCell};
25use crate::{ocr, ocr_input, page_ocr_scale, EnrichSlot, PdfError, Pipeline, RAPIDOCR_MAX_SIDE};
26
27/// What the OCR read off one picture: the lines in reading order (top to
28/// bottom, left to right within a row, rows joined by `\n`) and the engine
29/// that read them — docling's `PictureDescriptionData.provenance`.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct PictureText {
32    pub text: String,
33    /// `ppocr` or `tesseract` — the [`ocr::OcrEngine`] that ran.
34    pub provenance: &'static str,
35}
36
37impl Pipeline {
38    /// Decode an embedded picture's bytes (PNG/JPEG/GIF/BMP/TIFF/WebP) under
39    /// the standalone-image pixel cap (`DOCLING_RS_MAX_IMAGE_PIXELS`, 30000
40    /// per side) — a crafted header never allocates a multi-GB bitmap.
41    pub fn decode_picture(&self, bytes: &[u8]) -> Result<RgbImage, PdfError> {
42        crate::decode_image_limited(bytes)
43    }
44
45    /// The DocumentFigureClassifier's predictions for a picture (descending
46    /// confidence), loading the model on first use. `None` when the model is
47    /// not installed (warned once by the loader) or inference failed — the
48    /// caller decides what an unclassifiable picture means (the picture-OCR
49    /// class filter lets it through).
50    pub fn classify_picture(&mut self, img: &RgbImage) -> Option<Vec<docling_core::PictureClass>> {
51        let mut guard = self.classifier.lock().unwrap_or_else(|p| p.into_inner());
52        if matches!(*guard, EnrichSlot::Unloaded) {
53            *guard = match crate::enrich::PictureClassifier::load_with(crate::intra_threads()) {
54                Some(m) => EnrichSlot::Ready(m),
55                None => EnrichSlot::Missing,
56            };
57        }
58        let EnrichSlot::Ready(model) = &mut *guard else {
59            return None;
60        };
61        match model.classify(img) {
62            Ok(classes) => Some(classes),
63            Err(e) => {
64                eprintln!("docling-pdf: picture classifier: {e}");
65                None
66            }
67        }
68    }
69
70    /// OCR a picture: `Ok(None)` when the engine read no text (or could not
71    /// load — the recognizer's one-time warning says so, and `skip_ocr`
72    /// short-circuits without one), `Err` only for a failed inference.
73    pub fn ocr_picture(&mut self, img: &RgbImage) -> Result<Option<PictureText>, PdfError> {
74        let provenance = match self.ocr_engine {
75            ocr::OcrEngine::PpOcr => "ppocr",
76            ocr::OcrEngine::Tesseract => "tesseract",
77        };
78        let (w, h) = (img.width() as f32, img.height() as f32);
79        if w < 1.0 || h < 1.0 {
80            return Ok(None);
81        }
82        // The image is its own page at 1 px per point; the OCR reads it at
83        // `picture_ocr_scale` under RapidOCR's 2000 px cap (#666), else at
84        // docling's image resolution unless `ocr_scale` says otherwise.
85        let ocr_scale = match self.picture_ocr_scale {
86            Some(p) => picture_ocr_scale(p, w, h),
87            None => page_ocr_scale(self.ocr_scale, w, h, 1.0),
88        };
89        let mut cache = None;
90        let (view, scale) = ocr_input(&mut cache, img, 1.0, ocr_scale);
91        let region = Region {
92            label: "text",
93            score: 1.0,
94            l: 0.0,
95            t: 0.0,
96            r: w,
97            b: h,
98        };
99        let worker = self.primary()?;
100        let detected = worker
101            .with_det(|det| det.detect(view))
102            .transpose()
103            .map_err(PdfError::Ocr)?;
104        let Some(model) = worker.ocr_model()? else {
105            return Ok(None);
106        };
107        let cells = model
108            .ocr_page_with(
109                view,
110                std::slice::from_ref(&region),
111                scale,
112                detected.as_deref(),
113            )
114            .map_err(PdfError::Ocr)?;
115        let text = lines_text(cells.into_iter().map(|(c, _)| c).collect());
116        Ok((!text.is_empty()).then_some(PictureText { text, provenance }))
117    }
118}
119
120/// The px/px a picture reads at under `picture_ocr_scale` = `p` (#666):
121/// `p`, shrunk so the longer side stays within RapidOCR's 2000 px
122/// (`max_side_len`) — at `1.0`, RapidOCR's own rule: native pixels, only
123/// shrinking what exceeds the cap. `None` when that is the picture's own
124/// resolution (no resample).
125fn picture_ocr_scale(p: f32, w: f32, h: f32) -> Option<f32> {
126    let s = p.min(RAPIDOCR_MAX_SIDE / w.max(h));
127    ((s - 1.0).abs() > 1e-3).then_some(s)
128}
129
130/// Join OCR line cells into text in reading order: rows top to bottom, cells
131/// left to right within a row. A cell joins the row whose vertical extent
132/// contains its centre — two columns of a screenshot's dialog read across,
133/// the way a human scans it; a line that sits lower starts a new row. Empty
134/// cells are dropped.
135pub(crate) fn lines_text(mut cells: Vec<TextCell>) -> String {
136    cells.retain(|c| !c.text.trim().is_empty());
137    cells.sort_by(|a, b| a.t.total_cmp(&b.t).then(a.l.total_cmp(&b.l)));
138    let mut rows: Vec<(f32, f32, Vec<TextCell>)> = Vec::new();
139    for cell in cells {
140        let mid = (cell.t + cell.b) / 2.0;
141        match rows.last_mut() {
142            Some((t, b, row)) if mid >= *t && mid <= *b => {
143                *t = t.min(cell.t);
144                *b = b.max(cell.b);
145                row.push(cell);
146            }
147            _ => rows.push((cell.t, cell.b, vec![cell])),
148        }
149    }
150    rows.iter_mut()
151        .map(|(_, _, row)| {
152            row.sort_by(|a, b| a.l.total_cmp(&b.l));
153            row.iter()
154                .map(|c| c.text.trim())
155                .collect::<Vec<_>>()
156                .join(" ")
157        })
158        .collect::<Vec<_>>()
159        .join("\n")
160}
161
162/// Whether an OCR line belongs to a picture (#1219): its centre lies inside
163/// the picture's box.
164pub(crate) fn text_inside(c: &TextCell, r: &Region) -> bool {
165    let (cx, cy) = ((c.l + c.r) / 2.0, (c.t + c.b) / 2.0);
166    cx >= r.l && cx <= r.r && cy >= r.t && cy <= r.b
167}
168
169/// Hang a text-layer page's in-picture OCR lines (#1219, `picture_ocr`) on
170/// the assembled pictures as docling's `description` annotation — the
171/// shape the picture OCR of the other formats writes. The pictures carry
172/// only their 0–511 `location` by now, so each is matched back by that box
173/// (widened by one grid step for the rounding); a line inside two nested
174/// pictures goes to the smaller one. Pictures inside table cells are
175/// reached too; a picture that already has a description keeps it.
176pub(crate) fn describe_pictures(
177    nodes: &mut [Node],
178    page: &PdfPage,
179    cells: &[TextCell],
180    provenance: &str,
181) {
182    let (w, h) = (page.width.max(1.0), page.height.max(1.0));
183    let to_region = |loc: &[u16; 4]| {
184        let x = |v: u16| v as f32 * w / 512.0;
185        let y = |v: u16| v as f32 * h / 512.0;
186        Region {
187            label: "picture",
188            score: 1.0,
189            l: x(loc[0].saturating_sub(1)),
190            t: y(loc[1].saturating_sub(1)),
191            r: x(loc[2].saturating_add(1)),
192            b: y(loc[3].saturating_add(1)),
193        }
194    };
195    // Every picture's box, in document order, to settle the nesting.
196    let mut boxes: Vec<Region> = Vec::new();
197    visit_pictures(nodes, &mut |loc, _| boxes.push(to_region(loc)));
198    let area = |r: &Region| (r.r - r.l) * (r.b - r.t);
199    let owner: Vec<Option<usize>> = cells
200        .iter()
201        .map(|c| {
202            (0..boxes.len())
203                .filter(|&i| text_inside(c, &boxes[i]))
204                .min_by(|&a, &b| area(&boxes[a]).total_cmp(&area(&boxes[b])))
205        })
206        .collect();
207    let mut i = 0usize;
208    visit_pictures(nodes, &mut |_, description| {
209        let mine: Vec<TextCell> = cells
210            .iter()
211            .zip(&owner)
212            .filter(|(_, o)| **o == Some(i))
213            .map(|(c, _)| c.clone())
214            .collect();
215        i += 1;
216        if description.is_some() {
217            return;
218        }
219        let text = lines_text(mine);
220        if !text.is_empty() {
221            *description = Some(PictureDescription {
222                text,
223                provenance: provenance.to_string(),
224            });
225        }
226    });
227}
228
229/// Every located picture under `nodes`, page level and inside table cells,
230/// in document order.
231fn visit_pictures(
232    nodes: &mut [Node],
233    f: &mut dyn FnMut(&[u16; 4], &mut Option<PictureDescription>),
234) {
235    for node in nodes {
236        match node {
237            Node::Located { location, inner } => match inner.as_mut() {
238                Node::Picture { description, .. } => f(location, description),
239                other => visit_pictures(std::slice::from_mut(other), f),
240            },
241            Node::Table(t) => {
242                let Some(blocks) = t.cell_blocks.as_mut() else {
243                    continue;
244                };
245                for row in blocks.iter_mut() {
246                    for cell in row.iter_mut() {
247                        visit_pictures(cell, f);
248                    }
249                }
250            }
251            Node::Group { children, .. } | Node::PictureChildren(children) => {
252                visit_pictures(children, f)
253            }
254            _ => {}
255        }
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    fn cell(text: &str, l: f32, t: f32, r: f32, b: f32) -> TextCell {
264        TextCell {
265            text: text.into(),
266            l,
267            t,
268            r,
269            b,
270        }
271    }
272
273    /// #1219: each OCR line goes to the picture whose box holds its centre
274    /// — the smaller of two nested ones, a picture inside a table cell too —
275    /// and a picture that already has a description keeps it.
276    #[test]
277    fn describe_pictures_matches_lines_by_box() {
278        use docling_core::{CaptionParent, Table};
279        let pic = |loc: [u16; 4], description: Option<PictureDescription>| Node::Located {
280            location: loc,
281            inner: Box::new(Node::Picture {
282                caption: None,
283                caption_href: None,
284                image: None,
285                classification: None,
286                description,
287                caption_parent: CaptionParent::default(),
288                caption_location: None,
289            }),
290        };
291        // A 512 × 512 pt page: grid units are points.
292        let page = PdfPage::from_cells(512.0, 512.0, 2.0, Vec::new());
293        let table = Node::Table(Table {
294            cell_blocks: Some(vec![vec![vec![pic([300, 300, 400, 400], None)]]]),
295            ..Table::default()
296        });
297        let kept = PictureDescription {
298            text: "alt".into(),
299            provenance: PictureDescription::ALT_TEXT.into(),
300        };
301        let mut nodes = vec![
302            pic([0, 0, 200, 200], None),
303            pic([50, 50, 100, 100], None),
304            table,
305            pic([450, 0, 500, 50], Some(kept.clone())),
306        ];
307        let cells = [
308            cell("outer", 10.0, 10.0, 40.0, 20.0),
309            cell("inner", 60.0, 60.0, 90.0, 70.0),
310            cell("in table", 310.0, 310.0, 390.0, 320.0),
311            cell("ignored", 455.0, 5.0, 495.0, 15.0),
312            cell("nowhere", 250.0, 250.0, 260.0, 260.0),
313        ];
314        describe_pictures(&mut nodes, &page, &cells, "ppocr");
315        let mut got = Vec::new();
316        visit_pictures(&mut nodes, &mut |_, d| got.push(d.clone().map(|d| d.text)));
317        assert_eq!(
318            got,
319            [
320                Some("outer".to_string()),
321                Some("inner".to_string()),
322                Some("in table".to_string()),
323                Some("alt".to_string()),
324            ]
325        );
326    }
327
328    /// Rows read across, then down; a cell whose centre sits below the
329    /// current row starts a new one, and empty cells vanish.
330    #[test]
331    fn lines_text_reads_rows_across_then_down() {
332        let cells = vec![
333            cell("right", 200.0, 10.0, 260.0, 30.0),
334            cell("below", 10.0, 40.0, 80.0, 60.0),
335            cell("left", 10.0, 12.0, 60.0, 32.0),
336            cell("  ", 10.0, 70.0, 20.0, 80.0),
337        ];
338        assert_eq!(lines_text(cells), "left right\nbelow");
339        assert_eq!(lines_text(Vec::new()), "");
340    }
341
342    /// #666: `picture_ocr_scale(1.0)` is RapidOCR's rule — a 720 × 180
343    /// screenshot reads at its own 720 × 180 (no resample, where the default
344    /// upscales it to 2000 × 500), a 3000 × 1000 one shrinks to 2000 × 667.
345    #[test]
346    fn picture_scale_reads_native_pixels_under_the_2000_px_cap() {
347        let dims = |p: f32, w: f32, h: f32| {
348            let s = picture_ocr_scale(p, w, h).unwrap_or(1.0);
349            ((w * s).round(), (h * s).round())
350        };
351        assert_eq!(picture_ocr_scale(1.0, 720.0, 180.0), None);
352        assert_eq!(dims(1.0, 3000.0, 1000.0), (2000.0, 667.0));
353        assert_eq!(dims(2.0, 720.0, 180.0), (1440.0, 360.0));
354        assert_eq!(dims(2.0, 1280.0, 720.0), (2000.0, 1125.0));
355        // The default rule, for comparison: 3 px/pt under the cap.
356        let default = page_ocr_scale(None, 720.0, 180.0, 1.0).unwrap();
357        assert_eq!(
358            ((720.0 * default).round(), (180.0 * default).round()),
359            (2000.0, 500.0)
360        );
361    }
362}