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