Skip to main content

deepdoc_core/extract/
mod.rs

1//! The `Extractor` trait and the registry that maps a [`Format`] onto one.
2//!
3//! Extraction is the single impure edge of the core: it reads files and parses
4//! them into a [`Document`]. Everything downstream (`render`, `chunk`) is pure.
5
6pub mod container;
7pub mod csv;
8pub mod epub;
9pub mod html;
10pub mod markdown;
11pub mod odf;
12pub mod ooxml;
13pub mod pdf;
14pub mod rtf;
15pub mod spreadsheet;
16pub mod text;
17pub mod xml;
18
19use std::path::Path;
20
21use crate::detect::{Format, Sniff};
22use crate::error::{Error, Result};
23use crate::model::Document;
24
25/// Options that influence extraction.
26#[derive(Debug, Clone, Default)]
27pub struct ExtractOpts {
28    /// Page subset to extract, for paginated formats (PDF). `None` = all pages.
29    pub pages: Option<PageRange>,
30}
31
32/// Anything that can turn a file of some format into a [`Document`].
33pub trait Extractor {
34    /// Stable name, used in logs and error messages.
35    fn name(&self) -> &'static str;
36
37    /// Whether this extractor handles the given file.
38    fn supports(&self, path: &Path, sniff: &Sniff) -> bool;
39
40    /// Read and parse the file. The impure edge.
41    fn extract(&self, path: &Path, opts: &ExtractOpts) -> Result<Document>;
42}
43
44/// Pick the extractor for a format, if one exists yet.
45///
46/// Formats without an implementation return `None`; the caller turns that into
47/// [`Error::NotImplemented`]. Phases 2–5 fill this table in.
48pub fn for_format(format: Format) -> Option<Box<dyn Extractor>> {
49    match format {
50        Format::Txt => Some(Box::new(text::TextExtractor)),
51        Format::Markdown => Some(Box::new(markdown::MarkdownExtractor)),
52        Format::Csv => Some(Box::new(csv::CsvExtractor)),
53        Format::Html => Some(Box::new(html::HtmlExtractor)),
54        Format::Rtf => Some(Box::new(rtf::RtfExtractor)),
55        Format::Docx => Some(Box::new(ooxml::docx::DocxExtractor)),
56        Format::Pptx => Some(Box::new(ooxml::pptx::PptxExtractor)),
57        Format::Odt | Format::Odp => Some(Box::new(odf::OdfExtractor)),
58        Format::Xlsx | Format::Ods => Some(Box::new(spreadsheet::SpreadsheetExtractor)),
59        Format::Epub => Some(Box::new(epub::EpubExtractor)),
60        Format::Pdf => Some(Box::new(pdf::PdfExtractor)),
61    }
62}
63
64/// Detect the format of `path` and extract it.
65pub fn extract_path(path: &Path, opts: &ExtractOpts) -> Result<Document> {
66    let format = crate::detect::detect_path(path)?;
67    let extractor = for_format(format).ok_or(Error::NotImplemented { format })?;
68
69    let doc = extractor.extract(path, opts)?;
70    if doc.is_empty() {
71        return Err(Error::NoText {
72            path: path.to_path_buf(),
73        });
74    }
75    Ok(doc)
76}
77
78/// A `--pages` selection: `1-10`, `3`, `2-`.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct PageRange {
81    /// First page, 1-based and inclusive.
82    pub start: u32,
83    /// Last page, inclusive. `None` means "to the end".
84    pub end: Option<u32>,
85}
86
87impl PageRange {
88    /// Parse a range as accepted by `--pages`.
89    pub fn parse(input: &str) -> Result<PageRange> {
90        let invalid = |message: &str| Error::InvalidPageRange {
91            input: input.to_string(),
92            message: message.to_string(),
93        };
94        let parse_page = |value: &str| {
95            value
96                .parse::<u32>()
97                .ok()
98                .filter(|n| *n > 0)
99                .ok_or_else(|| invalid("page numbers start at 1"))
100        };
101
102        let trimmed = input.trim();
103        let range = match trimmed.split_once('-') {
104            None => {
105                let page = parse_page(trimmed)?;
106                PageRange {
107                    start: page,
108                    end: Some(page),
109                }
110            }
111            Some((start, "")) => PageRange {
112                start: parse_page(start)?,
113                end: None,
114            },
115            Some(("", _)) => return Err(invalid("missing first page")),
116            Some((start, end)) => PageRange {
117                start: parse_page(start)?,
118                end: Some(parse_page(end)?),
119            },
120        };
121
122        if let Some(end) = range.end
123            && end < range.start
124        {
125            return Err(invalid("last page is before the first"));
126        }
127        Ok(range)
128    }
129
130    /// Whether a 1-based page number falls inside the range.
131    pub fn contains(&self, page: u32) -> bool {
132        page >= self.start && self.end.is_none_or(|end| page <= end)
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn parses_page_ranges() {
142        assert_eq!(
143            PageRange::parse("1-10").unwrap(),
144            PageRange {
145                start: 1,
146                end: Some(10)
147            }
148        );
149        assert_eq!(
150            PageRange::parse("3").unwrap(),
151            PageRange {
152                start: 3,
153                end: Some(3)
154            }
155        );
156        assert_eq!(
157            PageRange::parse("2-").unwrap(),
158            PageRange {
159                start: 2,
160                end: None
161            }
162        );
163    }
164
165    #[test]
166    fn rejects_bad_page_ranges() {
167        for input in ["0", "-5", "10-2", "abc", ""] {
168            assert!(
169                PageRange::parse(input).is_err(),
170                "{input:?} should not parse"
171            );
172        }
173    }
174
175    #[test]
176    fn range_membership() {
177        let range = PageRange::parse("2-4").unwrap();
178        assert!(!range.contains(1));
179        assert!(range.contains(2) && range.contains(4));
180        assert!(!range.contains(5));
181
182        let open = PageRange::parse("2-").unwrap();
183        assert!(open.contains(9_999));
184    }
185
186    #[test]
187    fn every_known_format_has_an_extractor() {
188        for format in Format::ALL {
189            assert!(for_format(format).is_some(), "{format} has no extractor");
190        }
191    }
192}