1use image::RgbImage;
15
16pub const SIDE: u32 = 448;
18#[allow(clippy::excessive_precision)]
21pub const MEAN: [f32; 3] = [0.94247851, 0.94254675, 0.94292611];
22#[allow(clippy::excessive_precision)]
23pub const STD: [f32; 3] = [0.17910956, 0.17940403, 0.17931663];
24pub const MAX_STEPS: usize = 1024;
26pub const EMBED_DIM: usize = 512;
28
29pub const START: i64 = 2;
31pub const END: i64 = 3;
32pub 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; const CELL_TAGS: [i64; 6] = [FCEL, ECEL, XCEL, CHED, RHED, SROW];
43
44#[derive(Debug, Clone)]
48pub struct TableCell {
49 pub row: usize,
50 pub col: usize,
51 pub colspan: usize,
52 pub rowspan: usize,
53 pub tag: i64,
54 pub class: i64,
55 pub cx: f32,
56 pub cy: f32,
57 pub w: f32,
58 pub h: f32,
59}
60
61pub fn preprocess_input(img: &RgbImage) -> Vec<f32> {
66 let nn = (SIDE * SIDE) as usize;
67 let side = SIDE as usize;
68 let (sw, sh) = (img.width() as i32, img.height() as i32);
69 let sxr = sw as f32 / SIDE as f32;
70 let syr = sh as f32 / SIDE as f32;
71 let mut data = vec![0f32; 3 * nn];
72 for h in 0..side {
73 let fy = (h as f32 + 0.5) * syr - 0.5;
74 let wy = fy - fy.floor();
75 let y0c = (fy.floor() as i32).clamp(0, sh - 1) as u32;
76 let y1c = (fy.floor() as i32 + 1).clamp(0, sh - 1) as u32;
77 for w in 0..side {
78 let fx = (w as f32 + 0.5) * sxr - 0.5;
79 let wx = fx - fx.floor();
80 let x0c = (fx.floor() as i32).clamp(0, sw - 1) as u32;
81 let x1c = (fx.floor() as i32 + 1).clamp(0, sw - 1) as u32;
82 let p00 = img.get_pixel(x0c, y0c);
83 let p01 = img.get_pixel(x1c, y0c);
84 let p10 = img.get_pixel(x0c, y1c);
85 let p11 = img.get_pixel(x1c, y1c);
86 let idx = w * side + h; for c in 0..3 {
88 let top = p00[c] as f32 * (1.0 - wx) + p01[c] as f32 * wx;
89 let bot = p10[c] as f32 * (1.0 - wx) + p11[c] as f32 * wx;
90 let v = top * (1.0 - wy) + bot * wy;
91 data[c * nn + idx] = (v / 255.0 - MEAN[c]) / STD[c];
92 }
93 }
94 }
95 data
96}
97
98pub fn correct(raw: i64, prev_ucel: bool) -> i64 {
102 let mut tag = raw;
103 if tag == XCEL {
104 tag = LCEL;
105 }
106 if prev_ucel && tag == LCEL {
107 tag = FCEL;
108 }
109 tag
110}
111
112#[derive(Default)]
119pub struct BboxBook {
120 pub tags: Vec<i64>,
122 pub otsl: Vec<i64>,
124 pub hiddens: Vec<f32>,
126 pub n: usize,
128 pub merge: std::collections::HashMap<usize, i64>,
130 prev_ucel: bool,
131 skip: bool,
132 first_lcel: bool,
133 bbox_ind: usize,
134 cur_bbox_ind: usize,
135}
136
137impl BboxBook {
138 pub fn new() -> Self {
139 Self {
140 tags: vec![START],
141 skip: true, first_lcel: true,
143 ..Default::default()
144 }
145 }
146
147 pub fn step(&mut self, raw: i64, hidden: &[f32]) -> bool {
150 let tag = correct(raw, self.prev_ucel);
151 if tag == END {
152 return false;
153 }
154 if !self.skip && matches!(tag, FCEL | ECEL | CHED | RHED | SROW | NL | UCEL) {
156 self.hiddens.extend_from_slice(hidden);
157 self.n += 1;
158 if !self.first_lcel {
159 self.merge.insert(self.cur_bbox_ind, self.bbox_ind as i64);
160 }
161 self.bbox_ind += 1;
162 }
163 if tag != LCEL {
164 self.first_lcel = true;
165 } else if self.first_lcel {
166 self.hiddens.extend_from_slice(hidden);
167 self.n += 1;
168 self.first_lcel = false;
169 self.cur_bbox_ind = self.bbox_ind;
170 self.merge.insert(self.cur_bbox_ind, -1);
171 self.bbox_ind += 1;
172 }
173 self.skip = matches!(tag, NL | UCEL | XCEL);
174 self.prev_ucel = tag == UCEL;
175 self.otsl.push(tag);
176 self.tags.push(tag);
177 true
178 }
179}
180
181fn mergebboxes(b1: [f32; 4], b2: [f32; 4]) -> [f32; 4] {
184 let new_w = (b2[0] + b2[2] / 2.0) - (b1[0] - b1[2] / 2.0);
185 let new_h = (b2[1] + b2[3] / 2.0) - (b1[1] - b1[3] / 2.0);
186 let new_left = b1[0] - b1[2] / 2.0;
187 let new_top = (b2[1] - b2[3] / 2.0).min(b1[1] - b1[3] / 2.0);
188 [new_left + new_w / 2.0, new_top + new_h / 2.0, new_w, new_h]
189}
190
191pub fn merge_spans(
195 boxes: &[[f32; 4]],
196 classes: &[i64],
197 merge: &std::collections::HashMap<usize, i64>,
198) -> (Vec<[f32; 4]>, Vec<i64>) {
199 let skip: std::collections::HashSet<usize> = merge
200 .values()
201 .filter(|&&v| v >= 0)
202 .map(|&v| v as usize)
203 .collect();
204 let mut out = Vec::new();
205 let mut out_classes = Vec::new();
206 for (i, &b) in boxes.iter().enumerate() {
207 let class = classes.get(i).copied().unwrap_or(2);
208 if let Some(&j) = merge.get(&i) {
209 let partner = if j < 0 { boxes.len() - 1 } else { j as usize };
210 out.push(mergebboxes(b, boxes[partner.min(boxes.len() - 1)]));
211 out_classes.push(class);
212 } else if !skip.contains(&i) {
213 out.push(b);
214 out_classes.push(class);
215 }
216 }
217 (out, out_classes)
218}
219
220pub fn build_table_cells(otsl: &[i64], boxes: &[[f32; 4]], classes: &[i64]) -> Vec<TableCell> {
226 let mut grid: Vec<Vec<i64>> = vec![Vec::new()];
228 for &t in otsl {
229 if t == NL {
230 grid.push(Vec::new());
231 } else {
232 grid.last_mut().unwrap().push(t);
233 }
234 }
235 let mut cells = Vec::new();
236 let mut cell_id = 0usize;
237 for (r, row) in grid.iter().enumerate() {
238 for (c, &tag) in row.iter().enumerate() {
239 if !CELL_TAGS.contains(&tag) {
240 continue;
241 }
242 let mut colspan = 1;
243 while c + colspan < row.len() && matches!(row[c + colspan], LCEL | XCEL) {
244 colspan += 1;
245 }
246 let mut rowspan = 1;
247 while r + rowspan < grid.len()
248 && grid[r + rowspan]
249 .get(c)
250 .is_some_and(|&t| matches!(t, UCEL | XCEL))
251 {
252 rowspan += 1;
253 }
254 let b = boxes.get(cell_id).copied().unwrap_or([0.0; 4]);
255 let class = classes.get(cell_id).copied().unwrap_or(2);
257 cells.push(TableCell {
258 row: r,
259 col: c,
260 colspan,
261 rowspan,
262 tag,
263 class,
264 cx: b[0],
265 cy: b[1],
266 w: b[2],
267 h: b[3],
268 });
269 cell_id += 1;
270 }
271 }
272 cells
273}
274
275pub fn argmax(v: &[f32]) -> usize {
279 v.iter()
280 .enumerate()
281 .max_by(|a, b| a.1.total_cmp(b.1))
282 .map(|(i, _)| i)
283 .unwrap_or(0)
284}
285
286use crate::pdfium_backend::TextCell;
287use crate::tf_match::{PdfWord, TfCell};
288
289pub fn table_rows(
296 cells: &[TableCell],
297 region: [f32; 4],
298 words: &[TextCell],
299) -> Option<Vec<Vec<String>>> {
300 let table_words: Vec<PdfWord> = words
304 .iter()
305 .enumerate()
306 .filter(|(_, w)| !w.text.trim().is_empty())
307 .filter_map(|(wi, w)| {
308 let (l, t, r, b) = (w.l as f64, w.t as f64, w.r as f64, w.b as f64);
309 let area = (r - l) * (b - t);
310 let iw = (r.min(region[2] as f64) - l.max(region[0] as f64)).max(0.0);
311 let ih = (b.min(region[3] as f64) - t.max(region[1] as f64)).max(0.0);
312 if area > 0.0 && iw * ih / area > 0.8 {
313 Some(PdfWord {
314 id: wi,
315 bbox: [l, t, r, b],
316 text: w.text.trim().to_string(),
317 })
318 } else {
319 None
320 }
321 })
322 .collect();
323
324 if !table_words.is_empty() && !simple_match() {
325 return docling_match_rows(cells, region, &table_words, words);
326 }
327
328 let (rw, rh) = (region[2] - region[0], region[3] - region[1]);
329
330 let boxes: Vec<[f32; 4]> = cells
332 .iter()
333 .map(|c| {
334 [
335 region[0] + (c.cx - c.w / 2.0) * rw,
336 region[1] + (c.cy - c.h / 2.0) * rh,
337 region[0] + (c.cx + c.w / 2.0) * rw,
338 region[1] + (c.cy + c.h / 2.0) * rh,
339 ]
340 })
341 .collect();
342
343 let mut cell_words: Vec<Vec<usize>> = vec![Vec::new(); cells.len()];
345 for (wi, w) in words.iter().enumerate() {
346 let wa = ((w.r - w.l) * (w.b - w.t)).max(1.0);
347 let mut best: Option<(f32, usize)> = None;
348 for (ci, b) in boxes.iter().enumerate() {
349 let ix = (w.r.min(b[2]) - w.l.max(b[0])).max(0.0);
350 let iy = (w.b.min(b[3]) - w.t.max(b[1])).max(0.0);
351 let io = ix * iy / wa;
352 if io > 0.0 && best.is_none_or(|(bo, _)| io > bo) {
353 best = Some((io, ci));
354 }
355 }
356 if let Some((_, ci)) = best {
357 cell_words[ci].push(wi);
358 }
359 }
360
361 let num_rows = cells.iter().map(|c| c.row + c.rowspan).max().unwrap_or(0);
362 let num_cols = cells.iter().map(|c| c.col + c.colspan).max().unwrap_or(0);
363 if num_rows == 0 || num_cols == 0 {
364 return None;
365 }
366 let mut grid = vec![vec![String::new(); num_cols]; num_rows];
367 for (ci, c) in cells.iter().enumerate() {
368 let wis = std::mem::take(&mut cell_words[ci]);
371 let text = wis
372 .iter()
373 .map(|&i| words[i].text.trim())
374 .collect::<Vec<_>>()
375 .join(" ");
376 let text = normalize_cell_text(text);
377 for row in grid.iter_mut().skip(c.row).take(c.rowspan) {
379 for cell in row.iter_mut().skip(c.col).take(c.colspan) {
380 *cell = text.clone();
381 }
382 }
383 }
384 Some(grid)
385}
386
387fn simple_match() -> bool {
390 std::env::var("DOCLING_RS_TF_SIMPLE_MATCH").is_ok_and(|v| !v.is_empty() && v != "0")
391}
392
393fn normalize_cell_text(text: String) -> String {
398 text.replace("@ ", "@")
399}
400
401fn docling_match_rows(
409 cells: &[TableCell],
410 region: [f32; 4],
411 table_words: &[PdfWord],
412 words: &[TextCell],
413) -> Option<Vec<Vec<String>>> {
414 const SCALE: f64 = 2.0; let sl = (region[0] as f64).round_ties_even() * SCALE;
416 let st = (region[1] as f64).round_ties_even() * SCALE;
417 let sr = (region[2] as f64).round_ties_even() * SCALE;
418 let sb = (region[3] as f64).round_ties_even() * SCALE;
419 let (w2, h2) = (sr - sl, sb - st);
420
421 let tf_cells: Vec<TfCell> = cells
422 .iter()
423 .enumerate()
424 .map(|(i, c)| {
425 let (cx, cy) = (c.cx as f64, c.cy as f64);
426 let (w, h) = (c.w as f64, c.h as f64);
427 TfCell {
428 bbox: [
429 sl + (cx - w / 2.0) * w2,
430 st + (cy - h / 2.0) * h2,
431 sl + (cx + w / 2.0) * w2,
432 st + (cy + h / 2.0) * h2,
433 ],
434 cell_id: i,
435 row_id: c.row,
436 column_id: c.col,
437 cell_class: c.class,
438 colspan_val: if c.colspan > 1 { c.colspan } else { 0 },
439 rowspan_val: if c.rowspan > 1 { c.rowspan } else { 0 },
440 }
441 })
442 .collect();
443
444 let scaled_words: Vec<PdfWord> = table_words
445 .iter()
446 .map(|w| PdfWord {
447 id: w.id,
448 bbox: [
449 w.bbox[0] * SCALE,
450 w.bbox[1] * SCALE,
451 w.bbox[2] * SCALE,
452 w.bbox[3] * SCALE,
453 ],
454 text: w.text.clone(),
455 })
456 .collect();
457
458 #[cfg(feature = "ml")]
461 if let Ok(dir) = std::env::var("DOCLING_RS_TF_MATCH_DUMP") {
462 if !dir.is_empty() {
463 dump_match_inputs(&dir, &tf_cells, &scaled_words);
464 }
465 }
466
467 let (cells_wo, final_matches) =
468 crate::tf_match::match_and_post_process(tf_cells, &scaled_words);
469
470 struct Merged {
473 start_row: usize,
474 start_col: usize,
475 row_span: usize,
476 col_span: usize,
477 word_ids: Vec<usize>,
478 }
479 let mut merged: Vec<Merged> = Vec::new();
480 let mut key_ix: std::collections::HashMap<(usize, usize), usize> =
481 std::collections::HashMap::new();
482 for (&pdf_id, list) in &final_matches {
483 let tm = list[0].table_cell_id;
484 let Some(cell) = cells_wo.iter().find(|c| c.cell_id == tm) else {
485 continue;
486 };
487 match key_ix.entry((cell.column_id, cell.row_id)) {
488 std::collections::hash_map::Entry::Occupied(e) => {
489 merged[*e.get()].word_ids.push(pdf_id);
490 }
491 std::collections::hash_map::Entry::Vacant(e) => {
492 e.insert(merged.len());
493 merged.push(Merged {
494 start_row: cell.row_id,
495 start_col: cell.column_id,
496 row_span: cell.rowspan_val.max(1),
497 col_span: cell.colspan_val.max(1),
498 word_ids: vec![pdf_id],
499 });
500 }
501 }
502 }
503 if merged.is_empty() {
504 return None;
505 }
506
507 let mut start_cols: Vec<usize> = merged.iter().map(|m| m.start_col).collect();
510 start_cols.sort_unstable();
511 start_cols.dedup();
512 let mut start_rows: Vec<usize> = merged.iter().map(|m| m.start_row).collect();
513 start_rows.sort_unstable();
514 start_rows.dedup();
515 let mut num_rows = 0;
516 let mut num_cols = 0;
517 for m in &mut merged {
518 m.start_col = start_cols.binary_search(&m.start_col).expect("own value");
519 m.start_row = start_rows.binary_search(&m.start_row).expect("own value");
520 num_cols = num_cols.max(m.start_col + m.col_span);
521 num_rows = num_rows.max(m.start_row + m.row_span);
522 }
523 if num_rows == 0 || num_cols == 0 {
524 return None;
525 }
526
527 let mut grid = vec![vec![String::new(); num_cols]; num_rows];
528 for m in &merged {
529 let text = m
530 .word_ids
531 .iter()
532 .map(|&i| words[i].text.trim())
533 .collect::<Vec<_>>()
534 .join(" ");
535 let text = normalize_cell_text(text);
536 for row in grid.iter_mut().skip(m.start_row).take(m.row_span) {
537 for cell in row.iter_mut().skip(m.start_col).take(m.col_span) {
538 *cell = text.clone();
539 }
540 }
541 }
542 Some(grid)
543}
544
545#[cfg(feature = "ml")]
548fn dump_match_inputs(dir: &str, tf_cells: &[TfCell], words: &[PdfWord]) {
549 use std::io::Write;
550 let cells: Vec<String> = tf_cells
551 .iter()
552 .map(|c| {
553 format!(
554 r#"{{"bbox":[{},{},{},{}],"cell_id":{},"row_id":{},"column_id":{},"cell_class":{},"colspan_val":{},"rowspan_val":{}}}"#,
555 c.bbox[0], c.bbox[1], c.bbox[2], c.bbox[3],
556 c.cell_id, c.row_id, c.column_id, c.cell_class,
557 c.colspan_val, c.rowspan_val
558 )
559 })
560 .collect();
561 let ws: Vec<String> = words
562 .iter()
563 .map(|w| {
564 format!(
565 r#"{{"id":{},"bbox":[{},{},{},{}],"text":{}}}"#,
566 w.id,
567 w.bbox[0],
568 w.bbox[1],
569 w.bbox[2],
570 w.bbox[3],
571 serde_json_escape(&w.text)
572 )
573 })
574 .collect();
575 let line = format!(
576 r#"{{"table_cells":[{}],"pdf_cells":[{}]}}"#,
577 cells.join(","),
578 ws.join(",")
579 );
580 if let Ok(mut f) = std::fs::OpenOptions::new()
581 .create(true)
582 .append(true)
583 .open(format!("{dir}/tf_match_dump.jsonl"))
584 {
585 let _ = writeln!(f, "{line}");
586 }
587}
588
589#[cfg(feature = "ml")]
591fn serde_json_escape(s: &str) -> String {
592 let mut out = String::with_capacity(s.len() + 2);
593 out.push('"');
594 for ch in s.chars() {
595 match ch {
596 '"' => out.push_str("\\\""),
597 '\\' => out.push_str("\\\\"),
598 '\n' => out.push_str("\\n"),
599 '\r' => out.push_str("\\r"),
600 '\t' => out.push_str("\\t"),
601 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
602 c => out.push(c),
603 }
604 }
605 out.push('"');
606 out
607}
608
609#[cfg(test)]
610mod tests {
611 use super::*;
612
613 #[test]
614 fn corrections() {
615 assert_eq!(correct(XCEL, false), LCEL); assert_eq!(correct(LCEL, true), FCEL); assert_eq!(correct(XCEL, true), FCEL); assert_eq!(correct(FCEL, false), FCEL);
619 assert_eq!(correct(LCEL, false), LCEL);
620 }
621
622 #[test]
623 fn argmax_behaviour() {
624 assert_eq!(argmax(&[0.1, 0.9, 0.3]), 1);
625 assert_eq!(argmax(&[0.5, 0.5]), 1); assert_eq!(argmax(&[]), 0);
627 }
628
629 #[test]
630 fn book_skips_first_and_collects_hiddens() {
631 let mut b = BboxBook::new();
635 let h = [1.0f32; EMBED_DIM];
636 assert!(b.step(FCEL, &h)); assert!(b.step(FCEL, &h));
638 assert!(b.step(NL, &h));
639 assert!(!b.step(END, &h)); assert_eq!(b.otsl, vec![FCEL, FCEL, NL]);
641 assert_eq!(b.n, 2);
643 assert_eq!(b.hiddens.len(), 2 * EMBED_DIM);
644 assert!(b.merge.is_empty());
645 }
646
647 #[test]
648 fn book_merges_horizontal_span() {
649 let mut b = BboxBook::new();
652 let h = [0.0f32; EMBED_DIM];
653 b.step(FCEL, &h); b.step(FCEL, &h); b.step(LCEL, &h); assert_eq!(b.merge.get(&1), Some(&-1));
657 }
658
659 #[test]
660 fn build_cells_spans() {
661 let otsl = vec![FCEL, LCEL, NL, FCEL, ECEL];
664 let boxes = vec![[0.0; 4]; 3];
665 let classes = vec![2, 2, 2];
666 let cells = build_table_cells(&otsl, &boxes, &classes);
667 assert_eq!(cells.len(), 3);
668 assert_eq!((cells[0].colspan, cells[0].rowspan), (2, 1));
669 assert_eq!((cells[0].row, cells[0].col), (0, 0));
670 assert_eq!((cells[1].row, cells[1].col), (1, 0));
671 }
672}