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