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 kv: bool,
65}
66
67const KV_HEADS: usize = 8;
70const KV_HEAD_DIM: usize = 64;
71
72#[derive(Default)]
76struct DecodeCache {
77 a: Option<DynValue>,
78 b: Option<DynValue>,
79}
80
81type EmptyCache = (Tensor<f32>, Option<Tensor<f32>>);
84
85struct EncodeOut {
90 ck: DynValue,
91 cv: DynValue,
92 eo: DynValue,
93}
94
95impl TableFormer {
96 pub fn load() -> Option<Self> {
100 Self::load_with(crate::intra_threads())
101 }
102
103 pub fn load_with(intra: usize) -> Option<Self> {
107 let enc = std::env::var("DOCLING_TABLEFORMER_ENCODER")
108 .unwrap_or_else(|_| crate::resolve_asset("models/tableformer/encoder.onnx"));
109 let dec = std::env::var("DOCLING_TABLEFORMER_DECODER").unwrap_or_else(|_| {
120 let candidates: &[&str] = if crate::fp32_forced() {
121 &[
122 "models/tableformer/decoder_kv.onnx",
123 "models/tableformer/decoder.onnx",
124 ]
125 } else {
126 &[
127 "models/tableformer/decoder_kv_int8.onnx",
128 "models/tableformer/decoder_int8.onnx",
129 "models/tableformer/decoder_kv.onnx",
130 "models/tableformer/decoder.onnx",
131 ]
132 };
133 candidates
134 .iter()
135 .map(|p| crate::resolve_asset(p))
136 .find(|p| std::path::Path::new(p).exists())
137 .unwrap_or_else(|| "models/tableformer/decoder.onnx".to_string())
138 });
139 let bbx = std::env::var("DOCLING_TABLEFORMER_BBOX")
140 .unwrap_or_else(|_| crate::resolve_asset("models/tableformer/bbox.onnx"));
141 if [&enc, &dec, &bbx]
142 .iter()
143 .any(|p| !std::path::Path::new(p).exists())
144 {
145 warn_missing_once(&enc, &dec, &bbx);
152 return None;
153 }
154 let build = |path: &str, mem_pattern: bool| -> Result<Session, String> {
160 Session::builder()
161 .map_err(|e| e.to_string())?
162 .with_intra_threads(intra)
163 .map_err(|e| e.to_string())?
164 .with_memory_pattern(mem_pattern)
165 .map_err(|e| e.to_string())?
166 .commit_from_file(path)
167 .map_err(|e| format!("tableformer load {path}: {e}"))
168 };
169 match (build(&enc, true), build(&dec, false), build(&bbx, true)) {
170 (Ok(encoder), Ok(decoder), Ok(bbox)) => {
171 let kv = decoder.inputs().iter().any(|i| i.name() == "cache_k");
172 Some(Self {
173 encoder,
174 decoder,
175 bbox,
176 kv,
177 })
178 }
179 _ => None,
180 }
181 }
182
183 fn encode(&mut self, img: &RgbImage) -> Result<EncodeOut, String> {
187 let input = preprocess(img)?;
188 let mut enc_out = self
189 .encoder
190 .run(ort::inputs!["image" => input])
191 .map_err(|e| format!("tableformer: encode: {e}"))?;
192 let mut grab = |name: &str| -> Result<DynValue, String> {
193 enc_out
194 .remove(name)
195 .ok_or_else(|| format!("tableformer: encoder output {name} missing"))
196 };
197 Ok(EncodeOut {
198 ck: grab("cross_k")?,
199 cv: grab("cross_v")?,
200 eo: grab("enc_out")?,
201 })
202 }
203
204 fn decode_step(
213 &mut self,
214 tags: &[i64],
215 enc: &EncodeOut,
216 cache: &mut DecodeCache,
217 empty: &EmptyCache,
218 ) -> Result<(i64, Vec<f32>), String> {
219 let mut dout = if self.kv {
220 let last = *tags.last().expect("decode starts from <start>");
223 let tag_t = Tensor::from_array(([1usize, 1usize], vec![last]))
224 .map_err(|e| format!("tableformer: tag: {e}"))?;
225 match (cache.a.as_ref(), cache.b.as_ref()) {
226 (Some(k), Some(v)) => self.decoder.run(ort::inputs![
227 "tag" => tag_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
228 "cache_k" => k, "cache_v" => v]),
229 _ => self.decoder.run(ort::inputs![
230 "tag" => tag_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
231 "cache_k" => &empty.0,
232 "cache_v" => empty.1.as_ref().expect("kv empty cache has both halves")]),
233 }
234 } else {
235 let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.to_vec()))
236 .map_err(|e| format!("tableformer: tags: {e}"))?;
237 match cache.a.as_ref() {
238 None => self.decoder.run(ort::inputs![
239 "tags" => tags_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
240 "cache" => &empty.0]),
241 Some(c) => self.decoder.run(ort::inputs![
242 "tags" => tags_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
243 "cache" => c]),
244 }
245 }
246 .map_err(|e| format!("tableformer: decode: {e}"))?;
247 let (_, logits) = dout["logits"]
248 .try_extract_tensor::<f32>()
249 .map_err(|e| format!("tableformer: logits: {e}"))?;
250 let raw = argmax(logits) as i64;
251 let (_, hidden) = dout["hidden"]
252 .try_extract_tensor::<f32>()
253 .map_err(|e| format!("tableformer: hidden: {e}"))?;
254 let hidden = hidden.to_vec();
255 if self.kv {
256 cache.a = Some(
257 dout.remove("out_cache_k")
258 .ok_or_else(|| "tableformer: out_cache_k missing".to_string())?,
259 );
260 cache.b = Some(
261 dout.remove("out_cache_v")
262 .ok_or_else(|| "tableformer: out_cache_v missing".to_string())?,
263 );
264 } else {
265 cache.a = Some(
266 dout.remove("out_cache")
267 .ok_or_else(|| "tableformer: decoder output out_cache missing".to_string())?,
268 );
269 }
270 Ok((raw, hidden))
271 }
272
273 fn empty_cache(&self) -> Result<EmptyCache, String> {
277 let alloc = self.decoder.allocator();
278 if self.kv {
279 let mk = || {
280 Tensor::<f32>::new(alloc, [N_LAYERS, 1, KV_HEADS, 0usize, KV_HEAD_DIM])
281 .map_err(|e| format!("tableformer: empty kv cache: {e}"))
282 };
283 Ok((mk()?, Some(mk()?)))
284 } else {
285 let c = Tensor::<f32>::new(alloc, [N_LAYERS, 0usize, 1, EMBED_DIM])
286 .map_err(|e| format!("tableformer: empty cache: {e}"))?;
287 Ok((c, None))
288 }
289 }
290
291 pub fn predict_otsl(&mut self, img: &RgbImage) -> Result<Vec<i64>, String> {
293 let enc = self.encode(img)?;
294 let mut tags: Vec<i64> = vec![START];
297 let mut out: Vec<i64> = Vec::new();
298 let mut prev_ucel = false;
299 let mut cache = DecodeCache::default();
300 let empty = self.empty_cache()?;
301 while out.len() < MAX_STEPS {
302 let (raw, _hidden) = self.decode_step(&tags, &enc, &mut cache, &empty)?;
303 let mut tag = raw;
304 if tag == XCEL {
305 tag = LCEL;
306 }
307 if prev_ucel && tag == LCEL {
308 tag = FCEL;
309 }
310 if tag == END {
311 break;
312 }
313 out.push(tag);
314 tags.push(tag);
315 prev_ucel = tag == UCEL;
316 }
317 Ok(out)
318 }
319
320 pub fn predict_table_structure(&mut self, img: &RgbImage) -> Result<Vec<TableCell>, String> {
326 let enc = self.encode(img)?;
327
328 let mut tags: Vec<i64> = vec![START];
329 let mut otsl: Vec<i64> = Vec::new();
330 let mut hiddens: Vec<f32> = Vec::new(); let mut n = 0usize;
332 let mut prev_ucel = false;
333 let mut skip = true; let mut first_lcel = true;
335 let mut bbox_ind = 0usize;
336 let mut cur_bbox_ind = 0usize;
337 let mut merge: std::collections::HashMap<usize, i64> = std::collections::HashMap::new();
338 let mut cache = DecodeCache::default();
339 let empty = self.empty_cache()?;
340 while otsl.len() < MAX_STEPS {
341 let (raw, hidden) = self.decode_step(&tags, &enc, &mut cache, &empty)?;
342 let mut tag = raw;
343 if tag == XCEL {
344 tag = LCEL;
345 }
346 if prev_ucel && tag == LCEL {
347 tag = FCEL;
348 }
349 if tag == END {
350 break;
351 }
352 if !skip && matches!(tag, FCEL | ECEL | CHED | RHED | SROW | NL | UCEL) {
354 hiddens.extend_from_slice(&hidden);
355 n += 1;
356 if !first_lcel {
357 merge.insert(cur_bbox_ind, bbox_ind as i64);
358 }
359 bbox_ind += 1;
360 }
361 if tag != LCEL {
362 first_lcel = true;
363 } else if first_lcel {
364 hiddens.extend_from_slice(&hidden);
365 n += 1;
366 first_lcel = false;
367 cur_bbox_ind = bbox_ind;
368 merge.insert(cur_bbox_ind, -1);
369 bbox_ind += 1;
370 }
371 skip = matches!(tag, NL | UCEL | XCEL);
372 prev_ucel = tag == UCEL;
373 otsl.push(tag);
374 tags.push(tag);
375 }
376 if n == 0 {
377 return Ok(Vec::new());
378 }
379 let tag_h = Tensor::from_array(([n, 512usize], hiddens))
380 .map_err(|e| format!("tableformer: tag_h: {e}"))?;
381 let bout = self
382 .bbox
383 .run(ort::inputs!["enc_out" => &enc.eo, "tag_h" => tag_h])
384 .map_err(|e| format!("tableformer: bbox: {e}"))?;
385 let (_, raw) = bout["boxes"]
386 .try_extract_tensor::<f32>()
387 .map_err(|e| format!("tableformer: boxes: {e}"))?;
388 let boxes: Vec<[f32; 4]> = raw
389 .chunks_exact(4)
390 .map(|c| [c[0], c[1], c[2], c[3]])
391 .collect();
392 let (_, craw) = bout["classes"]
394 .try_extract_tensor::<f32>()
395 .map_err(|e| format!("tableformer: classes: {e}"))?;
396 let classes: Vec<i64> = craw.chunks_exact(3).map(|c| argmax(c) as i64).collect();
397 let (merged, merged_classes) = merge_spans(&boxes, &classes, &merge);
398 Ok(build_table_cells(&otsl, &merged, &merged_classes))
399 }
400
401 pub fn predict_table_rows(
408 &mut self,
409 page_image: &RgbImage,
410 region: [f32; 4],
411 words: &[TextCell],
412 ) -> Option<Vec<Vec<String>>> {
413 let sf = 1024.0 / page_image.height() as f32;
422 let pw = (page_image.width() as f32 * sf) as u32;
423 let page1024 = crate::timing::timed("tableformer.inter_area", || {
424 crate::resample::inter_area(page_image, pw, 1024)
425 });
426 let k = 2.0 * 1024.0 / page_image.height() as f64;
427 let px = |v: f32| (v as f64).round_ties_even() * k;
428 let x = (px(region[0]).round_ties_even()).max(0.0) as u32;
429 let y = (px(region[1]).round_ties_even()).max(0.0) as u32;
430 let x2 = (px(region[2]).round_ties_even() as u32).min(page1024.width());
431 let y2 = (px(region[3]).round_ties_even() as u32).min(page1024.height());
432 if x2 <= x || y2 <= y {
433 return None;
434 }
435 let crop = image::imageops::crop_imm(&page1024, x, y, x2 - x, y2 - y).to_image();
436 let cells = crate::timing::timed("tableformer.structure", || {
437 self.predict_table_structure(&crop)
438 })
439 .ok()?;
440 if cells.is_empty() {
441 return None;
442 }
443 let table_words: Vec<crate::tf_match::PdfWord> = words
447 .iter()
448 .enumerate()
449 .filter(|(_, w)| !w.text.trim().is_empty())
450 .filter_map(|(wi, w)| {
451 let (l, t, r, b) = (w.l as f64, w.t as f64, w.r as f64, w.b as f64);
452 let area = (r - l) * (b - t);
453 let iw = (r.min(region[2] as f64) - l.max(region[0] as f64)).max(0.0);
454 let ih = (b.min(region[3] as f64) - t.max(region[1] as f64)).max(0.0);
455 if area > 0.0 && iw * ih / area > 0.8 {
456 Some(crate::tf_match::PdfWord {
457 id: wi,
458 bbox: [l, t, r, b],
459 text: w.text.trim().to_string(),
460 })
461 } else {
462 None
463 }
464 })
465 .collect();
466
467 if !table_words.is_empty() && !simple_match() {
468 return docling_match_rows(&cells, region, &table_words, words);
469 }
470
471 let (rw, rh) = (region[2] - region[0], region[3] - region[1]);
472
473 let boxes: Vec<[f32; 4]> = cells
475 .iter()
476 .map(|c| {
477 [
478 region[0] + (c.cx - c.w / 2.0) * rw,
479 region[1] + (c.cy - c.h / 2.0) * rh,
480 region[0] + (c.cx + c.w / 2.0) * rw,
481 region[1] + (c.cy + c.h / 2.0) * rh,
482 ]
483 })
484 .collect();
485
486 let mut cell_words: Vec<Vec<usize>> = vec![Vec::new(); cells.len()];
488 for (wi, w) in words.iter().enumerate() {
489 let wa = ((w.r - w.l) * (w.b - w.t)).max(1.0);
490 let mut best: Option<(f32, usize)> = None;
491 for (ci, b) in boxes.iter().enumerate() {
492 let ix = (w.r.min(b[2]) - w.l.max(b[0])).max(0.0);
493 let iy = (w.b.min(b[3]) - w.t.max(b[1])).max(0.0);
494 let io = ix * iy / wa;
495 if io > 0.0 && best.is_none_or(|(bo, _)| io > bo) {
496 best = Some((io, ci));
497 }
498 }
499 if let Some((_, ci)) = best {
500 cell_words[ci].push(wi);
501 }
502 }
503
504 let num_rows = cells.iter().map(|c| c.row + c.rowspan).max().unwrap_or(0);
505 let num_cols = cells.iter().map(|c| c.col + c.colspan).max().unwrap_or(0);
506 if num_rows == 0 || num_cols == 0 {
507 return None;
508 }
509 let mut grid = vec![vec![String::new(); num_cols]; num_rows];
510 for (ci, c) in cells.iter().enumerate() {
511 let wis = std::mem::take(&mut cell_words[ci]);
515 let text = wis
516 .iter()
517 .map(|&i| words[i].text.trim())
518 .collect::<Vec<_>>()
519 .join(" ");
520 let text = normalize_cell_text(text);
521 for row in grid.iter_mut().skip(c.row).take(c.rowspan) {
523 for cell in row.iter_mut().skip(c.col).take(c.colspan) {
524 *cell = text.clone();
525 }
526 }
527 }
528 Some(grid)
529 }
530}
531
532fn dump_match_inputs(
535 dir: &str,
536 tf_cells: &[crate::tf_match::TfCell],
537 words: &[crate::tf_match::PdfWord],
538) {
539 use std::io::Write;
540 let cells: Vec<String> = tf_cells
541 .iter()
542 .map(|c| {
543 format!(
544 r#"{{"bbox":[{},{},{},{}],"cell_id":{},"row_id":{},"column_id":{},"cell_class":{},"colspan_val":{},"rowspan_val":{}}}"#,
545 c.bbox[0], c.bbox[1], c.bbox[2], c.bbox[3],
546 c.cell_id, c.row_id, c.column_id, c.cell_class,
547 c.colspan_val, c.rowspan_val
548 )
549 })
550 .collect();
551 let ws: Vec<String> = words
552 .iter()
553 .map(|w| {
554 format!(
555 r#"{{"id":{},"bbox":[{},{},{},{}],"text":{}}}"#,
556 w.id,
557 w.bbox[0],
558 w.bbox[1],
559 w.bbox[2],
560 w.bbox[3],
561 serde_json_escape(&w.text)
562 )
563 })
564 .collect();
565 let line = format!(
566 r#"{{"table_cells":[{}],"pdf_cells":[{}]}}"#,
567 cells.join(","),
568 ws.join(",")
569 );
570 if let Ok(mut f) = std::fs::OpenOptions::new()
571 .create(true)
572 .append(true)
573 .open(format!("{dir}/tf_match_dump.jsonl"))
574 {
575 let _ = writeln!(f, "{line}");
576 }
577}
578
579fn serde_json_escape(s: &str) -> String {
581 let mut out = String::with_capacity(s.len() + 2);
582 out.push('"');
583 for ch in s.chars() {
584 match ch {
585 '"' => out.push_str("\\\""),
586 '\\' => out.push_str("\\\\"),
587 '\n' => out.push_str("\\n"),
588 '\r' => out.push_str("\\r"),
589 '\t' => out.push_str("\\t"),
590 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
591 c => out.push(c),
592 }
593 }
594 out.push('"');
595 out
596}
597
598fn simple_match() -> bool {
601 std::env::var("DOCLING_RS_TF_SIMPLE_MATCH").is_ok_and(|v| !v.is_empty() && v != "0")
602}
603
604fn normalize_cell_text(text: String) -> String {
610 text.replace("@ ", "@")
611}
612
613fn docling_match_rows(
621 cells: &[TableCell],
622 region: [f32; 4],
623 table_words: &[crate::tf_match::PdfWord],
624 words: &[TextCell],
625) -> Option<Vec<Vec<String>>> {
626 const SCALE: f64 = 2.0; let sl = (region[0] as f64).round_ties_even() * SCALE;
628 let st = (region[1] as f64).round_ties_even() * SCALE;
629 let sr = (region[2] as f64).round_ties_even() * SCALE;
630 let sb = (region[3] as f64).round_ties_even() * SCALE;
631 let (w2, h2) = (sr - sl, sb - st);
632
633 let tf_cells: Vec<crate::tf_match::TfCell> = cells
634 .iter()
635 .enumerate()
636 .map(|(i, c)| {
637 let (cx, cy) = (c.cx as f64, c.cy as f64);
638 let (w, h) = (c.w as f64, c.h as f64);
639 crate::tf_match::TfCell {
640 bbox: [
641 sl + (cx - w / 2.0) * w2,
642 st + (cy - h / 2.0) * h2,
643 sl + (cx + w / 2.0) * w2,
644 st + (cy + h / 2.0) * h2,
645 ],
646 cell_id: i,
647 row_id: c.row,
648 column_id: c.col,
649 cell_class: c.class,
650 colspan_val: if c.colspan > 1 { c.colspan } else { 0 },
651 rowspan_val: if c.rowspan > 1 { c.rowspan } else { 0 },
652 }
653 })
654 .collect();
655
656 let scaled_words: Vec<crate::tf_match::PdfWord> = table_words
657 .iter()
658 .map(|w| crate::tf_match::PdfWord {
659 id: w.id,
660 bbox: [
661 w.bbox[0] * SCALE,
662 w.bbox[1] * SCALE,
663 w.bbox[2] * SCALE,
664 w.bbox[3] * SCALE,
665 ],
666 text: w.text.clone(),
667 })
668 .collect();
669
670 if let Ok(dir) = std::env::var("DOCLING_RS_TF_MATCH_DUMP") {
673 if !dir.is_empty() {
674 dump_match_inputs(&dir, &tf_cells, &scaled_words);
675 }
676 }
677
678 let (cells_wo, final_matches) =
679 crate::tf_match::match_and_post_process(tf_cells, &scaled_words);
680
681 struct Merged {
684 start_row: usize,
685 start_col: usize,
686 row_span: usize,
687 col_span: usize,
688 word_ids: Vec<usize>,
689 }
690 let mut merged: Vec<Merged> = Vec::new();
691 let mut key_ix: std::collections::HashMap<(usize, usize), usize> =
692 std::collections::HashMap::new();
693 for (&pdf_id, list) in &final_matches {
694 let tm = list[0].table_cell_id;
695 let Some(cell) = cells_wo.iter().find(|c| c.cell_id == tm) else {
696 continue;
697 };
698 match key_ix.entry((cell.column_id, cell.row_id)) {
699 std::collections::hash_map::Entry::Occupied(e) => {
700 merged[*e.get()].word_ids.push(pdf_id);
701 }
702 std::collections::hash_map::Entry::Vacant(e) => {
703 e.insert(merged.len());
704 merged.push(Merged {
705 start_row: cell.row_id,
706 start_col: cell.column_id,
707 row_span: cell.rowspan_val.max(1),
708 col_span: cell.colspan_val.max(1),
709 word_ids: vec![pdf_id],
710 });
711 }
712 }
713 }
714 if merged.is_empty() {
715 return None;
716 }
717
718 let mut start_cols: Vec<usize> = merged.iter().map(|m| m.start_col).collect();
721 start_cols.sort_unstable();
722 start_cols.dedup();
723 let mut start_rows: Vec<usize> = merged.iter().map(|m| m.start_row).collect();
724 start_rows.sort_unstable();
725 start_rows.dedup();
726 let mut num_rows = 0;
727 let mut num_cols = 0;
728 for m in &mut merged {
729 m.start_col = start_cols.binary_search(&m.start_col).expect("own value");
730 m.start_row = start_rows.binary_search(&m.start_row).expect("own value");
731 num_cols = num_cols.max(m.start_col + m.col_span);
732 num_rows = num_rows.max(m.start_row + m.row_span);
733 }
734 if num_rows == 0 || num_cols == 0 {
735 return None;
736 }
737
738 let mut grid = vec![vec![String::new(); num_cols]; num_rows];
739 for m in &merged {
740 let text = m
741 .word_ids
742 .iter()
743 .map(|&i| words[i].text.trim())
744 .collect::<Vec<_>>()
745 .join(" ");
746 let text = normalize_cell_text(text);
747 for row in grid.iter_mut().skip(m.start_row).take(m.row_span) {
748 for cell in row.iter_mut().skip(m.start_col).take(m.col_span) {
749 *cell = text.clone();
750 }
751 }
752 }
753 Some(grid)
754}
755
756fn warn_missing_once(enc: &str, dec: &str, bbx: &str) {
763 static WARNED: std::sync::Once = std::sync::Once::new();
764 WARNED.call_once(|| {
765 eprintln!(
766 "docling.rs: TableFormer models not found (checked {enc}, {dec}, {bbx}); \
767 tables will use geometric reconstruction instead of ML table-structure \
768 recognition. Set DOCLING_TABLEFORMER_ENCODER / DOCLING_TABLEFORMER_DECODER \
769 / DOCLING_TABLEFORMER_BBOX to enable it (see README.md)."
770 );
771 });
772}
773
774fn preprocess(img: &RgbImage) -> Result<Tensor<f32>, String> {
779 let nn = (SIDE * SIDE) as usize;
780 let side = SIDE as usize;
781 let (sw, sh) = (img.width() as i32, img.height() as i32);
782 let sxr = sw as f32 / SIDE as f32;
783 let syr = sh as f32 / SIDE as f32;
784 let mut data = vec![0f32; 3 * nn];
785 for h in 0..side {
786 let fy = (h as f32 + 0.5) * syr - 0.5;
787 let wy = fy - fy.floor();
788 let y0c = (fy.floor() as i32).clamp(0, sh - 1) as u32;
789 let y1c = (fy.floor() as i32 + 1).clamp(0, sh - 1) as u32;
790 for w in 0..side {
791 let fx = (w as f32 + 0.5) * sxr - 0.5;
792 let wx = fx - fx.floor();
793 let x0c = (fx.floor() as i32).clamp(0, sw - 1) as u32;
794 let x1c = (fx.floor() as i32 + 1).clamp(0, sw - 1) as u32;
795 let p00 = img.get_pixel(x0c, y0c);
796 let p01 = img.get_pixel(x1c, y0c);
797 let p10 = img.get_pixel(x0c, y1c);
798 let p11 = img.get_pixel(x1c, y1c);
799 let idx = w * side + h; for c in 0..3 {
801 let top = p00[c] as f32 * (1.0 - wx) + p01[c] as f32 * wx;
802 let bot = p10[c] as f32 * (1.0 - wx) + p11[c] as f32 * wx;
803 let v = top * (1.0 - wy) + bot * wy;
804 data[c * nn + idx] = (v / 255.0 - MEAN[c]) / STD[c];
805 }
806 }
807 }
808 Tensor::from_array(([1usize, 3, side, side], data))
809 .map_err(|e| format!("tableformer: input: {e}"))
810}
811
812fn mergebboxes(b1: [f32; 4], b2: [f32; 4]) -> [f32; 4] {
815 let new_w = (b2[0] + b2[2] / 2.0) - (b1[0] - b1[2] / 2.0);
816 let new_h = (b2[1] + b2[3] / 2.0) - (b1[1] - b1[3] / 2.0);
817 let new_left = b1[0] - b1[2] / 2.0;
818 let new_top = (b2[1] - b2[3] / 2.0).min(b1[1] - b1[3] / 2.0);
819 [new_left + new_w / 2.0, new_top + new_h / 2.0, new_w, new_h]
820}
821
822fn merge_spans(
826 boxes: &[[f32; 4]],
827 classes: &[i64],
828 merge: &std::collections::HashMap<usize, i64>,
829) -> (Vec<[f32; 4]>, Vec<i64>) {
830 let skip: std::collections::HashSet<usize> = merge
831 .values()
832 .filter(|&&v| v >= 0)
833 .map(|&v| v as usize)
834 .collect();
835 let mut out = Vec::new();
836 let mut out_classes = Vec::new();
837 for (i, &b) in boxes.iter().enumerate() {
838 let class = classes.get(i).copied().unwrap_or(2);
839 if let Some(&j) = merge.get(&i) {
840 let partner = if j < 0 { boxes.len() - 1 } else { j as usize };
841 out.push(mergebboxes(b, boxes[partner.min(boxes.len() - 1)]));
842 out_classes.push(class);
843 } else if !skip.contains(&i) {
844 out.push(b);
845 out_classes.push(class);
846 }
847 }
848 (out, out_classes)
849}
850
851const CELL_TAGS: [i64; 6] = [FCEL, ECEL, XCEL, CHED, RHED, SROW];
852
853fn build_table_cells(otsl: &[i64], boxes: &[[f32; 4]], classes: &[i64]) -> Vec<TableCell> {
859 let mut grid: Vec<Vec<i64>> = vec![Vec::new()];
861 for &t in otsl {
862 if t == NL {
863 grid.push(Vec::new());
864 } else {
865 grid.last_mut().unwrap().push(t);
866 }
867 }
868 let mut cells = Vec::new();
869 let mut cell_id = 0usize;
870 for (r, row) in grid.iter().enumerate() {
871 for (c, &tag) in row.iter().enumerate() {
872 if !CELL_TAGS.contains(&tag) {
873 continue;
874 }
875 let mut colspan = 1;
876 while c + colspan < row.len() && matches!(row[c + colspan], LCEL | XCEL) {
877 colspan += 1;
878 }
879 let mut rowspan = 1;
880 while r + rowspan < grid.len()
881 && grid[r + rowspan]
882 .get(c)
883 .is_some_and(|&t| matches!(t, UCEL | XCEL))
884 {
885 rowspan += 1;
886 }
887 let b = boxes.get(cell_id).copied().unwrap_or([0.0; 4]);
888 let class = classes.get(cell_id).copied().unwrap_or(2);
890 cells.push(TableCell {
891 row: r,
892 col: c,
893 colspan,
894 rowspan,
895 tag,
896 class,
897 cx: b[0],
898 cy: b[1],
899 w: b[2],
900 h: b[3],
901 });
902 cell_id += 1;
903 }
904 }
905 cells
906}
907
908fn argmax(v: &[f32]) -> usize {
909 v.iter()
910 .enumerate()
911 .max_by(|a, b| a.1.total_cmp(b.1))
912 .map(|(i, _)| i)
913 .unwrap_or(0)
914}