Skip to main content

docling_pdf/
enrich.rs

1//! Optional enrichment models (docling's `do_picture_classification` /
2//! `do_code_enrichment` / `do_formula_enrichment`, issue #76).
3//!
4//! * [`PictureClassifier`] — docling-project/DocumentFigureClassifier-v2.5, an
5//!   EfficientNet image classifier over 26 figure classes (bar_chart, logo,
6//!   signature, …). The HF repo ships the ONNX graph as-is; docling's ViT
7//!   preprocessing is 224×224 bilinear + rescale + normalize, and the raw
8//!   logits are softmaxed and sorted descending — the full distribution lands
9//!   on the picture item like docling's `PictureClassificationData`.
10//!
11//! * [`CodeFormula`] — docling-project/CodeFormulaV2, an Idefics3/SmolVLM-class
12//!   VLM that rewrites a code crop as clean source text prefixed with
13//!   `<_language_>`, or a formula crop as LaTeX. Exported to three graphs by
14//!   `scripts/install/export_code_formula.py` (vision tower+connector, token
15//!   embeddings, and a KV-cached Llama decoder step verified argmax-identical
16//!   to `transformers.generate`); this module ports the Idefics3 preprocessing
17//!   (longest-edge 2048 resize → multiple-of-512 resize → 512×512 tiling + a
18//!   squashed global tile), the tiled `<image>` prompt, and the greedy decode.
19
20use image::RgbImage;
21use ort::session::Session;
22use ort::value::Tensor;
23use tokenizers::Tokenizer;
24
25use docling_core::PictureClass;
26
27/// docling crops enrichment inputs at `images_scale` pixels per point:
28/// 2.0 for the picture classifier, 1.67 (≈120 dpi) for CodeFormula.
29pub const CLASSIFIER_SCALE: f32 = 2.0;
30pub const CODE_FORMULA_SCALE: f32 = 1.67;
31/// CodeFormula expands the region box by 18% of its size on every side
32/// (docling's `expansion_factor`) before cropping.
33pub const CODE_FORMULA_EXPANSION: f32 = 0.18;
34
35// ---------------------------------------------------------------------------
36// Picture classifier
37// ---------------------------------------------------------------------------
38
39/// The 26 classes of DocumentFigureClassifier-v2.5, indexed by model class id
40/// (`config.json` `id2label`).
41const 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;
71/// ViT preprocessing constants from the model's `preprocessor_config.json`.
72const 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    /// Load from `DOCLING_PICTURE_CLASSIFIER_ONNX` /
81    /// `models/picture_classifier(_int8).onnx`. `None` when the graph is
82    /// absent — the caller warns once and skips classification.
83    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    /// Classify one picture crop: the full 26-class distribution, descending
107    /// confidence (docling attaches all predicted classes, not just the top).
108    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        // softmax → (class, prob) sorted descending, like docling's engine.
140        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// ---------------------------------------------------------------------------
157// CodeFormula (Idefics3 VLM)
158// ---------------------------------------------------------------------------
159
160/// Which prompt the model gets for a region.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum CodeFormulaKind {
163    Code,
164    Formula,
165}
166
167/// Idefics3 processor constants (CodeFormulaV2's `preprocessor_config.json` /
168/// tokenizer). The token ids are fixed by the checkpoint's tokenizer.json.
169const TILE: u32 = 512; // max_image_size.longest_edge
170const LONGEST_EDGE: u32 = 2048; // size.longest_edge
171const MAX_IMAGE_SIZE: u32 = 4096; // transformers' hard upper bound
172const IMAGE_SEQ_LEN: usize = 64; // visual tokens per tile
173const IMAGE_TOKEN_ID: i64 = 100270; // <image>
174const EOS_ID: i64 = 100338; // <end_of_utterance>
175const 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    /// Load the three graphs + tokenizer from `DOCLING_CODE_FORMULA_DIR`
190    /// (default `models/code_formula/`). `None` when absent, with a one-time
191    /// warning from the caller's slot.
192    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        // INT8 variants take priority when present, like the other models.
197        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    /// Run the VLM on a code/formula crop and return the post-processed text
235    /// (still carrying the `<_language_>` prefix for code — see
236    /// [`extract_code_language`]).
237    pub fn predict(&mut self, crop: &RgbImage, kind: CodeFormulaKind) -> Result<String, String> {
238        // Debug aid: dump each crop the VLM sees (compare against docling's
239        // `prepare_element` output when chasing a generation divergence).
240        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        // Vision tower over the tile batch → [T, 64, 576]. (Scoped: the
250        // session outputs hold a mutable borrow of the session until dropped.)
251        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        // Prompt: the chat template with the single <image> expanded into the
265        // per-tile token grid (transformers' Idefics3Processor layout).
266        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        // Token embeddings, then scatter the visual tokens into the <image>
282        // positions (Idefics3's inputs_merger).
283        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        // Greedy KV-cache decode until <end_of_utterance> (docling caps
303        // generation at the model's 8192 context). The K/V caches stay owned
304        // `ort` values fed straight back into the next step — never extracted
305        // or copied (they grow every step, so per-step copies would be
306        // O(steps²) float traffic; same pattern as the TableFormer decoder).
307        // ort's array constructors reject a 0-length dim, so the zero-`past`
308        // first-step tensors go through the session allocator.
309        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
389/// The `<image>` expansion for a rows×cols tile grid + global tile
390/// (transformers' `Idefics3Processor.replace_image_token`).
391fn 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
406/// Idefics3 image preprocessing: longest-edge 2048 resize (LANCZOS), resize to
407/// multiples of 512, split into 512×512 tiles (row-major) plus the whole image
408/// squashed to 512×512 as the trailing global tile, then `(x/255 - 0.5)/0.5`.
409/// Returns the flattened `[T,3,512,512]` tensor data and the grid shape.
410fn preprocess_idefics3(crop: &RgbImage) -> (Vec<f32>, u32, u32) {
411    use image::imageops::FilterType;
412    // 1. longest edge → 2048 exactly (up- or down-scale), short side rounded
413    //    to even, both clamped below 4096 (rescale_to_max_len).
414    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    // 2. ceil each side to a multiple of the 512 tile (resize_for_vision_encoder).
420    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    // 3. tiles (row-major) + the global squash.
432    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
445/// transformers' `_resize_output_size_rescale_to_max_len`: longest edge to
446/// `max_len` exactly, the short side `int(long/aspect)` bumped to even.
447fn 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
467/// transformers' `_resize_output_size_scale_below_upper_bound` (a no-op unless
468/// the even-bump pushed a side past the hard 4096 cap).
469fn 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
483/// Append one 512×512 tile as CHW `(x/255 - 0.5)/0.5`.
484fn 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
495/// docling's CodeFormulaModel post-processing: truncate at
496/// `<end_of_utterance>`, remove the closing/query artifacts, strip leading
497/// whitespace.
498fn 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
510/// docling's `_extract_code_language`: an output beginning with
511/// `<_language_>` yields `(remainder, Some(language))`.
512pub 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    // The language is everything up to the closing `_>` that contains neither
518    // `_` nor `>` (docling's `[^_>]+`).
519    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        // An 800×300 crop resizes to 2048×768, tiles to 2048×1024 → 4×2 grid
555        // (+ global) — the shape verified against transformers' processor.
556        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}