Skip to content

A fast, helpful, and open-source document parser

align to typescript

Logan Markewich790168eb0eb4
diff --git a/packages/rust/crates/liteparse/src/config.rs b/packages/rust/crates/liteparse/src/config.rs
new file mode 100644
index 0000000..d47c9de
--- /dev/null
+++ b/packages/rust/crates/liteparse/src/config.rs
@@ -0,0 +1,98 @@
+use serde::{Deserialize, Serialize};
+
+/// Configuration for LiteParse document parsing.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LiteParseConfig {
+ /// OCR language code (Tesseract format: "eng", "fra", "deu", etc.).
+ pub ocr_language: String,
+ /// Whether OCR is enabled. When true, runs on text-sparse pages and embedded images.
+ pub ocr_enabled: bool,
+ /// Path to tessdata directory. Falls back to TESSDATA_PREFIX env var if not set.
+ pub tessdata_path: Option<String>,
+ /// Maximum number of pages to parse.
+ pub max_pages: usize,
+ /// Specific pages to parse (e.g., "1-5,10,15-20"). None means all pages.
+ pub target_pages: Option<String>,
+ /// DPI for rendering pages (used for OCR and screenshots).
+ pub dpi: f32,
+ /// Output format.
+ pub output_format: OutputFormat,
+ /// Keep very small text that would normally be filtered out.
+ pub preserve_very_small_text: bool,
+ /// Password for encrypted/protected documents.
+ pub password: Option<String>,
+ /// Suppress progress output.
+ pub quiet: bool,
+}
+
+/// Supported output formats.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum OutputFormat {
+ Json,
+ Text,
+}
+
+impl Default for LiteParseConfig {
+ fn default() -> Self {
+ Self {
+ ocr_language: "eng".to_string(),
+ ocr_enabled: true,
+ tessdata_path: None,
+ max_pages: 1000,
+ target_pages: None,
+ dpi: 150.0,
+ output_format: OutputFormat::Json,
+ preserve_very_small_text: false,
+ password: None,
+ quiet: false,
+ }
+ }
+}
+
+/// Parse a target pages string like "1-5,10,15-20" into a sorted list of page numbers.
+pub fn parse_target_pages(s: &str) -> Result<Vec<u32>, String> {
+ let mut pages = Vec::new();
+ for part in s.split(',') {
+ let part = part.trim();
+ if part.contains('-') {
+ let bounds: Vec<&str> = part.splitn(2, '-').collect();
+ let start: u32 = bounds[0]
+ .trim()
+ .parse()
+ .map_err(|_| format!("invalid page number: {}", bounds[0]))?;
+ let end: u32 = bounds[1]
+ .trim()
+ .parse()
+ .map_err(|_| format!("invalid page number: {}", bounds[1]))?;
+ if start > end {
+ return Err(format!("invalid range: {}-{}", start, end));
+ }
+ for p in start..=end {
+ pages.push(p);
+ }
+ } else {
+ let p: u32 = part
+ .parse()
+ .map_err(|_| format!("invalid page number: {}", part))?;
+ pages.push(p);
+ }
+ }
+ pages.sort();
+ pages.dedup();
+ Ok(pages)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_parse_target_pages() {
+ assert_eq!(parse_target_pages("1-5,10,15-20").unwrap(), vec![1, 2, 3, 4, 5, 10, 15, 16, 17, 18, 19, 20]);
+ assert_eq!(parse_target_pages("3").unwrap(), vec![3]);
+ assert_eq!(parse_target_pages("1,1,2").unwrap(), vec![1, 2]);
+ assert!(parse_target_pages("5-3").is_err());
+ assert!(parse_target_pages("abc").is_err());
+ }
+}
diff --git a/packages/rust/crates/liteparse/src/conversion.rs b/packages/rust/crates/liteparse/src/conversion.rs
new file mode 100644
index 0000000..4e076ff
--- /dev/null
+++ b/packages/rust/crates/liteparse/src/conversion.rs
@@ -0,0 +1,73 @@
+use std::path::Path;
+
+/// Supported file extensions for conversion (non-PDF formats).
+const OFFICE_EXTENSIONS: &[&str] = &[
+ "doc", "docx", "docm", "dot", "dotm", "dotx", "odt", "ott", "rtf", "pages",
+];
+const PRESENTATION_EXTENSIONS: &[&str] = &[
+ "ppt", "pptx", "pptm", "pot", "potm", "potx", "odp", "otp", "key",
+];
+const SPREADSHEET_EXTENSIONS: &[&str] = &[
+ "xls", "xlsx", "xlsm", "xlsb", "ods", "ots", "csv", "tsv", "numbers",
+];
+const IMAGE_EXTENSIONS: &[&str] = &[
+ "jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "webp", "svg",
+];
+
+/// Check if a file is a PDF (no conversion needed).
+pub fn is_pdf(path: &str) -> bool {
+ Path::new(path)
+ .extension()
+ .map(|ext| ext.eq_ignore_ascii_case("pdf"))
+ .unwrap_or(false)
+}
+
+/// Check if a file extension is supported (either PDF or convertible).
+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(),
+ None => return false,
+ };
+
+ if ext == "pdf" {
+ return true;
+ }
+
+ OFFICE_EXTENSIONS.contains(&ext.as_str())
+ || PRESENTATION_EXTENSIONS.contains(&ext.as_str())
+ || SPREADSHEET_EXTENSIONS.contains(&ext.as_str())
+ || IMAGE_EXTENSIONS.contains(&ext.as_str())
+}
+
+/// Attempt to convert a non-PDF file to PDF.
+///
+/// Currently stubbed out — returns an error directing users to install
+/// LibreOffice (for office documents) or ImageMagick (for images).
+pub fn convert_to_pdf(path: &str, _password: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
+ let ext = Path::new(path)
+ .extension()
+ .and_then(|e| e.to_str())
+ .map(|e| e.to_lowercase())
+ .unwrap_or_default();
+
+ if ext == "pdf" {
+ return Ok(path.to_string());
+ }
+
+ let tool = if OFFICE_EXTENSIONS.contains(&ext.as_str())
+ || PRESENTATION_EXTENSIONS.contains(&ext.as_str())
+ || SPREADSHEET_EXTENSIONS.contains(&ext.as_str())
+ {
+ "LibreOffice"
+ } else if IMAGE_EXTENSIONS.contains(&ext.as_str()) {
+ "ImageMagick"
+ } else {
+ return Err(format!("unsupported file format: .{}", ext).into());
+ };
+
+ Err(format!(
+ "conversion from .{ext} to PDF requires {tool}, which is not yet supported in the Rust port. \
+ Convert the file to PDF manually, or use the TypeScript version of LiteParse."
+ )
+ .into())
+}
diff --git a/packages/rust/crates/liteparse/src/extract.rs b/packages/rust/crates/liteparse/src/extract.rs
index d8551aa..1173992 100644
--- a/packages/rust/crates/liteparse/src/extract.rs
+++ b/packages/rust/crates/liteparse/src/extract.rs
@@ -39,6 +39,52 @@ pub fn extract_pages(
Ok(pages)
}
+/// Extract pages with filtering by target page list and max pages, with optional password.
+pub fn extract_pages_filtered(
+ pdf_path: &str,
+ 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 {
+ if !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)
+}
+
/// 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>> {
let pages = extract_pages(pdf_path, page_num)?;
diff --git a/packages/rust/crates/liteparse/src/lib.rs b/packages/rust/crates/liteparse/src/lib.rs
index 9f5e76b..66a9416 100644
--- a/packages/rust/crates/liteparse/src/lib.rs
+++ b/packages/rust/crates/liteparse/src/lib.rs
@@ -1,6 +1,10 @@
+pub mod config;
+pub mod conversion;
pub mod extract;
pub mod ocr;
pub mod ocr_merge;
+pub mod output;
+pub mod parser;
pub mod projection;
pub mod render;
pub mod types;
diff --git a/packages/rust/crates/liteparse/src/main.rs b/packages/rust/crates/liteparse/src/main.rs
index f9826d5..9b6d651 100644
--- a/packages/rust/crates/liteparse/src/main.rs
+++ b/packages/rust/crates/liteparse/src/main.rs
@@ -1,12 +1,12 @@
use clap::{Args, Parser, Subcommand};
+use liteparse_rs::config::{LiteParseConfig, OutputFormat};
+use liteparse_rs::conversion;
use liteparse_rs::extract;
-use liteparse_rs::ocr::tesseract::TesseractOcrEngine;
-use liteparse_rs::ocr_merge;
-use liteparse_rs::projection;
+use liteparse_rs::parser::LiteParse;
use liteparse_rs::render;
#[derive(Parser, Debug)]
-#[command(author, version, about, long_about = None)]
+#[command(name = "lit", version, about = "OSS document parsing tool (supports PDF, DOCX, XLSX, images, and more)")]
struct Cli {
#[command(subcommand)]
command: Commands,
@@ -14,40 +14,107 @@ struct Cli {
#[derive(Subcommand, Debug)]
enum Commands {
- /// Extract raw text items from a PDF file (no grid projection)
- Extract(PdfCommand),
- /// Parse a PDF file: extract + grid projection, output projected pages as JSON
+ /// Parse a document file (PDF, DOCX, XLSX, PPTX, images, etc.)
Parse(ParseCommand),
- /// Render a page to a PNG screenshot (file output)
+ /// Generate screenshots of PDF pages
Screenshot(ScreenshotCommand),
- /// Render a page to PNG and write to stdout
- ScreenshotStdout(ScreenshotStdoutCommand),
- /// Extract embedded image bounding boxes from a page
- ImageBounds(PdfCommand),
+ /// Parse multiple documents in batch mode
+ BatchParse(BatchParseCommand),
+ /// Extract raw text items from a PDF file (no grid projection) [dev tool]
+ Extract(ExtractCommand),
+ /// Extract embedded image bounding boxes from a page [dev tool]
+ ImageBounds(ExtractCommand),
}
#[derive(Args, Debug)]
-struct PdfCommand {
- /// Specify the path to the PDF file
+struct ParseCommand {
+ /// Input file path
+ file: String,
+
+ /// Output file path
+ #[arg(short, long)]
+ output: Option<String>,
+
+ /// Output format: json or text
+ #[arg(long, default_value = "text")]
+ format: String,
+
+ /// Disable OCR
#[arg(long)]
- pdf_path: String,
+ no_ocr: bool,
+
+ /// OCR language (Tesseract format, e.g. "eng", "fra", "deu")
+ #[arg(long, default_value = "eng")]
+ ocr_language: String,
- /// Optionally specify a target page number
+ /// Path to tessdata directory (overrides TESSDATA_PREFIX env var)
#[arg(long)]
- page_num: Option<u32>,
+ tessdata_path: Option<String>,
+
+ /// Max pages to parse
+ #[arg(long, default_value = "1000")]
+ max_pages: usize,
+
+ /// Target pages (e.g., "1-5,10,15-20")
+ #[arg(long)]
+ target_pages: Option<String>,
+
+ /// DPI for rendering (default: 150)
+ #[arg(long, default_value = "150")]
+ dpi: f32,
+
+ /// Preserve very small text
+ #[arg(long)]
+ preserve_small_text: bool,
+
+ /// Password for encrypted/protected documents
+ #[arg(long)]
+ password: Option<String>,
+
+ /// Suppress progress output
+ #[arg(short, long)]
+ quiet: bool,
}
#[derive(Args, Debug)]
-struct ParseCommand {
- /// Specify the path to the PDF file
+struct ScreenshotCommand {
+ /// Input file path
+ file: String,
+
+ /// Output directory for screenshots
+ #[arg(short, long, default_value = "./screenshots")]
+ output_dir: String,
+
+ /// Target pages (e.g., "1,3,5" or "1-5"). Defaults to all pages.
#[arg(long)]
- pdf_path: String,
+ target_pages: Option<String>,
- /// Optionally specify a target page number
+ /// DPI for rendering
+ #[arg(long, default_value = "150")]
+ dpi: f32,
+
+ /// Password for encrypted/protected documents
#[arg(long)]
- page_num: Option<u32>,
+ password: Option<String>,
+
+ /// Suppress progress output
+ #[arg(short, long)]
+ quiet: bool,
+}
+
+#[derive(Args, Debug)]
+struct BatchParseCommand {
+ /// Input directory
+ input_dir: String,
+
+ /// Output directory
+ output_dir: String,
- /// Disable OCR (by default, OCR runs on text-sparse pages and embedded images)
+ /// Output format: json or text
+ #[arg(long, default_value = "text")]
+ format: String,
+
+ /// Disable OCR
#[arg(long)]
no_ocr: bool,
@@ -59,89 +126,214 @@ struct ParseCommand {
#[arg(long)]
tessdata_path: Option<String>,
- /// DPI for rendering pages for OCR (default: 150)
+ /// Max pages to parse per file
+ #[arg(long, default_value = "1000")]
+ max_pages: usize,
+
+ /// DPI for rendering
#[arg(long, default_value = "150")]
- ocr_dpi: f32,
-}
+ dpi: f32,
-#[derive(Args, Debug)]
-struct ScreenshotCommand {
- /// Specify the path to the PDF file
+ /// Recursively search input directory
#[arg(long)]
- pdf_path: String,
+ recursive: bool,
- /// Target page number (1-based)
+ /// Only process files with this extension (e.g., ".pdf")
#[arg(long)]
- page_num: u32,
+ extension: Option<String>,
- /// Output PNG file path
+ /// Password for encrypted/protected documents
#[arg(long)]
- output: String,
+ password: Option<String>,
- /// DPI for rendering (default: 150)
- #[arg(long, default_value = "150")]
- dpi: f32,
+ /// Suppress progress output
+ #[arg(short, long)]
+ quiet: bool,
}
#[derive(Args, Debug)]
-struct ScreenshotStdoutCommand {
- /// Specify the path to the PDF file
+struct ExtractCommand {
+ /// Input PDF file path
#[arg(long)]
pdf_path: String,
/// Target page number (1-based)
#[arg(long)]
- page_num: u32,
+ page_num: Option<u32>,
+}
- /// DPI for rendering (default: 150)
- #[arg(long, default_value = "150")]
- dpi: f32,
+fn parse_output_format(s: &str) -> Result<OutputFormat, String> {
+ match s.to_lowercase().as_str() {
+ "json" => Ok(OutputFormat::Json),
+ "text" => Ok(OutputFormat::Text),
+ _ => Err(format!("unknown format '{}', expected 'json' or 'text'", s)),
+ }
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match cli.command {
- Commands::Extract(cmd) => {
- extract::extract(&cmd.pdf_path, cmd.page_num)?;
- }
Commands::Parse(cmd) => {
- let t0 = std::time::Instant::now();
- let mut pages = extract::extract_pages(&cmd.pdf_path, cmd.page_num)?;
- let t1 = std::time::Instant::now();
-
- if !cmd.no_ocr {
- let engine = TesseractOcrEngine::new(cmd.tessdata_path);
- ocr_merge::ocr_and_merge_pages(
- &mut pages,
- &cmd.pdf_path,
- cmd.ocr_dpi,
- &engine,
- &cmd.ocr_language,
- )?;
+ let format = parse_output_format(&cmd.format)?;
+
+ let config = LiteParseConfig {
+ ocr_language: cmd.ocr_language,
+ ocr_enabled: !cmd.no_ocr,
+ tessdata_path: cmd.tessdata_path,
+ max_pages: cmd.max_pages,
+ target_pages: cmd.target_pages,
+ dpi: cmd.dpi,
+ output_format: format,
+ preserve_very_small_text: cmd.preserve_small_text,
+ password: cmd.password,
+ quiet: cmd.quiet,
+ };
+
+ let lp = LiteParse::new(config);
+ let result = lp.parse(&cmd.file)?;
+ let formatted = lp.format(&result)?;
+
+ match cmd.output {
+ Some(path) => {
+ std::fs::write(&path, &formatted)?;
+ if !cmd.quiet {
+ eprintln!("[liteparse] wrote output to {}", path);
+ }
+ }
+ None => {
+ println!("{}", formatted);
+ }
+ }
+ }
+
+ Commands::Screenshot(cmd) => {
+ let target_pages = cmd
+ .target_pages
+ .as_ref()
+ .map(|s| liteparse_rs::config::parse_target_pages(s))
+ .transpose()
+ .map_err(|e| format!("invalid --target-pages: {}", e))?;
+
+ std::fs::create_dir_all(&cmd.output_dir)?;
+
+ let lib = pdfium::Library::init();
+ let document = lib.load_document(&cmd.file, cmd.password.as_deref())?;
+ let page_count = document.page_count();
+
+ for page_index in 0..page_count {
+ let page_number = page_index as u32 + 1;
+
+ if let Some(ref targets) = target_pages {
+ if !targets.contains(&page_number) {
+ continue;
+ }
+ }
+
+ let output_path = format!("{}/page_{}.png", cmd.output_dir, page_number);
+ render::screenshot(&cmd.file, page_number, cmd.dpi, &output_path)?;
+
+ if !cmd.quiet {
+ eprintln!("[liteparse] screenshot page {} → {}", page_number, output_path);
+ }
+ }
+ }
+
+ Commands::BatchParse(cmd) => {
+ let format = parse_output_format(&cmd.format)?;
+ let ext_filter = cmd.extension.as_ref().map(|e| {
+ let e = e.to_lowercase();
+ if e.starts_with('.') { e } else { format!(".{}", e) }
+ });
+
+ let config = LiteParseConfig {
+ ocr_language: cmd.ocr_language,
+ ocr_enabled: !cmd.no_ocr,
+ tessdata_path: cmd.tessdata_path,
+ max_pages: cmd.max_pages,
+ target_pages: None,
+ dpi: cmd.dpi,
+ output_format: format.clone(),
+ preserve_very_small_text: false,
+ password: cmd.password,
+ quiet: cmd.quiet,
+ };
+
+ let lp = LiteParse::new(config);
+ let out_ext = if format == OutputFormat::Json { "json" } else { "txt" };
+
+ std::fs::create_dir_all(&cmd.output_dir)?;
+
+ let files = collect_files(&cmd.input_dir, cmd.recursive, ext_filter.as_deref())?;
+
+ if files.is_empty() {
+ eprintln!("[liteparse] no matching files found in {}", cmd.input_dir);
+ return Ok(());
+ }
+
+ if !cmd.quiet {
+ eprintln!("[liteparse] found {} files to process", files.len());
+ }
+
+ let mut success = 0usize;
+ let mut errors = 0usize;
+
+ for file_path in &files {
+ let t0 = std::time::Instant::now();
+
+ // Build output path: mirror directory structure
+ let rel = file_path
+ .strip_prefix(&cmd.input_dir)
+ .unwrap_or(file_path);
+ let out_path = std::path::Path::new(&cmd.output_dir)
+ .join(rel)
+ .with_extension(out_ext);
+
+ if let Some(parent) = out_path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+
+ match lp.parse(file_path) {
+ Ok(result) => match lp.format(&result) {
+ Ok(formatted) => {
+ std::fs::write(&out_path, &formatted)?;
+ success += 1;
+ if !cmd.quiet {
+ let elapsed = t0.elapsed().as_secs_f64() * 1000.0;
+ eprintln!(
+ "[liteparse] {} → {} ({:.1}ms)",
+ file_path,
+ out_path.display(),
+ elapsed
+ );
+ }
+ }
+ Err(e) => {
+ eprintln!("[liteparse] error formatting {}: {}", file_path, e);
+ errors += 1;
+ }
+ },
+ Err(e) => {
+ eprintln!("[liteparse] error parsing {}: {}", file_path, e);
+ errors += 1;
+ }
+ }
}
- let t_ocr = std::time::Instant::now();
- let parsed_pages = projection::project_pages_to_grid(pages);
- let t2 = std::time::Instant::now();
- let json = serde_json::to_string(&parsed_pages)?;
- let t3 = std::time::Instant::now();
- println!("{}", json);
eprintln!(
- "[rust-bin] extract: {:.1}ms, ocr: {:.1}ms, project: {:.1}ms, serialize: {:.1}ms, total: {:.1}ms",
- t1.duration_since(t0).as_secs_f64() * 1000.0,
- t_ocr.duration_since(t1).as_secs_f64() * 1000.0,
- t2.duration_since(t_ocr).as_secs_f64() * 1000.0,
- t3.duration_since(t2).as_secs_f64() * 1000.0,
- t3.duration_since(t0).as_secs_f64() * 1000.0,
+ "[liteparse] batch complete: {} succeeded, {} failed",
+ success, errors
);
+
+ if errors > 0 {
+ std::process::exit(1);
+ }
}
- Commands::Screenshot(cmd) => {
- render::screenshot(&cmd.pdf_path, cmd.page_num, cmd.dpi, &cmd.output)?;
- }
- Commands::ScreenshotStdout(cmd) => {
- render::screenshot_to_stdout(&cmd.pdf_path, cmd.page_num, cmd.dpi)?;
+
+ Commands::Extract(cmd) => {
+ extract::extract(&cmd.pdf_path, cmd.page_num)?;
}
+
Commands::ImageBounds(cmd) => {
render::image_bounds(&cmd.pdf_path, cmd.page_num)?;
}
@@ -149,3 +341,47 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
+
+/// Collect files from a directory, optionally recursively, with an optional extension filter.
+fn collect_files(
+ dir: &str,
+ recursive: bool,
+ ext_filter: Option<&str>,
+) -> Result<Vec<String>, Box<dyn std::error::Error>> {
+ let mut files = Vec::new();
+ collect_files_inner(std::path::Path::new(dir), recursive, ext_filter, &mut files)?;
+ files.sort();
+ Ok(files)
+}
+
+fn collect_files_inner(
+ dir: &std::path::Path,
+ recursive: bool,
+ ext_filter: Option<&str>,
+ files: &mut Vec<String>,
+) -> Result<(), Box<dyn std::error::Error>> {
+ for entry in std::fs::read_dir(dir)? {
+ let entry = entry?;
+ let path = entry.path();
+
+ if path.is_dir() {
+ if recursive {
+ collect_files_inner(&path, recursive, ext_filter, files)?;
+ }
+ continue;
+ }
+
+ let path_str = path.to_string_lossy().to_string();
+
+ if let Some(filter) = ext_filter {
+ if !path_str.to_lowercase().ends_with(filter) {
+ continue;
+ }
+ } else if !conversion::is_supported_extension(&path_str) {
+ continue;
+ }
+
+ files.push(path_str);
+ }
+ Ok(())
+}
diff --git a/packages/rust/crates/liteparse/src/output/json.rs b/packages/rust/crates/liteparse/src/output/json.rs
new file mode 100644
index 0000000..29f6e44
--- /dev/null
+++ b/packages/rust/crates/liteparse/src/output/json.rs
@@ -0,0 +1,66 @@
+use crate::types::ParsedPage;
+use serde::Serialize;
+
+#[derive(Debug, Serialize)]
+pub struct JsonTextItem {
+ pub text: String,
+ pub x: f32,
+ pub y: f32,
+ pub width: f32,
+ pub height: f32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub font_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub font_size: Option<f32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub confidence: Option<f32>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct JsonPage {
+ pub page: usize,
+ pub width: f32,
+ pub height: f32,
+ pub text: String,
+ pub text_items: Vec<JsonTextItem>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct ParseResultJson {
+ pub pages: Vec<JsonPage>,
+}
+
+/// Build structured JSON output from parsed pages.
+pub fn build_json(pages: &[ParsedPage]) -> ParseResultJson {
+ ParseResultJson {
+ pages: pages
+ .iter()
+ .map(|page| JsonPage {
+ page: page.page_number,
+ width: page.page_width,
+ height: page.page_height,
+ text: page.text.clone(),
+ text_items: page
+ .text_items
+ .iter()
+ .map(|item| JsonTextItem {
+ text: item.text.clone(),
+ x: item.x,
+ y: item.y,
+ width: item.width,
+ height: item.height,
+ font_name: item.font_name.clone(),
+ font_size: item.font_size,
+ confidence: item.confidence.or(Some(1.0)),
+ })
+ .collect(),
+ })
+ .collect(),
+ }
+}
+
+/// Format parsed pages as pretty-printed JSON string.
+pub fn format_json(pages: &[ParsedPage]) -> Result<String, serde_json::Error> {
+ let result = build_json(pages);
+ serde_json::to_string_pretty(&result)
+}
diff --git a/packages/rust/crates/liteparse/src/output/mod.rs b/packages/rust/crates/liteparse/src/output/mod.rs
new file mode 100644
index 0000000..1c593c8
--- /dev/null
+++ b/packages/rust/crates/liteparse/src/output/mod.rs
@@ -0,0 +1,2 @@
+pub mod json;
+pub mod text;
diff --git a/packages/rust/crates/liteparse/src/output/text.rs b/packages/rust/crates/liteparse/src/output/text.rs
new file mode 100644
index 0000000..5886af3
--- /dev/null
+++ b/packages/rust/crates/liteparse/src/output/text.rs
@@ -0,0 +1,10 @@
+use crate::types::ParsedPage;
+
+/// Format parsed pages as plain text with page headers.
+pub fn format_text(pages: &[ParsedPage]) -> String {
+ pages
+ .iter()
+ .map(|page| format!("\n--- Page {} ---\n{}", page.page_number, page.text))
+ .collect::<Vec<_>>()
+ .join("\n\n")
+}
diff --git a/packages/rust/crates/liteparse/src/parser.rs b/packages/rust/crates/liteparse/src/parser.rs
new file mode 100644
index 0000000..594a0ee
--- /dev/null
+++ b/packages/rust/crates/liteparse/src/parser.rs
@@ -0,0 +1,119 @@
+use crate::config::{parse_target_pages, LiteParseConfig, OutputFormat};
+use crate::conversion;
+use crate::extract;
+use crate::ocr::tesseract::TesseractOcrEngine;
+use crate::ocr_merge;
+use crate::output::{json, text};
+use crate::projection;
+use crate::types::ParsedPage;
+
+/// Result of parsing a document.
+pub struct ParseResult {
+ /// Parsed pages with projected text layout.
+ pub pages: Vec<ParsedPage>,
+ /// Full document text, concatenated from all pages.
+ pub text: String,
+}
+
+/// Main LiteParse orchestrator.
+pub struct LiteParse {
+ config: LiteParseConfig,
+}
+
+impl LiteParse {
+ pub fn new(config: LiteParseConfig) -> Self {
+ Self { config }
+ }
+
+ /// Parse a document file, returning structured results.
+ pub fn parse(&self, input: &str) -> Result<ParseResult, Box<dyn std::error::Error>> {
+ let log = |msg: &str| {
+ if !self.config.quiet {
+ eprintln!("{}", msg);
+ }
+ };
+
+ // Resolve input to a PDF path (convert if needed)
+ let pdf_path = if conversion::is_pdf(input) {
+ input.to_string()
+ } else {
+ conversion::convert_to_pdf(input, self.config.password.as_deref())?
+ };
+
+ let t0 = std::time::Instant::now();
+
+ // Determine which pages to extract
+ let target_pages = self
+ .config
+ .target_pages
+ .as_ref()
+ .map(|s| parse_target_pages(s))
+ .transpose()
+ .map_err(|e| format!("invalid --target-pages: {}", e))?;
+
+ // Extract text items from PDF pages
+ let mut pages = extract::extract_pages_filtered(
+ &pdf_path,
+ target_pages.as_deref(),
+ self.config.max_pages,
+ self.config.password.as_deref(),
+ )?;
+ let t1 = std::time::Instant::now();
+ log(&format!(
+ "[liteparse] extract: {:.1}ms ({} pages)",
+ t1.duration_since(t0).as_secs_f64() * 1000.0,
+ pages.len()
+ ));
+
+ // OCR pass
+ if self.config.ocr_enabled {
+ let engine = TesseractOcrEngine::new(self.config.tessdata_path.clone());
+ ocr_merge::ocr_and_merge_pages(
+ &mut pages,
+ &pdf_path,
+ self.config.dpi,
+ &engine,
+ &self.config.ocr_language,
+ )?;
+ }
+ let t_ocr = std::time::Instant::now();
+ log(&format!(
+ "[liteparse] ocr: {:.1}ms",
+ t_ocr.duration_since(t1).as_secs_f64() * 1000.0
+ ));
+
+ // Grid projection
+ let parsed_pages = projection::project_pages_to_grid(pages);
+ let t2 = std::time::Instant::now();
+ log(&format!(
+ "[liteparse] project: {:.1}ms",
+ t2.duration_since(t_ocr).as_secs_f64() * 1000.0
+ ));
+
+ let full_text = parsed_pages
+ .iter()
+ .map(|p| p.text.as_str())
+ .collect::<Vec<_>>()
+ .join("\n\n");
+
+ let total = t2.duration_since(t0).as_secs_f64() * 1000.0;
+ log(&format!("[liteparse] total: {:.1}ms", total));
+
+ Ok(ParseResult {
+ pages: parsed_pages,
+ text: full_text,
+ })
+ }
+
+ /// Format a parse result according to the configured output format.
+ pub fn format(&self, result: &ParseResult) -> Result<String, Box<dyn std::error::Error>> {
+ match self.config.output_format {
+ OutputFormat::Json => Ok(json::format_json(&result.pages)?),
+ OutputFormat::Text => Ok(text::format_text(&result.pages)),
+ }
+ }
+
+ pub fn config(&self) -> &LiteParseConfig {
+ &self.config
+ }
+}