Skip to main content

docling_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/// Base confidence threshold (docling-ibm-models `base_threshold`): the raw
47/// RT-DETR floor before docling's `LayoutPostprocessor` applies its stricter
48/// per-label thresholds ([`label_threshold`]).
49const THRESHOLD: f32 = 0.3;
50const SIDE: u32 = 640;
51
52/// Per-label confidence threshold, ported from docling's
53/// `LayoutPostprocessor.CONFIDENCE_THRESHOLDS`. The raw predictor keeps every
54/// detection above the 0.3 base; the postprocessor then drops a cluster whose
55/// score is below its label's threshold. Applying it here (equivalent, since
56/// every per-label threshold is ≥ the 0.3 base) keeps low-confidence pictures /
57/// tables / list-items out of the assembly, matching docling.
58pub fn label_threshold(label: &str) -> f32 {
59    match label {
60        "section_header"
61        | "title"
62        | "code"
63        | "checkbox_selected"
64        | "checkbox_unselected"
65        | "form"
66        | "key_value_region"
67        | "document_index" => 0.45,
68        // caption, footnote, formula, list_item, page_footer, page_header,
69        // picture, table, text — all 0.5 in docling.
70        _ => 0.5,
71    }
72}
73
74pub struct LayoutModel {
75    session: Session,
76    /// Set when a multi-page inference fails — e.g. a locally built pre-#73
77    /// static graph (fixed batch=1) via `DOCLING_LAYOUT_ONNX` or a stale
78    /// `layout_heron_int8.onnx`. Batched calls then fall back to per-page runs
79    /// instead of failing the conversion.
80    batch_unsupported: bool,
81}
82
83impl LayoutModel {
84    /// Load the ONNX model from `DOCLING_LAYOUT_ONNX`. Without the override,
85    /// prefers `models/layout_heron_int8.onnx` when present (the quantized
86    /// default; `DOCLING_RS_FP32=1` opts out), else `models/layout_heron.onnx`.
87    pub fn load() -> Result<Self, String> {
88        Self::load_with(crate::intra_threads())
89    }
90
91    /// Like [`load`](Self::load) but with an explicit intra-op thread count. A
92    /// parallel page-worker pool loads its helper models on a single thread each
93    /// and gets its speed-up from running pages concurrently instead.
94    pub fn load_with(intra: usize) -> Result<Self, String> {
95        let path = crate::model_path(
96            "DOCLING_LAYOUT_ONNX",
97            "models/layout_heron.onnx",
98            "models/layout_heron_int8.onnx",
99        );
100        if crate::timing::enabled() {
101            eprintln!("docling-pdf: layout model: {path}");
102        }
103        let builder = Session::builder()
104            .map_err(|e| format!("layout: builder: {e}"))?
105            // Let inference use the available cores (ort otherwise defaults low);
106            // a large PDF runs this model once per page.
107            .with_intra_threads(intra)
108            .map_err(|e| format!("layout: intra_threads: {e}"))?;
109        let session = crate::ep::apply(builder)
110            .map_err(|e| format!("layout: {e}"))?
111            .commit_from_file(&path)
112            .map_err(|e| format!("layout: load {path}: {e}"))?;
113        Ok(Self {
114            session,
115            batch_unsupported: false,
116        })
117    }
118
119    /// Detect layout regions on a page image. `page_w`/`page_h` are the page size
120    /// in points; returned boxes are in those coordinates.
121    pub fn predict(
122        &mut self,
123        img: &RgbImage,
124        page_w: f32,
125        page_h: f32,
126    ) -> Result<Vec<Region>, String> {
127        Ok(self
128            .predict_batch(&[(img, page_w, page_h)])?
129            .pop()
130            .expect("one result per input page"))
131    }
132
133    /// Detect layout regions on several page images with **one** inference call
134    /// (issue #73). The ONNX export has a dynamic batch dimension, so a worker
135    /// can amortize the per-run framework overhead and keep its cores busier on
136    /// multi-page documents. Results are per-image, index-aligned with `pages`,
137    /// and identical to calling [`predict`](Self::predict) per page.
138    pub fn predict_batch(
139        &mut self,
140        pages: &[(&RgbImage, f32, f32)],
141    ) -> Result<Vec<Vec<Region>>, String> {
142        if pages.len() > 1 && self.batch_unsupported {
143            return self.predict_singly(pages);
144        }
145        match self.run_batch(pages) {
146            Err(e) if pages.len() > 1 => {
147                // A graph without the dynamic batch dim (pre-#73 export) fails
148                // only for batch > 1 — remember and recover per page. Warn once
149                // per process, not per worker: every worker owns a LayoutModel
150                // over the same graph file, so repeats carry no information.
151                static WARNED: std::sync::atomic::AtomicBool =
152                    std::sync::atomic::AtomicBool::new(false);
153                if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
154                    eprintln!(
155                        "docling-pdf: layout model rejected a {}-page batch ({e}); \
156                         falling back to per-page inference — re-export with \
157                         scripts/install/export_layout.py for batched layout",
158                        pages.len()
159                    );
160                }
161                self.batch_unsupported = true;
162                self.predict_singly(pages)
163            }
164            other => other,
165        }
166    }
167
168    fn predict_singly(
169        &mut self,
170        pages: &[(&RgbImage, f32, f32)],
171    ) -> Result<Vec<Vec<Region>>, String> {
172        pages
173            .iter()
174            .map(|p| Ok(self.run_batch(&[*p])?.pop().expect("one result")))
175            .collect()
176    }
177
178    fn run_batch(&mut self, pages: &[(&RgbImage, f32, f32)]) -> Result<Vec<Vec<Region>>, String> {
179        if pages.is_empty() {
180            return Ok(Vec::new());
181        }
182        // Resize each page to 640×640 (RT-DETR ignores aspect ratio), rescale to
183        // [0,1], lay out as NCHW.
184        let n = (SIDE * SIDE) as usize;
185        let batch = pages.len();
186        let mut data = vec![0f32; batch * 3 * n];
187        for (p, (img, _, _)) in pages.iter().enumerate() {
188            let resized = image::imageops::resize(*img, SIDE, SIDE, FilterType::Triangle);
189            let page_off = p * 3 * n;
190            for (i, px) in resized.pixels().enumerate() {
191                data[page_off + i] = px[0] as f32 / 255.0;
192                data[page_off + n + i] = px[1] as f32 / 255.0;
193                data[page_off + 2 * n + i] = px[2] as f32 / 255.0;
194            }
195        }
196        let input = Tensor::from_array(([batch, 3, SIDE as usize, SIDE as usize], data))
197            .map_err(|e| format!("layout: input tensor: {e}"))?;
198        let outputs = self
199            .session
200            .run(ort::inputs!["pixel_values" => input])
201            .map_err(|e| format!("layout: inference: {e}"))?;
202        let (lshape, logits) = outputs["logits"]
203            .try_extract_tensor::<f32>()
204            .map_err(|e| format!("layout: extract logits: {e}"))?;
205        let (_, boxes) = outputs["pred_boxes"]
206            .try_extract_tensor::<f32>()
207            .map_err(|e| format!("layout: extract boxes: {e}"))?;
208
209        let num_queries = lshape[1] as usize;
210        let num_classes = lshape[2] as usize;
211
212        let mut all = Vec::with_capacity(batch);
213        for (p, (_, page_w, page_h)) in pages.iter().enumerate() {
214            let logits =
215                &logits[p * num_queries * num_classes..(p + 1) * num_queries * num_classes];
216            let boxes = &boxes[p * num_queries * 4..(p + 1) * num_queries * 4];
217
218            // sigmoid over every (query, class); take the top `num_queries` scores.
219            let mut scored: Vec<(f32, usize)> = (0..num_queries * num_classes)
220                .map(|idx| (sigmoid(logits[idx]), idx))
221                .collect();
222            scored.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
223            scored.truncate(num_queries);
224
225            let mut regions = Vec::new();
226            for (score, idx) in scored {
227                if score <= THRESHOLD {
228                    continue;
229                }
230                let label_id = idx % num_classes;
231                let q = idx / num_classes;
232                let cx = boxes[q * 4];
233                let cy = boxes[q * 4 + 1];
234                let w = boxes[q * 4 + 2];
235                let h = boxes[q * 4 + 3];
236                // center_to_corners, then scale normalized coords to page points.
237                let l = (cx - w / 2.0) * page_w;
238                let t = (cy - h / 2.0) * page_h;
239                let r = (cx + w / 2.0) * page_w;
240                let b = (cy + h / 2.0) * page_h;
241                regions.push(Region {
242                    label: LABELS.get(label_id).copied().unwrap_or("text"),
243                    score,
244                    l,
245                    t,
246                    r,
247                    b,
248                });
249            }
250            all.push(regions);
251        }
252        Ok(all)
253    }
254}
255
256fn sigmoid(x: f32) -> f32 {
257    1.0 / (1.0 + (-x).exp())
258}