docling_core/document.rs
1//! The unified document representation.
2
3use crate::markdown::{to_markdown, to_markdown_images};
4use crate::ImageMode;
5
6/// The unified, format-agnostic document produced by every backend.
7///
8/// This is the heart of docling: backends parse their source format into a
9/// `DoclingDocument`, and serializers turn it back into Markdown, HTML, JSON,
10/// etc. Phase 0 uses a flat sequence of [`Node`]s; the production schema will
11/// match docling-core's body-tree-with-references layout.
12#[derive(Debug, Clone, PartialEq)]
13pub struct DoclingDocument {
14 /// Logical document name (usually the input file stem).
15 pub name: String,
16 /// Top-level content, in reading order.
17 pub nodes: Vec<Node>,
18 /// Default Markdown export mode for [`Self::export_to_markdown`]. `false`
19 /// (the default) reproduces docling's legacy output byte-for-byte; `true`
20 /// emits cleaner, more conformant Markdown. Set by `DocumentConverter`.
21 pub strict_markdown: bool,
22 /// Emit tables in the compact `| a | b |` / `| - | - |` form rather than
23 /// docling-core's width-padded GitHub serializer. The PDF backend sets this
24 /// (its committed groundtruth corpus predates the padded serializer); DOCX/HTML
25 /// leave it `false` to match current published docling.
26 pub compact_tables: bool,
27 /// Hyperlinks recovered from the source, as `(anchor_text, href)` pairs in
28 /// document order. docling's standard pipeline drops PDF link annotations, so
29 /// these are rendered as Markdown `[anchor](href)` **only in strict mode**
30 /// (legacy/docling output is left byte-for-byte unchanged). The PDF backend
31 /// populates this from pdfium link annotations; other backends leave it empty.
32 pub links: Vec<(String, String)>,
33 /// Conversion-confidence report (#183), populated by the PDF/image ML
34 /// pipeline; `None` for declarative conversions. Deliberately **not**
35 /// part of any document export (docling keeps it on the conversion
36 /// result, outside the document schema) — docling-serve surfaces it in
37 /// the HTTP response instead.
38 pub confidence: Option<crate::confidence::ConfidenceReport>,
39}
40
41/// A single piece of document content.
42#[derive(Debug, Clone, PartialEq)]
43pub enum Node {
44 /// A heading. `level` is 1-6.
45 Heading { level: u8, text: String },
46 /// A run of body text.
47 Paragraph { text: String },
48 /// A form checkbox (docling's `checkbox_selected`/`checkbox_unselected`): its
49 /// clean label `text` with the checked state. DocLang emits a `<checkbox>`
50 /// element head; Markdown/JSON render the task-list form (`- [x] `/`- [ ] `).
51 CheckboxItem { checked: bool, text: String },
52 /// A single list item at the given nesting `level` (0 = top). For ordered
53 /// items, `number` is the display number (honoring the list's `start`); it
54 /// is unused for unordered items. `first_in_list` marks the first item of a
55 /// list so the serializer can blank-line-separate adjacent sibling lists.
56 ///
57 /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
58 /// backend provides one — HTML and DOCX set it for enumerated items, so
59 /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
60 /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
61 /// docling, whose Markdown backend passes no marker).
62 ListItem {
63 ordered: bool,
64 number: u64,
65 first_in_list: bool,
66 text: String,
67 level: u8,
68 marker: Option<String>,
69 /// Optional layout provenance (`x0,y0,x1,y1`, normalized to 0–511): the
70 /// four DocLang `<location>` values emitted inside the `<list>` right
71 /// after the item's `<ldiv>`. Set only by backends with real geometry
72 /// (e.g. PPTX shapes); `None` for the declarative backends. Kept on the
73 /// item itself (rather than a [`Node::Located`] wrapper) so consecutive
74 /// items still group into one `<list>`.
75 location: Option<[u16; 4]>,
76 /// DocLang-only override for items whose DocLang form diverges from their
77 /// flat Markdown `text`. Markdown/JSON always render the fields above; the
78 /// DocLang serializer, when this is `Some`, takes the list kind, marker,
79 /// and content from here instead. Used for docx multilevel numbering
80 /// (Markdown shows `- 1.1. x`, DocLang an ordered `<marker>1.1.</marker>`
81 /// with clean text) and inline equations/formatting in list items.
82 dclx: Option<ListItemDclx>,
83 /// The item's hyperlink target, when its content is a link — docling's
84 /// HTML backend emits it as an `<href uri=…/>` in the item head, and the
85 /// anchor's Markdown link markup is stripped from the rendered content.
86 /// `None` for a plain item; ignored by Markdown/JSON.
87 href: Option<String>,
88 /// Non-body content layer (docling's HTML site chrome before the first
89 /// heading → `furniture`). DocLang emits a `<layer value=…/>` in the item
90 /// head; Markdown/JSON drop a non-body item entirely.
91 layer: Option<ContentLayer>,
92 },
93 /// A fenced code block.
94 Code {
95 language: Option<String>,
96 text: String,
97 /// The original (pre-enrichment) text when the CodeFormula model
98 /// rewrote `text`: docling keeps the raw extraction in the JSON `orig`
99 /// field while `text` carries the model output. `None` → `orig == text`.
100 orig: Option<String>,
101 /// A line-preserving rendering, when the backend can reconstruct one
102 /// but docling's own output for the format cannot. The PDF pipeline
103 /// sets it (docling-parse joins code lines with single spaces, so
104 /// `text` carries that flat docling-parity form): **strict** Markdown
105 /// prefers `pretty`, every byte-conformance surface (legacy Markdown,
106 /// JSON, DocLang, chunks) serializes `text`.
107 pretty: Option<String>,
108 },
109 /// A table. The first row is treated as the header.
110 Table(Table),
111 /// A picture/figure, with an optional caption and (when a backend extracts
112 /// it) the embedded image itself.
113 Picture {
114 caption: Option<String>,
115 /// Hyperlink annotation on the caption (docling's caption text item
116 /// `hyperlink`): the HTML backend sets it when an `<a href>` wraps the
117 /// image whose `alt` became the caption. DocLang emits the block-form
118 /// `<caption>` with an `<href uri=…/>` head; JSON puts `hyperlink` on
119 /// the caption item; Markdown and LaTeX print the plain caption text,
120 /// as docling does.
121 caption_href: Option<String>,
122 image: Option<PictureImage>,
123 /// DocumentPictureClassifier predictions (all classes, descending
124 /// confidence), when the picture-classification enrichment ran.
125 /// Serialized as docling's `classification` annotation + `meta` field
126 /// on the JSON picture item; Markdown/DocLang output is unaffected.
127 classification: Option<Vec<PictureClass>>,
128 },
129 /// A display-math formula item decoded by the CodeFormula enrichment:
130 /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
131 /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
132 /// `formula` text item (docling's un-enriched pipeline instead emits a
133 /// placeholder paragraph — see the PDF assembler).
134 Formula {
135 latex: String,
136 orig: String,
137 location: Option<[u16; 4]>,
138 },
139 /// A chart (docling's `PictureItem` classified as a chart, carrying a
140 /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
141 /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
142 /// item); the DocLang serializer emits `<picture class="chart">` with a
143 /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
144 Chart {
145 /// docling's classification label, e.g. `bar_chart`, `line_chart`.
146 kind: String,
147 /// The chart's data grid (row 0 is the header band).
148 table: Table,
149 /// The chart title (docling's caption item on the picture).
150 caption: Option<String>,
151 /// DocLang `<location>` provenance for the picture element.
152 location: Option<[u16; 4]>,
153 },
154 /// A logical grouping of child nodes (e.g. a list, a section, a spreadsheet
155 /// sheet). `name` is docling's group name when it differs from the label —
156 /// an xlsx sheet group is `label: "sheet"`, `name: Some("Sheet1")`. `layer`
157 /// puts the group *and* everything it contains on a non-body content layer
158 /// (a hidden sheet is `invisible`), which is how the serializers that only
159 /// render body content know to skip it; DocLang stamps each child with the
160 /// layer token, exactly as a [`Node::Furniture`] wrapper on each would.
161 /// DocLang has no group element, so a group is transparent there.
162 Group {
163 label: String,
164 name: Option<String>,
165 layer: Option<ContentLayer>,
166 children: Vec<Node>,
167 },
168 /// A form key-value region (docling's `field_region`): a set of form fields,
169 /// each pairing an optional marker, key, and value. Backends detect these
170 /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
171 /// `id`-convention); the serializers render each item's parts as separate
172 /// labelled texts (`marker` / `field_key` / `field_value`).
173 FieldRegion { items: Vec<FieldItem> },
174 /// Rich inline content — docling's `InlineGroup`: a run of styled text
175 /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
176 /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
177 /// flat Markdown text cannot represent. Markdown/JSON render this exactly
178 /// like `Paragraph { text: md_text }` (so their output is unchanged); the
179 /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
180 /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
181 InlineGroup {
182 unwrapped: bool,
183 runs: Vec<InlineRun>,
184 md_text: String,
185 },
186 /// A node in a non-body content layer — `furniture` (page headers/footers,
187 /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
188 /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
189 /// node with a `<layer value="{layer}"/>` head.
190 Furniture {
191 layer: ContentLayer,
192 inner: Box<Node>,
193 },
194 /// One reviewer comment: docling's notes-layer `comment_section` group
195 /// holding a single text item. `name` is docling's own — `comment-{id}` for
196 /// a docx `w:comment`, `comment-{sheet}-{cell}` for a spreadsheet cell note.
197 /// JSON emits the group plus its notes-layer text; DocLang emits the flat
198 /// `<text><layer value="notes"/>…</text>` upstream writes (its DocLang
199 /// carries no group for comments); Markdown and LaTeX omit the notes layer.
200 ///
201 /// `refs_note_text` picks what a [`Node::Commented`] annotation points at,
202 /// mirroring an upstream asymmetry: docling-core's `add_comment` appends the
203 /// **note text**'s ref to each target (which is what the xlsx backend gets),
204 /// while the docx backend overwrites that with the **group**'s ref so a
205 /// comment's replies group together.
206 CommentSection {
207 name: String,
208 text: String,
209 refs_note_text: bool,
210 },
211 /// A body item annotated by reviewer comments: `comments` are indices into
212 /// the document's [`Node::CommentSection`] nodes, in document order. JSON
213 /// emits docling's `comments: [{"$ref": …}]` on the item, each ref pointing
214 /// where the section says (see [`Node::CommentSection::refs_note_text`]);
215 /// every other serializer renders `inner` unchanged.
216 Commented {
217 comments: Vec<usize>,
218 inner: Box<Node>,
219 },
220 /// A node carrying layout provenance — the four DocLang `<location>` values
221 /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
222 /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
223 /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
224 /// tokens as the element's first children.
225 Located {
226 location: [u16; 4],
227 inner: Box<Node>,
228 },
229 /// A PDF page header or footer (docling's `page_header`/`page_footer`
230 /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
231 /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
232 /// text. Markdown and JSON omit it like other furniture.
233 PageFurniture {
234 footer: bool,
235 location: [u16; 4],
236 text: String,
237 },
238 /// A page boundary — docling's implicit page break between pages. The PPTX
239 /// backend emits one between consecutive slides. DocLang renders it as
240 /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
241 /// exports, which carry page breaks only in the document model).
242 PageBreak,
243 /// An invisible page marker — the first node of every page the PDF paths
244 /// assemble: the 1-based page number and the page size in PDF points. It
245 /// carries exactly what the JSON export needs to populate docling's
246 /// `pages` map and to denormalize the 0–511 `<location>` grid back into
247 /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
248 /// serializer skips it, so Markdown / DocLang / DocTags output is
249 /// byte-for-byte unchanged.
250 PageInfo {
251 /// 1-based page number (0 = "not yet numbered": the assembler emits
252 /// the marker, the document-level collector stamps the real number).
253 page_no: usize,
254 /// Page width in PDF points.
255 width: f32,
256 /// Page height in PDF points.
257 height: f32,
258 },
259 /// A node docling keeps in the document model (and DocLang) but leaves out
260 /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
261 /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
262 /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
263 DoclangOnly(Box<Node>),
264 /// A verbatim plain-text dump — docling's plain-text backend emits the whole
265 /// file as a single text item (used for legacy USPTO APS `.txt` grants, which
266 /// docling routes to plain text rather than its APS parser). The stored string
267 /// is the file body, one record per line. Markdown/JSON render it as one text
268 /// block; the DocLang serializer reproduces minidom's per-line layout, CDATA-
269 /// escaping only the lines that need it (see `emit_text_dump`).
270 TextDump(String),
271}
272
273/// Vertical text position of an [`InlineRun`] — docling's `Script`.
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
275pub enum Script {
276 #[default]
277 Baseline,
278 Sub,
279 Super,
280}
281
282/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
283/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
284/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
285/// source text node). A hyperlink is intentionally not stored: DocLang drops the
286/// target inside inline scope, keeping only the anchor text.
287#[derive(Debug, Clone, PartialEq, Eq, Default)]
288pub struct InlineRun {
289 pub text: String,
290 pub bold: bool,
291 pub italic: bool,
292 pub underline: bool,
293 pub strike: bool,
294 pub script: Script,
295 pub code: bool,
296 /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
297 /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
298 pub formula: bool,
299}
300
301/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub enum ContentLayer {
304 /// Page headers/footers, HTML `<title>`, site navigation/chrome.
305 Furniture,
306 /// Editorial notes (docx reviewer comments).
307 Notes,
308 /// Invisible content (hidden spreadsheet sheets).
309 Invisible,
310}
311
312impl ContentLayer {
313 /// The `<layer value="…"/>` token value.
314 pub fn value(self) -> &'static str {
315 match self {
316 ContentLayer::Furniture => "furniture",
317 ContentLayer::Notes => "notes",
318 ContentLayer::Invisible => "invisible",
319 }
320 }
321}
322
323/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
324/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
325/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
326/// (structured equations/formatting) when non-empty, else `text` re-parsed for
327/// inline markers.
328#[derive(Debug, Clone, PartialEq, Eq, Default)]
329pub struct ListItemDclx {
330 pub ordered: bool,
331 pub marker: Option<String>,
332 pub text: String,
333 pub runs: Vec<InlineRun>,
334}
335
336impl InlineRun {
337 /// A run with no active formatting (renders as bare inline text).
338 pub fn is_plain(&self) -> bool {
339 !self.bold
340 && !self.italic
341 && !self.underline
342 && !self.strike
343 && !self.code
344 && !self.formula
345 && self.script == Script::Baseline
346 }
347}
348
349/// Build the [`Node`] for a paragraph of inline content from its structured
350/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
351///
352/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
353/// serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
354/// * a single uniformly-formatted run, or two or more runs → a
355/// [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
356/// heading, so no enclosing `<text>`) only applies to multi-run groups.
357///
358/// Markdown/JSON render the group's `md_text`, so their output is identical to
359/// emitting a `Paragraph` — the structured runs are DocLang-only.
360pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
361 let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
362 if single_plain {
363 Node::Paragraph { text: md_text }
364 } else {
365 Node::InlineGroup {
366 unwrapped: unwrapped && runs.len() >= 2,
367 runs,
368 md_text,
369 }
370 }
371}
372
373/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
374/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
375/// / `field_value` child texts.
376#[derive(Debug, Clone, PartialEq, Default)]
377pub struct FieldItem {
378 pub marker: Option<String>,
379 pub key: Option<String>,
380 pub value: Option<String>,
381}
382
383/// One DocumentPictureClassifier prediction — docling-core's
384/// `PictureClassificationClass` (`class_name` + `confidence`).
385#[derive(Debug, Clone, PartialEq)]
386pub struct PictureClass {
387 /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
388 pub class_name: String,
389 pub confidence: f32,
390}
391
392/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
393/// the docling.rs analogue of docling-core's `ImageRef`.
394#[derive(Debug, Clone, PartialEq)]
395pub struct PictureImage {
396 /// e.g. `image/png`, `image/jpeg`.
397 pub mimetype: String,
398 pub width: u32,
399 pub height: u32,
400 /// The image file bytes, exactly as embedded (PNG/JPEG/…).
401 pub data: Vec<u8>,
402}
403
404impl PictureImage {
405 /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
406 pub fn data_uri(&self) -> String {
407 format!(
408 "data:{};base64,{}",
409 self.mimetype,
410 crate::base64::encode(&self.data)
411 )
412 }
413}
414
415/// One table cell as a first-class object (#240) — the Rust counterpart of
416/// docling's `TableCell`: its text, page geometry, grid rectangle and header
417/// roles. Produced by the PDF TableFormer paths from the predicted OTSL
418/// structure; `bbox` is `[l, t, r, b]` in page points with a top-left origin.
419#[derive(Debug, Clone, PartialEq)]
420pub struct TableCell {
421 pub text: String,
422 /// `[l, t, r, b]`, page points, top-left origin; `None` without geometry.
423 pub bbox: Option<[f32; 4]>,
424 /// Anchor grid position (0-based row/column offsets).
425 pub start_row: usize,
426 pub start_col: usize,
427 /// Span extents (≥ 1); the covered grid positions repeat the cell's text
428 /// in [`Table::rows`].
429 pub row_span: usize,
430 pub col_span: usize,
431 /// OTSL `ched` — a column-header cell.
432 pub column_header: bool,
433 /// OTSL `rhed` — a row-header cell.
434 pub row_header: bool,
435 /// OTSL `srow` — a section-row cell.
436 pub row_section: bool,
437}
438
439/// A simple row-major table. By default `rows[0]` is the header row; a
440/// [`TableStructure`] overlay overrides that and adds column spans.
441#[derive(Debug, Clone, PartialEq, Default)]
442pub struct Table {
443 pub rows: Vec<Vec<String>>,
444 /// Optional layout provenance: the four DocLang `<location>` values
445 /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
446 /// before the table's cells. Set only by backends with real geometry (e.g.
447 /// the spreadsheet backend, whose cell grid yields a bounding box); left
448 /// `None` by declarative backends, which have no coordinates.
449 pub location: Option<[u16; 4]>,
450 /// Optional OTSL structure overlay for backends that parse real table
451 /// geometry (USPTO CALS): explicit header-row count and horizontal-span
452 /// continuations. `None` → the default (row 0 is the header, no spans).
453 /// `rows` still carries the full text grid (span text replicated) for
454 /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
455 pub structure: Option<TableStructure>,
456 /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
457 /// ODF cell holding a list, several paragraphs, or a nested table) carries
458 /// its DocLang blocks here; the DocLang serializer emits them after the
459 /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
460 /// and render `rows`, so their output is unchanged. `None` (or an empty
461 /// `Vec` for a given cell) → the flat text is used everywhere.
462 pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
463 /// Optional caption (docling's `TableItem.captions`): the JATS
464 /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
465 /// it as a text line *before* the grid; JSON emits a caption text item the
466 /// table references; DocLang emits a `<caption>` as the table's first child.
467 /// `None` → the table has no caption.
468 pub caption: Option<String>,
469 /// Optional per-cell bounding boxes, same shape as [`Self::rows`]: `[l, t,
470 /// r, b]` in page points with a **top-left** origin (the PDF pipeline's
471 /// native space). Set by the ML pipeline's TableFormer paths — a spanned
472 /// cell repeats its anchor's box across the covered grid positions — and
473 /// First-class cells (#240): the authoritative per-cell records —
474 /// text, page geometry, spans and header roles — when the backend
475 /// produces them (the PDF TableFormer paths do; declarative backends
476 /// leave `None`). [`Self::rows`] stays the dense text grid every
477 /// serializer renders (a spanning cell's text is replicated across its
478 /// covered positions there); JSON serializes these cells verbatim when
479 /// present, and the DocLang structure overlay is derived from them.
480 pub cells: Option<Vec<TableCell>>,
481}
482
483impl Table {
484 /// A cell's text at a grid position, `None` outside the grid.
485 pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
486 self.rows.get(row)?.get(col).map(String::as_str)
487 }
488
489 /// Replace the text at a grid position; `false` (and no change) outside
490 /// the grid. When a first-class cell covers the position, the whole
491 /// cell is updated: its record text and every grid position its span
492 /// covers, so the repair shows once in Markdown, not once per covered
493 /// column.
494 pub fn set_cell_text(&mut self, row: usize, col: usize, text: impl Into<String>) -> bool {
495 if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
496 return false;
497 }
498 let text = text.into();
499 let covering = self.cells.as_mut().and_then(|cells| {
500 cells.iter_mut().find(|c| {
501 (c.start_row..c.start_row + c.row_span).contains(&row)
502 && (c.start_col..c.start_col + c.col_span).contains(&col)
503 })
504 });
505 if let Some(cell) = covering {
506 cell.text = text.clone();
507 let (r0, r1) = (cell.start_row, cell.start_row + cell.row_span);
508 let (c0, c1) = (cell.start_col, cell.start_col + cell.col_span);
509 for r in self.rows.iter_mut().take(r1).skip(r0) {
510 for slot in r.iter_mut().take(c1).skip(c0) {
511 *slot = text.clone();
512 }
513 }
514 } else {
515 self.rows[row][col] = text;
516 }
517 true
518 }
519
520 /// Derive first-class cells (#240) from the dense grid plus the
521 /// [`TableStructure`] overlay — how declarative tables (DOCX/XLSX merged
522 /// regions, HTML `th`/spans, ODF covered cells, USPTO CALS) get real
523 /// `TableCell` records without page geometry. Anchors are the positions
524 /// not marked as span continuations; extents scan the continuation grids
525 /// right/down (matching the DocLang `lcel`/`ucel` reading). Header roles
526 /// come from the per-cell `col_header`/`row_header` grids when present,
527 /// else the `header_row` band, else docling's declarative default (row 0
528 /// is the header). Without any overlay every position is a 1×1 cell.
529 pub fn derive_cells(&self) -> Vec<TableCell> {
530 let s = self.structure.as_ref();
531 let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| {
532 grid.and_then(|g| g.get(r))
533 .and_then(|row| row.get(c))
534 .copied()
535 .unwrap_or(false)
536 };
537 let col_cont = |r: usize, c: usize| flag(s.map(|s| &s.col_continuation), r, c);
538 let row_cont = |r: usize, c: usize| flag(s.map(|s| &s.row_continuation), r, c);
539 let is_col_header = |r: usize, c: usize| match s {
540 Some(st) if !st.col_header.is_empty() => flag(Some(&st.col_header), r, c),
541 Some(st) if !st.header_row.is_empty() => st.header_row.get(r).copied().unwrap_or(false),
542 _ => r == 0,
543 };
544 let mut cells = Vec::new();
545 for (r, row) in self.rows.iter().enumerate() {
546 for (c, text) in row.iter().enumerate() {
547 if col_cont(r, c) || row_cont(r, c) {
548 continue; // covered by a span anchor
549 }
550 let mut col_span = 1;
551 while c + col_span < row.len() && col_cont(r, c + col_span) {
552 col_span += 1;
553 }
554 let mut row_span = 1;
555 while r + row_span < self.rows.len() && row_cont(r + row_span, c) {
556 row_span += 1;
557 }
558 cells.push(TableCell {
559 text: text.clone(),
560 bbox: None,
561 start_row: r,
562 start_col: c,
563 row_span,
564 col_span,
565 column_header: is_col_header(r, c),
566 row_header: flag(s.map(|s| &s.row_header), r, c),
567 row_section: false,
568 });
569 }
570 }
571 cells
572 }
573
574 /// The first-class cell covering a grid position, if any.
575 pub fn cell_at(&self, row: usize, col: usize) -> Option<&TableCell> {
576 self.cells.as_ref()?.iter().find(|c| {
577 (c.start_row..c.start_row + c.row_span).contains(&row)
578 && (c.start_col..c.start_col + c.col_span).contains(&col)
579 })
580 }
581
582 /// A cell's bounding box (`[l, t, r, b]`, page points, top-left origin);
583 /// `None` when no cell with geometry covers the position.
584 pub fn cell_bbox(&self, row: usize, col: usize) -> Option<[f32; 4]> {
585 self.cell_at(row, col)?.bbox
586 }
587
588 /// Set (or replace) the bounding box of the cell covering a grid
589 /// position; `false` outside the text grid. A table without first-class
590 /// cells materializes them first (one 1×1 cell per grid position, texts
591 /// from the grid), so declarative tables can be annotated too.
592 pub fn set_cell_bbox(&mut self, row: usize, col: usize, bbox: [f32; 4]) -> bool {
593 if self.rows.get(row).and_then(|r| r.get(col)).is_none() {
594 return false;
595 }
596 let rows = &self.rows;
597 let cells = self.cells.get_or_insert_with(|| {
598 rows.iter()
599 .enumerate()
600 .flat_map(|(r, cols)| {
601 cols.iter().enumerate().map(move |(c, text)| TableCell {
602 text: text.clone(),
603 bbox: None,
604 start_row: r,
605 start_col: c,
606 row_span: 1,
607 col_span: 1,
608 column_header: false,
609 row_header: false,
610 row_section: false,
611 })
612 })
613 .collect()
614 });
615 match cells.iter_mut().find(|c| {
616 (c.start_row..c.start_row + c.row_span).contains(&row)
617 && (c.start_col..c.start_col + c.col_span).contains(&col)
618 }) {
619 Some(cell) => {
620 cell.bbox = Some(bbox);
621 true
622 }
623 None => {
624 cells.push(TableCell {
625 text: self.rows[row][col].clone(),
626 bbox: Some(bbox),
627 start_row: row,
628 start_col: col,
629 row_span: 1,
630 col_span: 1,
631 column_header: false,
632 row_header: false,
633 row_section: false,
634 });
635 true
636 }
637 }
638 }
639
640 /// The anchor position of the cell whose box overlaps `bbox` best
641 /// (largest intersection-over-union), ties resolved in cell order.
642 /// `None` when nothing overlaps or the table carries no geometry. This
643 /// is the lookup half of the repair workflow: find the cell an external
644 /// OCR box refers to, then [`Self::set_cell_text`] it.
645 pub fn find_cell_by_bbox(&self, bbox: [f32; 4]) -> Option<(usize, usize)> {
646 let area = |b: &[f32; 4]| ((b[2] - b[0]) * (b[3] - b[1])).max(0.0);
647 let mut best: Option<(f32, (usize, usize))> = None;
648 for cell in self.cells.as_deref()?.iter() {
649 let Some(cb) = cell.bbox else { continue };
650 let iw = (bbox[2].min(cb[2]) - bbox[0].max(cb[0])).max(0.0);
651 let ih = (bbox[3].min(cb[3]) - bbox[1].max(cb[1])).max(0.0);
652 let inter = iw * ih;
653 if inter <= 0.0 {
654 continue;
655 }
656 let iou = inter / (area(&bbox) + area(&cb) - inter).max(f32::EPSILON);
657 if best.is_none_or(|(b, _)| iou > b) {
658 best = Some((iou, (cell.start_row, cell.start_col)));
659 }
660 }
661 best.map(|(_, pos)| pos)
662 }
663
664 /// Locate the cell overlapping `bbox` best and replace its text — the
665 /// one-call form of the OCR-repair loop. Returns the updated anchor.
666 pub fn update_cell_by_bbox(
667 &mut self,
668 bbox: [f32; 4],
669 text: impl Into<String>,
670 ) -> Option<(usize, usize)> {
671 let (row, col) = self.find_cell_by_bbox(bbox)?;
672 self.set_cell_text(row, col, text);
673 Some((row, col))
674 }
675}
676
677/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
678#[derive(Debug, Clone, PartialEq, Default)]
679pub struct TableStructure {
680 /// Per-row: `true` if the row's non-empty cells are column headers
681 /// (emitted as `<ched/>` rather than `<fcel/>`).
682 pub header_row: Vec<bool>,
683 /// Same shape as [`Table::rows`]; `true` where a cell continues a
684 /// horizontal span from its left neighbour (emitted as `<lcel/>`).
685 pub col_continuation: Vec<Vec<bool>>,
686 /// Same shape as [`Table::rows`]; `true` where a cell continues a
687 /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
688 /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
689 pub row_continuation: Vec<Vec<bool>>,
690 /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
691 /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
692 /// the table has no row headers.
693 pub row_header: Vec<Vec<bool>>,
694 /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
695 /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
696 /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
697 /// cell-level `column_header` flag; the chunker derives its header-row
698 /// count from it.
699 pub col_header: Vec<Vec<bool>>,
700}
701
702impl DoclingDocument {
703 /// Create an empty document with the given name.
704 pub fn new(name: impl Into<String>) -> Self {
705 Self {
706 name: name.into(),
707 nodes: Vec::new(),
708 strict_markdown: false,
709 compact_tables: false,
710 links: Vec::new(),
711 confidence: None,
712 }
713 }
714
715 /// Append a node.
716 /// The document's top-level tables in reading order — the read half of
717 /// the post-extraction table API (#238). [`Node::Located`] wrappers (the
718 /// PDF pipeline attaches layout provenance that way) are looked through;
719 /// tables nested inside rich table cells (`Table::cell_blocks`) are not
720 /// traversed.
721 pub fn tables(&self) -> impl Iterator<Item = &Table> {
722 fn unwrap_table(n: &Node) -> Option<&Table> {
723 match n {
724 Node::Table(t) => Some(t),
725 Node::Located { inner, .. } => unwrap_table(inner),
726 _ => None,
727 }
728 }
729 self.nodes.iter().filter_map(unwrap_table)
730 }
731
732 /// Mutable access to the document's top-level tables, for repair
733 /// workflows (#238): locate a cell via [`Table::find_cell_by_bbox`], fix
734 /// its text with [`Table::set_cell_text`], then re-export — every
735 /// serializer reads the same grid.
736 pub fn tables_mut(&mut self) -> impl Iterator<Item = &mut Table> {
737 fn unwrap_table(n: &mut Node) -> Option<&mut Table> {
738 match n {
739 Node::Table(t) => Some(t),
740 Node::Located { inner, .. } => unwrap_table(inner),
741 _ => None,
742 }
743 }
744 self.nodes.iter_mut().filter_map(unwrap_table)
745 }
746
747 pub fn push(&mut self, node: Node) {
748 self.nodes.push(node);
749 }
750
751 /// Convenience: append a heading.
752 pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
753 self.push(Node::Heading {
754 level,
755 text: text.into(),
756 });
757 }
758
759 /// Convenience: append a paragraph.
760 pub fn add_paragraph(&mut self, text: impl Into<String>) {
761 self.push(Node::Paragraph { text: text.into() });
762 }
763
764 /// Serialize the document to Markdown.
765 ///
766 /// The Rust equivalent of docling-core's
767 /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
768 /// pick between docling-legacy output (default) and the cleaner, more
769 /// conformant variant.
770 pub fn export_to_markdown(&self) -> String {
771 to_markdown(self, self.strict_markdown)
772 }
773
774 /// Serialize to Markdown, explicitly choosing the mode regardless of
775 /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
776 /// conformant Markdown (code-fence languages preserved, no inline-run
777 /// spacing artifacts); `strict = false` reproduces docling's legacy output.
778 pub fn export_to_markdown_with(&self, strict: bool) -> String {
779 to_markdown(self, strict)
780 }
781
782 /// Markdown for this document as the *content of a rich table cell*
783 /// (docling-core's `in_table_cell` serialization, docling-core#540):
784 /// headings render as plain text since Markdown tables can't hold them.
785 /// Backends build a sub-document per rich cell and flatten this into the
786 /// cell text; no trailing newline.
787 pub fn export_to_table_cell_markdown(&self) -> String {
788 crate::markdown::to_markdown_table_cell(self, self.strict_markdown)
789 }
790
791 /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
792 /// schema), pretty-printed — the Rust equivalent of
793 /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
794 /// back into Python docling-core and round-trips to the same Markdown.
795 pub fn export_to_json(&self) -> String {
796 serde_json::to_string_pretty(&self.export_to_json_value())
797 .expect("DoclingDocument JSON is always serializable")
798 }
799
800 /// The same JSON wire format as [`Self::export_to_json`], as a
801 /// `serde_json::Value` — for callers that append response-level extras
802 /// (docling-serve adds the confidence report, #183) before serializing.
803 pub fn export_to_json_value(&self) -> serde_json::Value {
804 crate::json::to_json(self)
805 }
806
807 /// Serialize to a complete LaTeX document — the Rust counterpart of
808 /// docling-core's `LaTeXDocSerializer` with default parameters (docling
809 /// 2.124's `--to latex`, #317). No trailing newline, like the upstream
810 /// CLI's `<stem>.tex`.
811 pub fn export_to_latex(&self) -> String {
812 crate::latex::to_latex(self)
813 }
814
815 /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
816 /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
817 /// `export_to_doclang()` with default parameters. No trailing newline; the
818 /// archive writer appends exactly one.
819 pub fn export_to_doclang(&self) -> String {
820 crate::doclang::export_to_doclang(&self.nodes)
821 }
822
823 /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
824 /// docling's `image_mode`). Returns the Markdown and, for
825 /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
826 /// caller should write next to the Markdown file. `artifacts_dir` is the
827 /// directory name used in referenced links.
828 pub fn export_to_markdown_with_images(
829 &self,
830 image_mode: ImageMode,
831 artifacts_dir: &str,
832 ) -> (String, Vec<(String, Vec<u8>)>) {
833 to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
834 }
835}
836
837#[cfg(test)]
838mod table_api_tests {
839 use super::*;
840
841 fn cell(
842 text: &str,
843 bbox: [f32; 4],
844 (start_row, start_col): (usize, usize),
845 (row_span, col_span): (usize, usize),
846 ) -> TableCell {
847 TableCell {
848 text: text.into(),
849 bbox: Some(bbox),
850 start_row,
851 start_col,
852 row_span,
853 col_span,
854 column_header: false,
855 row_header: false,
856 row_section: false,
857 }
858 }
859
860 fn table() -> Table {
861 Table {
862 rows: vec![
863 vec!["Year".into(), "Ducks".into()],
864 vec!["2019".into(), "120".into()],
865 ],
866 cells: Some(vec![
867 cell("Year", [0.0, 0.0, 50.0, 10.0], (0, 0), (1, 1)),
868 cell("Ducks", [50.0, 0.0, 100.0, 10.0], (0, 1), (1, 1)),
869 cell("2019", [0.0, 10.0, 50.0, 20.0], (1, 0), (1, 1)),
870 cell("120", [50.0, 10.0, 100.0, 20.0], (1, 1), (1, 1)),
871 ]),
872 ..Default::default()
873 }
874 }
875
876 /// Declarative tables derive first-class cells from the structure
877 /// overlay: continuation grids become span extents, `col_header` (or the
878 /// row-0 fallback) becomes the header role — the XLSX/DOCX/HTML merge
879 /// path into real `TableCell`s (#240).
880 #[test]
881 fn derive_cells_reads_spans_and_headers_from_structure() {
882 let t = Table {
883 rows: vec![
884 vec!["Wide".into(), "Wide".into(), "C".into()],
885 vec!["a".into(), "b".into(), "c".into()],
886 ],
887 structure: Some(TableStructure {
888 header_row: vec![true, false],
889 col_continuation: vec![vec![false, true, false], vec![false; 3]],
890 row_continuation: vec![vec![false; 3], vec![false; 3]],
891 row_header: Vec::new(),
892 col_header: Vec::new(),
893 }),
894 ..Default::default()
895 };
896 let cells = t.derive_cells();
897 assert_eq!(cells.len(), 5, "two anchors in row 0, three in row 1");
898 let wide = &cells[0];
899 assert_eq!((wide.col_span, wide.row_span), (2, 1));
900 assert!(wide.column_header, "header_row band");
901 assert!(cells.iter().skip(2).all(|c| !c.column_header));
902
903 // Without any overlay: every position 1x1, row 0 the header
904 // (docling's declarative default — the old JSON synthesis).
905 let plain = Table {
906 rows: vec![vec!["h".into()], vec!["x".into()]],
907 ..Default::default()
908 };
909 let cells = plain.derive_cells();
910 assert_eq!(cells.len(), 2);
911 assert!(cells[0].column_header && !cells[1].column_header);
912 }
913
914 /// A spanning cell updates once: the record text and every covered grid
915 /// position — a repair shows once in Markdown, not once per column.
916 #[test]
917 fn span_repair_updates_the_whole_cell() {
918 let mut t = Table {
919 rows: vec![
920 vec!["Wide".into(), "Wide".into(), "C".into()],
921 vec!["a".into(), "b".into(), "c".into()],
922 ],
923 cells: Some(vec![
924 cell("Wide", [0.0, 0.0, 100.0, 10.0], (0, 0), (1, 2)),
925 cell("C", [100.0, 0.0, 150.0, 10.0], (0, 2), (1, 1)),
926 ]),
927 ..Default::default()
928 };
929 // Update through the covered (non-anchor) position.
930 assert!(t.set_cell_text(0, 1, "Fixed"));
931 assert_eq!(
932 t.rows[0],
933 vec!["Fixed".to_string(), "Fixed".into(), "C".into()]
934 );
935 assert_eq!(t.cell_at(0, 1).unwrap().text, "Fixed");
936 assert_eq!(t.cell_at(0, 1).unwrap().col_span, 2);
937 }
938
939 /// The OCR-repair loop (#238): locate a cell by an external box (best
940 /// IoU), replace its text, and see the fix in the export — the grid is
941 /// the single source of truth for every serializer.
942 #[test]
943 fn bbox_lookup_and_repair_flow_into_exports() {
944 let mut doc = DoclingDocument::new("t");
945 doc.push(Node::Table(table()));
946 assert_eq!(doc.tables().count(), 1);
947
948 let t = doc.tables_mut().next().unwrap();
949 // A slightly-off OCR box still lands on the (1,1) cell.
950 assert_eq!(t.find_cell_by_bbox([52.0, 11.0, 98.0, 19.0]), Some((1, 1)));
951 assert_eq!(
952 t.update_cell_by_bbox([52.0, 11.0, 98.0, 19.0], "125"),
953 Some((1, 1))
954 );
955 assert_eq!(t.cell_text(1, 1), Some("125"));
956 assert!(doc.export_to_markdown().contains("125"));
957
958 // No overlap → no match, nothing changed.
959 let t = doc.tables_mut().next().unwrap();
960 assert_eq!(t.find_cell_by_bbox([500.0, 500.0, 600.0, 600.0]), None);
961 }
962
963 #[test]
964 fn cell_accessors_bound_check_and_geometry_materializes() {
965 let mut t = table();
966 assert_eq!(t.cell_text(0, 0), Some("Year"));
967 assert_eq!(t.cell_text(5, 0), None);
968 assert!(!t.set_cell_text(0, 9, "x"), "outside the grid");
969 assert_eq!(t.cell_bbox(1, 0), Some([0.0, 10.0, 50.0, 20.0]));
970
971 // A geometry-less table materializes its box grid on first set.
972 let mut plain = Table {
973 rows: vec![vec!["a".into(), "b".into()]],
974 ..Default::default()
975 };
976 assert_eq!(plain.cell_bbox(0, 1), None);
977 assert!(!plain.set_cell_bbox(0, 5, [0.0; 4]), "outside the grid");
978 assert!(plain.set_cell_bbox(0, 1, [1.0, 2.0, 3.0, 4.0]));
979 assert_eq!(plain.cell_bbox(0, 1), Some([1.0, 2.0, 3.0, 4.0]));
980 assert_eq!(plain.find_cell_by_bbox([1.5, 2.5, 2.5, 3.5]), Some((0, 1)));
981 }
982}