Skip to main content

fleischwolf_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    ListItem {
47        ordered: bool,
48        number: u64,
49        first_in_list: bool,
50        text: String,
51        level: u8,
52    },
53    /// A fenced code block.
54    Code {
55        language: Option<String>,
56        text: String,
57    },
58    /// A table. The first row is treated as the header.
59    Table(Table),
60    /// A picture/figure, with an optional caption and (when a backend extracts
61    /// it) the embedded image itself.
62    Picture {
63        caption: Option<String>,
64        image: Option<PictureImage>,
65    },
66    /// A logical grouping of child nodes (e.g. a list, a section).
67    Group { label: String, children: Vec<Node> },
68}
69
70/// An extracted picture's raw encoded bytes plus its mimetype and pixel size —
71/// the fleischwolf analogue of docling-core's `ImageRef`.
72#[derive(Debug, Clone, PartialEq)]
73pub struct PictureImage {
74    /// e.g. `image/png`, `image/jpeg`.
75    pub mimetype: String,
76    pub width: u32,
77    pub height: u32,
78    /// The image file bytes, exactly as embedded (PNG/JPEG/…).
79    pub data: Vec<u8>,
80}
81
82impl PictureImage {
83    /// A `data:` URI for the image (`data:<mimetype>;base64,<…>`).
84    pub fn data_uri(&self) -> String {
85        format!(
86            "data:{};base64,{}",
87            self.mimetype,
88            crate::base64::encode(&self.data)
89        )
90    }
91}
92
93/// A simple row-major table. `rows[0]` is the header row.
94#[derive(Debug, Clone, PartialEq)]
95pub struct Table {
96    pub rows: Vec<Vec<String>>,
97}
98
99impl DoclingDocument {
100    /// Create an empty document with the given name.
101    pub fn new(name: impl Into<String>) -> Self {
102        Self {
103            name: name.into(),
104            nodes: Vec::new(),
105            strict_markdown: false,
106            compact_tables: false,
107            links: Vec::new(),
108        }
109    }
110
111    /// Append a node.
112    pub fn push(&mut self, node: Node) {
113        self.nodes.push(node);
114    }
115
116    /// Convenience: append a heading.
117    pub fn add_heading(&mut self, level: u8, text: impl Into<String>) {
118        self.push(Node::Heading {
119            level,
120            text: text.into(),
121        });
122    }
123
124    /// Convenience: append a paragraph.
125    pub fn add_paragraph(&mut self, text: impl Into<String>) {
126        self.push(Node::Paragraph { text: text.into() });
127    }
128
129    /// Serialize the document to Markdown.
130    ///
131    /// The Rust equivalent of docling-core's
132    /// `DoclingDocument.export_to_markdown()`. Uses [`Self::strict_markdown`] to
133    /// pick between docling-legacy output (default) and the cleaner, more
134    /// conformant variant.
135    pub fn export_to_markdown(&self) -> String {
136        to_markdown(self, self.strict_markdown)
137    }
138
139    /// Serialize to Markdown, explicitly choosing the mode regardless of
140    /// [`Self::strict_markdown`]. `strict = true` produces cleaner, more
141    /// conformant Markdown (code-fence languages preserved, no inline-run
142    /// spacing artifacts); `strict = false` reproduces docling's legacy output.
143    pub fn export_to_markdown_with(&self, strict: bool) -> String {
144        to_markdown(self, strict)
145    }
146
147    /// Serialize to docling-core's native JSON wire format (`DoclingDocument`
148    /// schema), pretty-printed — the Rust equivalent of
149    /// `DoclingDocument.export_to_dict()` / `save_as_json()`. The output loads
150    /// back into Python docling-core and round-trips to the same Markdown.
151    pub fn export_to_json(&self) -> String {
152        serde_json::to_string_pretty(&crate::json::to_json(self))
153            .expect("DoclingDocument JSON is always serializable")
154    }
155
156    /// Serialize to Markdown with an explicit picture [`ImageMode`] (mirrors
157    /// docling's `image_mode`). Returns the Markdown and, for
158    /// [`ImageMode::Referenced`], the `(relative-path, bytes)` of each image the
159    /// caller should write next to the Markdown file. `artifacts_dir` is the
160    /// directory name used in referenced links.
161    pub fn export_to_markdown_with_images(
162        &self,
163        image_mode: ImageMode,
164        artifacts_dir: &str,
165    ) -> (String, Vec<(String, Vec<u8>)>) {
166        to_markdown_images(self, self.strict_markdown, image_mode, artifacts_dir)
167    }
168}