Skip to main content

fleischwolf_pdf/
layout.rs

1//! Layout detection via the RT-DETR (`docling-layout-heron`) model exported to
2//! ONNX, run with `ort`. A port of docling-ibm-models' `LayoutPredictor`:
3//! resize the page image to 640×640 and rescale to `[0,1]` (the heron processor
4//! has `do_normalize=false`), run the model, then RT-DETR
5//! `post_process_object_detection` (sigmoid → top-k over query×class →
6//! center-to-corners boxes scaled to the page).
7
8use image::imageops::FilterType;
9use image::RgbImage;
10use ort::session::Session;
11use ort::value::Tensor;
12
13/// The 17 canonical layout classes, indexed by the model's class id
14/// (`config.json` `id2label`).
15pub const LABELS: [&str; 17] = [
16    "caption",
17    "footnote",
18    "formula",
19    "list_item",
20    "page_footer",
21    "page_header",
22    "picture",
23    "section_header",
24    "table",
25    "text",
26    "title",
27    "document_index",
28    "code",
29    "checkbox_selected",
30    "checkbox_unselected",
31    "form",
32    "key_value_region",
33];
34
35/// One detected region, in page points (top-left origin).
36#[derive(Debug, Clone)]
37pub struct Region {
38    pub label: &'static str,
39    pub score: f32,
40    pub l: f32,
41    pub t: f32,
42    pub r: f32,
43    pub b: f32,
44}
45
46/// Confidence threshold (docling-ibm-models `base_threshold`).
47const THRESHOLD: f32 = 0.3;
48const SIDE: u32 = 640;
49
50pub struct LayoutModel {
51    session: Session,
52}
53
54impl LayoutModel {
55    /// Load the ONNX model from `DOCLING_LAYOUT_ONNX` (or `models/layout_heron.onnx`).
56    pub fn load() -> Result<Self, String> {
57        let path = std::env::var("DOCLING_LAYOUT_ONNX")
58            .unwrap_or_else(|_| "models/layout_heron.onnx".to_string());
59        let mut builder = Session::builder().map_err(|e| format!("layout: builder: {e}"))?;
60        let session = builder
61            .commit_from_file(&path)
62            .map_err(|e| format!("layout: load {path}: {e}"))?;
63        Ok(Self { session })
64    }
65
66    /// Detect layout regions on a page image. `page_w`/`page_h` are the page size
67    /// in points; returned boxes are in those coordinates.
68    pub fn predict(
69        &mut self,
70        img: &RgbImage,
71        page_w: f32,
72        page_h: f32,
73    ) -> Result<Vec<Region>, String> {
74        // Resize to 640×640 (RT-DETR ignores aspect ratio), rescale to [0,1],
75        // lay out as CHW.
76        let resized = image::imageops::resize(img, SIDE, SIDE, FilterType::Triangle);
77        let n = (SIDE * SIDE) as usize;
78        let mut data = vec![0f32; 3 * n];
79        for (i, px) in resized.pixels().enumerate() {
80            data[i] = px[0] as f32 / 255.0;
81            data[n + i] = px[1] as f32 / 255.0;
82            data[2 * n + i] = px[2] as f32 / 255.0;
83        }
84        let input = Tensor::from_array(([1usize, 3, SIDE as usize, SIDE as usize], data))
85            .map_err(|e| format!("layout: input tensor: {e}"))?;
86        let outputs = self
87            .session
88            .run(ort::inputs!["pixel_values" => input])
89            .map_err(|e| format!("layout: inference: {e}"))?;
90        let (lshape, logits) = outputs["logits"]
91            .try_extract_tensor::<f32>()
92            .map_err(|e| format!("layout: extract logits: {e}"))?;
93        let (_, boxes) = outputs["pred_boxes"]
94            .try_extract_tensor::<f32>()
95            .map_err(|e| format!("layout: extract boxes: {e}"))?;
96
97        let num_queries = lshape[1] as usize;
98        let num_classes = lshape[2] as usize;
99
100        // sigmoid over every (query, class); take the top `num_queries` scores.
101        let mut scored: Vec<(f32, usize)> = (0..num_queries * num_classes)
102            .map(|idx| (sigmoid(logits[idx]), idx))
103            .collect();
104        scored.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
105        scored.truncate(num_queries);
106
107        let mut regions = Vec::new();
108        for (score, idx) in scored {
109            if score <= THRESHOLD {
110                continue;
111            }
112            let label_id = idx % num_classes;
113            let q = idx / num_classes;
114            let cx = boxes[q * 4];
115            let cy = boxes[q * 4 + 1];
116            let w = boxes[q * 4 + 2];
117            let h = boxes[q * 4 + 3];
118            // center_to_corners, then scale normalized coords to page points.
119            let l = (cx - w / 2.0) * page_w;
120            let t = (cy - h / 2.0) * page_h;
121            let r = (cx + w / 2.0) * page_w;
122            let b = (cy + h / 2.0) * page_h;
123            regions.push(Region {
124                label: LABELS.get(label_id).copied().unwrap_or("text"),
125                score,
126                l,
127                t,
128                r,
129                b,
130            });
131        }
132        Ok(regions)
133    }
134}
135
136fn sigmoid(x: f32) -> f32 {
137    1.0 / (1.0 + (-x).exp())
138}