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