1use 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#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct PictureText {
32 pub text: String,
33 pub provenance: &'static str,
35}
36
37impl Pipeline {
38 pub fn decode_picture(&self, bytes: &[u8]) -> Result<RgbImage, PdfError> {
42 crate::decode_image_limited(bytes)
43 }
44
45 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 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 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(®ion),
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
120fn 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
130pub(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
162pub(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
169pub(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 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
229fn 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 #[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 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 #[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 #[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 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}