docling_core/tree.rs
1//! docling's **item tree**, for a backend that knows the exact shape upstream
2//! gives a document and wants the JSON export to reproduce it.
3//!
4//! [`DoclingDocument::nodes`](crate::DoclingDocument::nodes) is a flat,
5//! reading-order stream tuned for Markdown / DocLang / LaTeX; the JSON export
6//! rebuilds docling's parent/child structure from it with generic rules (runs
7//! of list items become list groups, a heading is a flat sibling of the text
8//! that follows it). Upstream's backends do not all agree on that structure:
9//! the HTML backend nests everything after a heading *under* the heading,
10//! splits a paragraph of mixed formatting into an `inline` group of one text
11//! item per formatting run, parents a rich table cell's content to a group
12//! under the table, keeps site chrome on the `furniture` layer… and numbers
13//! every item in the order it *creates* them. A backend that ports those
14//! rules call-for-call (HTML's `html_tree.rs`, DOCX's `docx_tree.rs`) records
15//! the result here — an arena of items in
16//! creation order, each with its parent and children — and the JSON export
17//! ([`DoclingDocument::export_to_json`](crate::DoclingDocument::export_to_json))
18//! serializes this tree instead of deriving one from the nodes. Every other
19//! serializer keeps reading the flat nodes, so their output is unaffected.
20
21use crate::{ContentLayer, FieldItem, PictureImage, Script, Table};
22
23/// docling-core's `Formatting`: the inline styles an item carries in JSON.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct Formatting {
26 pub bold: bool,
27 pub italic: bool,
28 pub underline: bool,
29 pub strikethrough: bool,
30 pub script: Script,
31}
32
33/// A `list_item`'s docling fields.
34#[derive(Debug, Clone, PartialEq, Eq, Default)]
35pub struct ListMeta {
36 pub enumerated: bool,
37 /// docling's `marker` — the HTML backend writes `""` unless an ordered
38 /// list carries an explicit `start`, then `"{n}."`.
39 pub marker: String,
40}
41
42/// What an item in the tree is. Mirrors the docling-core item classes the
43/// JSON `texts` / `groups` / `tables` / `pictures` / `field_regions` buckets
44/// hold.
45#[derive(Debug, Clone, PartialEq)]
46pub enum TreeKind {
47 /// A `TextItem` / `TitleItem` / `SectionHeaderItem` / `ListItem`, told
48 /// apart by `label` (`text`, `title`, `section_header`, `list_item`,
49 /// `caption`, `checkbox_selected`, `checkbox_unselected`, …).
50 Text {
51 label: String,
52 text: String,
53 /// docling's `orig` when it differs from `text` (the heading text
54 /// before unicode cleanup, say); `None` = same as `text`.
55 orig: Option<String>,
56 formatting: Option<Formatting>,
57 hyperlink: Option<String>,
58 /// `section_header` only: docling's heading level.
59 level: Option<u8>,
60 /// `list_item` only.
61 list: Option<ListMeta>,
62 },
63 /// A `CodeItem`.
64 Code {
65 text: String,
66 orig: Option<String>,
67 /// The language hint (a highlighter class token such as `python`),
68 /// mapped onto docling's `CodeLanguageLabel` at export; `None` →
69 /// `unknown`.
70 language: Option<String>,
71 formatting: Option<Formatting>,
72 hyperlink: Option<String>,
73 },
74 /// A `GroupItem`: `label` is docling's `GroupLabel` value (`inline`,
75 /// `list`, `section`, `unspecified`, …), `name` its name (`group`, `list`,
76 /// `ordered list`, `header-2`, `rich_cell_group_1_0_3`, …).
77 Group { label: String, name: String },
78 /// A `TableItem`. `rich_cells` marks the cells docling serialized as a
79 /// `RichTableCell`: `(row, col)` grid anchor → the group item (a child of
80 /// the table) that holds the cell's content. `captions` are caption text
81 /// items in the tree.
82 Table {
83 table: Table,
84 rich_cells: Vec<(usize, usize, usize)>,
85 captions: Vec<usize>,
86 },
87 /// A `PictureItem`, its caption text items and optional payload.
88 /// `classification` is a `PictureClassificationLabel` value written as
89 /// the picture's `meta.classification` (an HTML `<stamp>` / `<signature>`).
90 Picture {
91 captions: Vec<usize>,
92 image: Option<PictureImage>,
93 classification: Option<String>,
94 /// The prediction's `confidence`, when the backend writes one: the
95 /// DocLang deserializer stamps `1.0`; the office and HTML backends
96 /// leave it out (`None`).
97 confidence: Option<f64>,
98 /// A native chart's data grid (docling's `meta.tabular_chart.chart_data`,
99 /// the series reconstructed as a `TableData`), for a DOCX chart drawing.
100 chart: Option<Table>,
101 /// The `ImageRef.dpi` docling writes for `image` when the backend
102 /// read one from the file (python-pptx's `Image.dpi`: PIL's `dpi`
103 /// info, rounded, 72 when absent or out of 1–2048); `None` → 72,
104 /// which is what upstream's other office backends pass.
105 dpi: Option<u32>,
106 },
107 /// A form key-value region (`field_regions` / `field_items`).
108 FieldRegion { items: Vec<FieldItem> },
109}
110
111/// docling's `ProvenanceItem` for a tree item, written verbatim: the
112/// backend's own geometry in the page's units — a PPTX shape's EMU box,
113/// whose `pages` entry is the slide size in EMU — rather than the 0–511
114/// DocLang grid the flat [`Node::Located`](crate::Node::Located) carries
115/// (which cannot round-trip those integers).
116#[derive(Debug, Clone, PartialEq)]
117pub struct TreeProv {
118 /// 1-based page (slide) number.
119 pub page_no: usize,
120 /// `[l, t, r, b]`, exactly as docling computed them.
121 pub bbox: [f64; 4],
122 /// docling's `coord_origin` tag. `MsPowerpointDocumentBackend` builds a
123 /// shape's box with `BoundingBox.from_tuple(…, BOTTOMLEFT)` — which reads
124 /// the tuple as `(l, b, r, t)`, so the shape's top EMU lands in `b` — a
125 /// quirk the JSON keeps; a speaker note's zero box is `TOPLEFT`
126 /// (`BoundingBox`'s default).
127 pub bottom_left: bool,
128 /// `[0, len(text)]` in characters for a text item, `[0, 0]` for a table
129 /// or picture.
130 pub charspan: [usize; 2],
131}
132
133/// docling's `TrackSource` — where in a time-based track (a WebVTT cue) a
134/// text item came from. Written as the item's `source: [{"kind": "track", …}]`.
135#[derive(Debug, Clone, PartialEq)]
136pub struct TreeTrack {
137 /// The cue's start offset in seconds (docling's `WebVTTTimestamp.seconds`:
138 /// `h*3600 + m*60 + s + millis/1000.0`, so the float is bit-identical).
139 pub start_time: f64,
140 /// The cue's end offset in seconds.
141 pub end_time: f64,
142 /// The cue identifier line, when the cue has one.
143 pub identifier: Option<String>,
144 /// The `<v …>` voice annotation the text sits in, when any.
145 pub voice: Option<String>,
146}
147
148/// One item of an [`ItemTree`].
149#[derive(Debug, Clone, PartialEq)]
150pub struct TreeItem {
151 /// The parent item's index; `None` = the document body.
152 pub parent: Option<usize>,
153 /// Child item indices, in docling's `children` order.
154 pub children: Vec<usize>,
155 /// The content layer; `None` = `body`.
156 pub layer: Option<ContentLayer>,
157 pub kind: TreeKind,
158 /// The item's `prov` entry, when the backend has page geometry for it
159 /// (`None` → `prov: []`, what the HTML and DOCX backends write).
160 pub prov: Option<TreeProv>,
161 /// docling's `DocItem.comments`: the `comment_section` groups (or note
162 /// text items) annotating this item, as item indices — written after
163 /// `prov` when non-empty.
164 pub comments: Vec<usize>,
165 /// docling's `DocItem.source`: the track segment a text item was taken
166 /// from (WebVTT cues) — written after `prov` when set.
167 pub source: Option<TreeTrack>,
168 /// Removed by [`ItemTree::delete`] (docling's `delete_items`): the slot
169 /// stays so every other index keeps its meaning, but the item is not
170 /// numbered or written.
171 pub deleted: bool,
172}
173
174/// docling's item tree in creation order (see the [module docs](self)).
175#[derive(Debug, Clone, PartialEq, Default)]
176pub struct ItemTree {
177 /// Every item, indexed by creation order — which is how docling numbers
178 /// `#/texts/N`, `#/groups/N`, … within each bucket.
179 pub items: Vec<TreeItem>,
180 /// The body's `children`, as item indices.
181 pub body: Vec<usize>,
182}
183
184impl ItemTree {
185 /// Append an item under `parent` (`None` = body) on `layer`, registering
186 /// it as its parent's last child — docling's `add_*` calls do exactly that.
187 pub fn add(
188 &mut self,
189 parent: Option<usize>,
190 layer: Option<ContentLayer>,
191 kind: TreeKind,
192 ) -> usize {
193 let id = self.items.len();
194 self.items.push(TreeItem {
195 parent,
196 children: Vec::new(),
197 layer,
198 kind,
199 prov: None,
200 comments: Vec::new(),
201 source: None,
202 deleted: false,
203 });
204 match parent {
205 Some(p) => self.items[p].children.push(id),
206 None => self.body.push(id),
207 }
208 id
209 }
210
211 /// [`add`](Self::add) with the item's provenance — docling's
212 /// `add_text(…, prov=prov)`.
213 pub fn add_with_prov(
214 &mut self,
215 parent: Option<usize>,
216 layer: Option<ContentLayer>,
217 kind: TreeKind,
218 prov: TreeProv,
219 ) -> usize {
220 let id = self.add(parent, layer, kind);
221 self.items[id].prov = Some(prov);
222 id
223 }
224
225 /// Append every item of `other` after this tree's, renumbering its
226 /// indices (parents, children, comments, table/picture caption and
227 /// rich-cell refs) and adding its body children to this body — so a
228 /// backend can build independent fragments in parallel (one per PPTX
229 /// slide) and still hand the export one tree in creation order, exactly
230 /// as if it had been built sequentially.
231 pub fn append(&mut self, other: ItemTree) {
232 let off = self.items.len();
233 let shift = |i: usize| i + off;
234 for mut item in other.items {
235 item.parent = item.parent.map(shift);
236 for c in item.children.iter_mut().chain(item.comments.iter_mut()) {
237 *c = shift(*c);
238 }
239 match &mut item.kind {
240 TreeKind::Table {
241 rich_cells,
242 captions,
243 ..
244 } => {
245 for (_, _, g) in rich_cells.iter_mut() {
246 *g = shift(*g);
247 }
248 for c in captions.iter_mut() {
249 *c = shift(*c);
250 }
251 }
252 TreeKind::Picture { captions, .. } => {
253 for c in captions.iter_mut() {
254 *c = shift(*c);
255 }
256 }
257 _ => {}
258 }
259 self.items.push(item);
260 }
261 self.body.extend(other.body.into_iter().map(shift));
262 }
263
264 /// Move `id` under `new_parent`, dropping it from its current parent's
265 /// children and appending it to the new one's — docling's
266 /// `group_cell_elements` re-parenting of a rich cell's items.
267 pub fn reparent(&mut self, id: usize, new_parent: Option<usize>) {
268 let old = self.items[id].parent;
269 let siblings = match old {
270 Some(p) => &mut self.items[p].children,
271 None => &mut self.body,
272 };
273 siblings.retain(|&c| c != id);
274 self.items[id].parent = new_parent;
275 match new_parent {
276 Some(p) => self.items[p].children.push(id),
277 None => self.body.push(id),
278 }
279 }
280
281 /// Remove `id` from the tree — docling's `delete_items`, which the DOCX
282 /// backend uses to drop the empty text item a blank spacer paragraph left
283 /// between two items of a resumed list. The item leaves its parent's
284 /// children and is neither numbered nor written; its slot stays so the
285 /// indices held elsewhere stay valid.
286 pub fn delete(&mut self, id: usize) {
287 match self.items[id].parent {
288 Some(p) => self.items[p].children.retain(|&c| c != id),
289 None => self.body.retain(|&c| c != id),
290 }
291 self.items[id].deleted = true;
292 }
293
294 /// The last live text-bucket item (docling's `doc.texts[-1]`).
295 pub fn last_text(&self) -> Option<usize> {
296 self.items.iter().rposition(|it| {
297 !it.deleted && matches!(it.kind, TreeKind::Text { .. } | TreeKind::Code { .. })
298 })
299 }
300
301 /// How many items of a bucket precede `id` — its `#/{bucket}/N` index.
302 pub fn bucket_index(&self, id: usize) -> usize {
303 let same = |k: &TreeKind| {
304 std::mem::discriminant(k) == std::mem::discriminant(&self.items[id].kind)
305 || matches!(
306 (k, &self.items[id].kind),
307 (TreeKind::Text { .. }, TreeKind::Code { .. })
308 | (TreeKind::Code { .. }, TreeKind::Text { .. })
309 )
310 };
311 self.items[..id]
312 .iter()
313 .filter(|it| !it.deleted && same(&it.kind))
314 .count()
315 }
316
317 /// The number of tables created so far (docling's `len(doc.tables)`).
318 pub fn table_count(&self) -> usize {
319 self.items
320 .iter()
321 .filter(|it| !it.deleted && matches!(it.kind, TreeKind::Table { .. }))
322 .count()
323 }
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 fn text(t: &str) -> TreeKind {
331 TreeKind::Text {
332 label: "text".into(),
333 text: t.into(),
334 orig: None,
335 formatting: None,
336 hyperlink: None,
337 level: None,
338 list: None,
339 }
340 }
341
342 /// `add` registers the item as its parent's (or the body's) last child;
343 /// `reparent` moves it — a rich cell's items leave the heading they were
344 /// created under for the table's group.
345 #[test]
346 fn add_and_reparent_keep_docling_children_order() {
347 let mut t = ItemTree::default();
348 let title = t.add(None, None, text("Title"));
349 let a = t.add(Some(title), None, text("a"));
350 let b = t.add(Some(title), None, text("b"));
351 let table = t.add(
352 Some(title),
353 None,
354 TreeKind::Table {
355 table: Table::default(),
356 rich_cells: Vec::new(),
357 captions: Vec::new(),
358 },
359 );
360 let group = t.add(
361 Some(table),
362 None,
363 TreeKind::Group {
364 label: "unspecified".into(),
365 name: "rich_cell_group_1_0_0".into(),
366 },
367 );
368 assert_eq!(t.body, vec![title]);
369 assert_eq!(t.items[title].children, vec![a, b, table]);
370 t.reparent(a, Some(group));
371 assert_eq!(t.items[title].children, vec![b, table]);
372 assert_eq!(t.items[group].children, vec![a]);
373 assert_eq!(t.items[a].parent, Some(group));
374 assert_eq!(t.table_count(), 1);
375 // Text and code share the `texts` bucket.
376 let code = t.add(
377 None,
378 None,
379 TreeKind::Code {
380 text: "x".into(),
381 orig: None,
382 language: None,
383 formatting: None,
384 hyperlink: None,
385 },
386 );
387 assert_eq!(t.bucket_index(code), 3, "title, a, b precede it in `texts`");
388 assert_eq!(t.bucket_index(group), 0);
389 assert_eq!(t.body, vec![title, code]);
390 }
391
392 /// `append` renumbers a fragment built on its own (a slide converted in
393 /// parallel) so the merged tree reads as if built in one pass: parents,
394 /// children, comment back-refs and caption refs all shift together.
395 #[test]
396 fn append_renumbers_a_fragment_into_creation_order() {
397 let mut whole = ItemTree::default();
398 let slide0 = whole.add(
399 None,
400 None,
401 TreeKind::Group {
402 label: "chapter".into(),
403 name: "slide-0".into(),
404 },
405 );
406 whole.add(Some(slide0), None, text("first"));
407
408 let mut frag = ItemTree::default();
409 let slide1 = frag.add(
410 None,
411 None,
412 TreeKind::Group {
413 label: "chapter".into(),
414 name: "slide-1".into(),
415 },
416 );
417 let cap = frag.add_with_prov(
418 Some(slide1),
419 None,
420 TreeKind::Text {
421 label: "caption".into(),
422 text: "Title".into(),
423 orig: None,
424 formatting: None,
425 hyperlink: None,
426 level: None,
427 list: None,
428 },
429 TreeProv {
430 page_no: 2,
431 bbox: [1.0, 2.0, 3.0, 4.0],
432 bottom_left: true,
433 charspan: [0, 5],
434 },
435 );
436 let pic = frag.add(
437 Some(slide1),
438 None,
439 TreeKind::Picture {
440 captions: vec![cap],
441 image: None,
442 classification: Some("bar_chart".into()),
443 confidence: None,
444 chart: None,
445 dpi: None,
446 },
447 );
448 let note = frag.add(
449 None,
450 Some(ContentLayer::Notes),
451 TreeKind::Group {
452 label: "comment_section".into(),
453 name: "comment-slide2-1".into(),
454 },
455 );
456 frag.items[pic].comments.push(note);
457
458 whole.append(frag);
459 assert_eq!(whole.body, vec![slide0, 2, 5]);
460 assert_eq!(whole.items[2].children, vec![3, 4]);
461 assert_eq!(whole.items[3].parent, Some(2));
462 assert_eq!(whole.items[3].prov.as_ref().map(|p| p.page_no), Some(2));
463 assert!(
464 matches!(&whole.items[4].kind, TreeKind::Picture { captions, .. } if captions == &[3])
465 );
466 assert_eq!(whole.items[4].comments, vec![5]);
467 assert_eq!(whole.items[5].parent, None);
468 assert_eq!(
469 whole.bucket_index(4),
470 0,
471 "the fragment's picture is #/pictures/0"
472 );
473 assert_eq!(
474 whole.bucket_index(5),
475 2,
476 "slide-0, slide-1 precede it in `groups`"
477 );
478 }
479}