Skip to main content

deepdoc_core/extract/
text.rs

1//! Plain-text extractor — blank-line separated paragraphs.
2//!
3//! Minimal on purpose: it exists so the pipeline (`detect` → `extract` →
4//! `render`) is end-to-end runnable from day one. Phase 2 gives Markdown its
5//! own extractor and adds csv/html/rtf next to this one.
6
7use std::path::Path;
8
9use crate::detect::{Format, Sniff};
10use crate::error::{Error, Result};
11use crate::extract::{ExtractOpts, Extractor};
12use crate::model::{Block, Document, Metadata};
13
14pub struct TextExtractor;
15
16impl Extractor for TextExtractor {
17    fn name(&self) -> &'static str {
18        "text"
19    }
20
21    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
22        matches!(
23            crate::detect::detect(sniff),
24            Some(Format::Txt | Format::Markdown)
25        )
26    }
27
28    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
29        let raw = std::fs::read(path).map_err(|e| Error::io(path, e))?;
30        let text = String::from_utf8_lossy(&raw);
31
32        let format = crate::detect::detect_path(path).unwrap_or(Format::Txt);
33        let meta = Metadata {
34            source_format: Some(format),
35            source_path: Some(path.display().to_string()),
36            ..Metadata::default()
37        };
38
39        Ok(Document {
40            meta,
41            blocks: paragraphs(&text),
42        })
43    }
44}
45
46/// Split plain text into paragraphs on blank lines. Pure.
47fn paragraphs(text: &str) -> Vec<Block> {
48    text.split("\n\n")
49        .map(|chunk| chunk.trim())
50        .filter(|chunk| !chunk.is_empty())
51        .map(|chunk| Block::paragraph(chunk.replace("\r\n", "\n")))
52        .collect()
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn splits_on_blank_lines() {
61        let blocks = paragraphs("first line\nstill first\n\n\nsecond\n");
62        assert_eq!(
63            blocks,
64            vec![
65                Block::paragraph("first line\nstill first"),
66                Block::paragraph("second"),
67            ]
68        );
69    }
70
71    #[test]
72    fn empty_input_yields_no_blocks() {
73        assert!(paragraphs("   \n\n  ").is_empty());
74    }
75}