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}
98
99/// Vertical text position of an [`InlineRun`] — docling's `Script`.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101pub enum Script {
102    #[default]
103    Baseline,
104    Sub,
105    Super,
106}
107
108/// One styled segment of a [`Node::InlineGroup`] — the docling.rs analogue of a
109/// `TextItem` inside an `InlineGroup`, carrying the ancestor formatting docling
110/// tracks. `text` is already whitespace-normalized/trimmed (one segment per
111/// source text node). A hyperlink is intentionally not stored: DocLang drops the
112/// target inside inline scope, keeping only the anchor text.
113#[derive(Debug, Clone, PartialEq, Eq, Default)]
114pub struct InlineRun {
115    pub text: String,
116    pub bold: bool,
117    pub italic: bool,
118    pub underline: bool,
119    pub strike: bool,
120    pub script: Script,
121    pub code: bool,
122}
123
124impl InlineRun {
125    /// A run with no active formatting (renders as bare inline text).
126    pub fn is_plain(&self) -> bool {
127        !self.bold
128            && !self.italic
129            && !self.underline
130            && !self.strike
131            && !self.code
132            && self.script == Script::Baseline
133    }
134}
135
136/// Build the [`Node`] for a paragraph of inline content from its structured
137/// `runs` and Markdown text, applying docling's `InlineGroup` boundary:
138///
139/// * a single plain run (or none) → a plain [`Node::Paragraph`] (which the
140///   serializers render as `<text>…</text>`, and a lone hyperlink via `<href>`);
141/// * a single uniformly-formatted run, or two or more runs → a
142///   [`Node::InlineGroup`]. `unwrapped` (the group's docling parent is a
143///   heading, so no enclosing `<text>`) only applies to multi-run groups.
144///
145/// Markdown/JSON render the group's `md_text`, so their output is identical to
146/// emitting a `Paragraph` — the structured runs are DocLang-only.
147pub fn inline_paragraph_node(md_text: String, runs: Vec<InlineRun>, unwrapped: bool) -> Node {
148    let single_plain = runs.len() <= 1 && runs.first().map_or(true, |r| r.is_plain());
149    if single_plain {
150        Node::Paragraph { text: md_text }
151    } else {
152        Node::InlineGroup {
153            unwrapped: unwrapped && runs.len() >= 2,
154            runs,
155            md_text,
156        }
157    }
158}
159
160/// One entry of a [`Node::FieldRegion`]: a marker/key/value triple, any of which
161/// may be absent. Mirrors docling's `field_item` with its `marker` / `field_key`
162/// / `field_value` child texts.
163#[derive(Debug, Clone, PartialEq, Default)]
164pub struct FieldItem {
165    pub marker: Option<String>,
166    pub key: Option<String>,
167    pub value: Option<String>,
168}
169
170/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
171/// the docling.rs analogue of docling-core's `ImageRef`.
172#[derive(Debug, Clone, PartialEq)]
173pub struct PictureImage {
174    /// e.g. `image/png`, `image/jpeg`.
175    pub mimetype: String,
176    pub width: u32,
177    pub height: u32,
178    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
179    pub data: Vec<u8>,
180}
181
182impl PictureImage {
183    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
184    pub fn data_uri(&self) -> String {
185        format!(
186            "data:{};base64,{}",
187            self.mimetype,
188            crate::base64::encode(&self.data)
189        )
190    }
191}
192
193/// A simple row-major table. By default `rows[0]` is the header row; a
194/// [`TableStructure`] overlay overrides that and adds column spans.
195#[derive(Debug, Clone, PartialEq, Default)]
196pub struct Table {
197    pub rows: Vec<Vec<String>>,
198    /// Optional layout provenance: the four DocLang `<location>` values
199    /// (`x0,y0,x1,y1`, each already normalized to the 0–511 resolution) emitted
200    /// before the table's cells. Set only by backends with real geometry (e.g.
201    /// the spreadsheet backend, whose cell grid yields a bounding box); left
202    /// `None` by declarative backends, which have no coordinates.
203    pub location: Option<[u16; 4]>,
204    /// Optional OTSL structure overlay for backends that parse real table
205    /// geometry (USPTO CALS): explicit header-row count and horizontal-span
206    /// continuations. `None` → the default (row 0 is the header, no spans).
207    /// `rows` still carries the full text grid (span text replicated) for
208    /// Markdown/JSON; DocLang uses this overlay to emit `<ched/>`/`<lcel/>`.
209    pub structure: Option<TableStructure>,
210}
211
212/// OTSL structure overlay for a [`Table`], parallel to [`Table::rows`].
213#[derive(Debug, Clone, PartialEq, Default)]
214pub struct TableStructure {
215    /// Per-row: `true` if the row's non-empty cells are column headers
216    /// (emitted as `<ched/>` rather than `<fcel/>`).
217    pub header_row: Vec<bool>,
218    /// Same shape as [`Table::rows`]; `true` where a cell continues a
219    /// horizontal span from its left neighbour (emitted as `<lcel/>`).
220    pub col_continuation: Vec<Vec<bool>>,
221}
222
223impl DoclingDocument {
224    /// Create an empty document with the given name.
225    pub fn new(name: impl Into<String>) -> Self {
226        Self {
227            name: name.into(),
228            nodes: Vec::new(),
229            strict_markdown: false,
230            compact_tables: false,
231            links: Vec::new(),
232        }
233    }
234
235    /// Append a node.
236    pub fn push(&mut self, node: Node) {
237        self.nodes.push(node);
238    }
239
240    /// Convenience: append a heading.
241    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
242        self.push(Node::Heading {
243            level,
244            text: text.into(),
245        });
246    }
247
248    /// Convenience: append a paragraph.
249    pub fn add_paragraph(&mut self, text: impl Into<String>) {
250        self.push(Node::Paragraph { text: text.into() });
251    }
252
253    /// Serialize the document to Markdown.
254    ///
255    /// The Rust equivalent of docling-core's
256    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
257    /// pick between docling-legacy output (default) and the cleaner, more
258    /// conformant variant.
259    pub fn export_to_markdown(&self) -> String {
260        to_markdown(self, self.strict_markdown)
261    }
262
263    /// Serialize to Markdown, explicitly choosing the mode regardless of
264    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
265    /// conformant Markdown (code-fence languages preserved, no inline-run
266    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
267    pub fn export_to_markdown_with(&self, strict: bool) -> String {
268        to_markdown(self, strict)
269    }
270
271    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
272    /// schema), pretty-printed — the Rust equivalent of
273    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
274    /// back into Python docling-core and round-trips to the same Markdown.
275    pub fn export_to_json(&self) -> String {
276        serde_json::to_string_pretty(&crate::json::to_json(self))
277            .expect("DoclingDocument JSON is always serializable")
278    }
279
280    /// Serialize to DocLang XML (`<doclang version="0.7">…`), the markup that
281    /// lives inside a `.dclx` archive — the Rust counterpart of docling-core's
282    /// `export_to_doclang()` with default parameters. No trailing newline; the
283    /// archive writer appends exactly one.
284    pub fn export_to_doclang(&self) -> String {
285        crate::doclang::export_to_doclang(&self.nodes)
286    }
287
288    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
289    /// docling's `image_mode`). Returns the Markdown and, for
290    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
291    /// caller should write next to the Markdown file. `artifacts_dir` is the
292    /// directory name used in referenced links.
293    pub fn export_to_markdown_with_images(
294        &self,
295        image_mode: ImageMode,
296        artifacts_dir: &str,
297    ) -> (String, Vec<(String, Vec<u8>)>) {
298        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
299    }
300}