fleischwolf_pdf/
layout.rs1use 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;
48const SIDE: u32 = 640;
49
50pub struct LayoutModel {
51 session: Session,
52}
53
54impl LayoutModel {
55 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 session = Session::builder()
60 .map_err(|e| format!("layout: builder: {e}"))?
61 .with_intra_threads(crate::intra_threads())
64 .map_err(|e| format!("layout: intra_threads: {e}"))?
65 .commit_from_file(&path)
66 .map_err(|e| format!("layout: load {path}: {e}"))?;
67 Ok(Self { session })
68 }
69
70 pub fn predict(
73 &mut self,
74 img: &RgbImage,
75 page_w: f32,
76 page_h: f32,
77 ) -> Result<Vec<Region>, String> {
78 let resized = image::imageops::resize(img, SIDE, SIDE, FilterType::Triangle);
81 let n = (SIDE * SIDE) as usize;
82 let mut data = vec![0f32; 3 * n];
83 for (i, px) in resized.pixels().enumerate() {
84 data[i] = px[0] as f32 / 255.0;
85 data[n + i] = px[1] as f32 / 255.0;
86 data[2 * n + i] = px[2] as f32 / 255.0;
87 }
88 let input = Tensor::from_array(([1usize, 3, SIDE as usize, SIDE as usize], data))
89 .map_err(|e| format!("layout: input tensor: {e}"))?;
90 let outputs = self
91 .session
92 .run(ort::inputs!["pixel_values" => input])
93 .map_err(|e| format!("layout: inference: {e}"))?;
94 let (lshape, logits) = outputs["logits"]
95 .try_extract_tensor::<f32>()
96 .map_err(|e| format!("layout: extract logits: {e}"))?;
97 let (_, boxes) = outputs["pred_boxes"]
98 .try_extract_tensor::<f32>()
99 .map_err(|e| format!("layout: extract boxes: {e}"))?;
100
101 let num_queries = lshape[1] as usize;
102 let num_classes = lshape[2] as usize;
103
104 let mut scored: Vec<(f32, usize)> = (0..num_queries * num_classes)
106 .map(|idx| (sigmoid(logits[idx]), idx))
107 .collect();
108 scored.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
109 scored.truncate(num_queries);
110
111 let mut regions = Vec::new();
112 for (score, idx) in scored {
113 if score <= THRESHOLD {
114 continue;
115 }
116 let label_id = idx % num_classes;
117 let q = idx / num_classes;
118 let cx = boxes[q * 4];
119 let cy = boxes[q * 4 + 1];
120 let w = boxes[q * 4 + 2];
121 let h = boxes[q * 4 + 3];
122 let l = (cx - w / 2.0) * page_w;
124 let t = (cy - h / 2.0) * page_h;
125 let r = (cx + w / 2.0) * page_w;
126 let b = (cy + h / 2.0) * page_h;
127 regions.push(Region {
128 label: LABELS.get(label_id).copied().unwrap_or("text"),
129 score,
130 l,
131 t,
132 r,
133 b,
134 });
135 }
136 Ok(regions)
137 }
138}
139
140fn sigmoid(x: f32) -> f32 {
141 1.0 / (1.0 + (-x).exp())
142}