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