deepdoc_core/extract/
text.rs1use 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
46fn 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}