Skip to main content

graphrt_doc/
lib.rs

1//! # graphrt-doc
2//!
3//! Text extraction from documents, as a library ([`extract`]) and as the
4//! `document-extractor` workflow node ([`register`]).
5//!
6//! Everything is pure Rust. Formats and the features that enable them:
7//!
8//! | Format | Feature |
9//! | --- | --- |
10//! | txt, md, json, yaml, xml, csv, tsv, html, vtt, srt | always |
11//! | pdf | `pdf` |
12//! | docx, pptx | `office` |
13//! | xlsx, xls, ods | `spreadsheet` |
14//! | epub | `epub` |
15//! | eml | `email` |
16//!
17//! The format is chosen from the MIME type, then the file extension, then the
18//! content itself. Archives are read with entry-count and decompressed-size
19//! limits (zip-bomb protection), and parsers that are known to panic on
20//! malformed input are isolated with `catch_unwind` (effective only in builds
21//! that unwind on panic).
22
23use serde::{Deserialize, Serialize};
24
25mod binary;
26pub mod detect;
27mod node;
28#[cfg(feature = "pdf")]
29mod pdf_budget;
30pub mod text;
31#[cfg(feature = "zip-formats")]
32mod zipfmt;
33
34pub use detect::Format;
35pub use node::{DocLimits, DocumentExtractorNode, KIND, descriptor, register};
36
37/// Shape of the extracted text.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "lowercase")]
40pub enum OutputFormat {
41    /// Plain text; tables become tab-separated lines.
42    #[default]
43    Text,
44    /// Markdown; tables become Markdown tables, headings keep their level.
45    Markdown,
46}
47
48/// Extraction options and limits.
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Options {
51    pub format: OutputFormat,
52    /// Output longer than this many characters is truncated.
53    pub max_output_chars: usize,
54    /// Maximum PDF pages, presentation slides or EPUB chapters.
55    pub max_pages: usize,
56    /// Maximum spreadsheet sheets.
57    pub max_sheets: usize,
58    /// Maximum rows per spreadsheet sheet (and per CSV/TSV file).
59    pub max_rows: usize,
60    /// Maximum columns of any table (spreadsheet sheet, CSV/TSV, DOCX table).
61    pub max_cols: usize,
62    /// Maximum non-empty cells across a spreadsheet sheet. Spreadsheets whose
63    /// used range would exceed this are rejected before they are loaded.
64    pub max_cells: usize,
65    /// Maximum entries in a zip container.
66    pub max_zip_entries: usize,
67    /// Maximum total decompressed bytes read from a zip container.
68    pub max_decompressed_bytes: u64,
69}
70
71impl Default for Options {
72    fn default() -> Self {
73        Self {
74            format: OutputFormat::Text,
75            max_output_chars: 5_000_000,
76            max_pages: 2_000,
77            max_sheets: 100,
78            max_rows: 200_000,
79            max_cols: 2_048,
80            max_cells: 2_000_000,
81            max_zip_entries: 10_000,
82            max_decompressed_bytes: 256 * 1024 * 1024,
83        }
84    }
85}
86
87impl Options {
88    pub fn with_format(mut self, format: OutputFormat) -> Self {
89        self.format = format;
90        self
91    }
92
93    pub fn with_max_output_chars(mut self, max: usize) -> Self {
94        self.max_output_chars = max;
95        self
96    }
97}
98
99/// Extraction failure.
100#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
101#[non_exhaustive]
102pub enum DocError {
103    /// The content type could not be identified or is not a document format.
104    #[error("unsupported document format: {detected}")]
105    Unsupported { detected: String },
106    /// The format is known but its cargo feature is not enabled in this build.
107    #[error("{format} documents are not supported by this build (enable the `{feature}` feature)")]
108    FeatureDisabled { format: Format, feature: &'static str },
109    /// The document could not be parsed.
110    #[error("malformed {format} document: {message}")]
111    Malformed { format: String, message: String },
112    /// A size limit was exceeded.
113    #[error("document exceeds limits: {0}")]
114    LimitExceeded(String),
115}
116
117impl DocError {
118    #[cfg_attr(
119        not(any(
120            feature = "pdf",
121            feature = "spreadsheet",
122            feature = "zip-formats",
123            feature = "email",
124            feature = "tokio"
125        )),
126        allow(dead_code)
127    )]
128    pub(crate) fn malformed(format: &str, err: impl std::fmt::Display) -> Self {
129        DocError::Malformed { format: format.to_owned(), message: err.to_string() }
130    }
131
132    /// Stable machine-readable category.
133    pub fn kind(&self) -> &'static str {
134        match self {
135            DocError::Unsupported { .. } | DocError::FeatureDisabled { .. } => "unsupported_format",
136            DocError::Malformed { .. } => "malformed_document",
137            DocError::LimitExceeded(_) => "limit_exceeded",
138        }
139    }
140}
141
142/// Result of [`extract_detailed`].
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct Extraction {
145    pub text: String,
146    pub format: Format,
147    /// Whether the text was cut at [`Options::max_output_chars`].
148    pub truncated: bool,
149}
150
151/// Extract the text of a document.
152///
153/// `mime` and `filename` are hints; either may be `None`. Text longer than
154/// [`Options::max_output_chars`] is cut; use [`extract_detailed`] to learn
155/// whether that happened.
156pub fn extract(bytes: &[u8], mime: Option<&str>, filename: Option<&str>, opts: &Options) -> Result<String, DocError> {
157    extract_detailed(bytes, mime, filename, opts).map(|e| e.text)
158}
159
160/// Like [`extract`], also reporting the detected format and truncation.
161pub fn extract_detailed(
162    bytes: &[u8],
163    mime: Option<&str>,
164    filename: Option<&str>,
165    opts: &Options,
166) -> Result<Extraction, DocError> {
167    let format = resolve_format(bytes, mime, filename, opts)?;
168    let text = extract_as(format, bytes, opts)?;
169    let (text, truncated) = truncate_chars(text, opts.max_output_chars);
170    Ok(Extraction { text, format, truncated })
171}
172
173/// Determine the format: MIME type, then extension, then content sniffing.
174pub fn resolve_format(
175    bytes: &[u8],
176    mime: Option<&str>,
177    filename: Option<&str>,
178    opts: &Options,
179) -> Result<Format, DocError> {
180    let claimed = mime
181        .and_then(detect::from_mime)
182        .or_else(|| filename.and_then(detect::extension).and_then(detect::from_extension));
183    if let Some(f) = claimed {
184        if !f.is_textual() {
185            return Ok(f);
186        }
187        // A text label on binary content (a PDF uploaded as text/plain, a zip named
188        // .txt) would otherwise "succeed" with garbage text.
189        if detect::sniff(bytes).is_some_and(|s| !s.is_textual()) || detect::is_zip(bytes) {
190            return sniffed_binary(bytes, opts);
191        }
192        if !bytes.is_empty() && !detect::looks_textual(bytes) {
193            return Err(DocError::Unsupported { detected: format!("binary data labelled as {f}") });
194        }
195        return Ok(f);
196    }
197    if let Some(f) = detect::sniff(bytes) {
198        if f == Format::Xls && !detect::ole_is_workbook(bytes) {
199            return Err(DocError::Unsupported {
200                detected: "legacy OLE document (.doc / .ppt / .msg) — only spreadsheets are supported".into(),
201            });
202        }
203        return Ok(f);
204    }
205    if detect::is_zip(bytes) {
206        #[cfg(feature = "zip-formats")]
207        if let Some(f) = zipfmt::identify(bytes, opts)? {
208            return Ok(f);
209        }
210        return Err(DocError::Unsupported { detected: "zip archive".into() });
211    }
212    let _ = opts;
213    if !bytes.is_empty() && detect::looks_textual(bytes) {
214        return Ok(Format::PlainText);
215    }
216    let detected = match (mime, filename.and_then(detect::extension)) {
217        (Some(m), _) => m.to_owned(),
218        (None, Some(ext)) => format!(".{ext}"),
219        (None, None) if bytes.is_empty() => "empty file".to_owned(),
220        (None, None) => "binary data".to_owned(),
221    };
222    Err(DocError::Unsupported { detected })
223}
224
225/// Resolve content that sniffing identified as binary, ignoring a text label.
226fn sniffed_binary(bytes: &[u8], opts: &Options) -> Result<Format, DocError> {
227    resolve_format(bytes, None, None, opts)
228}
229
230/// Extract text from bytes known to be in `format`.
231pub fn extract_as(format: Format, bytes: &[u8], opts: &Options) -> Result<String, DocError> {
232    #[allow(unused_variables)]
233    let disabled = |feature: &'static str| DocError::FeatureDisabled { format, feature };
234    match format {
235        Format::PlainText | Format::Markdown | Format::Json | Format::Yaml | Format::Xml => {
236            Ok(text::decode(bytes).trim_end().to_owned())
237        }
238        Format::Csv | Format::Tsv => {
239            let delimiter = if format == Format::Csv { ',' } else { '\t' };
240            let rows = text::parse_delimited(&text::decode(bytes), delimiter);
241            if rows.len() > opts.max_rows {
242                return Err(DocError::LimitExceeded(format!("{} rows (limit {})", rows.len(), opts.max_rows)));
243            }
244            text::render_table(&rows, opts)
245        }
246        Format::Html => Ok(text::html_to_text(&text::decode(bytes), opts.format)),
247        Format::Vtt | Format::Srt => Ok(text::subtitles(&text::decode(bytes))),
248        Format::Pdf => {
249            #[cfg(feature = "pdf")]
250            return binary::pdf(bytes, opts);
251            #[cfg(not(feature = "pdf"))]
252            return Err(disabled("pdf"));
253        }
254        Format::Docx => {
255            #[cfg(feature = "office")]
256            return zipfmt::docx(bytes, opts);
257            #[cfg(not(feature = "office"))]
258            return Err(disabled("office"));
259        }
260        Format::Pptx => {
261            #[cfg(feature = "office")]
262            return zipfmt::pptx(bytes, opts);
263            #[cfg(not(feature = "office"))]
264            return Err(disabled("office"));
265        }
266        Format::Epub => {
267            #[cfg(feature = "epub")]
268            return zipfmt::epub(bytes, opts);
269            #[cfg(not(feature = "epub"))]
270            return Err(disabled("epub"));
271        }
272        Format::Xlsx | Format::Xls | Format::Ods => {
273            #[cfg(feature = "spreadsheet")]
274            return binary::spreadsheet(bytes, format, opts);
275            #[cfg(not(feature = "spreadsheet"))]
276            return Err(disabled("spreadsheet"));
277        }
278        Format::Eml => {
279            #[cfg(feature = "email")]
280            return binary::email(bytes, opts);
281            #[cfg(not(feature = "email"))]
282            return Err(disabled("email"));
283        }
284    }
285}
286
287/// Cut `text` to at most `max` characters (on a char boundary).
288fn truncate_chars(mut text: String, max: usize) -> (String, bool) {
289    match text.char_indices().nth(max) {
290        Some((byte_index, _)) => {
291            text.truncate(byte_index);
292            (text, true)
293        }
294        None => (text, false),
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn truncation_respects_char_boundaries() {
304        let (t, cut) = truncate_chars("héllo".to_owned(), 2);
305        assert_eq!((t.as_str(), cut), ("hé", true));
306        let (t, cut) = truncate_chars("hi".to_owned(), 2);
307        assert_eq!((t.as_str(), cut), ("hi", false));
308    }
309
310    #[test]
311    fn format_resolution_order() {
312        let opts = Options::default();
313        // MIME wins over extension.
314        assert_eq!(resolve_format(b"x", Some("text/csv"), Some("a.json"), &opts), Ok(Format::Csv));
315        // Generic MIME falls through to the extension.
316        assert_eq!(resolve_format(b"x", Some("application/octet-stream"), Some("a.md"), &opts), Ok(Format::Markdown));
317        // Sniffing, then plain-text fallback.
318        assert_eq!(resolve_format(b"%PDF-1.7", None, None, &opts), Ok(Format::Pdf));
319        assert_eq!(resolve_format(b"just words", None, None, &opts), Ok(Format::PlainText));
320        assert!(matches!(resolve_format(&[0, 1, 2, 3], None, Some("x.bin"), &opts), Err(DocError::Unsupported { .. })));
321    }
322
323    #[test]
324    fn csv_markdown_and_text() {
325        let csv = b"name,qty\napple,3\n";
326        let md = extract(csv, Some("text/csv"), None, &Options::default().with_format(OutputFormat::Markdown));
327        assert_eq!(md.as_deref(), Ok("| name | qty |\n| --- | --- |\n| apple | 3 |"));
328        let txt = extract(csv, None, Some("f.csv"), &Options::default());
329        assert_eq!(txt.as_deref(), Ok("name\tqty\napple\t3"));
330    }
331}