1use image::RgbImage;
21use ort::session::Session;
22use ort::value::Tensor;
23use tokenizers::Tokenizer;
24
25use docling_core::PictureClass;
26
27pub const CLASSIFIER_SCALE: f32 = 2.0;
30pub const CODE_FORMULA_SCALE: f32 = 1.67;
31pub const CODE_FORMULA_EXPANSION: f32 = 0.18;
34
35const PICTURE_CLASSES: [&str; 26] = [
42 "logo",
43 "photograph",
44 "icon",
45 "engineering_drawing",
46 "line_chart",
47 "bar_chart",
48 "other",
49 "table",
50 "flow_chart",
51 "screenshot_from_computer",
52 "signature",
53 "screenshot_from_manual",
54 "geographical_map",
55 "pie_chart",
56 "page_thumbnail",
57 "stamp",
58 "music",
59 "calendar",
60 "qr_code",
61 "bar_code",
62 "full_page_image",
63 "scatter_plot",
64 "chemistry_structure",
65 "topographical_map",
66 "crossword_puzzle",
67 "box_plot",
68];
69
70const CLASSIFIER_SIDE: u32 = 224;
71const CLASSIFIER_MEAN: [f32; 3] = [0.485, 0.456, 0.406];
73const CLASSIFIER_STD: [f32; 3] = [0.478_539_44, 0.473_286_4, 0.474_341_63];
74
75pub struct PictureClassifier {
76 session: Session,
77}
78
79impl PictureClassifier {
80 pub fn load_with(intra: usize) -> Option<Self> {
84 let path = crate::model_path(
85 "DOCLING_PICTURE_CLASSIFIER_ONNX",
86 "models/picture_classifier.onnx",
87 "models/picture_classifier_int8.onnx",
88 );
89 if !std::path::Path::new(&path).exists() {
90 eprintln!(
91 "docling-pdf: picture classifier model not found ({path}); \
92 picture classification skipped. Run scripts/install/download_dependencies.sh."
93 );
94 return None;
95 }
96 let builder = Session::builder().ok()?.with_intra_threads(intra).ok()?;
97 let session = crate::ep::apply(builder)
98 .map_err(|e| eprintln!("docling-pdf: picture classifier: {e}"))
99 .ok()?
100 .commit_from_file(&path)
101 .map_err(|e| eprintln!("docling-pdf: picture classifier load {path}: {e}"))
102 .ok()?;
103 Some(Self { session })
104 }
105
106 pub fn classify(&mut self, crop: &RgbImage) -> Result<Vec<PictureClass>, String> {
109 let resized = image::imageops::resize(
110 crop,
111 CLASSIFIER_SIDE,
112 CLASSIFIER_SIDE,
113 image::imageops::FilterType::Triangle,
114 );
115 let n = (CLASSIFIER_SIDE * CLASSIFIER_SIDE) as usize;
116 let mut data = vec![0f32; 3 * n];
117 for (i, px) in resized.pixels().enumerate() {
118 for c in 0..3 {
119 data[c * n + i] = (px[c] as f32 / 255.0 - CLASSIFIER_MEAN[c]) / CLASSIFIER_STD[c];
120 }
121 }
122 let input = Tensor::from_array((
123 [
124 1usize,
125 3,
126 CLASSIFIER_SIDE as usize,
127 CLASSIFIER_SIDE as usize,
128 ],
129 data,
130 ))
131 .map_err(|e| format!("picture classifier: input: {e}"))?;
132 let outputs = self
133 .session
134 .run(ort::inputs!["input" => input])
135 .map_err(|e| format!("picture classifier: inference: {e}"))?;
136 let (_, logits) = outputs[0]
137 .try_extract_tensor::<f32>()
138 .map_err(|e| format!("picture classifier: output: {e}"))?;
139 let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
141 let exp: Vec<f32> = logits.iter().map(|&v| (v - max).exp()).collect();
142 let sum: f32 = exp.iter().sum();
143 let mut preds: Vec<PictureClass> = exp
144 .iter()
145 .enumerate()
146 .map(|(i, &e)| PictureClass {
147 class_name: PICTURE_CLASSES.get(i).copied().unwrap_or("other").into(),
148 confidence: e / sum,
149 })
150 .collect();
151 preds.sort_by(|a, b| b.confidence.total_cmp(&a.confidence));
152 Ok(preds)
153 }
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum CodeFormulaKind {
163 Code,
164 Formula,
165}
166
167const TILE: u32 = 512; const LONGEST_EDGE: u32 = 2048; const MAX_IMAGE_SIZE: u32 = 4096; const IMAGE_SEQ_LEN: usize = 64; const IMAGE_TOKEN_ID: i64 = 100270; const EOS_ID: i64 = 100338; const MODEL_MAX_LEN: usize = 8192;
176const HIDDEN: usize = 576;
177const N_LAYERS: usize = 30;
178const N_KV: usize = 3;
179const HEAD_DIM: usize = 64;
180
181pub struct CodeFormula {
182 vision: Session,
183 embed: Session,
184 decoder: Session,
185 tokenizer: Tokenizer,
186}
187
188impl CodeFormula {
189 pub fn load_with(intra: usize) -> Option<Self> {
193 let dir = std::env::var("DOCLING_CODE_FORMULA_DIR")
194 .unwrap_or_else(|_| crate::resolve_asset("models/code_formula"));
195 let file = |name: &str| format!("{dir}/{name}");
196 let graph = |base: &str| {
198 let int8 = file(&format!("{base}_int8.onnx"));
199 if !crate::prefer_fp32() && std::path::Path::new(&int8).exists() {
200 int8
201 } else {
202 file(&format!("{base}.onnx"))
203 }
204 };
205 for f in [&graph("vision"), &graph("embed"), &graph("decoder_kv")] {
206 if !std::path::Path::new(f.as_str()).exists() {
207 eprintln!(
208 "docling-pdf: CodeFormula model not found ({f}); code/formula \
209 enrichment skipped. Run scripts/install/download_dependencies.sh."
210 );
211 return None;
212 }
213 }
214 let load = |p: String| {
215 let builder = Session::builder().ok()?.with_intra_threads(intra).ok()?;
216 crate::ep::apply(builder)
217 .map_err(|e| eprintln!("docling-pdf: CodeFormula: {e}"))
218 .ok()?
219 .commit_from_file(&p)
220 .map_err(|e| eprintln!("docling-pdf: CodeFormula load {p}: {e}"))
221 .ok()
222 };
223 let tokenizer = Tokenizer::from_file(file("tokenizer.json"))
224 .map_err(|e| eprintln!("docling-pdf: CodeFormula tokenizer: {e}"))
225 .ok()?;
226 Some(Self {
227 vision: load(graph("vision"))?,
228 embed: load(graph("embed"))?,
229 decoder: load(graph("decoder_kv"))?,
230 tokenizer,
231 })
232 }
233
234 pub fn predict(&mut self, crop: &RgbImage, kind: CodeFormulaKind) -> Result<String, String> {
238 if let Ok(dir) = std::env::var("DOCLING_RS_ENRICH_DEBUG") {
241 use std::sync::atomic::{AtomicUsize, Ordering};
242 static N: AtomicUsize = AtomicUsize::new(0);
243 let n = N.fetch_add(1, Ordering::Relaxed);
244 let _ = crop.save(format!("{dir}/rs_crop_{n}.png"));
245 }
246 let (tiles, rows, cols) = preprocess_idefics3(crop);
247 let n_tiles = tiles.len() / (3 * (TILE * TILE) as usize);
248
249 let feats: Vec<f32> = {
252 let input = Tensor::from_array(([n_tiles, 3, TILE as usize, TILE as usize], tiles))
253 .map_err(|e| format!("code-formula: vision input: {e}"))?;
254 let outputs = self
255 .vision
256 .run(ort::inputs!["pixel_values" => input])
257 .map_err(|e| format!("code-formula: vision: {e}"))?;
258 let (_, feats) = outputs["image_features"]
259 .try_extract_tensor::<f32>()
260 .map_err(|e| format!("code-formula: vision output: {e}"))?;
261 feats.to_vec()
262 };
263
264 let query = match kind {
267 CodeFormulaKind::Code => "<code>",
268 CodeFormulaKind::Formula => "<formula>",
269 };
270 let prompt = format!(
271 "<|start_of_role|>user:{}{query}<end_of_utterance>\nassistant:",
272 image_prompt(rows, cols)
273 );
274 let enc = self
275 .tokenizer
276 .encode(prompt, false)
277 .map_err(|e| format!("code-formula: tokenize: {e}"))?;
278 let ids: Vec<i64> = enc.get_ids().iter().map(|&v| v as i64).collect();
279 let seq = ids.len();
280
281 let mut embeds = self.embed_ids(&ids)?;
284 let image_positions: Vec<usize> = ids
285 .iter()
286 .enumerate()
287 .filter(|(_, &t)| t == IMAGE_TOKEN_ID)
288 .map(|(i, _)| i)
289 .collect();
290 if image_positions.len() != n_tiles * IMAGE_SEQ_LEN {
291 return Err(format!(
292 "code-formula: {} image tokens for {} tiles",
293 image_positions.len(),
294 n_tiles
295 ));
296 }
297 for (v, &pos) in image_positions.iter().enumerate() {
298 embeds[pos * HIDDEN..(pos + 1) * HIDDEN]
299 .copy_from_slice(&feats[v * HIDDEN..(v + 1) * HIDDEN]);
300 }
301
302 let mut cache: Option<(ort::value::DynValue, ort::value::DynValue)> = None;
310 let empty = {
311 let mk = || {
312 Tensor::<f32>::new(
313 self.decoder.allocator(),
314 [N_LAYERS, 1, N_KV, 0usize, HEAD_DIM],
315 )
316 .map_err(|e| format!("code-formula: empty kv cache: {e}"))
317 };
318 (mk()?, mk()?)
319 };
320 let mut past_len = 0usize;
321 let mut positions: Vec<i64> = (0..seq as i64).collect();
322 let mut x = embeds;
323 let mut x_seq = seq;
324 let mut out_ids: Vec<u32> = Vec::new();
325 let max_new = MODEL_MAX_LEN.saturating_sub(seq);
326 for _ in 0..max_new {
327 let embeds_t = Tensor::from_array(([1usize, x_seq, HIDDEN], x))
328 .map_err(|e| format!("code-formula: embeds: {e}"))?;
329 let pos_t = Tensor::from_array(([1usize, positions.len()], positions.clone()))
330 .map_err(|e| format!("code-formula: positions: {e}"))?;
331 let next = {
332 let mut out = match cache.as_ref() {
333 Some((k, v)) => self.decoder.run(ort::inputs![
334 "inputs_embeds" => embeds_t, "position_ids" => pos_t,
335 "past_k" => k, "past_v" => v]),
336 None => self.decoder.run(ort::inputs![
337 "inputs_embeds" => embeds_t, "position_ids" => pos_t,
338 "past_k" => &empty.0, "past_v" => &empty.1]),
339 }
340 .map_err(|e| format!("code-formula: decoder: {e}"))?;
341 let (_, logits) = out["logits"]
342 .try_extract_tensor::<f32>()
343 .map_err(|e| format!("code-formula: logits: {e}"))?;
344 let next = logits
345 .iter()
346 .enumerate()
347 .max_by(|a, b| a.1.total_cmp(b.1))
348 .map(|(i, _)| i as i64)
349 .unwrap_or(EOS_ID);
350 cache = Some((
351 out.remove("new_k")
352 .ok_or_else(|| "code-formula: new_k missing".to_string())?,
353 out.remove("new_v")
354 .ok_or_else(|| "code-formula: new_v missing".to_string())?,
355 ));
356 next
357 };
358 past_len += x_seq;
359 if next == EOS_ID {
360 break;
361 }
362 out_ids.push(next as u32);
363 x = self.embed_ids(&[next])?;
364 x_seq = 1;
365 positions = vec![past_len as i64];
366 }
367
368 let text = self
369 .tokenizer
370 .decode(&out_ids, false)
371 .map_err(|e| format!("code-formula: decode: {e}"))?;
372 Ok(post_process(&text))
373 }
374
375 fn embed_ids(&mut self, ids: &[i64]) -> Result<Vec<f32>, String> {
376 let input = Tensor::from_array(([1usize, ids.len()], ids.to_vec()))
377 .map_err(|e| format!("code-formula: ids: {e}"))?;
378 let out = self
379 .embed
380 .run(ort::inputs!["input_ids" => input])
381 .map_err(|e| format!("code-formula: embed: {e}"))?;
382 let (_, embeds) = out["inputs_embeds"]
383 .try_extract_tensor::<f32>()
384 .map_err(|e| format!("code-formula: embed output: {e}"))?;
385 Ok(embeds.to_vec())
386 }
387}
388
389fn image_prompt(rows: u32, cols: u32) -> String {
392 let img = "<image>".repeat(IMAGE_SEQ_LEN);
393 let mut s = String::new();
394 for r in 1..=rows {
395 for c in 1..=cols {
396 s.push_str(&format!("<fake_token_around_image><row_{r}_col_{c}>{img}"));
397 }
398 s.push('\n');
399 }
400 s.push_str(&format!(
401 "\n<fake_token_around_image><global-img>{img}<fake_token_around_image>"
402 ));
403 s
404}
405
406fn preprocess_idefics3(crop: &RgbImage) -> (Vec<f32>, u32, u32) {
411 use image::imageops::FilterType;
412 let (w0, h0) = crop.dimensions();
415 let (mut w, mut h) = rescale_to_max_len(w0, h0, LONGEST_EDGE);
416 (h, w) = scale_below_upper_bound(h, w, MAX_IMAGE_SIZE);
417 let img = image::imageops::resize(crop, w, h, FilterType::Lanczos3);
418
419 let (tw, th) = if w >= h {
421 let tw = w.div_ceil(TILE) * TILE;
422 let th0 = (tw as f64 / (w as f64 / h as f64)) as u32;
423 (tw, th0.div_ceil(TILE) * TILE)
424 } else {
425 let th = h.div_ceil(TILE) * TILE;
426 let tw0 = (th as f64 * (w as f64 / h as f64)) as u32;
427 (tw0.div_ceil(TILE) * TILE, th)
428 };
429 let img = image::imageops::resize(&img, tw, th, FilterType::Lanczos3);
430
431 let (rows, cols) = (th / TILE, tw / TILE);
433 let mut tensor = Vec::with_capacity(((rows * cols + 1) * 3 * TILE * TILE) as usize);
434 for r in 0..rows {
435 for c in 0..cols {
436 let tile = image::imageops::crop_imm(&img, c * TILE, r * TILE, TILE, TILE).to_image();
437 push_normalized(&mut tensor, &tile);
438 }
439 }
440 let global = image::imageops::resize(&img, TILE, TILE, FilterType::Lanczos3);
441 push_normalized(&mut tensor, &global);
442 (tensor, rows, cols)
443}
444
445fn rescale_to_max_len(w0: u32, h0: u32, max_len: u32) -> (u32, u32) {
448 let aspect = w0 as f64 / h0 as f64;
449 let (w, h) = if w0 >= h0 {
450 let w = max_len;
451 let mut h = (w as f64 / aspect) as u32;
452 if !h.is_multiple_of(2) {
453 h += 1;
454 }
455 (w, h)
456 } else {
457 let h = max_len;
458 let mut w = (h as f64 * aspect) as u32;
459 if !w.is_multiple_of(2) {
460 w += 1;
461 }
462 (w, h)
463 };
464 (w.max(1), h.max(1))
465}
466
467fn scale_below_upper_bound(h0: u32, w0: u32, max_len: u32) -> (u32, u32) {
470 let aspect = w0 as f64 / h0 as f64;
471 let (h, w) = if w0 >= h0 && w0 > max_len {
472 let w = max_len;
473 (((w as f64 / aspect) as u32).max(1), w)
474 } else if h0 > w0 && h0 > max_len {
475 let h = max_len;
476 (h, ((h as f64 * aspect) as u32).max(1))
477 } else {
478 (h0, w0)
479 };
480 (h.max(1), w.max(1))
481}
482
483fn push_normalized(tensor: &mut Vec<f32>, tile: &RgbImage) {
485 let n = (TILE * TILE) as usize;
486 let base = tensor.len();
487 tensor.resize(base + 3 * n, 0.0);
488 for (i, px) in tile.pixels().enumerate() {
489 for c in 0..3 {
490 tensor[base + c * n + i] = px[c] as f32 / 255.0 * 2.0 - 1.0;
491 }
492 }
493}
494
495fn post_process(text: &str) -> String {
499 let mut t = match text.find("<end_of_utterance>") {
500 Some(i) => &text[..i],
501 None => text,
502 }
503 .to_string();
504 for tok in ["</code>", "</formula>", "<loc_0><loc_0><loc_500><loc_500>"] {
505 t = t.replace(tok, "");
506 }
507 t.trim_start().to_string()
508}
509
510pub fn extract_code_language(s: &str) -> (String, Option<String>) {
513 let rest = match s.strip_prefix("<_") {
514 Some(r) => r,
515 None => return (s.to_string(), None),
516 };
517 match rest.find("_>") {
520 Some(end) if !rest[..end].is_empty() && !rest[..end].contains(['_', '>']) => {
521 let lang = rest[..end].to_string();
522 let remainder = rest[end + 2..].trim_start().to_string();
523 (remainder, Some(lang))
524 }
525 _ => (s.to_string(), None),
526 }
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532
533 #[test]
534 fn language_prefix_extraction() {
535 assert_eq!(
536 extract_code_language("<_JavaScript_> function f() {}"),
537 (
538 "function f() {}".to_string(),
539 Some("JavaScript".to_string())
540 )
541 );
542 assert_eq!(
543 extract_code_language("plain text"),
544 ("plain text".to_string(), None)
545 );
546 assert_eq!(
547 extract_code_language("<_x_y_> t"),
548 ("<_x_y_> t".to_string(), None)
549 );
550 }
551
552 #[test]
553 fn idefics3_grid_matches_processor() {
554 let img = RgbImage::new(800, 300);
557 let (tensor, rows, cols) = preprocess_idefics3(&img);
558 assert_eq!((rows, cols), (2, 4));
559 assert_eq!(tensor.len(), 9 * 3 * 512 * 512);
560 }
561
562 #[test]
563 fn image_prompt_layout() {
564 let p = image_prompt(1, 2);
565 assert!(p.starts_with("<fake_token_around_image><row_1_col_1><image>"));
566 assert!(p.contains("<row_1_col_2>"));
567 let tail = "<fake_token_around_image><global-img>".to_owned()
568 + &"<image>".repeat(64)
569 + "<fake_token_around_image>";
570 assert!(p.ends_with(&tail));
571 assert_eq!(p.matches("<image>").count(), 3 * 64);
572 }
573}