Skip to content

A fast, helpful, and open-source document parser

code fixes

Logan Markewich92955b949559
diff --git a/Cargo.lock b/Cargo.lock
index 0434c0b..1036245 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1196,7 +1196,6 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
name = "liteparse"
version = "2.0.0"
dependencies = [
- "anyhow",
"clap",
"image",
"infer",
@@ -1207,6 +1206,7 @@ dependencies = [
"serde_json",
"tempfile",
"tesseract-rs",
+ "thiserror 2.0.18",
"tokio",
"web-time",
]
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index d5d6cb6..058563e 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -186,5 +186,4 @@ impl JsParseResult {
text: result.text.clone(),
}
}
-
}
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index 0c70552..c6696e3 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -132,7 +132,6 @@ impl PyParseResult {
text: result.text.clone(),
}
}
-
}
#[pyclass(frozen, from_py_object)]
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index f20ce85..bb4137f 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -330,5 +330,4 @@ impl LiteParse {
serde_wasm_bindgen::to_value(&js_result)
.map_err(|e| JsError::new(&format!("serialize result failed: {}", e)))
}
-
}
diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.toml
index 89dd1fc..fb7c7e4 100644
--- a/crates/liteparse/Cargo.toml
+++ b/crates/liteparse/Cargo.toml
@@ -18,7 +18,6 @@ default = ["tesseract"]
tesseract = ["dep:tesseract-rs"]
[dependencies]
-anyhow = "1.0.102"
clap = { version = "4.5.55", features = ["derive"] }
image = { version = "0.25", default-features = false, features = ["png"] }
infer = "0.19.0"
@@ -28,6 +27,7 @@ reqwest = { version = "0.13.3", default-features = false, features = ["json", "f
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
tempfile = "3.27.0"
+thiserror = "2"
tesseract-rs = { version = "0.2", features = ["build-tesseract"], optional = true }
tokio = { version = "1.52.3", features = ["rt", "macros", "sync", "time", "io-util"] }
web-time = "1.1.0"
diff --git a/crates/liteparse/src/conversion.rs b/crates/liteparse/src/conversion.rs
index d75e023..b2f6f73 100644
--- a/crates/liteparse/src/conversion.rs
+++ b/crates/liteparse/src/conversion.rs
@@ -1,3 +1,4 @@
+use crate::error::LiteParseError;
use std::{
fmt::{self, Display},
path::Path,
@@ -34,12 +35,12 @@ pub struct ConversionResult {
pub original_extension: String,
}
-enum ConverstionTool {
+enum ConversionTool {
LibreOffice,
ImageMagick,
}
-impl Display for ConverstionTool {
+impl Display for ConversionTool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::ImageMagick => "ImageMagick",
@@ -81,7 +82,7 @@ pub fn is_supported_extension(path: &str) -> bool {
pub async fn convert_to_pdf(
path: &str,
password: Option<&str>,
-) -> Result<ConversionResult, Box<dyn std::error::Error>> {
+) -> Result<ConversionResult, LiteParseError> {
let ext = Path::new(path)
.extension()
.and_then(|e| e.to_str())
@@ -99,19 +100,22 @@ pub async fn convert_to_pdf(
|| PRESENTATION_EXTENSIONS.contains(&ext.as_str())
|| SPREADSHEET_EXTENSIONS.contains(&ext.as_str())
{
- ConverstionTool::LibreOffice
+ ConversionTool::LibreOffice
} else if IMAGE_EXTENSIONS.contains(&ext.as_str()) {
- ConverstionTool::ImageMagick
+ ConversionTool::ImageMagick
} else {
- return Err(format!("unsupported file format: .{}", ext).into());
+ return Err(LiteParseError::Conversion(format!(
+ "unsupported file format: .{}",
+ ext
+ )));
};
let tmp_dir = tempfile::Builder::new().prefix("liteparse-").tempdir()?;
let pdf_path = match tool {
- ConverstionTool::ImageMagick => {
+ ConversionTool::ImageMagick => {
convert_image_to_pdf(path, tmp_dir.path().to_str().unwrap()).await?
}
- ConverstionTool::LibreOffice => {
+ ConversionTool::LibreOffice => {
convert_office_document(path, tmp_dir.path().to_str().unwrap(), password).await?
}
};
@@ -127,7 +131,7 @@ pub async fn execute_command(
command: &str,
args: Vec<&str>,
timeout_ms: u64,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> Result<String, LiteParseError> {
let proc = tokio::process::Command::new(command)
.args(args)
.stdin(std::process::Stdio::null())
@@ -147,19 +151,20 @@ pub async fn execute_command(
if output.status.success() {
Ok(stdout)
} else {
- Err(anyhow::anyhow!("Command failed: {stderr}").into())
+ Err(LiteParseError::Conversion(format!(
+ "Command failed: {stderr}"
+ )))
}
}
- Ok(Err(e)) => Err(anyhow::anyhow!("Command error: {e}").into()),
- Err(_) => Err(anyhow::anyhow!("Command timed out after {timeout_ms}ms").into()),
+ Ok(Err(e)) => Err(LiteParseError::Conversion(format!("Command error: {e}"))),
+ Err(_) => Err(LiteParseError::Conversion(format!(
+ "Command timed out after {timeout_ms}ms"
+ ))),
}
}
/// Execute a command for PowerShel
-pub async fn execute_powershell(
- command: &str,
- timeout_ms: u64,
-) -> Result<String, Box<dyn std::error::Error>> {
+pub async fn execute_powershell(command: &str, timeout_ms: u64) -> Result<String, LiteParseError> {
execute_command(
"powershell",
vec!["-NoProfile", "-Command", command],
@@ -327,12 +332,12 @@ pub async fn convert_office_document(
file_path: &str,
output_dir: &str,
password: Option<&str>,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> Result<String, LiteParseError> {
let libre_office_cmd = find_libre_office_command().await.ok_or_else(|| {
- anyhow::anyhow!(
+ LiteParseError::Conversion(
"LibreOffice is not installed. Please install LibreOffice to convert office documents. \
On macOS: brew install --cask libreoffice, On Ubuntu: apt-get install libreoffice, \
- On Windows: choco install libreoffice-fresh"
+ On Windows: choco install libreoffice-fresh".into()
)
})?;
@@ -356,7 +361,7 @@ pub async fn convert_office_document(
let base_name = Path::new(file_path)
.file_stem()
.and_then(|s| s.to_str())
- .ok_or_else(|| anyhow::anyhow!("invalid file path: {file_path}"))?;
+ .ok_or_else(|| LiteParseError::Conversion(format!("invalid file path: {file_path}")))?;
let pdf_path = Path::new(output_dir)
.join(format!("{base_name}.pdf"))
.to_string_lossy()
@@ -365,7 +370,9 @@ pub async fn convert_office_document(
if tokio::fs::metadata(&pdf_path).await.is_ok() {
Ok(pdf_path)
} else {
- Err(anyhow::anyhow!("LibreOffice conversion succeeded but output PDF not found").into())
+ Err(LiteParseError::Conversion(
+ "LibreOffice conversion succeeded but output PDF not found".into(),
+ ))
}
}
@@ -373,12 +380,13 @@ pub async fn convert_office_document(
pub async fn convert_image_to_pdf(
file_path: &str,
output_dir: &str,
-) -> Result<String, Box<dyn std::error::Error>> {
+) -> Result<String, LiteParseError> {
let image_magick = find_image_magick_command().await.ok_or_else(|| {
- anyhow::anyhow!(
+ LiteParseError::Conversion(
"ImageMagick is not installed. Please install ImageMagick to convert images. \
On macOS: brew install imagemagick, On Ubuntu: apt-get install imagemagick, \
On Windows: choco install imagemagick.app"
+ .into(),
)
})?;
@@ -393,20 +401,19 @@ pub async fn convert_image_to_pdf(
let has_ghostscript =
is_command_available("gs").await || is_command_available_windows("gs").await;
if !has_ghostscript {
- return Err(anyhow::anyhow!(
+ return Err(LiteParseError::Conversion(format!(
"Ghostscript is required to convert {} files but is not installed. \
On macOS: brew install ghostscript, On Ubuntu: apt-get install ghostscript, \
On Windows: choco install ghostscript",
ext.to_uppercase()
- )
- .into());
+ )));
}
}
let base_name = Path::new(file_path)
.file_stem()
.and_then(|s| s.to_str())
- .ok_or_else(|| anyhow::anyhow!("invalid file path: {file_path}"))?;
+ .ok_or_else(|| LiteParseError::Conversion(format!("invalid file path: {file_path}")))?;
let pdf_path = Path::new(output_dir)
.join(format!("{base_name}.pdf"))
.to_string_lossy()
@@ -425,21 +432,19 @@ pub async fn convert_image_to_pdf(
Err(error) => {
let error_msg = error.to_string();
if error_msg.contains("gs") && error_msg.contains("command not found") {
- return Err(anyhow::anyhow!(
+ return Err(LiteParseError::Conversion(format!(
"Ghostscript is required to convert {} files but is not installed. \
On macOS: brew install ghostscript, On Ubuntu: apt-get install ghostscript, \
On Windows: choco install ghostscript",
ext.to_uppercase()
- )
- .into());
+ )));
}
if error_msg.contains("FailedToExecuteCommand") && error_msg.contains("gs") {
- return Err(anyhow::anyhow!(
+ return Err(LiteParseError::Conversion(format!(
"Ghostscript failed during {} conversion. \
Ensure Ghostscript is properly installed: brew install ghostscript",
ext.to_uppercase()
- )
- .into());
+ )));
}
Err(error)
}
@@ -447,18 +452,13 @@ pub async fn convert_image_to_pdf(
}
pub fn guess_extension_from_data(data: &[u8]) -> Option<String> {
- let kind = infer::get(data);
- let ext = kind.map(|k| k.extension());
- if let Some(e) = ext {
- return Some(e.to_string());
- }
- None
+ infer::get(data).map(|k| k.extension().to_string())
}
pub async fn convert_data_to_pdf(
data: Vec<u8>,
password: Option<&str>,
-) -> Result<ConversionResult, Box<dyn std::error::Error>> {
+) -> Result<ConversionResult, LiteParseError> {
let ext = guess_extension_from_data(&data);
let tmp_dir = tempfile::Builder::new().prefix("liteparse-").tempdir()?;
let tmp_path = tmp_dir
@@ -496,8 +496,8 @@ mod tests {
#[test]
fn test_conversion_tool_display() {
- assert_eq!(ConverstionTool::ImageMagick.to_string(), "ImageMagick");
- assert_eq!(ConverstionTool::LibreOffice.to_string(), "LibreOffice");
+ assert_eq!(ConversionTool::ImageMagick.to_string(), "ImageMagick");
+ assert_eq!(ConversionTool::LibreOffice.to_string(), "LibreOffice");
}
#[test]
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 468414a..dd3b395 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -1,3 +1,4 @@
+use crate::error::LiteParseError;
use crate::types::{Page as LitePage, PdfInput, TextItem};
use pdfium::{Font, FontType, Library, Page, RectF, TextPage};
@@ -5,38 +6,14 @@ use pdfium::{Font, FontType, Library, Page, RectF, TextPage};
pub fn extract_pages(
pdf_path: &str,
page_num: Option<u32>,
-) -> Result<Vec<LitePage>, Box<dyn std::error::Error>> {
- let lib = Library::init();
- let document = lib.load_document(pdf_path, None)?;
- let page_count = document.page_count();
- let mut pages = Vec::new();
-
- for page_index in 0..page_count {
- if let Some(target_page) = page_num
- && page_index as u32 + 1 != target_page
- {
- continue;
- }
-
- let page = document.page(page_index)?;
- let text_page = page.text()?;
- let view_box = page.view_box().unwrap_or(RectF {
- left: 0.0,
- top: page.height(),
- right: page.width(),
- bottom: 0.0,
- });
- let text_items = extract_page_text_items(&page, &text_page, &view_box)?;
-
- pages.push(LitePage {
- page_number: (page_index + 1) as usize,
- page_width: page.width(),
- page_height: page.height(),
- text_items,
- });
- }
-
- Ok(pages)
+) -> Result<Vec<LitePage>, LiteParseError> {
+ let target_pages: Option<Vec<u32>> = page_num.map(|p| vec![p]);
+ extract_pages_from_input(
+ &PdfInput::Path(pdf_path.to_string()),
+ target_pages.as_deref(),
+ usize::MAX,
+ None,
+ )
}
/// Extract pages with filtering by target page list and max pages, with optional password.
@@ -45,58 +22,22 @@ pub fn extract_pages_filtered(
target_pages: Option<&[u32]>,
max_pages: usize,
password: Option<&str>,
-) -> Result<Vec<LitePage>, Box<dyn std::error::Error>> {
- let lib = Library::init();
- let document = lib.load_document(pdf_path, password)?;
- let page_count = document.page_count();
- let mut pages = Vec::new();
-
- for page_index in 0..page_count {
- let page_number = page_index as u32 + 1;
-
- if let Some(targets) = target_pages
- && !targets.contains(&page_number)
- {
- continue;
- }
-
- if pages.len() >= max_pages {
- break;
- }
-
- let page = document.page(page_index)?;
- let text_page = page.text()?;
- let view_box = page.view_box().unwrap_or(RectF {
- left: 0.0,
- top: page.height(),
- right: page.width(),
- bottom: 0.0,
- });
- let text_items = extract_page_text_items(&page, &text_page, &view_box)?;
-
- pages.push(LitePage {
- page_number: page_number as usize,
- page_width: page.width(),
- page_height: page.height(),
- text_items,
- });
- }
-
- Ok(pages)
+) -> Result<Vec<LitePage>, LiteParseError> {
+ extract_pages_from_input(
+ &PdfInput::Path(pdf_path.to_string()),
+ target_pages,
+ max_pages,
+ password,
+ )
}
/// Extract pages from a `PdfInput` (file path or bytes) with filtering.
-///
-/// Returns `(pages, pdf_data)` where `pdf_data` is the owned byte buffer when
-/// input was `PdfInput::Bytes`. The caller should keep `pdf_data` alive as long
-/// as any pdfium objects derived from it are in use. This is needed because
-/// pdfium's memory-loaded documents require the buffer to outlive the document.
pub fn extract_pages_from_input(
input: &PdfInput,
target_pages: Option<&[u32]>,
max_pages: usize,
password: Option<&str>,
-) -> Result<Vec<LitePage>, Box<dyn std::error::Error>> {
+) -> Result<Vec<LitePage>, LiteParseError> {
let lib = Library::init();
let document = match input {
PdfInput::Path(path) => lib.load_document(path, password)?,
@@ -140,7 +81,7 @@ pub fn extract_pages_from_input(
}
/// Extract raw text items and print each page as a JSON-line object to stdout.
-pub fn extract(pdf_path: &str, page_num: Option<u32>) -> Result<(), Box<dyn std::error::Error>> {
+pub fn extract(pdf_path: &str, page_num: Option<u32>) -> Result<(), LiteParseError> {
let pages = extract_pages(pdf_path, page_num)?;
for page in &pages {
println!("{}", serde_json::to_string(page)?);
@@ -216,7 +157,7 @@ fn extract_page_text_items(
page: &Page,
text_page: &TextPage,
view_box: &RectF,
-) -> Result<Vec<TextItem>, Box<dyn std::error::Error>> {
+) -> Result<Vec<TextItem>, LiteParseError> {
let char_count = text_page.char_count();
if char_count <= 0 {
return Ok(Vec::new());
@@ -772,32 +713,7 @@ impl SegmentBuilder {
});
}
- // Reset
- self.text.clear();
- self.vp_left = f32::MAX;
- self.vp_right = f32::MIN;
- self.vp_top = f32::MAX;
- self.vp_bottom = f32::MIN;
- self.last_char_right = f32::MIN;
- self.last_char_bottom = f32::MIN;
- self.char_count = 0;
- self.font_name = None;
- self.font_size = 0.0;
- self.font_height = None;
- self.font_ascent = None;
- self.font_descent = None;
- self.font_weight = None;
- self.font_flags = None;
- self.font_is_buggy = false;
- self.font_is_embedded = false;
- self.font = None;
- self.rotation_deg = 0.0;
- self.text_width = 0.0;
- self.mcid = None;
- self.fill_color = None;
- self.stroke_color = None;
- self.has_content = false;
- self.pending_space = false;
+ *self = Self::new();
}
}
@@ -813,20 +729,7 @@ mod tests {
y,
width: w,
height: h,
- rotation: 0.0,
- font_name: None,
- font_size: None,
- font_height: None,
- font_ascent: None,
- font_descent: None,
- font_weight: None,
- font_flags: None,
- text_width: None,
- font_is_buggy: false,
- mcid: None,
- fill_color: None,
- stroke_color: None,
- confidence: None,
+ ..Default::default()
}
}
diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rs
index 231e6d1..b376d8d 100644
--- a/crates/liteparse/src/lib.rs
+++ b/crates/liteparse/src/lib.rs
@@ -1,6 +1,7 @@
pub mod config;
#[cfg(not(target_arch = "wasm32"))]
pub mod conversion;
+pub mod error;
pub mod extract;
pub mod ocr;
pub mod ocr_merge;
diff --git a/crates/liteparse/src/ocr/http_simple.rs b/crates/liteparse/src/ocr/http_simple.rs
index 9771b0b..d44cea7 100644
--- a/crates/liteparse/src/ocr/http_simple.rs
+++ b/crates/liteparse/src/ocr/http_simple.rs
@@ -38,19 +38,6 @@ impl HttpOcrEngine {
server_url,
}
}
-
- async fn _recognize_batch(
- &self,
- images: Vec<&[u8]>,
- options: OcrOptions,
- ) -> Result<Vec<Vec<OcrResult>>, Box<dyn std::error::Error>> {
- let mut results: Vec<Vec<OcrResult>> = vec![];
- for i in images {
- let result = self.recognize(i, 0, 0, &options).await?;
- results.push(result);
- }
- Ok(results)
- }
}
impl OcrEngine for HttpOcrEngine {
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index cb0397b..ab300a4 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -1,3 +1,4 @@
+use crate::error::LiteParseError;
use crate::ocr::{OcrEngine, OcrOptions};
use crate::types::{Page, PdfInput, TextItem};
use image::{ImageBuffer, Rgba};
@@ -13,7 +14,7 @@ pub async fn ocr_and_merge_pages(
dpi: f32,
ocr_engine: &dyn OcrEngine,
ocr_language: &str,
-) -> Result<(), Box<dyn std::error::Error>> {
+) -> Result<(), LiteParseError> {
ocr_and_merge_pages_from_input(
pages,
&PdfInput::Path(pdf_path.to_string()),
@@ -32,7 +33,7 @@ pub async fn ocr_and_merge_pages_from_input(
dpi: f32,
ocr_engine: &dyn OcrEngine,
ocr_language: &str,
-) -> Result<(), Box<dyn std::error::Error>> {
+) -> Result<(), LiteParseError> {
// Phase 1: render all pages that need OCR. The pdfium `Document` holds raw
// pointers that are not `Send`, so we must not hold it across an `.await`.
// Render synchronously into owned buffers and drop the document before
@@ -72,7 +73,9 @@ pub async fn ocr_and_merge_pages_from_input(
let rgba = bitmap.to_rgba();
let img: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(width, height, rgba)
- .ok_or("failed to create image buffer")?;
+ .ok_or(LiteParseError::Other(
+ "failed to create image buffer".into(),
+ ))?;
let rgb_img = image::DynamicImage::ImageRgba8(img).to_rgb8();
let rgb_bytes = rgb_img.into_raw();
@@ -147,20 +150,10 @@ pub async fn ocr_and_merge_pages_from_input(
y: ocr_y,
width: ocr_w,
height: ocr_h,
- rotation: 0.0,
font_name: Some("OCR".to_string()),
font_size: Some(ocr_h),
- font_height: None,
- font_ascent: None,
- font_descent: None,
- font_weight: None,
- font_flags: None,
- text_width: None,
- font_is_buggy: false,
- mcid: None,
- fill_color: None,
- stroke_color: None,
confidence: Some((r.confidence * 1000.0).round() / 1000.0),
+ ..Default::default()
});
added += 1;
}
@@ -256,20 +249,7 @@ mod tests {
y,
width: w,
height: h,
- rotation: 0.0,
- font_name: None,
- font_size: None,
- font_height: None,
- font_ascent: None,
- font_descent: None,
- font_weight: None,
- font_flags: None,
- text_width: None,
- font_is_buggy: false,
- mcid: None,
- fill_color: None,
- stroke_color: None,
- confidence: None,
+ ..Default::default()
}
}
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index ba1a4cc..1b06b7d 100644
--- a/crates/liteparse/src/output/json.rs
+++ b/crates/liteparse/src/output/json.rs
@@ -77,20 +77,10 @@ mod tests {
y: 2.0,
width: 3.0,
height: 4.0,
- rotation: 0.0,
font_name: Some("Helv".into()),
font_size: Some(10.0),
- font_height: None,
- font_ascent: None,
- font_descent: None,
- font_weight: None,
- font_flags: None,
- text_width: None,
- font_is_buggy: false,
- mcid: None,
- fill_color: None,
- stroke_color: None,
confidence: conf,
+ ..Default::default()
}
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index ecc01ab..12c49af 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -1,6 +1,7 @@
use crate::config::{LiteParseConfig, parse_target_pages};
#[cfg(not(target_arch = "wasm32"))]
use crate::conversion;
+use crate::error::LiteParseError;
use crate::extract;
use crate::ocr::OcrEngine;
#[cfg(not(target_arch = "wasm32"))]
@@ -52,7 +53,7 @@ impl LiteParse {
/// Not available on `wasm32` — the browser has no filesystem. Use
/// [`LiteParse::parse_input`] with [`PdfInput::Bytes`] instead.
#[cfg(not(target_arch = "wasm32"))]
- pub async fn parse(&self, input: &str) -> Result<ParseResult, Box<dyn std::error::Error>> {
+ pub async fn parse(&self, input: &str) -> Result<ParseResult, LiteParseError> {
// Resolve file path to a PdfInput (convert non-PDFs first)
let pdf_input = if conversion::is_pdf(input) {
PdfInput::Path(input.to_string())
@@ -69,10 +70,7 @@ impl LiteParse {
///
/// Use `PdfInput::Path` for files on disk or `PdfInput::Bytes` for
/// in-memory PDF data (e.g. from a network response or Node.js Buffer).
- pub async fn parse_input(
- &self,
- input: PdfInput,
- ) -> Result<ParseResult, Box<dyn std::error::Error>> {
+ pub async fn parse_input(&self, input: PdfInput) -> Result<ParseResult, LiteParseError> {
let log = |msg: &str| {
if !self.config.quiet {
eprintln!("{}", msg);
@@ -193,5 +191,4 @@ mod tests {
assert!(!lp.config().ocr_enabled);
assert_eq!(lp.config().max_pages, 7);
}
-
}
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 888ee20..0f7e08b 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -86,13 +86,7 @@ fn compute_median_textbox_size(items: &[ProjectedTextItem]) -> (f32, f32) {
}
fn canonical_rotation(rotation: f32) -> i32 {
- let mut r = rotation;
- while r < 0.0 {
- r += 360.0;
- }
- while r >= 360.0 {
- r -= 360.0;
- }
+ let r = rotation.rem_euclid(360.0);
let candidates = [0.0f32, 90.0, 180.0, 270.0];
let mut best = 0.0f32;
diff --git a/crates/liteparse/src/render.rs b/crates/liteparse/src/render.rs
index 82548c6..364d81e 100644
--- a/crates/liteparse/src/render.rs
+++ b/crates/liteparse/src/render.rs
@@ -1,3 +1,4 @@
+use crate::error::LiteParseError;
use image::{ImageBuffer, Rgba};
use pdfium::Library;
use serde::Serialize;
@@ -8,7 +9,7 @@ pub fn screenshot(
page_num: u32,
dpi: f32,
output_path: &str,
-) -> Result<(), Box<dyn std::error::Error>> {
+) -> Result<(), LiteParseError> {
let lib = Library::init();
let document = lib.load_document(pdf_path, None)?;
let page = document.page((page_num - 1) as i32)?;
@@ -18,8 +19,9 @@ pub fn screenshot(
let height = bitmap.height() as u32;
let rgba = bitmap.to_rgba();
- let img: ImageBuffer<Rgba<u8>, Vec<u8>> =
- ImageBuffer::from_raw(width, height, rgba).ok_or("failed to create image buffer")?;
+ let img: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(width, height, rgba).ok_or(
+ LiteParseError::Other("failed to create image buffer".into()),
+ )?;
img.save(output_path)?;
eprintln!(
@@ -31,11 +33,7 @@ pub fn screenshot(
}
/// Render a single page and write raw PNG bytes to stdout.
-pub fn screenshot_to_stdout(
- pdf_path: &str,
- page_num: u32,
- dpi: f32,
-) -> Result<(), Box<dyn std::error::Error>> {
+pub fn screenshot_to_stdout(pdf_path: &str, page_num: u32, dpi: f32) -> Result<(), LiteParseError> {
let lib = Library::init();
let document = lib.load_document(pdf_path, None)?;
let page = document.page((page_num - 1) as i32)?;
@@ -61,10 +59,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<(), Box<dyn std::error::Error>> {
+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 page_count = document.page_count();
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 63cd002..ebc358e 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -1,15 +1,6 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
-/// Supported output formats for parsed documents.
-/// - `"json"` — Structured JSON with per-page text items, bounding boxes, and metadata.
-/// - `"text"` — Plain text with spatial layout preserved.
-#[derive(Debug, Serialize, Deserialize)]
-pub enum OutputFormat {
- Json,
- Text,
-}
-
/// Accepted input types for input documents.
/// - `FilePath(String)` — A file path to a local PDF document.
/// - `Buffer(Vec<u8>)` — A byte buffer containing the PDF data.
@@ -33,7 +24,7 @@ pub enum PdfInput {
/// Represents a single text item extracted from a PDF page,
/// including its content, position, size, rotation, and font metadata.
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Default, Serialize)]
pub struct TextItem {
pub text: String,
/// Viewport-space coordinates (top-left origin, 72 DPI).
@@ -137,35 +128,12 @@ mod tests {
y: 2.0,
width: 10.0,
height: 4.0,
- rotation: 0.0,
font_name: Some("Arial".into()),
font_size: Some(12.0),
- font_height: None,
- font_ascent: None,
- font_descent: None,
- font_weight: None,
- font_flags: None,
- text_width: None,
- font_is_buggy: false,
- mcid: None,
- fill_color: None,
- stroke_color: None,
- confidence: None,
+ ..Default::default()
}
}
- #[test]
- fn output_format_serializes() {
- assert_eq!(
- serde_json::to_string(&OutputFormat::Json).unwrap(),
- "\"Json\""
- );
- assert_eq!(
- serde_json::to_string(&OutputFormat::Text).unwrap(),
- "\"Text\""
- );
- }
-
#[test]
fn input_type_roundtrip() {
let v = InputType::FilePath("/tmp/x.pdf".into());