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