Skip to main content

ragfs_extract/
registry.rs

1//! Extractor registry for managing content extractors.
2
3use ragfs_core::{ContentExtractor, ExtractError, ExtractedContent};
4use std::collections::HashMap;
5use std::path::Path;
6use std::sync::Arc;
7
8/// Registry of content extractors.
9pub struct ExtractorRegistry {
10    /// Named extractors
11    extractors: HashMap<String, Arc<dyn ContentExtractor>>,
12    /// MIME type to extractor name mapping
13    mime_mapping: HashMap<String, String>,
14    captioner: Option<Arc<dyn crate::ImageCaptioner>>,
15}
16
17impl ExtractorRegistry {
18    /// Create a new empty registry.
19    #[must_use]
20    pub fn new() -> Self {
21        Self {
22            extractors: HashMap::new(),
23            mime_mapping: HashMap::new(),
24            captioner: None,
25        }
26    }
27
28    /// Caption images from all extractors, including embedded PDF images.
29    pub fn set_captioner(&mut self, captioner: Arc<dyn crate::ImageCaptioner>) {
30        self.captioner = Some(captioner);
31    }
32
33    /// Register an extractor.
34    pub fn register<E: ContentExtractor + 'static>(&mut self, name: &str, extractor: E) {
35        let extractor = Arc::new(extractor);
36        for mime in extractor.supported_types() {
37            self.mime_mapping
38                .insert((*mime).to_string(), name.to_string());
39        }
40        self.extractors.insert(name.to_string(), extractor);
41    }
42
43    /// Get an extractor for a MIME type.
44    #[must_use]
45    pub fn get_for_mime(&self, mime_type: &str) -> Option<Arc<dyn ContentExtractor>> {
46        self.mime_mapping
47            .get(mime_type)
48            .and_then(|name| self.extractors.get(name))
49            .cloned()
50    }
51
52    /// Get an extractor that can handle a file.
53    #[must_use]
54    pub fn get_for_file(&self, path: &Path, mime_type: &str) -> Option<Arc<dyn ContentExtractor>> {
55        // First try by MIME type
56        if let Some(extractor) = self.get_for_mime(mime_type) {
57            return Some(extractor);
58        }
59
60        // Then try by extension
61        for extractor in self.extractors.values() {
62            if extractor.can_extract(path, mime_type) {
63                return Some(extractor.clone());
64            }
65        }
66
67        None
68    }
69
70    /// Extract content from a file.
71    pub async fn extract(
72        &self,
73        path: &Path,
74        mime_type: &str,
75    ) -> Result<ExtractedContent, ExtractError> {
76        let extractor = self
77            .get_for_file(path, mime_type)
78            .ok_or_else(|| ExtractError::UnsupportedType(mime_type.to_string()))?;
79
80        let mut content = extractor.extract(path).await?;
81        if let Some(captioner) = &self.captioner {
82            for image in &mut content.images {
83                if image.caption.is_some() {
84                    continue;
85                }
86                if let Err(error) = crate::image::checked_dimensions(&image.data) {
87                    tracing::warn!("Skipping caption for {:?}: {error}", path);
88                    continue;
89                }
90                match captioner.caption(&image.data).await {
91                    Ok(caption) => image.caption = caption,
92                    Err(error) => tracing::warn!("Caption failed for {:?}: {error}", path),
93                }
94            }
95        }
96        Ok(content)
97    }
98}
99
100impl Default for ExtractorRegistry {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::TextExtractor;
110    use tempfile::tempdir;
111
112    #[test]
113    fn test_new_registry_is_empty() {
114        let registry = ExtractorRegistry::new();
115        assert!(registry.extractors.is_empty());
116        assert!(registry.mime_mapping.is_empty());
117    }
118
119    #[test]
120    fn test_register_extractor() {
121        let mut registry = ExtractorRegistry::new();
122        registry.register("text", TextExtractor::new());
123
124        assert!(registry.extractors.contains_key("text"));
125        // TextExtractor supports text/plain and text/markdown
126        assert!(registry.mime_mapping.contains_key("text/plain"));
127    }
128
129    #[test]
130    fn test_get_for_mime_existing() {
131        let mut registry = ExtractorRegistry::new();
132        registry.register("text", TextExtractor::new());
133
134        let extractor = registry.get_for_mime("text/plain");
135        assert!(extractor.is_some());
136    }
137
138    #[test]
139    fn test_get_for_mime_nonexistent() {
140        let registry = ExtractorRegistry::new();
141        let extractor = registry.get_for_mime("video/mp4");
142        assert!(extractor.is_none());
143    }
144
145    #[test]
146    fn test_get_for_file_by_mime() {
147        let mut registry = ExtractorRegistry::new();
148        registry.register("text", TextExtractor::new());
149
150        let path = std::path::PathBuf::from("/test/file.txt");
151        let extractor = registry.get_for_file(&path, "text/plain");
152        assert!(extractor.is_some());
153    }
154
155    #[test]
156    fn test_get_for_file_unknown_type() {
157        let registry = ExtractorRegistry::new();
158        let path = std::path::PathBuf::from("/test/file.xyz");
159        let extractor = registry.get_for_file(&path, "application/unknown");
160        assert!(extractor.is_none());
161    }
162
163    #[tokio::test]
164    async fn test_extract_success() {
165        let temp_dir = tempdir().unwrap();
166        let file_path = temp_dir.path().join("test.txt");
167        std::fs::write(&file_path, "Hello, world!").unwrap();
168
169        let mut registry = ExtractorRegistry::new();
170        registry.register("text", TextExtractor::new());
171
172        let result = registry.extract(&file_path, "text/plain").await;
173        assert!(result.is_ok());
174
175        let content = result.unwrap();
176        assert_eq!(content.text, "Hello, world!");
177    }
178
179    #[tokio::test]
180    async fn test_extract_unsupported_type() {
181        let temp_dir = tempdir().unwrap();
182        let file_path = temp_dir.path().join("test.bin");
183        std::fs::write(&file_path, [0u8; 10]).unwrap();
184
185        let registry = ExtractorRegistry::new();
186
187        let result = registry
188            .extract(&file_path, "application/octet-stream")
189            .await;
190        assert!(result.is_err());
191
192        match result.unwrap_err() {
193            ExtractError::UnsupportedType(mime) => {
194                assert_eq!(mime, "application/octet-stream");
195            }
196            _ => panic!("Expected UnsupportedType error"),
197        }
198    }
199
200    #[test]
201    fn test_multiple_extractors() {
202        let mut registry = ExtractorRegistry::new();
203        registry.register("text", TextExtractor::new());
204        // Could register more extractors here
205
206        assert_eq!(registry.extractors.len(), 1);
207        // TextExtractor registers multiple MIME types
208        assert!(!registry.mime_mapping.is_empty());
209    }
210
211    #[test]
212    fn test_default_implementation() {
213        let registry = ExtractorRegistry::default();
214        assert!(registry.extractors.is_empty());
215    }
216}
217
218#[cfg(test)]
219mod caption_tests {
220    use super::*;
221    use crate::{CaptionError, ImageCaptioner, PdfExtractor};
222    use lopdf::{Document, Object, Stream, dictionary};
223
224    struct CaptionStub;
225    #[async_trait::async_trait]
226    impl ImageCaptioner for CaptionStub {
227        async fn init(&self) -> Result<(), CaptionError> {
228            Ok(())
229        }
230        async fn caption(&self, _: &[u8]) -> Result<Option<String>, CaptionError> {
231            Ok(Some("A lighthouse".into()))
232        }
233        async fn is_initialized(&self) -> bool {
234            true
235        }
236        fn model_name(&self) -> &str {
237            "fixture"
238        }
239    }
240
241    #[tokio::test]
242    async fn embedded_pdf_jpeg_uses_the_shared_captioner() {
243        let root = tempfile::tempdir().unwrap();
244        let path = root.path().join("image.pdf");
245        let image = image::RgbImage::from_pixel(64, 64, image::Rgb([255, 0, 0]));
246        let mut jpeg = std::io::Cursor::new(Vec::new());
247        image.write_to(&mut jpeg, image::ImageFormat::Jpeg).unwrap();
248        let mut doc = Document::with_version("1.5");
249        let pages = doc.new_object_id();
250        let image_id = doc.add_object(Stream::new(
251            dictionary! {
252                "Type" => "XObject", "Subtype" => "Image", "Width" => 64, "Height" => 64,
253                "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode",
254            },
255            jpeg.into_inner(),
256        ));
257        let content = doc.add_object(Stream::new(
258            dictionary! {},
259            b"q 64 0 0 64 0 0 cm /Im0 Do Q".to_vec(),
260        ));
261        let page = doc.add_object(dictionary! {
262            "Type" => "Page", "Parent" => pages, "MediaBox" => vec![0.into(), 0.into(), 100.into(), 100.into()],
263            "Resources" => dictionary! { "XObject" => dictionary! { "Im0" => image_id } }, "Contents" => content,
264        });
265        doc.objects.insert(
266            pages,
267            Object::Dictionary(
268                dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 },
269            ),
270        );
271        let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
272        doc.trailer.set("Root", catalog);
273        doc.save(&path).unwrap();
274        let mut registry = ExtractorRegistry::new();
275        registry.register("pdf", PdfExtractor::new());
276        registry.set_captioner(Arc::new(CaptionStub));
277        let content = registry.extract(&path, "application/pdf").await.unwrap();
278        assert_eq!(content.images.len(), 1);
279        assert_eq!(content.images[0].caption.as_deref(), Some("A lighthouse"));
280        assert_eq!(content.images[0].page, Some(1));
281    }
282}