Skip to content

A fast, helpful, and open-source document parser

fix: don't return word boxes extracted only for extract_blocks

Christopher Atlan924d2045148d
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index f0761df..06ef92d 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -452,6 +452,10 @@ impl JsTextItem {
}
pub fn from_rust(item: &TextItem) -> Self {
+ Self::from_rust_with_words(item, true)
+ }
+
+ fn from_rust_with_words(item: &TextItem, word_boxes: bool) -> Self {
Self {
text: item.text.clone(),
x: item.x as f64,
@@ -473,14 +477,23 @@ impl JsTextItem {
char_codes: Some(item.char_codes.clone()),
trailing_space_generated: Some(item.trailing_space_generated),
confidence: item.confidence.map(|v| v as f64),
- words: item.words.iter().map(JsWordBox::from_rust).collect(),
+ words: if word_boxes {
+ item.words.iter().map(JsWordBox::from_rust).collect()
+ } else {
+ Vec::new()
+ },
}
}
/// `from_rust` with the rich-metadata fields taken from the core-gated
/// [`liteparse::types::TextMetadata`] view, so the "what counts as text
- /// metadata" list lives in one place instead of per binding.
- fn from_rust_for_output(item: &TextItem, extract_text_metadata: bool) -> Self {
+ /// metadata" list lives in one place instead of per binding. `words` is
+ /// left empty unless `word_boxes` (see `LiteParseConfig::output_word_boxes`).
+ fn from_rust_for_output(
+ item: &TextItem,
+ extract_text_metadata: bool,
+ word_boxes: bool,
+ ) -> Self {
let meta = item.text_metadata(extract_text_metadata);
Self {
font_height: meta.font_height.map(|v| v as f64),
@@ -494,7 +507,7 @@ impl JsTextItem {
stroke_color: meta.stroke_color.map(str::to_owned),
char_codes: meta.char_codes.map(<[u32]>::to_vec),
trailing_space_generated: meta.trailing_space_generated,
- ..Self::from_rust(item)
+ ..Self::from_rust_with_words(item, word_boxes)
}
}
}
@@ -986,7 +999,7 @@ impl JsLayoutBlock {
}
impl JsParsedPage {
- pub fn from_rust(page: &ParsedPage, extract_text_metadata: bool) -> Self {
+ pub fn from_rust(page: &ParsedPage, extract_text_metadata: bool, word_boxes: bool) -> Self {
Self {
page_num: page.page_number as u32,
page_label: page.page_label.clone(),
@@ -1003,7 +1016,9 @@ impl JsParsedPage {
text_items: page
.text_items
.iter()
- .map(|item| JsTextItem::from_rust_for_output(item, extract_text_metadata))
+ .map(|item| {
+ JsTextItem::from_rust_for_output(item, extract_text_metadata, word_boxes)
+ })
.collect(),
complexity: page
.complexity
@@ -1326,7 +1341,13 @@ impl JsParseResult {
pages: result
.pages
.iter()
- .map(|page| JsParsedPage::from_rust(page, config.extract_text_metadata))
+ .map(|page| {
+ JsParsedPage::from_rust(
+ page,
+ config.extract_text_metadata,
+ config.output_word_boxes(),
+ )
+ })
.collect(),
page_errors: result
.page_errors
@@ -1381,6 +1402,35 @@ impl JsParseResult {
mod tests {
use super::*;
+ #[test]
+ fn words_are_returned_only_when_requested() {
+ let item = TextItem {
+ text: "a b".into(),
+ words: vec![
+ WordBox {
+ text: "a".into(),
+ ..Default::default()
+ },
+ WordBox {
+ text: "b".into(),
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ };
+ assert!(
+ JsTextItem::from_rust_for_output(&item, false, false)
+ .words
+ .is_empty()
+ );
+ assert_eq!(
+ JsTextItem::from_rust_for_output(&item, false, true)
+ .words
+ .len(),
+ 2
+ );
+ }
+
#[test]
fn text_metadata_round_trips_through_napi_type() {
let item = TextItem {
@@ -1404,7 +1454,7 @@ mod tests {
assert_eq!(js.trailing_space_generated, Some(true));
assert_eq!(js.fill_color.as_deref(), Some("ff112233"));
- let lightweight = JsTextItem::from_rust_for_output(&item, false);
+ let lightweight = JsTextItem::from_rust_for_output(&item, false, false);
assert_eq!(lightweight.font_height, None);
assert_eq!(lightweight.font_is_buggy, None);
assert_eq!(lightweight.char_codes, None);
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index 187917a..e6bfb61 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -490,8 +490,16 @@ impl PyTextItem {
/// `from_rust` with the rich-metadata fields taken from the core-gated
/// [`liteparse::types::TextMetadata`] view, so the "what counts as text
- /// metadata" list lives in one place instead of per binding.
- fn from_rust_for_output(item: liteparse::types::TextItem, extract_text_metadata: bool) -> Self {
+ /// metadata" list lives in one place instead of per binding. `words` is
+ /// left empty unless `word_boxes` (see `LiteParseConfig::output_word_boxes`).
+ fn from_rust_for_output(
+ mut item: liteparse::types::TextItem,
+ extract_text_metadata: bool,
+ word_boxes: bool,
+ ) -> Self {
+ if !word_boxes {
+ item.words.clear();
+ }
let meta = item.text_metadata(extract_text_metadata);
let (fill_color, stroke_color, char_codes) = (
meta.fill_color.map(str::to_owned),
@@ -666,7 +674,11 @@ impl PyParsedPage {
}
impl PyParsedPage {
- fn from_rust(page: liteparse::types::ParsedPage, extract_text_metadata: bool) -> Self {
+ fn from_rust(
+ page: liteparse::types::ParsedPage,
+ extract_text_metadata: bool,
+ word_boxes: bool,
+ ) -> Self {
Self {
page_num: page.page_number as u32,
page_label: page.page_label.clone(),
@@ -683,7 +695,9 @@ impl PyParsedPage {
text_items: page
.text_items
.into_iter()
- .map(|item| PyTextItem::from_rust_for_output(item, extract_text_metadata))
+ .map(|item| {
+ PyTextItem::from_rust_for_output(item, extract_text_metadata, word_boxes)
+ })
.collect(),
complexity: page
.complexity
@@ -851,13 +865,17 @@ impl PyParseResult {
}
impl PyParseResult {
- fn from_rust(result: liteparse::parser::ParseResult, extract_text_metadata: bool) -> Self {
+ fn from_rust(
+ result: liteparse::parser::ParseResult,
+ extract_text_metadata: bool,
+ word_boxes: bool,
+ ) -> Self {
Self {
total_pages: result.total_pages,
pages: result
.pages
.into_iter()
- .map(|page| PyParsedPage::from_rust(page, extract_text_metadata))
+ .map(|page| PyParsedPage::from_rust(page, extract_text_metadata, word_boxes))
.collect(),
text: result.text,
images: result
@@ -1388,6 +1406,7 @@ struct PyParseSession {
inner: liteparse::ParseSession,
runtime: std::sync::Arc<tokio::runtime::Runtime>,
extract_text_metadata: bool,
+ word_boxes: bool,
}
#[pymethods]
@@ -1410,7 +1429,11 @@ impl PyParseSession {
Ok(batch.map(|batch| PyParseBatch {
start_page: batch.start_page,
end_page: batch.end_page,
- result: PyParseResult::from_rust(batch.result, self.extract_text_metadata),
+ result: PyParseResult::from_rust(
+ batch.result,
+ self.extract_text_metadata,
+ self.word_boxes,
+ ),
}))
}
@@ -1673,6 +1696,7 @@ impl LiteParse {
Ok(PyParseResult::from_rust(
result,
self.config.extract_text_metadata,
+ self.config.output_word_boxes(),
))
}
@@ -1714,6 +1738,7 @@ impl LiteParse {
Ok(PyParseResult::from_rust(
result,
self.config.extract_text_metadata,
+ self.config.output_word_boxes(),
))
}
@@ -1818,6 +1843,7 @@ impl LiteParse {
inner: session,
runtime: self.runtime.clone(),
extract_text_metadata: self.config.extract_text_metadata,
+ word_boxes: self.config.output_word_boxes(),
})
}
}
@@ -1929,6 +1955,35 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {
mod tests {
use super::*;
+ #[test]
+ fn words_are_returned_only_when_requested() {
+ let item = liteparse::types::TextItem {
+ text: "a b".into(),
+ words: vec![
+ liteparse::types::WordBox {
+ text: "a".into(),
+ ..Default::default()
+ },
+ liteparse::types::WordBox {
+ text: "b".into(),
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ };
+ assert!(
+ PyTextItem::from_rust_for_output(item.clone(), false, false)
+ .words
+ .is_empty()
+ );
+ assert_eq!(
+ PyTextItem::from_rust_for_output(item, false, true)
+ .words
+ .len(),
+ 2
+ );
+ }
+
#[test]
fn text_metadata_round_trips_through_python_type() {
let item = liteparse::types::TextItem {
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index 172b002..d0e2bc0 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -1154,6 +1154,7 @@ impl LiteParse {
Ok(to_js_result(
&result,
self.inner.config().extract_text_metadata,
+ self.inner.config().output_word_boxes(),
))
}
}
@@ -1162,7 +1163,11 @@ impl LiteParse {
///
/// Shared by `parse()` and `ParseSession::nextBatch()` so a batch is mapped
/// exactly the same way a whole-document result is.
-fn to_js_result(result: &liteparse::ParseResult, extract_text_metadata: bool) -> ParseResult {
+fn to_js_result(
+ result: &liteparse::ParseResult,
+ extract_text_metadata: bool,
+ word_boxes: bool,
+) -> ParseResult {
let pages: Vec<ParsedPage> = result
.pages
.iter()
@@ -1210,7 +1215,7 @@ fn to_js_result(result: &liteparse::ParseResult, extract_text_metadata: bool) ->
.filter(|codes| !codes.is_empty())
.map(<[u32]>::to_vec),
trailing_space_generated: meta.trailing_space_generated,
- words: if i.words.is_empty() {
+ words: if !word_boxes || i.words.is_empty() {
None
} else {
Some(
@@ -1403,6 +1408,7 @@ impl LiteParse {
Ok(ParseSession {
extract_text_metadata: self.inner.config().extract_text_metadata,
+ word_boxes: self.inner.config().output_word_boxes(),
inner: session,
})
}
@@ -1430,6 +1436,7 @@ pub struct ParseBatch {
pub struct ParseSession {
inner: liteparse::ParseSession,
extract_text_metadata: bool,
+ word_boxes: bool,
}
#[wasm_bindgen]
@@ -1456,7 +1463,7 @@ impl ParseSession {
Ok(batch.map(|batch| ParseBatch {
start_page: batch.start_page,
end_page: batch.end_page,
- result: to_js_result(&batch.result, self.extract_text_metadata),
+ result: to_js_result(&batch.result, self.extract_text_metadata, self.word_boxes),
}))
}
}
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index 5929c44..369a0a1 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -264,6 +264,14 @@ impl LiteParseConfig {
pub fn effective_emit_word_boxes(&self) -> bool {
self.emit_word_boxes || self.output_format == OutputFormat::Markdown || self.extract_blocks
}
+
+ /// Whether the bindings return `TextItem.words` (napi, python, wasm; the
+ /// CLI JSON never does). Word boxes extracted only for `extract_blocks`
+ /// are left out there, so turning on blocks doesn't grow their text-item
+ /// payload. Rust callers still get them on `ParseResult`'s items.
+ pub fn output_word_boxes(&self) -> bool {
+ self.emit_word_boxes || self.output_format == OutputFormat::Markdown
+ }
}
impl Default for LiteParseConfig {
@@ -462,6 +470,20 @@ mod tests {
assert!(c.effective_emit_word_boxes());
}
+ #[test]
+ fn word_boxes_extracted_only_for_blocks_are_not_output() {
+ let mut c = LiteParseConfig {
+ extract_blocks: true,
+ ..LiteParseConfig::default()
+ };
+ assert!(!c.output_word_boxes());
+ c.emit_word_boxes = true;
+ assert!(c.output_word_boxes());
+ c.emit_word_boxes = false;
+ c.output_format = OutputFormat::Markdown;
+ assert!(c.output_word_boxes());
+ }
+
#[test]
fn test_output_format_lowercase_serde() {
let s = serde_json::to_string(&OutputFormat::Json).unwrap();