Skip to content

A fast, helpful, and open-source document parser

fix: restore piped cli file support

Logan Markewicha5ea09162569
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index b13ab5c..d10d77c 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -3,6 +3,7 @@ use liteparse::config::{ImageMode, LiteParseConfig, OutputFormat};
use liteparse::conversion;
use liteparse::output::{json, text};
use liteparse::parser::LiteParse;
+use liteparse::types::PdfInput;
#[derive(Parser, Debug)]
#[command(
@@ -23,6 +24,8 @@ enum Commands {
Screenshot(ScreenshotCommand),
/// Parse multiple documents in batch mode
BatchParse(BatchParseCommand),
+ /// Check if a document is 'complex' enough to require OCR or advanced parsing
+ IsComplex(IsComplexCommand),
}
#[derive(Args, Debug)]
@@ -93,6 +96,24 @@ struct ScreenshotCommand {
quiet: bool,
}
+#[derive(Args, Debug)]
+struct IsComplexCommand {
+ /// Input file path (or `-` to read the document from stdin)
+ file: String,
+ /// Emit dense, whitespace-free JSON instead of pretty-printed (still valid
+ /// for `jq` and friends).
+ #[arg(long)]
+ compact: bool,
+ #[arg(long, default_value = "1000")]
+ max_pages: usize,
+ #[arg(long)]
+ target_pages: Option<String>,
+ #[arg(long)]
+ password: Option<String>,
+ #[arg(short, long)]
+ quiet: bool,
+}
+
#[derive(Args, Debug)]
struct BatchParseCommand {
input_dir: String,
@@ -167,6 +188,21 @@ fn parse_image_mode(s: &str) -> Result<ImageMode, String> {
}
}
+/// Read all bytes from stdin, used when the input path is `-` (e.g. a piped
+/// document: `curl -sL … | lit parse -`).
+fn read_stdin_bytes() -> Result<Vec<u8>, std::io::Error> {
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ std::io::stdin().lock().read_to_end(&mut bytes)?;
+ if bytes.is_empty() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ "no data on stdin (input `-` expects a document piped in, e.g. `curl … | lit parse -`)",
+ ));
+ }
+ Ok(bytes)
+}
+
/// Run the CLI with the given args (typically from sys.argv).
pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse_from(args);
@@ -198,7 +234,11 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
config.num_workers = n;
}
let lp = LiteParse::new(config);
- let result = rt.block_on(lp.parse(&cmd.file))?;
+ let result = if cmd.file == "-" {
+ rt.block_on(lp.parse_input(PdfInput::Bytes(read_stdin_bytes()?)))?
+ } else {
+ rt.block_on(lp.parse(&cmd.file))?
+ };
let formatted = match lp.config().output_format {
OutputFormat::Json => json::format_json(&result.pages)?,
OutputFormat::Text => text::format_text(&result.pages),
@@ -369,6 +409,57 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
std::process::exit(1);
}
}
+ Commands::IsComplex(cmd) => {
+ let config = LiteParseConfig {
+ max_pages: cmd.max_pages,
+ target_pages: cmd.target_pages,
+ password: cmd.password,
+ quiet: cmd.quiet,
+ ..Default::default()
+ };
+ let lp = LiteParse::new(config);
+ let input = if cmd.file == "-" {
+ PdfInput::Bytes(read_stdin_bytes()?)
+ } else {
+ PdfInput::Path(cmd.file)
+ };
+ let is_complex = rt.block_on(lp.is_complex(input))?;
+
+ let complex_pages = is_complex.iter().filter(|c| c.needs_ocr).count();
+
+ // Always emit JSON on stdout so the command composes with `jq` and
+ // friends without a flag. Pretty by default for human readability;
+ // `--compact` drops the whitespace. Both parse identically.
+ let json = if cmd.compact {
+ serde_json::to_string(&is_complex)?
+ } else {
+ serde_json::to_string_pretty(&is_complex)?
+ };
+ println!("{}", json);
+
+ // The human-readable verdict goes to stderr so it never pollutes the
+ // JSON on stdout. The exit code below carries the same signal for
+ // scripts that don't want to read either stream.
+ if !cmd.quiet {
+ let verdict = if complex_pages > 0 {
+ "COMPLEX"
+ } else {
+ "SIMPLE"
+ };
+ eprintln!(
+ "{} — {}/{} page(s) need OCR",
+ verdict,
+ complex_pages,
+ is_complex.len()
+ );
+ }
+
+ // Exit non-zero when any page needs OCR, so the command is usable as
+ // a shell predicate: exit 0 (simple) → `&& parse --no-ocr` is safe.
+ if complex_pages > 0 {
+ std::process::exit(1);
+ }
+ }
}
Ok(())
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index 241616a..021ebcb 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -271,6 +271,22 @@ fn parse_output_format(s: &str) -> Result<OutputFormat, String> {
}
/// Parse a `Name: Value` header string into a `(name, value)` pair.
+/// Read all bytes from stdin, used when the input path is `-` (e.g. a piped
+/// document: `curl -sL … | lit parse -`). Errors carry a hint so a common
+/// mistake — passing `-` with nothing piped — is diagnosable.
+fn read_stdin_bytes() -> Result<Vec<u8>, std::io::Error> {
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ std::io::stdin().lock().read_to_end(&mut bytes)?;
+ if bytes.is_empty() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ "no data on stdin (input `-` expects a document piped in, e.g. `curl … | lit parse -`)",
+ ));
+ }
+ Ok(bytes)
+}
+
fn parse_header(s: &str) -> Result<(String, String), String> {
let (name, value) = s
.split_once(':')
@@ -327,7 +343,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
let lp = LiteParse::new(config);
- let result = lp.parse(&cmd.file).await?;
+ let result = if cmd.file == "-" {
+ lp.parse_input(PdfInput::Bytes(read_stdin_bytes()?)).await?
+ } else {
+ lp.parse(&cmd.file).await?
+ };
let formatted = match lp.config().output_format {
OutputFormat::Json => json::format_json(&result.pages)?,
OutputFormat::Text => text::format_text(&result.pages),
@@ -524,7 +544,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
..Default::default()
};
let lp = LiteParse::new(config);
- let is_complex = lp.is_complex(PdfInput::Path(cmd.file)).await?;
+ let input = if cmd.file == "-" {
+ PdfInput::Bytes(read_stdin_bytes()?)
+ } else {
+ PdfInput::Path(cmd.file)
+ };
+ let is_complex = lp.is_complex(input).await?;
let complex_pages = is_complex.iter().filter(|c| c.needs_ocr).count();
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index 7ba78b7..c9d5f69 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -73,6 +73,12 @@ export interface JsLiteParseConfig {
* false. Use to exclude rotated watermarks/stamps from the output.
*/
skipDiagonalText?: boolean
+ /**
+ * Compute per-page complexity signals during parse and attach them to each
+ * page as `ParsedPage.complexity` (the same signals `isComplex` returns).
+ * Default false; enabling it runs an extra vector-text detection pass.
+ */
+ includeComplexity?: boolean
}
/**
* A page sub-region as the fraction cropped from each side (top-left origin,
@@ -159,6 +165,7 @@ export interface JsParsedPage {
text: string
markdown: string
textItems: Array<JsTextItem>
+ complexity?: JsPageComplexityStats
}
export interface JsParseResult {
pages: Array<JsParsedPage>
diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.ts
index 79ccce9..39df8c6 100644
--- a/packages/node/src/cli.ts
+++ b/packages/node/src/cli.ts
@@ -10,6 +10,27 @@ program
.description("Fast, lightweight PDF and document parsing")
.version("2.0.0");
+/**
+ * Resolve a CLI `<file>` argument into a parser input. `-` means read the
+ * document from stdin (e.g. `curl -sL … | liteparse parse -`); anything else is
+ * passed through as a path. Streaming stdin (rather than `readFileSync(0)`)
+ * avoids EAGAIN on non-blocking pipes.
+ */
+async function resolveInput(file: string): Promise<string | Buffer> {
+ if (file !== "-") return file;
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(chunk as Buffer);
+ }
+ const bytes = Buffer.concat(chunks);
+ if (bytes.length === 0) {
+ throw new Error(
+ "no data on stdin (input `-` expects a document piped in, e.g. `curl … | liteparse parse -`)",
+ );
+ }
+ return bytes;
+}
+
/** Collect repeated `--ocr-server-header "Name: Value"` flags into an object. */
function collectHeader(
value: string,
@@ -101,7 +122,7 @@ program
if (!config.outputFormat) config.outputFormat = "text";
const parser = new LiteParse(config);
- const result = await parser.parse(file);
+ const result = await parser.parse(await resolveInput(file));
const output =
config.outputFormat === "json"
@@ -169,7 +190,7 @@ program
if (opts.quiet) config.quiet = true;
const parser = new LiteParse(config);
- const stats = await parser.isComplex(file);
+ const stats = await parser.isComplex(await resolveInput(file));
const complexPages = stats.filter((s) => s.needsOcr).length;