1use image::imageops::FilterType;
9use image::RgbImage;
10use ort::session::Session;
11use ort::value::Tensor;
12
13pub 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#[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
46const THRESHOLD: f32 = 0.3;
50const SIDE: u32 = 640;
51
52pub 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 _ => 0.5,
71 }
72}
73
74pub struct LayoutModel {
75 session: Session,
76 batch_unsupported: bool,
81}
82
83impl LayoutModel {
84 pub fn load() -> Result<Self, String> {
88 Self::load_with(crate::intra_threads())
89 }
90
91 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 let session = Session::builder()
101 .map_err(|e| format!("layout: builder: {e}"))?
102 .with_intra_threads(intra)
105 .map_err(|e| format!("layout: intra_threads: {e}"))?
106 .commit_from_file(&path)
107 .map_err(|e| format!("layout: load {path}: {e}"))?;
108 Ok(Self {
109 session,
110 batch_unsupported: false,
111 })
112 }
113
114 pub fn predict(
117 &mut self,
118 img: &RgbImage,
119 page_w: f32,
120 page_h: f32,
121 ) -> Result<Vec<Region>, String> {
122 Ok(self
123 .predict_batch(&[(img, page_w, page_h)])?
124 .pop()
125 .expect("one result per input page"))
126 }
127
128 pub fn predict_batch(
134 &mut self,
135 pages: &[(&RgbImage, f32, f32)],
136 ) -> Result<Vec<Vec<Region>>, String> {
137 if pages.len() > 1 && self.batch_unsupported {
138 return self.predict_singly(pages);
139 }
140 match self.run_batch(pages) {
141 Err(e) if pages.len() > 1 => {
142 eprintln!(
145 "docling-pdf: layout model rejected a {}-page batch ({e}); \
146 falling back to per-page inference — re-export with \
147 scripts/install/export_layout.py for batched layout",
148 pages.len()
149 );
150 self.batch_unsupported = true;
151 self.predict_singly(pages)
152 }
153 other => other,
154 }
155 }
156
157 fn predict_singly(
158 &mut self,
159 pages: &[(&RgbImage, f32, f32)],
160 ) -> Result<Vec<Vec<Region>>, String> {
161 pages
162 .iter()
163 .map(|p| Ok(self.run_batch(&[*p])?.pop().expect("one result")))
164 .collect()
165 }
166
167 fn run_batch(&mut self, pages: &[(&RgbImage, f32, f32)]) -> Result<Vec<Vec<Region>>, String> {
168 if pages.is_empty() {
169 return Ok(Vec::new());
170 }
171 let n = (SIDE * SIDE) as usize;
174 let batch = pages.len();
175 let mut data = vec![0f32; batch * 3 * n];
176 for (p, (img, _, _)) in pages.iter().enumerate() {
177 let resized = image::imageops::resize(*img, SIDE, SIDE, FilterType::Triangle);
178 let page_off = p * 3 * n;
179 for (i, px) in resized.pixels().enumerate() {
180 data[page_off + i] = px[0] as f32 / 255.0;
181 data[page_off + n + i] = px[1] as f32 / 255.0;
182 data[page_off + 2 * n + i] = px[2] as f32 / 255.0;
183 }
184 }
185 let input = Tensor::from_array(([batch, 3, SIDE as usize, SIDE as usize], data))
186 .map_err(|e| format!("layout: input tensor: {e}"))?;
187 let outputs = self
188 .session
189 .run(ort::inputs!["pixel_values" => input])
190 .map_err(|e| format!("layout: inference: {e}"))?;
191 let (lshape, logits) = outputs["logits"]
192 .try_extract_tensor::<f32>()
193 .map_err(|e| format!("layout: extract logits: {e}"))?;
194 let (_, boxes) = outputs["pred_boxes"]
195 .try_extract_tensor::<f32>()
196 .map_err(|e| format!("layout: extract boxes: {e}"))?;
197
198 let num_queries = lshape[1] as usize;
199 let num_classes = lshape[2] as usize;
200
201 let mut all = Vec::with_capacity(batch);
202 for (p, (_, page_w, page_h)) in pages.iter().enumerate() {
203 let logits =
204 &logits[p * num_queries * num_classes..(p + 1) * num_queries * num_classes];
205 let boxes = &boxes[p * num_queries * 4..(p + 1) * num_queries * 4];
206
207 let mut scored: Vec<(f32, usize)> = (0..num_queries * num_classes)
209 .map(|idx| (sigmoid(logits[idx]), idx))
210 .collect();
211 scored.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
212 scored.truncate(num_queries);
213
214 let mut regions = Vec::new();
215 for (score, idx) in scored {
216 if score <= THRESHOLD {
217 continue;
218 }
219 let label_id = idx % num_classes;
220 let q = idx / num_classes;
221 let cx = boxes[q * 4];
222 let cy = boxes[q * 4 + 1];
223 let w = boxes[q * 4 + 2];
224 let h = boxes[q * 4 + 3];
225 let l = (cx - w / 2.0) * page_w;
227 let t = (cy - h / 2.0) * page_h;
228 let r = (cx + w / 2.0) * page_w;
229 let b = (cy + h / 2.0) * page_h;
230 regions.push(Region {
231 label: LABELS.get(label_id).copied().unwrap_or("text"),
232 score,
233 l,
234 t,
235 r,
236 b,
237 });
238 }
239 all.push(regions);
240 }
241 Ok(all)
242 }
243}
244
245fn sigmoid(x: f32) -> f32 {
246 1.0 / (1.0 + (-x).exp())
247}