Skip to content

A fast, helpful, and open-source document parser

remove format() method

Logan Markewich3aceb4371207
diff --git a/crates/liteparse-napi/src/lib.rs b/crates/liteparse-napi/src/lib.rs
index 3edf545..d21ba4d 100644
--- a/crates/liteparse-napi/src/lib.rs
+++ b/crates/liteparse-napi/src/lib.rs
@@ -101,15 +101,6 @@ impl LiteParse {
Ok(results)
}
- /// Format a parse result according to the configured output format.
- #[napi]
- pub fn format(&self, result: JsParseResult) -> Result<String> {
- let rust_result = result.to_rust();
- self.inner
- .format(&rust_result)
- .map_err(|e| Error::from_reason(e.to_string()))
- }
-
/// Get the current configuration.
#[napi(getter)]
pub fn config(&self) -> JsLiteParseConfig {
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index d25677e..d5d6cb6 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -187,44 +187,4 @@ impl JsParseResult {
}
}
- pub fn to_rust(&self) -> ParseResult {
- ParseResult {
- pages: self
- .pages
- .iter()
- .map(|p| ParsedPage {
- page_number: p.page_num as usize,
- page_width: p.width as f32,
- page_height: p.height as f32,
- text: p.text.clone(),
- text_items: p
- .text_items
- .iter()
- .map(|item| TextItem {
- text: item.text.clone(),
- x: item.x as f32,
- y: item.y as f32,
- width: item.width as f32,
- height: item.height as f32,
- rotation: 0.0,
- font_name: item.font_name.clone(),
- font_size: item.font_size.map(|v| v as f32),
- 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: item.confidence.map(|v| v as f32),
- })
- .collect(),
- })
- .collect(),
- text: self.text.clone(),
- }
- }
}
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index 0deacdc..2d329bd 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -2,6 +2,7 @@ use clap::{Args, Parser, Subcommand};
use liteparse::config::{LiteParseConfig, OutputFormat};
use liteparse::conversion;
use liteparse::extract;
+use liteparse::output::{json, text};
use liteparse::parser::LiteParse;
use liteparse::render;
@@ -141,7 +142,10 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
};
let lp = LiteParse::new(config);
let result = rt.block_on(lp.parse(&cmd.file))?;
- let formatted = lp.format(&result)?;
+ let formatted = match lp.config().output_format {
+ OutputFormat::Json => json::format_json(&result.pages)?,
+ OutputFormat::Text => text::format_text(&result.pages),
+ };
match cmd.output {
Some(path) => {
std::fs::write(&path, &formatted)?;
@@ -243,25 +247,34 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
}
match rt.block_on(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
- );
+ Ok(result) => {
+ let fmt_result: Result<String, Box<dyn std::error::Error>> =
+ match lp.config().output_format {
+ OutputFormat::Json => {
+ json::format_json(&result.pages).map_err(|e| e.into())
+ }
+ OutputFormat::Text => Ok(text::format_text(&result.pages)),
+ };
+ match fmt_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 formatting {}: {}", file_path, e);
- errors += 1;
- }
- },
+ }
Err(e) => {
eprintln!("[liteparse] error parsing {}: {}", file_path, e);
errors += 1;
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index 3307693..0c70552 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -133,46 +133,6 @@ impl PyParseResult {
}
}
- fn to_rust(&self) -> liteparse::parser::ParseResult {
- liteparse::parser::ParseResult {
- pages: self
- .pages
- .iter()
- .map(|p| liteparse::types::ParsedPage {
- page_number: p.page_num as usize,
- page_width: p.width as f32,
- page_height: p.height as f32,
- text: p.text.clone(),
- text_items: p
- .text_items
- .iter()
- .map(|item| liteparse::types::TextItem {
- text: item.text.clone(),
- x: item.x as f32,
- y: item.y as f32,
- width: item.width as f32,
- height: item.height as f32,
- rotation: 0.0,
- font_name: item.font_name.clone(),
- font_size: item.font_size.map(|v| v as f32),
- 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: item.confidence.map(|v| v as f32),
- })
- .collect(),
- })
- .collect(),
- text: self.text.clone(),
- }
- }
}
#[pyclass(frozen, from_py_object)]
@@ -371,14 +331,6 @@ impl LiteParse {
Ok(results)
}
- /// Format a parse result according to the configured output format.
- fn format(&self, result: &PyParseResult) -> PyResult<String> {
- let rust_result = result.to_rust();
- self.inner
- .format(&rust_result)
- .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))
- }
-
fn __repr__(&self) -> String {
format!(
"LiteParse(ocr_enabled={}, dpi={}, max_pages={})",
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index e1bf4e8..f20ce85 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -2,7 +2,7 @@
//! WebAssembly bindings for LiteParse.
//!
//! Exposes a small JS-facing API mirroring `packages/node`:
-//! - `LiteParse` class with `new(config)`, `parse(Uint8Array)`, `format(result)`
+//! - `LiteParse` class with `new(config)`, `parse(Uint8Array)`
//! - JS-side OCR callback bridge (any object with an async `recognize` method)
use std::pin::Pin;
@@ -331,33 +331,4 @@ impl LiteParse {
.map_err(|e| JsError::new(&format!("serialize result failed: {}", e)))
}
- /// Format a parse result (JS object as returned from `parse`) as a string
- /// according to the configured `outputFormat` (`"json"` or `"text"`).
- pub fn format(&self, result: JsValue) -> Result<String, JsError> {
- // Round-trip via serde_json to reuse the same formatters as native.
- let pages_val = Reflect::get(&result, &JsValue::from_str("pages"))
- .map_err(|_| JsError::new("result.pages missing"))?;
- let raw_pages: serde_json::Value = serde_wasm_bindgen::from_value(pages_val)
- .map_err(|e| JsError::new(&format!("decode pages failed: {}", e)))?;
-
- match self.config.output_format {
- OutputFormat::Json => serde_json::to_string(&raw_pages)
- .map_err(|e| JsError::new(&format!("json encode failed: {}", e))),
- OutputFormat::Text => {
- // For text output, concatenate the per-page `text` strings.
- let mut out = String::new();
- if let Some(arr) = raw_pages.as_array() {
- for (i, p) in arr.iter().enumerate() {
- if i > 0 {
- out.push_str("\n\n");
- }
- if let Some(s) = p.get("text").and_then(|v| v.as_str()) {
- out.push_str(s);
- }
- }
- }
- Ok(out)
- }
- }
- }
}
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index edb9950..d131e59 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -2,6 +2,7 @@ use clap::{Args, Parser, Subcommand};
use liteparse::config::{LiteParseConfig, OutputFormat};
use liteparse::conversion;
use liteparse::extract;
+use liteparse::output::{json, text};
use liteparse::parser::LiteParse;
use liteparse::render;
@@ -206,7 +207,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let lp = LiteParse::new(config);
let result = lp.parse(&cmd.file).await?;
- let formatted = lp.format(&result)?;
+ let formatted = match lp.config().output_format {
+ OutputFormat::Json => json::format_json(&result.pages)?,
+ OutputFormat::Text => text::format_text(&result.pages),
+ };
match cmd.output {
Some(path) => {
@@ -318,25 +322,34 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
match lp.parse(file_path).await {
- 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
- );
+ Ok(result) => {
+ let fmt_result: Result<String, Box<dyn std::error::Error>> =
+ match lp.config().output_format {
+ OutputFormat::Json => {
+ json::format_json(&result.pages).map_err(|e| e.into())
+ }
+ OutputFormat::Text => Ok(text::format_text(&result.pages)),
+ };
+ match fmt_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 formatting {}: {}", file_path, e);
- errors += 1;
- }
- },
+ }
Err(e) => {
eprintln!("[liteparse] error parsing {}: {}", file_path, e);
errors += 1;
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 0e0946c..ecc01ab 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -1,4 +1,4 @@
-use crate::config::{LiteParseConfig, OutputFormat, parse_target_pages};
+use crate::config::{LiteParseConfig, parse_target_pages};
#[cfg(not(target_arch = "wasm32"))]
use crate::conversion;
use crate::extract;
@@ -8,7 +8,6 @@ use crate::ocr::http_simple::HttpOcrEngine;
#[cfg(feature = "tesseract")]
use crate::ocr::tesseract::TesseractOcrEngine;
use crate::ocr_merge;
-use crate::output::{json, text};
use crate::projection;
use crate::types::{ParsedPage, PdfInput};
@@ -174,14 +173,6 @@ impl LiteParse {
})
}
- /// 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
}
@@ -203,37 +194,4 @@ mod tests {
assert_eq!(lp.config().max_pages, 7);
}
- fn fake_result() -> ParseResult {
- ParseResult {
- pages: vec![ParsedPage {
- page_number: 1,
- page_width: 100.0,
- page_height: 200.0,
- text: "hello".into(),
- text_items: vec![],
- }],
- text: "hello".into(),
- }
- }
-
- #[test]
- #[allow(clippy::field_reassign_with_default)]
- fn test_format_json() {
- let mut cfg = LiteParseConfig::default();
- cfg.output_format = OutputFormat::Json;
- let lp = LiteParse::new(cfg);
- let s = lp.format(&fake_result()).unwrap();
- assert!(s.contains("\"page\""));
- assert!(s.contains("\"hello\""));
- }
-
- #[test]
- #[allow(clippy::field_reassign_with_default)]
- fn test_format_text() {
- let mut cfg = LiteParseConfig::default();
- cfg.output_format = OutputFormat::Text;
- let lp = LiteParse::new(cfg);
- let s = lp.format(&fake_result()).unwrap();
- assert!(s.contains("hello"));
- }
}