Skip to main content

memvid_core/reader/
pptx.rs

1use std::io::{Cursor, Read};
2
3use quick_xml::Reader as XmlReader;
4use quick_xml::events::Event;
5use zip::ZipArchive;
6
7use crate::{
8    DocumentFormat, DocumentReader, PassthroughReader, ReaderDiagnostics, ReaderHint, ReaderOutput,
9    Result,
10};
11
12const SLIDE_PREFIX: &str = "ppt/slides/slide";
13const SLIDE_SUFFIX: &str = ".xml";
14
15pub struct PptxReader;
16
17impl PptxReader {
18    fn extract_text(bytes: &[u8]) -> Result<String> {
19        let cursor = Cursor::new(bytes);
20        let mut archive =
21            ZipArchive::new(cursor).map_err(|err| crate::MemvidError::ExtractionFailed {
22                reason: format!("failed to open pptx archive: {err}").into(),
23            })?;
24
25        let mut slides: Vec<String> = Vec::new();
26        for i in 1..=archive.len() {
27            let name = format!("{SLIDE_PREFIX}{i}{SLIDE_SUFFIX}");
28            if let Ok(mut file) = archive.by_name(&name) {
29                let mut xml = String::new();
30                file.read_to_string(&mut xml).map_err(|err| {
31                    crate::MemvidError::ExtractionFailed {
32                        reason: format!("failed to read {name}: {err}").into(),
33                    }
34                })?;
35                slides.push(xml);
36            }
37        }
38
39        if slides.is_empty() {
40            return Ok(String::new());
41        }
42
43        let mut out = String::new();
44        for (idx, xml) in slides.iter().enumerate() {
45            if idx > 0 {
46                out.push_str("\n\n");
47            }
48            out.push_str(&format!("Slide {}:\n", idx + 1));
49            out.push_str(&extract_plain_text(xml, b"p"));
50        }
51
52        Ok(out.trim().to_string())
53    }
54}
55
56impl DocumentReader for PptxReader {
57    fn name(&self) -> &'static str {
58        "pptx"
59    }
60
61    fn supports(&self, hint: &ReaderHint<'_>) -> bool {
62        matches!(hint.format, Some(DocumentFormat::Pptx))
63            || hint.mime.is_some_and(|mime| {
64                mime.eq_ignore_ascii_case(
65                    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
66                )
67            })
68    }
69
70    fn extract(&self, bytes: &[u8], hint: &ReaderHint<'_>) -> Result<ReaderOutput> {
71        match Self::extract_text(bytes) {
72            Ok(text) => {
73                if text.trim().is_empty() {
74                    // quick-xml returned empty - try extractous as fallback
75                    let mut fallback = PassthroughReader.extract(bytes, hint)?;
76                    fallback.reader_name = self.name().to_string();
77                    fallback.diagnostics.mark_fallback();
78                    fallback.diagnostics.record_warning(
79                        "pptx reader produced empty text; falling back to default extractor",
80                    );
81                    Ok(fallback)
82                } else {
83                    // quick-xml succeeded - build output directly WITHOUT calling extractous
84                    let mut document = crate::ExtractedDocument::empty();
85                    document.text = Some(text);
86                    document.mime_type = Some(
87                        "application/vnd.openxmlformats-officedocument.presentationml.presentation"
88                            .to_string(),
89                    );
90                    Ok(ReaderOutput::new(document, self.name())
91                        .with_diagnostics(ReaderDiagnostics::default()))
92                }
93            }
94            Err(err) => {
95                // quick-xml failed - try extractous as fallback
96                let mut fallback = PassthroughReader.extract(bytes, hint)?;
97                fallback.reader_name = self.name().to_string();
98                fallback.diagnostics.mark_fallback();
99                fallback
100                    .diagnostics
101                    .record_warning(format!("pptx reader error: {err}"));
102                Ok(fallback)
103            }
104        }
105    }
106}
107
108fn extract_plain_text(xml: &str, block_suffix: &[u8]) -> String {
109    let mut reader = XmlReader::from_str(xml);
110    reader.trim_text(true);
111    let mut buf = Vec::new();
112    let mut text = String::new();
113    let mut first_block = true;
114
115    loop {
116        match reader.read_event_into(&mut buf) {
117            Ok(Event::Start(e)) => {
118                if e.name().as_ref().ends_with(block_suffix) {
119                    if !first_block {
120                        text.push('\n');
121                    }
122                    first_block = false;
123                }
124            }
125            Ok(Event::Text(t)) => {
126                if let Ok(content) = t.unescape() {
127                    if !content.trim().is_empty() {
128                        text.push_str(content.trim());
129                        text.push(' ');
130                    }
131                }
132            }
133            Ok(Event::Eof) => break,
134            Err(_) => break,
135            _ => (),
136        }
137        buf.clear();
138    }
139
140    text.trim().to_string()
141}