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            // PDF page headers and footers: docling writes them as body-parented
1222            // `page_header`/`page_footer` text items on the furniture layer, so a
1223            // JSON consumer can read running headers (printed page ids, dates).
1224            Node::PageFurniture {
1225                footer,
1226                location,
1227                text,
1228            } => {
1229                if self.cur_page > 0 {
1230                    self.pending_loc = Some(*location);
1231                }
1232                let label = if *footer {
1233                    "page_footer"
1234                } else {
1235                    "page_header"
1236                };
1237                let item = self.add_text(label, text, parent, json!({}));
1238                self.pending_loc = None;
1239                self.set_layer(&item, "furniture");
1240                Some(item)
1241            }
1242            // A location wrapper turns into the wrapped item's `prov` entry —
1243            // but only on pages the PDF paths described with a PageInfo marker
1244            // (other geometry-bearing backends, e.g. PPTX shapes, keep their
1245            // pre-#171 provenance-less JSON until they emit markers too).
1246            Node::Located { location, inner } => {
1247                if self.cur_page > 0 {
1248                    self.pending_loc = Some(*location);
1249                }
1250                let r = self.add_node(inner, parent);
1251                self.pending_loc = None;
1252                r
1253            }
1254            Node::Prov {
1255                page_no,
1256                bbox,
1257                charspan,
1258                inner,
1259                ..
1260            } => {
1261                self.pending_exact = Some(ExactProv {
1262                    page_no: *page_no,
1263                    bbox: bbox.map(f64::from),
1264                    bottom_left: false,
1265                    charspan: *charspan,
1266                });
1267                let r = self.add_node(inner, parent);
1268                self.pending_exact = None;
1269                r
1270            }
1271            // Page breaks are DocLang-only; docling omits them from the JSON body.
1272            Node::PageBreak => None,
1273            // The page marker: record the page's number and size for the
1274            // `pages` map, and denormalize every following location against it.
1275            Node::PageInfo {
1276                page_no,
1277                width,
1278                height,
1279            } => {
1280                self.cur_page = *page_no;
1281                self.cur_w = *width as f64;
1282                self.cur_h = *height as f64;
1283                if *page_no > 0 {
1284                    self.pages.push((*page_no, self.cur_w, self.cur_h));
1285                }
1286                None
1287            }
1288            // Handled by `add_list` in `walk`.
1289            Node::ListItem { .. } => None,
1290        }
1291    }
1292
1293    /// A form key-value region: `field_regions/N` holds the region, each field is
1294    /// a `field_items/M` whose children are its `marker` / `field_key` /
1295    /// `field_value` texts (absent parts are simply omitted).
1296    fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
1297        let self_ref = format!("#/field_regions/{}", self.field_regions.len());
1298        self.field_regions.push(Value::Null);
1299        let region_index = self.field_regions.len() - 1;
1300        let mut item_refs = Vec::new();
1301        for item in items {
1302            item_refs.push(json!({ "$ref": self.add_field_item(item, &self_ref) }));
1303        }
1304        self.field_regions[region_index] = json!({
1305            "self_ref": self_ref,
1306            "parent": { "$ref": parent },
1307            "children": item_refs,
1308            "content_layer": "body",
1309            "label": "field_region",
1310            "prov": [],
1311        });
1312        self_ref
1313    }
1314
1315    /// A `KeyValueItem`: docling's `GraphData` written cell for cell and link
1316    /// for link (`key_value_items/N`), the item itself childless and without
1317    /// provenance, the way the XBRL backend creates it.
1318    fn add_key_value_graph(
1319        &mut self,
1320        cells: &[crate::GraphCell],
1321        links: &[crate::GraphLink],
1322        parent: &str,
1323    ) -> String {
1324        let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
1325        let cells: Vec<Value> = cells
1326            .iter()
1327            .map(|c| {
1328                json!({
1329                    "label": c.label,
1330                    "cell_id": c.cell_id,
1331                    "text": c.text,
1332                    "orig": c.orig,
1333                })
1334            })
1335            .collect();
1336        let links: Vec<Value> = links
1337            .iter()
1338            .map(|l| {
1339                json!({
1340                    "label": l.label,
1341                    "source_cell_id": l.source_cell_id,
1342                    "target_cell_id": l.target_cell_id,
1343                })
1344            })
1345            .collect();
1346        self.key_value_items.push(json!({
1347            "self_ref": self_ref,
1348            "parent": { "$ref": parent },
1349            "children": [],
1350            "content_layer": "body",
1351            "label": "key_value_region",
1352            "prov": [],
1353            "captions": [],
1354            "references": [],
1355            "footnotes": [],
1356            "graph": { "cells": cells, "links": links },
1357        }));
1358        self_ref
1359    }
1360
1361    fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
1362        let self_ref = format!("#/field_items/{}", self.field_items.len());
1363        self.field_items.push(Value::Null);
1364        let item_index = self.field_items.len() - 1;
1365        let mut child_refs = Vec::new();
1366        for (label, text) in [
1367            ("marker", &item.marker),
1368            ("field_key", &item.key),
1369            ("field_value", &item.value),
1370        ] {
1371            if let Some(text) = text {
1372                // A value's `kind` (docling's `read_only` / `fillable`)
1373                // follows its text.
1374                let extra = match (label, &item.value_kind) {
1375                    ("field_value", Some(kind)) => json!({ "kind": kind }),
1376                    _ => json!({}),
1377                };
1378                child_refs.push(json!({ "$ref": self.add_text(label, text, &self_ref, extra) }));
1379            }
1380        }
1381        self.field_items[item_index] = json!({
1382            "self_ref": self_ref,
1383            "parent": { "$ref": parent },
1384            "children": child_refs,
1385            "content_layer": "body",
1386            "label": "field_item",
1387            "prov": [],
1388        });
1389        self_ref
1390    }
1391
1392    /// Move an already-emitted item onto a content layer. Notes are single
1393    /// text items today; a deeper notes subtree would need its children moved
1394    /// too, and no backend builds one.
1395    fn set_layer(&mut self, self_ref: &str, layer: &str) {
1396        let bucket = match self_ref.split('/').nth(1) {
1397            Some("texts") => &mut self.texts,
1398            Some("tables") => &mut self.tables,
1399            Some("pictures") => &mut self.pictures,
1400            Some("groups") => &mut self.groups,
1401            _ => return,
1402        };
1403        if let Some(item) = self_ref
1404            .rsplit('/')
1405            .next()
1406            .and_then(|i| i.parse::<usize>().ok())
1407            .and_then(|i| bucket.get_mut(i))
1408        {
1409            item["content_layer"] = json!(layer);
1410        }
1411    }
1412
1413    fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
1414        let prov = self.take_prov(unescape_text(text).chars().count());
1415        self.add_text_with(label, text, parent, extra, prov)
1416    }
1417
1418    /// [`Self::add_text`] with an explicit `prov` (a chart caption shares the
1419    /// chart's box without consuming it).
1420    fn add_text_with(
1421        &mut self,
1422        label: &str,
1423        text: &str,
1424        parent: &str,
1425        extra: Value,
1426        prov: Value,
1427    ) -> String {
1428        let self_ref = format!("#/texts/{}", self.texts.len());
1429        let raw = unescape_text(text);
1430        let mut item = json!({
1431            "self_ref": self_ref,
1432            "parent": { "$ref": parent },
1433            "children": [],
1434            "content_layer": "body",
1435            "label": label,
1436            "prov": prov,
1437            "orig": raw,
1438            "text": raw,
1439        });
1440        merge(&mut item, extra);
1441        self.texts.push(item);
1442        self_ref
1443    }
1444
1445    /// A display-math formula item. `latex` is the raw content (no `$$`); docling
1446    /// re-wraps it and never escapes it.
1447    fn add_formula(&mut self, latex: &str, parent: &str) -> String {
1448        let self_ref = format!("#/texts/{}", self.texts.len());
1449        let prov = self.take_prov(latex.chars().count());
1450        self.texts.push(json!({
1451            "self_ref": self_ref,
1452            "parent": { "$ref": parent },
1453            "children": [],
1454            "content_layer": "body",
1455            "label": "formula",
1456            "prov": prov,
1457            "orig": latex,
1458            "text": latex,
1459        }));
1460        self_ref
1461    }
1462
1463    /// A CodeFormula-enriched display formula: `text` is the model's LaTeX
1464    /// while `orig` keeps the raw glyph extraction (docling's enriched shape;
1465    /// the plain [`Self::add_formula`] above sets both to the same string).
1466    fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
1467        let self_ref = format!("#/texts/{}", self.texts.len());
1468        let prov = self.take_prov(latex.chars().count());
1469        self.texts.push(json!({
1470            "self_ref": self_ref,
1471            "parent": { "$ref": parent },
1472            "children": [],
1473            "content_layer": "body",
1474            "label": "formula",
1475            "prov": prov,
1476            "orig": orig,
1477            "text": latex,
1478        }));
1479        self_ref
1480    }
1481
1482    fn add_code(
1483        &mut self,
1484        text: &str,
1485        language: Option<&str>,
1486        orig: Option<&str>,
1487        parent: &str,
1488    ) -> String {
1489        let self_ref = format!("#/texts/{}", self.texts.len());
1490        let raw = unescape_text(text);
1491        let prov = self.take_prov(raw.chars().count());
1492        self.texts.push(json!({
1493            "self_ref": self_ref,
1494            "parent": { "$ref": parent },
1495            "children": [],
1496            "content_layer": "body",
1497            "label": "code",
1498            "prov": prov,
1499            // With code enrichment, `text` is the model's rewrite while `orig`
1500            // keeps the raw extraction; otherwise both are the same string.
1501            "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
1502            "text": raw,
1503            "captions": [],
1504            "references": [],
1505            "footnotes": [],
1506            "code_language": code_language(language),
1507        }));
1508        self_ref
1509    }
1510
1511    /// Build a list group from a run of (possibly multi-level) list items. A
1512    /// deeper level starts a nested list under the preceding item.
1513    fn add_list(&mut self, items: &[Node], parent: &str) -> String {
1514        let self_ref = format!("#/groups/{}", self.groups.len());
1515        // reserve the slot so nested groups get later indices
1516        self.groups.push(Value::Null);
1517        let base = level_of(&items[0]);
1518        let mut children = Vec::new();
1519        let mut i = 0;
1520        while i < items.len() {
1521            // Empty paragraphs absorbed into the run (blank lines between items)
1522            // are not list items — skip them.
1523            if !matches!(items[i], Node::ListItem { .. }) {
1524                i += 1;
1525                continue;
1526            }
1527            let lvl = level_of(&items[i]);
1528            if lvl > base {
1529                // shouldn't happen at the head; skip defensively
1530                i += 1;
1531                continue;
1532            }
1533            let item_ref = self.add_list_item(&items[i], &self_ref);
1534            // collect any deeper items that nest under this one
1535            let mut j = i + 1;
1536            while j < items.len() && level_of(&items[j]) > base {
1537                j += 1;
1538            }
1539            if j > i + 1 {
1540                let mut nested = Vec::new();
1541                self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
1542                // the nested list group(s) are children of this item
1543                if let Some(idx) = ref_index(&item_ref) {
1544                    self.texts[idx]["children"]
1545                        .as_array_mut()
1546                        .unwrap()
1547                        .extend(nested);
1548                }
1549            }
1550            children.push(json!({ "$ref": item_ref }));
1551            i = j;
1552        }
1553        self.groups[group_index(&self_ref)] = json!({
1554            "self_ref": self_ref,
1555            "parent": { "$ref": parent },
1556            "children": children,
1557            "content_layer": "body",
1558            "name": "list",
1559            "label": "list",
1560        });
1561        self_ref
1562    }
1563
1564    fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
1565        let Node::ListItem {
1566            ordered,
1567            number,
1568            text,
1569            location,
1570            ..
1571        } = node
1572        else {
1573            unreachable!()
1574        };
1575        self.adopt_loc(*location);
1576        let self_ref = format!("#/texts/{}", self.texts.len());
1577        let raw = unescape_text(text);
1578        let prov = self.take_prov(raw.chars().count());
1579        let marker = if *ordered {
1580            format!("{number}.")
1581        } else {
1582            "-".to_string()
1583        };
1584        self.texts.push(json!({
1585            "self_ref": self_ref,
1586            "parent": { "$ref": parent },
1587            "children": [],
1588            "content_layer": "body",
1589            "label": "list_item",
1590            "prov": prov,
1591            "orig": raw,
1592            "text": raw,
1593            "enumerated": ordered,
1594            "marker": marker,
1595        }));
1596        self_ref
1597    }
1598
1599    fn add_table(&mut self, t: &Table, parent: &str) -> String {
1600        self.add_table_with(t, parent, false)
1601    }
1602
1603    /// [`Self::add_table`]; `raw` cell text is written verbatim (see
1604    /// [`table_data_with`]).
1605    fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
1606        let self_ref = format!("#/tables/{}", self.tables.len());
1607        self.adopt_loc(t.location);
1608        let prov = self.take_prov(0);
1609        // The caption is a separate text item the table references (docling's
1610        // `TableItem.captions`), added before the grid so its box isn't
1611        // inherited by a later item.
1612        let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
1613            Some(cap) => self.add_caption(cap, json!({}), &self_ref, parent, t.caption_parent),
1614            None => (Vec::new(), Vec::new()),
1615        };
1616        let data = table_data_with(t, raw);
1617        self.tables.push(json!({
1618            "self_ref": self_ref,
1619            "parent": { "$ref": parent },
1620            "children": children,
1621            "content_layer": "body",
1622            "label": "table",
1623            "prov": prov,
1624            "captions": captions,
1625            "references": [],
1626            "footnotes": [],
1627            "data": data,
1628            "annotations": [],
1629        }));
1630        self_ref
1631    }
1632
1633    /// Add a picture's or table's caption text item where `choice` says it
1634    /// hangs (#390), returning the `captions` entry for the item and the
1635    /// item's own `children` (the caption, when it is the item's child).
1636    /// The caption never consumes the item's pending provenance — the item
1637    /// takes its box first.
1638    fn add_caption(
1639        &mut self,
1640        text: &str,
1641        extra: Value,
1642        self_ref: &str,
1643        parent: &str,
1644        choice: CaptionParent,
1645    ) -> (Vec<Value>, Vec<Value>) {
1646        // docling's PDF pipeline parents the caption to the item; every
1647        // declarative backend leaves `add_text`'s default — the body — even
1648        // for an item inside a group; the office backends and HTML's
1649        // `<figure>` hang it off the item's container.
1650        let cap_parent = match choice {
1651            CaptionParent::Item => self_ref,
1652            CaptionParent::Container | CaptionParent::ContainerAfter => parent,
1653            CaptionParent::Body => "#/body",
1654        };
1655        let cap_ref = json!({ "$ref": self.add_text("caption", text, cap_parent, extra) });
1656        match choice {
1657            CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
1658            // Created ahead of the item, so it precedes the item in the
1659            // container's children — and, on the body, in the body's.
1660            CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
1661            CaptionParent::Body if parent == "#/body" => {
1662                self.pending_siblings.push(cap_ref.clone())
1663            }
1664            CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
1665            // The item sits deeper: the body's children get the caption after
1666            // the top-level item under walk, where docling appended it.
1667            CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
1668        }
1669        (vec![cap_ref], Vec::new())
1670    }
1671
1672    /// `meta` is the picture's docling `PictureMeta` (a classifier's
1673    /// predictions, a chart's kind and data), `None` for a plain picture.
1674    fn add_picture(
1675        &mut self,
1676        caption: Option<&str>,
1677        caption_href: Option<&str>,
1678        image: Option<&crate::PictureImage>,
1679        meta: Option<Value>,
1680        parent: &str,
1681        caption_parent: CaptionParent,
1682    ) -> String {
1683        let self_ref = format!("#/pictures/{}", self.pictures.len());
1684        // Take the picture's own provenance before the caption text is added —
1685        // the caption is a separate item and must not inherit the crop's box.
1686        let prov = self.take_prov(0);
1687        let (captions, children) = match caption.filter(|c| !c.is_empty()) {
1688            Some(cap) => {
1689                // Emit the caption as a text item that the picture references. A
1690                // wrapping `<a href>`'s link rides as docling's `hyperlink` field
1691                // on the caption item (#328).
1692                let extra = match caption_href {
1693                    Some(href) => json!({ "hyperlink": href }),
1694                    None => json!({}),
1695                };
1696                self.add_caption(cap, extra, &self_ref, parent, caption_parent)
1697            }
1698            None => (Vec::new(), Vec::new()),
1699        };
1700        self.push_picture(prov, captions, children, image, meta, parent)
1701    }
1702
1703    /// Append the picture item itself — `prov`, `captions` and `children`
1704    /// (a PDF caption is the picture's child) already settled.
1705    fn push_picture(
1706        &mut self,
1707        prov: Value,
1708        captions: Vec<Value>,
1709        children: Vec<Value>,
1710        image: Option<&crate::PictureImage>,
1711        meta: Option<Value>,
1712        parent: &str,
1713    ) -> String {
1714        let self_ref = format!("#/pictures/{}", self.pictures.len());
1715        // The legacy `classification` annotation rides along with a
1716        // classifier's `meta` (see `classification_meta`); a chart's meta has
1717        // none, like docling's.
1718        let annotations = meta
1719            .as_ref()
1720            .and_then(|m| m.get("annotations").cloned())
1721            .unwrap_or_else(|| json!([]));
1722        let meta = meta.map(|mut m| {
1723            if let Some(obj) = m.as_object_mut() {
1724                obj.remove("annotations");
1725            }
1726            m
1727        });
1728        // `meta` sits between `content_layer` and `label` in docling's field
1729        // order (and `preserve_order` keeps ours byte-compatible), so the item
1730        // is built in one shot per shape rather than patched afterwards.
1731        let mut item = match meta {
1732            Some(meta) => json!({
1733                "self_ref": self_ref,
1734                "parent": { "$ref": parent },
1735                "children": children,
1736                "content_layer": "body",
1737                "meta": meta,
1738                "label": "picture",
1739                "prov": prov,
1740                "captions": captions,
1741                "references": [],
1742                "footnotes": [],
1743                "annotations": annotations,
1744            }),
1745            None => json!({
1746                "self_ref": self_ref,
1747                "parent": { "$ref": parent },
1748                "children": children,
1749                "content_layer": "body",
1750                "label": "picture",
1751                "prov": prov,
1752                "captions": captions,
1753                "references": [],
1754                "footnotes": [],
1755                "annotations": annotations,
1756            }),
1757        };
1758        // docling stores the extracted image as an `ImageRef` (data URI + size,
1759        // the size as floats) between `footnotes` and `annotations` — pydantic
1760        // field order, which `preserve_order` lets us reproduce by rebuilding
1761        // the tail.
1762        if let Some(img) = image {
1763            let image = json!({
1764                "mimetype": img.mimetype,
1765                "dpi": 72,
1766                "size": { "width": img.width as f64, "height": img.height as f64 },
1767                "uri": img.data_uri(),
1768            });
1769            if let Some(obj) = item.as_object_mut() {
1770                let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
1771                obj.insert("image".into(), image);
1772                obj.insert("annotations".into(), annotations);
1773            }
1774        }
1775        self.pictures.push(item);
1776        self_ref
1777    }
1778
1779    fn add_group(
1780        &mut self,
1781        label: &str,
1782        name: Option<&str>,
1783        layer: Option<ContentLayer>,
1784        nodes: &[Node],
1785        parent: &str,
1786    ) -> String {
1787        let self_ref = format!("#/groups/{}", self.groups.len());
1788        self.groups.push(Value::Null);
1789        // Everything the walk creates belongs to this group, so a non-body
1790        // layer (a hidden sheet) is stamped on the whole subtree afterwards —
1791        // docling puts the layer on the group *and* on every item under it.
1792        let mark = (
1793            self.texts.len(),
1794            self.tables.len(),
1795            self.pictures.len(),
1796            self.groups.len(),
1797        );
1798        let children = self.walk_into(nodes, &self_ref);
1799        let name = name.unwrap_or(if label == "inline" { "group" } else { label });
1800        let content_layer = layer.map_or("body", |l| l.value());
1801        self.groups[group_index(&self_ref)] = json!({
1802            "self_ref": self_ref,
1803            "parent": { "$ref": parent },
1804            "children": children,
1805            "content_layer": content_layer,
1806            "name": name,
1807            "label": label,
1808        });
1809        if layer.is_some() {
1810            let (t, tb, p, g) = mark;
1811            for item in self.texts[t..]
1812                .iter_mut()
1813                .chain(self.tables[tb..].iter_mut())
1814                .chain(self.pictures[p..].iter_mut())
1815                .chain(self.groups[g..].iter_mut())
1816            {
1817                if let Some(obj) = item.as_object_mut() {
1818                    obj.insert("content_layer".into(), json!(content_layer));
1819                }
1820            }
1821        }
1822        self_ref
1823    }
1824
1825    /// Walk a slice of sibling nodes, returning each child's `$ref`; runs of
1826    /// list items are folded into list groups (one per sibling list).
1827    fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Value> {
1828        // Siblings that all carry a creation rank (an XLSX sheet's items) are
1829        // *added* in that order — so `#/tables/N` and friends are numbered as
1830        // docling numbers them — while their refs keep the node order, which
1831        // is docling's position-sorted `children`.
1832        let seqs: Option<Vec<usize>> = nodes
1833            .iter()
1834            .map(|n| match n {
1835                Node::Prov { seq: Some(s), .. } => Some(*s),
1836                _ => None,
1837            })
1838            .collect();
1839        if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
1840            let mut order: Vec<usize> = (0..nodes.len()).collect();
1841            order.sort_by_key(|&i| seqs[i]);
1842            let mut slots: Vec<Vec<Value>> = vec![Vec::new(); nodes.len()];
1843            for i in order {
1844                if let Some(r) = self.add_node(&nodes[i], parent) {
1845                    slots[i].append(&mut self.pending_siblings);
1846                    slots[i].push(json!({ "$ref": r }));
1847                    slots[i].append(&mut self.pending_after);
1848                }
1849                if parent == "#/body" {
1850                    slots[i].append(&mut self.pending_body);
1851                }
1852            }
1853            return slots.into_iter().flatten().collect();
1854        }
1855        let mut children = Vec::new();
1856        let mut i = 0;
1857        while i < nodes.len() {
1858            if matches!(nodes[i], Node::ListItem { .. }) {
1859                let start = i;
1860                i += 1;
1861                loop {
1862                    match nodes.get(i) {
1863                        Some(Node::ListItem { .. }) => i += 1,
1864                        // Absorb an empty paragraph sitting between two list
1865                        // items (docling keeps the ListGroup contiguous).
1866                        Some(Node::Paragraph { text })
1867                            if text.is_empty()
1868                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
1869                        {
1870                            i += 1
1871                        }
1872                        _ => break,
1873                    }
1874                }
1875                self.add_sibling_lists(&nodes[start..i], parent, &mut children);
1876            } else {
1877                if let Some(r) = self.add_node(&nodes[i], parent) {
1878                    children.append(&mut self.pending_siblings);
1879                    children.push(json!({ "$ref": r }));
1880                    children.append(&mut self.pending_after);
1881                }
1882                i += 1;
1883            }
1884            // Body-parented captions of items deeper in the tree follow the
1885            // top-level item they were created under (#390).
1886            if parent == "#/body" {
1887                children.append(&mut self.pending_body);
1888            }
1889        }
1890        children
1891    }
1892
1893    /// A run of list items may hold several *sibling* lists; emit one list group
1894    /// per sibling. The boundary is the backend's `first_in_list` flag on a
1895    /// base-level item — the same rule as the Markdown serializer's blank line
1896    /// (#385; the kind-flip and number-gap guesses are gone).
1897    fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
1898        let base = level_of(&run[0]);
1899        let mut seg = 0;
1900        for k in 0..run.len() {
1901            let Node::ListItem {
1902                first_in_list,
1903                level,
1904                ..
1905            } = &run[k]
1906            else {
1907                continue;
1908            };
1909            if *level != base {
1910                continue; // nested item — handled inside add_list
1911            }
1912            if k > seg && *first_in_list {
1913                out.push(json!({ "$ref": self.add_list(&run[seg..k], parent) }));
1914                seg = k;
1915            }
1916        }
1917        out.push(json!({ "$ref": self.add_list(&run[seg..], parent) }));
1918    }
1919}
1920
1921fn level_of(node: &Node) -> u8 {
1922    match node {
1923        Node::ListItem { level, .. } => *level,
1924        _ => 0,
1925    }
1926}
1927
1928fn group_index(self_ref: &str) -> usize {
1929    self_ref.rsplit('/').next().unwrap().parse().unwrap()
1930}
1931
1932fn ref_index(self_ref: &str) -> Option<usize> {
1933    self_ref.rsplit('/').next()?.parse().ok()
1934}
1935
1936/// Merge the key/values of `extra` (an object) into `target` (an object).
1937fn merge(target: &mut Value, extra: Value) {
1938    if let (Some(t), Some(e)) = (target.as_object_mut(), extra.as_object()) {
1939        for (k, v) in e {
1940            t.insert(k.clone(), v.clone());
1941        }
1942    }
1943}
1944
1945/// Reverse [`crate`]'s Markdown text escaping (HTML entities + `\_`).
1946fn unescape_text(s: &str) -> String {
1947    s.replace("&lt;", "<")
1948        .replace("&gt;", ">")
1949        .replace("&amp;", "&")
1950        .replace("\\_", "_")
1951}
1952
1953/// 64-bit FNV-1a, a stand-in for docling's `binary_hash` (we lack the source bytes
1954/// at export time; the value only needs to be a stable u64).
1955fn fnv1a(s: &str) -> u64 {
1956    let mut h: u64 = 0xcbf29ce484222325;
1957    for b in s.bytes() {
1958        h ^= b as u64;
1959        h = h.wrapping_mul(0x100000001b3);
1960    }
1961    h
1962}
1963
1964#[cfg(test)]
1965mod tests {
1966    use crate::{
1967        CaptionParent, ContentLayer, DoclingDocument, ImageMode, Node, PictureImage, Table,
1968    };
1969    use serde_json::Value;
1970
1971    fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
1972        crate::TableCell {
1973            text: text.into(),
1974            bbox: None,
1975            start_row: row,
1976            start_col: col,
1977            row_span: 1,
1978            col_span,
1979            column_header: row == 0,
1980            row_header: false,
1981            row_section: false,
1982        }
1983    }
1984
1985    /// First-class cells past the rows: rectangular rows are the grid and
1986    /// clip them (docling's `TableData.grid` on USPTO's overrun replicas);
1987    /// ragged rows — an xlsx table compacted by `skip_empty_cells` (#271) —
1988    /// are no grid, so the cells' extent sizes it and the omitted positions
1989    /// come back as empty filler cells in `grid` only.
1990    #[test]
1991    fn ragged_rows_take_their_grid_from_first_class_cells() {
1992        let cells = vec![
1993            cell_at("h0", 0, 0, 1),
1994            cell_at("h2", 0, 2, 1),
1995            cell_at("wide", 1, 0, 3),
1996        ];
1997        let export = |rows: Vec<Vec<String>>| -> Value {
1998            let mut doc = DoclingDocument::new("t");
1999            doc.push(Node::Table(Table {
2000                rows,
2001                cells: Some(cells.clone()),
2002                ..Table::default()
2003            }));
2004            let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2005            v["tables"][0]["data"].clone()
2006        };
2007        // Compacted rows: 2 and 3 wide, the cells say the grid is 3 wide.
2008        let data = export(vec![
2009            vec!["h0".into(), "h2".into()],
2010            vec!["wide".into(), "wide".into(), "wide".into()],
2011        ]);
2012        assert_eq!(data["num_rows"], 2);
2013        assert_eq!(data["num_cols"], 3);
2014        assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
2015        let row0: Vec<&str> = data["grid"][0]
2016            .as_array()
2017            .unwrap()
2018            .iter()
2019            .map(|c| c["text"].as_str().unwrap())
2020            .collect();
2021        assert_eq!(row0, ["h0", "", "h2"]);
2022        assert_eq!(data["table_cells"][2]["col_span"], 3);
2023        // Rectangular rows narrower than the cells: the rows win, the cells
2024        // are clipped to them exactly as before.
2025        let data = export(vec![
2026            vec!["h0".into(), "h2".into()],
2027            vec!["wide".into(), "wide".into()],
2028        ]);
2029        assert_eq!(data["num_cols"], 2);
2030        assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
2031    }
2032
2033    fn doc_with_image() -> DoclingDocument {
2034        let mut doc = DoclingDocument::new("t");
2035        doc.push(Node::Picture {
2036            caption: Some("Fig 1".into()),
2037            caption_href: None,
2038            image: Some(PictureImage {
2039                mimetype: "image/png".into(),
2040                width: 4,
2041                height: 2,
2042                data: b"foobar".to_vec(),
2043            }),
2044            classification: None,
2045            caption_parent: Default::default(),
2046        });
2047        doc
2048    }
2049
2050    /// #402: a deck's speaker notes are content, and docling puts them in the
2051    /// JSON on the `notes` layer so a consumer reading only JSON can pick them
2052    /// out. Markdown still serializes the body layer alone, and page furniture
2053    /// stays out of the JSON, where docling does keep it.
2054    #[test]
2055    fn notes_layer_items_reach_the_json_but_furniture_does_not() {
2056        let mut doc = DoclingDocument::new("t");
2057        doc.push(Node::Heading {
2058            level: 1,
2059            text: "Slide One".into(),
2060        });
2061        doc.push(Node::Furniture {
2062            layer: ContentLayer::Notes,
2063            inner: Box::new(Node::Located {
2064                location: [0, 0, 0, 0],
2065                inner: Box::new(Node::Paragraph {
2066                    text: "Speaker note for slide 1.".into(),
2067                }),
2068            }),
2069        });
2070        doc.push(Node::Furniture {
2071            layer: ContentLayer::Furniture,
2072            inner: Box::new(Node::Paragraph {
2073                text: "page header".into(),
2074            }),
2075        });
2076
2077        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2078        let texts = v["texts"].as_array().unwrap();
2079        assert_eq!(
2080            texts
2081                .iter()
2082                .map(|t| (
2083                    t["label"].as_str().unwrap(),
2084                    t["content_layer"].as_str().unwrap(),
2085                    t["text"].as_str().unwrap()
2086                ))
2087                .collect::<Vec<_>>(),
2088            vec![
2089                ("title", "body", "Slide One"),
2090                ("text", "notes", "Speaker note for slide 1."),
2091            ],
2092            "the note is carried on its own layer; the furniture is not carried"
2093        );
2094        // The body layer is what Markdown serializes, so it does not change.
2095        assert_eq!(doc.export_to_markdown(), "# Slide One\n");
2096    }
2097
2098    /// #410: a backend that describes merged ranges only as continuation
2099    /// flags (xlsx `<mergeCell>`, docx `gridSpan`/`vMerge`) gets docling's
2100    /// one-`TableCell`-per-range JSON: the anchor's offsets and spans, the
2101    /// entry repeated across the grid positions it covers — not a 1×1 cell
2102    /// per position with the text copied into each.
2103    #[test]
2104    fn continuation_flags_become_spanning_cells() {
2105        let mut doc = DoclingDocument::new("t");
2106        // A1:C2 merged ("merged"), then a plain row underneath.
2107        let rows = vec![
2108            vec!["merged".to_string(), "merged".into(), "merged".into()],
2109            vec!["merged".to_string(), "merged".into(), "merged".into()],
2110            vec!["a".to_string(), "b".into(), "c".into()],
2111        ];
2112        doc.push(Node::Table(crate::Table {
2113            rows,
2114            location: None,
2115            structure: Some(crate::TableStructure {
2116                header_row: vec![true, false, false],
2117                col_continuation: vec![
2118                    vec![false, true, true],
2119                    vec![false, true, true],
2120                    vec![false, false, false],
2121                ],
2122                row_continuation: vec![
2123                    vec![false, false, false],
2124                    vec![true, true, true],
2125                    vec![false, false, false],
2126                ],
2127                row_header: Vec::new(),
2128                col_header: Vec::new(),
2129            }),
2130            cell_blocks: None,
2131            cells: None,
2132            caption: None,
2133            caption_parent: Default::default(),
2134        }));
2135        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2136        let data = &v["tables"][0]["data"];
2137        assert_eq!(data["num_rows"], 3);
2138        assert_eq!(data["num_cols"], 3);
2139        let cells = data["table_cells"].as_array().unwrap();
2140        assert_eq!(
2141            cells.len(),
2142            4,
2143            "one cell for the range, three for the plain row"
2144        );
2145        assert_eq!(
2146            cells[0],
2147            serde_json::json!({
2148                "row_span": 2, "col_span": 3,
2149                "start_row_offset_idx": 0, "end_row_offset_idx": 2,
2150                "start_col_offset_idx": 0, "end_col_offset_idx": 3,
2151                "text": "merged", "column_header": true, "row_header": false,
2152                "row_section": false, "fillable": false,
2153            })
2154        );
2155        assert_eq!(cells[1]["text"], "a");
2156        assert_eq!(cells[1]["row_span"], 1);
2157        assert_eq!(cells[1]["column_header"], false);
2158        // The grid repeats the range's entry at every position it covers.
2159        let grid = data["grid"].as_array().unwrap();
2160        assert_eq!(grid.len(), 3);
2161        for (r, row) in grid.iter().take(2).enumerate() {
2162            for (c, cell) in row.as_array().unwrap().iter().enumerate() {
2163                assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
2164            }
2165        }
2166        assert_eq!(grid[2][2]["text"], "c");
2167    }
2168
2169    /// A [`Node::Prov`] wrapper is docling's provenance verbatim — the exact
2170    /// box in a top-left origin, the backend's charspan — and the page marker
2171    /// before it sizes the page; a chart's caption becomes a sibling of the
2172    /// picture in the container, listed first, sharing the chart's box with
2173    /// a charspan over its text. That is the JSON shape of an XLSX sheet.
2174    #[test]
2175    fn exact_provenance_pages_and_chart_captions_follow_docling() {
2176        let mut doc = DoclingDocument::new("t");
2177        doc.push(Node::PageInfo {
2178            page_no: 1,
2179            width: 3.0,
2180            height: 4.0,
2181        });
2182        let table = crate::Table {
2183            rows: vec![vec!["a".to_string(), "b".into()]],
2184            ..Default::default()
2185        };
2186        doc.push(Node::Group {
2187            label: "sheet".into(),
2188            name: Some("Data".into()),
2189            layer: None,
2190            children: vec![
2191                // Node order is the position-sorted one; creation order (the
2192                // `seq`) had the chart first — so the chart is `#/pictures/0`
2193                // *and* its caption `#/texts/0`, while the table stays the
2194                // group's first child.
2195                Node::Prov {
2196                    page_no: 1,
2197                    bbox: [0.0, 0.0, 3.0, 4.0],
2198                    charspan: [0, 0],
2199                    seq: Some(1),
2200                    inner: Box::new(Node::Table(table.clone())),
2201                },
2202                Node::Prov {
2203                    page_no: 1,
2204                    bbox: [0.0, 1.0, 1.0, 1.0],
2205                    charspan: [0, 0],
2206                    seq: Some(0),
2207                    inner: Box::new(Node::Chart {
2208                        kind: "bar_chart".into(),
2209                        table,
2210                        caption: Some("Sales".into()),
2211                        location: Some([0, 128, 170, 128]),
2212                    }),
2213                },
2214            ],
2215        });
2216        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2217        assert_eq!(
2218            v["pages"],
2219            serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
2220        );
2221        assert_eq!(
2222            v["tables"][0]["prov"],
2223            serde_json::json!([{
2224                "page_no": 1,
2225                "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
2226                "charspan": [0, 0],
2227            }])
2228        );
2229        assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
2230        // The caption is the group's child *before* the picture, parented to
2231        // the group, and referenced by the picture.
2232        let sheet = &v["groups"][0];
2233        assert_eq!(
2234            sheet["children"],
2235            serde_json::json!([
2236                {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
2237            ])
2238        );
2239        let cap = &v["texts"][0];
2240        assert_eq!(cap["label"], "caption");
2241        assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
2242        assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
2243        assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
2244        let pic = &v["pictures"][0];
2245        assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
2246        assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
2247        assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
2248        assert_eq!(
2249            pic["meta"]["classification"]["predictions"][0]["class_name"],
2250            "bar_chart"
2251        );
2252        assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
2253    }
2254
2255    /// An all-zero location is the "no geometry" sentinel — a slide's speaker
2256    /// notes carry one — and docling writes it as a zero bbox, not as a box
2257    /// spanning the whole page, which is what denormalizing the grid gives.
2258    #[test]
2259    fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
2260        let mut doc = DoclingDocument::new("t");
2261        doc.push(Node::PageInfo {
2262            page_no: 1,
2263            width: 12192000.0,
2264            height: 6858000.0,
2265        });
2266        doc.push(Node::Furniture {
2267            layer: ContentLayer::Notes,
2268            inner: Box::new(Node::Located {
2269                location: [0, 0, 0, 0],
2270                inner: Box::new(Node::Paragraph {
2271                    text: "a note".into(),
2272                }),
2273            }),
2274        });
2275        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2276        let prov = &v["texts"][0]["prov"][0];
2277        assert_eq!(prov["page_no"], 1);
2278        assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
2279        assert_eq!(
2280            prov["bbox"],
2281            serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
2282        );
2283        // The page itself is recorded at its true size.
2284        assert_eq!(
2285            v["pages"]["1"]["size"],
2286            serde_json::json!({"width": 12192000.0, "height": 6858000.0})
2287        );
2288    }
2289
2290    /// #171: PageInfo markers become the `pages` map, and `Located` wrappers /
2291    /// node-level locations become per-item `prov` — the 0–511 grid
2292    /// denormalized against the page into BOTTOMLEFT points. Without markers
2293    /// (every declarative backend) the JSON stays exactly as before: empty
2294    /// `pages`, `prov: []` even for located nodes.
2295    #[test]
2296    fn page_markers_produce_pages_and_prov() {
2297        let mut doc = DoclingDocument::new("t");
2298        doc.push(Node::PageInfo {
2299            page_no: 1,
2300            width: 512.0,
2301            height: 1024.0,
2302        });
2303        doc.push(Node::Located {
2304            location: [128, 64, 256, 128], // quarter/eighth points of the grid
2305            inner: Box::new(Node::Paragraph {
2306                text: "hello".into(),
2307            }),
2308        });
2309        doc.push(Node::Table(Table {
2310            rows: vec![vec!["a".into()]],
2311            location: Some([0, 0, 512, 512]),
2312            ..Table::default()
2313        }));
2314        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2315        assert_eq!(v["pages"]["1"]["page_no"], 1);
2316        assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
2317        assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
2318        // 512-wide page: grid x scales 1:1; 1024-high: grid y doubles, then
2319        // flips to the BOTTOMLEFT origin (t from grid-top 64 → 1024-128=896).
2320        let prov = &v["texts"][0]["prov"][0];
2321        assert_eq!(prov["page_no"], 1);
2322        assert_eq!(prov["bbox"]["l"], 128.0);
2323        assert_eq!(prov["bbox"]["t"], 896.0);
2324        assert_eq!(prov["bbox"]["r"], 256.0);
2325        assert_eq!(prov["bbox"]["b"], 768.0);
2326        assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
2327        assert_eq!(prov["charspan"][1], 5);
2328        // The table adopts its own location field; charspan is [0, 0].
2329        let tprov = &v["tables"][0]["prov"][0];
2330        assert_eq!(tprov["bbox"]["t"], 1024.0);
2331        assert_eq!(tprov["bbox"]["b"], 0.0);
2332        assert_eq!(tprov["charspan"][1], 0);
2333
2334        // No markers → the pre-#171 shape, byte for byte.
2335        let mut plain = DoclingDocument::new("t");
2336        plain.push(Node::Located {
2337            location: [1, 2, 3, 4],
2338            inner: Box::new(Node::Paragraph { text: "x".into() }),
2339        });
2340        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
2341        assert_eq!(v["pages"], serde_json::json!({}));
2342        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
2343    }
2344
2345    /// PDF page headers/footers reach the JSON as docling writes them:
2346    /// body-parented text items on the furniture layer, with their box.
2347    #[test]
2348    fn page_furniture_becomes_furniture_layer_text() {
2349        let mut doc = DoclingDocument::new("t");
2350        doc.push(Node::PageInfo {
2351            page_no: 1,
2352            width: 512.0,
2353            height: 512.0,
2354        });
2355        doc.push(Node::PageFurniture {
2356            footer: false,
2357            location: [10, 0, 100, 20],
2358            text: "Chapter 1".into(),
2359        });
2360        doc.push(Node::Paragraph {
2361            text: "body".into(),
2362        });
2363        doc.push(Node::PageFurniture {
2364            footer: true,
2365            location: [400, 490, 500, 512],
2366            text: "1.10.2".into(),
2367        });
2368        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2369        let texts = v["texts"].as_array().unwrap();
2370        assert_eq!(texts.len(), 3);
2371        assert_eq!(texts[0]["label"], "page_header");
2372        assert_eq!(texts[0]["content_layer"], "furniture");
2373        assert_eq!(texts[0]["parent"]["$ref"], "#/body");
2374        assert_eq!(texts[0]["prov"][0]["bbox"]["l"], 10.0);
2375        assert_eq!(texts[1]["content_layer"], "body");
2376        assert_eq!(texts[1]["prov"], serde_json::json!([]));
2377        assert_eq!(texts[2]["label"], "page_footer");
2378        assert_eq!(texts[2]["text"], "1.10.2");
2379        assert_eq!(texts[2]["content_layer"], "furniture");
2380    }
2381
2382    #[test]
2383    fn picture_image_in_markdown_modes_and_json() {
2384        let doc = doc_with_image();
2385        // placeholder (default) ignores the image
2386        assert!(doc.export_to_markdown().contains("<!-- image -->"));
2387        // embedded → base64 data URI (b"foobar" → "Zm9vYmFy")
2388        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
2389        assert!(
2390            md.contains("![Image](data:image/png;base64,Zm9vYmFy)"),
2391            "got:\n{md}"
2392        );
2393        assert!(files.is_empty());
2394        // referenced → file link + collected bytes
2395        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
2396        assert!(
2397            md.contains("![Image](artifacts/image_000000.png)"),
2398            "got:\n{md}"
2399        );
2400        assert_eq!(
2401            files,
2402            vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
2403        );
2404        // JSON carries the ImageRef (data URI + size — floats, as docling's
2405        // `Size` is — placed before `annotations`).
2406        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2407        assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
2408        assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
2409        let keys: Vec<&str> = v["pictures"][0]
2410            .as_object()
2411            .unwrap()
2412            .keys()
2413            .map(String::as_str)
2414            .collect();
2415        assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
2416        assert_eq!(
2417            v["pictures"][0]["image"]["uri"],
2418            "data:image/png;base64,Zm9vYmFy"
2419        );
2420    }
2421
2422    #[test]
2423    fn exports_docling_schema() {
2424        let mut doc = DoclingDocument::new("t");
2425        doc.push(Node::Heading {
2426            level: 1,
2427            text: "Title".into(),
2428        });
2429        doc.push(Node::Heading {
2430            level: 2,
2431            text: "Sec".into(),
2432        });
2433        doc.push(Node::Paragraph {
2434            text: "Body &amp; more".into(),
2435        }); // markdown-escaped
2436        doc.push(Node::ListItem {
2437            ordered: false,
2438            number: 0,
2439            first_in_list: true,
2440            text: "one".into(),
2441            level: 0,
2442            marker: None,
2443            location: None,
2444            dclx: None,
2445            href: None,
2446            layer: None,
2447        });
2448        doc.push(Node::ListItem {
2449            ordered: false,
2450            number: 0,
2451            first_in_list: false,
2452            text: "two".into(),
2453            level: 0,
2454            marker: None,
2455            location: None,
2456            dclx: None,
2457            href: None,
2458            layer: None,
2459        });
2460        doc.push(Node::Table(Table {
2461            rows: vec![vec!["A".into(), "B".into()]],
2462            location: None,
2463            structure: None,
2464            cell_blocks: None,
2465            cells: None,
2466            caption: None,
2467            caption_parent: Default::default(),
2468        }));
2469
2470        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2471        assert_eq!(v["schema_name"], "DoclingDocument");
2472        assert_eq!(v["version"], "1.10.0");
2473        assert_eq!(v["texts"][0]["label"], "title");
2474        assert_eq!(v["texts"][1]["label"], "section_header");
2475        assert_eq!(v["texts"][1]["level"], 1); // heading level 2 → docling level 1
2476        assert_eq!(v["texts"][2]["text"], "Body & more"); // un-escaped for the wire format
2477                                                          // consecutive list items fold into one list group, parented to it
2478        assert_eq!(v["groups"][0]["label"], "list");
2479        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
2480        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
2481        assert_eq!(v["texts"][3]["marker"], "-");
2482        // table grid + header flag
2483        assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
2484        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
2485    }
2486    /// A named group on a non-body layer — docling's hidden spreadsheet sheet:
2487    /// the group carries the sheet's name and the `invisible` layer, and every
2488    /// item inside it carries the layer too.
2489    #[test]
2490    fn a_layered_group_stamps_its_whole_subtree() {
2491        let doc = DoclingDocument {
2492            name: "s".into(),
2493            nodes: vec![
2494                Node::Group {
2495                    label: "sheet".into(),
2496                    name: Some("Sheet1".into()),
2497                    layer: None,
2498                    children: vec![Node::Paragraph {
2499                        text: "visible".into(),
2500                    }],
2501                },
2502                Node::Group {
2503                    label: "sheet".into(),
2504                    name: Some("Sheet2".into()),
2505                    layer: Some(ContentLayer::Invisible),
2506                    children: vec![Node::Paragraph {
2507                        text: "hidden".into(),
2508                    }],
2509                },
2510            ],
2511            ..DoclingDocument::new("s")
2512        };
2513        let v = crate::json::to_json(&doc);
2514        assert_eq!(v["groups"][0]["label"], "sheet");
2515        assert_eq!(v["groups"][0]["name"], "Sheet1");
2516        assert_eq!(v["groups"][0]["content_layer"], "body");
2517        assert_eq!(v["texts"][0]["content_layer"], "body");
2518        assert_eq!(v["groups"][1]["name"], "Sheet2");
2519        assert_eq!(v["groups"][1]["content_layer"], "invisible");
2520        assert_eq!(v["texts"][1]["content_layer"], "invisible");
2521        // The group's children are the items, and the body holds the groups.
2522        assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
2523        assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
2524    }
2525
2526    /// A backend-built item tree is serialized as it is: items numbered in
2527    /// creation order per bucket (a field region's part texts included), the
2528    /// tree's parents / children / layers, docling's field order for
2529    /// `formatting`, `hyperlink`, `level`, `enumerated`/`marker`, a rich
2530    /// cell's `ref` on `table_cells` only, raw cell text.
2531    /// The DOCX tree's extras: an item `delete`d (docling's `delete_items`,
2532    /// the spacer between two items of a resumed list) is neither written nor
2533    /// numbered, `comments` back-refs sit between `prov` and `orig`, and a
2534    /// chart picture carries `classification` plus `tabular_chart`.
2535    #[test]
2536    fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
2537        use crate::tree::{ItemTree, TreeKind};
2538        let mut t = ItemTree::default();
2539        let text = |txt: &str| TreeKind::Text {
2540            label: "text".into(),
2541            text: txt.into(),
2542            orig: None,
2543            formatting: None,
2544            hyperlink: None,
2545            level: None,
2546            list: None,
2547        };
2548        let a = t.add(None, None, text("a"));
2549        let blank = t.add(None, None, text(""));
2550        let b = t.add(None, None, text("b"));
2551        t.delete(blank);
2552        let group = t.add(
2553            None,
2554            Some(ContentLayer::Notes),
2555            TreeKind::Group {
2556                label: "comment_section".into(),
2557                name: "comment-0".into(),
2558            },
2559        );
2560        t.add(Some(group), Some(ContentLayer::Notes), text("note"));
2561        t.items[a].comments.push(group);
2562        t.add(
2563            None,
2564            None,
2565            TreeKind::Picture {
2566                captions: Vec::new(),
2567                image: None,
2568                classification: Some("bar_chart".into()),
2569                confidence: None,
2570                chart: Some(Table {
2571                    rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
2572                    ..Table::default()
2573                }),
2574                dpi: None,
2575            },
2576        );
2577        assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
2578        assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
2579        let mut doc = DoclingDocument::new("t");
2580        doc.tree = Some(t);
2581        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2582        let texts = v["texts"].as_array().unwrap();
2583        assert_eq!(texts.len(), 3);
2584        assert_eq!(texts[1]["text"], "b");
2585        assert_eq!(texts[1]["self_ref"], "#/texts/1");
2586        assert_eq!(
2587            v["body"]["children"],
2588            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
2589        );
2590        let keys: Vec<&str> = texts[0]
2591            .as_object()
2592            .unwrap()
2593            .keys()
2594            .map(String::as_str)
2595            .collect();
2596        assert_eq!(
2597            keys,
2598            vec![
2599                "self_ref",
2600                "parent",
2601                "children",
2602                "content_layer",
2603                "label",
2604                "prov",
2605                "comments",
2606                "orig",
2607                "text"
2608            ]
2609        );
2610        assert_eq!(
2611            texts[0]["comments"],
2612            serde_json::json!([{"$ref": "#/groups/0"}])
2613        );
2614        assert!(texts[1].get("comments").is_none());
2615        let meta = &v["pictures"][0]["meta"];
2616        assert_eq!(
2617            meta["classification"]["predictions"][0]["class_name"],
2618            "bar_chart"
2619        );
2620        assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
2621    }
2622
2623    /// A tree item's `TreeProv` is written verbatim — a raw EMU box with
2624    /// whatever origin tag the backend set (`BOTTOMLEFT` here) and a per-item
2625    /// charspan, a note's zero `TOPLEFT` box — a picture's `image.dpi` is the file's when the backend
2626    /// read one, an item without provenance writes `prov: []`, and the page
2627    /// map still comes from the flat stream's markers.
2628    #[test]
2629    fn tree_items_carry_exact_provenance_and_dpi() {
2630        use crate::tree::{ItemTree, TreeKind, TreeProv};
2631        let text = |label: &str, t: &str| TreeKind::Text {
2632            label: label.into(),
2633            text: t.into(),
2634            orig: None,
2635            formatting: None,
2636            hyperlink: None,
2637            level: None,
2638            list: None,
2639        };
2640        let mut t = ItemTree::default();
2641        let slide = t.add(
2642            None,
2643            None,
2644            TreeKind::Group {
2645                label: "chapter".into(),
2646                name: "slide-0".into(),
2647            },
2648        );
2649        t.add_with_prov(
2650            Some(slide),
2651            None,
2652            text("paragraph", "héllo"),
2653            TreeProv {
2654                page_no: 1,
2655                bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
2656                bottom_left: true,
2657                charspan: [0, 5],
2658            },
2659        );
2660        t.add_with_prov(
2661            Some(slide),
2662            None,
2663            TreeKind::Picture {
2664                captions: Vec::new(),
2665                image: Some(crate::PictureImage {
2666                    mimetype: "image/png".into(),
2667                    width: 2,
2668                    height: 2,
2669                    data: vec![0],
2670                }),
2671                classification: None,
2672                confidence: None,
2673                chart: None,
2674                dpi: Some(300),
2675            },
2676            TreeProv {
2677                page_no: 1,
2678                bbox: [0.0; 4],
2679                bottom_left: false,
2680                charspan: [0, 0],
2681            },
2682        );
2683        t.add(
2684            Some(slide),
2685            Some(ContentLayer::Notes),
2686            text("text", "no geometry"),
2687        );
2688        let mut doc = DoclingDocument::new("t");
2689        doc.push(Node::PageInfo {
2690            page_no: 1,
2691            width: 9144000.0,
2692            height: 6858000.0,
2693        });
2694        doc.tree = Some(t);
2695        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2696        assert_eq!(
2697            v["texts"][0]["prov"],
2698            serde_json::json!([{
2699                "page_no": 1,
2700                "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
2701                "charspan": [0, 5],
2702            }])
2703        );
2704        assert_eq!(v["texts"][0]["label"], "paragraph");
2705        assert_eq!(
2706            v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
2707            "TOPLEFT"
2708        );
2709        assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
2710        assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
2711        assert_eq!(v["texts"][1]["content_layer"], "notes");
2712        assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
2713        assert_eq!(v["pages"]["1"]["page_no"], 1);
2714    }
2715
2716    /// docling-core's `validate_document` clamps every provenance box (and a
2717    /// one-page table's cell boxes) into its page — the state every
2718    /// `ConversionResult` leaves a document in, so the state docling's JSON
2719    /// shows. A box on a page the document does not describe is left alone.
2720    #[test]
2721    fn provenance_boxes_are_clamped_to_their_page() {
2722        let mut doc = DoclingDocument::new("t");
2723        doc.push(Node::PageInfo {
2724            page_no: 1,
2725            width: 10.0,
2726            height: 8.0,
2727        });
2728        doc.push(Node::Prov {
2729            page_no: 1,
2730            bbox: [-1.0, 2.0, 12.0, 9.5],
2731            charspan: [0, 1],
2732            seq: None,
2733            inner: Box::new(Node::Paragraph { text: "x".into() }),
2734        });
2735        let mut table = Table {
2736            rows: vec![vec!["a".into()]],
2737            ..Table::default()
2738        };
2739        table.cells = Some(vec![crate::TableCell {
2740            text: "a".into(),
2741            bbox: Some([1.0, 1.0, 11.0, 9.0]),
2742            start_row: 0,
2743            start_col: 0,
2744            row_span: 1,
2745            col_span: 1,
2746            column_header: false,
2747            row_header: false,
2748            row_section: false,
2749        }]);
2750        doc.push(Node::Prov {
2751            page_no: 1,
2752            bbox: [0.0, 0.0, 10.0, 8.0],
2753            charspan: [0, 0],
2754            seq: None,
2755            inner: Box::new(Node::Table(table)),
2756        });
2757        doc.push(Node::Prov {
2758            page_no: 7,
2759            bbox: [-5.0, 0.0, 50.0, 50.0],
2760            charspan: [0, 1],
2761            seq: None,
2762            inner: Box::new(Node::Paragraph { text: "y".into() }),
2763        });
2764        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2765        assert_eq!(
2766            v["texts"][0]["prov"][0]["bbox"],
2767            serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
2768        );
2769        let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
2770        assert_eq!(
2771            (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
2772            (Some(1.0), Some(10.0), Some(8.0))
2773        );
2774        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
2775        assert_eq!(
2776            v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
2777            "page 7 is not described"
2778        );
2779    }
2780
2781    #[test]
2782    fn a_backend_item_tree_is_written_verbatim() {
2783        use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
2784        let mut t = ItemTree::default();
2785        let text = |label: &str, txt: &str| TreeKind::Text {
2786            label: label.into(),
2787            text: txt.into(),
2788            orig: None,
2789            formatting: None,
2790            hyperlink: None,
2791            level: None,
2792            list: None,
2793        };
2794        let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
2795        let h = t.add(None, None, text("title", "Heading"));
2796        let group = t.add(
2797            Some(h),
2798            None,
2799            TreeKind::Group {
2800                label: "inline".into(),
2801                name: "group".into(),
2802            },
2803        );
2804        t.add(
2805            Some(group),
2806            None,
2807            TreeKind::Text {
2808                label: "text".into(),
2809                text: "bold".into(),
2810                orig: None,
2811                formatting: Some(Formatting {
2812                    bold: true,
2813                    ..Formatting::default()
2814                }),
2815                hyperlink: Some("https://example.com/".into()),
2816                level: None,
2817                list: None,
2818            },
2819        );
2820        t.add(
2821            Some(group),
2822            None,
2823            TreeKind::Code {
2824                text: "x = 1".into(),
2825                orig: None,
2826                language: Some("python".into()),
2827                formatting: None,
2828                hyperlink: None,
2829            },
2830        );
2831        let sub = t.add(
2832            Some(h),
2833            None,
2834            TreeKind::Text {
2835                label: "section_header".into(),
2836                text: "Sub".into(),
2837                orig: Some("Sub\u{2019}".into()),
2838                formatting: None,
2839                hyperlink: None,
2840                level: Some(1),
2841                list: None,
2842            },
2843        );
2844        t.add(
2845            Some(sub),
2846            None,
2847            TreeKind::Text {
2848                label: "list_item".into(),
2849                text: "item".into(),
2850                orig: None,
2851                formatting: None,
2852                hyperlink: None,
2853                level: None,
2854                list: Some(ListMeta {
2855                    enumerated: true,
2856                    marker: "3.".into(),
2857                }),
2858            },
2859        );
2860        let _region = t.add(
2861            Some(sub),
2862            None,
2863            TreeKind::FieldRegion {
2864                items: vec![crate::FieldItem {
2865                    marker: None,
2866                    key: Some("Name".into()),
2867                    value: Some("Duck".into()),
2868                    value_kind: Some("read_only".into()),
2869                }],
2870            },
2871        );
2872        let table = t.add(
2873            Some(sub),
2874            None,
2875            TreeKind::Table {
2876                table: Table {
2877                    rows: vec![vec!["a  \n&lt;".into(), "b".into()]],
2878                    cells: Some(vec![
2879                        crate::TableCell {
2880                            text: "a  \n&lt;".into(),
2881                            bbox: None,
2882                            start_row: 0,
2883                            start_col: 0,
2884                            row_span: 3,
2885                            col_span: 1,
2886                            column_header: false,
2887                            row_header: true,
2888                            row_section: false,
2889                        },
2890                        crate::TableCell {
2891                            text: "b".into(),
2892                            bbox: None,
2893                            start_row: 0,
2894                            start_col: 1,
2895                            row_span: 1,
2896                            col_span: 1,
2897                            column_header: false,
2898                            row_header: false,
2899                            row_section: false,
2900                        },
2901                    ]),
2902                    ..Table::default()
2903                },
2904                rich_cells: vec![(0, 1, 0)], // patched below
2905                captions: Vec::new(),
2906            },
2907        );
2908        let cell_group = t.add(
2909            Some(table),
2910            None,
2911            TreeKind::Group {
2912                label: "unspecified".into(),
2913                name: "rich_cell_group_1_0_0".into(),
2914            },
2915        );
2916        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
2917            *rich_cells = vec![(0, 1, cell_group)];
2918        }
2919        let after = t.add(Some(sub), None, text("text", "after the region"));
2920        let _ = (title, after);
2921
2922        let doc = DoclingDocument {
2923            tree: Some(t),
2924            ..DoclingDocument::new("t")
2925        };
2926        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2927        // Creation order: Page, Heading, bold, x = 1, Sub, item, [Name, Duck], after.
2928        let texts: Vec<&str> = v["texts"]
2929            .as_array()
2930            .unwrap()
2931            .iter()
2932            .map(|t| t["text"].as_str().unwrap())
2933            .collect();
2934        assert_eq!(
2935            texts,
2936            [
2937                "Page",
2938                "Heading",
2939                "bold",
2940                "x = 1",
2941                "Sub",
2942                "item",
2943                "Name",
2944                "Duck",
2945                "after the region"
2946            ]
2947        );
2948        assert_eq!(
2949            v["body"]["children"],
2950            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
2951        );
2952        assert_eq!(v["texts"][0]["content_layer"], "furniture");
2953        assert_eq!(
2954            v["texts"][1]["children"],
2955            serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
2956        );
2957        let bold = &v["texts"][2];
2958        assert_eq!(bold["parent"]["$ref"], "#/groups/0");
2959        let keys: Vec<&str> = bold
2960            .as_object()
2961            .unwrap()
2962            .keys()
2963            .map(String::as_str)
2964            .collect();
2965        assert_eq!(
2966            keys,
2967            [
2968                "self_ref",
2969                "parent",
2970                "children",
2971                "content_layer",
2972                "label",
2973                "prov",
2974                "orig",
2975                "text",
2976                "formatting",
2977                "hyperlink"
2978            ]
2979        );
2980        assert_eq!(
2981            bold["formatting"],
2982            serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
2983        );
2984        let code = &v["texts"][3];
2985        assert_eq!(code["label"], "code");
2986        assert_eq!(code["code_language"], "Python");
2987        let sub = &v["texts"][4];
2988        assert_eq!(sub["orig"], "Sub\u{2019}");
2989        assert_eq!(sub["level"], 1);
2990        let item = &v["texts"][5];
2991        let keys: Vec<&str> = item
2992            .as_object()
2993            .unwrap()
2994            .keys()
2995            .map(String::as_str)
2996            .collect();
2997        assert_eq!(
2998            keys,
2999            [
3000                "self_ref",
3001                "parent",
3002                "children",
3003                "content_layer",
3004                "label",
3005                "prov",
3006                "orig",
3007                "text",
3008                "enumerated",
3009                "marker"
3010            ]
3011        );
3012        assert_eq!(item["marker"], "3.");
3013        assert_eq!(v["texts"][7]["kind"], "read_only");
3014        assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
3015        let table = &v["tables"][0];
3016        assert_eq!(
3017            table["children"],
3018            serde_json::json!([{"$ref": "#/groups/1"}])
3019        );
3020        let cells = table["data"]["table_cells"].as_array().unwrap();
3021        assert_eq!(
3022            cells[0]["text"], "a  \n&lt;",
3023            "raw cell text is written verbatim"
3024        );
3025        assert_eq!(
3026            cells[0]["end_row_offset_idx"], 3,
3027            "declared spans are not clamped"
3028        );
3029        assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
3030        assert!(cells[0].get("ref").is_none());
3031        assert!(
3032            table["data"]["grid"][0][1].get("ref").is_none(),
3033            "the grid shows plain cells"
3034        );
3035        assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
3036    }
3037
3038    /// A comment section that links its note text rather than its group — the
3039    /// spreadsheet shape, where docling-core's `add_comment` appends the text
3040    /// item's ref to each target.
3041    #[test]
3042    fn a_comment_section_can_be_referenced_by_its_note_text() {
3043        let doc = DoclingDocument {
3044            name: "c".into(),
3045            nodes: vec![
3046                Node::Commented {
3047                    comments: vec![0],
3048                    inner: Box::new(Node::Paragraph {
3049                        text: "annotated".into(),
3050                    }),
3051                },
3052                Node::CommentSection {
3053                    name: "comment-Sheet1-A1".into(),
3054                    text: "[author: A]: note".into(),
3055                    refs_note_text: true,
3056                    grouped: true,
3057                },
3058            ],
3059            ..DoclingDocument::new("c")
3060        };
3061        let v = crate::json::to_json(&doc);
3062        assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
3063        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
3064    }
3065
3066    /// docx reviewer comments: a `comment_section` group on the notes layer
3067    /// holding the note text, and a `comments` back-ref on the annotated item —
3068    /// keyed between `prov` and `orig`, the slot docling emits it in.
3069    #[test]
3070    fn comment_sections_link_back_to_their_items() {
3071        let doc = DoclingDocument {
3072            name: "c".into(),
3073            nodes: vec![
3074                Node::Commented {
3075                    comments: vec![0],
3076                    inner: Box::new(Node::Paragraph {
3077                        text: "annotated".into(),
3078                    }),
3079                },
3080                Node::Paragraph {
3081                    text: "plain".into(),
3082                },
3083                Node::CommentSection {
3084                    name: "comment-7".into(),
3085                    text: "[time: t]: note".into(),
3086                    refs_note_text: false,
3087                    grouped: true,
3088                },
3089            ],
3090            ..DoclingDocument::new("c")
3091        };
3092        let v = crate::json::to_json(&doc);
3093        // The group is the comment section; its only child is the notes text.
3094        assert_eq!(v["groups"][0]["label"], "comment_section");
3095        assert_eq!(v["groups"][0]["name"], "comment-7");
3096        assert_eq!(v["groups"][0]["content_layer"], "notes");
3097        assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
3098        assert_eq!(v["texts"][2]["content_layer"], "notes");
3099        // The annotated item points back at the group; the plain one has no key.
3100        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
3101        assert!(v["texts"][1].get("comments").is_none());
3102        // docling's key order: … prov, comments, orig, text.
3103        let keys: Vec<&str> = v["texts"][0]
3104            .as_object()
3105            .unwrap()
3106            .keys()
3107            .map(String::as_str)
3108            .collect();
3109        assert_eq!(
3110            &keys[keys.len() - 4..],
3111            &["prov", "comments", "orig", "text"]
3112        );
3113    }
3114
3115    fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
3116        Node::Picture {
3117            caption: Some(caption.into()),
3118            caption_href: None,
3119            image: None,
3120            classification: None,
3121            caption_parent,
3122        }
3123    }
3124
3125    fn group(children: Vec<Node>) -> Node {
3126        Node::Group {
3127            label: "section".into(),
3128            name: None,
3129            layer: None,
3130            children,
3131        }
3132    }
3133
3134    fn refs(v: &Value) -> Vec<&str> {
3135        v.as_array()
3136            .unwrap()
3137            .iter()
3138            .map(|r| r["$ref"].as_str().unwrap())
3139            .collect()
3140    }
3141
3142    /// #390: a declarative backend's caption is docling's `add_text` default —
3143    /// a body child, appended as it is created — wherever the picture sits:
3144    /// ahead of a top-level picture, behind the top-level item enclosing a
3145    /// nested one. The picture references it either way and has no children.
3146    #[test]
3147    fn a_body_caption_follows_the_enclosing_top_level_item() {
3148        let mut doc = DoclingDocument::new("t");
3149        doc.push(picture("top", CaptionParent::Body));
3150        doc.push(group(vec![
3151            Node::Paragraph { text: "p".into() },
3152            picture("nested", CaptionParent::Body),
3153        ]));
3154        doc.push(Node::Paragraph {
3155            text: "after".into(),
3156        });
3157        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3158        assert_eq!(
3159            refs(&v["body"]["children"]),
3160            [
3161                "#/texts/0",
3162                "#/pictures/0",
3163                "#/groups/0",
3164                "#/texts/2",
3165                "#/texts/3"
3166            ]
3167        );
3168        assert_eq!(
3169            refs(&v["groups"][0]["children"]),
3170            ["#/texts/1", "#/pictures/1"]
3171        );
3172        for (cap, pic) in [(0, 0), (2, 1)] {
3173            assert_eq!(v["texts"][cap]["label"], "caption");
3174            assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
3175            assert_eq!(
3176                refs(&v["pictures"][pic]["captions"]),
3177                [format!("#/texts/{cap}")]
3178            );
3179            assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
3180        }
3181    }
3182
3183    /// The PDF pipeline's caption is the picture's (or table's) own child,
3184    /// as docling attaches a layout caption.
3185    #[test]
3186    fn an_item_caption_is_the_items_first_child() {
3187        let mut doc = DoclingDocument::new("t");
3188        doc.push(picture("fig", CaptionParent::Item));
3189        doc.push(Node::Table(Table {
3190            rows: vec![vec!["a".into()]],
3191            caption: Some("tab".into()),
3192            caption_parent: CaptionParent::Item,
3193            ..Table::default()
3194        }));
3195        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3196        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
3197        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
3198        assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
3199        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3200        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
3201        assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
3202        assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
3203    }
3204
3205    /// A container caption sits beside its item under the item's parent —
3206    /// ahead of it (an office chart's title) or behind it (an HTML
3207    /// `<figure>`'s table, whose figcaption docling adds after the table).
3208    #[test]
3209    fn a_container_caption_is_the_items_sibling() {
3210        let mut doc = DoclingDocument::new("t");
3211        doc.push(group(vec![
3212            picture("chart", CaptionParent::Container),
3213            Node::Table(Table {
3214                rows: vec![vec!["a".into()]],
3215                caption: Some("figcaption".into()),
3216                caption_parent: CaptionParent::ContainerAfter,
3217                ..Table::default()
3218            }),
3219        ]));
3220        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3221        assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
3222        assert_eq!(
3223            refs(&v["groups"][0]["children"]),
3224            ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
3225        );
3226        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
3227        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
3228        assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
3229        assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
3230    }
3231}