Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewich7c64221aa43e
diff --git a/MARKDOWN_PROGRESS.md b/MARKDOWN_PROGRESS.md
index 5e98f9a..2964aae 100644
--- a/MARKDOWN_PROGRESS.md
+++ b/MARKDOWN_PROGRESS.md
@@ -2,6 +2,16 @@
Tracks build-order progress against [MARKDOWN_PLAN.md](MARKDOWN_PLAN.md). Update as steps complete.
+> **2026-06-15 launch benchmark sweep + reproduce script + strikethrough feature (clean) + semantic_formatting gap analysis. 213 lib tests pass (5 new). No regression on any tracked metric.** Three pieces this session: (1) a fresh full model-free sweep across all three benches with the core-4 competitors → `LAUNCH_BENCHMARKS.md`; (2) `run_benchmarks.sh` to reproduce it (with `--liteparse-only` to skip competitors), documented in `BENCHMARKS.md`; (3) strikethrough support, shipped in its clean form after establishing it's a dead benchmark lever.
+>
+> **Launch sweep (fresh, model-free, 2026-06-15; full numbers in `LAUNCH_BENCHMARKS.md`).** liteparse leads the headline metric of all three benches among free tools: olmOCR Overall 39.1% (next-best pymupdf4llm 32.9%), opendataloader #1 open/free on all four (overall 0.875; only the *commercial* nutrient edges it at 0.885), ParseBench #1 Overall + Tables + Content-Faithfulness. Speed 144 ms/doc, 17–27× faster than pymupdf4llm/markitdown/opendataloader. Where we DON'T lead: nutrient (commercial) on opendataloader; olmOCR multi_column (−0.9 tie) and long_tiny_text; ParseBench `semantic_formatting` (pymupdf4llm 0.446 vs 0.409). Re-run gotchas captured in `BENCHMARKS.md` + [[project_competitor_baselines]]: opendataloader needs openjdk@11 (system Java 8 fails) and errors on raw `.png`; ParseBench writes per-group reports to `output/<pipe>/<group>/_evaluation_report.json` (metrics under `aggregate_metrics`); top-level `_evaluation_report.json` is a stale aggregate; `layout`/Visual-Grounding scored over only 64/500 docs (unusable).
+>
+> **Strikethrough (`~~…~~`) — SHIPPED clean; real output-quality win, ZERO benchmark movement (by design).** New: geometric detection in `extract.rs::assign_strikethrough` (a thin horizontal stroke/thin-rect crossing a text item's vertical *middle* band, 0.20–0.65 of height, ≥60% width coverage — cleanly separated from underlines ≈0.93 and overlines <0; calibrated on `text_simple__{strikeout,edits,redlined,strikeUnderline}.pdf`). Plumbed via new `TextItem.strike` → `is_strike_item` → `SpanStyle.strike` → `apply_style` (`~~` wraps outermost, composes with bold/italic/mono). Required a paragraph-path fix: `classify.rs`/`paragraphs.rs` route struck paragraphs through the per-line `inline` renderer instead of the uniform raw-text fast path (which silently dropped the markers — the `uniform` tuple only carries bold/italic). Kill: none (always on, gated on detection).
+>
+> **Why strikethrough is a dead benchmark lever (don't re-chase).** ParseBench `is_strikeout` stayed exactly **0.0** despite correct `~~` output. Root cause: the rule matches `~~query~~` with markers *tight* against the queried text; each struck line in these PDFs is extracted as a **single text item**, so we emit one GFM-correct `~~whole run~~` and the query sits mid-run → no match. The ONLY way to score is splitting runs into per-word `~~word~~ ~~word~~` (the rule's markup-tolerance bridges the gaps; this is what pymupdf4llm effectively does because PyMuPDF emits short spans) — but that's noisy output and metric-gaming, so per the project's anti-gaming stance ([[project_formatting_triage]]) we kept the clean merged version. Regression-checked: opendataloader 0.8750/0.9131/0.6929/0.8165 (−0.0001 noise); ParseBench text_content + table **byte-flat**; `semantic_formatting` unchanged at 0.4092 (so `LAUNCH_BENCHMARKS.md` needed no edit). Files: `types.rs`, `extract.rs`, `projection.rs`, `markdown_layout/{inline,classify,paragraphs}.rs`.
+>
+> **`semantic_formatting` gap decomposition (the one ParseBench category we trail).** Formula = weighted mean of text_styling(×1.0) + title_accuracy(×1.0) + latex(×0.2) + code_block(×0.2). Per-tool: title_accuracy 0.398 vs 0.442 (**biggest drag**, full weight, = heading detection: is_title + title_hierarchy); text_styling 0.436 vs 0.456 (driven almost entirely by **is_italic** 0.367 vs 0.492 — **is_bold is TIED** 0.519 vs 0.532); latex + code_block we WIN (0.255 vs 0.214, 0.200 vs 0.000). text_styling is a *per-doc* F₀.₅ blend of the style rules present on that doc. Counterfactual: forcing `is_strikeout` to perfect 1.0 lifts semantic_formatting only **+0.0094** (only 13/476 docs carry a strikeout rule) — so strikeout is ≤15% of the gap at its ceiling, not the bottleneck. **The real levers are heading detection (= same capability as opendataloader MHS, which we already lead) and is_italic — and is_italic is ~⅔ `text_absent` (extraction/reading-order) + ~¾ `no_signal` (italic absent from font flags AND name → unrecoverable from metadata); the buildable slice is table-cell/heading emphasis, the same lever that regressed ODL TEDS for bold.** Net: pushing `semantic_formatting` is really a heading-detection + extraction-fidelity project (both shared with categories we already win), not formatting-markup work. Pure bold/italic detection is at its metadata ceiling.
+
> **2026-06-14 (pm) launch-readiness cosmetic-noise + prose-chrome cleanup — audit followups #2 and #3 from the 2026-06-14 audit entry. Three contained markdown-emission fixes SHIPPED; 208 lib tests pass (2 new). Net: opendataloader clean win, ParseBench table + olmOCR flat.** All three are emission-/classification-layer changes that the three benches structurally barely see (the defects live in prose ornaments + form-table cosmetics that the corpora lack), so they were measured primarily for *non-regression*, with the real payoff being human-perceived output quality. Audit scratch under `/tmp/lp_audit/` (base/ = pre-change binary `lit-base`, new/ = shipping binary).
>
> **Fix A — decorative divider / flourish lines (`markdown_layout/classify.rs`, audit #2).** A line whose trimmed text has **no alphanumeric content** and consists only of divider symbols (`* * * *`, `———`, `____`) was flowing into the paragraph accumulator and gluing the ornament onto the *start* of the next paragraph (8× in the Berkshire 2023 letter: `\* \* \* \* … Writers find it useful…`), and a lone decorative em-dash under the title was getting size-promoted to a stray `# -` heading. New `decorative_divider_kind(text)` run *before* heading/paragraph classification (after the code-block flush): ≥3 symbols → `Block::HorizontalRule` (a real thematic break); 1–2 symbols → dropped (too small to be a meaningful rule). Conservative symbol set (`* - _ – — • · ● ▪ ■ ◦ ★ ☆`) — excludes `.`/`=`/`~`/`+`/`#` to avoid dot-leaders, ellipses, setext rules. `is_alphanumeric()` gate means any letter/digit (incl. CJK) → not decorative, so single-char numeric/letter headings are untouched. Verified on Berkshire: `# -` gone, the 8 dividers now emit as standalone `---` with the previously-glued prose intact as its own paragraph.
diff --git a/crates/liteparse-napi/src/lib.rs b/crates/liteparse-napi/src/lib.rs
index a959491..22d8cfd 100644
--- a/crates/liteparse-napi/src/lib.rs
+++ b/crates/liteparse-napi/src/lib.rs
@@ -3,7 +3,7 @@ use napi_derive::napi;
mod types;
-use types::{JsLiteParseConfig, JsParseResult, JsScreenshotResult, JsTextItem};
+use types::{JsLiteParseConfig, JsPageInput, JsParseResult, JsScreenshotResult, JsTextItem};
/// Main LiteParse parser class.
#[napi]
@@ -45,6 +45,20 @@ impl LiteParse {
Ok(JsParseResult::from_rust(&result, &self.config))
}
+ /// Parse from pre-extracted pages, skipping PDFium text extraction.
+ ///
+ /// The caller supplies pages already populated with text items in viewport
+ /// space (top-left origin, 72 DPI). Runs only grid projection + the
+ /// configured output formatter, so it never loads PDFium. Use when an
+ /// external extractor owns text extraction (e.g. to keep its own
+ /// font-recovery pipeline).
+ #[napi]
+ pub fn parse_pages(&self, pages: Vec<JsPageInput>) -> Result<JsParseResult> {
+ let rust_pages: Vec<_> = pages.iter().map(JsPageInput::to_rust).collect();
+ let result = self.inner.parse_from_pages(rust_pages, Vec::new());
+ Ok(JsParseResult::from_rust(&result, &self.config))
+ }
+
/// Take screenshots of document pages. Returns PNG image buffers.
///
/// Non-PDF files are automatically converted to PDF before rendering when
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 0c483c4..6c94c84 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -2,7 +2,7 @@ use napi_derive::napi;
use liteparse::config::{ImageMode, LiteParseConfig, OutputFormat};
use liteparse::parser::ParseResult;
-use liteparse::types::{ParsedPage, TextItem};
+use liteparse::types::{GraphicPrimitive, Page, ParsedPage, Rect, TextItem};
// ---------------------------------------------------------------------------
// Config
@@ -143,6 +143,8 @@ pub struct JsTextItem {
pub font_name: Option<String>,
pub font_size: Option<f64>,
pub confidence: Option<f64>,
+ /// Rotation in degrees (viewport space). Defaults to 0 when omitted.
+ pub rotation: Option<f64>,
}
impl JsTextItem {
@@ -153,6 +155,7 @@ impl JsTextItem {
y: self.y as f32,
width: self.width as f32,
height: self.height as f32,
+ rotation: self.rotation.unwrap_or(0.0) as f32,
font_name: self.font_name.clone(),
font_size: self.font_size.map(|v| v as f32),
confidence: self.confidence.map(|v| v as f32),
@@ -167,6 +170,7 @@ impl JsTextItem {
y: item.y as f64,
width: item.width as f64,
height: item.height as f64,
+ rotation: Some(item.rotation as f64),
font_name: item.font_name.clone(),
font_size: item.font_size.map(|v| v as f64),
confidence: item.confidence.map(|v| v as f64).or(Some(1.0)),
@@ -174,6 +178,113 @@ impl JsTextItem {
}
}
+// ---------------------------------------------------------------------------
+// Graphic primitive (pre-extracted vector graphics)
+// ---------------------------------------------------------------------------
+
+/// A vector-graphic primitive supplied by an external extractor. `kind` selects
+/// the variant: `"stroke"` (uses `x1/y1/x2/y2`) or `"rect"` (uses
+/// `x/y/width/height`). Coordinates are viewport space (top-left origin, 72
+/// DPI), matching the text items. `has_fill`/`has_stroke` carry the paint
+/// intent even when no color is known, so ruled-table edge detection still
+/// treats a colorless stroked rect as stroked.
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsGraphic {
+ /// "stroke" or "rect". Anything else is dropped.
+ pub kind: String,
+ // Stroke endpoints (used when kind == "stroke").
+ pub x1: Option<f64>,
+ pub y1: Option<f64>,
+ pub x2: Option<f64>,
+ pub y2: Option<f64>,
+ // Rect bbox top-left + size (used when kind == "rect").
+ pub x: Option<f64>,
+ pub y: Option<f64>,
+ pub width: Option<f64>,
+ pub height: Option<f64>,
+ /// Whether the path is filled. Drives Rect `fill` presence.
+ pub has_fill: Option<bool>,
+ /// Whether the path is stroked. Drives Rect `stroke` presence.
+ pub has_stroke: Option<bool>,
+ /// Fill color as ARGB hex (e.g. "ff000000"). May be absent even when filled.
+ pub fill_color: Option<String>,
+ /// Stroke color as ARGB hex. May be absent even when stroked.
+ pub stroke_color: Option<String>,
+ /// Stroke line width in points.
+ pub line_width: Option<f64>,
+}
+
+impl JsGraphic {
+ pub fn to_rust(&self) -> Option<GraphicPrimitive> {
+ match self.kind.as_str() {
+ "stroke" => Some(GraphicPrimitive::Stroke {
+ x1: self.x1.unwrap_or(0.0) as f32,
+ y1: self.y1.unwrap_or(0.0) as f32,
+ x2: self.x2.unwrap_or(0.0) as f32,
+ y2: self.y2.unwrap_or(0.0) as f32,
+ color: self.stroke_color.clone(),
+ width: self.line_width.unwrap_or(0.0) as f32,
+ }),
+ "rect" => Some(GraphicPrimitive::Rect {
+ bbox: Rect {
+ x: self.x.unwrap_or(0.0) as f32,
+ y: self.y.unwrap_or(0.0) as f32,
+ width: self.width.unwrap_or(0.0) as f32,
+ height: self.height.unwrap_or(0.0) as f32,
+ },
+ fill: if self.has_fill.unwrap_or(false) {
+ Some(self.fill_color.clone().unwrap_or_default())
+ } else {
+ None
+ },
+ stroke: if self.has_stroke.unwrap_or(false) {
+ Some(self.stroke_color.clone().unwrap_or_default())
+ } else {
+ None
+ },
+ }),
+ _ => None,
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Page input (pre-extracted)
+// ---------------------------------------------------------------------------
+
+/// A page of pre-extracted text supplied by an external extractor. Coordinates
+/// are viewport space (top-left origin, 72 DPI). `graphics` enables ruled-table
+/// and horizontal-rule detection; struct nodes are still unsupported on this
+/// path, so tagged-heading detection remains unavailable until they are added.
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsPageInput {
+ pub page_number: u32,
+ pub page_width: f64,
+ pub page_height: f64,
+ pub text_items: Vec<JsTextItem>,
+ pub graphics: Option<Vec<JsGraphic>>,
+}
+
+impl JsPageInput {
+ pub fn to_rust(&self) -> Page {
+ Page {
+ page_number: self.page_number as usize,
+ page_width: self.page_width as f32,
+ page_height: self.page_height as f32,
+ text_items: self.text_items.iter().map(JsTextItem::to_rust).collect(),
+ graphics: self
+ .graphics
+ .as_ref()
+ .map(|gs| gs.iter().filter_map(JsGraphic::to_rust).collect())
+ .unwrap_or_default(),
+ struct_nodes: Vec::new(),
+ image_refs: Vec::new(),
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// ParsedPage
// ---------------------------------------------------------------------------
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index f3ff319..3948050 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -9,6 +9,10 @@ pub struct LiteParseConfig {
pub ocr_enabled: bool,
/// HTTP OCR server URL (uses Tesseract if not provided)
pub ocr_server_url: Option<String>,
+ /// Extra HTTP headers sent with every request to `ocr_server_url`, as
+ /// `(name, value)` pairs. Use for auth, e.g. `("Authorization", "Bearer …")`.
+ /// Ignored when `ocr_server_url` is None.
+ pub ocr_server_headers: Vec<(String, String)>,
/// 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.
@@ -70,6 +74,7 @@ impl Default for LiteParseConfig {
ocr_language: "eng".to_string(),
ocr_enabled: true,
ocr_server_url: None,
+ ocr_server_headers: Vec::new(),
tessdata_path: None,
max_pages: 1000,
target_pages: None,
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index 4ce228b..a4085a0 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -58,6 +58,11 @@ struct ParseCommand {
#[arg(long, default_value = None)]
ocr_server_url: Option<String>,
+ /// Extra header for OCR server requests, "Name: Value" (repeatable).
+ /// e.g. --ocr-server-header "Authorization: Bearer <token>"
+ #[arg(long = "ocr-server-header", value_parser = parse_header)]
+ ocr_server_headers: Vec<(String, String)>,
+
/// Path to tessdata directory (overrides TESSDATA_PREFIX env var)
#[arg(long)]
tessdata_path: Option<String>,
@@ -163,6 +168,11 @@ struct BatchParseCommand {
#[arg(long, default_value = None)]
ocr_server_url: Option<String>,
+ /// Extra header for OCR server requests, "Name: Value" (repeatable).
+ /// e.g. --ocr-server-header "Authorization: Bearer <token>"
+ #[arg(long = "ocr-server-header", value_parser = parse_header)]
+ ocr_server_headers: Vec<(String, String)>,
+
/// Path to tessdata directory (overrides TESSDATA_PREFIX env var)
#[arg(long)]
tessdata_path: Option<String>,
@@ -219,6 +229,18 @@ fn parse_output_format(s: &str) -> Result<OutputFormat, String> {
}
}
+/// Parse a `Name: Value` header string into a `(name, value)` pair.
+fn parse_header(s: &str) -> Result<(String, String), String> {
+ let (name, value) = s
+ .split_once(':')
+ .ok_or_else(|| format!("invalid header '{}', expected 'Name: Value'", s))?;
+ let name = name.trim();
+ if name.is_empty() {
+ return Err(format!("invalid header '{}', empty header name", s));
+ }
+ Ok((name.to_string(), value.trim().to_string()))
+}
+
fn parse_image_mode(s: &str) -> Result<liteparse::config::ImageMode, String> {
use liteparse::config::ImageMode;
match s.to_lowercase().as_str() {
@@ -253,6 +275,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
password: cmd.password,
quiet: cmd.quiet,
ocr_server_url: cmd.ocr_server_url,
+ ocr_server_headers: cmd.ocr_server_headers,
image_mode,
extract_links: !cmd.no_links,
..Default::default()
@@ -354,6 +377,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
password: cmd.password,
quiet: cmd.quiet,
ocr_server_url: cmd.ocr_server_url,
+ ocr_server_headers: cmd.ocr_server_headers,
..Default::default()
};
if let Some(n) = cmd.num_workers {
diff --git a/crates/liteparse/src/ocr/http_simple.rs b/crates/liteparse/src/ocr/http_simple.rs
index fc32b61..7094773 100644
--- a/crates/liteparse/src/ocr/http_simple.rs
+++ b/crates/liteparse/src/ocr/http_simple.rs
@@ -21,9 +21,75 @@ pub struct HttpOcrResponseItem {
polygon: Option<[[f32; 2]; 4]>,
}
-#[derive(Debug, Serialize, Deserialize)]
-pub struct HttpOcrResponse {
- pub results: Vec<HttpOcrResponseItem>,
+impl HttpOcrResponseItem {
+ fn into_ocr_result(self) -> OcrResult {
+ OcrResult {
+ text: self.text,
+ bbox: self.bbox,
+ confidence: self.confidence,
+ polygon: self.polygon,
+ }
+ }
+}
+
+/// A single detection from the LlamaParse prod OCR worker, which emits
+/// EasyOCR/PaddleOCR-style positional tuples: `[polygon, text, confidence]`,
+/// where `polygon` is a list of `[x, y]` points (4 for both engines) ordered
+/// top-left → top-right → bottom-right → bottom-left.
+#[derive(Debug, Deserialize)]
+struct ProdOcrItem(Vec<[f32; 2]>, String, f32);
+
+impl ProdOcrItem {
+ fn into_ocr_result(self) -> OcrResult {
+ let ProdOcrItem(poly, text, confidence) = self;
+ // Axis-aligned bbox from the polygon's min/max extents.
+ let mut min_x = f32::INFINITY;
+ let mut min_y = f32::INFINITY;
+ let mut max_x = f32::NEG_INFINITY;
+ let mut max_y = f32::NEG_INFINITY;
+ for [x, y] in &poly {
+ min_x = min_x.min(*x);
+ min_y = min_y.min(*y);
+ max_x = max_x.max(*x);
+ max_y = max_y.max(*y);
+ }
+ // Forward the raw polygon only when it's exactly 4 points, so the
+ // projector can recover rotation for sideways text.
+ let polygon = match poly.as_slice() {
+ [a, b, c, d] => Some([*a, *b, *c, *d]),
+ _ => None,
+ };
+ OcrResult {
+ text,
+ bbox: [min_x, min_y, max_x, max_y],
+ confidence,
+ polygon,
+ }
+ }
+}
+
+/// Accepts either the LiteParse standard response or the LlamaParse prod OCR
+/// worker response. Untagged: serde tries `Standard` first (keyed on
+/// `results` with object items), then falls back to `Prod` (keyed on `result`
+/// with positional-tuple items).
+#[derive(Debug, Deserialize)]
+#[serde(untagged)]
+enum HttpOcrResponse {
+ Standard { results: Vec<HttpOcrResponseItem> },
+ Prod { result: Vec<ProdOcrItem> },
+}
+
+impl HttpOcrResponse {
+ fn into_results(self) -> Vec<OcrResult> {
+ match self {
+ HttpOcrResponse::Standard { results } => {
+ results.into_iter().map(|i| i.into_ocr_result()).collect()
+ }
+ HttpOcrResponse::Prod { result } => {
+ result.into_iter().map(|i| i.into_ocr_result()).collect()
+ }
+ }
+ }
}
/// HTTP-based OCR engine that conforms to LiteParse OCR API specification.
@@ -35,13 +101,20 @@ pub struct HttpOcrResponse {
pub struct HttpOcrEngine {
pub name: String,
server_url: String,
+ /// Extra headers (name, value) sent with every request, e.g. auth tokens.
+ headers: Vec<(String, String)>,
}
impl HttpOcrEngine {
pub fn new(server_url: String) -> Self {
+ Self::with_headers(server_url, Vec::new())
+ }
+
+ pub fn with_headers(server_url: String, headers: Vec<(String, String)>) -> Self {
Self {
name: "http-ocr".to_string(),
server_url,
+ headers,
}
}
}
@@ -81,27 +154,29 @@ impl OcrEngine for HttpOcrEngine {
.mime_str("image/png")?,
)
.text("language", options.language.clone());
- let response: HttpOcrResponse = client
+ let mut request = client
.post(&self.server_url)
.multipart(form)
- .timeout(Duration::from_millis(60000))
- .send()
- .await?
- .error_for_status()?
- .json()
- .await?;
-
- let results: Vec<OcrResult> = response
- .results
- .iter()
- .map(|i| OcrResult {
- text: i.text.clone(),
- bbox: i.bbox,
- confidence: i.confidence,
- polygon: i.polygon,
- })
- .collect();
-
+ .timeout(Duration::from_millis(60000));
+ for (name, value) in &self.headers {
+ request = request.header(name.as_str(), value.as_str());
+ }
+ let raw = request.send().await?.error_for_status()?.text().await?;
+ // Parse from the buffered body (rather than `.json()`) so a
+ // malformed/unexpected response can surface a snippet of what the
+ // server actually returned.
+ let response: HttpOcrResponse = serde_json::from_str(&raw).map_err(|e| {
+ let snippet: String = raw.chars().take(200).collect();
+ format!("OCR server returned unparseable response: {e}; body starts: {snippet}")
+ })?;
+ let results = response.into_results();
+ if std::env::var("LITEPARSE_DEBUG_OCR").is_ok() {
+ eprintln!(
+ "[ocr-http] {} bytes -> {} result(s)",
+ raw.len(),
+ results.len()
+ );
+ }
Ok(results)
})
}
@@ -122,17 +197,43 @@ mod tests {
fn test_response_deserializes() {
let raw = r#"{"results":[{"text":"hi","bbox":[1.0,2.0,3.0,4.0],"confidence":0.85}]}"#;
let parsed: HttpOcrResponse = serde_json::from_str(raw).unwrap();
- assert_eq!(parsed.results.len(), 1);
- assert_eq!(parsed.results[0].text, "hi");
- assert_eq!(parsed.results[0].bbox, [1.0, 2.0, 3.0, 4.0]);
- assert!((parsed.results[0].confidence - 0.85).abs() < 1e-6);
+ let results = parsed.into_results();
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].text, "hi");
+ assert_eq!(results[0].bbox, [1.0, 2.0, 3.0, 4.0]);
+ assert!((results[0].confidence - 0.85).abs() < 1e-6);
}
#[test]
fn test_response_deserializes_empty() {
let raw = r#"{"results":[]}"#;
let parsed: HttpOcrResponse = serde_json::from_str(raw).unwrap();
- assert!(parsed.results.is_empty());
+ assert!(parsed.into_results().is_empty());
+ }
+
+ #[test]
+ fn test_prod_response_deserializes() {
+ // LlamaParse prod worker shape: `result` tuples + `document_angle`.
+ let raw = r#"{"document_angle":-90,"result":[[[[10.0,20.0],[60.0,20.0],[60.0,40.0],[10.0,40.0]],"hi",0.85]]}"#;
+ let parsed: HttpOcrResponse = serde_json::from_str(raw).unwrap();
+ let results = parsed.into_results();
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].text, "hi");
+ // bbox is the polygon's min/max extents.
+ assert_eq!(results[0].bbox, [10.0, 20.0, 60.0, 40.0]);
+ assert!((results[0].confidence - 0.85).abs() < 1e-6);
+ // 4-point polygon forwarded as-is (TL → TR → BR → BL).
+ assert_eq!(
+ results[0].polygon,
+ Some([[10.0, 20.0], [60.0, 20.0], [60.0, 40.0], [10.0, 40.0]])
+ );
+ }
+
+ #[test]
+ fn test_prod_response_empty() {
+ let raw = r#"{"document_angle":null,"result":[]}"#;
+ let parsed: HttpOcrResponse = serde_json::from_str(raw).unwrap();
+ assert!(parsed.into_results().is_empty());
}
#[tokio::test]
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index f64c9fa..e345a30 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -13,7 +13,7 @@ use crate::output::markdown;
use crate::projection;
#[cfg(not(target_arch = "wasm32"))]
use crate::render;
-use crate::types::{ExtractedImage, OutlineTarget, ParsedPage, PdfInput};
+use crate::types::{ExtractedImage, OutlineTarget, Page, ParsedPage, PdfInput};
use pdfium::Library;
/// Result of parsing a document.
@@ -176,7 +176,10 @@ impl LiteParse {
#[cfg(not(target_arch = "wasm32"))]
{
if let Some(ref url) = self.config.ocr_server_url {
- std::sync::Arc::new(HttpOcrEngine::new(url.clone()))
+ std::sync::Arc::new(HttpOcrEngine::with_headers(
+ url.clone(),
+ self.config.ocr_server_headers.clone(),
+ ))
} else {
#[cfg(feature = "tesseract")]
{
@@ -248,6 +251,35 @@ impl LiteParse {
})
}
+ /// Parse from pre-extracted pages, skipping PDFium text extraction.
+ ///
+ /// The caller supplies `Page`s already populated with text items (and,
+ /// optionally, graphics / struct nodes / image refs) in viewport space
+ /// (top-left origin, 72 DPI). This runs only grid projection and the
+ /// configured output formatter, so it touches neither PDFium nor OCR and
+ /// is fully synchronous. Used when an external extractor (e.g. with its
+ /// own font-recovery pipeline) owns text extraction.
+ pub fn parse_from_pages(&self, pages: Vec<Page>, outline: Vec<OutlineTarget>) -> ParseResult {
+ let parsed_pages = projection::project_pages_to_grid(pages);
+
+ let full_text = if self.config.output_format == crate::config::OutputFormat::Markdown {
+ markdown::format_markdown(&parsed_pages, &outline, self.config.image_mode)
+ } else {
+ parsed_pages
+ .iter()
+ .map(|p| p.text.as_str())
+ .collect::<Vec<_>>()
+ .join("\n\n")
+ };
+
+ ParseResult {
+ pages: parsed_pages,
+ text: full_text,
+ outline,
+ images: Vec::new(),
+ }
+ }
+
/// Generate screenshots of document pages as PNG bytes.
///
/// Non-PDF files are automatically converted to PDF first (requires
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 5b6329a..b0e141f 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -3041,6 +3041,15 @@ const XY_COLUMN_PEAK_BALANCE_RATIO: f32 = 0.4;
/// detector) on sparse tabular layouts.
const XY_COLUMN_MIN_FILL: f32 = 0.55;
+/// A peak whose band count is below this fraction of the most-banded column's
+/// is treated as a figure-scatter "phantom" (axis tick labels, a point cloud
+/// spread across x) rather than a real column. Real table columns have one
+/// cell per row, so their band counts are comparable to their siblings; a
+/// plot embedded in 2-column prose contributes a sparse, low-fill third peak
+/// that would otherwise flip the whole region to `tabular` and suppress the
+/// genuine column split. See the phantom-drop in `xy_find_column_cut`.
+const XY_COLUMN_PHANTOM_BAND_FRACTION: f32 = 0.25;
+
#[derive(Debug, Clone, Copy)]
struct CutCandidate {
axis: CutAxis,
@@ -3655,7 +3664,7 @@ fn xy_find_column_cut(
// the rows whole. Per band, measure each column's covered span / slot
// width; if too sparse, treat as a table and bail.
{
- let n = peaks.len();
+ let mut n = peaks.len();
let mut covered_sum = vec![0.0f32; n];
let mut band_count = vec![0usize; n];
let mut kk = 0;
@@ -3728,7 +3737,7 @@ fn xy_find_column_cut(
weighted_n += band_count[c] as f32;
}
}
- let avg_fill = if weighted_n > 0.0 {
+ let mut avg_fill = if weighted_n > 0.0 {
weighted_sum / weighted_n
} else {
f32::INFINITY
@@ -3749,6 +3758,61 @@ fn xy_find_column_cut(
);
}
const MIN_FILL_HARD_FLOOR: f32 = 0.38;
+ // Figure-scatter phantom column: on a 2-column page with an embedded
+ // plot (scatter cloud, axis tick labels), the plot's x-spread items
+ // form a third peak that is BOTH sparsely-banded (far fewer text rows
+ // than the real columns) and low-fill. Left in, it drags min_fill
+ // under the floor and flips the whole region to `tabular`, suppressing
+ // the genuine column split. A real narrow table column instead has a
+ // band count comparable to its siblings (one cell per row), so the
+ // band-count ratio cleanly separates the two. Drop phantom peaks when
+ // ≥2 well-filled columns survive, then re-run the gate on them.
+ if n > 2 && std::env::var("LITEPARSE_DISABLE_PHANTOM_COL_DROP").is_err() {
+ let max_bands = band_count.iter().copied().max().unwrap_or(0);
+ if max_bands > 0 {
+ let band_floor =
+ (max_bands as f32 * XY_COLUMN_PHANTOM_BAND_FRACTION).ceil() as usize;
+ let col_fill = |c: usize| -> f32 {
+ if band_count[c] > 0 {
+ covered_sum[c] / band_count[c] as f32
+ } else {
+ 0.0
+ }
+ };
+ let survivors: Vec<usize> = (0..n)
+ .filter(|&c| !(band_count[c] < band_floor && col_fill(c) < MIN_FILL_HARD_FLOOR))
+ .collect();
+ let survivors_filled = survivors
+ .iter()
+ .all(|&c| col_fill(c) >= MIN_FILL_HARD_FLOOR);
+ if survivors.len() >= 2 && survivors.len() < n && survivors_filled {
+ let kept: Vec<(f32, usize)> = survivors.iter().map(|&c| peaks[c]).collect();
+ let mut new_min = f32::INFINITY;
+ let mut wsum = 0.0f32;
+ let mut wn = 0.0f32;
+ for &c in &survivors {
+ let f = col_fill(c);
+ new_min = new_min.min(f);
+ wsum += f * band_count[c] as f32;
+ wn += band_count[c] as f32;
+ }
+ if dbg {
+ eprintln!(
+ "[xy col-phantom] dropped {} sparse low-fill peak(s) (band_floor={band_floor}); kept xs=[{}]",
+ n - survivors.len(),
+ kept.iter()
+ .map(|(x, _)| format!("{x:.0}"))
+ .collect::<Vec<_>>()
+ .join(",")
+ );
+ }
+ peaks = kept;
+ n = peaks.len();
+ min_fill = new_min;
+ avg_fill = if wn > 0.0 { wsum / wn } else { f32::INFINITY };
+ }
+ }
+ }
// The min-floor catches ≥3-col tables whose narrow numeric column is
// diluted out of the weighted average by wide neighbors. With only 2
// columns no dilution is possible — a sparse column of two drags the
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index c8d2d86..3a93b62 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -28,6 +28,17 @@ export interface JsLiteParseConfig {
quiet?: boolean
/** Number of concurrent OCR workers (default: CPU cores - 1). */
numWorkers?: number
+ /**
+ * How to surface raster images in markdown output: "off", "placeholder"
+ * (default — emits `![](image_pN_K.png)` references with no bytes), or
+ * "embed" (also returns each image's PNG bytes on `images`).
+ */
+ imageMode?: string
+ /**
+ * Render hyperlink annotations as `[text](url)` in markdown output
+ * (default true). Set false for plain anchor text.
+ */
+ extractLinks?: boolean
}
export interface JsTextItem {
text: string
@@ -38,6 +49,51 @@ export interface JsTextItem {
fontName?: string
fontSize?: number
confidence?: number
+ /** Rotation in degrees (viewport space). Defaults to 0 when omitted. */
+ rotation?: number
+}
+/**
+ * A vector-graphic primitive supplied by an external extractor. `kind` selects
+ * the variant: `"stroke"` (uses `x1/y1/x2/y2`) or `"rect"` (uses
+ * `x/y/width/height`). Coordinates are viewport space (top-left origin, 72
+ * DPI), matching the text items. `has_fill`/`has_stroke` carry the paint
+ * intent even when no color is known, so ruled-table edge detection still
+ * treats a colorless stroked rect as stroked.
+ */
+export interface JsGraphic {
+ /** "stroke" or "rect". Anything else is dropped. */
+ kind: string
+ x1?: number
+ y1?: number
+ x2?: number
+ y2?: number
+ x?: number
+ y?: number
+ width?: number
+ height?: number
+ /** Whether the path is filled. Drives Rect `fill` presence. */
+ hasFill?: boolean
+ /** Whether the path is stroked. Drives Rect `stroke` presence. */
+ hasStroke?: boolean
+ /** Fill color as ARGB hex (e.g. "ff000000"). May be absent even when filled. */
+ fillColor?: string
+ /** Stroke color as ARGB hex. May be absent even when stroked. */
+ strokeColor?: string
+ /** Stroke line width in points. */
+ lineWidth?: number
+}
+/**
+ * A page of pre-extracted text supplied by an external extractor. Coordinates
+ * are viewport space (top-left origin, 72 DPI). `graphics` enables ruled-table
+ * and horizontal-rule detection; struct nodes are still unsupported on this
+ * path, so tagged-heading detection remains unavailable until they are added.
+ */
+export interface JsPageInput {
+ pageNumber: number
+ pageWidth: number
+ pageHeight: number
+ textItems: Array<JsTextItem>
+ graphics?: Array<JsGraphic>
}
export interface JsParsedPage {
pageNum: number
@@ -49,6 +105,13 @@ export interface JsParsedPage {
export interface JsParseResult {
pages: Array<JsParsedPage>
text: string
+ images: Array<JsExtractedImage>
+}
+export interface JsExtractedImage {
+ id: string
+ page: number
+ format: string
+ bytes: Buffer
}
export interface JsScreenshotResult {
pageNum: number
@@ -67,6 +130,16 @@ export declare class LiteParse {
constructor(config?: JsLiteParseConfig | undefined | null)
/** Parse a document. Accepts a file path (string) or raw PDF bytes (Buffer). */
parse(input: string | Buffer): Promise<JsParseResult>
+ /**
+ * Parse from pre-extracted pages, skipping PDFium text extraction.
+ *
+ * The caller supplies pages already populated with text items in viewport
+ * space (top-left origin, 72 DPI). Runs only grid projection + the
+ * configured output formatter, so it never loads PDFium. Use when an
+ * external extractor owns text extraction (e.g. to keep its own
+ * font-recovery pipeline).
+ */
+ parsePages(pages: Array<JsPageInput>): JsParseResult
/**
* Take screenshots of document pages. Returns PNG image buffers.
*
diff --git a/packages/node/package.json b/packages/node/package.json
index 2b61225..9ca39df 100644
--- a/packages/node/package.json
+++ b/packages/node/package.json
@@ -53,7 +53,8 @@
"@types/node": "^22.0.0",
"typescript": "~5.9.2"
},
- "optionalDependencies": {
+ "_comment_optionalDependencies": "Renamed from optionalDependencies for local file: consumption — the published 2.0.8 platform packages predate parsePages and would shadow the locally-built .node. Restore this key to optionalDependencies (and bump versions) before publishing.",
+ "optionalDependencies_publishOnly": {
"@llamaindex/liteparse-darwin-arm64": "2.0.8",
"@llamaindex/liteparse-darwin-x64": "2.0.8",
"@llamaindex/liteparse-linux-arm64-gnu": "2.0.8",
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index 4127472..d8a5c91 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -4,6 +4,7 @@ import {
type LiteParseNativeConfig,
type NativeParseResult,
type NativeParsedPage,
+ type NativePageInput,
type NativeTextItem,
type NativeExtractedImage,
} from "./native.js";
@@ -44,6 +45,46 @@ export interface TextItem {
fontName?: string;
fontSize?: number;
confidence?: number;
+ /** Rotation in degrees (viewport space). Defaults to 0 when omitted. */
+ rotation?: number;
+}
+
+/**
+ * A vector-graphic primitive supplied to {@link LiteParse.parsePages}. `kind`
+ * selects the variant: `"stroke"` (uses `x1/y1/x2/y2`) or `"rect"` (uses
+ * `x/y/width/height`, top-left origin). Coordinates are viewport space (72 DPI),
+ * matching the text items. `hasFill`/`hasStroke` carry the paint intent even
+ * when the color is unknown, so ruled-table edge detection still treats a
+ * colorless stroked rect as stroked.
+ */
+export interface Graphic {
+ kind: "stroke" | "rect";
+ x1?: number;
+ y1?: number;
+ x2?: number;
+ y2?: number;
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ hasFill?: boolean;
+ hasStroke?: boolean;
+ fillColor?: string;
+ strokeColor?: string;
+ lineWidth?: number;
+}
+
+/**
+ * A page of pre-extracted text supplied to {@link LiteParse.parsePages}.
+ * Coordinates are viewport space (top-left origin, 72 DPI). `graphics` is
+ * optional; when supplied it enables ruled-table and horizontal-rule detection.
+ */
+export interface PageInput {
+ pageNumber: number;
+ pageWidth: number;
+ pageHeight: number;
+ textItems: TextItem[];
+ graphics?: Graphic[];
}
export interface ParsedPage {
@@ -136,6 +177,28 @@ export class LiteParse {
};
}
+ /**
+ * Parse from pre-extracted pages, skipping PDFium text extraction. Runs only
+ * grid projection + the configured output formatter, so the caller's own
+ * text-extraction / font-recovery owns the text content. Synchronous: no
+ * PDFium load and no OCR on this path.
+ */
+ parsePages(pages: PageInput[]): ParseResult {
+ const nativePages: NativePageInput[] = pages.map((p) => ({
+ pageNumber: p.pageNumber,
+ pageWidth: p.pageWidth,
+ pageHeight: p.pageHeight,
+ textItems: p.textItems,
+ graphics: p.graphics,
+ }));
+ const result = this._native.parsePages(nativePages);
+ return {
+ pages: result.pages.map(toPage),
+ text: result.text,
+ images: (result.images ?? []).map(toImage),
+ };
+ }
+
async screenshot(
input: LiteParseInput,
pageNumbers?: number[],
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index 7133024..19dfb75 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -45,6 +45,32 @@ export interface NativeTextItem {
fontName?: string;
fontSize?: number;
confidence?: number;
+ rotation?: number;
+}
+
+export interface NativeGraphic {
+ kind: string;
+ x1?: number;
+ y1?: number;
+ x2?: number;
+ y2?: number;
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ hasFill?: boolean;
+ hasStroke?: boolean;
+ fillColor?: string;
+ strokeColor?: string;
+ lineWidth?: number;
+}
+
+export interface NativePageInput {
+ pageNumber: number;
+ pageWidth: number;
+ pageHeight: number;
+ textItems: NativeTextItem[];
+ graphics?: NativeGraphic[];
}
export interface NativeParsedPage {
@@ -77,6 +103,7 @@ export interface NativeScreenshotResult {
export interface LiteParseNative {
parse(input: string | Buffer): Promise<NativeParseResult>;
+ parsePages(pages: NativePageInput[]): NativeParseResult;
screenshot(
input: string | Buffer,
pageNumbers?: number[] | null,