1use crate::pdfium_backend::TextCell;
8use image::RgbImage;
9use ort::session::Session;
10use ort::value::{DynValue, Tensor};
11
12const SIDE: u32 = 448;
13#[allow(clippy::excessive_precision)]
16const MEAN: [f32; 3] = [0.94247851, 0.94254675, 0.94292611];
17#[allow(clippy::excessive_precision)]
18const STD: [f32; 3] = [0.17910956, 0.17940403, 0.17931663];
19const MAX_STEPS: usize = 1024;
20const N_LAYERS: usize = 6;
23const EMBED_DIM: usize = 512;
24
25pub const START: i64 = 2;
27pub const END: i64 = 3;
28pub const ECEL: i64 = 4; pub const FCEL: i64 = 5; pub const LCEL: i64 = 6; pub const UCEL: i64 = 7; pub const XCEL: i64 = 8; pub const NL: i64 = 9; pub const CHED: i64 = 10; pub const RHED: i64 = 11; pub const SROW: i64 = 12; #[derive(Debug, Clone)]
42pub struct TableCell {
43 pub row: usize,
44 pub col: usize,
45 pub colspan: usize,
46 pub rowspan: usize,
47 pub tag: i64,
48 pub class: i64,
49 pub cx: f32,
50 pub cy: f32,
51 pub w: f32,
52 pub h: f32,
53}
54
55pub struct TableFormer {
56 encoder: Session,
57 decoder: Session,
58 bbox: Session,
59 style: DecoderStyle,
63}
64
65#[derive(Clone, Copy, PartialEq, Eq)]
67enum DecoderStyle {
68 Legacy,
71 KvStacked,
74 KvHoisted,
79}
80
81const KV_HEADS: usize = 8;
84const KV_HEAD_DIM: usize = 64;
85
86#[derive(Default)]
90struct DecodeCache {
91 a: Option<DynValue>,
92 b: Option<DynValue>,
93}
94
95type EmptyCache = (Tensor<f32>, Option<Tensor<f32>>);
98
99struct EncodeOut {
104 ck: DynValue,
105 cv: DynValue,
106 eo: DynValue,
107 per_layer: Vec<(String, DynValue)>,
110}
111
112impl TableFormer {
113 pub fn load() -> Option<Self> {
117 Self::load_with(crate::intra_threads())
118 }
119
120 pub fn load_with(intra: usize) -> Option<Self> {
124 let enc = std::env::var("DOCLING_TABLEFORMER_ENCODER")
125 .unwrap_or_else(|_| crate::resolve_asset("models/tableformer/encoder.onnx"));
126 let dec = std::env::var("DOCLING_TABLEFORMER_DECODER").unwrap_or_else(|_| {
137 let candidates: &[&str] = if crate::fp32_forced() {
138 &[
139 "models/tableformer/decoder_kv.onnx",
140 "models/tableformer/decoder.onnx",
141 ]
142 } else {
143 &[
148 "models/tableformer/decoder_kv_int8.onnx",
149 "models/tableformer/decoder_kv.onnx",
150 "models/tableformer/decoder_int8.onnx",
151 "models/tableformer/decoder.onnx",
152 ]
153 };
154 candidates
155 .iter()
156 .map(|p| crate::resolve_asset(p))
157 .find(|p| std::path::Path::new(p).exists())
158 .unwrap_or_else(|| "models/tableformer/decoder.onnx".to_string())
159 });
160 let bbx = std::env::var("DOCLING_TABLEFORMER_BBOX")
161 .unwrap_or_else(|_| crate::resolve_asset("models/tableformer/bbox.onnx"));
162 if crate::timing::enabled() {
163 eprintln!("docling-pdf: tableformer decoder: {dec}");
164 }
165 if [&enc, &dec, &bbx]
166 .iter()
167 .any(|p| !std::path::Path::new(p).exists())
168 {
169 warn_missing_once(&enc, &dec, &bbx);
176 return None;
177 }
178 let build = |path: &str, mem_pattern: bool| -> Result<Session, String> {
184 Session::builder()
185 .map_err(|e| e.to_string())?
186 .with_intra_threads(intra)
187 .map_err(|e| e.to_string())?
188 .with_memory_pattern(mem_pattern)
189 .map_err(|e| e.to_string())?
190 .commit_from_file(path)
191 .map_err(|e| format!("tableformer load {path}: {e}"))
192 };
193 match (build(&enc, true), build(&dec, false), build(&bbx, true)) {
194 (Ok(encoder), Ok(decoder), Ok(bbox)) => {
195 let has = |n: &str| decoder.inputs().iter().any(|i| i.name() == n);
196 let style = if has("cross_kt_0") {
197 DecoderStyle::KvHoisted
198 } else if has("cache_k") {
199 DecoderStyle::KvStacked
200 } else {
201 DecoderStyle::Legacy
202 };
203 if style == DecoderStyle::KvHoisted
204 && !encoder.outputs().iter().any(|o| o.name() == "cross_kt_0")
205 {
206 eprintln!(
207 "docling-pdf: tableformer decoder needs per-layer cross tensors \
208 (cross_kt_*) the encoder doesn't emit — re-download or re-export \
209 the model set (scripts/install/export_tableformer.py); \
210 falling back to geometric tables"
211 );
212 return None;
213 }
214 Some(Self {
215 encoder,
216 decoder,
217 bbox,
218 style,
219 })
220 }
221 _ => None,
222 }
223 }
224
225 fn encode(&mut self, img: &RgbImage) -> Result<EncodeOut, String> {
229 let input = preprocess(img)?;
230 let mut enc_out = self
231 .encoder
232 .run(ort::inputs!["image" => input])
233 .map_err(|e| format!("tableformer: encode: {e}"))?;
234 let mut per_layer = Vec::new();
235 if self.style == DecoderStyle::KvHoisted {
236 for prefix in ["cross_kt_", "cross_v_"] {
237 for i in 0.. {
238 let name = format!("{prefix}{i}");
239 match enc_out.remove(&name) {
240 Some(v) => per_layer.push((name, v)),
241 None => break,
242 }
243 }
244 }
245 if per_layer.is_empty() {
246 return Err("tableformer: encoder emitted no cross_kt_* outputs".into());
247 }
248 }
249 let mut grab = |name: &str| -> Result<DynValue, String> {
250 enc_out
251 .remove(name)
252 .ok_or_else(|| format!("tableformer: encoder output {name} missing"))
253 };
254 Ok(EncodeOut {
255 ck: grab("cross_k")?,
256 cv: grab("cross_v")?,
257 eo: grab("enc_out")?,
258 per_layer,
259 })
260 }
261
262 fn decode_step(
271 &mut self,
272 tags: &[i64],
273 enc: &EncodeOut,
274 cache: &mut DecodeCache,
275 empty: &EmptyCache,
276 ) -> Result<(i64, Vec<f32>), String> {
277 crate::timing::timed("tf.decode_step", || {
278 self.decode_step_inner(tags, enc, cache, empty)
279 })
280 }
281
282 fn decode_step_inner(
283 &mut self,
284 tags: &[i64],
285 enc: &EncodeOut,
286 cache: &mut DecodeCache,
287 empty: &EmptyCache,
288 ) -> Result<(i64, Vec<f32>), String> {
289 let mut dout = match self.style {
290 DecoderStyle::KvHoisted => {
291 let last = *tags.last().expect("decode starts from <start>");
294 let tag_t = Tensor::from_array(([1usize, 1usize], vec![last]))
295 .map_err(|e| format!("tableformer: tag: {e}"))?;
296 let mut inputs: Vec<(
297 std::borrow::Cow<'_, str>,
298 ort::session::SessionInputValue<'_>,
299 )> = Vec::with_capacity(3 + enc.per_layer.len());
300 inputs.push(("tag".into(), tag_t.into()));
301 match (cache.a.as_ref(), cache.b.as_ref()) {
302 (Some(k), Some(v)) => {
303 inputs.push(("cache_k".into(), k.into()));
304 inputs.push(("cache_v".into(), v.into()));
305 }
306 _ => {
307 inputs.push(("cache_k".into(), (&empty.0).into()));
308 inputs.push((
309 "cache_v".into(),
310 empty
311 .1
312 .as_ref()
313 .expect("kv empty cache has both halves")
314 .into(),
315 ));
316 }
317 }
318 for (name, v) in &enc.per_layer {
319 inputs.push((name.as_str().into(), v.into()));
320 }
321 self.decoder.run(inputs)
322 }
323 DecoderStyle::KvStacked => {
324 let last = *tags.last().expect("decode starts from <start>");
328 let tag_t = Tensor::from_array(([1usize, 1usize], vec![last]))
329 .map_err(|e| format!("tableformer: tag: {e}"))?;
330 match (cache.a.as_ref(), cache.b.as_ref()) {
331 (Some(k), Some(v)) => self.decoder.run(ort::inputs![
332 "tag" => tag_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
333 "cache_k" => k, "cache_v" => v]),
334 _ => self.decoder.run(ort::inputs![
335 "tag" => tag_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
336 "cache_k" => &empty.0,
337 "cache_v" => empty.1.as_ref().expect("kv empty cache has both halves")]),
338 }
339 }
340 DecoderStyle::Legacy => {
341 let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.to_vec()))
342 .map_err(|e| format!("tableformer: tags: {e}"))?;
343 match cache.a.as_ref() {
344 None => self.decoder.run(ort::inputs![
345 "tags" => tags_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
346 "cache" => &empty.0]),
347 Some(c) => self.decoder.run(ort::inputs![
348 "tags" => tags_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
349 "cache" => c]),
350 }
351 }
352 }
353 .map_err(|e| format!("tableformer: decode: {e}"))?;
354 let (_, logits) = dout["logits"]
355 .try_extract_tensor::<f32>()
356 .map_err(|e| format!("tableformer: logits: {e}"))?;
357 let raw = argmax(logits) as i64;
358 let (_, hidden) = dout["hidden"]
359 .try_extract_tensor::<f32>()
360 .map_err(|e| format!("tableformer: hidden: {e}"))?;
361 let hidden = hidden.to_vec();
362 if self.style != DecoderStyle::Legacy {
363 cache.a = Some(
364 dout.remove("out_cache_k")
365 .ok_or_else(|| "tableformer: out_cache_k missing".to_string())?,
366 );
367 cache.b = Some(
368 dout.remove("out_cache_v")
369 .ok_or_else(|| "tableformer: out_cache_v missing".to_string())?,
370 );
371 } else {
372 cache.a = Some(
373 dout.remove("out_cache")
374 .ok_or_else(|| "tableformer: decoder output out_cache missing".to_string())?,
375 );
376 }
377 Ok((raw, hidden))
378 }
379
380 fn empty_cache(&self) -> Result<EmptyCache, String> {
384 let alloc = self.decoder.allocator();
385 if self.style != DecoderStyle::Legacy {
386 let mk = || {
387 Tensor::<f32>::new(alloc, [N_LAYERS, 1, KV_HEADS, 0usize, KV_HEAD_DIM])
388 .map_err(|e| format!("tableformer: empty kv cache: {e}"))
389 };
390 Ok((mk()?, Some(mk()?)))
391 } else {
392 let c = Tensor::<f32>::new(alloc, [N_LAYERS, 0usize, 1, EMBED_DIM])
393 .map_err(|e| format!("tableformer: empty cache: {e}"))?;
394 Ok((c, None))
395 }
396 }
397
398 pub fn predict_otsl(&mut self, img: &RgbImage) -> Result<Vec<i64>, String> {
400 let enc = self.encode(img)?;
401 let mut tags: Vec<i64> = vec![START];
404 let mut out: Vec<i64> = Vec::new();
405 let mut prev_ucel = false;
406 let mut cache = DecodeCache::default();
407 let empty = self.empty_cache()?;
408 while out.len() < MAX_STEPS {
409 let (raw, _hidden) = self.decode_step(&tags, &enc, &mut cache, &empty)?;
410 let mut tag = raw;
411 if tag == XCEL {
412 tag = LCEL;
413 }
414 if prev_ucel && tag == LCEL {
415 tag = FCEL;
416 }
417 if tag == END {
418 break;
419 }
420 out.push(tag);
421 tags.push(tag);
422 prev_ucel = tag == UCEL;
423 }
424 Ok(out)
425 }
426
427 pub fn predict_table_structure(&mut self, img: &RgbImage) -> Result<Vec<TableCell>, String> {
433 let enc = self.encode(img)?;
434
435 let mut tags: Vec<i64> = vec![START];
436 let mut otsl: Vec<i64> = Vec::new();
437 let mut hiddens: Vec<f32> = Vec::new(); let mut n = 0usize;
439 let mut prev_ucel = false;
440 let mut skip = true; let mut first_lcel = true;
442 let mut bbox_ind = 0usize;
443 let mut cur_bbox_ind = 0usize;
444 let mut merge: std::collections::HashMap<usize, i64> = std::collections::HashMap::new();
445 let mut cache = DecodeCache::default();
446 let empty = self.empty_cache()?;
447 while otsl.len() < MAX_STEPS {
448 let (raw, hidden) = self.decode_step(&tags, &enc, &mut cache, &empty)?;
449 let mut tag = raw;
450 if tag == XCEL {
451 tag = LCEL;
452 }
453 if prev_ucel && tag == LCEL {
454 tag = FCEL;
455 }
456 if tag == END {
457 break;
458 }
459 if !skip && matches!(tag, FCEL | ECEL | CHED | RHED | SROW | NL | UCEL) {
461 hiddens.extend_from_slice(&hidden);
462 n += 1;
463 if !first_lcel {
464 merge.insert(cur_bbox_ind, bbox_ind as i64);
465 }
466 bbox_ind += 1;
467 }
468 if tag != LCEL {
469 first_lcel = true;
470 } else if first_lcel {
471 hiddens.extend_from_slice(&hidden);
472 n += 1;
473 first_lcel = false;
474 cur_bbox_ind = bbox_ind;
475 merge.insert(cur_bbox_ind, -1);
476 bbox_ind += 1;
477 }
478 skip = matches!(tag, NL | UCEL | XCEL);
479 prev_ucel = tag == UCEL;
480 otsl.push(tag);
481 tags.push(tag);
482 }
483 if n == 0 {
484 return Ok(Vec::new());
485 }
486 let tag_h = Tensor::from_array(([n, 512usize], hiddens))
487 .map_err(|e| format!("tableformer: tag_h: {e}"))?;
488 let bout = self
489 .bbox
490 .run(ort::inputs!["enc_out" => &enc.eo, "tag_h" => tag_h])
491 .map_err(|e| format!("tableformer: bbox: {e}"))?;
492 let (_, raw) = bout["boxes"]
493 .try_extract_tensor::<f32>()
494 .map_err(|e| format!("tableformer: boxes: {e}"))?;
495 let boxes: Vec<[f32; 4]> = raw
496 .chunks_exact(4)
497 .map(|c| [c[0], c[1], c[2], c[3]])
498 .collect();
499 let (_, craw) = bout["classes"]
501 .try_extract_tensor::<f32>()
502 .map_err(|e| format!("tableformer: classes: {e}"))?;
503 let classes: Vec<i64> = craw.chunks_exact(3).map(|c| argmax(c) as i64).collect();
504 let (merged, merged_classes) = merge_spans(&boxes, &classes, &merge);
505 Ok(build_table_cells(&otsl, &merged, &merged_classes))
506 }
507
508 pub fn predict_table_rows(
515 &mut self,
516 page_image: &RgbImage,
517 region: [f32; 4],
518 words: &[TextCell],
519 ) -> Option<Vec<Vec<String>>> {
520 let sf = 1024.0 / page_image.height() as f32;
529 let pw = (page_image.width() as f32 * sf) as u32;
530 let page1024 = crate::timing::timed("tableformer.inter_area", || {
531 crate::resample::inter_area(page_image, pw, 1024)
532 });
533 let k = 2.0 * 1024.0 / page_image.height() as f64;
534 let px = |v: f32| (v as f64).round_ties_even() * k;
535 let x = (px(region[0]).round_ties_even()).max(0.0) as u32;
536 let y = (px(region[1]).round_ties_even()).max(0.0) as u32;
537 let x2 = (px(region[2]).round_ties_even() as u32).min(page1024.width());
538 let y2 = (px(region[3]).round_ties_even() as u32).min(page1024.height());
539 if x2 <= x || y2 <= y {
540 return None;
541 }
542 let crop = image::imageops::crop_imm(&page1024, x, y, x2 - x, y2 - y).to_image();
543 let cells = crate::timing::timed("tableformer.structure", || {
544 self.predict_table_structure(&crop)
545 })
546 .ok()?;
547 if cells.is_empty() {
548 return None;
549 }
550 let table_words: Vec<crate::tf_match::PdfWord> = words
554 .iter()
555 .enumerate()
556 .filter(|(_, w)| !w.text.trim().is_empty())
557 .filter_map(|(wi, w)| {
558 let (l, t, r, b) = (w.l as f64, w.t as f64, w.r as f64, w.b as f64);
559 let area = (r - l) * (b - t);
560 let iw = (r.min(region[2] as f64) - l.max(region[0] as f64)).max(0.0);
561 let ih = (b.min(region[3] as f64) - t.max(region[1] as f64)).max(0.0);
562 if area > 0.0 && iw * ih / area > 0.8 {
563 Some(crate::tf_match::PdfWord {
564 id: wi,
565 bbox: [l, t, r, b],
566 text: w.text.trim().to_string(),
567 })
568 } else {
569 None
570 }
571 })
572 .collect();
573
574 if !table_words.is_empty() && !simple_match() {
575 return docling_match_rows(&cells, region, &table_words, words);
576 }
577
578 let (rw, rh) = (region[2] - region[0], region[3] - region[1]);
579
580 let boxes: Vec<[f32; 4]> = cells
582 .iter()
583 .map(|c| {
584 [
585 region[0] + (c.cx - c.w / 2.0) * rw,
586 region[1] + (c.cy - c.h / 2.0) * rh,
587 region[0] + (c.cx + c.w / 2.0) * rw,
588 region[1] + (c.cy + c.h / 2.0) * rh,
589 ]
590 })
591 .collect();
592
593 let mut cell_words: Vec<Vec<usize>> = vec![Vec::new(); cells.len()];
595 for (wi, w) in words.iter().enumerate() {
596 let wa = ((w.r - w.l) * (w.b - w.t)).max(1.0);
597 let mut best: Option<(f32, usize)> = None;
598 for (ci, b) in boxes.iter().enumerate() {
599 let ix = (w.r.min(b[2]) - w.l.max(b[0])).max(0.0);
600 let iy = (w.b.min(b[3]) - w.t.max(b[1])).max(0.0);
601 let io = ix * iy / wa;
602 if io > 0.0 && best.is_none_or(|(bo, _)| io > bo) {
603 best = Some((io, ci));
604 }
605 }
606 if let Some((_, ci)) = best {
607 cell_words[ci].push(wi);
608 }
609 }
610
611 let num_rows = cells.iter().map(|c| c.row + c.rowspan).max().unwrap_or(0);
612 let num_cols = cells.iter().map(|c| c.col + c.colspan).max().unwrap_or(0);
613 if num_rows == 0 || num_cols == 0 {
614 return None;
615 }
616 let mut grid = vec![vec![String::new(); num_cols]; num_rows];
617 for (ci, c) in cells.iter().enumerate() {
618 let wis = std::mem::take(&mut cell_words[ci]);
622 let text = wis
623 .iter()
624 .map(|&i| words[i].text.trim())
625 .collect::<Vec<_>>()
626 .join(" ");
627 let text = normalize_cell_text(text);
628 for row in grid.iter_mut().skip(c.row).take(c.rowspan) {
630 for cell in row.iter_mut().skip(c.col).take(c.colspan) {
631 *cell = text.clone();
632 }
633 }
634 }
635 Some(grid)
636 }
637}
638
639fn dump_match_inputs(
642 dir: &str,
643 tf_cells: &[crate::tf_match::TfCell],
644 words: &[crate::tf_match::PdfWord],
645) {
646 use std::io::Write;
647 let cells: Vec<String> = tf_cells
648 .iter()
649 .map(|c| {
650 format!(
651 r#"{{"bbox":[{},{},{},{}],"cell_id":{},"row_id":{},"column_id":{},"cell_class":{},"colspan_val":{},"rowspan_val":{}}}"#,
652 c.bbox[0], c.bbox[1], c.bbox[2], c.bbox[3],
653 c.cell_id, c.row_id, c.column_id, c.cell_class,
654 c.colspan_val, c.rowspan_val
655 )
656 })
657 .collect();
658 let ws: Vec<String> = words
659 .iter()
660 .map(|w| {
661 format!(
662 r#"{{"id":{},"bbox":[{},{},{},{}],"text":{}}}"#,
663 w.id,
664 w.bbox[0],
665 w.bbox[1],
666 w.bbox[2],
667 w.bbox[3],
668 serde_json_escape(&w.text)
669 )
670 })
671 .collect();
672 let line = format!(
673 r#"{{"table_cells":[{}],"pdf_cells":[{}]}}"#,
674 cells.join(","),
675 ws.join(",")
676 );
677 if let Ok(mut f) = std::fs::OpenOptions::new()
678 .create(true)
679 .append(true)
680 .open(format!("{dir}/tf_match_dump.jsonl"))
681 {
682 let _ = writeln!(f, "{line}");
683 }
684}
685
686fn serde_json_escape(s: &str) -> String {
688 let mut out = String::with_capacity(s.len() + 2);
689 out.push('"');
690 for ch in s.chars() {
691 match ch {
692 '"' => out.push_str("\\\""),
693 '\\' => out.push_str("\\\\"),
694 '\n' => out.push_str("\\n"),
695 '\r' => out.push_str("\\r"),
696 '\t' => out.push_str("\\t"),
697 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
698 c => out.push(c),
699 }
700 }
701 out.push('"');
702 out
703}
704
705fn simple_match() -> bool {
708 std::env::var("DOCLING_RS_TF_SIMPLE_MATCH").is_ok_and(|v| !v.is_empty() && v != "0")
709}
710
711fn normalize_cell_text(text: String) -> String {
717 text.replace("@ ", "@")
718}
719
720fn docling_match_rows(
728 cells: &[TableCell],
729 region: [f32; 4],
730 table_words: &[crate::tf_match::PdfWord],
731 words: &[TextCell],
732) -> Option<Vec<Vec<String>>> {
733 const SCALE: f64 = 2.0; let sl = (region[0] as f64).round_ties_even() * SCALE;
735 let st = (region[1] as f64).round_ties_even() * SCALE;
736 let sr = (region[2] as f64).round_ties_even() * SCALE;
737 let sb = (region[3] as f64).round_ties_even() * SCALE;
738 let (w2, h2) = (sr - sl, sb - st);
739
740 let tf_cells: Vec<crate::tf_match::TfCell> = cells
741 .iter()
742 .enumerate()
743 .map(|(i, c)| {
744 let (cx, cy) = (c.cx as f64, c.cy as f64);
745 let (w, h) = (c.w as f64, c.h as f64);
746 crate::tf_match::TfCell {
747 bbox: [
748 sl + (cx - w / 2.0) * w2,
749 st + (cy - h / 2.0) * h2,
750 sl + (cx + w / 2.0) * w2,
751 st + (cy + h / 2.0) * h2,
752 ],
753 cell_id: i,
754 row_id: c.row,
755 column_id: c.col,
756 cell_class: c.class,
757 colspan_val: if c.colspan > 1 { c.colspan } else { 0 },
758 rowspan_val: if c.rowspan > 1 { c.rowspan } else { 0 },
759 }
760 })
761 .collect();
762
763 let scaled_words: Vec<crate::tf_match::PdfWord> = table_words
764 .iter()
765 .map(|w| crate::tf_match::PdfWord {
766 id: w.id,
767 bbox: [
768 w.bbox[0] * SCALE,
769 w.bbox[1] * SCALE,
770 w.bbox[2] * SCALE,
771 w.bbox[3] * SCALE,
772 ],
773 text: w.text.clone(),
774 })
775 .collect();
776
777 if let Ok(dir) = std::env::var("DOCLING_RS_TF_MATCH_DUMP") {
780 if !dir.is_empty() {
781 dump_match_inputs(&dir, &tf_cells, &scaled_words);
782 }
783 }
784
785 let (cells_wo, final_matches) =
786 crate::tf_match::match_and_post_process(tf_cells, &scaled_words);
787
788 struct Merged {
791 start_row: usize,
792 start_col: usize,
793 row_span: usize,
794 col_span: usize,
795 word_ids: Vec<usize>,
796 }
797 let mut merged: Vec<Merged> = Vec::new();
798 let mut key_ix: std::collections::HashMap<(usize, usize), usize> =
799 std::collections::HashMap::new();
800 for (&pdf_id, list) in &final_matches {
801 let tm = list[0].table_cell_id;
802 let Some(cell) = cells_wo.iter().find(|c| c.cell_id == tm) else {
803 continue;
804 };
805 match key_ix.entry((cell.column_id, cell.row_id)) {
806 std::collections::hash_map::Entry::Occupied(e) => {
807 merged[*e.get()].word_ids.push(pdf_id);
808 }
809 std::collections::hash_map::Entry::Vacant(e) => {
810 e.insert(merged.len());
811 merged.push(Merged {
812 start_row: cell.row_id,
813 start_col: cell.column_id,
814 row_span: cell.rowspan_val.max(1),
815 col_span: cell.colspan_val.max(1),
816 word_ids: vec![pdf_id],
817 });
818 }
819 }
820 }
821 if merged.is_empty() {
822 return None;
823 }
824
825 let mut start_cols: Vec<usize> = merged.iter().map(|m| m.start_col).collect();
828 start_cols.sort_unstable();
829 start_cols.dedup();
830 let mut start_rows: Vec<usize> = merged.iter().map(|m| m.start_row).collect();
831 start_rows.sort_unstable();
832 start_rows.dedup();
833 let mut num_rows = 0;
834 let mut num_cols = 0;
835 for m in &mut merged {
836 m.start_col = start_cols.binary_search(&m.start_col).expect("own value");
837 m.start_row = start_rows.binary_search(&m.start_row).expect("own value");
838 num_cols = num_cols.max(m.start_col + m.col_span);
839 num_rows = num_rows.max(m.start_row + m.row_span);
840 }
841 if num_rows == 0 || num_cols == 0 {
842 return None;
843 }
844
845 let mut grid = vec![vec![String::new(); num_cols]; num_rows];
846 for m in &merged {
847 let text = m
848 .word_ids
849 .iter()
850 .map(|&i| words[i].text.trim())
851 .collect::<Vec<_>>()
852 .join(" ");
853 let text = normalize_cell_text(text);
854 for row in grid.iter_mut().skip(m.start_row).take(m.row_span) {
855 for cell in row.iter_mut().skip(m.start_col).take(m.col_span) {
856 *cell = text.clone();
857 }
858 }
859 }
860 Some(grid)
861}
862
863fn warn_missing_once(enc: &str, dec: &str, bbx: &str) {
870 static WARNED: std::sync::Once = std::sync::Once::new();
871 WARNED.call_once(|| {
872 eprintln!(
873 "docling.rs: TableFormer models not found (checked {enc}, {dec}, {bbx}); \
874 tables will use geometric reconstruction instead of ML table-structure \
875 recognition. Set DOCLING_TABLEFORMER_ENCODER / DOCLING_TABLEFORMER_DECODER \
876 / DOCLING_TABLEFORMER_BBOX to enable it (see README.md)."
877 );
878 });
879}
880
881fn preprocess(img: &RgbImage) -> Result<Tensor<f32>, String> {
886 let nn = (SIDE * SIDE) as usize;
887 let side = SIDE as usize;
888 let (sw, sh) = (img.width() as i32, img.height() as i32);
889 let sxr = sw as f32 / SIDE as f32;
890 let syr = sh as f32 / SIDE as f32;
891 let mut data = vec![0f32; 3 * nn];
892 for h in 0..side {
893 let fy = (h as f32 + 0.5) * syr - 0.5;
894 let wy = fy - fy.floor();
895 let y0c = (fy.floor() as i32).clamp(0, sh - 1) as u32;
896 let y1c = (fy.floor() as i32 + 1).clamp(0, sh - 1) as u32;
897 for w in 0..side {
898 let fx = (w as f32 + 0.5) * sxr - 0.5;
899 let wx = fx - fx.floor();
900 let x0c = (fx.floor() as i32).clamp(0, sw - 1) as u32;
901 let x1c = (fx.floor() as i32 + 1).clamp(0, sw - 1) as u32;
902 let p00 = img.get_pixel(x0c, y0c);
903 let p01 = img.get_pixel(x1c, y0c);
904 let p10 = img.get_pixel(x0c, y1c);
905 let p11 = img.get_pixel(x1c, y1c);
906 let idx = w * side + h; for c in 0..3 {
908 let top = p00[c] as f32 * (1.0 - wx) + p01[c] as f32 * wx;
909 let bot = p10[c] as f32 * (1.0 - wx) + p11[c] as f32 * wx;
910 let v = top * (1.0 - wy) + bot * wy;
911 data[c * nn + idx] = (v / 255.0 - MEAN[c]) / STD[c];
912 }
913 }
914 }
915 Tensor::from_array(([1usize, 3, side, side], data))
916 .map_err(|e| format!("tableformer: input: {e}"))
917}
918
919fn mergebboxes(b1: [f32; 4], b2: [f32; 4]) -> [f32; 4] {
922 let new_w = (b2[0] + b2[2] / 2.0) - (b1[0] - b1[2] / 2.0);
923 let new_h = (b2[1] + b2[3] / 2.0) - (b1[1] - b1[3] / 2.0);
924 let new_left = b1[0] - b1[2] / 2.0;
925 let new_top = (b2[1] - b2[3] / 2.0).min(b1[1] - b1[3] / 2.0);
926 [new_left + new_w / 2.0, new_top + new_h / 2.0, new_w, new_h]
927}
928
929fn merge_spans(
933 boxes: &[[f32; 4]],
934 classes: &[i64],
935 merge: &std::collections::HashMap<usize, i64>,
936) -> (Vec<[f32; 4]>, Vec<i64>) {
937 let skip: std::collections::HashSet<usize> = merge
938 .values()
939 .filter(|&&v| v >= 0)
940 .map(|&v| v as usize)
941 .collect();
942 let mut out = Vec::new();
943 let mut out_classes = Vec::new();
944 for (i, &b) in boxes.iter().enumerate() {
945 let class = classes.get(i).copied().unwrap_or(2);
946 if let Some(&j) = merge.get(&i) {
947 let partner = if j < 0 { boxes.len() - 1 } else { j as usize };
948 out.push(mergebboxes(b, boxes[partner.min(boxes.len() - 1)]));
949 out_classes.push(class);
950 } else if !skip.contains(&i) {
951 out.push(b);
952 out_classes.push(class);
953 }
954 }
955 (out, out_classes)
956}
957
958const CELL_TAGS: [i64; 6] = [FCEL, ECEL, XCEL, CHED, RHED, SROW];
959
960fn build_table_cells(otsl: &[i64], boxes: &[[f32; 4]], classes: &[i64]) -> Vec<TableCell> {
966 let mut grid: Vec<Vec<i64>> = vec![Vec::new()];
968 for &t in otsl {
969 if t == NL {
970 grid.push(Vec::new());
971 } else {
972 grid.last_mut().unwrap().push(t);
973 }
974 }
975 let mut cells = Vec::new();
976 let mut cell_id = 0usize;
977 for (r, row) in grid.iter().enumerate() {
978 for (c, &tag) in row.iter().enumerate() {
979 if !CELL_TAGS.contains(&tag) {
980 continue;
981 }
982 let mut colspan = 1;
983 while c + colspan < row.len() && matches!(row[c + colspan], LCEL | XCEL) {
984 colspan += 1;
985 }
986 let mut rowspan = 1;
987 while r + rowspan < grid.len()
988 && grid[r + rowspan]
989 .get(c)
990 .is_some_and(|&t| matches!(t, UCEL | XCEL))
991 {
992 rowspan += 1;
993 }
994 let b = boxes.get(cell_id).copied().unwrap_or([0.0; 4]);
995 let class = classes.get(cell_id).copied().unwrap_or(2);
997 cells.push(TableCell {
998 row: r,
999 col: c,
1000 colspan,
1001 rowspan,
1002 tag,
1003 class,
1004 cx: b[0],
1005 cy: b[1],
1006 w: b[2],
1007 h: b[3],
1008 });
1009 cell_id += 1;
1010 }
1011 }
1012 cells
1013}
1014
1015fn argmax(v: &[f32]) -> usize {
1016 v.iter()
1017 .enumerate()
1018 .max_by(|a, b| a.1.total_cmp(b.1))
1019 .map(|(i, _)| i)
1020 .unwrap_or(0)
1021}