Skip to main content

docling_core/
json.rs

1//! Export a [`DoclingDocument`] to docling-core's native JSON wire format
2//! (`DoclingDocument` schema v1.10.0) — the same shape `export_to_dict()` /
3//! `save_as_json()` produce in Python docling, and the inverse of the
4//! JSON-docling reader.
5//!
6//! The crate's [`Node`] model bakes Markdown escaping (and inline markers) into
7//! its text, whereas docling stores raw text and escapes at render time. We
8//! therefore *un-escape* on the way out so a docling-core round-trip
9//! (`load_from_json().export_to_markdown()`) reproduces the same Markdown.
10
11use serde_json::{json, Value};
12
13use crate::document::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
14
15const SCHEMA_VERSION: &str = "1.10.0";
16
17/// docling-core's `CodeLanguageLabel` values (anything else serializes as
18/// `unknown`, which the model requires for code items).
19const CODE_LANGUAGES: &[&str] = &[
20    "Ada",
21    "Awk",
22    "Bash",
23    "bc",
24    "C",
25    "C#",
26    "C++",
27    "CMake",
28    "COBOL",
29    "CSS",
30    "Ceylon",
31    "Clojure",
32    "Crystal",
33    "Cuda",
34    "Cython",
35    "D",
36    "Dart",
37    "dc",
38    "Dockerfile",
39    "DocLang",
40    "Elixir",
41    "Erlang",
42    "FORTRAN",
43    "Forth",
44    "Go",
45    "HTML",
46    "Haskell",
47    "Haxe",
48    "Java",
49    "JavaScript",
50    "JSON",
51    "Julia",
52    "Kotlin",
53    "Latex",
54    "Lisp",
55    "Lua",
56    "Matlab",
57    "MoonScript",
58    "Nim",
59    "OCaml",
60    "ObjectiveC",
61    "Octave",
62    "PHP",
63    "Pascal",
64    "Perl",
65    "Prolog",
66    "Python",
67    "Racket",
68    "Ruby",
69    "Rust",
70    "SML",
71    "SQL",
72    "Scala",
73    "Scheme",
74    "Swift",
75    "Tikz",
76    "TypeScript",
77    "VisualBasic",
78    "XML",
79    "YAML",
80];
81
82/// Map a fence language to docling's `CodeLanguageLabel` (case-insensitive), else
83/// `unknown`.
84/// docling's `CodeLanguageLabel` for a language name (`unknown` when it is
85/// not one docling knows) — the mapping the JSON `code_language` field uses,
86/// for a backend that wants to test a hint before storing it.
87pub fn code_language_label(lang: &str) -> &'static str {
88    code_language(Some(lang))
89}
90
91pub(crate) fn code_language(lang: Option<&str>) -> &'static str {
92    match lang {
93        Some(l) => CODE_LANGUAGES
94            .iter()
95            .find(|c| c.eq_ignore_ascii_case(l))
96            .copied()
97            .unwrap_or("unknown"),
98        None => "unknown",
99    }
100}
101
102/// An item's exact provenance, written verbatim (see [`Builder::prov_json`]):
103/// a [`Node::Prov`] wrapper's top-left page box, or a tree item's
104/// [`TreeProv`](crate::tree::TreeProv).
105#[derive(Clone, Copy)]
106struct ExactProv {
107    page_no: usize,
108    bbox: [f64; 4],
109    bottom_left: bool,
110    charspan: [usize; 2],
111}
112
113impl From<&crate::tree::TreeProv> for ExactProv {
114    fn from(p: &crate::tree::TreeProv) -> Self {
115        ExactProv {
116            page_no: p.page_no,
117            bbox: p.bbox,
118            bottom_left: p.bottom_left,
119            charspan: p.charspan,
120        }
121    }
122}
123
124/// docling-core's `_clamp_provenance_bboxes_to_pages`: each `prov` box of
125/// every item on a known page is clamped to `[0, width] × [0, height]`
126/// (whatever its `coord_origin` — docling clamps the stored numbers), and a
127/// table whose provenance sits on one page has its cell boxes clamped too.
128fn clamp_boxes_to_pages(out: &mut Value, pages: &[(usize, f64, f64)]) {
129    if pages.is_empty() {
130        return;
131    }
132    let size = |page_no: &Value| -> Option<(f64, f64)> {
133        let n = page_no.as_u64()? as usize;
134        pages
135            .iter()
136            .find(|(p, _, _)| *p == n)
137            .map(|(_, w, h)| (*w, *h))
138    };
139    let r2 = |v: f64| (v * 100.0).round() / 100.0;
140    let clamp_bbox = |bbox: &mut Value, (w, h): (f64, f64)| {
141        for (key, hi) in [("l", w), ("r", w), ("t", h), ("b", h)] {
142            if let Some(v) = bbox.get(key).and_then(Value::as_f64) {
143                bbox[key] = json!(r2(v.clamp(0.0, hi.max(0.0))));
144            }
145        }
146    };
147    for bucket in [
148        "texts",
149        "pictures",
150        "tables",
151        "key_value_items",
152        "form_items",
153        "field_regions",
154        "field_items",
155    ] {
156        let Some(items) = out.get_mut(bucket).and_then(Value::as_array_mut) else {
157            continue;
158        };
159        for item in items {
160            let mut table_page: Option<Option<(f64, f64)>> = None;
161            if let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) {
162                let mut page_nos: Vec<u64> = Vec::new();
163                for prov in provs.iter_mut() {
164                    if let Some(n) = prov.get("page_no").and_then(Value::as_u64) {
165                        page_nos.push(n);
166                    }
167                    let Some(sz) = prov.get("page_no").and_then(size) else {
168                        continue;
169                    };
170                    if let Some(bbox) = prov.get_mut("bbox") {
171                        clamp_bbox(bbox, sz);
172                    }
173                }
174                page_nos.sort_unstable();
175                page_nos.dedup();
176                if let [only] = page_nos[..] {
177                    table_page = Some(size(&json!(only)));
178                }
179            }
180            // A table's cells (and the `grid` docling derives from them).
181            if let (Some(Some(sz)), Some(data)) = (table_page, item.get_mut("data")) {
182                for key in ["table_cells", "grid"] {
183                    let Some(rows) = data.get_mut(key).and_then(Value::as_array_mut) else {
184                        continue;
185                    };
186                    for entry in rows.iter_mut() {
187                        let cells: Vec<&mut Value> = match entry {
188                            Value::Array(row) => row.iter_mut().collect(),
189                            other => vec![other],
190                        };
191                        for cell in cells {
192                            if let Some(bbox) = cell.get_mut("bbox").filter(|b| b.is_object()) {
193                                clamp_bbox(bbox, sz);
194                            }
195                        }
196                    }
197                }
198            }
199        }
200    }
201}
202
203/// docling-core's `Formatting` model, every field written.
204fn formatting_json(f: &crate::tree::Formatting) -> Value {
205    json!({
206        "bold": f.bold,
207        "italic": f.italic,
208        "underline": f.underline,
209        "strikethrough": f.strikethrough,
210        "script": match f.script {
211            crate::Script::Baseline => "baseline",
212            crate::Script::Sub => "sub",
213            crate::Script::Super => "super",
214        },
215    })
216}
217
218/// docling's `TrackSource` entry: `kind`, the two offsets, then the optional
219/// `identifier` / `voice` (dropped when `None`, as `exclude_none` does).
220fn track_json(t: &crate::tree::TreeTrack) -> Value {
221    let mut m = serde_json::Map::new();
222    m.insert("kind".into(), json!("track"));
223    m.insert("start_time".into(), json!(t.start_time));
224    m.insert("end_time".into(), json!(t.end_time));
225    if let Some(id) = &t.identifier {
226        m.insert("identifier".into(), json!(id));
227    }
228    if let Some(v) = &t.voice {
229        m.insert("voice".into(), json!(v));
230    }
231    Value::Object(m)
232}
233
234/// Build the docling-core JSON object for `doc`.
235pub fn to_json(doc: &DoclingDocument) -> Value {
236    let mut b = Builder::default();
237    // A backend that built docling's item tree ([`crate::tree`]) has already
238    // decided every parent, child and creation index; serialize that. The
239    // flat nodes are for the other serializers.
240    let body = match &doc.tree {
241        Some(tree) => {
242            // The page map still comes from the flat stream's markers (a
243            // PPTX slide's EMU size): the tree holds items, not pages.
244            for n in &doc.nodes {
245                if let Node::PageInfo {
246                    page_no,
247                    width,
248                    height,
249                } = n
250                {
251                    if *page_no > 0 {
252                        b.pages.push((*page_no, *width as f64, *height as f64));
253                    }
254                }
255            }
256            b.write_tree(tree)
257        }
258        None => b.walk_into(&doc.nodes, "#/body"),
259    };
260    b.link_comments();
261
262    let mut out = json!({
263        "schema_name": "DoclingDocument",
264        "version": SCHEMA_VERSION,
265        "name": doc.name,
266        "origin": {
267            "mimetype": "text/plain",
268            "binary_hash": fnv1a(&doc.name),
269            "filename": doc.name,
270        },
271        "furniture": {
272            "self_ref": "#/furniture",
273            "children": [],
274            "content_layer": "furniture",
275            "name": "_root_",
276            "label": "unspecified",
277        },
278        "body": {
279            "self_ref": "#/body",
280            "children": body,
281            "content_layer": "body",
282            "name": "_root_",
283            "label": "unspecified",
284        },
285        "groups": b.groups,
286        "texts": b.texts,
287        "pictures": b.pictures,
288        "tables": b.tables,
289        "key_value_items": b.key_value_items,
290        "form_items": [],
291        "pages": b.pages.iter().map(|(n, w, h)| {
292            let r2 = |v: f64| (v * 100.0).round() / 100.0;
293            (n.to_string(), json!({
294                "size": { "width": r2(*w), "height": r2(*h) },
295                "page_no": n,
296            }))
297        }).collect::<serde_json::Map<String, Value>>(),
298    });
299
300    // docling-core's `validate_document` — a pydantic `model_validator` every
301    // `DoclingDocument` passes through when a `ConversionResult` (or a
302    // serializer) is built around it — clamps every provenance box, and a
303    // table's cell boxes, into its page's bounds in place
304    // (`_clamp_provenance_bboxes_to_pages`). The JSON docling writes therefore
305    // carries the clamped boxes: a spreadsheet region whose page was sized
306    // `right − left` × `bottom − top` loses its offset, a slide shape hanging
307    // off the slide edge is cut at it. Reproduce that on the finished items.
308    clamp_boxes_to_pages(&mut out, &b.pages);
309
310    // docling only emits `field_regions` / `field_items` when a document has
311    // form fields, and places them just before `pages`. Insert them in that slot
312    // (re-appending `pages` afterwards, since `preserve_order` keeps insertion
313    // order) so non-KVP documents' JSON is byte-identical to before.
314    if !b.field_regions.is_empty() {
315        if let Some(obj) = out.as_object_mut() {
316            let pages = obj.remove("pages");
317            obj.insert("field_regions".into(), Value::Array(b.field_regions));
318            obj.insert("field_items".into(), Value::Array(b.field_items));
319            if let Some(pages) = pages {
320                obj.insert("pages".into(), pages);
321            }
322        }
323    }
324    out
325}
326
327/// A DocumentPictureClassifier's predictions as the picture's `meta` — they
328/// land twice, exactly like docling 2.x writes them: the newer
329/// `meta.classification` field (pydantic field order: confidence, created_by,
330/// class_name) and the deprecated-but-still-emitted `classification`
331/// annotation, carried here under an `annotations` key that `add_picture`
332/// lifts onto the item.
333fn classification_meta(classes: &[crate::PictureClass]) -> Value {
334    json!({
335        "classification": {
336            "predictions": classes.iter().map(|c| json!({
337                "confidence": c.confidence as f64,
338                "created_by": "DocumentPictureClassifier",
339                "class_name": c.class_name,
340            })).collect::<Vec<_>>(),
341        },
342        "annotations": [{
343            "kind": "classification",
344            "provenance": "DocumentPictureClassifier",
345            "predicted_classes": classes.iter().map(|c| json!({
346                "class_name": c.class_name,
347                "confidence": c.confidence as f64,
348            })).collect::<Vec<_>>(),
349        }],
350    })
351}
352
353/// docling's `TableData` for a table: `table_cells`, `num_rows`/`num_cols`
354/// and the `grid` that repeats each cell at every position it covers. Shared
355/// by table items and a chart picture's `meta.tabular_chart.chart_data`.
356/// One table cell as docling's `TableCell` JSON: the eleven fields in
357/// pydantic order, `bbox` appended when the cell carries one. Built straight
358/// into a `Map` sized for the entries — the table grid repeats every cell
359/// object once per spanned slot, so on a table-heavy document (a patent's
360/// claims tables, an EBCDIC dump) this constructor and its clones *are* the
361/// JSON export's cost; the `json!` macro built the same object through a
362/// growing map with a rehash per doubling.
363#[allow(clippy::too_many_arguments)]
364fn cell_value(
365    row_span: usize,
366    col_span: usize,
367    start_row: usize,
368    end_row: usize,
369    start_col: usize,
370    end_col: usize,
371    text: String,
372    column_header: bool,
373    row_header: bool,
374    row_section: bool,
375    bbox: Option<[f32; 4]>,
376) -> Value {
377    let mut m = serde_json::Map::with_capacity(12);
378    m.insert("row_span".into(), row_span.into());
379    m.insert("col_span".into(), col_span.into());
380    m.insert("start_row_offset_idx".into(), start_row.into());
381    m.insert("end_row_offset_idx".into(), end_row.into());
382    m.insert("start_col_offset_idx".into(), start_col.into());
383    m.insert("end_col_offset_idx".into(), end_col.into());
384    m.insert("text".into(), Value::String(text));
385    m.insert("column_header".into(), column_header.into());
386    m.insert("row_header".into(), row_header.into());
387    m.insert("row_section".into(), row_section.into());
388    m.insert("fillable".into(), false.into());
389    if let Some(b) = bbox {
390        m.insert(
391            "bbox".into(),
392            json!({
393                "l": b[0], "t": b[1], "r": b[2], "b": b[3],
394                "coord_origin": "TOPLEFT",
395            }),
396        );
397    }
398    Value::Object(m)
399}
400
401/// `TableData` from a table whose cell text is Markdown-flavoured (the flat
402/// nodes: escapes to undo, GFM hard-break markers to strip).
403fn table_data(t: &Table) -> Value {
404    table_data_with(t, false)
405}
406
407/// `TableData`; with `raw` the cell text is docling's own raw cell text (a
408/// backend-built tree) and is written verbatim.
409fn table_data_with(t: &Table, raw: bool) -> Value {
410    let cell_text = |s: &str| {
411        if raw {
412            s.to_string()
413        } else {
414            unescape_text(&crate::markdown::strip_hard_breaks(s))
415        }
416    };
417    let mut num_rows = t.rows.len();
418    let mut num_cols = t.rows.iter().map(Vec::len).max().unwrap_or(0);
419    // Rectangular `rows` are the grid, and cells reaching past it are
420    // clipped — docling's own `TableData.grid` on a USPTO table whose
421    // replicated cells outrun `num_cols`, or an HTML rowspan past the last
422    // row. Ragged rows are no grid at all: a backend that compacts them
423    // (xlsx `skip_empty_cells`, #271) keeps the true offsets in first-class
424    // cells, so there the grid spans every cell's extent and the omitted
425    // positions come back as docling's empty filler cells.
426    let ragged = t.rows.iter().any(|r| r.len() != num_cols);
427    if let Some(first_class) = t.cells.as_ref().filter(|c| ragged && !c.is_empty()) {
428        for c in first_class {
429            num_rows = num_rows.max(c.start_row + c.row_span);
430            num_cols = num_cols.max(c.start_col + c.col_span);
431        }
432    }
433    let mut grid = Vec::with_capacity(num_rows);
434    let mut cells = Vec::new();
435    // Grid slot → index into `cells` (the anchor cell covering it). A flat
436    // row-major table instead of a `HashMap<(r, c), Value>` of clones: the
437    // grid is filled from it with one clone per slot, and nothing is hashed.
438    let mut slot: Vec<Option<usize>> = vec![None; num_rows * num_cols];
439    if let Some(first_class) = t.cells.as_ref().filter(|c| !c.is_empty()) {
440        for c in first_class {
441            let idx = cells.len();
442            cells.push(cell_value(
443                c.row_span,
444                c.col_span,
445                c.start_row,
446                c.start_row + c.row_span,
447                c.start_col,
448                c.start_col + c.col_span,
449                cell_text(&c.text),
450                c.column_header,
451                c.row_header,
452                c.row_section,
453                c.bbox,
454            ));
455            for r in c.start_row..(c.start_row + c.row_span).min(num_rows) {
456                for k in c.start_col..(c.start_col + c.col_span).min(num_cols) {
457                    slot[r * num_cols + k] = Some(idx);
458                }
459            }
460        }
461        for r in 0..num_rows {
462            let mut grid_row = Vec::with_capacity(num_cols);
463            for c in 0..num_cols {
464                grid_row.push(match slot[r * num_cols + c] {
465                    Some(i) => cells[i].clone(),
466                    None => cell_value(
467                        1,
468                        1,
469                        r,
470                        r + 1,
471                        c,
472                        c + 1,
473                        String::new(),
474                        false,
475                        false,
476                        false,
477                        None,
478                    ),
479                });
480            }
481            grid.push(grid_row);
482        }
483    } else {
484        let s = t.structure.as_ref();
485        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| -> bool {
486            grid.and_then(|g| g.get(r))
487                .and_then(|row| row.get(c))
488                .copied()
489                .unwrap_or(false)
490        };
491        let anchor_of = |r: usize, c: usize| -> (usize, usize) {
492            let (mut r0, mut c0) = (r, c);
493            while c0 > 0 && flag(s.map(|s| &s.col_continuation), r, c0) {
494                c0 -= 1;
495            }
496            while r0 > 0 && flag(s.map(|s| &s.row_continuation), r0, c0) {
497                r0 -= 1;
498            }
499            (r0, c0)
500        };
501        // Each slot's anchor, computed once; the anchor's extent is the
502        // farthest slot that resolves to it.
503        let anchors: Vec<(usize, usize)> = (0..num_rows)
504            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
505            .map(|(r, c)| anchor_of(r, c))
506            .collect();
507        let mut extent: Vec<(usize, usize)> = (0..num_rows)
508            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
509            .collect();
510        for (i, &(ar, ac)) in anchors.iter().enumerate() {
511            let (r, c) = (i / num_cols.max(1), i % num_cols.max(1));
512            let e = &mut extent[ar * num_cols + ac];
513            e.0 = e.0.max(r);
514            e.1 = e.1.max(c);
515        }
516        for (r, row) in t.rows.iter().enumerate() {
517            let mut grid_row = Vec::with_capacity(num_cols);
518            for c in 0..num_cols {
519                let (ar, ac) = anchors[r * num_cols + c];
520                if (ar, ac) == (r, c) {
521                    let (er, ec) = extent[r * num_cols + c];
522                    let text = row.get(c).map(|s| cell_text(s)).unwrap_or_default();
523                    let column_header = match s.filter(|s| !s.col_header.is_empty()) {
524                        Some(s) => flag(Some(&s.col_header), r, c),
525                        None => r == 0,
526                    };
527                    slot[r * num_cols + c] = Some(cells.len());
528                    cells.push(cell_value(
529                        er - r + 1,
530                        ec - c + 1,
531                        r,
532                        er + 1,
533                        c,
534                        ec + 1,
535                        text,
536                        column_header,
537                        flag(s.map(|s| &s.row_header), r, c),
538                        false,
539                        None,
540                    ));
541                }
542                grid_row.push(match slot[ar * num_cols + ac] {
543                    Some(i) => cells[i].clone(),
544                    None => Value::Null,
545                });
546            }
547            grid.push(grid_row);
548        }
549    }
550    json!({
551        "table_cells": cells,
552        "num_rows": num_rows,
553        "num_cols": num_cols,
554        "orientation": "rot_0",
555        "grid": grid,
556    })
557}
558
559#[derive(Default)]
560struct Builder {
561    texts: Vec<Value>,
562    groups: Vec<Value>,
563    tables: Vec<Value>,
564    pictures: Vec<Value>,
565    field_regions: Vec<Value>,
566    field_items: Vec<Value>,
567    key_value_items: Vec<Value>,
568    /// Pages seen so far (`page_no`, width, height in points) — from the
569    /// [`Node::PageInfo`] markers the PDF paths emit; empty for every other
570    /// backend, which keeps their JSON byte-identical (`"pages": {}`, no prov).
571    pages: Vec<(usize, f64, f64)>,
572    /// The page the walk is currently on (0 before the first marker).
573    cur_page: usize,
574    cur_w: f64,
575    cur_h: f64,
576    /// The enclosing [`Node::Located`] wrapper's 0–511 grid box, waiting to be
577    /// consumed as the next item's provenance.
578    pending_loc: Option<[u16; 4]>,
579    /// The enclosing [`Node::Prov`] wrapper's (or the tree item's) exact
580    /// provenance, which takes precedence over the grid box.
581    pending_exact: Option<ExactProv>,
582    /// `$ref`s an item wants placed in its parent's `children` *before* its
583    /// own — a chart's caption item, which docling's office backends add to
584    /// the container ahead of the picture that references it.
585    pending_siblings: Vec<Value>,
586    /// `$ref`s an item wants placed in its parent's `children` right *after*
587    /// its own — an HTML `<figure>`-wrapped table's caption
588    /// ([`CaptionParent::ContainerAfter`]).
589    pending_after: Vec<Value>,
590    /// Caption `$ref`s that hang off `#/body` while their item sits deeper
591    /// ([`CaptionParent::Body`]): docling appends them to the body's children
592    /// as they are created, so they follow the top-level item being walked.
593    pending_body: Vec<Value>,
594    /// What each [`Node::CommentSection`] is referenced by, in document order —
595    /// its group `$ref`, or its note text's when the section says so. The index
596    /// is what a [`Node::Commented`] annotation carries.
597    comment_groups: Vec<String>,
598    /// The last `comment_section` group emitted, as `(name, self_ref)`: a
599    /// following section of the same name adds its note to that group rather
600    /// than opening another — one `comment-{sheet}-{cell}` group holds every
601    /// message of a threaded comment (docling#4353).
602    last_comment_section: Option<(String, String)>,
603    /// Annotated items awaiting their refs: comments are usually emitted
604    /// *after* the body they annotate (docx appends them), so the link is
605    /// patched in once the whole document has been walked.
606    pending_comments: Vec<(String, Vec<usize>)>,
607}
608
609impl Builder {
610    /// Consume the pending location (if any) into a docling `prov` array: the
611    /// 0-511 grid denormalized against the current page into BOTTOMLEFT
612    /// points, rounded to 2 decimals like docling's own export. `char_len` is
613    /// the item's text length in characters (0 for tables and pictures, whose
614    /// charspan docling emits as `[0, 0]`).
615    fn take_prov(&mut self, char_len: usize) -> Value {
616        let prov = self.prov_json(char_len, false);
617        self.pending_exact = None;
618        self.pending_loc = None;
619        prov
620    }
621
622    /// The pending provenance without consuming it. An exact [`Node::Prov`]
623    /// box wins over the grid; its own `charspan` is used unless
624    /// `span_over_text` asks for `[0, char_len]` (a chart caption's span
625    /// covers the caption text where the chart's is `[0, 0]`).
626    fn prov_json(&self, char_len: usize, span_over_text: bool) -> Value {
627        let r2 = |v: f64| (v * 100.0).round() / 100.0;
628        if let Some(ExactProv {
629            page_no,
630            bbox: [l, t, r, b],
631            bottom_left,
632            charspan,
633        }) = self.pending_exact
634        {
635            let charspan = if span_over_text {
636                [0, char_len]
637            } else {
638                charspan
639            };
640            return json!([{
641                "page_no": page_no,
642                "bbox": {
643                    "l": r2(l), "t": r2(t), "r": r2(r), "b": r2(b),
644                    "coord_origin": if bottom_left { "BOTTOMLEFT" } else { "TOPLEFT" },
645                },
646                "charspan": charspan,
647            }]);
648        }
649        let Some([x0, y0, x1, y1]) = self.pending_loc else {
650            return json!([]);
651        };
652        // An all-zero grid box is the sentinel for "this item has no geometry"
653        // (a slide's speaker notes, say). docling writes a zero bbox for it,
654        // not a box spanning the page, which is what denormalizing would give.
655        if [x0, y0, x1, y1] == [0, 0, 0, 0] {
656            return json!([{
657                "page_no": self.cur_page,
658                "bbox": { "l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT" },
659                "charspan": [0, char_len],
660            }]);
661        }
662        json!([{
663            "page_no": self.cur_page,
664            "bbox": {
665                "l": r2(x0 as f64 * self.cur_w / 512.0),
666                "t": r2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
667                "r": r2(x1 as f64 * self.cur_w / 512.0),
668                "b": r2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
669                "coord_origin": "BOTTOMLEFT",
670            },
671            "charspan": [0, char_len],
672        }])
673    }
674
675    /// Adopt a node's own location field (tables, formulas, list items carry
676    /// one instead of a [`Node::Located`] wrapper) when no wrapper is pending.
677    fn adopt_loc(&mut self, loc: Option<[u16; 4]>) {
678        if self.pending_loc.is_none() && self.cur_page > 0 {
679            self.pending_loc = loc;
680        }
681    }
682
683    /// Resolve the [`Node::Commented`] annotations collected during the walk
684    /// into docling's `comments: [{"$ref": "#/groups/N"}]` key on the annotated
685    /// item. It has to run after the whole walk: docx appends its comment
686    /// bodies, so the groups they live in are usually allocated *later* than
687    /// the paragraphs pointing at them. docling emits the key between `prov`
688    /// and `orig`, so insert it in place rather than appending (serde_json runs
689    /// with `preserve_order`, i.e. key order is output order).
690    fn link_comments(&mut self) {
691        let refs: Vec<(String, Vec<Value>)> = std::mem::take(&mut self.pending_comments)
692            .into_iter()
693            .map(|(item, comments)| {
694                let refs = comments
695                    .iter()
696                    .filter_map(|i| self.comment_groups.get(*i))
697                    .map(|r| json!({ "$ref": r }))
698                    .collect();
699                (item, refs)
700            })
701            .collect();
702        for (item, comment_refs) in refs {
703            if comment_refs.is_empty() {
704                continue;
705            }
706            let Some(target) = self.item_mut(&item) else {
707                continue;
708            };
709            let Some(obj) = target.as_object_mut() else {
710                continue;
711            };
712            let tail: Vec<(String, Value)> = obj
713                .iter()
714                .skip_while(|(k, _)| k.as_str() != "prov")
715                .skip(1)
716                .map(|(k, v)| (k.clone(), v.clone()))
717                .collect();
718            for (k, _) in &tail {
719                obj.shift_remove(k);
720            }
721            obj.insert("comments".into(), Value::Array(comment_refs));
722            for (k, v) in tail {
723                obj.insert(k, v);
724            }
725        }
726    }
727
728    /// The stored JSON object a `#/texts/N`-style self-ref points at.
729    fn item_mut(&mut self, self_ref: &str) -> Option<&mut Value> {
730        let idx = ref_index(self_ref)?;
731        let bucket = if self_ref.starts_with("#/texts/") {
732            &mut self.texts
733        } else if self_ref.starts_with("#/tables/") {
734            &mut self.tables
735        } else if self_ref.starts_with("#/pictures/") {
736            &mut self.pictures
737        } else if self_ref.starts_with("#/groups/") {
738            &mut self.groups
739        } else {
740            return None;
741        };
742        bucket.get_mut(idx)
743    }
744
745    /// Serialize a backend-built [`ItemTree`](crate::tree::ItemTree): every
746    /// item in creation order into its bucket, with the parent / children /
747    /// layer the tree recorded. Returns the body's `children` refs.
748    fn write_tree(&mut self, tree: &crate::tree::ItemTree) -> Vec<Value> {
749        use crate::tree::TreeKind;
750        // Every item's `self_ref` first: children may be listed before they
751        // are written (a rich cell's group is created after its content).
752        let mut refs: Vec<String> = Vec::with_capacity(tree.items.len());
753        let (mut nt, mut ng, mut ntb, mut np, mut nf, mut nk) = (0, 0, 0, 0, 0, 0);
754        for item in &tree.items {
755            if item.deleted {
756                refs.push(String::new());
757                continue;
758            }
759            let r = match &item.kind {
760                TreeKind::Text { .. } | TreeKind::Code { .. } => {
761                    nt += 1;
762                    format!("#/texts/{}", nt - 1)
763                }
764                TreeKind::Group { .. } => {
765                    ng += 1;
766                    format!("#/groups/{}", ng - 1)
767                }
768                TreeKind::Table { .. } => {
769                    ntb += 1;
770                    format!("#/tables/{}", ntb - 1)
771                }
772                TreeKind::Picture { .. } => {
773                    np += 1;
774                    format!("#/pictures/{}", np - 1)
775                }
776                TreeKind::FieldRegion { items } => {
777                    // A region's marker / key / value parts are text items
778                    // too, numbered where docling creates them.
779                    nt += items
780                        .iter()
781                        .map(|i| {
782                            [&i.marker, &i.key, &i.value]
783                                .iter()
784                                .filter(|p| p.is_some())
785                                .count()
786                        })
787                        .sum::<usize>();
788                    nf += 1;
789                    format!("#/field_regions/{}", nf - 1)
790                }
791                TreeKind::KeyValueGraph { .. } => {
792                    nk += 1;
793                    format!("#/key_value_items/{}", nk - 1)
794                }
795            };
796            refs.push(r);
797        }
798        let ref_of = |id: usize| json!({ "$ref": refs[id] });
799        for (id, item) in tree.items.iter().enumerate() {
800            if item.deleted {
801                continue;
802            }
803            let parent = item.parent.map_or("#/body", |p| refs[p].as_str());
804            let children: Vec<Value> = item.children.iter().map(|&c| ref_of(c)).collect();
805            let layer = item.layer.map_or("body", |l| l.value());
806            // The item's own provenance, consumed by the writer below
807            // (`take_prov`); an item without one writes `prov: []`.
808            self.pending_exact = item.prov.as_ref().map(ExactProv::from);
809            let self_ref = match &item.kind {
810                TreeKind::Text {
811                    label,
812                    text,
813                    orig,
814                    formatting,
815                    hyperlink,
816                    level,
817                    list,
818                } => {
819                    // docling's field order: …, text, formatting, hyperlink,
820                    // then the subclass fields (`level`; `enumerated`, `marker`).
821                    let mut tail = serde_json::Map::new();
822                    if let Some(f) = formatting {
823                        tail.insert("formatting".into(), formatting_json(f));
824                    }
825                    if let Some(h) = hyperlink {
826                        tail.insert("hyperlink".into(), json!(h));
827                    }
828                    if let Some(l) = level {
829                        tail.insert("level".into(), json!(l));
830                    }
831                    if let Some(l) = list {
832                        tail.insert("enumerated".into(), json!(l.enumerated));
833                        tail.insert("marker".into(), json!(l.marker));
834                    }
835                    let r = format!("#/texts/{}", self.texts.len());
836                    let prov = self.take_prov(text.chars().count());
837                    let mut item_json = json!({
838                        "self_ref": r,
839                        "parent": { "$ref": parent },
840                        "children": children,
841                        "content_layer": layer,
842                        "label": label,
843                        "prov": prov,
844                    });
845                    // docling's `comments` back-refs sit between `prov` and
846                    // `orig`, and are written only when set.
847                    if !item.comments.is_empty() {
848                        item_json["comments"] =
849                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
850                    }
851                    // `DocItem.source`, likewise only when set: a WebVTT
852                    // cue's `TrackSource`, whose `None` fields are omitted.
853                    if let Some(track) = &item.source {
854                        item_json["source"] = json!([track_json(track)]);
855                    }
856                    merge(
857                        &mut item_json,
858                        json!({
859                            "orig": orig.as_deref().unwrap_or(text),
860                            "text": text,
861                        }),
862                    );
863                    merge(&mut item_json, Value::Object(tail));
864                    self.texts.push(item_json);
865                    r
866                }
867                TreeKind::Code {
868                    text,
869                    orig,
870                    language,
871                    formatting,
872                    hyperlink,
873                } => {
874                    let r = format!("#/texts/{}", self.texts.len());
875                    let prov = self.take_prov(text.chars().count());
876                    let mut item_json = json!({
877                        "self_ref": r,
878                        "parent": { "$ref": parent },
879                        "children": children,
880                        "content_layer": layer,
881                        "label": "code",
882                        "prov": prov,
883                    });
884                    if !item.comments.is_empty() {
885                        item_json["comments"] =
886                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
887                    }
888                    merge(
889                        &mut item_json,
890                        json!({
891                            "orig": orig.as_deref().unwrap_or(text),
892                            "text": text,
893                        }),
894                    );
895                    if let Some(f) = formatting {
896                        item_json["formatting"] = formatting_json(f);
897                    }
898                    if let Some(h) = hyperlink {
899                        item_json["hyperlink"] = json!(h);
900                    }
901                    merge(
902                        &mut item_json,
903                        json!({
904                            "captions": [],
905                            "references": [],
906                            "footnotes": [],
907                            "code_language": code_language(language.as_deref()),
908                        }),
909                    );
910                    self.texts.push(item_json);
911                    r
912                }
913                TreeKind::Group { label, name } => {
914                    self.pending_exact = None;
915                    let r = format!("#/groups/{}", self.groups.len());
916                    self.groups.push(json!({
917                        "self_ref": r,
918                        "parent": { "$ref": parent },
919                        "children": children,
920                        "content_layer": layer,
921                        "name": name,
922                        "label": label,
923                    }));
924                    r
925                }
926                TreeKind::Table {
927                    table,
928                    rich_cells,
929                    captions,
930                } => {
931                    // docling's raw cell text: nothing to unescape or strip.
932                    let r = self.add_table_with(table, parent, true);
933                    let idx = ref_index(&r).expect("table ref");
934                    let t = &mut self.tables[idx];
935                    t["children"] = Value::Array(children);
936                    t["content_layer"] = json!(layer);
937                    t["captions"] = Value::Array(captions.iter().map(|&c| ref_of(c)).collect());
938                    // A `RichTableCell` is the plain cell plus a `ref` to the
939                    // group holding its content — on `table_cells` only; the
940                    // derived `grid` shows plain cells.
941                    for &(row, col, group) in rich_cells {
942                        let cell_ref = ref_of(group);
943                        let hit = |c: &Value| {
944                            c["start_row_offset_idx"] == json!(row)
945                                && c["start_col_offset_idx"] == json!(col)
946                        };
947                        if let Some(cells) = t["data"]["table_cells"].as_array_mut() {
948                            for c in cells.iter_mut().filter(|c| hit(c)) {
949                                c["ref"] = cell_ref.clone();
950                            }
951                        }
952                    }
953                    r
954                }
955                TreeKind::Picture {
956                    captions,
957                    image,
958                    classification,
959                    confidence,
960                    chart,
961                    dpi,
962                } => {
963                    // A chart's meta: the kind as the one classification
964                    // prediction (pydantic's field order puts `confidence`
965                    // first when present), then the reconstructed data grid
966                    // (#405).
967                    let mut meta = classification.as_ref().map(|c| {
968                        let mut pred = serde_json::Map::new();
969                        if let Some(conf) = confidence {
970                            pred.insert("confidence".into(), json!(conf));
971                        }
972                        pred.insert("class_name".into(), json!(c));
973                        json!({ "classification": { "predictions": [pred] } })
974                    });
975                    if let (Some(m), Some(t)) = (meta.as_mut(), chart) {
976                        if !t.rows.is_empty() {
977                            m["tabular_chart"] = json!({ "chart_data": table_data(t) });
978                        }
979                    }
980                    let prov = self.take_prov(0);
981                    let r = self.push_picture(
982                        prov,
983                        captions.iter().map(|&c| ref_of(c)).collect(),
984                        children,
985                        image.as_ref(),
986                        meta,
987                        parent,
988                    );
989                    if let Some(idx) = ref_index(&r) {
990                        self.pictures[idx]["content_layer"] = json!(layer);
991                        // The image's dpi is the file's when the backend read
992                        // it (python-pptx does); the default 72 otherwise.
993                        if let (Some(dpi), Some(img)) = (dpi, self.pictures[idx].get_mut("image")) {
994                            img["dpi"] = json!(dpi);
995                        }
996                    }
997                    r
998                }
999                TreeKind::FieldRegion { items } => {
1000                    self.pending_exact = None;
1001                    let r = self.add_field_region(items, parent);
1002                    if let Some(region) = self.field_regions.last_mut() {
1003                        region["content_layer"] = json!(layer);
1004                    }
1005                    r
1006                }
1007                TreeKind::KeyValueGraph { cells, links } => {
1008                    self.pending_exact = None;
1009                    let r = self.add_key_value_graph(cells, links, parent);
1010                    if let Some(item) = self.key_value_items.last_mut() {
1011                        item["content_layer"] = json!(layer);
1012                    }
1013                    r
1014                }
1015            };
1016            debug_assert_eq!(self_ref, refs[id], "tree item {id} numbered out of order");
1017        }
1018        tree.body.iter().map(|&c| ref_of(c)).collect()
1019    }
1020
1021    fn add_node(&mut self, node: &Node, parent: &str) -> Option<String> {
1022        match node {
1023            Node::Heading { level: 1, text } => {
1024                Some(self.add_text("title", text, parent, json!({})))
1025            }
1026            Node::Heading { level, text } => Some(self.add_text(
1027                "section_header",
1028                text,
1029                parent,
1030                json!({ "level": level.saturating_sub(1) }),
1031            )),
1032            Node::Caption { text, href } => {
1033                let extra = match href {
1034                    Some(url) => json!({ "hyperlink": url }),
1035                    None => json!({}),
1036                };
1037                Some(self.add_text("caption", text, parent, extra))
1038            }
1039            Node::Paragraph { text } => {
1040                // A whole-paragraph display equation is a formula item (docling
1041                // wraps it in `$$…$$` and, unlike a text item, never escapes it).
1042                let t = text.trim();
1043                match t.strip_prefix("$$").and_then(|s| s.strip_suffix("$$")) {
1044                    Some(inner) if !inner.is_empty() => Some(self.add_formula(inner, parent)),
1045                    _ => Some(self.add_text("text", text, parent, json!({}))),
1046                }
1047            }
1048            Node::CheckboxItem { checked, text } => {
1049                // JSON keeps the task-list form as a plain text item (the
1050                // `checkbox_selected`/`checkbox_unselected` label is DocLang-only).
1051                let mark = if *checked { "- [x] " } else { "- [ ] " };
1052                Some(self.add_text("text", &format!("{mark}{text}"), parent, json!({})))
1053            }
1054            Node::Code {
1055                language,
1056                text,
1057                orig,
1058                ..
1059            } => Some(self.add_code(text, language.as_deref(), orig.as_deref(), parent)),
1060            // A CodeFormula-decoded display formula: `text` carries the LaTeX,
1061            // `orig` the raw glyph extraction (docling's enriched shape).
1062            Node::Formula {
1063                latex,
1064                orig,
1065                location,
1066            } => {
1067                self.adopt_loc(*location);
1068                Some(self.add_formula_item(latex, orig, parent))
1069            }
1070            // docling's notes-layer `comment_section` group holding the
1071            // comment's text item. What the annotated items point at differs
1072            // upstream: the docx backend links the group (so a comment's
1073            // replies group together), everything going through
1074            // docling-core's `add_comment` links the note text itself.
1075            Node::CommentSection {
1076                name,
1077                text,
1078                refs_note_text,
1079                grouped,
1080            } => {
1081                if !*grouped {
1082                    // docling-core's bare `add_comment`: the note text sits
1083                    // directly under the parent and is what the back-refs
1084                    // point at.
1085                    let child =
1086                        self.add_text("text", text, parent, json!({ "content_layer": "notes" }));
1087                    self.comment_groups.push(child.clone());
1088                    return Some(child);
1089                }
1090                if let Some((_, self_ref)) = self
1091                    .last_comment_section
1092                    .as_ref()
1093                    .filter(|(n, _)| n == name)
1094                    .cloned()
1095                {
1096                    // Another message of the same thread: a further note in
1097                    // the group already open for this cell.
1098                    let child =
1099                        self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1100                    if let Some(children) =
1101                        self.groups[group_index(&self_ref)]["children"].as_array_mut()
1102                    {
1103                        children.push(json!({ "$ref": child }));
1104                    }
1105                    self.comment_groups.push(if *refs_note_text {
1106                        child
1107                    } else {
1108                        self_ref.clone()
1109                    });
1110                    return Some(self_ref);
1111                }
1112                let self_ref = format!("#/groups/{}", self.groups.len());
1113                self.groups.push(Value::Null);
1114                let child =
1115                    self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1116                self.groups[group_index(&self_ref)] = json!({
1117                    "self_ref": self_ref,
1118                    "parent": { "$ref": parent },
1119                    "children": [{ "$ref": child }],
1120                    "content_layer": "notes",
1121                    "name": name,
1122                    "label": "comment_section",
1123                });
1124                self.last_comment_section = Some((name.clone(), self_ref.clone()));
1125                self.comment_groups.push(if *refs_note_text {
1126                    child
1127                } else {
1128                    self_ref.clone()
1129                });
1130                Some(self_ref)
1131            }
1132            // The annotation itself is a cross-reference: emit the item, then
1133            // remember it so the group refs can be filled in at the end.
1134            Node::Commented { comments, inner } => {
1135                let item = self.add_node(inner, parent)?;
1136                if !comments.is_empty() {
1137                    self.pending_comments.push((item.clone(), comments.clone()));
1138                }
1139                Some(item)
1140            }
1141            Node::Table(t) => Some(self.add_table(t, parent)),
1142            Node::Picture {
1143                caption,
1144                caption_href,
1145                image,
1146                classification,
1147                caption_parent,
1148            } => Some(self.add_picture(
1149                caption.as_deref(),
1150                caption_href.as_deref(),
1151                image.as_ref(),
1152                classification.as_deref().map(classification_meta),
1153                parent,
1154                *caption_parent,
1155            )),
1156            // A chart is a picture item in the JSON with docling's chart
1157            // meta — `classification` (the chart kind, as the one prediction)
1158            // and `tabular_chart.chart_data`, the series reconstructed as a
1159            // `TableData` (#405) — and no image payload.
1160            Node::Chart {
1161                kind,
1162                table,
1163                caption,
1164                location,
1165            } => {
1166                self.adopt_loc(*location);
1167                let mut meta = json!({
1168                    "classification": { "predictions": [{ "class_name": kind }] },
1169                });
1170                if !table.rows.is_empty() {
1171                    meta["tabular_chart"] = json!({ "chart_data": table_data(table) });
1172                }
1173                // docling's office backends add the chart's title as a caption
1174                // item of the *container* (the sheet group, the slide), listed
1175                // before the picture that references it, with the chart's own
1176                // box and a charspan over the caption text — not as a child
1177                // of the picture, which is where a PDF caption lives.
1178                let mut captions = Vec::new();
1179                if let Some(cap) = caption.as_deref().filter(|c| !c.is_empty()) {
1180                    let prov = self.prov_json(unescape_text(cap).chars().count(), true);
1181                    let cap_ref = self.add_text_with("caption", cap, parent, json!({}), prov);
1182                    self.pending_siblings.push(json!({ "$ref": cap_ref }));
1183                    captions.push(json!({ "$ref": cap_ref }));
1184                }
1185                let prov = self.take_prov(0);
1186                Some(self.push_picture(prov, captions, Vec::new(), None, Some(meta), parent))
1187            }
1188            // A DocLang-only node is omitted from the JSON body.
1189            Node::DoclangOnly(_) => None,
1190            Node::Group {
1191                label,
1192                name,
1193                layer,
1194                children,
1195            } => Some(self.add_group(label, name.as_deref(), *layer, children, parent)),
1196            Node::FieldRegion { items } => Some(self.add_field_region(items, parent)),
1197            Node::KeyValueGraph { cells, links } => {
1198                Some(self.add_key_value_graph(cells, links, parent))
1199            }
1200            // A rich inline group is a text item over its Markdown text; the
1201            // structured runs are DocLang-only, so the JSON matches a paragraph.
1202            Node::InlineGroup { md_text, .. } => {
1203                Some(self.add_text("text", md_text, parent, json!({})))
1204            }
1205            // A plain-text backend dump is a single text item over the file body.
1206            Node::TextDump(text) => Some(self.add_text("text", text, parent, json!({}))),
1207            // Speaker notes are content a deck carries, and docling puts them
1208            // in the JSON on their own layer, so a consumer reading only JSON
1209            // can pick them (#402). Page furniture stays out of the flat
1210            // path; a backend that builds docling's item tree (HTML) puts its
1211            // furniture-layer items in the JSON through `write_tree`.
1212            Node::Furniture {
1213                layer: ContentLayer::Notes,
1214                inner,
1215            } => {
1216                let item = self.add_node(inner, parent)?;
1217                self.set_layer(&item, "notes");
1218                Some(item)
1219            }
1220            Node::Furniture { .. } => None,
1221            Node::PageFurniture { .. } => None,
1222            // A location wrapper turns into the wrapped item's `prov` entry —
1223            // but only on pages the PDF paths described with a PageInfo marker
1224            // (other geometry-bearing backends, e.g. PPTX shapes, keep their
1225            // pre-#171 provenance-less JSON until they emit markers too).
1226            Node::Located { location, inner } => {
1227                if self.cur_page > 0 {
1228                    self.pending_loc = Some(*location);
1229                }
1230                let r = self.add_node(inner, parent);
1231                self.pending_loc = None;
1232                r
1233            }
1234            Node::Prov {
1235                page_no,
1236                bbox,
1237                charspan,
1238                inner,
1239                ..
1240            } => {
1241                self.pending_exact = Some(ExactProv {
1242                    page_no: *page_no,
1243                    bbox: bbox.map(f64::from),
1244                    bottom_left: false,
1245                    charspan: *charspan,
1246                });
1247                let r = self.add_node(inner, parent);
1248                self.pending_exact = None;
1249                r
1250            }
1251            // Page breaks are DocLang-only; docling omits them from the JSON body.
1252            Node::PageBreak => None,
1253            // The page marker: record the page's number and size for the
1254            // `pages` map, and denormalize every following location against it.
1255            Node::PageInfo {
1256                page_no,
1257                width,
1258                height,
1259            } => {
1260                self.cur_page = *page_no;
1261                self.cur_w = *width as f64;
1262                self.cur_h = *height as f64;
1263                if *page_no > 0 {
1264                    self.pages.push((*page_no, self.cur_w, self.cur_h));
1265                }
1266                None
1267            }
1268            // Handled by `add_list` in `walk`.
1269            Node::ListItem { .. } => None,
1270        }
1271    }
1272
1273    /// A form key-value region: `field_regions/N` holds the region, each field is
1274    /// a `field_items/M` whose children are its `marker` / `field_key` /
1275    /// `field_value` texts (absent parts are simply omitted).
1276    fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
1277        let self_ref = format!("#/field_regions/{}", self.field_regions.len());
1278        self.field_regions.push(Value::Null);
1279        let region_index = self.field_regions.len() - 1;
1280        let mut item_refs = Vec::new();
1281        for item in items {
1282            item_refs.push(json!({ "$ref": self.add_field_item(item, &self_ref) }));
1283        }
1284        self.field_regions[region_index] = json!({
1285            "self_ref": self_ref,
1286            "parent": { "$ref": parent },
1287            "children": item_refs,
1288            "content_layer": "body",
1289            "label": "field_region",
1290            "prov": [],
1291        });
1292        self_ref
1293    }
1294
1295    /// A `KeyValueItem`: docling's `GraphData` written cell for cell and link
1296    /// for link (`key_value_items/N`), the item itself childless and without
1297    /// provenance, the way the XBRL backend creates it.
1298    fn add_key_value_graph(
1299        &mut self,
1300        cells: &[crate::GraphCell],
1301        links: &[crate::GraphLink],
1302        parent: &str,
1303    ) -> String {
1304        let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
1305        let cells: Vec<Value> = cells
1306            .iter()
1307            .map(|c| {
1308                json!({
1309                    "label": c.label,
1310                    "cell_id": c.cell_id,
1311                    "text": c.text,
1312                    "orig": c.orig,
1313                })
1314            })
1315            .collect();
1316        let links: Vec<Value> = links
1317            .iter()
1318            .map(|l| {
1319                json!({
1320                    "label": l.label,
1321                    "source_cell_id": l.source_cell_id,
1322                    "target_cell_id": l.target_cell_id,
1323                })
1324            })
1325            .collect();
1326        self.key_value_items.push(json!({
1327            "self_ref": self_ref,
1328            "parent": { "$ref": parent },
1329            "children": [],
1330            "content_layer": "body",
1331            "label": "key_value_region",
1332            "prov": [],
1333            "captions": [],
1334            "references": [],
1335            "footnotes": [],
1336            "graph": { "cells": cells, "links": links },
1337        }));
1338        self_ref
1339    }
1340
1341    fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
1342        let self_ref = format!("#/field_items/{}", self.field_items.len());
1343        self.field_items.push(Value::Null);
1344        let item_index = self.field_items.len() - 1;
1345        let mut child_refs = Vec::new();
1346        for (label, text) in [
1347            ("marker", &item.marker),
1348            ("field_key", &item.key),
1349            ("field_value", &item.value),
1350        ] {
1351            if let Some(text) = text {
1352                // A value's `kind` (docling's `read_only` / `fillable`)
1353                // follows its text.
1354                let extra = match (label, &item.value_kind) {
1355                    ("field_value", Some(kind)) => json!({ "kind": kind }),
1356                    _ => json!({}),
1357                };
1358                child_refs.push(json!({ "$ref": self.add_text(label, text, &self_ref, extra) }));
1359            }
1360        }
1361        self.field_items[item_index] = json!({
1362            "self_ref": self_ref,
1363            "parent": { "$ref": parent },
1364            "children": child_refs,
1365            "content_layer": "body",
1366            "label": "field_item",
1367            "prov": [],
1368        });
1369        self_ref
1370    }
1371
1372    /// Move an already-emitted item onto a content layer. Notes are single
1373    /// text items today; a deeper notes subtree would need its children moved
1374    /// too, and no backend builds one.
1375    fn set_layer(&mut self, self_ref: &str, layer: &str) {
1376        let bucket = match self_ref.split('/').nth(1) {
1377            Some("texts") => &mut self.texts,
1378            Some("tables") => &mut self.tables,
1379            Some("pictures") => &mut self.pictures,
1380            Some("groups") => &mut self.groups,
1381            _ => return,
1382        };
1383        if let Some(item) = self_ref
1384            .rsplit('/')
1385            .next()
1386            .and_then(|i| i.parse::<usize>().ok())
1387            .and_then(|i| bucket.get_mut(i))
1388        {
1389            item["content_layer"] = json!(layer);
1390        }
1391    }
1392
1393    fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
1394        let prov = self.take_prov(unescape_text(text).chars().count());
1395        self.add_text_with(label, text, parent, extra, prov)
1396    }
1397
1398    /// [`Self::add_text`] with an explicit `prov` (a chart caption shares the
1399    /// chart's box without consuming it).
1400    fn add_text_with(
1401        &mut self,
1402        label: &str,
1403        text: &str,
1404        parent: &str,
1405        extra: Value,
1406        prov: Value,
1407    ) -> String {
1408        let self_ref = format!("#/texts/{}", self.texts.len());
1409        let raw = unescape_text(text);
1410        let mut item = json!({
1411            "self_ref": self_ref,
1412            "parent": { "$ref": parent },
1413            "children": [],
1414            "content_layer": "body",
1415            "label": label,
1416            "prov": prov,
1417            "orig": raw,
1418            "text": raw,
1419        });
1420        merge(&mut item, extra);
1421        self.texts.push(item);
1422        self_ref
1423    }
1424
1425    /// A display-math formula item. `latex` is the raw content (no `$$`); docling
1426    /// re-wraps it and never escapes it.
1427    fn add_formula(&mut self, latex: &str, parent: &str) -> String {
1428        let self_ref = format!("#/texts/{}", self.texts.len());
1429        let prov = self.take_prov(latex.chars().count());
1430        self.texts.push(json!({
1431            "self_ref": self_ref,
1432            "parent": { "$ref": parent },
1433            "children": [],
1434            "content_layer": "body",
1435            "label": "formula",
1436            "prov": prov,
1437            "orig": latex,
1438            "text": latex,
1439        }));
1440        self_ref
1441    }
1442
1443    /// A CodeFormula-enriched display formula: `text` is the model's LaTeX
1444    /// while `orig` keeps the raw glyph extraction (docling's enriched shape;
1445    /// the plain [`Self::add_formula`] above sets both to the same string).
1446    fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
1447        let self_ref = format!("#/texts/{}", self.texts.len());
1448        let prov = self.take_prov(latex.chars().count());
1449        self.texts.push(json!({
1450            "self_ref": self_ref,
1451            "parent": { "$ref": parent },
1452            "children": [],
1453            "content_layer": "body",
1454            "label": "formula",
1455            "prov": prov,
1456            "orig": orig,
1457            "text": latex,
1458        }));
1459        self_ref
1460    }
1461
1462    fn add_code(
1463        &mut self,
1464        text: &str,
1465        language: Option<&str>,
1466        orig: Option<&str>,
1467        parent: &str,
1468    ) -> String {
1469        let self_ref = format!("#/texts/{}", self.texts.len());
1470        let raw = unescape_text(text);
1471        let prov = self.take_prov(raw.chars().count());
1472        self.texts.push(json!({
1473            "self_ref": self_ref,
1474            "parent": { "$ref": parent },
1475            "children": [],
1476            "content_layer": "body",
1477            "label": "code",
1478            "prov": prov,
1479            // With code enrichment, `text` is the model's rewrite while `orig`
1480            // keeps the raw extraction; otherwise both are the same string.
1481            "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
1482            "text": raw,
1483            "captions": [],
1484            "references": [],
1485            "footnotes": [],
1486            "code_language": code_language(language),
1487        }));
1488        self_ref
1489    }
1490
1491    /// Build a list group from a run of (possibly multi-level) list items. A
1492    /// deeper level starts a nested list under the preceding item.
1493    fn add_list(&mut self, items: &[Node], parent: &str) -> String {
1494        let self_ref = format!("#/groups/{}", self.groups.len());
1495        // reserve the slot so nested groups get later indices
1496        self.groups.push(Value::Null);
1497        let base = level_of(&items[0]);
1498        let mut children = Vec::new();
1499        let mut i = 0;
1500        while i < items.len() {
1501            // Empty paragraphs absorbed into the run (blank lines between items)
1502            // are not list items — skip them.
1503            if !matches!(items[i], Node::ListItem { .. }) {
1504                i += 1;
1505                continue;
1506            }
1507            let lvl = level_of(&items[i]);
1508            if lvl > base {
1509                // shouldn't happen at the head; skip defensively
1510                i += 1;
1511                continue;
1512            }
1513            let item_ref = self.add_list_item(&items[i], &self_ref);
1514            // collect any deeper items that nest under this one
1515            let mut j = i + 1;
1516            while j < items.len() && level_of(&items[j]) > base {
1517                j += 1;
1518            }
1519            if j > i + 1 {
1520                let mut nested = Vec::new();
1521                self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
1522                // the nested list group(s) are children of this item
1523                if let Some(idx) = ref_index(&item_ref) {
1524                    self.texts[idx]["children"]
1525                        .as_array_mut()
1526                        .unwrap()
1527                        .extend(nested);
1528                }
1529            }
1530            children.push(json!({ "$ref": item_ref }));
1531            i = j;
1532        }
1533        self.groups[group_index(&self_ref)] = json!({
1534            "self_ref": self_ref,
1535            "parent": { "$ref": parent },
1536            "children": children,
1537            "content_layer": "body",
1538            "name": "list",
1539            "label": "list",
1540        });
1541        self_ref
1542    }
1543
1544    fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
1545        let Node::ListItem {
1546            ordered,
1547            number,
1548            text,
1549            location,
1550            ..
1551        } = node
1552        else {
1553            unreachable!()
1554        };
1555        self.adopt_loc(*location);
1556        let self_ref = format!("#/texts/{}", self.texts.len());
1557        let raw = unescape_text(text);
1558        let prov = self.take_prov(raw.chars().count());
1559        let marker = if *ordered {
1560            format!("{number}.")
1561        } else {
1562            "-".to_string()
1563        };
1564        self.texts.push(json!({
1565            "self_ref": self_ref,
1566            "parent": { "$ref": parent },
1567            "children": [],
1568            "content_layer": "body",
1569            "label": "list_item",
1570            "prov": prov,
1571            "orig": raw,
1572            "text": raw,
1573            "enumerated": ordered,
1574            "marker": marker,
1575        }));
1576        self_ref
1577    }
1578
1579    fn add_table(&mut self, t: &Table, parent: &str) -> String {
1580        self.add_table_with(t, parent, false)
1581    }
1582
1583    /// [`Self::add_table`]; `raw` cell text is written verbatim (see
1584    /// [`table_data_with`]).
1585    fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
1586        let self_ref = format!("#/tables/{}", self.tables.len());
1587        self.adopt_loc(t.location);
1588        let prov = self.take_prov(0);
1589        // The caption is a separate text item the table references (docling's
1590        // `TableItem.captions`), added before the grid so its box isn't
1591        // inherited by a later item.
1592        let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
1593            Some(cap) => self.add_caption(cap, json!({}), &self_ref, parent, t.caption_parent),
1594            None => (Vec::new(), Vec::new()),
1595        };
1596        let data = table_data_with(t, raw);
1597        self.tables.push(json!({
1598            "self_ref": self_ref,
1599            "parent": { "$ref": parent },
1600            "children": children,
1601            "content_layer": "body",
1602            "label": "table",
1603            "prov": prov,
1604            "captions": captions,
1605            "references": [],
1606            "footnotes": [],
1607            "data": data,
1608            "annotations": [],
1609        }));
1610        self_ref
1611    }
1612
1613    /// Add a picture's or table's caption text item where `choice` says it
1614    /// hangs (#390), returning the `captions` entry for the item and the
1615    /// item's own `children` (the caption, when it is the item's child).
1616    /// The caption never consumes the item's pending provenance — the item
1617    /// takes its box first.
1618    fn add_caption(
1619        &mut self,
1620        text: &str,
1621        extra: Value,
1622        self_ref: &str,
1623        parent: &str,
1624        choice: CaptionParent,
1625    ) -> (Vec<Value>, Vec<Value>) {
1626        // docling's PDF pipeline parents the caption to the item; every
1627        // declarative backend leaves `add_text`'s default — the body — even
1628        // for an item inside a group; the office backends and HTML's
1629        // `<figure>` hang it off the item's container.
1630        let cap_parent = match choice {
1631            CaptionParent::Item => self_ref,
1632            CaptionParent::Container | CaptionParent::ContainerAfter => parent,
1633            CaptionParent::Body => "#/body",
1634        };
1635        let cap_ref = json!({ "$ref": self.add_text("caption", text, cap_parent, extra) });
1636        match choice {
1637            CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
1638            // Created ahead of the item, so it precedes the item in the
1639            // container's children — and, on the body, in the body's.
1640            CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
1641            CaptionParent::Body if parent == "#/body" => {
1642                self.pending_siblings.push(cap_ref.clone())
1643            }
1644            CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
1645            // The item sits deeper: the body's children get the caption after
1646            // the top-level item under walk, where docling appended it.
1647            CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
1648        }
1649        (vec![cap_ref], Vec::new())
1650    }
1651
1652    /// `meta` is the picture's docling `PictureMeta` (a classifier's
1653    /// predictions, a chart's kind and data), `None` for a plain picture.
1654    fn add_picture(
1655        &mut self,
1656        caption: Option<&str>,
1657        caption_href: Option<&str>,
1658        image: Option<&crate::PictureImage>,
1659        meta: Option<Value>,
1660        parent: &str,
1661        caption_parent: CaptionParent,
1662    ) -> String {
1663        let self_ref = format!("#/pictures/{}", self.pictures.len());
1664        // Take the picture's own provenance before the caption text is added —
1665        // the caption is a separate item and must not inherit the crop's box.
1666        let prov = self.take_prov(0);
1667        let (captions, children) = match caption.filter(|c| !c.is_empty()) {
1668            Some(cap) => {
1669                // Emit the caption as a text item that the picture references. A
1670                // wrapping `<a href>`'s link rides as docling's `hyperlink` field
1671                // on the caption item (#328).
1672                let extra = match caption_href {
1673                    Some(href) => json!({ "hyperlink": href }),
1674                    None => json!({}),
1675                };
1676                self.add_caption(cap, extra, &self_ref, parent, caption_parent)
1677            }
1678            None => (Vec::new(), Vec::new()),
1679        };
1680        self.push_picture(prov, captions, children, image, meta, parent)
1681    }
1682
1683    /// Append the picture item itself — `prov`, `captions` and `children`
1684    /// (a PDF caption is the picture's child) already settled.
1685    fn push_picture(
1686        &mut self,
1687        prov: Value,
1688        captions: Vec<Value>,
1689        children: Vec<Value>,
1690        image: Option<&crate::PictureImage>,
1691        meta: Option<Value>,
1692        parent: &str,
1693    ) -> String {
1694        let self_ref = format!("#/pictures/{}", self.pictures.len());
1695        // The legacy `classification` annotation rides along with a
1696        // classifier's `meta` (see `classification_meta`); a chart's meta has
1697        // none, like docling's.
1698        let annotations = meta
1699            .as_ref()
1700            .and_then(|m| m.get("annotations").cloned())
1701            .unwrap_or_else(|| json!([]));
1702        let meta = meta.map(|mut m| {
1703            if let Some(obj) = m.as_object_mut() {
1704                obj.remove("annotations");
1705            }
1706            m
1707        });
1708        // `meta` sits between `content_layer` and `label` in docling's field
1709        // order (and `preserve_order` keeps ours byte-compatible), so the item
1710        // is built in one shot per shape rather than patched afterwards.
1711        let mut item = match meta {
1712            Some(meta) => json!({
1713                "self_ref": self_ref,
1714                "parent": { "$ref": parent },
1715                "children": children,
1716                "content_layer": "body",
1717                "meta": meta,
1718                "label": "picture",
1719                "prov": prov,
1720                "captions": captions,
1721                "references": [],
1722                "footnotes": [],
1723                "annotations": annotations,
1724            }),
1725            None => json!({
1726                "self_ref": self_ref,
1727                "parent": { "$ref": parent },
1728                "children": children,
1729                "content_layer": "body",
1730                "label": "picture",
1731                "prov": prov,
1732                "captions": captions,
1733                "references": [],
1734                "footnotes": [],
1735                "annotations": annotations,
1736            }),
1737        };
1738        // docling stores the extracted image as an `ImageRef` (data URI + size,
1739        // the size as floats) between `footnotes` and `annotations` — pydantic
1740        // field order, which `preserve_order` lets us reproduce by rebuilding
1741        // the tail.
1742        if let Some(img) = image {
1743            let image = json!({
1744                "mimetype": img.mimetype,
1745                "dpi": 72,
1746                "size": { "width": img.width as f64, "height": img.height as f64 },
1747                "uri": img.data_uri(),
1748            });
1749            if let Some(obj) = item.as_object_mut() {
1750                let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
1751                obj.insert("image".into(), image);
1752                obj.insert("annotations".into(), annotations);
1753            }
1754        }
1755        self.pictures.push(item);
1756        self_ref
1757    }
1758
1759    fn add_group(
1760        &mut self,
1761        label: &str,
1762        name: Option<&str>,
1763        layer: Option<ContentLayer>,
1764        nodes: &[Node],
1765        parent: &str,
1766    ) -> String {
1767        let self_ref = format!("#/groups/{}", self.groups.len());
1768        self.groups.push(Value::Null);
1769        // Everything the walk creates belongs to this group, so a non-body
1770        // layer (a hidden sheet) is stamped on the whole subtree afterwards —
1771        // docling puts the layer on the group *and* on every item under it.
1772        let mark = (
1773            self.texts.len(),
1774            self.tables.len(),
1775            self.pictures.len(),
1776            self.groups.len(),
1777        );
1778        let children = self.walk_into(nodes, &self_ref);
1779        let name = name.unwrap_or(if label == "inline" { "group" } else { label });
1780        let content_layer = layer.map_or("body", |l| l.value());
1781        self.groups[group_index(&self_ref)] = json!({
1782            "self_ref": self_ref,
1783            "parent": { "$ref": parent },
1784            "children": children,
1785            "content_layer": content_layer,
1786            "name": name,
1787            "label": label,
1788        });
1789        if layer.is_some() {
1790            let (t, tb, p, g) = mark;
1791            for item in self.texts[t..]
1792                .iter_mut()
1793                .chain(self.tables[tb..].iter_mut())
1794                .chain(self.pictures[p..].iter_mut())
1795                .chain(self.groups[g..].iter_mut())
1796            {
1797                if let Some(obj) = item.as_object_mut() {
1798                    obj.insert("content_layer".into(), json!(content_layer));
1799                }
1800            }
1801        }
1802        self_ref
1803    }
1804
1805    /// Walk a slice of sibling nodes, returning each child's `$ref`; runs of
1806    /// list items are folded into list groups (one per sibling list).
1807    fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Value> {
1808        // Siblings that all carry a creation rank (an XLSX sheet's items) are
1809        // *added* in that order — so `#/tables/N` and friends are numbered as
1810        // docling numbers them — while their refs keep the node order, which
1811        // is docling's position-sorted `children`.
1812        let seqs: Option<Vec<usize>> = nodes
1813            .iter()
1814            .map(|n| match n {
1815                Node::Prov { seq: Some(s), .. } => Some(*s),
1816                _ => None,
1817            })
1818            .collect();
1819        if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
1820            let mut order: Vec<usize> = (0..nodes.len()).collect();
1821            order.sort_by_key(|&i| seqs[i]);
1822            let mut slots: Vec<Vec<Value>> = vec![Vec::new(); nodes.len()];
1823            for i in order {
1824                if let Some(r) = self.add_node(&nodes[i], parent) {
1825                    slots[i].append(&mut self.pending_siblings);
1826                    slots[i].push(json!({ "$ref": r }));
1827                    slots[i].append(&mut self.pending_after);
1828                }
1829                if parent == "#/body" {
1830                    slots[i].append(&mut self.pending_body);
1831                }
1832            }
1833            return slots.into_iter().flatten().collect();
1834        }
1835        let mut children = Vec::new();
1836        let mut i = 0;
1837        while i < nodes.len() {
1838            if matches!(nodes[i], Node::ListItem { .. }) {
1839                let start = i;
1840                i += 1;
1841                loop {
1842                    match nodes.get(i) {
1843                        Some(Node::ListItem { .. }) => i += 1,
1844                        // Absorb an empty paragraph sitting between two list
1845                        // items (docling keeps the ListGroup contiguous).
1846                        Some(Node::Paragraph { text })
1847                            if text.is_empty()
1848                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
1849                        {
1850                            i += 1
1851                        }
1852                        _ => break,
1853                    }
1854                }
1855                self.add_sibling_lists(&nodes[start..i], parent, &mut children);
1856            } else {
1857                if let Some(r) = self.add_node(&nodes[i], parent) {
1858                    children.append(&mut self.pending_siblings);
1859                    children.push(json!({ "$ref": r }));
1860                    children.append(&mut self.pending_after);
1861                }
1862                i += 1;
1863            }
1864            // Body-parented captions of items deeper in the tree follow the
1865            // top-level item they were created under (#390).
1866            if parent == "#/body" {
1867                children.append(&mut self.pending_body);
1868            }
1869        }
1870        children
1871    }
1872
1873    /// A run of list items may hold several *sibling* lists; emit one list group
1874    /// per sibling. The boundary is the backend's `first_in_list` flag on a
1875    /// base-level item — the same rule as the Markdown serializer's blank line
1876    /// (#385; the kind-flip and number-gap guesses are gone).
1877    fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
1878        let base = level_of(&run[0]);
1879        let mut seg = 0;
1880        for k in 0..run.len() {
1881            let Node::ListItem {
1882                first_in_list,
1883                level,
1884                ..
1885            } = &run[k]
1886            else {
1887                continue;
1888            };
1889            if *level != base {
1890                continue; // nested item — handled inside add_list
1891            }
1892            if k > seg && *first_in_list {
1893                out.push(json!({ "$ref": self.add_list(&run[seg..k], parent) }));
1894                seg = k;
1895            }
1896        }
1897        out.push(json!({ "$ref": self.add_list(&run[seg..], parent) }));
1898    }
1899}
1900
1901fn level_of(node: &Node) -> u8 {
1902    match node {
1903        Node::ListItem { level, .. } => *level,
1904        _ => 0,
1905    }
1906}
1907
1908fn group_index(self_ref: &str) -> usize {
1909    self_ref.rsplit('/').next().unwrap().parse().unwrap()
1910}
1911
1912fn ref_index(self_ref: &str) -> Option<usize> {
1913    self_ref.rsplit('/').next()?.parse().ok()
1914}
1915
1916/// Merge the key/values of `extra` (an object) into `target` (an object).
1917fn merge(target: &mut Value, extra: Value) {
1918    if let (Some(t), Some(e)) = (target.as_object_mut(), extra.as_object()) {
1919        for (k, v) in e {
1920            t.insert(k.clone(), v.clone());
1921        }
1922    }
1923}
1924
1925/// Reverse [`crate`]'s Markdown text escaping (HTML entities + `\_`).
1926fn unescape_text(s: &str) -> String {
1927    s.replace("&lt;", "<")
1928        .replace("&gt;", ">")
1929        .replace("&amp;", "&")
1930        .replace("\\_", "_")
1931}
1932
1933/// 64-bit FNV-1a, a stand-in for docling's `binary_hash` (we lack the source bytes
1934/// at export time; the value only needs to be a stable u64).
1935fn fnv1a(s: &str) -> u64 {
1936    let mut h: u64 = 0xcbf29ce484222325;
1937    for b in s.bytes() {
1938        h ^= b as u64;
1939        h = h.wrapping_mul(0x100000001b3);
1940    }
1941    h
1942}
1943
1944#[cfg(test)]
1945mod tests {
1946    use crate::{
1947        CaptionParent, ContentLayer, DoclingDocument, ImageMode, Node, PictureImage, Table,
1948    };
1949    use serde_json::Value;
1950
1951    fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
1952        crate::TableCell {
1953            text: text.into(),
1954            bbox: None,
1955            start_row: row,
1956            start_col: col,
1957            row_span: 1,
1958            col_span,
1959            column_header: row == 0,
1960            row_header: false,
1961            row_section: false,
1962        }
1963    }
1964
1965    /// First-class cells past the rows: rectangular rows are the grid and
1966    /// clip them (docling's `TableData.grid` on USPTO's overrun replicas);
1967    /// ragged rows — an xlsx table compacted by `skip_empty_cells` (#271) —
1968    /// are no grid, so the cells' extent sizes it and the omitted positions
1969    /// come back as empty filler cells in `grid` only.
1970    #[test]
1971    fn ragged_rows_take_their_grid_from_first_class_cells() {
1972        let cells = vec![
1973            cell_at("h0", 0, 0, 1),
1974            cell_at("h2", 0, 2, 1),
1975            cell_at("wide", 1, 0, 3),
1976        ];
1977        let export = |rows: Vec<Vec<String>>| -> Value {
1978            let mut doc = DoclingDocument::new("t");
1979            doc.push(Node::Table(Table {
1980                rows,
1981                cells: Some(cells.clone()),
1982                ..Table::default()
1983            }));
1984            let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
1985            v["tables"][0]["data"].clone()
1986        };
1987        // Compacted rows: 2 and 3 wide, the cells say the grid is 3 wide.
1988        let data = export(vec![
1989            vec!["h0".into(), "h2".into()],
1990            vec!["wide".into(), "wide".into(), "wide".into()],
1991        ]);
1992        assert_eq!(data["num_rows"], 2);
1993        assert_eq!(data["num_cols"], 3);
1994        assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
1995        let row0: Vec<&str> = data["grid"][0]
1996            .as_array()
1997            .unwrap()
1998            .iter()
1999            .map(|c| c["text"].as_str().unwrap())
2000            .collect();
2001        assert_eq!(row0, ["h0", "", "h2"]);
2002        assert_eq!(data["table_cells"][2]["col_span"], 3);
2003        // Rectangular rows narrower than the cells: the rows win, the cells
2004        // are clipped to them exactly as before.
2005        let data = export(vec![
2006            vec!["h0".into(), "h2".into()],
2007            vec!["wide".into(), "wide".into()],
2008        ]);
2009        assert_eq!(data["num_cols"], 2);
2010        assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
2011    }
2012
2013    fn doc_with_image() -> DoclingDocument {
2014        let mut doc = DoclingDocument::new("t");
2015        doc.push(Node::Picture {
2016            caption: Some("Fig 1".into()),
2017            caption_href: None,
2018            image: Some(PictureImage {
2019                mimetype: "image/png".into(),
2020                width: 4,
2021                height: 2,
2022                data: b"foobar".to_vec(),
2023            }),
2024            classification: None,
2025            caption_parent: Default::default(),
2026        });
2027        doc
2028    }
2029
2030    /// #402: a deck's speaker notes are content, and docling puts them in the
2031    /// JSON on the `notes` layer so a consumer reading only JSON can pick them
2032    /// out. Markdown still serializes the body layer alone, and page furniture
2033    /// stays out of the JSON, where docling does keep it.
2034    #[test]
2035    fn notes_layer_items_reach_the_json_but_furniture_does_not() {
2036        let mut doc = DoclingDocument::new("t");
2037        doc.push(Node::Heading {
2038            level: 1,
2039            text: "Slide One".into(),
2040        });
2041        doc.push(Node::Furniture {
2042            layer: ContentLayer::Notes,
2043            inner: Box::new(Node::Located {
2044                location: [0, 0, 0, 0],
2045                inner: Box::new(Node::Paragraph {
2046                    text: "Speaker note for slide 1.".into(),
2047                }),
2048            }),
2049        });
2050        doc.push(Node::Furniture {
2051            layer: ContentLayer::Furniture,
2052            inner: Box::new(Node::Paragraph {
2053                text: "page header".into(),
2054            }),
2055        });
2056
2057        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2058        let texts = v["texts"].as_array().unwrap();
2059        assert_eq!(
2060            texts
2061                .iter()
2062                .map(|t| (
2063                    t["label"].as_str().unwrap(),
2064                    t["content_layer"].as_str().unwrap(),
2065                    t["text"].as_str().unwrap()
2066                ))
2067                .collect::<Vec<_>>(),
2068            vec![
2069                ("title", "body", "Slide One"),
2070                ("text", "notes", "Speaker note for slide 1."),
2071            ],
2072            "the note is carried on its own layer; the furniture is not carried"
2073        );
2074        // The body layer is what Markdown serializes, so it does not change.
2075        assert_eq!(doc.export_to_markdown(), "# Slide One\n");
2076    }
2077
2078    /// #410: a backend that describes merged ranges only as continuation
2079    /// flags (xlsx `<mergeCell>`, docx `gridSpan`/`vMerge`) gets docling's
2080    /// one-`TableCell`-per-range JSON: the anchor's offsets and spans, the
2081    /// entry repeated across the grid positions it covers — not a 1×1 cell
2082    /// per position with the text copied into each.
2083    #[test]
2084    fn continuation_flags_become_spanning_cells() {
2085        let mut doc = DoclingDocument::new("t");
2086        // A1:C2 merged ("merged"), then a plain row underneath.
2087        let rows = vec![
2088            vec!["merged".to_string(), "merged".into(), "merged".into()],
2089            vec!["merged".to_string(), "merged".into(), "merged".into()],
2090            vec!["a".to_string(), "b".into(), "c".into()],
2091        ];
2092        doc.push(Node::Table(crate::Table {
2093            rows,
2094            location: None,
2095            structure: Some(crate::TableStructure {
2096                header_row: vec![true, false, false],
2097                col_continuation: vec![
2098                    vec![false, true, true],
2099                    vec![false, true, true],
2100                    vec![false, false, false],
2101                ],
2102                row_continuation: vec![
2103                    vec![false, false, false],
2104                    vec![true, true, true],
2105                    vec![false, false, false],
2106                ],
2107                row_header: Vec::new(),
2108                col_header: Vec::new(),
2109            }),
2110            cell_blocks: None,
2111            cells: None,
2112            caption: None,
2113            caption_parent: Default::default(),
2114        }));
2115        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2116        let data = &v["tables"][0]["data"];
2117        assert_eq!(data["num_rows"], 3);
2118        assert_eq!(data["num_cols"], 3);
2119        let cells = data["table_cells"].as_array().unwrap();
2120        assert_eq!(
2121            cells.len(),
2122            4,
2123            "one cell for the range, three for the plain row"
2124        );
2125        assert_eq!(
2126            cells[0],
2127            serde_json::json!({
2128                "row_span": 2, "col_span": 3,
2129                "start_row_offset_idx": 0, "end_row_offset_idx": 2,
2130                "start_col_offset_idx": 0, "end_col_offset_idx": 3,
2131                "text": "merged", "column_header": true, "row_header": false,
2132                "row_section": false, "fillable": false,
2133            })
2134        );
2135        assert_eq!(cells[1]["text"], "a");
2136        assert_eq!(cells[1]["row_span"], 1);
2137        assert_eq!(cells[1]["column_header"], false);
2138        // The grid repeats the range's entry at every position it covers.
2139        let grid = data["grid"].as_array().unwrap();
2140        assert_eq!(grid.len(), 3);
2141        for (r, row) in grid.iter().take(2).enumerate() {
2142            for (c, cell) in row.as_array().unwrap().iter().enumerate() {
2143                assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
2144            }
2145        }
2146        assert_eq!(grid[2][2]["text"], "c");
2147    }
2148
2149    /// A [`Node::Prov`] wrapper is docling's provenance verbatim — the exact
2150    /// box in a top-left origin, the backend's charspan — and the page marker
2151    /// before it sizes the page; a chart's caption becomes a sibling of the
2152    /// picture in the container, listed first, sharing the chart's box with
2153    /// a charspan over its text. That is the JSON shape of an XLSX sheet.
2154    #[test]
2155    fn exact_provenance_pages_and_chart_captions_follow_docling() {
2156        let mut doc = DoclingDocument::new("t");
2157        doc.push(Node::PageInfo {
2158            page_no: 1,
2159            width: 3.0,
2160            height: 4.0,
2161        });
2162        let table = crate::Table {
2163            rows: vec![vec!["a".to_string(), "b".into()]],
2164            ..Default::default()
2165        };
2166        doc.push(Node::Group {
2167            label: "sheet".into(),
2168            name: Some("Data".into()),
2169            layer: None,
2170            children: vec![
2171                // Node order is the position-sorted one; creation order (the
2172                // `seq`) had the chart first — so the chart is `#/pictures/0`
2173                // *and* its caption `#/texts/0`, while the table stays the
2174                // group's first child.
2175                Node::Prov {
2176                    page_no: 1,
2177                    bbox: [0.0, 0.0, 3.0, 4.0],
2178                    charspan: [0, 0],
2179                    seq: Some(1),
2180                    inner: Box::new(Node::Table(table.clone())),
2181                },
2182                Node::Prov {
2183                    page_no: 1,
2184                    bbox: [0.0, 1.0, 1.0, 1.0],
2185                    charspan: [0, 0],
2186                    seq: Some(0),
2187                    inner: Box::new(Node::Chart {
2188                        kind: "bar_chart".into(),
2189                        table,
2190                        caption: Some("Sales".into()),
2191                        location: Some([0, 128, 170, 128]),
2192                    }),
2193                },
2194            ],
2195        });
2196        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2197        assert_eq!(
2198            v["pages"],
2199            serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
2200        );
2201        assert_eq!(
2202            v["tables"][0]["prov"],
2203            serde_json::json!([{
2204                "page_no": 1,
2205                "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
2206                "charspan": [0, 0],
2207            }])
2208        );
2209        assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
2210        // The caption is the group's child *before* the picture, parented to
2211        // the group, and referenced by the picture.
2212        let sheet = &v["groups"][0];
2213        assert_eq!(
2214            sheet["children"],
2215            serde_json::json!([
2216                {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
2217            ])
2218        );
2219        let cap = &v["texts"][0];
2220        assert_eq!(cap["label"], "caption");
2221        assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
2222        assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
2223        assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
2224        let pic = &v["pictures"][0];
2225        assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
2226        assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
2227        assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
2228        assert_eq!(
2229            pic["meta"]["classification"]["predictions"][0]["class_name"],
2230            "bar_chart"
2231        );
2232        assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
2233    }
2234
2235    /// An all-zero location is the "no geometry" sentinel — a slide's speaker
2236    /// notes carry one — and docling writes it as a zero bbox, not as a box
2237    /// spanning the whole page, which is what denormalizing the grid gives.
2238    #[test]
2239    fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
2240        let mut doc = DoclingDocument::new("t");
2241        doc.push(Node::PageInfo {
2242            page_no: 1,
2243            width: 12192000.0,
2244            height: 6858000.0,
2245        });
2246        doc.push(Node::Furniture {
2247            layer: ContentLayer::Notes,
2248            inner: Box::new(Node::Located {
2249                location: [0, 0, 0, 0],
2250                inner: Box::new(Node::Paragraph {
2251                    text: "a note".into(),
2252                }),
2253            }),
2254        });
2255        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2256        let prov = &v["texts"][0]["prov"][0];
2257        assert_eq!(prov["page_no"], 1);
2258        assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
2259        assert_eq!(
2260            prov["bbox"],
2261            serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
2262        );
2263        // The page itself is recorded at its true size.
2264        assert_eq!(
2265            v["pages"]["1"]["size"],
2266            serde_json::json!({"width": 12192000.0, "height": 6858000.0})
2267        );
2268    }
2269
2270    /// #171: PageInfo markers become the `pages` map, and `Located` wrappers /
2271    /// node-level locations become per-item `prov` — the 0–511 grid
2272    /// denormalized against the page into BOTTOMLEFT points. Without markers
2273    /// (every declarative backend) the JSON stays exactly as before: empty
2274    /// `pages`, `prov: []` even for located nodes.
2275    #[test]
2276    fn page_markers_produce_pages_and_prov() {
2277        let mut doc = DoclingDocument::new("t");
2278        doc.push(Node::PageInfo {
2279            page_no: 1,
2280            width: 512.0,
2281            height: 1024.0,
2282        });
2283        doc.push(Node::Located {
2284            location: [128, 64, 256, 128], // quarter/eighth points of the grid
2285            inner: Box::new(Node::Paragraph {
2286                text: "hello".into(),
2287            }),
2288        });
2289        doc.push(Node::Table(Table {
2290            rows: vec![vec!["a".into()]],
2291            location: Some([0, 0, 512, 512]),
2292            ..Table::default()
2293        }));
2294        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2295        assert_eq!(v["pages"]["1"]["page_no"], 1);
2296        assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
2297        assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
2298        // 512-wide page: grid x scales 1:1; 1024-high: grid y doubles, then
2299        // flips to the BOTTOMLEFT origin (t from grid-top 64 → 1024-128=896).
2300        let prov = &v["texts"][0]["prov"][0];
2301        assert_eq!(prov["page_no"], 1);
2302        assert_eq!(prov["bbox"]["l"], 128.0);
2303        assert_eq!(prov["bbox"]["t"], 896.0);
2304        assert_eq!(prov["bbox"]["r"], 256.0);
2305        assert_eq!(prov["bbox"]["b"], 768.0);
2306        assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
2307        assert_eq!(prov["charspan"][1], 5);
2308        // The table adopts its own location field; charspan is [0, 0].
2309        let tprov = &v["tables"][0]["prov"][0];
2310        assert_eq!(tprov["bbox"]["t"], 1024.0);
2311        assert_eq!(tprov["bbox"]["b"], 0.0);
2312        assert_eq!(tprov["charspan"][1], 0);
2313
2314        // No markers → the pre-#171 shape, byte for byte.
2315        let mut plain = DoclingDocument::new("t");
2316        plain.push(Node::Located {
2317            location: [1, 2, 3, 4],
2318            inner: Box::new(Node::Paragraph { text: "x".into() }),
2319        });
2320        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
2321        assert_eq!(v["pages"], serde_json::json!({}));
2322        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
2323    }
2324
2325    #[test]
2326    fn picture_image_in_markdown_modes_and_json() {
2327        let doc = doc_with_image();
2328        // placeholder (default) ignores the image
2329        assert!(doc.export_to_markdown().contains("<!-- image -->"));
2330        // embedded → base64 data URI (b"foobar" → "Zm9vYmFy")
2331        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
2332        assert!(
2333            md.contains("![Image](data:image/png;base64,Zm9vYmFy)"),
2334            "got:\n{md}"
2335        );
2336        assert!(files.is_empty());
2337        // referenced → file link + collected bytes
2338        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
2339        assert!(
2340            md.contains("![Image](artifacts/image_000000.png)"),
2341            "got:\n{md}"
2342        );
2343        assert_eq!(
2344            files,
2345            vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
2346        );
2347        // JSON carries the ImageRef (data URI + size — floats, as docling's
2348        // `Size` is — placed before `annotations`).
2349        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2350        assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
2351        assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
2352        let keys: Vec<&str> = v["pictures"][0]
2353            .as_object()
2354            .unwrap()
2355            .keys()
2356            .map(String::as_str)
2357            .collect();
2358        assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
2359        assert_eq!(
2360            v["pictures"][0]["image"]["uri"],
2361            "data:image/png;base64,Zm9vYmFy"
2362        );
2363    }
2364
2365    #[test]
2366    fn exports_docling_schema() {
2367        let mut doc = DoclingDocument::new("t");
2368        doc.push(Node::Heading {
2369            level: 1,
2370            text: "Title".into(),
2371        });
2372        doc.push(Node::Heading {
2373            level: 2,
2374            text: "Sec".into(),
2375        });
2376        doc.push(Node::Paragraph {
2377            text: "Body &amp; more".into(),
2378        }); // markdown-escaped
2379        doc.push(Node::ListItem {
2380            ordered: false,
2381            number: 0,
2382            first_in_list: true,
2383            text: "one".into(),
2384            level: 0,
2385            marker: None,
2386            location: None,
2387            dclx: None,
2388            href: None,
2389            layer: None,
2390        });
2391        doc.push(Node::ListItem {
2392            ordered: false,
2393            number: 0,
2394            first_in_list: false,
2395            text: "two".into(),
2396            level: 0,
2397            marker: None,
2398            location: None,
2399            dclx: None,
2400            href: None,
2401            layer: None,
2402        });
2403        doc.push(Node::Table(Table {
2404            rows: vec![vec!["A".into(), "B".into()]],
2405            location: None,
2406            structure: None,
2407            cell_blocks: None,
2408            cells: None,
2409            caption: None,
2410            caption_parent: Default::default(),
2411        }));
2412
2413        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2414        assert_eq!(v["schema_name"], "DoclingDocument");
2415        assert_eq!(v["version"], "1.10.0");
2416        assert_eq!(v["texts"][0]["label"], "title");
2417        assert_eq!(v["texts"][1]["label"], "section_header");
2418        assert_eq!(v["texts"][1]["level"], 1); // heading level 2 → docling level 1
2419        assert_eq!(v["texts"][2]["text"], "Body & more"); // un-escaped for the wire format
2420                                                          // consecutive list items fold into one list group, parented to it
2421        assert_eq!(v["groups"][0]["label"], "list");
2422        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
2423        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
2424        assert_eq!(v["texts"][3]["marker"], "-");
2425        // table grid + header flag
2426        assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
2427        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
2428    }
2429    /// A named group on a non-body layer — docling's hidden spreadsheet sheet:
2430    /// the group carries the sheet's name and the `invisible` layer, and every
2431    /// item inside it carries the layer too.
2432    #[test]
2433    fn a_layered_group_stamps_its_whole_subtree() {
2434        let doc = DoclingDocument {
2435            name: "s".into(),
2436            nodes: vec![
2437                Node::Group {
2438                    label: "sheet".into(),
2439                    name: Some("Sheet1".into()),
2440                    layer: None,
2441                    children: vec![Node::Paragraph {
2442                        text: "visible".into(),
2443                    }],
2444                },
2445                Node::Group {
2446                    label: "sheet".into(),
2447                    name: Some("Sheet2".into()),
2448                    layer: Some(ContentLayer::Invisible),
2449                    children: vec![Node::Paragraph {
2450                        text: "hidden".into(),
2451                    }],
2452                },
2453            ],
2454            ..DoclingDocument::new("s")
2455        };
2456        let v = crate::json::to_json(&doc);
2457        assert_eq!(v["groups"][0]["label"], "sheet");
2458        assert_eq!(v["groups"][0]["name"], "Sheet1");
2459        assert_eq!(v["groups"][0]["content_layer"], "body");
2460        assert_eq!(v["texts"][0]["content_layer"], "body");
2461        assert_eq!(v["groups"][1]["name"], "Sheet2");
2462        assert_eq!(v["groups"][1]["content_layer"], "invisible");
2463        assert_eq!(v["texts"][1]["content_layer"], "invisible");
2464        // The group's children are the items, and the body holds the groups.
2465        assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
2466        assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
2467    }
2468
2469    /// A backend-built item tree is serialized as it is: items numbered in
2470    /// creation order per bucket (a field region's part texts included), the
2471    /// tree's parents / children / layers, docling's field order for
2472    /// `formatting`, `hyperlink`, `level`, `enumerated`/`marker`, a rich
2473    /// cell's `ref` on `table_cells` only, raw cell text.
2474    /// The DOCX tree's extras: an item `delete`d (docling's `delete_items`,
2475    /// the spacer between two items of a resumed list) is neither written nor
2476    /// numbered, `comments` back-refs sit between `prov` and `orig`, and a
2477    /// chart picture carries `classification` plus `tabular_chart`.
2478    #[test]
2479    fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
2480        use crate::tree::{ItemTree, TreeKind};
2481        let mut t = ItemTree::default();
2482        let text = |txt: &str| TreeKind::Text {
2483            label: "text".into(),
2484            text: txt.into(),
2485            orig: None,
2486            formatting: None,
2487            hyperlink: None,
2488            level: None,
2489            list: None,
2490        };
2491        let a = t.add(None, None, text("a"));
2492        let blank = t.add(None, None, text(""));
2493        let b = t.add(None, None, text("b"));
2494        t.delete(blank);
2495        let group = t.add(
2496            None,
2497            Some(ContentLayer::Notes),
2498            TreeKind::Group {
2499                label: "comment_section".into(),
2500                name: "comment-0".into(),
2501            },
2502        );
2503        t.add(Some(group), Some(ContentLayer::Notes), text("note"));
2504        t.items[a].comments.push(group);
2505        t.add(
2506            None,
2507            None,
2508            TreeKind::Picture {
2509                captions: Vec::new(),
2510                image: None,
2511                classification: Some("bar_chart".into()),
2512                confidence: None,
2513                chart: Some(Table {
2514                    rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
2515                    ..Table::default()
2516                }),
2517                dpi: None,
2518            },
2519        );
2520        assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
2521        assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
2522        let mut doc = DoclingDocument::new("t");
2523        doc.tree = Some(t);
2524        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2525        let texts = v["texts"].as_array().unwrap();
2526        assert_eq!(texts.len(), 3);
2527        assert_eq!(texts[1]["text"], "b");
2528        assert_eq!(texts[1]["self_ref"], "#/texts/1");
2529        assert_eq!(
2530            v["body"]["children"],
2531            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
2532        );
2533        let keys: Vec<&str> = texts[0]
2534            .as_object()
2535            .unwrap()
2536            .keys()
2537            .map(String::as_str)
2538            .collect();
2539        assert_eq!(
2540            keys,
2541            vec![
2542                "self_ref",
2543                "parent",
2544                "children",
2545                "content_layer",
2546                "label",
2547                "prov",
2548                "comments",
2549                "orig",
2550                "text"
2551            ]
2552        );
2553        assert_eq!(
2554            texts[0]["comments"],
2555            serde_json::json!([{"$ref": "#/groups/0"}])
2556        );
2557        assert!(texts[1].get("comments").is_none());
2558        let meta = &v["pictures"][0]["meta"];
2559        assert_eq!(
2560            meta["classification"]["predictions"][0]["class_name"],
2561            "bar_chart"
2562        );
2563        assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
2564    }
2565
2566    /// A tree item's `TreeProv` is written verbatim — a raw EMU box with
2567    /// whatever origin tag the backend set (`BOTTOMLEFT` here) and a per-item
2568    /// charspan, a note's zero `TOPLEFT` box — a picture's `image.dpi` is the file's when the backend
2569    /// read one, an item without provenance writes `prov: []`, and the page
2570    /// map still comes from the flat stream's markers.
2571    #[test]
2572    fn tree_items_carry_exact_provenance_and_dpi() {
2573        use crate::tree::{ItemTree, TreeKind, TreeProv};
2574        let text = |label: &str, t: &str| TreeKind::Text {
2575            label: label.into(),
2576            text: t.into(),
2577            orig: None,
2578            formatting: None,
2579            hyperlink: None,
2580            level: None,
2581            list: None,
2582        };
2583        let mut t = ItemTree::default();
2584        let slide = t.add(
2585            None,
2586            None,
2587            TreeKind::Group {
2588                label: "chapter".into(),
2589                name: "slide-0".into(),
2590            },
2591        );
2592        t.add_with_prov(
2593            Some(slide),
2594            None,
2595            text("paragraph", "héllo"),
2596            TreeProv {
2597                page_no: 1,
2598                bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
2599                bottom_left: true,
2600                charspan: [0, 5],
2601            },
2602        );
2603        t.add_with_prov(
2604            Some(slide),
2605            None,
2606            TreeKind::Picture {
2607                captions: Vec::new(),
2608                image: Some(crate::PictureImage {
2609                    mimetype: "image/png".into(),
2610                    width: 2,
2611                    height: 2,
2612                    data: vec![0],
2613                }),
2614                classification: None,
2615                confidence: None,
2616                chart: None,
2617                dpi: Some(300),
2618            },
2619            TreeProv {
2620                page_no: 1,
2621                bbox: [0.0; 4],
2622                bottom_left: false,
2623                charspan: [0, 0],
2624            },
2625        );
2626        t.add(
2627            Some(slide),
2628            Some(ContentLayer::Notes),
2629            text("text", "no geometry"),
2630        );
2631        let mut doc = DoclingDocument::new("t");
2632        doc.push(Node::PageInfo {
2633            page_no: 1,
2634            width: 9144000.0,
2635            height: 6858000.0,
2636        });
2637        doc.tree = Some(t);
2638        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2639        assert_eq!(
2640            v["texts"][0]["prov"],
2641            serde_json::json!([{
2642                "page_no": 1,
2643                "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
2644                "charspan": [0, 5],
2645            }])
2646        );
2647        assert_eq!(v["texts"][0]["label"], "paragraph");
2648        assert_eq!(
2649            v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
2650            "TOPLEFT"
2651        );
2652        assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
2653        assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
2654        assert_eq!(v["texts"][1]["content_layer"], "notes");
2655        assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
2656        assert_eq!(v["pages"]["1"]["page_no"], 1);
2657    }
2658
2659    /// docling-core's `validate_document` clamps every provenance box (and a
2660    /// one-page table's cell boxes) into its page — the state every
2661    /// `ConversionResult` leaves a document in, so the state docling's JSON
2662    /// shows. A box on a page the document does not describe is left alone.
2663    #[test]
2664    fn provenance_boxes_are_clamped_to_their_page() {
2665        let mut doc = DoclingDocument::new("t");
2666        doc.push(Node::PageInfo {
2667            page_no: 1,
2668            width: 10.0,
2669            height: 8.0,
2670        });
2671        doc.push(Node::Prov {
2672            page_no: 1,
2673            bbox: [-1.0, 2.0, 12.0, 9.5],
2674            charspan: [0, 1],
2675            seq: None,
2676            inner: Box::new(Node::Paragraph { text: "x".into() }),
2677        });
2678        let mut table = Table {
2679            rows: vec![vec!["a".into()]],
2680            ..Table::default()
2681        };
2682        table.cells = Some(vec![crate::TableCell {
2683            text: "a".into(),
2684            bbox: Some([1.0, 1.0, 11.0, 9.0]),
2685            start_row: 0,
2686            start_col: 0,
2687            row_span: 1,
2688            col_span: 1,
2689            column_header: false,
2690            row_header: false,
2691            row_section: false,
2692        }]);
2693        doc.push(Node::Prov {
2694            page_no: 1,
2695            bbox: [0.0, 0.0, 10.0, 8.0],
2696            charspan: [0, 0],
2697            seq: None,
2698            inner: Box::new(Node::Table(table)),
2699        });
2700        doc.push(Node::Prov {
2701            page_no: 7,
2702            bbox: [-5.0, 0.0, 50.0, 50.0],
2703            charspan: [0, 1],
2704            seq: None,
2705            inner: Box::new(Node::Paragraph { text: "y".into() }),
2706        });
2707        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2708        assert_eq!(
2709            v["texts"][0]["prov"][0]["bbox"],
2710            serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
2711        );
2712        let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
2713        assert_eq!(
2714            (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
2715            (Some(1.0), Some(10.0), Some(8.0))
2716        );
2717        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
2718        assert_eq!(
2719            v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
2720            "page 7 is not described"
2721        );
2722    }
2723
2724    #[test]
2725    fn a_backend_item_tree_is_written_verbatim() {
2726        use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
2727        let mut t = ItemTree::default();
2728        let text = |label: &str, txt: &str| TreeKind::Text {
2729            label: label.into(),
2730            text: txt.into(),
2731            orig: None,
2732            formatting: None,
2733            hyperlink: None,
2734            level: None,
2735            list: None,
2736        };
2737        let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
2738        let h = t.add(None, None, text("title", "Heading"));
2739        let group = t.add(
2740            Some(h),
2741            None,
2742            TreeKind::Group {
2743                label: "inline".into(),
2744                name: "group".into(),
2745            },
2746        );
2747        t.add(
2748            Some(group),
2749            None,
2750            TreeKind::Text {
2751                label: "text".into(),
2752                text: "bold".into(),
2753                orig: None,
2754                formatting: Some(Formatting {
2755                    bold: true,
2756                    ..Formatting::default()
2757                }),
2758                hyperlink: Some("https://example.com/".into()),
2759                level: None,
2760                list: None,
2761            },
2762        );
2763        t.add(
2764            Some(group),
2765            None,
2766            TreeKind::Code {
2767                text: "x = 1".into(),
2768                orig: None,
2769                language: Some("python".into()),
2770                formatting: None,
2771                hyperlink: None,
2772            },
2773        );
2774        let sub = t.add(
2775            Some(h),
2776            None,
2777            TreeKind::Text {
2778                label: "section_header".into(),
2779                text: "Sub".into(),
2780                orig: Some("Sub\u{2019}".into()),
2781                formatting: None,
2782                hyperlink: None,
2783                level: Some(1),
2784                list: None,
2785            },
2786        );
2787        t.add(
2788            Some(sub),
2789            None,
2790            TreeKind::Text {
2791                label: "list_item".into(),
2792                text: "item".into(),
2793                orig: None,
2794                formatting: None,
2795                hyperlink: None,
2796                level: None,
2797                list: Some(ListMeta {
2798                    enumerated: true,
2799                    marker: "3.".into(),
2800                }),
2801            },
2802        );
2803        let _region = t.add(
2804            Some(sub),
2805            None,
2806            TreeKind::FieldRegion {
2807                items: vec![crate::FieldItem {
2808                    marker: None,
2809                    key: Some("Name".into()),
2810                    value: Some("Duck".into()),
2811                    value_kind: Some("read_only".into()),
2812                }],
2813            },
2814        );
2815        let table = t.add(
2816            Some(sub),
2817            None,
2818            TreeKind::Table {
2819                table: Table {
2820                    rows: vec![vec!["a  \n&lt;".into(), "b".into()]],
2821                    cells: Some(vec![
2822                        crate::TableCell {
2823                            text: "a  \n&lt;".into(),
2824                            bbox: None,
2825                            start_row: 0,
2826                            start_col: 0,
2827                            row_span: 3,
2828                            col_span: 1,
2829                            column_header: false,
2830                            row_header: true,
2831                            row_section: false,
2832                        },
2833                        crate::TableCell {
2834                            text: "b".into(),
2835                            bbox: None,
2836                            start_row: 0,
2837                            start_col: 1,
2838                            row_span: 1,
2839                            col_span: 1,
2840                            column_header: false,
2841                            row_header: false,
2842                            row_section: false,
2843                        },
2844                    ]),
2845                    ..Table::default()
2846                },
2847                rich_cells: vec![(0, 1, 0)], // patched below
2848                captions: Vec::new(),
2849            },
2850        );
2851        let cell_group = t.add(
2852            Some(table),
2853            None,
2854            TreeKind::Group {
2855                label: "unspecified".into(),
2856                name: "rich_cell_group_1_0_0".into(),
2857            },
2858        );
2859        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
2860            *rich_cells = vec![(0, 1, cell_group)];
2861        }
2862        let after = t.add(Some(sub), None, text("text", "after the region"));
2863        let _ = (title, after);
2864
2865        let doc = DoclingDocument {
2866            tree: Some(t),
2867            ..DoclingDocument::new("t")
2868        };
2869        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2870        // Creation order: Page, Heading, bold, x = 1, Sub, item, [Name, Duck], after.
2871        let texts: Vec<&str> = v["texts"]
2872            .as_array()
2873            .unwrap()
2874            .iter()
2875            .map(|t| t["text"].as_str().unwrap())
2876            .collect();
2877        assert_eq!(
2878            texts,
2879            [
2880                "Page",
2881                "Heading",
2882                "bold",
2883                "x = 1",
2884                "Sub",
2885                "item",
2886                "Name",
2887                "Duck",
2888                "after the region"
2889            ]
2890        );
2891        assert_eq!(
2892            v["body"]["children"],
2893            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
2894        );
2895        assert_eq!(v["texts"][0]["content_layer"], "furniture");
2896        assert_eq!(
2897            v["texts"][1]["children"],
2898            serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
2899        );
2900        let bold = &v["texts"][2];
2901        assert_eq!(bold["parent"]["$ref"], "#/groups/0");
2902        let keys: Vec<&str> = bold
2903            .as_object()
2904            .unwrap()
2905            .keys()
2906            .map(String::as_str)
2907            .collect();
2908        assert_eq!(
2909            keys,
2910            [
2911                "self_ref",
2912                "parent",
2913                "children",
2914                "content_layer",
2915                "label",
2916                "prov",
2917                "orig",
2918                "text",
2919                "formatting",
2920                "hyperlink"
2921            ]
2922        );
2923        assert_eq!(
2924            bold["formatting"],
2925            serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
2926        );
2927        let code = &v["texts"][3];
2928        assert_eq!(code["label"], "code");
2929        assert_eq!(code["code_language"], "Python");
2930        let sub = &v["texts"][4];
2931        assert_eq!(sub["orig"], "Sub\u{2019}");
2932        assert_eq!(sub["level"], 1);
2933        let item = &v["texts"][5];
2934        let keys: Vec<&str> = item
2935            .as_object()
2936            .unwrap()
2937            .keys()
2938            .map(String::as_str)
2939            .collect();
2940        assert_eq!(
2941            keys,
2942            [
2943                "self_ref",
2944                "parent",
2945                "children",
2946                "content_layer",
2947                "label",
2948                "prov",
2949                "orig",
2950                "text",
2951                "enumerated",
2952                "marker"
2953            ]
2954        );
2955        assert_eq!(item["marker"], "3.");
2956        assert_eq!(v["texts"][7]["kind"], "read_only");
2957        assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
2958        let table = &v["tables"][0];
2959        assert_eq!(
2960            table["children"],
2961            serde_json::json!([{"$ref": "#/groups/1"}])
2962        );
2963        let cells = table["data"]["table_cells"].as_array().unwrap();
2964        assert_eq!(
2965            cells[0]["text"], "a  \n&lt;",
2966            "raw cell text is written verbatim"
2967        );
2968        assert_eq!(
2969            cells[0]["end_row_offset_idx"], 3,
2970            "declared spans are not clamped"
2971        );
2972        assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
2973        assert!(cells[0].get("ref").is_none());
2974        assert!(
2975            table["data"]["grid"][0][1].get("ref").is_none(),
2976            "the grid shows plain cells"
2977        );
2978        assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
2979    }
2980
2981    /// A comment section that links its note text rather than its group — the
2982    /// spreadsheet shape, where docling-core's `add_comment` appends the text
2983    /// item's ref to each target.
2984    #[test]
2985    fn a_comment_section_can_be_referenced_by_its_note_text() {
2986        let doc = DoclingDocument {
2987            name: "c".into(),
2988            nodes: vec![
2989                Node::Commented {
2990                    comments: vec![0],
2991                    inner: Box::new(Node::Paragraph {
2992                        text: "annotated".into(),
2993                    }),
2994                },
2995                Node::CommentSection {
2996                    name: "comment-Sheet1-A1".into(),
2997                    text: "[author: A]: note".into(),
2998                    refs_note_text: true,
2999                    grouped: true,
3000                },
3001            ],
3002            ..DoclingDocument::new("c")
3003        };
3004        let v = crate::json::to_json(&doc);
3005        assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
3006        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
3007    }
3008
3009    /// docx reviewer comments: a `comment_section` group on the notes layer
3010    /// holding the note text, and a `comments` back-ref on the annotated item —
3011    /// keyed between `prov` and `orig`, the slot docling emits it in.
3012    #[test]
3013    fn comment_sections_link_back_to_their_items() {
3014        let doc = DoclingDocument {
3015            name: "c".into(),
3016            nodes: vec![
3017                Node::Commented {
3018                    comments: vec![0],
3019                    inner: Box::new(Node::Paragraph {
3020                        text: "annotated".into(),
3021                    }),
3022                },
3023                Node::Paragraph {
3024                    text: "plain".into(),
3025                },
3026                Node::CommentSection {
3027                    name: "comment-7".into(),
3028                    text: "[time: t]: note".into(),
3029                    refs_note_text: false,
3030                    grouped: true,
3031                },
3032            ],
3033            ..DoclingDocument::new("c")
3034        };
3035        let v = crate::json::to_json(&doc);
3036        // The group is the comment section; its only child is the notes text.
3037        assert_eq!(v["groups"][0]["label"], "comment_section");
3038        assert_eq!(v["groups"][0]["name"], "comment-7");
3039        assert_eq!(v["groups"][0]["content_layer"], "notes");
3040        assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
3041        assert_eq!(v["texts"][2]["content_layer"], "notes");
3042        // The annotated item points back at the group; the plain one has no key.
3043        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
3044        assert!(v["texts"][1].get("comments").is_none());
3045        // docling's key order: … prov, comments, orig, text.
3046        let keys: Vec<&str> = v["texts"][0]
3047            .as_object()
3048            .unwrap()
3049            .keys()
3050            .map(String::as_str)
3051            .collect();
3052        assert_eq!(
3053            &keys[keys.len() - 4..],
3054            &["prov", "comments", "orig", "text"]
3055        );
3056    }
3057
3058    fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
3059        Node::Picture {
3060            caption: Some(caption.into()),
3061            caption_href: None,
3062            image: None,
3063            classification: None,
3064            caption_parent,
3065        }
3066    }
3067
3068    fn group(children: Vec<Node>) -> Node {
3069        Node::Group {
3070            label: "section".into(),
3071            name: None,
3072            layer: None,
3073            children,
3074        }
3075    }
3076
3077    fn refs(v: &Value) -> Vec<&str> {
3078        v.as_array()
3079            .unwrap()
3080            .iter()
3081            .map(|r| r["$ref"].as_str().unwrap())
3082            .collect()
3083    }
3084
3085    /// #390: a declarative backend's caption is docling's `add_text` default —
3086    /// a body child, appended as it is created — wherever the picture sits:
3087    /// ahead of a top-level picture, behind the top-level item enclosing a
3088    /// nested one. The picture references it either way and has no children.
3089    #[test]
3090    fn a_body_caption_follows_the_enclosing_top_level_item() {
3091        let mut doc = DoclingDocument::new("t");
3092        doc.push(picture("top", CaptionParent::Body));
3093        doc.push(group(vec![
3094            Node::Paragraph { text: "p".into() },
3095            picture("nested", CaptionParent::Body),
3096        ]));
3097        doc.push(Node::Paragraph {
3098            text: "after".into(),
3099        });
3100        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3101        assert_eq!(
3102            refs(&v["body"]["children"]),
3103            [
3104                "#/texts/0",
3105                "#/pictures/0",
3106                "#/groups/0",
3107                "#/texts/2",
3108                "#/texts/3"
3109            ]
3110        );
3111        assert_eq!(
3112            refs(&v["groups"][0]["children"]),
3113            ["#/texts/1", "#/pictures/1"]
3114        );
3115        for (cap, pic) in [(0, 0), (2, 1)] {
3116            assert_eq!(v["texts"][cap]["label"], "caption");
3117            assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
3118            assert_eq!(
3119                refs(&v["pictures"][pic]["captions"]),
3120                [format!("#/texts/{cap}")]
3121            );
3122            assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
3123        }
3124    }
3125
3126    /// The PDF pipeline's caption is the picture's (or table's) own child,
3127    /// as docling attaches a layout caption.
3128    #[test]
3129    fn an_item_caption_is_the_items_first_child() {
3130        let mut doc = DoclingDocument::new("t");
3131        doc.push(picture("fig", CaptionParent::Item));
3132        doc.push(Node::Table(Table {
3133            rows: vec![vec!["a".into()]],
3134            caption: Some("tab".into()),
3135            caption_parent: CaptionParent::Item,
3136            ..Table::default()
3137        }));
3138        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3139        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
3140        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
3141        assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
3142        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3143        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
3144        assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
3145        assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
3146    }
3147
3148    /// A container caption sits beside its item under the item's parent —
3149    /// ahead of it (an office chart's title) or behind it (an HTML
3150    /// `<figure>`'s table, whose figcaption docling adds after the table).
3151    #[test]
3152    fn a_container_caption_is_the_items_sibling() {
3153        let mut doc = DoclingDocument::new("t");
3154        doc.push(group(vec![
3155            picture("chart", CaptionParent::Container),
3156            Node::Table(Table {
3157                rows: vec![vec!["a".into()]],
3158                caption: Some("figcaption".into()),
3159                caption_parent: CaptionParent::ContainerAfter,
3160                ..Table::default()
3161            }),
3162        ]));
3163        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3164        assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
3165        assert_eq!(
3166            refs(&v["groups"][0]["children"]),
3167            ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
3168        );
3169        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
3170        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
3171        assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
3172        assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
3173    }
3174}