Skip to main content

deepdoc_core/
model.rs

1//! The `Document` IR — the format-neutral model every extractor produces and
2//! every renderer consumes.
3//!
4//! Deliberately modest: the goal is clean Markdown, not pixel-perfect layout.
5//! Anything that cannot be expressed here (fonts, colours, absolute positions)
6//! is intentionally dropped during extraction.
7
8use serde::{Deserialize, Serialize};
9
10use crate::detect::Format;
11
12/// A parsed document: metadata plus an ordered list of block-level elements.
13#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
14pub struct Document {
15    pub meta: Metadata,
16    pub blocks: Vec<Block>,
17}
18
19impl Document {
20    /// An empty document with the given metadata.
21    pub fn new(meta: Metadata) -> Self {
22        Self {
23            meta,
24            blocks: Vec::new(),
25        }
26    }
27
28    /// True when the document carries no extractable text at all.
29    ///
30    /// Used by the "looks like a scan, needs `--ocr`" heuristic (exit code 4).
31    pub fn is_empty(&self) -> bool {
32        self.blocks.iter().all(|b| b.plain_text().trim().is_empty())
33    }
34}
35
36/// Document-level metadata. Every field is optional — most formats supply only a subset.
37#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
38pub struct Metadata {
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub title: Option<String>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub author: Option<String>,
43    /// Creation date as found in the source, ISO-8601 when the format allows it.
44    /// Kept as a string on purpose: no date-time dependency in the core.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub created: Option<String>,
47    /// BCP-47 or ISO-639 language tag, as the source spelled it (`en`, `en-GB`).
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub language: Option<String>,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub publisher: Option<String>,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub page_count: Option<u32>,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub source_format: Option<Format>,
56    /// Path the document was read from, as given on the command line.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub source_path: Option<String>,
59}
60
61/// A block-level element.
62///
63/// `Paragraph` is a struct variant rather than the newtype the plan sketches:
64/// serde's internally-tagged representation cannot tag a newtype wrapping a
65/// sequence, and `Inline` is transparent over `Vec<Span>`.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67#[serde(tag = "type", rename_all = "snake_case")]
68pub enum Block {
69    Heading {
70        level: u8,
71        text: Inline,
72    },
73    Paragraph {
74        text: Inline,
75    },
76    List {
77        ordered: bool,
78        items: Vec<Vec<Block>>,
79    },
80    Table {
81        header: Option<Row>,
82        rows: Vec<Row>,
83    },
84    Code {
85        lang: Option<String>,
86        text: String,
87    },
88    /// Images carry alt text only — DeepDoc never extracts pixels (that is DeepThumb).
89    Image {
90        alt: Option<String>,
91    },
92    /// Page boundary marker; `page` is the number of the page that starts here.
93    PageBreak {
94        page: u32,
95    },
96}
97
98impl Block {
99    /// A paragraph of unstyled text — convenience for extractors and tests.
100    pub fn paragraph(text: impl Into<String>) -> Self {
101        Block::Paragraph {
102            text: Inline::text(text),
103        }
104    }
105
106    /// The block's text with all markup removed.
107    pub fn plain_text(&self) -> String {
108        match self {
109            Block::Heading { text, .. } | Block::Paragraph { text } => text.plain_text(),
110            Block::List { items, .. } => items
111                .iter()
112                .flat_map(|item| item.iter().map(Block::plain_text))
113                .collect::<Vec<_>>()
114                .join("\n"),
115            Block::Table { header, rows } => header
116                .iter()
117                .chain(rows.iter())
118                .map(Row::plain_text)
119                .collect::<Vec<_>>()
120                .join("\n"),
121            Block::Code { text, .. } => text.clone(),
122            Block::Image { alt } => alt.clone().unwrap_or_default(),
123            Block::PageBreak { .. } => String::new(),
124        }
125    }
126}
127
128/// A single table row.
129#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
130pub struct Row {
131    pub cells: Vec<Inline>,
132}
133
134impl Row {
135    pub fn new(cells: Vec<Inline>) -> Self {
136        Self { cells }
137    }
138
139    /// Build a row from plain strings — convenience for extractors and tests.
140    pub fn from_texts<I, S>(cells: I) -> Self
141    where
142        I: IntoIterator<Item = S>,
143        S: Into<String>,
144    {
145        Self::new(cells.into_iter().map(Inline::text).collect())
146    }
147
148    pub fn plain_text(&self) -> String {
149        self.cells
150            .iter()
151            .map(Inline::plain_text)
152            .collect::<Vec<_>>()
153            .join("\t")
154    }
155}
156
157/// Inline content: a sequence of spans.
158#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
159#[serde(transparent)]
160pub struct Inline {
161    pub spans: Vec<Span>,
162}
163
164impl Inline {
165    pub fn new(spans: Vec<Span>) -> Self {
166        Self { spans }
167    }
168
169    /// A single run of unstyled text.
170    pub fn text(text: impl Into<String>) -> Self {
171        Self::new(vec![Span::Text(text.into())])
172    }
173
174    pub fn is_empty(&self) -> bool {
175        self.spans.is_empty()
176    }
177
178    /// The inline content with all markup removed.
179    pub fn plain_text(&self) -> String {
180        let mut out = String::new();
181        for span in &self.spans {
182            span.write_plain_text(&mut out);
183        }
184        out
185    }
186}
187
188/// Inline markup. Kept minimal on purpose — bold, italic, code, links, breaks.
189///
190/// Adjacently tagged (`{"type": "text", "value": "…"}`) because the variants
191/// wrap strings and sequences, which serde's internal tagging cannot carry.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193#[serde(tag = "type", content = "value", rename_all = "snake_case")]
194pub enum Span {
195    Text(String),
196    Bold(Vec<Span>),
197    Italic(Vec<Span>),
198    Code(String),
199    Link { href: String, text: Vec<Span> },
200    LineBreak,
201}
202
203impl Span {
204    fn write_plain_text(&self, out: &mut String) {
205        match self {
206            Span::Text(text) | Span::Code(text) => out.push_str(text),
207            Span::Bold(spans) | Span::Italic(spans) | Span::Link { text: spans, .. } => {
208                for span in spans {
209                    span.write_plain_text(out);
210                }
211            }
212            Span::LineBreak => out.push('\n'),
213        }
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn plain_text_strips_nested_markup() {
223        let inline = Inline::new(vec![
224            Span::Text("a ".into()),
225            Span::Bold(vec![Span::Italic(vec![Span::Text("b".into())])]),
226            Span::Text(" ".into()),
227            Span::Link {
228                href: "https://example.com".into(),
229                text: vec![Span::Text("c".into())],
230            },
231        ]);
232        assert_eq!(inline.plain_text(), "a b c");
233    }
234
235    /// Every variant must survive a JSON round trip — serde's tagged
236    /// representations reject some shapes only at runtime.
237    #[test]
238    fn every_block_round_trips_through_json() {
239        let doc = Document {
240            meta: Metadata {
241                title: Some("Title".into()),
242                page_count: Some(2),
243                source_format: Some(Format::Pdf),
244                ..Metadata::default()
245            },
246            blocks: vec![
247                Block::Heading {
248                    level: 1,
249                    text: Inline::text("Heading"),
250                },
251                Block::Paragraph {
252                    text: Inline::new(vec![
253                        Span::Text("plain ".into()),
254                        Span::Bold(vec![Span::Text("bold".into())]),
255                        Span::Italic(vec![Span::Text("italic".into())]),
256                        Span::Code("code".into()),
257                        Span::Link {
258                            href: "https://example.com".into(),
259                            text: vec![Span::Text("link".into())],
260                        },
261                        Span::LineBreak,
262                    ]),
263                },
264                Block::List {
265                    ordered: true,
266                    items: vec![vec![Block::paragraph("item")]],
267                },
268                Block::Table {
269                    header: Some(Row::from_texts(["a", "b"])),
270                    rows: vec![Row::from_texts(["1", "2"])],
271                },
272                Block::Code {
273                    lang: Some("rust".into()),
274                    text: "fn main() {}".into(),
275                },
276                Block::Image {
277                    alt: Some("diagram".into()),
278                },
279                Block::PageBreak { page: 2 },
280            ],
281        };
282
283        let json = serde_json::to_string(&doc).expect("Document must serialize");
284        let back: Document = serde_json::from_str(&json).expect("Document must deserialize");
285        assert_eq!(doc, back);
286    }
287
288    #[test]
289    fn document_without_text_is_empty() {
290        let doc = Document {
291            meta: Metadata::default(),
292            blocks: vec![Block::PageBreak { page: 1 }, Block::paragraph("  ")],
293        };
294        assert!(doc.is_empty());
295    }
296}