1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "lowercase")]
40pub enum OutputFormat {
41 #[default]
43 Text,
44 Markdown,
46}
47
48#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Options {
51 pub format: OutputFormat,
52 pub max_output_chars: usize,
54 pub max_pages: usize,
56 pub max_sheets: usize,
58 pub max_rows: usize,
60 pub max_cols: usize,
62 pub max_cells: usize,
65 pub max_zip_entries: usize,
67 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
101#[non_exhaustive]
102pub enum DocError {
103 #[error("unsupported document format: {detected}")]
105 Unsupported { detected: String },
106 #[error("{format} documents are not supported by this build (enable the `{feature}` feature)")]
108 FeatureDisabled { format: Format, feature: &'static str },
109 #[error("malformed {format} document: {message}")]
111 Malformed { format: String, message: String },
112 #[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 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#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct Extraction {
145 pub text: String,
146 pub format: Format,
147 pub truncated: bool,
149}
150
151pub 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
160pub 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
173pub 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 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
225fn sniffed_binary(bytes: &[u8], opts: &Options) -> Result<Format, DocError> {
227 resolve_format(bytes, None, None, opts)
228}
229
230pub 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
287fn 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 assert_eq!(resolve_format(b"x", Some("text/csv"), Some("a.json"), &opts), Ok(Format::Csv));
315 assert_eq!(resolve_format(b"x", Some("application/octet-stream"), Some("a.md"), &opts), Ok(Format::Markdown));
317 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}