use image::RgbImage;
use crate::layout::Region;
use docling_core::{Node, PictureDescription};
use crate::pdfium_backend::{PdfPage, TextCell};
use crate::{ocr, ocr_input, page_ocr_scale, EnrichSlot, PdfError, Pipeline, RAPIDOCR_MAX_SIDE};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PictureText {
pub text: String,
pub provenance: &'static str,
}
impl Pipeline {
pub fn decode_picture(&self, bytes: &[u8]) -> Result<RgbImage, PdfError> {
crate::decode_image_limited(bytes)
}
pub fn classify_picture(&mut self, img: &RgbImage) -> Option<Vec<docling_core::PictureClass>> {
let mut guard = self.classifier.lock().unwrap_or_else(|p| p.into_inner());
if matches!(*guard, EnrichSlot::Unloaded) {
*guard = match crate::enrich::PictureClassifier::load_with(crate::intra_threads()) {
Some(m) => EnrichSlot::Ready(m),
None => EnrichSlot::Missing,
};
}
let EnrichSlot::Ready(model) = &mut *guard else {
return None;
};
match model.classify(img) {
Ok(classes) => Some(classes),
Err(e) => {
eprintln!("docling-pdf: picture classifier: {e}");
None
}
}
}
pub fn ocr_picture(&mut self, img: &RgbImage) -> Result<Option<PictureText>, PdfError> {
let provenance = match self.ocr_engine {
ocr::OcrEngine::PpOcr => "ppocr",
ocr::OcrEngine::Tesseract => "tesseract",
};
let (w, h) = (img.width() as f32, img.height() as f32);
if w < 1.0 || h < 1.0 {
return Ok(None);
}
let ocr_scale = match self.picture_ocr_scale {
Some(p) => picture_ocr_scale(p, w, h),
None => page_ocr_scale(self.ocr_scale, w, h, 1.0),
};
let mut cache = None;
let (view, scale) = ocr_input(&mut cache, img, 1.0, ocr_scale);
let region = Region {
label: "text",
score: 1.0,
l: 0.0,
t: 0.0,
r: w,
b: h,
};
let worker = self.primary()?;
let detected = worker
.with_det(|det| det.detect(view))
.transpose()
.map_err(PdfError::Ocr)?;
let Some(model) = worker.ocr_model()? else {
return Ok(None);
};
let cells = model
.ocr_page_with(
view,
std::slice::from_ref(®ion),
scale,
detected.as_deref(),
)
.map_err(PdfError::Ocr)?;
let text = lines_text(cells.into_iter().map(|(c, _)| c).collect());
Ok((!text.is_empty()).then_some(PictureText { text, provenance }))
}
}
fn picture_ocr_scale(p: f32, w: f32, h: f32) -> Option<f32> {
let s = p.min(RAPIDOCR_MAX_SIDE / w.max(h));
((s - 1.0).abs() > 1e-3).then_some(s)
}
pub(crate) fn lines_text(mut cells: Vec<TextCell>) -> String {
cells.retain(|c| !c.text.trim().is_empty());
cells.sort_by(|a, b| a.t.total_cmp(&b.t).then(a.l.total_cmp(&b.l)));
let mut rows: Vec<(f32, f32, Vec<TextCell>)> = Vec::new();
for cell in cells {
let mid = (cell.t + cell.b) / 2.0;
match rows.last_mut() {
Some((t, b, row)) if mid >= *t && mid <= *b => {
*t = t.min(cell.t);
*b = b.max(cell.b);
row.push(cell);
}
_ => rows.push((cell.t, cell.b, vec![cell])),
}
}
rows.iter_mut()
.map(|(_, _, row)| {
row.sort_by(|a, b| a.l.total_cmp(&b.l));
row.iter()
.map(|c| c.text.trim())
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>()
.join("\n")
}
pub(crate) fn text_inside(c: &TextCell, r: &Region) -> bool {
let (cx, cy) = ((c.l + c.r) / 2.0, (c.t + c.b) / 2.0);
cx >= r.l && cx <= r.r && cy >= r.t && cy <= r.b
}
pub(crate) fn describe_pictures(
nodes: &mut [Node],
page: &PdfPage,
cells: &[TextCell],
provenance: &str,
) {
let (w, h) = (page.width.max(1.0), page.height.max(1.0));
let to_region = |loc: &[u16; 4]| {
let x = |v: u16| v as f32 * w / 512.0;
let y = |v: u16| v as f32 * h / 512.0;
Region {
label: "picture",
score: 1.0,
l: x(loc[0].saturating_sub(1)),
t: y(loc[1].saturating_sub(1)),
r: x(loc[2].saturating_add(1)),
b: y(loc[3].saturating_add(1)),
}
};
let mut boxes: Vec<Region> = Vec::new();
visit_pictures(nodes, &mut |loc, _| boxes.push(to_region(loc)));
let area = |r: &Region| (r.r - r.l) * (r.b - r.t);
let owner: Vec<Option<usize>> = cells
.iter()
.map(|c| {
(0..boxes.len())
.filter(|&i| text_inside(c, &boxes[i]))
.min_by(|&a, &b| area(&boxes[a]).total_cmp(&area(&boxes[b])))
})
.collect();
let mut i = 0usize;
visit_pictures(nodes, &mut |_, description| {
let mine: Vec<TextCell> = cells
.iter()
.zip(&owner)
.filter(|(_, o)| **o == Some(i))
.map(|(c, _)| c.clone())
.collect();
i += 1;
if description.is_some() {
return;
}
let text = lines_text(mine);
if !text.is_empty() {
*description = Some(PictureDescription {
text,
provenance: provenance.to_string(),
});
}
});
}
fn visit_pictures(
nodes: &mut [Node],
f: &mut dyn FnMut(&[u16; 4], &mut Option<PictureDescription>),
) {
for node in nodes {
match node {
Node::Located { location, inner } => match inner.as_mut() {
Node::Picture { description, .. } => f(location, description),
other => visit_pictures(std::slice::from_mut(other), f),
},
Node::Table(t) => {
let Some(blocks) = t.cell_blocks.as_mut() else {
continue;
};
for row in blocks.iter_mut() {
for cell in row.iter_mut() {
visit_pictures(cell, f);
}
}
}
Node::Group { children, .. } | Node::PictureChildren(children) => {
visit_pictures(children, f)
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cell(text: &str, l: f32, t: f32, r: f32, b: f32) -> TextCell {
TextCell {
text: text.into(),
l,
t,
r,
b,
}
}
#[test]
fn describe_pictures_matches_lines_by_box() {
use docling_core::{CaptionParent, Table};
let pic = |loc: [u16; 4], description: Option<PictureDescription>| Node::Located {
location: loc,
inner: Box::new(Node::Picture {
caption: None,
caption_href: None,
image: None,
classification: None,
description,
caption_parent: CaptionParent::default(),
caption_location: None,
}),
};
let page = PdfPage::from_cells(512.0, 512.0, 2.0, Vec::new());
let table = Node::Table(Table {
cell_blocks: Some(vec![vec![vec![pic([300, 300, 400, 400], None)]]]),
..Table::default()
});
let kept = PictureDescription {
text: "alt".into(),
provenance: PictureDescription::ALT_TEXT.into(),
};
let mut nodes = vec![
pic([0, 0, 200, 200], None),
pic([50, 50, 100, 100], None),
table,
pic([450, 0, 500, 50], Some(kept.clone())),
];
let cells = [
cell("outer", 10.0, 10.0, 40.0, 20.0),
cell("inner", 60.0, 60.0, 90.0, 70.0),
cell("in table", 310.0, 310.0, 390.0, 320.0),
cell("ignored", 455.0, 5.0, 495.0, 15.0),
cell("nowhere", 250.0, 250.0, 260.0, 260.0),
];
describe_pictures(&mut nodes, &page, &cells, "ppocr");
let mut got = Vec::new();
visit_pictures(&mut nodes, &mut |_, d| got.push(d.clone().map(|d| d.text)));
assert_eq!(
got,
[
Some("outer".to_string()),
Some("inner".to_string()),
Some("in table".to_string()),
Some("alt".to_string()),
]
);
}
#[test]
fn lines_text_reads_rows_across_then_down() {
let cells = vec![
cell("right", 200.0, 10.0, 260.0, 30.0),
cell("below", 10.0, 40.0, 80.0, 60.0),
cell("left", 10.0, 12.0, 60.0, 32.0),
cell(" ", 10.0, 70.0, 20.0, 80.0),
];
assert_eq!(lines_text(cells), "left right\nbelow");
assert_eq!(lines_text(Vec::new()), "");
}
#[test]
fn picture_scale_reads_native_pixels_under_the_2000_px_cap() {
let dims = |p: f32, w: f32, h: f32| {
let s = picture_ocr_scale(p, w, h).unwrap_or(1.0);
((w * s).round(), (h * s).round())
};
assert_eq!(picture_ocr_scale(1.0, 720.0, 180.0), None);
assert_eq!(dims(1.0, 3000.0, 1000.0), (2000.0, 667.0));
assert_eq!(dims(2.0, 720.0, 180.0), (1440.0, 360.0));
assert_eq!(dims(2.0, 1280.0, 720.0), (2000.0, 1125.0));
let default = page_ocr_scale(None, 720.0, 180.0, 1.0).unwrap();
assert_eq!(
((720.0 * default).round(), (180.0 * default).round()),
(2000.0, 500.0)
);
}
}