Skip to content

A fast, helpful, and open-source document parser

feat: add crop-box support, add ignore-diagonal-text support

Logan Markewich4735352e46f2
diff --git a/Cargo.lock b/Cargo.lock
index d4b7c43..d90a134 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1232,7 +1232,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "liteparse"
-version = "2.4.1"
+version = "2.5.0"
dependencies = [
"blake3",
"clap",
@@ -1256,7 +1256,7 @@ dependencies = [
[[package]]
name = "liteparse-napi"
-version = "2.4.1"
+version = "2.5.0"
dependencies = [
"image",
"liteparse",
@@ -1291,7 +1291,7 @@ dependencies = [
[[package]]
name = "liteparse-python"
-version = "2.4.1"
+version = "2.5.0"
dependencies = [
"anyhow",
"clap",
diff --git a/crates/liteparse-napi/Cargo.toml b/crates/liteparse-napi/Cargo.toml
index 86cf6c3..15bd80d 100644
--- a/crates/liteparse-napi/Cargo.toml
+++ b/crates/liteparse-napi/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "liteparse-napi"
-version = "2.4.1"
+version = "2.5.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
@@ -14,7 +14,7 @@ default = ["tesseract"]
tesseract = ["liteparse/tesseract"]
[dependencies]
-liteparse = { package = "liteparse", version = "2.4.1", path = "../liteparse", default-features = false }
+liteparse = { package = "liteparse", version = "2.5.0", path = "../liteparse", default-features = false }
pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.3.0", path = "../pdfium-sys" }
napi = { version = "2", features = ["async", "serde-json", "napi9"] }
napi-derive = "2"
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 848536d..7c0b1cf 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -2,7 +2,7 @@ use std::collections::HashMap;
use napi_derive::napi;
-use liteparse::config::{ImageMode, LiteParseConfig, OutputFormat};
+use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};
use liteparse::parser::ParseResult;
use liteparse::types::{GraphicPrimitive, Page, ParsedPage, Rect, TextItem, WordBox};
@@ -59,6 +59,24 @@ pub struct JsLiteParseConfig {
/// false. Word boxes roughly double the text-item payload, so enable only
/// for word-level bbox attribution.
pub emit_word_boxes: Option<bool>,
+ /// Restrict output to a page sub-region. Each field is the fraction of the
+ /// page cropped from that side; a text item survives only if it lies
+ /// entirely inside the remaining rectangle. Unset keeps the whole page.
+ pub crop_box: Option<JsCropBox>,
+ /// Drop diagonal text (rotation >2° off the nearest right angle). Default
+ /// false. Use to exclude rotated watermarks/stamps from the output.
+ pub skip_diagonal_text: Option<bool>,
+}
+
+/// A page sub-region as the fraction cropped from each side (top-left origin,
+/// each in `[0, 1]`).
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsCropBox {
+ pub top: f64,
+ pub right: f64,
+ pub bottom: f64,
+ pub left: f64,
}
impl JsLiteParseConfig {
@@ -126,6 +144,17 @@ impl JsLiteParseConfig {
if let Some(v) = self.emit_word_boxes {
cfg.emit_word_boxes = v;
}
+ if let Some(v) = self.crop_box {
+ cfg.crop_box = Some(CropBox {
+ top: v.top as f32,
+ right: v.right as f32,
+ bottom: v.bottom as f32,
+ left: v.left as f32,
+ });
+ }
+ if let Some(v) = self.skip_diagonal_text {
+ cfg.skip_diagonal_text = v;
+ }
cfg
}
@@ -166,6 +195,13 @@ impl JsLiteParseConfig {
.collect(),
),
emit_word_boxes: Some(cfg.emit_word_boxes),
+ crop_box: cfg.crop_box.map(|c| JsCropBox {
+ top: c.top as f64,
+ right: c.right as f64,
+ bottom: c.bottom as f64,
+ left: c.left as f64,
+ }),
+ skip_diagonal_text: Some(cfg.skip_diagonal_text),
}
}
}
diff --git a/crates/liteparse-python/Cargo.toml b/crates/liteparse-python/Cargo.toml
index 92ff4eb..3849a1c 100644
--- a/crates/liteparse-python/Cargo.toml
+++ b/crates/liteparse-python/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "liteparse-python"
-version = "2.4.1"
+version = "2.5.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
@@ -15,7 +15,7 @@ default = ["tesseract"]
tesseract = ["liteparse/tesseract"]
[dependencies]
-liteparse = { package = "liteparse", version = "2.4.1", path = "../liteparse", default-features = false }
+liteparse = { package = "liteparse", version = "2.5.0", path = "../liteparse", default-features = false }
pdfium-sys = { package = "liteparse-pdfium-sys", version = "1.3.0", path = "../pdfium-sys" }
pdfium = { package = "liteparse-pdfium", version = "1.3.0", path = "../pdfium" }
clap = { version = "4.5.55", features = ["derive"] }
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index b6f7842..85fadf2 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
-use liteparse::config::{ImageMode, LiteParseConfig, OutputFormat};
+use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};
use liteparse::types::PdfInput;
mod cli;
@@ -456,6 +456,8 @@ impl LiteParse {
ocr_failure_fatal = None,
ocr_hedge_delays_ms = None,
emit_word_boxes = None,
+ crop_box = None,
+ skip_diagonal_text = None,
))]
fn new(
ocr_language: Option<String>,
@@ -476,6 +478,8 @@ impl LiteParse {
ocr_failure_fatal: Option<bool>,
ocr_hedge_delays_ms: Option<Vec<u64>>,
emit_word_boxes: Option<bool>,
+ crop_box: Option<(f32, f32, f32, f32)>,
+ skip_diagonal_text: Option<bool>,
) -> PyResult<Self> {
let mut cfg = LiteParseConfig::default();
if let Some(v) = ocr_language {
@@ -540,6 +544,17 @@ impl LiteParse {
if let Some(v) = emit_word_boxes {
cfg.emit_word_boxes = v;
}
+ if let Some((top, right, bottom, left)) = crop_box {
+ cfg.crop_box = Some(CropBox {
+ top,
+ right,
+ bottom,
+ left,
+ });
+ }
+ if let Some(v) = skip_diagonal_text {
+ cfg.skip_diagonal_text = v;
+ }
let inner = liteparse::parser::LiteParse::new(cfg.clone());
let runtime = tokio::runtime::Runtime::new()
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index 94fbde5..73bcd57 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -16,7 +16,9 @@ use tsify_next::Tsify;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
-use liteparse::config::{ImageMode, LiteParseConfig as CoreConfig, OutputFormat};
+use liteparse::config::{
+ CropBox as CoreCropBox, ImageMode, LiteParseConfig as CoreConfig, OutputFormat,
+};
use liteparse::ocr::{OcrEngine, OcrOptions, OcrResult as CoreOcrResult};
use liteparse::parser::LiteParse as CoreLiteParse;
use liteparse::search;
@@ -59,6 +61,25 @@ pub struct LiteParseConfig {
password: Option<String>,
quiet: Option<bool>,
emit_word_boxes: Option<bool>,
+ /// Restrict output to a page sub-region. Each field is the fraction of the
+ /// page cropped from that side; a text item survives only if it lies
+ /// entirely inside the remaining rectangle. Unset keeps the whole page.
+ crop_box: Option<CropBox>,
+ /// Drop diagonal text (rotation >2° off the nearest right angle). Default
+ /// false. Use to exclude rotated watermarks/stamps from the output.
+ skip_diagonal_text: Option<bool>,
+}
+
+/// A page sub-region as the fraction cropped from each side (top-left origin,
+/// each in `[0, 1]`).
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Tsify)]
+#[tsify(into_wasm_abi, from_wasm_abi)]
+#[serde(rename_all = "camelCase", default)]
+pub struct CropBox {
+ top: f32,
+ right: f32,
+ bottom: f32,
+ left: f32,
}
impl LiteParseConfig {
@@ -129,6 +150,17 @@ impl LiteParseConfig {
if let Some(v) = self.emit_word_boxes {
cfg.emit_word_boxes = v;
}
+ if let Some(v) = self.crop_box {
+ cfg.crop_box = Some(CoreCropBox {
+ top: v.top,
+ right: v.right,
+ bottom: v.bottom,
+ left: v.left,
+ });
+ }
+ if let Some(v) = self.skip_diagonal_text {
+ cfg.skip_diagonal_text = v;
+ }
cfg.num_workers = 1;
Ok(cfg)
}
@@ -164,6 +196,13 @@ impl LiteParseConfig {
password: cfg.password.clone(),
quiet: Some(cfg.quiet),
emit_word_boxes: Some(cfg.emit_word_boxes),
+ crop_box: cfg.crop_box.map(|c| CropBox {
+ top: c.top,
+ right: c.right,
+ bottom: c.bottom,
+ left: c.left,
+ }),
+ skip_diagonal_text: Some(cfg.skip_diagonal_text),
}
}
}
diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.toml
index 4717ee7..283cd71 100644
--- a/crates/liteparse/Cargo.toml
+++ b/crates/liteparse/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "liteparse"
-version = "2.4.1"
+version = "2.5.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index 517286a..94f024f 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -60,6 +60,30 @@ pub struct LiteParseConfig {
/// `false`, `TextItem.words` is always empty and the per-word tracking is
/// skipped entirely (zero allocation).
pub emit_word_boxes: bool,
+ /// Restrict output to a sub-region of every page. Each field is the
+ /// fraction of the page to crop away from that side (e.g. `left = 0.5`
+ /// discards the left half). A text item is kept only when it lies
+ /// *entirely* inside the surviving rectangle
+ /// `[left·W, (1-right)·W] × [top·H, (1-bottom)·H]` (top-left origin).
+ /// `None` (default) keeps the whole page. Applied after OCR merge, so it
+ /// also drops OCR-sourced text outside the region.
+ pub crop_box: Option<CropBox>,
+ /// Drop diagonal (skewed) text — items whose rotation is more than 2°
+ /// off the nearest right angle (0/90/180/270). Default `false`. Matches
+ /// the host worker's `skip_diagonal_text` behaviour so watermarks and
+ /// rotated stamps can be excluded from the fast-tier output.
+ pub skip_diagonal_text: bool,
+}
+
+/// A page sub-region expressed as the fraction cropped from each side.
+/// All fields are in `[0, 1]`; `left + right < 1` and `top + bottom < 1`
+/// for a non-empty region. Origin is top-left, matching `TextItem` coordinates.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
+pub struct CropBox {
+ pub top: f32,
+ pub right: f32,
+ pub bottom: f32,
+ pub left: f32,
}
/// Image handling for the markdown emitter.
@@ -121,6 +145,8 @@ impl Default for LiteParseConfig {
ocr_failure_fatal: true,
ocr_hedge_delays_ms: Vec::new(),
emit_word_boxes: false,
+ crop_box: None,
+ skip_diagonal_text: false,
}
}
}
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 13a8dc3..8a60875 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -611,6 +611,10 @@ fn extract_page_text_items(
(it.next().unwrap(), it.as_str())
} else {
match unicode {
+ 0x01 => (' ', ""), // SOH → space: buggy subset fonts (e.g. some
+ // Calibri/Cambria embeds) encode the space glyph as 0x01. Left as
+ // a raw control char it fuses adjacent words ("StatisticsCheatSheet");
+ // as a space it drives the normal pending-space word break below.
0x02 => ('-', ""), // STX → hyphen (common in some PDF encodings)
0x1A => ('f', "f"), // ff ligature
0x1B => ('f', "t"), // ft ligature
@@ -912,6 +916,18 @@ fn dedup_overlapping_items(items: &mut Vec<TextItem>, debug: bool) {
let a = &items[i];
let b = &items[j];
+ // Diagonal (non-right-angle) text has a *loose* axis-aligned
+ // bounding box — the hull of a rotated glyph run is far larger than
+ // the ink, so two stacked lines of the same skewed block (e.g.
+ // "Paris has the" above "eiffel tower" at 51°) report heavy bbox
+ // overlap even though the glyphs never touch. Dedup keys off AABB
+ // overlap, so it would wrongly drop one of those lines. Skip the
+ // comparison entirely when either item is diagonal; true duplicate
+ // stamps are upright and still handled below.
+ if is_diagonal_rotation(a.rotation) || is_diagonal_rotation(b.rotation) {
+ continue;
+ }
+
// Compute intersection area
let ix_left = a.x.max(b.x);
let ix_right = (a.x + a.width).min(b.x + b.width);
@@ -1011,6 +1027,56 @@ fn dedup_overlapping_items(items: &mut Vec<TextItem>, debug: bool) {
});
}
+/// True when `rotation` (degrees) is more than 2° off the nearest right angle
+/// (0/90/180/270). Mirrors the host worker's diagonal-text rule
+/// `|r - round(r / 90) * 90| > 2`, so a page's diagonal watermark/stamp text
+/// is classified identically on both sides.
+fn is_diagonal_rotation(rotation: f32) -> bool {
+ let nearest_right_angle = (rotation / 90.0).round() * 90.0;
+ (rotation - nearest_right_angle).abs() > 2.0
+}
+
+/// Apply caller-requested content filters to already-extracted (and
+/// OCR-merged) pages, in place, just before grid projection:
+///
+/// * `skip_diagonal` drops skewed text (watermarks, rotated stamps).
+/// * `crop_box` keeps only items lying *entirely* inside the surviving page
+/// region — fractions cropped from each side, top-left origin, matching the
+/// host worker's bounding-box crop.
+///
+/// Running here (after OCR merge, before projection) means both native and
+/// OCR-sourced items are filtered and removed text never reaches the output.
+/// No-op when neither filter is requested.
+pub(crate) fn apply_content_filters(
+ pages: &mut [LitePage],
+ crop_box: Option<&crate::config::CropBox>,
+ skip_diagonal: bool,
+) {
+ if crop_box.is_none() && !skip_diagonal {
+ return;
+ }
+ for page in pages.iter_mut() {
+ if skip_diagonal {
+ page.text_items
+ .retain(|it| !is_diagonal_rotation(it.rotation));
+ }
+ if let Some(cb) = crop_box {
+ let w = page.page_width;
+ let h = page.page_height;
+ let min_x = cb.left * w;
+ let max_x = (1.0 - cb.right) * w;
+ let min_y = cb.top * h;
+ let max_y = (1.0 - cb.bottom) * h;
+ page.text_items.retain(|it| {
+ it.x >= min_x
+ && it.x + it.width <= max_x
+ && it.y >= min_y
+ && it.y + it.height <= max_y
+ });
+ }
+ }
+}
+
/// Adjust character angle for page rotation.
/// PDFium returns counter-clockwise angle in PDF space; page /Rotate is clockwise.
fn adjust_angle_for_rotation(angle_rad: f32, page_rotation: i32) -> f32 {
@@ -1858,6 +1924,25 @@ mod tests {
assert_eq!(items.len(), 2);
}
+ #[test]
+ fn dedup_keeps_overlapping_diagonal_lines() {
+ // Two stacked lines of one rotated block: their loose axis-aligned
+ // bounding boxes overlap heavily, but both must survive (the
+ // "Paris has the" / "eiffel tower" @51° regression).
+ let mut items = vec![
+ TextItem {
+ rotation: 51.0,
+ ..ti("Paris has the", 0.0, 0.0, 100.0, 40.0)
+ },
+ TextItem {
+ rotation: 51.0,
+ ..ti("eiffel tower", 5.0, 5.0, 100.0, 40.0)
+ },
+ ];
+ dedup_overlapping_items(&mut items, false);
+ assert_eq!(items.len(), 2);
+ }
+
#[test]
fn dedup_noop_for_empty_or_single() {
let mut empty: Vec<TextItem> = vec![];
@@ -1868,6 +1953,81 @@ mod tests {
assert_eq!(one.len(), 1);
}
+ fn rot(text: &str, rotation: f32) -> TextItem {
+ TextItem {
+ rotation,
+ ..ti(text, 10.0, 10.0, 20.0, 5.0)
+ }
+ }
+
+ fn page_with(items: Vec<TextItem>) -> LitePage {
+ LitePage {
+ page_number: 1,
+ page_width: 100.0,
+ page_height: 100.0,
+ text_items: items,
+ graphics: Vec::new(),
+ struct_nodes: Vec::new(),
+ image_refs: Vec::new(),
+ }
+ }
+
+ fn texts(page: &LitePage) -> Vec<&str> {
+ page.text_items.iter().map(|it| it.text.as_str()).collect()
+ }
+
+ #[test]
+ fn is_diagonal_rotation_matches_worker_rule() {
+ // Within 2° of a right angle → not diagonal.
+ assert!(!is_diagonal_rotation(0.0));
+ assert!(!is_diagonal_rotation(1.9));
+ assert!(!is_diagonal_rotation(90.0));
+ assert!(!is_diagonal_rotation(271.5));
+ assert!(!is_diagonal_rotation(358.5));
+ // More than 2° off → diagonal (2.57° San-francisco case, 51°, 324°).
+ assert!(is_diagonal_rotation(2.57));
+ assert!(is_diagonal_rotation(51.0));
+ assert!(is_diagonal_rotation(324.0));
+ }
+
+ #[test]
+ fn skip_diagonal_keeps_only_upright_text() {
+ let mut pages = vec![page_with(vec![
+ rot("upright", 0.0),
+ rot("slightly-skewed", 2.57),
+ rot("diagonal", 51.0),
+ rot("landscape", 90.0),
+ ])];
+ apply_content_filters(&mut pages, None, true);
+ assert_eq!(texts(&pages[0]), vec!["upright", "landscape"]);
+ }
+
+ #[test]
+ fn crop_box_keeps_only_items_fully_inside_region() {
+ // 100×100 page; crop away the left half (left = 0.5) → survivors must
+ // sit entirely within x ∈ [50, 100].
+ let cb = crate::config::CropBox {
+ top: 0.0,
+ right: 0.0,
+ bottom: 0.0,
+ left: 0.5,
+ };
+ let mut pages = vec![page_with(vec![
+ ti("left", 10.0, 10.0, 20.0, 5.0), // fully left → dropped
+ ti("straddle", 45.0, 10.0, 20.0, 5.0), // crosses x=50 → dropped
+ ti("right", 60.0, 10.0, 20.0, 5.0), // fully right → kept
+ ])];
+ apply_content_filters(&mut pages, Some(&cb), false);
+ assert_eq!(texts(&pages[0]), vec!["right"]);
+ }
+
+ #[test]
+ fn content_filters_noop_without_options() {
+ let mut pages = vec![page_with(vec![rot("diagonal", 45.0)])];
+ apply_content_filters(&mut pages, None, false);
+ assert_eq!(pages[0].text_items.len(), 1);
+ }
+
#[test]
fn adjust_angle_no_rotation() {
assert!((adjust_angle_for_rotation(0.5, 0) - 0.5).abs() < 1e-6);
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 0d41929..1877214 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -349,6 +349,15 @@ impl LiteParse {
t_ocr.duration_since(t1).as_secs_f64() * 1000.0
));
+ // Caller-requested content filters (page-region crop, diagonal-text
+ // removal). Runs after OCR merge so it also drops OCR text outside the
+ // crop region, and before projection so filtered items never surface.
+ extract::apply_content_filters(
+ &mut pages,
+ self.config.crop_box.as_ref(),
+ self.config.skip_diagonal_text,
+ );
+
// Grid projection
let mut parsed_pages = projection::project_pages_to_grid(pages);
let t2 = web_time::Instant::now();
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index c0803e8..7ba78b7 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -62,6 +62,27 @@ export interface JsLiteParseConfig {
* for word-level bbox attribution.
*/
emitWordBoxes?: boolean
+ /**
+ * Restrict output to a page sub-region. Each field is the fraction of the
+ * page cropped from that side; a text item survives only if it lies
+ * entirely inside the remaining rectangle. Unset keeps the whole page.
+ */
+ cropBox?: JsCropBox
+ /**
+ * Drop diagonal text (rotation >2° off the nearest right angle). Default
+ * false. Use to exclude rotated watermarks/stamps from the output.
+ */
+ skipDiagonalText?: boolean
+}
+/**
+ * A page sub-region as the fraction cropped from each side (top-left origin,
+ * each in `[0, 1]`).
+ */
+export interface JsCropBox {
+ top: number
+ right: number
+ bottom: number
+ left: number
}
/** One word's sub-box within a `JsTextItem`, in the same viewport space. */
export interface JsWordBox {
diff --git a/packages/node/package.json b/packages/node/package.json
index 54d4f85..748c975 100644
--- a/packages/node/package.json
+++ b/packages/node/package.json
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/liteparse",
- "version": "2.4.1",
+ "version": "2.5.0",
"description": "Fast, lightweight PDF and document parsing with spatial text extraction",
"type": "module",
"main": "./dist/lib.js",
@@ -54,13 +54,13 @@
"typescript": "~5.9.2"
},
"optionalDependencies": {
- "@llamaindex/liteparse-darwin-arm64": "2.4.1",
- "@llamaindex/liteparse-darwin-x64": "2.4.1",
- "@llamaindex/liteparse-linux-arm64-gnu": "2.4.1",
- "@llamaindex/liteparse-linux-x64-gnu": "2.4.1",
- "@llamaindex/liteparse-win32-arm64-msvc": "2.4.1",
- "@llamaindex/liteparse-win32-x64-msvc": "2.4.1",
- "@llamaindex/liteparse-linux-x64-musl": "2.4.1"
+ "@llamaindex/liteparse-darwin-arm64": "2.5.0",
+ "@llamaindex/liteparse-darwin-x64": "2.5.0",
+ "@llamaindex/liteparse-linux-arm64-gnu": "2.5.0",
+ "@llamaindex/liteparse-linux-x64-gnu": "2.5.0",
+ "@llamaindex/liteparse-win32-arm64-msvc": "2.5.0",
+ "@llamaindex/liteparse-win32-x64-msvc": "2.5.0",
+ "@llamaindex/liteparse-linux-x64-musl": "2.5.0"
},
"engines": {
"node": ">=18.0.0"
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index e16a6d7..25d85c2 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -57,6 +57,31 @@ export interface LiteParseConfig {
* marshalling), so enable only when doing word-level bbox attribution.
*/
emitWordBoxes: boolean;
+ /**
+ * Restrict output to a page sub-region. Each field is the fraction of the
+ * page cropped away from that side (top-left origin), so `{ left: 0.5 }`
+ * discards the left half. A text item survives only when it lies entirely
+ * inside the remaining rectangle. Undefined (default) keeps the whole page.
+ * Applied after OCR merge, so OCR text outside the region is dropped too.
+ */
+ cropBox?: CropBox;
+ /**
+ * Drop diagonal text — items whose rotation is more than 2° off the nearest
+ * right angle (0/90/180/270). Default false. Use to exclude rotated
+ * watermarks/stamps from the output.
+ */
+ skipDiagonalText: boolean;
+}
+
+/**
+ * A page sub-region expressed as the fraction cropped from each side
+ * (top-left origin, each value in `[0, 1]`).
+ */
+export interface CropBox {
+ top: number;
+ right: number;
+ bottom: number;
+ left: number;
}
/**
@@ -226,6 +251,8 @@ export class LiteParse {
ocrFailureFatal: userConfig.ocrFailureFatal,
ocrHedgeDelaysMs: userConfig.ocrHedgeDelaysMs,
emitWordBoxes: userConfig.emitWordBoxes,
+ cropBox: userConfig.cropBox,
+ skipDiagonalText: userConfig.skipDiagonalText,
};
this._native = new native.LiteParse(nativeConfig);
@@ -251,6 +278,8 @@ export class LiteParse {
ocrFailureFatal: resolved.ocrFailureFatal ?? true,
ocrHedgeDelaysMs: resolved.ocrHedgeDelaysMs ?? [],
emitWordBoxes: resolved.emitWordBoxes ?? false,
+ cropBox: resolved.cropBox ?? undefined,
+ skipDiagonalText: resolved.skipDiagonalText ?? false,
};
}
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index b565c30..03942dc 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -38,6 +38,15 @@ export interface LiteParseNativeConfig {
ocrFailureFatal?: boolean;
ocrHedgeDelaysMs?: number[];
emitWordBoxes?: boolean;
+ cropBox?: NativeCropBox;
+ skipDiagonalText?: boolean;
+}
+
+export interface NativeCropBox {
+ top: number;
+ right: number;
+ bottom: number;
+ left: number;
}
export interface NativeWordBox {
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index fa74753..3d07fdc 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -1,7 +1,7 @@
"""LiteParse Python wrapper - native Rust bindings via PyO3."""
from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
+from typing import Any, Dict, List, Optional, Tuple, Union
from liteparse._liteparse import LiteParse as _NativeLiteParse
from liteparse._liteparse import search_items as _native_search_items
@@ -107,6 +107,8 @@ class LiteParse:
ocr_failure_fatal: Optional[bool] = None,
ocr_hedge_delays_ms: Optional[List[int]] = None,
emit_word_boxes: Optional[bool] = None,
+ crop_box: Optional[Tuple[float, float, float, float]] = None,
+ skip_diagonal_text: Optional[bool] = None,
):
"""
Initialize LiteParse parser.
@@ -143,6 +145,15 @@ class LiteParse:
(``TextItem.words``). Default False. Word boxes roughly double
the text-item payload, so enable only for word-level bbox
attribution.
+ crop_box: Restrict output to a page sub-region, as a
+ ``(top, right, bottom, left)`` tuple where each value is the
+ fraction cropped from that side (top-left origin, each in
+ ``[0, 1]``); e.g. ``(0, 0, 0, 0.5)`` keeps the right half. A
+ text item survives only if it lies entirely inside the
+ remaining rectangle. None (default) keeps the whole page.
+ skip_diagonal_text: Drop diagonal text — items whose rotation is
+ more than 2° off the nearest right angle (0/90/180/270).
+ Default False. Use to exclude rotated watermarks/stamps.
"""
kwargs = {}
if ocr_enabled is not None:
@@ -181,6 +192,10 @@ class LiteParse:
kwargs["ocr_hedge_delays_ms"] = ocr_hedge_delays_ms
if emit_word_boxes is not None:
kwargs["emit_word_boxes"] = emit_word_boxes
+ if crop_box is not None:
+ kwargs["crop_box"] = crop_box
+ if skip_diagonal_text is not None:
+ kwargs["skip_diagonal_text"] = skip_diagonal_text
self._native = _NativeLiteParse(**kwargs)