Skip to main content

ragfs_extract/
pdf.rs

1//! PDF content extractor.
2//!
3//! Uses pdf-extract to extract text content and lopdf for embedded images.
4
5use async_trait::async_trait;
6use flate2::read::ZlibDecoder;
7use lopdf::Document;
8use ragfs_core::{
9    ContentElement, ContentExtractor, ContentMetadataInfo, ExtractError, ExtractedContent,
10    ExtractedImage,
11};
12use std::io::Read;
13use std::path::Path;
14use tracing::{debug, warn};
15
16/// Extractor for PDF files.
17pub struct PdfExtractor;
18
19impl PdfExtractor {
20    /// Create a new PDF extractor.
21    #[must_use]
22    pub fn new() -> Self {
23        Self
24    }
25}
26
27impl Default for PdfExtractor {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33#[async_trait]
34impl ContentExtractor for PdfExtractor {
35    fn supported_types(&self) -> &[&str] {
36        &["application/pdf"]
37    }
38
39    fn can_extract_by_extension(&self, path: &Path) -> bool {
40        path.extension()
41            .and_then(|ext| ext.to_str())
42            .is_some_and(|ext| ext.eq_ignore_ascii_case("pdf"))
43    }
44
45    async fn extract(&self, path: &Path) -> Result<ExtractedContent, ExtractError> {
46        debug!("Extracting PDF: {:?}", path);
47
48        // Read PDF file
49        let bytes = tokio::fs::read(path).await?;
50
51        // Extract text using pdf-extract (blocking operation)
52        let text = tokio::task::spawn_blocking({
53            let bytes = bytes.clone();
54            move || extract_pdf_text(&bytes)
55        })
56        .await
57        .map_err(|e| ExtractError::Failed(format!("Task join error: {e}")))?
58        .map_err(|e| ExtractError::Failed(format!("PDF extraction failed: {e}")))?;
59
60        // Extract images using lopdf (blocking operation)
61        let images = tokio::task::spawn_blocking(move || extract_pdf_images(&bytes))
62            .await
63            .map_err(|e| ExtractError::Failed(format!("Image extraction task error: {e}")))?;
64
65        // Split into pages/paragraphs for elements
66        let elements = build_elements(&text);
67
68        // Estimate page count from page breaks or text length
69        let page_count = estimate_page_count(&text);
70
71        Ok(ExtractedContent {
72            text,
73            elements,
74            images,
75            metadata: ContentMetadataInfo {
76                page_count: Some(page_count),
77                ..Default::default()
78            },
79        })
80    }
81}
82
83/// Extract text from PDF bytes using pdf-extract.
84fn extract_pdf_text(bytes: &[u8]) -> Result<String, String> {
85    pdf_extract::extract_text_from_mem(bytes).map_err(|e| e.to_string())
86}
87
88/// Configuration for image extraction limits.
89const MAX_IMAGES: usize = 100;
90const MAX_TOTAL_BYTES: usize = 50 * 1024 * 1024; // 50MB
91const MIN_DIMENSION: u32 = 50; // Skip tiny images (icons, etc.)
92
93/// Extract images from PDF document using lopdf.
94fn extract_pdf_images(bytes: &[u8]) -> Vec<ExtractedImage> {
95    let doc = match Document::load_mem(bytes) {
96        Ok(d) => d,
97        Err(e) => {
98            warn!("Failed to load PDF for image extraction: {}", e);
99            return vec![];
100        }
101    };
102
103    let mut images = Vec::new();
104    let mut total_bytes = 0usize;
105
106    let pages = doc.get_pages();
107    for (page_num, page_id) in pages {
108        if images.len() >= MAX_IMAGES {
109            debug!(
110                "Reached maximum image count ({}), stopping extraction",
111                MAX_IMAGES
112            );
113            break;
114        }
115
116        match doc.get_page_images(page_id) {
117            Ok(page_images) => {
118                for pdf_image in page_images {
119                    if images.len() >= MAX_IMAGES || total_bytes >= MAX_TOTAL_BYTES {
120                        break;
121                    }
122
123                    // Skip tiny images
124                    if pdf_image.width < i64::from(MIN_DIMENSION)
125                        || pdf_image.height < i64::from(MIN_DIMENSION)
126                    {
127                        debug!(
128                            "Skipping small image: {}x{}",
129                            pdf_image.width, pdf_image.height
130                        );
131                        continue;
132                    }
133
134                    // Never let a single image, or the running total, exceed the
135                    // cap: a small FlateDecode stream can inflate without bound.
136                    let budget = MAX_TOTAL_BYTES - total_bytes;
137                    if let Some(extracted) = decode_pdf_image(&pdf_image, page_num, budget) {
138                        total_bytes += extracted.data.len();
139                        images.push(extracted);
140                    }
141                }
142            }
143            Err(e) => {
144                debug!("Failed to get images from page {}: {}", page_num, e);
145            }
146        }
147    }
148
149    debug!(
150        "Extracted {} images from PDF ({} bytes total)",
151        images.len(),
152        total_bytes
153    );
154    images
155}
156
157/// Decode a PDF image into `ExtractedImage` format.
158///
159/// `budget` is the number of bytes still available under `MAX_TOTAL_BYTES`;
160/// anything larger is rejected rather than allocated.
161fn decode_pdf_image(
162    pdf_image: &lopdf::xobject::PdfImage<'_>,
163    page_num: u32,
164    budget: usize,
165) -> Option<ExtractedImage> {
166    if pdf_image.width <= 0
167        || pdf_image.height <= 0
168        || (pdf_image.width as u64).saturating_mul(pdf_image.height as u64)
169            > crate::image::MAX_IMAGE_PIXELS
170    {
171        return None;
172    }
173    let filters = pdf_image.filters.as_ref()?;
174
175    // Determine MIME type and decode based on filter
176    let (data, mime_type) = if filters.iter().any(|f| f == "DCTDecode") {
177        // JPEG - can use raw content directly
178        (pdf_image.content.to_vec(), "image/jpeg".to_string())
179    } else if filters.iter().any(|f| f == "FlateDecode") {
180        // Compressed raw image data - decompress and convert to PNG
181        match decode_flate_image(pdf_image, budget) {
182            Ok((data, mime)) => (data, mime),
183            Err(e) => {
184                debug!("Failed to decode FlateDecode image: {}", e);
185                return None;
186            }
187        }
188    } else if filters.iter().any(|f| f == "JPXDecode") {
189        // JPEG 2000 - use raw content
190        (pdf_image.content.to_vec(), "image/jp2".to_string())
191    } else {
192        // Unsupported filter
193        debug!("Unsupported image filter: {:?}", filters);
194        return None;
195    };
196
197    // The DCT/JPX paths are bounded by the file size, but they still have to
198    // respect the remaining budget.
199    if data.len() > budget {
200        debug!(
201            "Skipping image: {} bytes exceeds the remaining budget of {} bytes",
202            data.len(),
203            budget
204        );
205        return None;
206    }
207
208    Some(ExtractedImage {
209        data,
210        mime_type,
211        caption: None, // Will be filled by vision model in future
212        page: Some(page_num),
213    })
214}
215
216/// Decode `FlateDecode` compressed image to PNG.
217fn decode_flate_image(
218    pdf_image: &lopdf::xobject::PdfImage<'_>,
219    budget: usize,
220) -> Result<(Vec<u8>, String), String> {
221    // Decompress with a hard bound. `read_to_end` on a hostile stream is a
222    // decompression bomb; read at most one byte past the budget so an oversized
223    // image is rejected instead of silently truncated.
224    let mut decoder = ZlibDecoder::new(pdf_image.content);
225    let mut decompressed = Vec::new();
226    decoder
227        .by_ref()
228        .take(budget as u64 + 1)
229        .read_to_end(&mut decompressed)
230        .map_err(|e| format!("Decompression failed: {e}"))?;
231
232    if decompressed.len() > budget {
233        return Err(format!(
234            "Decompressed image exceeds the remaining budget of {budget} bytes"
235        ));
236    }
237
238    // Determine color space and create image
239    let color_space = pdf_image.color_space.as_deref().unwrap_or("DeviceRGB");
240    let width = pdf_image.width as u32;
241    let height = pdf_image.height as u32;
242
243    let img = match color_space {
244        "DeviceRGB" | "RGB" => image::RgbImage::from_raw(width, height, decompressed)
245            .map(image::DynamicImage::ImageRgb8),
246        "DeviceGray" | "Gray" => image::GrayImage::from_raw(width, height, decompressed)
247            .map(image::DynamicImage::ImageLuma8),
248        "DeviceCMYK" | "CMYK" => {
249            // Convert CMYK to RGB
250            let rgb_data = cmyk_to_rgb(&decompressed);
251            image::RgbImage::from_raw(width, height, rgb_data).map(image::DynamicImage::ImageRgb8)
252        }
253        _ => {
254            // Attempt RGB as fallback
255            debug!("Unknown color space '{}', attempting RGB", color_space);
256            image::RgbImage::from_raw(width, height, decompressed)
257                .map(image::DynamicImage::ImageRgb8)
258        }
259    };
260
261    let img = img.ok_or_else(|| "Failed to create image from raw data".to_string())?;
262
263    // Encode to PNG
264    let mut png_data = Vec::new();
265    img.write_to(
266        &mut std::io::Cursor::new(&mut png_data),
267        image::ImageFormat::Png,
268    )
269    .map_err(|e| format!("PNG encoding failed: {e}"))?;
270
271    Ok((png_data, "image/png".to_string()))
272}
273
274/// Convert CMYK bytes to RGB.
275#[allow(clippy::many_single_char_names)]
276fn cmyk_to_rgb(cmyk: &[u8]) -> Vec<u8> {
277    let mut rgb = Vec::with_capacity((cmyk.len() / 4) * 3);
278    for chunk in cmyk.as_chunks::<4>().0 {
279        let c = f32::from(chunk[0]) / 255.0;
280        let m = f32::from(chunk[1]) / 255.0;
281        let y = f32::from(chunk[2]) / 255.0;
282        let k = f32::from(chunk[3]) / 255.0;
283
284        let r = 255.0 * (1.0 - c) * (1.0 - k);
285        let g = 255.0 * (1.0 - m) * (1.0 - k);
286        let b = 255.0 * (1.0 - y) * (1.0 - k);
287
288        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
289        {
290            rgb.push(r as u8);
291            rgb.push(g as u8);
292            rgb.push(b as u8);
293        }
294    }
295    rgb
296}
297
298/// Build `ContentElements` from extracted text.
299fn build_elements(text: &str) -> Vec<ContentElement> {
300    let mut elements = Vec::new();
301    let mut current_offset = 0u64;
302
303    // Split by double newlines to get paragraphs
304    for paragraph in text.split("\n\n") {
305        let trimmed = paragraph.trim();
306        if trimmed.is_empty() {
307            current_offset += paragraph.len() as u64 + 2; // +2 for \n\n
308            continue;
309        }
310
311        // Check if it looks like a heading (short, possibly capitalized)
312        if looks_like_heading(trimmed) {
313            elements.push(ContentElement::Heading {
314                level: 1,
315                text: trimmed.to_string(),
316                byte_offset: current_offset,
317            });
318        } else {
319            elements.push(ContentElement::Paragraph {
320                text: trimmed.to_string(),
321                byte_offset: current_offset,
322            });
323        }
324
325        current_offset += paragraph.len() as u64 + 2;
326    }
327
328    elements
329}
330
331/// Heuristic to detect if text looks like a heading.
332fn looks_like_heading(text: &str) -> bool {
333    // Short text (likely a title/heading)
334    if text.len() > 100 {
335        return false;
336    }
337
338    // No period at end (headings typically don't end with periods)
339    if text.ends_with('.') {
340        return false;
341    }
342
343    // Single line
344    if text.contains('\n') {
345        return false;
346    }
347
348    // All caps or title case with few words
349    let words: Vec<&str> = text.split_whitespace().collect();
350    if words.len() <= 8 {
351        // Check if mostly capitalized
352        let caps_count = words
353            .iter()
354            .filter(|w| w.chars().next().is_some_and(char::is_uppercase))
355            .count();
356        return caps_count >= words.len() / 2;
357    }
358
359    false
360}
361
362/// Estimate page count from text.
363fn estimate_page_count(text: &str) -> u32 {
364    // Look for form feed characters (page breaks)
365    let form_feeds = text.matches('\x0C').count();
366    if form_feeds > 0 {
367        return (form_feeds + 1) as u32;
368    }
369
370    // Estimate based on character count (~3000 chars per page average)
371    let chars = text.len();
372    std::cmp::max(1, (chars / 3000) as u32)
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn test_looks_like_heading() {
381        assert!(looks_like_heading("Chapter 1"));
382        assert!(looks_like_heading("INTRODUCTION"));
383        assert!(looks_like_heading("The Quick Brown Fox"));
384        assert!(!looks_like_heading("This is a normal sentence."));
385        assert!(!looks_like_heading(
386            "This is a very long paragraph that goes on and on and definitely is not a heading"
387        ));
388    }
389
390    #[test]
391    fn test_estimate_page_count() {
392        assert_eq!(estimate_page_count("short"), 1);
393        assert_eq!(estimate_page_count(&"x".repeat(6000)), 2);
394        assert_eq!(estimate_page_count("page1\x0Cpage2\x0Cpage3"), 3);
395    }
396
397    #[test]
398    fn test_build_elements() {
399        let text = "Title\n\nFirst paragraph here.\n\nSecond paragraph.";
400        let elements = build_elements(text);
401        assert_eq!(elements.len(), 3);
402    }
403
404    /// A hostile PDF can make a tiny `FlateDecode` stream inflate without
405    /// bound, so the decoder must refuse anything above the remaining budget.
406    #[test]
407    fn test_decode_flate_image_respects_budget() {
408        use flate2::Compression;
409        use flate2::write::ZlibEncoder;
410        use std::io::Write;
411
412        // 4x4 DeviceRGB = 48 bytes of pixel data.
413        let pixels = vec![7u8; 48];
414        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
415        encoder.write_all(&pixels).unwrap();
416        let compressed = encoder.finish().unwrap();
417
418        let dict = lopdf::Dictionary::new();
419        let image = lopdf::xobject::PdfImage {
420            id: (1, 0),
421            width: 4,
422            height: 4,
423            color_space: Some("DeviceRGB".to_string()),
424            filters: Some(vec!["FlateDecode".to_string()]),
425            bits_per_component: Some(8),
426            content: &compressed,
427            origin_dict: &dict,
428        };
429
430        // A budget below the decompressed size must be refused, not truncated.
431        assert!(decode_flate_image(&image, 16).is_err());
432
433        // A sufficient budget decodes to a PNG.
434        let (png, mime) = decode_flate_image(&image, 4096).unwrap();
435        assert_eq!(mime, "image/png");
436        assert!(!png.is_empty());
437    }
438}