Skip to main content

docling_pdf/
tf_core.rs

1//! ONNX-free half of the TableFormer pipeline: the 448 encoder-input
2//! preprocessing, the autoregressive loop's structure corrections and bbox
3//! bookkeeping, span merging, and the OTSL→grid layout. Everything here is pure
4//! Rust (no `ort`), so the browser build (#157 stage 3) runs the *same*
5//! conformance-critical logic the native pipeline does and delegates only the
6//! three ONNX graphs (encoder / decoder / bbox) to ONNX Runtime Web. Keeping
7//! one implementation is what keeps the wasm table structure identical to the
8//! native CPU path; drift can only come from the runtime kernels.
9//!
10//! `tableformer.rs` (native, `ml` feature) owns the `ort` sessions and the
11//! owned-value KV-cache fast path; it calls into here for the parts that don't
12//! touch the runtime.
13
14use image::RgbImage;
15
16/// The encoder's fixed square input side.
17pub const SIDE: u32 = 448;
18// Verbatim from docling's tm_config.json image_normalization (more digits than
19// f32 holds; kept exact for provenance).
20#[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];
24/// Cap on decode steps (docling's generation limit).
25pub const MAX_STEPS: usize = 1024;
26/// The decoder hidden width, and the bbox decoder's per-cell `tag_h` stride.
27pub const EMBED_DIM: usize = 512;
28
29/// OTSL structure tokens (TableModel04_rs wordmap indices).
30pub const START: i64 = 2;
31pub const END: i64 = 3;
32pub const ECEL: i64 = 4; // empty cell
33pub const FCEL: i64 = 5; // full (content) cell
34pub const LCEL: i64 = 6; // left-looking: extends the cell to its left (colspan)
35pub const UCEL: i64 = 7; // up-looking: extends the cell above (rowspan)
36pub const XCEL: i64 = 8; // cross: spans both ways
37pub const NL: i64 = 9; // new row
38pub const CHED: i64 = 10; // column header
39pub const RHED: i64 = 11; // row header
40pub const SROW: i64 = 12; // section row
41
42const CELL_TAGS: [i64; 6] = [FCEL, ECEL, XCEL, CHED, RHED, SROW];
43
44/// A predicted table cell: an OTSL grid position (with spans) + its box in the
45/// 448 image normalized cxcywh, the OTSL tag, and the bbox decoder's cell
46/// class (docling's `cell_class`; 2 = full, ≤1 = predicted empty).
47#[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
61/// Resize `img` to `SIDE×SIDE` (bilinear, aligned to docling's half-pixel
62/// centers) and normalize, laid out `(C, W, H)` as the exported encoder expects
63/// — the raw `[1,3,SIDE,SIDE]` float buffer. The native path wraps this in an
64/// `ort` tensor; the browser path hands it to ONNX Runtime Web directly.
65pub 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; // (C, W, H): c*n + w*H + h
87            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
98/// docling's two structure corrections, applied to a raw argmax tag: `xcel`
99/// collapses to `lcel` (its `line_num` is never incremented, so this fires on
100/// every row), and an `lcel` right after a `ucel` becomes a full cell.
101pub 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/// The autoregressive loop's per-step state, mirroring docling's `predict`
113/// bookkeeping (`tag_H_buf` / `bboxes_to_merge`): which decoder hidden states
114/// feed the bbox decoder and how horizontal spans merge. Both the native and
115/// browser loops step the decoder themselves (sync vs async `ort`) and feed
116/// each result through [`step`](Self::step); everything else stays here so the
117/// two paths can't drift.
118#[derive(Default)]
119pub struct BboxBook {
120    /// The decoder input prefix (`[START]`, then every emitted tag).
121    pub tags: Vec<i64>,
122    /// The emitted OTSL structure tokens (no `START`/`END`).
123    pub otsl: Vec<i64>,
124    /// Per-bbox-cell decoder hidden states, flattened `[n, EMBED_DIM]`.
125    pub hiddens: Vec<f32>,
126    /// Number of hidden states collected (`hiddens.len() / EMBED_DIM`).
127    pub n: usize,
128    /// Span merges: `cur_bbox_ind → partner` (`-1` → the last box).
129    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 tag after <start> is skipped
142            first_lcel: true,
143            ..Default::default()
144        }
145    }
146
147    /// Feed one raw decoded tag and its hidden state. Returns `false` when the
148    /// corrected tag is `END` (stop decoding) — the tag is not recorded then.
149    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        // docling's tag_H_buf / bboxes_to_merge bookkeeping.
155        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
181/// docling's `mergebboxes` (cxcywh): the union box of a horizontal span's first
182/// and last cell.
183fn 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
191/// Apply docling's span merges: each merge key combines its box with the partner
192/// (`-1` → the last box); partners are dropped. The merged cell keeps the
193/// *first* box's class, matching docling's `outputs_class1.append(cls1)`.
194pub 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
220/// Lay the OTSL tag stream onto a grid (docling's `_build_table_cells`, OTSL
221/// mode): cell tags create cells at (row, col); `lcel`/`ucel`/`xcel` are spans
222/// (counted toward the column index but not cells). Colspan/rowspan are read off
223/// the grid (consecutive `lcel`/`ucel` to the right/below). `boxes` are indexed
224/// by cell order and aligned with the cells.
225pub fn build_table_cells(otsl: &[i64], boxes: &[[f32; 4]], classes: &[i64]) -> Vec<TableCell> {
226    // 2D grid of tags (rows split on NL) for span lookups.
227    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            // docling defaults a class-less cell to 2 (full).
256            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
275/// Index of the maximum. Uses Rust's `max_by` (ties resolve to the *last*
276/// index; the decoder/bbox float logits don't produce exact ties in practice).
277/// Kept verbatim from the native path so the two stay bit-identical.
278pub 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
289/// The ONNX-free tail of TableFormer row prediction: match the page's word
290/// cells into the predicted structure `cells` and expand spans into a dense
291/// `rows × cols` text grid. `region` is `(l, t, r, b)` in page points; `cells`
292/// are in the 448 image (normalized cxcywh). Shared by the native pipeline
293/// (after `predict_table_structure`) and the browser path (after the ort-web
294/// decode loop) — identical from here on. `None` when nothing matched.
295pub fn table_rows(
296    cells: &[TableCell],
297    region: [f32; 4],
298    words: &[TextCell],
299) -> Option<Vec<Vec<String>>> {
300    // Words that belong to the table: non-empty text, ≥80 % of the word's area
301    // inside the table region (docling's `get_cells_in_bbox` ios test). Ids stay
302    // the page-level word indices so text joins in stream order.
303    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    // Cell boxes in page points (top-left), aligned with `cells`.
331    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    // Assign each word to the cell it overlaps most (intersection / word area).
344    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        // Keep words in text-stream order (their word index), matching docling's
369        // cell text assembly — geometric re-sorting scrambles wrapped cells.
370        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        // Spanned cells repeat their text across the covered grid positions.
378        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
387/// `DOCLING_RS_TF_SIMPLE_MATCH=1` reverts to the pre-#60 best-overlap word
388/// assignment (A/B escape hatch for the docling matching post-processor).
389fn simple_match() -> bool {
390    std::env::var("DOCLING_RS_TF_SIMPLE_MATCH").is_ok_and(|v| !v.is_empty() && v != "0")
391}
392
393/// docling glues `@` to whatever follows it (`mAP @0.5`, an email): the PDF's
394/// word cells split `@` from the next token, and joining with a space would
395/// widen the cell and — via the column pad — shift every row. The groundtruth
396/// never contains "@ ", so this is always the right normalization.
397fn normalize_cell_text(text: String) -> String {
398    text.replace("@ ", "@")
399}
400
401/// docling's matched-cell grid assembly (`tf_predictor.predict` with
402/// `do_cell_matching=True`): run the ported matching post-processor, group the
403/// word→cell assignments per grid position, compress the surviving row/column
404/// ids to sequential indexes, and expand spans into a dense `rows × cols` text
405/// grid. Matching runs in docling's coordinate space — the table bbox rounded
406/// to integers, everything ×2 (its page scale) — so the post-processor's
407/// absolute rounding agrees.
408fn 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; // docling's table-structure page scale
415    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    // Debug (native only): dump the matcher inputs as JSON lines for a
459    // side-by-side run against docling's Python post-processor.
460    #[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    // `_merge_tf_output`: group per (column, row) in ascending-pdf-id order; the
471    // first word's table cell fixes the group's offsets and spans.
472    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    // `multi_table_predict`'s sort_row_col_indexes: compress the surviving
508    // row/column ids to gap-free indexes.
509    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/// Append one JSON line per table into `<dir>/tf_match_dump.jsonl` with the
546/// exact matcher inputs (hand-rolled JSON to avoid a serde dependency).
547#[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/// Minimal JSON string escaping for the parity dump.
590#[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); // xcel → lcel
616        assert_eq!(correct(LCEL, true), FCEL); // lcel after ucel → fcel
617        assert_eq!(correct(XCEL, true), FCEL); // xcel → lcel → fcel
618        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); // Rust max_by ties to the last index
626        assert_eq!(argmax(&[]), 0);
627    }
628
629    #[test]
630    fn book_skips_first_and_collects_hiddens() {
631        // <start> then a 2x1 row: FCEL FCEL NL, END. The first FCEL after start
632        // is NOT skipped (skip only guards the tag right after start-consumed
633        // rows); verify hidden collection count and merge stays empty.
634        let mut b = BboxBook::new();
635        let h = [1.0f32; EMBED_DIM];
636        assert!(b.step(FCEL, &h)); // skip=true initially → not collected
637        assert!(b.step(FCEL, &h));
638        assert!(b.step(NL, &h));
639        assert!(!b.step(END, &h)); // stop
640        assert_eq!(b.otsl, vec![FCEL, FCEL, NL]);
641        // first FCEL skipped (skip=true), second FCEL + NL collected → n=2
642        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        // FCEL LCEL: the LCEL is the first-lcel of a horizontal span → records a
650        // merge partner (-1 placeholder) for the span's leading cell.
651        let mut b = BboxBook::new();
652        let h = [0.0f32; EMBED_DIM];
653        b.step(FCEL, &h); // skipped (skip=true)
654        b.step(FCEL, &h); // collected, bbox_ind 0→1
655        b.step(LCEL, &h); // first-lcel: cur=1, merge{1:-1}, bbox_ind 1→2
656        assert_eq!(b.merge.get(&1), Some(&-1));
657    }
658
659    #[test]
660    fn build_cells_spans() {
661        // Row 0: FCEL LCEL  (a 1x2 colspan)
662        // Row 1: FCEL ECEL
663        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}