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 single list item at the given nesting `level` (0 = top). For ordered
43    /// items, `number` is the display number (honoring the list's `start`); it
44    /// is unused for unordered items. `first_in_list` marks the first item of a
45    /// list so the serializer can blank-line-separate adjacent sibling lists.
46    ///
47    /// `marker` is the DocLang enumeration marker (`"1."`, `"1.1."`, …) when the
48    /// backend provides one — HTML and DOCX set it for enumerated items, so
49    /// DocLang emits `<ldiv><marker>…</marker></ldiv>`; Markdown and the other
50    /// declarative backends leave it `None`, giving a bare `<ldiv/>` (matching
51    /// docling, whose Markdown backend passes no marker).
52    ListItem {
53        ordered: bool,
54        number: u64,
55        first_in_list: bool,
56        text: String,
57        level: u8,
58        marker: Option<String>,
59    },
60    /// A fenced code block.
61    Code {
62        language: Option<String>,
63        text: String,
64    },
65    /// A table. The first row is treated as the header.
66    Table(Table),
67    /// A picture/figure, with an optional caption and (when a backend extracts
68    /// it) the embedded image itself.
69    Picture {
70        caption: Option<String>,
71        image: Option<PictureImage>,
72    },
73    /// A logical grouping of child nodes (e.g. a list, a section).
74    Group { label: String, children: Vec<Node> },
75    /// A form key-value region (docling's `field_region`): a set of form fields,
76    /// each pairing an optional marker, key, and value. Backends detect these
77    /// from form structure (e.g. HTML's `keyN` / `keyN_valueM` / `keyN_marker`
78    /// `id`-convention); the serializers render each item's parts as separate
79    /// labelled texts (`marker` / `field_key` / `field_value`).
80    FieldRegion { items: Vec<FieldItem> },
81    /// Rich inline content — docling's `InlineGroup`: a run of styled text
82    /// segments that a backend captured with formatting (`<bold>`, `<italic>`,
83    /// `<underline>`, `<strikethrough>`, sub/superscript, inline `<code>`) the
84    /// flat Markdown text cannot represent. Markdown/JSON render this exactly
85    /// like `Paragraph { text: md_text }` (so their output is unchanged); the
86    /// DocLang serializer uses the structured `runs`. `unwrapped` is set when the
87    /// group's docling parent is a heading/text (no enclosing `<text>` wrapper).
88    InlineGroup {
89        unwrapped: bool,
90        runs: Vec<InlineRun>,
91        md_text: String,
92    },
93    /// A node in docling's `furniture` content layer (page headers/footers, the
94    /// HTML `<title>`, …). Markdown and JSON omit furniture by default; DocLang
95    /// renders the wrapped node with a `<layer value="furniture"/>` head.
96    Furniture(Box<Node>),
97    /// A node carrying layout provenance — the four DocLang `<location>` values
98    /// (`x0,y0,x1,y1`, normalized to 0–511) docling attaches to elements from
99    /// backends with real geometry (e.g. the slide shapes in PPTX). Markdown and
100    /// JSON render the wrapped node unchanged; DocLang emits the `<location>`
101    /// tokens as the element's first children.
102    Located {
103        location: [u16; 4],
104        inner: Box<Node>,
105    },
106}
107
108/// Vertical text position of an [`InlineRun`] — docling's `Script`.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
110pub enum Script {
111    #[default]
112    Baseline,
113    Sub,
114    Super,
115}
116
117/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
118/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
119/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
120/// source text node). A hyperlink is intentionally not stored: DocLang drops the
121/// target inside inline scope, keeping only the anchor text.
122#[derive(Debug, Clone, PartialEq, Eq, Default)]
123pub struct InlineRun {
124    pub text: String,
125    pub bold: bool,
126    pub italic: bool,
127    pub underline: bool,
128    pub strike: bool,
129    pub script: Script,
130    pub code: bool,
131}
132
133impl InlineRun {
134    /// A run with no active formatting (renders as bare inline text).
135    pub fn is_plain(&self) -> bool {
136        !self.bold
137            && !self.italic
138            && !self.underline
139            && !self.strike
140            && !self.code
141            && self.script == Script::Baseline
142    }
143}
144
145/// Build the [`Node`] for a paragraph of inline content from its structured
146/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
147///
148/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
149///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
150/// * a single uniformly-formatted run, or two or more runs → a
151///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
152///   heading, so no enclosing `<text>`) only applies to multi-run groups.
153///
154/// Markdown/JSON render the group's `md_text`, so their output is identical to
155/// emitting a `Paragraph` — the structured runs are DocLang-only.
156pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
157    let single_plain = runs.len() <= 1 && runs.first().map_or(true, |r| r.is_plain());
158    if single_plain {
159        Node::Paragraph { text: md_text }
160    } else {
161        Node::InlineGroup {
162            unwrapped: unwrapped && runs.len() >= 2,
163            runs,
164            md_text,
165        }
166    }
167}
168
169/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
170/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
171/// / `field_value` child texts.
172#[derive(Debug, Clone, PartialEq, Default)]
173pub struct FieldItem {
174    pub marker: Option<String>,
175    pub key: Option<String>,
176    pub value: Option<String>,
177}
178
179/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
180/// the docling.rs analogue of docling-core's `ImageRef`.
181#[derive(Debug, Clone, PartialEq)]
182pub struct PictureImage {
183    /// e.g. `image/png`, `image/jpeg`.
184    pub mimetype: String,
185    pub width: u32,
186    pub height: u32,
187    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
188    pub data: Vec<u8>,
189}
190
191impl PictureImage {
192    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
193    pub fn data_uri(&self) -> String {
194        format!(
195            "data:{};base64,{}",
196            self.mimetype,
197            crate::base64::encode(&self.data)
198        )
199    }
200}
201
202/// A simple row-major table. By default `rows[0]` is the header row; a
203/// [`TableStructure`] overlay overrides that and adds column spans.
204#[derive(Debug, Clone, PartialEq, Default)]
205pub struct Table {
206    pub rows: Vec<Vec<String>>,
207    /// Optional layout provenance: the four DocLang `<location>` values
208    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
209    /// before the table's cells. Set only by backends with real geometry (e.g.
210    /// the spreadsheet backend, whose cell grid yields a bounding box); left
211    /// `None` by declarative backends, which have no coordinates.
212    pub location: Option<[u16; 4]>,
213    /// Optional OTSL structure overlay for backends that parse real table
214    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
215    /// continuations. `None` → the default (row 0 is the header, no spans).
216    /// `rows` still carries the full text grid (span text replicated) for
217    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
218    pub structure: Option<TableStructure>,
219}
220
221/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
222#[derive(Debug, Clone, PartialEq, Default)]
223pub struct TableStructure {
224    /// Per-row: `true` if the row's non-empty cells are column headers
225    /// (emitted as `<ched/>` rather than `<fcel/>`).
226    pub header_row: Vec<bool>,
227    /// Same shape as [`Table::rows`]; `true` where a cell continues a
228    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
229    pub col_continuation: Vec<Vec<bool>>,
230}
231
232impl DoclingDocument {
233    /// Create an empty document with the given name.
234    pub fn new(name: impl Into<String>) -> Self {
235        Self {
236            name: name.into(),
237            nodes: Vec::new(),
238            strict_markdown: false,
239            compact_tables: false,
240            links: Vec::new(),
241        }
242    }
243
244    /// Append a node.
245    pub fn push(&mut self, node: Node) {
246        self.nodes.push(node);
247    }
248
249    /// Convenience: append a heading.
250    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
251        self.push(Node::Heading {
252            level,
253            text: text.into(),
254        });
255    }
256
257    /// Convenience: append a paragraph.
258    pub fn add_paragraph(&mut self, text: impl Into<String>) {
259        self.push(Node::Paragraph { text: text.into() });
260    }
261
262    /// Serialize the document to Markdown.
263    ///
264    /// The Rust equivalent of docling-core's
265    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
266    /// pick between docling-legacy output (default) and the cleaner, more
267    /// conformant variant.
268    pub fn export_to_markdown(&self) -> String {
269        to_markdown(self, self.strict_markdown)
270    }
271
272    /// Serialize to Markdown, explicitly choosing the mode regardless of
273    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
274    /// conformant Markdown (code-fence languages preserved, no inline-run
275    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
276    pub fn export_to_markdown_with(&self, strict: bool) -> String {
277        to_markdown(self, strict)
278    }
279
280    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
281    /// schema), pretty-printed — the Rust equivalent of
282    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
283    /// back into Python docling-core and round-trips to the same Markdown.
284    pub fn export_to_json(&self) -> String {
285        serde_json::to_string_pretty(&crate::json::to_json(self))
286            .expect("DoclingDocument JSON is always serializable")
287    }
288
289    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
290    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
291    /// `export_to_doclang()` with default parameters. No trailing newline; the
292    /// archive writer appends exactly one.
293    pub fn export_to_doclang(&self) -> String {
294        crate::doclang::export_to_doclang(&self.nodes)
295    }
296
297    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
298    /// docling's `image_mode`). Returns the Markdown and, for
299    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
300    /// caller should write next to the Markdown file. `artifacts_dir` is the
301    /// directory name used in referenced links.
302    pub fn export_to_markdown_with_images(
303        &self,
304        image_mode: ImageMode,
305        artifacts_dir: &str,
306    ) -> (String, Vec<(String, Vec<u8>)>) {
307        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
308    }
309}