Skip to main content

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    },
102    /// A table. The first row is treated as the header.
103    Table(Table),
104    /// A picture/figure, with an optional caption and (when a backend extracts
105    /// it) the embedded image itself.
106    Picture {
107        caption: Option<String>,
108        image: Option<PictureImage>,
109        /// DocumentPictureClassifier predictions (all classes, descending
110        /// confidence), when the picture-classification enrichment ran.
111        /// Serialized as docling's `classification` annotation + `meta` field
112        /// on the JSON picture item; Markdown/DocLang output is unaffected.
113        classification: Option<Vec<PictureClass>>,
114    },
115    /// A display-math formula item decoded by the CodeFormula enrichment:
116    /// `latex` is the model's LaTeX (no `$$` wrapping), `orig` the raw glyph
117    /// text extracted from the PDF. Markdown renders `$$latex$$`; JSON emits a
118    /// `formula` text item (docling's un-enriched pipeline instead emits a
119    /// placeholder paragraph — see the PDF assembler).
120    Formula {
121        latex: String,
122        orig: String,
123        location: Option<[u16; 4]>,
124    },
125    /// A chart (docling's `PictureItem` classified as a chart, carrying a
126    /// `PictureTabularChartData` annotation). Markdown and JSON render it exactly
127    /// like a [`Node::Picture`] placeholder (an `<!-- image -->` / `picture`
128    /// item); the DocLang serializer emits `<picture class="chart">` with a
129    /// `<label value="{kind}"/>` and the data `table` as a `<tabular>`.
130    Chart {
131        /// docling's classification label, e.g. `bar_chart`, `line_chart`.
132        kind: String,
133        /// The chart's data grid (row 0 is the header band).
134        table: Table,
135        /// The chart title (docling's caption item on the picture).
136        caption: Option<String>,
137        /// DocLang `<location>` provenance for the picture element.
138        location: Option<[u16; 4]>,
139    },
140    /// A logical grouping of child nodes (e.g. a list, a section).
141    Group { label: String, children: Vec<Node> },
142    /// A form key-value region (docling's `field_region`): a set of form fields,
143    /// each pairing an optional marker, key, and value. Backends detect these
144    /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
145    /// `id`-convention); the serializers render each item's parts as separate
146    /// labelled texts (`marker` / `field_key` / `field_value`).
147    FieldRegion { items: Vec<FieldItem> },
148    /// Rich inline content — docling's `InlineGroup`: a run of styled text
149    /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
150    /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
151    /// flat Markdown text cannot represent. Markdown/JSON render this exactly
152    /// like `Paragraph { text: md_text }` (so their output is unchanged); the
153    /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
154    /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
155    InlineGroup {
156        unwrapped: bool,
157        runs: Vec<InlineRun>,
158        md_text: String,
159    },
160    /// A node in a non-body content layer — `furniture` (page headers/footers,
161    /// the HTML `<title>`, site navigation/chrome) or `notes` (docx comments).
162    /// Markdown and JSON omit these layers by default; DocLang renders the wrapped
163    /// node with a `<layer value="{layer}"/>` head.
164    Furniture {
165        layer: ContentLayer,
166        inner: Box<Node>,
167    },
168    /// A node carrying layout provenance — the four DocLang `<location>` values
169    /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
170    /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
171    /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
172    /// tokens as the element's first children.
173    Located {
174        location: [u16; 4],
175        inner: Box<Node>,
176    },
177    /// A PDF page header or footer (docling's `page_header`/`page_footer`
178    /// furniture): DocLang emits `<page_header>`/`<page_footer>` with a
179    /// `<layer value="furniture"/>` head, the four `<location>` tokens, then the
180    /// text. Markdown and JSON omit it like other furniture.
181    PageFurniture {
182        footer: bool,
183        location: [u16; 4],
184        text: String,
185    },
186    /// A page boundary — docling's implicit page break between pages. The PPTX
187    /// backend emits one between consecutive slides. DocLang renders it as
188    /// `<page_break/>`; Markdown and JSON omit it (matching docling's default
189    /// exports, which carry page breaks only in the document model).
190    PageBreak,
191    /// An invisible page marker — the first node of every page the PDF paths
192    /// assemble: the 1-based page number and the page size in PDF points. It
193    /// carries exactly what the JSON export needs to populate docling's
194    /// `pages` map and to denormalize the 0–511 `<location>` grid back into
195    /// BOTTOMLEFT point bboxes for per-item `prov` (#171). Every other
196    /// serializer skips it, so Markdown / DocLang / DocTags output is
197    /// byte-for-byte unchanged.
198    PageInfo {
199        /// 1-based page number (0 = "not yet numbered": the assembler emits
200        /// the marker, the document-level collector stamps the real number).
201        page_no: usize,
202        /// Page width in PDF points.
203        width: f32,
204        /// Page height in PDF points.
205        height: f32,
206    },
207    /// A node docling keeps in the document model (and DocLang) but leaves out
208    /// of the Markdown and JSON exports — e.g. an ODF *presentation*'s pictures
209    /// and charts, which appear in the `.dclx` body but not in its `.md`/`.json`.
210    /// DocLang renders the wrapped node in place; Markdown and JSON skip it.
211    DoclangOnly(Box<Node>),
212    /// A verbatim plain-text dump — docling's plain-text backend emits the whole
213    /// file as a single text item (used for legacy USPTO APS `.txt` grants, which
214    /// docling routes to plain text rather than its APS parser). The stored string
215    /// is the file body, one record per line. Markdown/JSON render it as one text
216    /// block; the DocLang serializer reproduces minidom's per-line layout, CDATA-
217    /// escaping only the lines that need it (see `emit_text_dump`).
218    TextDump(String),
219}
220
221/// Vertical text position of an [`InlineRun`] — docling's `Script`.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
223pub enum Script {
224    #[default]
225    Baseline,
226    Sub,
227    Super,
228}
229
230/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
231/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
232/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
233/// source text node). A hyperlink is intentionally not stored: DocLang drops the
234/// target inside inline scope, keeping only the anchor text.
235#[derive(Debug, Clone, PartialEq, Eq, Default)]
236pub struct InlineRun {
237    pub text: String,
238    pub bold: bool,
239    pub italic: bool,
240    pub underline: bool,
241    pub strike: bool,
242    pub script: Script,
243    pub code: bool,
244    /// An inline equation (`text` holds LaTeX): DocLang renders `<formula>…`,
245    /// Markdown/JSON keep the `$…$` already baked into the group's `md_text`.
246    pub formula: bool,
247}
248
249/// A DocLang content layer other than the default `body` (see [`Node::Furniture`]).
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum ContentLayer {
252    /// Page headers/footers, HTML `<title>`, site navigation/chrome.
253    Furniture,
254    /// Editorial notes (docx reviewer comments).
255    Notes,
256    /// Invisible content (hidden spreadsheet sheets).
257    Invisible,
258}
259
260impl ContentLayer {
261    /// The `<layer value="…"/>` token value.
262    pub fn value(self) -> &'static str {
263        match self {
264            ContentLayer::Furniture => "furniture",
265            ContentLayer::Notes => "notes",
266            ContentLayer::Invisible => "invisible",
267        }
268    }
269}
270
271/// DocLang-only content for a [`Node::ListItem`] whose DocLang form differs from
272/// its flat Markdown `text` (see [`Node::ListItem::dclx`]). `ordered` picks the
273/// enclosing `<list>` kind, `marker` the `<ldiv><marker>`; content is `runs`
274/// (structured equations/formatting) when non-empty, else `text` re-parsed for
275/// inline markers.
276#[derive(Debug, Clone, PartialEq, Eq, Default)]
277pub struct ListItemDclx {
278    pub ordered: bool,
279    pub marker: Option<String>,
280    pub text: String,
281    pub runs: Vec<InlineRun>,
282}
283
284impl InlineRun {
285    /// A run with no active formatting (renders as bare inline text).
286    pub fn is_plain(&self) -> bool {
287        !self.bold
288            && !self.italic
289            && !self.underline
290            && !self.strike
291            && !self.code
292            && !self.formula
293            && self.script == Script::Baseline
294    }
295}
296
297/// Build the [`Node`] for a paragraph of inline content from its structured
298/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
299///
300/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
301///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
302/// * a single uniformly-formatted run, or two or more runs → a
303///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
304///   heading, so no enclosing `<text>`) only applies to multi-run groups.
305///
306/// Markdown/JSON render the group's `md_text`, so their output is identical to
307/// emitting a `Paragraph` — the structured runs are DocLang-only.
308pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
309    let single_plain = runs.len() <= 1 && runs.first().is_none_or(|r| r.is_plain());
310    if single_plain {
311        Node::Paragraph { text: md_text }
312    } else {
313        Node::InlineGroup {
314            unwrapped: unwrapped && runs.len() >= 2,
315            runs,
316            md_text,
317        }
318    }
319}
320
321/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
322/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
323/// / `field_value` child texts.
324#[derive(Debug, Clone, PartialEq, Default)]
325pub struct FieldItem {
326    pub marker: Option<String>,
327    pub key: Option<String>,
328    pub value: Option<String>,
329}
330
331/// One DocumentPictureClassifier prediction — docling-core's
332/// `PictureClassificationClass` (`class_name` + `confidence`).
333#[derive(Debug, Clone, PartialEq)]
334pub struct PictureClass {
335    /// e.g. `bar_chart`, `logo`, `signature` (the classifier's 26-label set).
336    pub class_name: String,
337    pub confidence: f32,
338}
339
340/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
341/// the docling.rs analogue of docling-core's `ImageRef`.
342#[derive(Debug, Clone, PartialEq)]
343pub struct PictureImage {
344    /// e.g. `image/png`, `image/jpeg`.
345    pub mimetype: String,
346    pub width: u32,
347    pub height: u32,
348    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
349    pub data: Vec<u8>,
350}
351
352impl PictureImage {
353    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
354    pub fn data_uri(&self) -> String {
355        format!(
356            "data:{};base64,{}",
357            self.mimetype,
358            crate::base64::encode(&self.data)
359        )
360    }
361}
362
363/// A simple row-major table. By default `rows[0]` is the header row; a
364/// [`TableStructure`] overlay overrides that and adds column spans.
365#[derive(Debug, Clone, PartialEq, Default)]
366pub struct Table {
367    pub rows: Vec<Vec<String>>,
368    /// Optional layout provenance: the four DocLang `<location>` values
369    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
370    /// before the table's cells. Set only by backends with real geometry (e.g.
371    /// the spreadsheet backend, whose cell grid yields a bounding box); left
372    /// `None` by declarative backends, which have no coordinates.
373    pub location: Option<[u16; 4]>,
374    /// Optional OTSL structure overlay for backends that parse real table
375    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
376    /// continuations. `None` → the default (row 0 is the header, no spans).
377    /// `rows` still carries the full text grid (span text replicated) for
378    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
379    pub structure: Option<TableStructure>,
380    /// Optional per-cell block content, parallel to `rows`. A *rich* cell (an
381    /// ODF cell holding a list, several paragraphs, or a nested table) carries
382    /// its DocLang blocks here; the DocLang serializer emits them after the
383    /// cell token instead of the flat `rows` text. Markdown/JSON ignore this
384    /// and render `rows`, so their output is unchanged. `None` (or an empty
385    /// `Vec` for a given cell) → the flat text is used everywhere.
386    pub cell_blocks: Option<Vec<Vec<Vec<Node>>>>,
387    /// Optional caption (docling's `TableItem.captions`): the JATS
388    /// `<table-wrap>` label+caption, an HTML `<caption>`, etc. Markdown renders
389    /// it as a text line *before* the grid; JSON emits a caption text item the
390    /// table references; DocLang emits a `<caption>` as the table's first child.
391    /// `None` → the table has no caption.
392    pub caption: Option<String>,
393}
394
395/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
396#[derive(Debug, Clone, PartialEq, Default)]
397pub struct TableStructure {
398    /// Per-row: `true` if the row's non-empty cells are column headers
399    /// (emitted as `<ched/>` rather than `<fcel/>`).
400    pub header_row: Vec<bool>,
401    /// Same shape as [`Table::rows`]; `true` where a cell continues a
402    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
403    pub col_continuation: Vec<Vec<bool>>,
404    /// Same shape as [`Table::rows`]; `true` where a cell continues a
405    /// vertical span from the cell above (emitted as `<ucel/>`). Empty or all
406    /// `false` when the backend has no vertical spans (e.g. USPTO CALS).
407    pub row_continuation: Vec<Vec<bool>>,
408    /// Same shape as [`Table::rows`]; `true` where a non-empty cell is a row
409    /// header (emitted as `<rhed/>`) — a chart's category column. Empty when
410    /// the table has no row headers.
411    pub row_header: Vec<Vec<bool>>,
412    /// Same shape as [`Table::rows`]; `true` where a cell is a *column header*
413    /// cell (an HTML `<th>`). When non-empty this per-cell grid supersedes the
414    /// per-row [`Self::header_row`] for `<ched/>` emission, matching docling's
415    /// cell-level `column_header` flag; the chunker derives its header-row
416    /// count from it.
417    pub col_header: Vec<Vec<bool>>,
418}
419
420impl DoclingDocument {
421    /// Create an empty document with the given name.
422    pub fn new(name: impl Into<String>) -> Self {
423        Self {
424            name: name.into(),
425            nodes: Vec::new(),
426            strict_markdown: false,
427            compact_tables: false,
428            links: Vec::new(),
429            confidence: None,
430        }
431    }
432
433    /// Append a node.
434    pub fn push(&mut self, node: Node) {
435        self.nodes.push(node);
436    }
437
438    /// Convenience: append a heading.
439    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
440        self.push(Node::Heading {
441            level,
442            text: text.into(),
443        });
444    }
445
446    /// Convenience: append a paragraph.
447    pub fn add_paragraph(&mut self, text: impl Into<String>) {
448        self.push(Node::Paragraph { text: text.into() });
449    }
450
451    /// Serialize the document to Markdown.
452    ///
453    /// The Rust equivalent of docling-core's
454    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
455    /// pick between docling-legacy output (default) and the cleaner, more
456    /// conformant variant.
457    pub fn export_to_markdown(&self) -> String {
458        to_markdown(self, self.strict_markdown)
459    }
460
461    /// Serialize to Markdown, explicitly choosing the mode regardless of
462    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
463    /// conformant Markdown (code-fence languages preserved, no inline-run
464    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
465    pub fn export_to_markdown_with(&self, strict: bool) -> String {
466        to_markdown(self, strict)
467    }
468
469    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
470    /// schema), pretty-printed — the Rust equivalent of
471    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
472    /// back into Python docling-core and round-trips to the same Markdown.
473    pub fn export_to_json(&self) -> String {
474        serde_json::to_string_pretty(&self.export_to_json_value())
475            .expect("DoclingDocument JSON is always serializable")
476    }
477
478    /// The same JSON wire format as [`Self::export_to_json`], as a
479    /// `serde_json::Value` — for callers that append response-level extras
480    /// (docling-serve adds the confidence report, #183) before serializing.
481    pub fn export_to_json_value(&self) -> serde_json::Value {
482        crate::json::to_json(self)
483    }
484
485    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
486    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
487    /// `export_to_doclang()` with default parameters. No trailing newline; the
488    /// archive writer appends exactly one.
489    pub fn export_to_doclang(&self) -> String {
490        crate::doclang::export_to_doclang(&self.nodes)
491    }
492
493    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
494    /// docling's `image_mode`). Returns the Markdown and, for
495    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
496    /// caller should write next to the Markdown file. `artifacts_dir` is the
497    /// directory name used in referenced links.
498    pub fn export_to_markdown_with_images(
499        &self,
500        image_mode: ImageMode,
501        artifacts_dir: &str,
502    ) -> (String, Vec<(String, Vec<u8>)>) {
503        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
504    }
505}