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