A fast, helpful, and open-source document parser
merge main, simplify
Logan Markewich470847c5802a
diff --cc crates/liteparse/src/conversion.rsindex c2b9e22,e44abe1..c3df1a4--- a/crates/liteparse/src/conversion.rs+++ b/crates/liteparse/src/conversion.rs@@@ -64,104 -61,6 +64,67 @@@ pub fn is_pdf(path: &str) -> bool}/// Check if a file extension is supported (either PDF or convertible).+/// Returns true when the extension denotes a plain-text format with no page layout.+pub fn is_text_only_extension(ext: &str) -> bool {+ TEXT_ONLY_EXTENSIONS.contains(&ext.to_lowercase().as_str())+}++pub fn screenshot_text_format_error(ext: &str) -> LiteParseError {+ LiteParseError::Conversion(format!(+ "Cannot screenshot text-based format (.{ext}). Convert to PDF first."+ ))+}++/// Keeps converted PDF temp directories alive until rendering or parsing completes.++/// All temp dirs are cleaned up automatically when this guard is dropped.+#[derive(Debug)]+pub struct PdfInputGuard {- /// Conversion output directory; kept alive until this guard is dropped.+ #[allow(dead_code)]- conv_tmp: Option<TempDir>,- /// Set when non-PDF bytes were staged and converted; requires explicit staging cleanup.- pub bytes_converted: bool,- }-- impl PdfInputGuard {- pub fn cleanup_bytes_staging(&self, input: &crate::types::PdfInput) {- if self.bytes_converted {- if let crate::types::PdfInput::Path(p) = input- && let Some(parent) = Path::new(p).parent()- {- let _ = std::fs::remove_dir_all(parent);- }- }- }++ temps: Vec<TempDir>,+}++/// Resolve a document input to a PDF suitable for rendering or text extraction.+///+/// When `reject_text_formats` is true, plain-text files (`.txt`, etc.) return a+/// clear error instead of attempting conversion.+pub async fn resolve_pdf_input(+ input: crate::types::PdfInput,+ password: Option<&str>,+ reject_text_formats: bool,+) -> Result<(crate::types::PdfInput, PdfInputGuard), LiteParseError> {+ use crate::types::PdfInput;++ match input {+ PdfInput::Path(p) => {+ let ext = Path::new(&p)+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or("");+ if reject_text_formats && is_text_only_extension(ext) {+ return Err(screenshot_text_format_error(ext));+ }+ if is_pdf(&p) {- Ok((- PdfInput::Path(p),- PdfInputGuard {- conv_tmp: None,- bytes_converted: false,- },- ))++ Ok((PdfInput::Path(p), PdfInputGuard { temps: Vec::new() }))+ } else {- let (converted, tmp_dir) = convert_to_pdf(&p, password, false).await?;- Ok((- PdfInput::Path(converted.pdf_path),- PdfInputGuard {- conv_tmp: tmp_dir,- bytes_converted: false,- },- ))++ let (converted, tmp_dir) = convert_to_pdf(&p, password).await?;++ let temps = tmp_dir.into_iter().collect();++ Ok((PdfInput::Path(converted.pdf_path), PdfInputGuard { temps }))+ }+ }+ PdfInput::Bytes(b) => {+ let ext = guess_extension_from_data(&b);+ if ext.as_deref() == Some("pdf") {- return Ok((- PdfInput::Bytes(b),- PdfInputGuard {- conv_tmp: None,- bytes_converted: false,- },- ));++ return Ok((PdfInput::Bytes(b), PdfInputGuard { temps: Vec::new() }));+ }+ if reject_text_formats && ext.as_ref().is_some_and(|e| is_text_only_extension(e)) {+ return Err(screenshot_text_format_error(ext.as_ref().unwrap()));+ }- let (converted, tmp_dir) = convert_data_to_pdf(b, password).await?;- Ok((- PdfInput::Path(converted.pdf_path),- PdfInputGuard {- conv_tmp: tmp_dir,- bytes_converted: true,- },- ))++ let (converted, temps) = convert_data_to_pdf(b, password).await?;++ Ok((PdfInput::Path(converted.pdf_path), PdfInputGuard { temps }))+ }+ }+}+pub fn is_supported_extension(path: &str) -> bool {let ext = match Path::new(path).extension().and_then(|e| e.to_str()) {Some(e) => e.to_lowercase(),@@@ -695,41 -610,9 +674,41 @@@ mod testsassert!(!is_path_executable("/no/such/path/zzz").await);}+ #[test]+ fn test_is_text_only_extension() {+ assert!(is_text_only_extension("txt"));+ assert!(is_text_only_extension("TXT"));+ assert!(is_text_only_extension("md"));+ assert!(!is_text_only_extension("pdf"));+ assert!(!is_text_only_extension("docx"));+ }++ #[tokio::test]+ async fn test_resolve_pdf_input_rejects_text_for_screenshot() {+ use crate::types::PdfInput;++ let err = resolve_pdf_input(PdfInput::Path("/tmp/readme.txt".into()), None, true)+ .await+ .unwrap_err()+ .to_string();+ assert!(err.contains("Cannot screenshot text-based format"));+ }++ #[tokio::test]+ async fn test_resolve_pdf_input_pdf_bytes_zero_disk() {+ use crate::types::PdfInput;++ let pdf_bytes = b"%PDF-1.4\n";+ let (input, guard) = resolve_pdf_input(PdfInput::Bytes(pdf_bytes.to_vec()), None, true)+ .await+ .unwrap();+ assert!(matches!(input, PdfInput::Bytes(_)));- assert!(!guard.bytes_converted);++ assert!(guard.temps.is_empty());+ }+#[tokio::test]async fn test_convert_to_pdf_passthrough_pdf() {- let (res, _) = convert_to_pdf("/some/file.pdf", None, false).await.unwrap();+ let (res, _) = convert_to_pdf("/some/file.pdf", None).await.unwrap();assert_eq!(res.pdf_path, "/some/file.pdf");assert_eq!(res.original_extension, "pdf");}diff --cc crates/liteparse/src/parser.rsindex 73bc114,a31e7f0..4a295ae--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@@ -82,11 -73,38 +82,11 @@@ impl LiteParselet t0 = web_time::Instant::now();#[cfg(not(target_arch = "wasm32"))]- let (validated_input, guard) =- let mut _buffer_temps: Vec<tempfile::TempDir> = Vec::new();- #[cfg(not(target_arch = "wasm32"))]- let mut _conv_tmp_dir: Option<tempfile::TempDir> = None;-- let validated_input = {- #[cfg(target_arch = "wasm32")]- {- input- }++ let (validated_input, _guard) =+ conversion::resolve_pdf_input(input, self.config.password.as_deref(), false).await?;- #[cfg(not(target_arch = "wasm32"))]- match input {- PdfInput::Path(p) => {- if conversion::is_pdf(&p) {- PdfInput::Path(p)- } else {- let (converted, tmp_dir) =- conversion::convert_to_pdf(&p, self.config.password.as_deref()).await?;- _conv_tmp_dir = tmp_dir;- // The on-disk source isn't ours to delete; only the- // converted temp file should be cleaned up by `tmp_dir`.- PdfInput::Path(converted.pdf_path)- }- }- PdfInput::Bytes(b) => {- let (converted, temps) =- convert_data_to_pdf(b, self.config.password.as_deref()).await?;- _buffer_temps = temps;- PdfInput::Path(converted.pdf_path)- }- }- };+ #[cfg(target_arch = "wasm32")]+ let validated_input = input;// Determine which pages to extractlet target_pages = self@@@ -187,63 -226,6 +208,61 @@@})}+ /// Generate screenshots of document pages as PNG bytes.+ ///+ /// Non-PDF files are automatically converted to PDF first (requires+ /// LibreOffice/ImageMagick on the system). Plain-text formats cannot be+ /// rendered and return a clear error.+ #[cfg(not(target_arch = "wasm32"))]+ pub async fn screenshot(+ &self,+ input: &str,+ page_numbers: Option<Vec<u32>>,+ ) -> Result<Vec<ScreenshotResult>, LiteParseError> {+ self.screenshot_input(PdfInput::Path(input.to_string()), page_numbers)+ .await+ }++ /// Generate screenshots from a file path or raw bytes.+ #[cfg(not(target_arch = "wasm32"))]+ pub async fn screenshot_input(+ &self,+ input: PdfInput,+ page_numbers: Option<Vec<u32>>,+ ) -> Result<Vec<ScreenshotResult>, LiteParseError> {+ let log = |msg: &str| {+ if !self.config.quiet {+ eprintln!("{}", msg);+ }+ };+- let (validated_input, guard) =++ let (validated_input, _guard) =+ conversion::resolve_pdf_input(input, self.config.password.as_deref(), true).await?;++ if let PdfInput::Path(ref path) = validated_input+ && !conversion::is_pdf(path)+ {+ log("[liteparse] converted input to PDF for screenshot rendering");+ }++ let rendered = render::render_pages_to_png(+ &validated_input,+ page_numbers.as_deref(),+ self.config.dpi,+ self.config.password.as_deref(),+ )?;+- guard.cleanup_bytes_staging(&validated_input);-+ Ok(rendered+ .into_iter()+ .map(|page| ScreenshotResult {+ page_num: page.page_num,+ width: page.width,+ height: page.height,+ image_bytes: page.png_bytes,+ })+ .collect())+ }+pub fn config(&self) -> &LiteParseConfig {&self.config}diff --cc crates/liteparse/src/render.rsindex 8e3eb80,364d81e..afe1294--- a/crates/liteparse/src/render.rs+++ b/crates/liteparse/src/render.rs@@@ -1,82 -1,8 +1,73 @@@use crate::error::LiteParseError;-use image::{ImageBuffer, Rgba};-use pdfium::Library;++use crate::extract::load_document_from_input;+use crate::types::PdfInput;+use image::ImageEncoder;- use pdfium::Library;use serde::Serialize;+/// A single rendered page as PNG bytes.+#[derive(Debug, Clone)]+pub struct RenderedPage {+ pub page_num: u32,+ pub width: u32,+ pub height: u32,+ pub png_bytes: Vec<u8>,+}++/// Render selected pages from a PDF input to PNG bytes.+pub fn render_pages_to_png(+ input: &PdfInput,+ page_numbers: Option<&[u32]>,+ dpi: f32,+ password: Option<&str>,+) -> Result<Vec<RenderedPage>, LiteParseError> {- let lib = Library::init();- match input {- PdfInput::Path(path) => {- let document = lib.load_document(path, password)?;- render_document_pages(&document, page_numbers, dpi)- }- PdfInput::Bytes(data) => {- let document = lib.load_document_from_bytes(data, password)?;- render_document_pages(&document, page_numbers, dpi)- }- }++ let document = load_document_from_input(input, password)?;++ render_document_pages(&document, page_numbers, dpi)+}++fn render_document_pages(+ document: &pdfium::Document,+ page_numbers: Option<&[u32]>,+ dpi: f32,+) -> Result<Vec<RenderedPage>, LiteParseError> {+ let page_count = document.page_count() as u32;+ let pages: Vec<u32> = match page_numbers {+ Some(nums) => nums.to_vec(),+ None => (1..=page_count).collect(),+ };++ let mut results = Vec::with_capacity(pages.len());+ for page_num in pages {+ if page_num < 1 || page_num > page_count {+ return Err(LiteParseError::Other(format!(+ "page {page_num} out of range (document has {page_count} pages)"+ )));+ }++ let page = document.page((page_num - 1) as i32)?;+ let bitmap = page.render(dpi)?;+ let width = bitmap.width() as u32;+ let height = bitmap.height() as u32;+ let rgba = bitmap.to_rgba();+ let png_bytes = encode_png(&rgba, width, height)?;++ results.push(RenderedPage {+ page_num,+ width,+ height,+ png_bytes,+ });+ }++ Ok(results)+}++fn encode_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>, LiteParseError> {+ let mut png_buf = Vec::new();+ let encoder = image::codecs::png::PngEncoder::new(&mut png_buf);+ encoder.write_image(rgba, width, height, image::ColorType::Rgba8.into())?;+ Ok(png_buf)+}+/// Render a single page to a PNG file.pub fn screenshot(pdf_path: &str,@@@ -130,8 -60,8 +121,7 @@@ struct ImageBoundsOutput/// Extract image bounding boxes and print as JSON to stdout.pub fn image_bounds(pdf_path: &str, page_num: Option<u32>) -> Result<(), LiteParseError> {-- let lib = Library::init();-- let document = lib.load_document(pdf_path, None)?;++ let document = load_document_from_input(&PdfInput::Path(pdf_path.to_string()), None)?;let page_count = document.page_count();for page_index in 0..page_count {