Skip to content

A fast, helpful, and open-source document parser

feat: add block-level layout to output

Logan Markewich3a1aa39060a2
diff --git a/README.md b/README.md
index 4f53e23..4de9580 100644
--- a/README.md
+++ b/README.md
@@ -202,6 +202,9 @@ lit parse document.pdf --format markdown --no-links
# Include tagged-PDF logical structure in JSON
lit parse document.pdf --format json --extract-structure-tree
+
+# Include the classified layout blocks (with bounding boxes) in JSON
+lit parse document.pdf --format json --extract-blocks
```
Image handling is controlled by `--image-mode`:
@@ -255,6 +258,49 @@ text, title, typed scalar attributes, marked-content IDs, children, and referenc
link annotations. The field is absent by default; enabled untagged pages contain
`roots: []`.
+### Layout blocks
+
+The Markdown renderer works by classifying each page into blocks — headings,
+paragraphs, list items, tables, code, rules, figures — and then rendering them.
+Enable `--extract-blocks` (Rust/Python `extract_blocks`, JavaScript/WASM
+`extractBlocks`) to get that decomposition as data instead of only as rendered
+text, with the coordinates the classifier used.
+
+Each page gains a `blocks` array in reading order — the same order, and the same
+blocks, the Markdown output is built from. Every block carries:
+
+- `kind`: one of `heading`, `paragraph`, `list_item`, `code`, `table`,
+ `grid_fallback`, `rule`, `figure`.
+- `bbox`: the region it occupies, in the same top-left 72-DPI viewport space as
+ `text_items`. This is the union of every source line that fed the block, so a
+ wrapped heading or a multi-line paragraph reports its whole band.
+- Kind-specific fields, omitted when they don't apply: `text` and `level` for
+ headings; `ordered` / `marker` for list items; `lines` and `lang` for code;
+ `header` and `rows` for tables; `id` / `format` for figures.
+
+Table cells are objects, not bare strings — each has `text` and its own `bbox`,
+so a cell can be mapped back to the region of the page it was read from. For
+ruled tables that box is the drawn grid cell; for borderless tables it is the
+extent of the spans the cell was built from. Cells that exist only to square off
+a ragged grid carry no `bbox`, since they have no ink behind them.
+
+```json
+{
+ "kind": "table",
+ "bbox": { "x": 72.0, "y": 310.5, "width": 468.0, "height": 96.0 },
+ "header": [
+ { "text": "Territory Code", "bbox": { "x": 72.0, "y": 310.5, "width": 120.0, "height": 24.0 } },
+ { "text": "Factor", "bbox": { "x": 192.0, "y": 310.5, "width": 96.0, "height": 24.0 } }
+ ],
+ "rows": [
+ [
+ { "text": "001", "bbox": { "x": 72.0, "y": 334.5, "width": 120.0, "height": 24.0 } },
+ { "text": "1.25", "bbox": { "x": 192.0, "y": 334.5, "width": 96.0, "height": 24.0 } }
+ ]
+ ]
+}
+```
+
### Document metadata, content bounds, and XFA packets
Parse results (Rust/Node/Python APIs) carry the document's `/Info` `creator`
diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rs
index 88e2bb7..4d7df3d 100644
--- a/crates/liteparse-napi/src/types.rs
+++ b/crates/liteparse-napi/src/types.rs
@@ -3,6 +3,7 @@ use std::collections::HashMap;
use napi_derive::napi;
use liteparse::config::{CropBox, ImageMode, LiteParseConfig, OutputFormat};
+use liteparse::layout::{LayoutBlock, LayoutCell};
use liteparse::parser::ParseResult;
use liteparse::types::{
DocumentAnnotation, FormField, GraphicPrimitive, Page, ParsedPage, Rect, ScreenshotRect,
@@ -67,6 +68,10 @@ pub struct JsLiteParseConfig {
pub keep_headers_footers: Option<bool>,
/// Extract all PDF annotations as page-scoped structured data.
pub extract_annotations: Option<bool>,
+ /// Emit each page's classified layout blocks (headings, paragraphs, list
+ /// items, tables with per-cell boxes, code, rules, figures) with bounding
+ /// boxes as `ParsedPage.blocks`. Default false.
+ pub extract_blocks: Option<bool>,
/// Extract AcroForm widget fields and values.
pub extract_form_fields: Option<bool>,
/// Extract the tagged-PDF logical structure tree.
@@ -201,6 +206,9 @@ impl JsLiteParseConfig {
if let Some(v) = self.extract_annotations {
cfg.extract_annotations = v;
}
+ if let Some(v) = self.extract_blocks {
+ cfg.extract_blocks = v;
+ }
if let Some(v) = self.extract_form_fields {
cfg.extract_form_fields = v;
}
@@ -289,6 +297,7 @@ impl JsLiteParseConfig {
extract_links: Some(cfg.extract_links),
keep_headers_footers: Some(cfg.keep_headers_footers),
extract_annotations: Some(cfg.extract_annotations),
+ extract_blocks: Some(cfg.extract_blocks),
extract_form_fields: Some(cfg.extract_form_fields),
extract_structure_tree: Some(cfg.extract_structure_tree),
extract_xfa_packets: Some(cfg.extract_xfa_packets),
@@ -585,6 +594,9 @@ pub struct JsParsedPage {
pub complexity: Option<JsPageComplexityStats>,
pub vector_graphics: Option<JsVectorGraphics>,
pub annotations: Option<Vec<JsDocumentAnnotation>>,
+ /// Classified layout blocks in reading order; present only when
+ /// `extractBlocks` is enabled.
+ pub blocks: Option<Vec<JsLayoutBlock>>,
pub form_fields: Option<Vec<JsFormField>>,
pub structure_tree: Option<JsStructureTree>,
}
@@ -846,6 +858,90 @@ impl JsDocumentAnnotation {
}
}
+/// One table cell: its rendered text and the region it occupied. `bbox` is
+/// absent for cells with no ink behind them (padding for a ragged grid, or a
+/// merged run split at an estimated boundary).
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsLayoutCell {
+ pub text: String,
+ pub bbox: Option<JsAnnotationRect>,
+}
+
+/// A classified block plus where it sits on the page. Flat by design — `kind`
+/// discriminates the block and every field that doesn't apply to that kind is
+/// absent.
+#[napi(object)]
+#[derive(Clone)]
+pub struct JsLayoutBlock {
+ /// One of `heading`, `paragraph`, `list_item`, `code`, `table`,
+ /// `grid_fallback`, `rule`, `figure`.
+ pub kind: String,
+ /// Rendered text for the text-bearing kinds (`heading`, `paragraph`,
+ /// `list_item`). Table text lives in `header`/`rows`; code and grid text in
+ /// `lines`.
+ pub text: Option<String>,
+ /// Heading level (1–6), or list nesting depth for `list_item`.
+ pub level: Option<u8>,
+ /// Whether the block's text is uniformly bold / italic. `paragraph` and
+ /// `list_item` only; false otherwise.
+ pub bold: bool,
+ pub italic: bool,
+ /// `list_item`: whether the list is ordered, and the original marker as it
+ /// appeared on the page (`138.`, `iii)`, `•`).
+ pub ordered: Option<bool>,
+ pub marker: Option<String>,
+ /// Verbatim source lines for `code` and `grid_fallback`.
+ pub lines: Option<Vec<String>>,
+ /// Best-effort language hint for `code`.
+ pub lang: Option<String>,
+ /// `table`: the header row, when one was detected.
+ pub header: Option<Vec<JsLayoutCell>>,
+ /// `table`: the body rows.
+ pub rows: Option<Vec<Vec<JsLayoutCell>>>,
+ /// `figure`: the image's page-scoped id and encoded format, matching the
+ /// `img_{id}.{format}` target the markdown renderer emits.
+ pub id: Option<String>,
+ pub format: Option<String>,
+ /// Region of the page this block occupies, in the same viewport space as
+ /// `textItems`. Absent when the block has no page geometry behind it.
+ pub bbox: Option<JsAnnotationRect>,
+}
+
+impl JsLayoutCell {
+ fn from_rust(cell: &LayoutCell) -> Self {
+ Self {
+ text: cell.text.clone(),
+ bbox: cell.bbox.as_ref().map(JsAnnotationRect::from_rust),
+ }
+ }
+}
+
+impl JsLayoutBlock {
+ fn from_rust(block: &LayoutBlock) -> Self {
+ let cells = |row: &Vec<LayoutCell>| row.iter().map(JsLayoutCell::from_rust).collect();
+ Self {
+ kind: block.kind.to_string(),
+ text: block.text.clone(),
+ level: block.level,
+ bold: block.bold,
+ italic: block.italic,
+ ordered: block.ordered,
+ marker: block.marker.clone(),
+ lines: block.lines.clone(),
+ lang: block.lang.clone(),
+ header: block.header.as_ref().map(&cells),
+ rows: block
+ .rows
+ .as_ref()
+ .map(|rows| rows.iter().map(&cells).collect()),
+ id: block.id.clone(),
+ format: block.format.clone(),
+ bbox: block.bbox.as_ref().map(JsAnnotationRect::from_rust),
+ }
+ }
+}
+
impl JsParsedPage {
pub fn from_rust(page: &ParsedPage, extract_text_metadata: bool) -> Self {
Self {
@@ -879,6 +975,10 @@ impl JsParsedPage {
.map(JsDocumentAnnotation::from_rust)
.collect()
}),
+ blocks: page
+ .blocks
+ .as_ref()
+ .map(|blocks| blocks.iter().map(JsLayoutBlock::from_rust).collect()),
form_fields: page
.form_fields
.as_ref()
diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rs
index 69f1cc8..a241078 100644
--- a/crates/liteparse-python/src/cli.rs
+++ b/crates/liteparse-python/src/cli.rs
@@ -92,6 +92,11 @@ struct ParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include each page's classified layout blocks (headings, paragraphs,
+ /// list items, tables with per-cell boxes, code, rules, figures) with
+ /// bounding boxes, in reading order.
+ #[arg(long)]
+ extract_blocks: bool,
/// Include raw XFA packets (name + XML content) in JSON output.
#[arg(long)]
extract_xfa_packets: bool,
@@ -197,6 +202,11 @@ struct BatchParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include each page's classified layout blocks (headings, paragraphs,
+ /// list items, tables with per-cell boxes, code, rules, figures) with
+ /// bounding boxes, in reading order.
+ #[arg(long)]
+ extract_blocks: bool,
/// Include raw XFA packets (name + XML content) in JSON output.
#[arg(long)]
extract_xfa_packets: bool,
@@ -288,6 +298,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_blocks: cmd.extract_blocks,
extract_xfa_packets: cmd.extract_xfa_packets,
extract_content_bounds: cmd.extract_content_bounds,
include_complexity: cmd.complexity,
@@ -393,6 +404,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_blocks: cmd.extract_blocks,
extract_xfa_packets: cmd.extract_xfa_packets,
extract_content_bounds: cmd.extract_content_bounds,
..Default::default()
diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rs
index c465df7..5ad832d 100644
--- a/crates/liteparse-python/src/lib.rs
+++ b/crates/liteparse-python/src/lib.rs
@@ -263,6 +263,113 @@ impl PyDocumentAnnotation {
}
}
+/// One table cell: its rendered text and the region it occupied.
+///
+/// `bbox` is `None` for cells with no ink behind them — padding inserted to
+/// square off a ragged grid, or halves of a merged run split at an estimated
+/// position rather than an observed boundary.
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyLayoutCell {
+ #[pyo3(get)]
+ text: String,
+ #[pyo3(get)]
+ bbox: Option<PyAnnotationRect>,
+}
+
+impl PyLayoutCell {
+ fn from_rust(cell: liteparse::layout::LayoutCell) -> Self {
+ Self {
+ text: cell.text,
+ bbox: cell.bbox.map(PyAnnotationRect::from_rust),
+ }
+ }
+}
+
+/// A classified block plus where it sits on the page.
+///
+/// `kind` discriminates the block; every field that doesn't apply to a block's
+/// kind is `None` (or `False` for the flags). Blocks appear in reading order,
+/// matching the order the markdown renderer emits them.
+#[pyclass(frozen, from_py_object)]
+#[derive(Clone)]
+struct PyLayoutBlock {
+ /// One of `heading`, `paragraph`, `list_item`, `code`, `table`,
+ /// `grid_fallback`, `rule`, `figure`.
+ #[pyo3(get)]
+ kind: String,
+ /// Rendered text for the text-bearing kinds (`heading`, `paragraph`,
+ /// `list_item`). Table text lives in `header`/`rows`; code and grid text in
+ /// `lines`.
+ #[pyo3(get)]
+ text: Option<String>,
+ /// Heading level (1–6), or list nesting depth for `list_item`.
+ #[pyo3(get)]
+ level: Option<u8>,
+ /// Whether the block's text is uniformly bold / italic. `paragraph` and
+ /// `list_item` only.
+ #[pyo3(get)]
+ bold: bool,
+ #[pyo3(get)]
+ italic: bool,
+ /// `list_item`: whether the list is ordered, and the original marker as it
+ /// appeared on the page (`138.`, `iii)`, `•`).
+ #[pyo3(get)]
+ ordered: Option<bool>,
+ #[pyo3(get)]
+ marker: Option<String>,
+ /// Verbatim source lines for `code` and `grid_fallback`.
+ #[pyo3(get)]
+ lines: Option<Vec<String>>,
+ /// Best-effort language hint for `code`.
+ #[pyo3(get)]
+ lang: Option<String>,
+ /// `table`: the header row, when one was detected.
+ #[pyo3(get)]
+ header: Option<Vec<PyLayoutCell>>,
+ /// `table`: the body rows.
+ #[pyo3(get)]
+ rows: Option<Vec<Vec<PyLayoutCell>>>,
+ /// `figure`: the image's page-scoped id and encoded format, matching the
+ /// `img_{id}.{format}` target the markdown renderer emits.
+ #[pyo3(get)]
+ id: Option<String>,
+ #[pyo3(get)]
+ format: Option<String>,
+ /// Region of the page this block occupies, in the same top-left, 72-DPI
+ /// viewport space as `text_items`. `None` when the block has no page
+ /// geometry behind it.
+ #[pyo3(get)]
+ bbox: Option<PyAnnotationRect>,
+}
+
+impl PyLayoutBlock {
+ fn from_rust(block: liteparse::layout::LayoutBlock) -> Self {
+ Self {
+ kind: block.kind.to_string(),
+ text: block.text,
+ level: block.level,
+ bold: block.bold,
+ italic: block.italic,
+ ordered: block.ordered,
+ marker: block.marker,
+ lines: block.lines,
+ lang: block.lang,
+ header: block
+ .header
+ .map(|cells| cells.into_iter().map(PyLayoutCell::from_rust).collect()),
+ rows: block.rows.map(|rows| {
+ rows.into_iter()
+ .map(|row| row.into_iter().map(PyLayoutCell::from_rust).collect())
+ .collect()
+ }),
+ id: block.id,
+ format: block.format,
+ bbox: block.bbox.map(PyAnnotationRect::from_rust),
+ }
+ }
+}
+
#[pyclass(frozen, from_py_object)]
#[derive(Clone)]
struct PyFormField {
@@ -433,6 +540,8 @@ struct PyParsedPage {
form_fields: Option<Vec<PyFormField>>,
#[pyo3(get)]
structure_tree: Option<PyStructureTree>,
+ #[pyo3(get)]
+ blocks: Option<Vec<PyLayoutBlock>>,
}
#[pyclass(frozen, from_py_object)]
@@ -589,6 +698,9 @@ impl PyParsedPage {
.map(PyStructureTreeElement::from_rust)
.collect(),
}),
+ blocks: page
+ .blocks
+ .map(|blocks| blocks.into_iter().map(PyLayoutBlock::from_rust).collect()),
}
}
}
@@ -1125,6 +1237,8 @@ struct PyLiteParseConfig {
#[pyo3(get)]
extract_structure_tree: bool,
#[pyo3(get)]
+ extract_blocks: bool,
+ #[pyo3(get)]
extract_xfa_packets: bool,
#[pyo3(get)]
extract_document_metadata: bool,
@@ -1202,6 +1316,7 @@ impl PyLiteParseConfig {
extract_annotations: cfg.extract_annotations,
extract_form_fields: cfg.extract_form_fields,
extract_structure_tree: cfg.extract_structure_tree,
+ extract_blocks: cfg.extract_blocks,
extract_xfa_packets: cfg.extract_xfa_packets,
extract_document_metadata: cfg.extract_document_metadata,
extract_content_bounds: cfg.extract_content_bounds,
@@ -1333,6 +1448,7 @@ impl LiteParse {
extract_annotations = None,
extract_form_fields = None,
extract_structure_tree = None,
+ extract_blocks = None,
extract_xfa_packets = None,
extract_document_metadata = None,
extract_content_bounds = None,
@@ -1371,6 +1487,7 @@ impl LiteParse {
extract_annotations: Option<bool>,
extract_form_fields: Option<bool>,
extract_structure_tree: Option<bool>,
+ extract_blocks: Option<bool>,
extract_xfa_packets: Option<bool>,
extract_document_metadata: Option<bool>,
extract_content_bounds: Option<bool>,
@@ -1463,6 +1580,9 @@ impl LiteParse {
if let Some(v) = extract_structure_tree {
cfg.extract_structure_tree = v;
}
+ if let Some(v) = extract_blocks {
+ cfg.extract_blocks = v;
+ }
if let Some(v) = extract_xfa_packets {
cfg.extract_xfa_packets = v;
}
@@ -1765,6 +1885,8 @@ fn _liteparse(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyStructureAttribute>()?;
m.add_class::<PyStructureTreeElement>()?;
m.add_class::<PyStructureTree>()?;
+ m.add_class::<PyLayoutCell>()?;
+ m.add_class::<PyLayoutBlock>()?;
m.add_class::<PyFormField>()?;
m.add_class::<PyScreenshotResult>()?;
m.add_class::<PyScreenshotRect>()?;
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index 37f2cb0..1341a02 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -106,6 +106,9 @@ pub struct LiteParseConfig {
/// Draw AcroForm field appearances into OCR rasters (runs document
/// open/JS actions). Default false.
render_form_fields: Option<bool>,
+ /// Attach the markdown classifier's block decomposition to each page as
+ /// `ParsedPage.blocks`. Default false.
+ extract_blocks: Option<bool>,
}
/// A page sub-region as the fraction cropped from each side (top-left origin,
@@ -244,6 +247,9 @@ impl LiteParseConfig {
if let Some(v) = self.render_form_fields {
cfg.render_form_fields = v;
}
+ if let Some(v) = self.extract_blocks {
+ cfg.extract_blocks = v;
+ }
cfg.num_workers = 1;
Ok(cfg)
}
@@ -301,6 +307,7 @@ impl LiteParseConfig {
extract_vector_graphics: Some(cfg.extract_vector_graphics),
extract_text_metadata: Some(cfg.extract_text_metadata),
render_form_fields: Some(cfg.render_form_fields),
+ extract_blocks: Some(cfg.extract_blocks),
}
}
}
@@ -390,6 +397,10 @@ pub struct ParsedPage {
pub form_fields: Option<Vec<FormField>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub structure_tree: Option<StructureTree>,
+ /// Classified layout blocks in reading order; present only when
+ /// `extractBlocks` is enabled.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blocks: Option<Vec<LayoutBlock>>,
}
#[derive(Serialize, Tsify)]
@@ -488,6 +499,122 @@ impl DocumentAnnotation {
}
}
+/// One table cell: its rendered text and the region it occupied.
+///
+/// `bbox` is absent for cells with no ink behind them — padding inserted to
+/// square off a ragged grid, or halves of a merged run split at an estimated
+/// position.
+#[derive(Serialize, Tsify)]
+#[tsify(into_wasm_abi)]
+#[serde(rename_all = "camelCase")]
+pub struct LayoutCell {
+ pub text: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bbox: Option<AnnotationRect>,
+}
+
+/// A classified block plus where it sits on the page.
+///
+/// `kind` discriminates the block and every field that doesn't apply to that
+/// kind is omitted, so a heading serializes as `{kind, text, level, bbox}`.
+/// Blocks appear in reading order, matching the page's markdown.
+#[derive(Serialize, Tsify)]
+#[tsify(into_wasm_abi)]
+#[serde(rename_all = "camelCase")]
+pub struct LayoutBlock {
+ /// One of `heading`, `paragraph`, `list_item`, `code`, `table`,
+ /// `grid_fallback`, `rule`, `figure`.
+ pub kind: String,
+ /// Rendered text for the text-bearing kinds (`heading`, `paragraph`,
+ /// `list_item`). Table text lives in `header`/`rows`; code and grid text
+ /// in `lines`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
+ /// Heading level (1–6), or list nesting depth for `list_item`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub level: Option<u8>,
+ /// Whether the block's text is uniformly bold / italic. `paragraph` and
+ /// `list_item` only; omitted when false.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub bold: bool,
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub italic: bool,
+ /// `list_item`: whether the list is ordered, and the original marker as it
+ /// appeared on the page (`138.`, `iii)`, `•`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ordered: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub marker: Option<String>,
+ /// Verbatim source lines for `code` and `grid_fallback`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lines: Option<Vec<String>>,
+ /// Best-effort language hint for `code`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lang: Option<String>,
+ /// `table`: the header row, when one was detected.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub header: Option<Vec<LayoutCell>>,
+ /// `table`: the body rows.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rows: Option<Vec<Vec<LayoutCell>>>,
+ /// `figure`: the image's page-scoped id and encoded format, matching the
+ /// `img_{id}.{format}` target the markdown renderer emits.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub format: Option<String>,
+ /// Region of the page this block occupies, in the same top-left, 72-DPI
+ /// viewport space as `textItems`. Absent when the block has no page
+ /// geometry behind it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bbox: Option<AnnotationRect>,
+}
+
+fn to_annotation_rect(rect: &liteparse::types::Rect) -> AnnotationRect {
+ AnnotationRect {
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ }
+}
+
+impl LayoutCell {
+ fn from_rust(cell: &liteparse::layout::LayoutCell) -> Self {
+ Self {
+ text: cell.text.clone(),
+ bbox: cell.bbox.as_ref().map(to_annotation_rect),
+ }
+ }
+}
+
+impl LayoutBlock {
+ fn from_rust(block: &liteparse::layout::LayoutBlock) -> Self {
+ let cells = |row: &Vec<liteparse::layout::LayoutCell>| {
+ row.iter().map(LayoutCell::from_rust).collect::<Vec<_>>()
+ };
+ Self {
+ kind: block.kind.to_string(),
+ text: block.text.clone(),
+ level: block.level,
+ bold: block.bold,
+ italic: block.italic,
+ ordered: block.ordered,
+ marker: block.marker.clone(),
+ lines: block.lines.clone(),
+ lang: block.lang.clone(),
+ header: block.header.as_ref().map(&cells),
+ rows: block
+ .rows
+ .as_ref()
+ .map(|rows| rows.iter().map(&cells).collect()),
+ id: block.id.clone(),
+ format: block.format.clone(),
+ bbox: block.bbox.as_ref().map(to_annotation_rect),
+ }
+ }
+}
+
#[derive(Serialize, Tsify)]
#[tsify(into_wasm_abi)]
#[serde(rename_all = "camelCase")]
@@ -1099,6 +1226,10 @@ fn to_js_result(result: &liteparse::ParseResult, extract_text_metadata: bool) ->
.as_ref()
.map(|fields| fields.iter().map(FormField::from_rust).collect()),
structure_tree: p.structure_tree.as_ref().map(StructureTree::from_rust),
+ blocks: p
+ .blocks
+ .as_ref()
+ .map(|blocks| blocks.iter().map(LayoutBlock::from_rust).collect()),
})
.collect();
diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rs
index a4bca65..ff3a8f7 100644
--- a/crates/liteparse/src/config.rs
+++ b/crates/liteparse/src/config.rs
@@ -73,6 +73,16 @@ pub struct LiteParseConfig {
/// Extract the tagged-PDF logical structure tree. Default `false`.
#[serde(default)]
pub extract_structure_tree: bool,
+ /// Emit each page's classified layout blocks (headings, paragraphs, list
+ /// items, tables with per-cell boxes, code, rules, figures) with bounding
+ /// boxes. Default `false`.
+ ///
+ /// This is the same decomposition the Markdown renderer consumes, exposed
+ /// as data. It is independent of `output_format`: blocks are available in
+ /// JSON and text modes too, and enabling it never changes the rendered
+ /// Markdown.
+ #[serde(default)]
+ pub extract_blocks: bool,
/// Emit each page's `content_bounds`: the union bbox of its top-level
/// content objects in viewport coords (visible content extent). Default
/// `false` to keep the default output shape unchanged. Content bounds are
@@ -239,6 +249,7 @@ impl Default for LiteParseConfig {
extract_annotations: false,
extract_form_fields: false,
extract_structure_tree: false,
+ extract_blocks: false,
extract_content_bounds: false,
extract_xfa_packets: false,
extract_document_metadata: false,
diff --git a/crates/liteparse/src/layout.rs b/crates/liteparse/src/layout.rs
new file mode 100644
index 0000000..0bf9fde
--- /dev/null
+++ b/crates/liteparse/src/layout.rs
@@ -0,0 +1,176 @@
+//! Public, serializable view of the markdown classifier's block decomposition.
+//!
+//! The classifier's internal [`Block`](crate::markdown_layout::Block) is a Rust
+//! enum with per-variant payloads. That shape can't cross the napi or PyO3
+//! boundary — neither supports enums carrying data — so the public type is a
+//! single flat struct discriminated by `kind`, with the variant-specific fields
+//! as `Option`s. This mirrors how the crate already exposes
+//! `StructureAttributeValue` to the bindings, and keeps one block shape across
+//! Rust, JSON, Node, Python, and WASM instead of three divergent ones.
+//!
+//! Every field that doesn't apply to a block's `kind` is `None` and is skipped
+//! during serialization, so a heading serializes as `{kind, text, level, bbox}`
+//! rather than a wall of nulls.
+
+use serde::Serialize;
+
+use crate::markdown_layout::{Block, Cell, PositionedBlock};
+use crate::types::Rect;
+
+/// One table cell: its rendered text and the region it occupied.
+///
+/// `bbox` is `None` for cells with no ink behind them — padding inserted to
+/// square off a ragged grid, or halves of a merged run split at an estimated
+/// position rather than an observed boundary.
+#[derive(Debug, Clone, Serialize)]
+pub struct LayoutCell {
+ pub text: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bbox: Option<Rect>,
+}
+
+impl From<&Cell> for LayoutCell {
+ fn from(c: &Cell) -> Self {
+ LayoutCell {
+ text: c.text.clone(),
+ bbox: c.bbox.clone(),
+ }
+ }
+}
+
+/// A classified block plus where it sits on the page.
+///
+/// `kind` discriminates the block; see each field for which kinds populate it.
+/// Blocks appear in reading order, matching the order the markdown renderer
+/// emits them, so the Nth block here is the Nth block of that page's markdown.
+#[derive(Debug, Clone, Serialize)]
+pub struct LayoutBlock {
+ /// One of `heading`, `paragraph`, `list_item`, `code`, `table`,
+ /// `grid_fallback`, `rule`, `figure`.
+ pub kind: &'static str,
+ /// Rendered text for the text-bearing kinds (`heading`, `paragraph`,
+ /// `list_item`). Table text lives in `header`/`rows`; code and grid text in
+ /// `lines`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
+ /// Heading level (1–6), or list nesting depth for `list_item`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub level: Option<u8>,
+ /// Whether the block's text is uniformly bold / italic. `paragraph` and
+ /// `list_item` only; omitted when false.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub bold: bool,
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub italic: bool,
+ /// `list_item`: whether the list is ordered, and the original marker as it
+ /// appeared on the page (`138.`, `iii)`, `•`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ordered: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub marker: Option<String>,
+ /// Verbatim source lines for `code` and `grid_fallback`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lines: Option<Vec<String>>,
+ /// Best-effort language hint for `code`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lang: Option<String>,
+ /// `table`: the header row, when one was detected.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub header: Option<Vec<LayoutCell>>,
+ /// `table`: the body rows.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rows: Option<Vec<Vec<LayoutCell>>>,
+ /// `figure`: the image's page-scoped id and encoded format, matching the
+ /// `img_{id}.{format}` target the markdown renderer emits.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub format: Option<String>,
+ /// Region of the page this block occupies, in the same top-left, 72-DPI
+ /// viewport space as `text_items`. The union of every source line that fed
+ /// the block, so a wrapped heading or multi-line paragraph reports its full
+ /// band. `None` when the block has no page geometry behind it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bbox: Option<Rect>,
+}
+
+impl LayoutBlock {
+ /// Base value with every variant-specific field cleared.
+ fn of(kind: &'static str, bbox: Option<Rect>) -> Self {
+ LayoutBlock {
+ kind,
+ text: None,
+ level: None,
+ bold: false,
+ italic: false,
+ ordered: None,
+ marker: None,
+ lines: None,
+ lang: None,
+ header: None,
+ rows: None,
+ id: None,
+ format: None,
+ bbox,
+ }
+ }
+}
+
+fn cells(row: &[Cell]) -> Vec<LayoutCell> {
+ row.iter().map(LayoutCell::from).collect()
+}
+
+impl From<&PositionedBlock> for LayoutBlock {
+ fn from(pb: &PositionedBlock) -> Self {
+ let bbox = pb.bbox.clone();
+ match &pb.block {
+ Block::Heading { level, text } => LayoutBlock {
+ text: Some(text.clone()),
+ level: Some(*level),
+ ..LayoutBlock::of("heading", bbox)
+ },
+ Block::Paragraph { text, bold, italic } => LayoutBlock {
+ text: Some(text.clone()),
+ bold: *bold,
+ italic: *italic,
+ ..LayoutBlock::of("paragraph", bbox)
+ },
+ Block::ListItem {
+ ordered,
+ marker,
+ level,
+ text,
+ bold,
+ italic,
+ } => LayoutBlock {
+ text: Some(text.clone()),
+ level: Some(*level),
+ ordered: Some(*ordered),
+ marker: Some(marker.clone()),
+ bold: *bold,
+ italic: *italic,
+ ..LayoutBlock::of("list_item", bbox)
+ },
+ Block::CodeBlock { lines, lang } => LayoutBlock {
+ lines: Some(lines.clone()),
+ lang: lang.clone(),
+ ..LayoutBlock::of("code", bbox)
+ },
+ Block::Table { header, rows } => LayoutBlock {
+ header: header.as_ref().map(|h| cells(h)),
+ rows: Some(rows.iter().map(|r| cells(r)).collect()),
+ ..LayoutBlock::of("table", bbox)
+ },
+ Block::GridFallback { lines } => LayoutBlock {
+ lines: Some(lines.clone()),
+ ..LayoutBlock::of("grid_fallback", bbox)
+ },
+ Block::HorizontalRule => LayoutBlock::of("rule", bbox),
+ Block::Figure { id, format } => LayoutBlock {
+ id: Some(id.clone()),
+ format: Some(format.clone()),
+ ..LayoutBlock::of("figure", bbox)
+ },
+ }
+ }
+}
diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rs
index 4b0a4c8..a3d1bc8 100644
--- a/crates/liteparse/src/lib.rs
+++ b/crates/liteparse/src/lib.rs
@@ -18,6 +18,7 @@ pub use types::{DocumentMetadata, ParsedPage, TextItem, WordBox};
pub mod config;
pub mod error;
pub mod glyph_resolver;
+pub mod layout;
pub mod parser;
pub mod search;
pub mod types;
diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rs
index df6c426..b0dd380 100644
--- a/crates/liteparse/src/main.rs
+++ b/crates/liteparse/src/main.rs
@@ -146,6 +146,11 @@ struct ParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include each page's classified layout blocks (headings, paragraphs,
+ /// list items, tables with per-cell boxes, code, rules, figures) with
+ /// bounding boxes, in reading order.
+ #[arg(long)]
+ extract_blocks: bool,
/// Include raw XFA packets (name + XML content) in JSON output.
#[arg(long)]
extract_xfa_packets: bool,
@@ -281,6 +286,11 @@ struct BatchParseCommand {
/// Include the tagged-PDF logical structure tree.
#[arg(long)]
extract_structure_tree: bool,
+ /// Include each page's classified layout blocks (headings, paragraphs,
+ /// list items, tables with per-cell boxes, code, rules, figures) with
+ /// bounding boxes, in reading order.
+ #[arg(long)]
+ extract_blocks: bool,
/// Include raw XFA packets (name + XML content) in JSON output.
#[arg(long)]
extract_xfa_packets: bool,
@@ -430,6 +440,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_blocks: cmd.extract_blocks,
extract_xfa_packets: cmd.extract_xfa_packets,
extract_content_bounds: cmd.extract_content_bounds,
include_complexity: cmd.complexity,
@@ -534,6 +545,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
extract_annotations: cmd.extract_annotations,
extract_form_fields: cmd.extract_form_fields,
extract_structure_tree: cmd.extract_structure_tree,
+ extract_blocks: cmd.extract_blocks,
extract_xfa_packets: cmd.extract_xfa_packets,
extract_content_bounds: cmd.extract_content_bounds,
..Default::default()
diff --git a/crates/liteparse/src/markdown_layout/blocks.rs b/crates/liteparse/src/markdown_layout/blocks.rs
index be06fee..ece6f05 100644
--- a/crates/liteparse/src/markdown_layout/blocks.rs
+++ b/crates/liteparse/src/markdown_layout/blocks.rs
@@ -1,6 +1,81 @@
use super::inline::escape_inline;
use super::paragraphs::{ParaAccum, is_soft_hyphen_break};
use super::tables::escape_table_cell;
+use crate::types::Rect;
+
+/// One table cell: rendered text plus, when the cell came from real page
+/// content, the region it occupied. `bbox` is `None` for cells that exist only
+/// to square off a ragged grid (padding inserted when rows disagree on column
+/// count) — those occupy no ink on the page, and reporting a rect for them
+/// would invent geometry the classifier never saw.
+#[derive(Debug, Clone, Default)]
+pub struct Cell {
+ pub text: String,
+ pub bbox: Option<Rect>,
+}
+
+impl Cell {
+ /// Cell carrying text and the region it was read from.
+ pub fn located(text: impl Into<String>, bbox: Rect) -> Self {
+ Cell {
+ text: text.into(),
+ bbox: Some(bbox),
+ }
+ }
+
+ /// Borrow the cell's text. Lets call sites that only care about content
+ /// read a `Cell` about as tersely as the `String` it replaced.
+ pub fn as_str(&self) -> &str {
+ &self.text
+ }
+}
+
+// Text-only construction (`"a".into()`, `s.to_string().into()`)
+impl From<&str> for Cell {
+ fn from(text: &str) -> Self {
+ Cell {
+ text: text.to_string(),
+ bbox: None,
+ }
+ }
+}
+
+impl From<String> for Cell {
+ fn from(text: String) -> Self {
+ Cell { text, bbox: None }
+ }
+}
+
+// Cells compare by content alone. A cell's box is derived metadata describing
+// where the text was read from, not part of its identity — two cells holding
+// the same text are the same table content whether or not either one knows its
+// coordinates. This is also what lets assertions compare a detected grid
+// against a plain literal of expected strings.
+impl PartialEq for Cell {
+ fn eq(&self, other: &Self) -> bool {
+ self.text == other.text
+ }
+}
+
+impl Eq for Cell {}
+
+impl PartialEq<str> for Cell {
+ fn eq(&self, other: &str) -> bool {
+ self.text == other
+ }
+}
+
+impl PartialEq<&str> for Cell {
+ fn eq(&self, other: &&str) -> bool {
+ self.text == *other
+ }
+}
+
+impl PartialEq<String> for Cell {
+ fn eq(&self, other: &String) -> bool {
+ self.text == *other
+ }
+}
/// Coarse block representation: the output of page classification, consumed by
/// `render_blocks` to produce the final markdown string.
@@ -36,8 +111,8 @@ pub enum Block {
/// when the first row didn't qualify (e.g. wasn't bold and the table mode
/// can't otherwise distinguish it).
Table {
- header: Option<Vec<String>>,
- rows: Vec<Vec<String>>,
+ header: Option<Vec<Cell>>,
+ rows: Vec<Vec<Cell>>,
},
/// Tabular-looking region we couldn't classify confidently — rendered
/// verbatim inside a fenced block to preserve visual structure for the
@@ -96,40 +171,94 @@ fn wrap_emphasis(text: &str, bold: bool, italic: bool) -> String {
}
}
-/// Render a list of blocks to a markdown string.
-pub fn render_blocks(blocks: &[Block]) -> String {
- let mut out = String::new();
- for (i, block) in blocks.iter().enumerate() {
- if i > 0 {
- // A word hyphenated across a soft line wrap sometimes lands in two
- // *separate* paragraph blocks (the classifier mis-split mid-word):
- // `…they dis-` ‖ `lodged…`. When the previous block ends with
- // `<letter>-` and this block is a plain paragraph beginning with a
- // lowercase letter, splice them: drop the hyphen and join with no
- // separator, healing both the word and the spurious break. The
- // lowercase + plain-text gates keep real compounds (`well-` then a
- // capitalized `Known`) and emphasised/heading/table starts intact.
- if let (
- Block::Paragraph { .. },
+/// A classified block plus the region of the page it was read from.
+///
+/// `bbox` is the union of the boxes of every source line that fed the block, so
+/// a wrapped heading or a multi-line paragraph reports the whole band it
+/// occupies. It is `None` only for blocks with no page geometry behind them —
+/// synthesized content, or sources that never carried coordinates.
+#[derive(Debug, Clone)]
+pub struct PositionedBlock {
+ pub block: Block,
+ pub bbox: Option<Rect>,
+}
+
+impl PositionedBlock {
+ pub fn new(block: Block, bbox: Option<Rect>) -> Self {
+ PositionedBlock { block, bbox }
+ }
+
+ /// A block with no known geometry.
+ pub fn unlocated(block: Block) -> Self {
+ PositionedBlock { block, bbox: None }
+ }
+
+ /// Grow this block's box to also cover `other`.
+ fn absorb(&mut self, other: &Option<Rect>) {
+ if let Some(r) = other {
+ Rect::extend(&mut self.bbox, r);
+ }
+ }
+}
+
+/// Heal words hyphenated across a soft line wrap that the classifier split into
+/// two *separate* paragraph blocks: `…they dis-` ‖ `lodged…`. When a plain
+/// paragraph ends with `<letter>-` and the next is a plain paragraph starting
+/// lowercase, fuse them — dropping the hyphen and joining with no separator —
+/// and union their boxes, since the result spans both source regions.
+///
+/// This runs as a pass over the block list rather than inside the renderer so
+/// that the blocks callers receive are the same ones that produced the
+/// markdown. The lowercase and plain-text gates keep real compounds (`well-`
+/// then a capitalized `Known`) and emphasised/heading/table starts intact.
+pub fn splice_soft_hyphens(blocks: Vec<PositionedBlock>) -> Vec<PositionedBlock> {
+ let mut out: Vec<PositionedBlock> = Vec::with_capacity(blocks.len());
+ for pb in blocks {
+ // Both sides must be unemphasised: an emphasised predecessor renders
+ // with a trailing `**`/`*`, so its final character was never the
+ // hyphen this splice keys off.
+ let joinable = match (out.last().map(|p| &p.block), &pb.block) {
+ (
+ Some(Block::Paragraph {
+ text: prev,
+ bold: false,
+ italic: false,
+ }),
Block::Paragraph {
text,
bold: false,
italic: false,
},
- ) = (&blocks[i - 1], block)
- && is_soft_hyphen_break(&out, text)
- {
- while out.ends_with(|c: char| c.is_whitespace()) {
- out.pop();
+ ) => is_soft_hyphen_break(prev, text).then(|| text.clone()),
+ _ => None,
+ };
+ if let Some(tail) = joinable {
+ let prev = out.last_mut().expect("gate matched on a previous block");
+ if let Block::Paragraph { text, .. } = &mut prev.block {
+ while text.ends_with(|c: char| c.is_whitespace()) {
+ text.pop();
}
- out.pop(); // the soft hyphen
- out.push_str(text);
- continue;
+ text.pop(); // the soft hyphen
+ text.push_str(&tail);
}
+ prev.absorb(&pb.bbox);
+ continue;
+ }
+ out.push(pb);
+ }
+ out
+}
+
+/// Render a list of blocks to a markdown string.
+pub fn render_blocks(blocks: &[PositionedBlock]) -> String {
+ let mut out = String::new();
+ for (i, positioned) in blocks.iter().enumerate() {
+ let block = &positioned.block;
+ if i > 0 {
// Consecutive list items render as a tight list (single newline).
// Everything else gets a blank line between blocks.
let tight = matches!(block, Block::ListItem { .. })
- && matches!(blocks[i - 1], Block::ListItem { .. });
+ && matches!(blocks[i - 1].block, Block::ListItem { .. });
if tight {
out.push('\n');
} else {
@@ -174,7 +303,7 @@ pub fn render_blocks(blocks: &[Block]) -> String {
// detector found no header, promote the first body row instead
// of synthesizing a blank `| | |` header — a visible empty
// row reads as sloppy output and carries no information.
- let (head, body): (Option<&[String]>, &[Vec<String>]) = match header {
+ let (head, body): (Option<&[Cell]>, &[Vec<Cell>]) = match header {
Some(h) => (Some(h.as_slice()), rows.as_slice()),
None => match rows.split_first() {
Some((first, rest)) => (Some(first.as_slice()), rest),
@@ -190,7 +319,7 @@ pub fn render_blocks(blocks: &[Block]) -> String {
if i > 0 {
out.push_str(" | ");
}
- out.push_str(&escape_table_cell(cell));
+ out.push_str(&escape_table_cell(&cell.text));
}
out.push_str(" |\n");
out.push('|');
@@ -203,7 +332,7 @@ pub fn render_blocks(blocks: &[Block]) -> String {
if i > 0 {
out.push_str(" | ");
}
- out.push_str(&escape_table_cell(cell));
+ out.push_str(&escape_table_cell(&cell.text));
}
out.push_str(" |");
}
@@ -255,6 +384,14 @@ pub fn render_blocks(blocks: &[Block]) -> String {
mod tests {
use super::*;
+ /// Render content blocks that carry no geometry — the shape almost every
+ /// rendering assertion below cares about.
+ fn render(blocks: Vec<Block>) -> String {
+ let positioned: Vec<PositionedBlock> =
+ blocks.into_iter().map(PositionedBlock::unlocated).collect();
+ render_blocks(&positioned)
+ }
+
#[test]
fn render_blocks_formats_markdown() {
let blocks = vec![
@@ -272,14 +409,14 @@ mod tests {
text: "Sub".into(),
},
];
- let s = render_blocks(&blocks);
+ let s = render(blocks);
assert_eq!(s, "# Title\n\nA paragraph.\n\n## Sub");
}
#[test]
fn render_figure_uses_extracted_format() {
assert_eq!(
- render_blocks(&[Block::Figure {
+ render(vec![Block::Figure {
id: "p1_1".into(),
format: "jpg".into(),
}]),
@@ -317,11 +454,11 @@ mod tests {
italic: false,
},
];
- let s = render_blocks(&blocks);
+ let s = render(blocks);
assert_eq!(s, "Intro.\n\n- a\n- b\n\nOutro.");
// Ordered: original marker preserved
- let s = render_blocks(&[
+ let s = render(vec![
Block::ListItem {
ordered: true,
marker: "138.".into(),
@@ -356,7 +493,7 @@ mod tests {
lines: vec!["body containing ``` backticks".into()],
lang: None,
}];
- let s = render_blocks(&blocks);
+ let s = render(blocks);
assert!(s.starts_with("~~~\n"));
assert!(s.ends_with("~~~"));
}
@@ -367,7 +504,7 @@ mod tests {
header: Some(vec!["a".into(), "b".into()]),
rows: vec![vec!["1".into(), "2".into()], vec!["3".into(), "4".into()]],
}];
- let s = render_blocks(&blocks);
+ let s = render(blocks);
assert_eq!(s, "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |");
}
@@ -378,15 +515,40 @@ mod tests {
bold: false,
italic: false,
};
+ let spliced = |a: &str, b: &str| {
+ splice_soft_hyphens(vec![
+ PositionedBlock::unlocated(p(a)),
+ PositionedBlock::unlocated(p(b)),
+ ])
+ };
+ let rendered = |a: &str, b: &str| render_blocks(&spliced(a, b));
// Mid-word hyphen split into two paragraphs heals into one.
- let s = render_blocks(&[p("they dis-"), p("lodged the part")]);
- assert_eq!(s, "they dislodged the part");
+ assert_eq!(
+ rendered("they dis-", "lodged the part"),
+ "they dislodged the part"
+ );
// Capitalized continuation is a real compound break — left intact.
- let s = render_blocks(&[p("the well-"), p("Known fact")]);
- assert_eq!(s, "the well-\n\nKnown fact");
+ assert_eq!(
+ rendered("the well-", "Known fact"),
+ "the well-\n\nKnown fact"
+ );
// Trailing dash not preceded by a letter doesn't splice.
- let s = render_blocks(&[p("a -"), p("dash line")]);
- assert_eq!(s, "a -\n\ndash line");
+ assert_eq!(rendered("a -", "dash line"), "a -\n\ndash line");
+ // A spliced block covers both source regions; an unspliced pair stays
+ // as two blocks with their own boxes.
+ let r = |y: f32| Rect {
+ x: 10.0,
+ y,
+ width: 100.0,
+ height: 12.0,
+ };
+ let joined = splice_soft_hyphens(vec![
+ PositionedBlock::new(p("they dis-"), Some(r(50.0))),
+ PositionedBlock::new(p("lodged the part"), Some(r(70.0))),
+ ]);
+ assert_eq!(joined.len(), 1);
+ let bbox = joined[0].bbox.clone().expect("merged block keeps geometry");
+ assert_eq!((bbox.y, bbox.height), (50.0, 32.0));
}
#[test]
@@ -395,7 +557,7 @@ mod tests {
header: None,
rows: vec![vec!["h1".into(), "h2".into()], vec!["1".into(), "2".into()]],
}];
- let s = render_blocks(&blocks);
+ let s = render(blocks);
// No blank `| | |` header: the first row becomes the header.
assert_eq!(s, "| h1 | h2 |\n|---|---|\n| 1 | 2 |");
}
diff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rs
index bb6b45c..7db5b52 100644
--- a/crates/liteparse/src/markdown_layout/classify.rs
+++ b/crates/liteparse/src/markdown_layout/classify.rs
@@ -1,6 +1,6 @@
-use crate::types::{OutlineTarget, ParsedPage, ProjectedLine};
+use crate::types::{OutlineTarget, ParsedPage, ProjectedLine, Rect};
-use super::blocks::{Block, paragraph_from_accum};
+use super::blocks::{Block, PositionedBlock, paragraph_from_accum};
use super::headings::{
HEADING_MAX_TEXT_CHARS, MAX_HEADING_LEVELS, heading_level_for, heading_size_of,
is_caption_line, is_toc_title, looks_like_bold_heading, looks_like_numbered_bold_heading,
@@ -28,12 +28,13 @@ use super::tables::{detect_ruled_tables, detect_tables_banded, merge_table_runs}
/// other.
#[derive(Clone)]
enum Interruption {
- Hr,
+ /// A divider rule, carrying the region of the stroke that produced it.
+ Hr(crate::types::Rect),
Figure(crate::types::ImageRef),
/// A ruled table detected by the global pass, already fully built. Emitted
/// at its top-y position like other interruptions; its lines were pulled
/// out of the region pipeline so it won't be re-detected per-region.
- Table(super::blocks::Block),
+ Table(super::blocks::PositionedBlock),
}
/// Returns true if any span on the line is rotated more than ~5° off
@@ -51,7 +52,7 @@ pub(super) fn is_rotated_line(line: &ProjectedLine) -> bool {
/// Classify a single page's `ProjectedLine`s into blocks.
#[cfg(test)]
-pub(super) fn classify_page(page: &ParsedPage, heading_map: &[(f32, u8)]) -> Vec<Block> {
+pub(super) fn classify_page(page: &ParsedPage, heading_map: &[(f32, u8)]) -> Vec<PositionedBlock> {
classify_page_with_filters(
page,
heading_map,
@@ -77,7 +78,7 @@ pub fn classify_page_with_filters(
outline: &[OutlineTarget],
image_mode: crate::config::ImageMode,
chrome_indices: &std::collections::HashSet<usize>,
-) -> Vec<Block> {
+) -> Vec<PositionedBlock> {
let debug = *super::flags::DEBUG_MD;
// TOC suppression: when ≥3 lines on this page look like TOC entries
@@ -163,7 +164,7 @@ pub fn classify_page_with_filters(
// Rule segments are extracted from the page graphics once and shared by
// every table-detection pass below (global, per-region, leaf veto, bands).
let rule_segments = super::tables::extract_rule_segments(&page.graphics);
- let mut global_ruled_tables: Vec<(f32, Block)> = Vec::new();
+ let mut global_ruled_tables: Vec<(f32, PositionedBlock)> = Vec::new();
let mut global_ruled_consumed: std::collections::HashSet<usize> =
std::collections::HashSet::new();
for (run, consumed) in super::tables::detect_ruled_tables_global(
@@ -233,7 +234,7 @@ pub fn classify_page_with_filters(
.iter()
.map(|&i| lines[i].bbox.y)
.fold(f32::INFINITY, f32::min);
- global_ruled_tables.push((top_y, run.block));
+ global_ruled_tables.push((top_y, PositionedBlock::new(run.block, run.bbox)));
global_ruled_consumed.extend(consumed);
}
let global_ruled_owned: Option<Vec<ProjectedLine>> = if global_ruled_consumed.is_empty() {
@@ -308,7 +309,7 @@ pub fn classify_page_with_filters(
// that no leaf covers) are emitted between regions in y order.
let mut all_interruptions: Vec<(f32, Interruption)> = detect_horizontal_rules(page)
.into_iter()
- .map(|y| (y, Interruption::Hr))
+ .map(|r| (r.y, Interruption::Hr(r)))
.collect();
if !matches!(image_mode, crate::config::ImageMode::Off) {
for r in &page.image_refs {
@@ -327,17 +328,10 @@ pub fn classify_page_with_filters(
// governs intra-region merging — no second source of truth.
let mut region_boundaries: Vec<usize> = Vec::new();
let mut interrupt_cursor = 0usize;
- let mut blocks: Vec<Block> = Vec::new();
+ let mut blocks: Vec<PositionedBlock> = Vec::new();
- let push_interruption = |blocks: &mut Vec<Block>, kind: Interruption| {
- blocks.push(match kind {
- Interruption::Hr => Block::HorizontalRule,
- Interruption::Figure(r) => Block::Figure {
- id: r.id,
- format: r.format,
- },
- Interruption::Table(b) => b,
- });
+ let push_interruption = |blocks: &mut Vec<PositionedBlock>, kind: Interruption| {
+ blocks.push(positioned_interruption(kind));
};
for (rstart, rend) in region_ranges {
@@ -406,6 +400,23 @@ pub fn classify_page_with_filters(
stitch_regions(blocks, &region_boundaries)
}
+/// Turn an interruption into a positioned block. Both the page-level walker
+/// and `FlowState::emit_before` funnel through here so the two emission paths
+/// stay identical.
+fn positioned_interruption(kind: Interruption) -> PositionedBlock {
+ match kind {
+ Interruption::Hr(rect) => PositionedBlock::new(Block::HorizontalRule, Some(rect)),
+ Interruption::Figure(r) => PositionedBlock::new(
+ Block::Figure {
+ id: r.id,
+ format: r.format,
+ },
+ Some(r.bbox),
+ ),
+ Interruption::Table(b) => b,
+ }
+}
+
/// Mutable per-line flow state threaded through `classify_region`: the active
/// paragraph accumulator, the active code run, and the current list run. The
/// flush/reset/emit methods live here so list-state resets collapse to method
@@ -414,7 +425,7 @@ pub fn classify_page_with_filters(
#[derive(Default)]
struct FlowState {
paragraph: Option<ParaAccum>,
- code: Option<Vec<String>>,
+ code: Option<(Vec<String>, Option<Rect>)>,
list_base_indent: Option<f32>,
last_list_item_idx: Option<usize>,
last_list_line: Option<usize>,
@@ -430,21 +441,22 @@ impl FlowState {
}
/// Emit the active paragraph (if it has non-blank content) and clear it.
- fn flush_paragraph(&mut self, blocks: &mut Vec<Block>) {
+ fn flush_paragraph(&mut self, blocks: &mut Vec<PositionedBlock>) {
if let Some(acc) = self.paragraph.take()
&& !acc.raw.trim().is_empty()
{
- blocks.push(paragraph_from_accum(acc));
+ let bbox = acc.bbox.clone();
+ blocks.push(PositionedBlock::new(paragraph_from_accum(acc), bbox));
}
}
/// Emit the active code run (if non-empty) and clear it.
- fn flush_code(&mut self, blocks: &mut Vec<Block>) {
- if let Some(lines) = self.code.take()
+ fn flush_code(&mut self, blocks: &mut Vec<PositionedBlock>) {
+ if let Some((lines, bbox)) = self.code.take()
&& !lines.is_empty()
{
let lang = detect_code_language(&lines);
- blocks.push(Block::CodeBlock { lines, lang });
+ blocks.push(PositionedBlock::new(Block::CodeBlock { lines, lang }, bbox));
}
}
@@ -452,7 +464,7 @@ impl FlowState {
/// active paragraph/code/list state first so each lands as its own block.
fn emit_before(
&mut self,
- blocks: &mut Vec<Block>,
+ blocks: &mut Vec<PositionedBlock>,
iter: &mut std::iter::Peekable<std::vec::IntoIter<(f32, Interruption)>>,
before_y: f32,
) {
@@ -464,14 +476,7 @@ impl FlowState {
self.flush_paragraph(blocks);
self.flush_code(blocks);
self.reset_list();
- blocks.push(match kind {
- Interruption::Hr => Block::HorizontalRule,
- Interruption::Figure(r) => Block::Figure {
- id: r.id,
- format: r.format,
- },
- Interruption::Table(b) => b,
- });
+ blocks.push(positioned_interruption(kind));
}
}
}
@@ -493,8 +498,8 @@ fn classify_region(
toc_page: bool,
debug: bool,
precomputed_tables: Option<Vec<super::tables::TableRun>>,
-) -> Vec<Block> {
- let mut blocks: Vec<Block> = Vec::new();
+) -> Vec<PositionedBlock> {
+ let mut blocks: Vec<PositionedBlock> = Vec::new();
let mut state = FlowState::default();
let mut heading_run: Option<(u8, usize)> = None;
// Track whether we've already emitted a TOC title on this page. Once seen,
@@ -563,7 +568,7 @@ fn classify_region(
state.flush_code(&mut blocks);
state.reset_list();
let run = table_iter.next().unwrap();
- blocks.push(run.block);
+ blocks.push(PositionedBlock::new(run.block, run.bbox));
idx = run.end;
continue;
}
@@ -601,10 +606,9 @@ fn classify_region(
if line.all_mono {
state.flush_paragraph(&mut blocks);
state.reset_list();
- state
- .code
- .get_or_insert_with(Vec::new)
- .push(line.text.trim_end().to_string());
+ let code = state.code.get_or_insert_with(Default::default);
+ code.0.push(line.text.trim_end().to_string());
+ Rect::extend(&mut code.1, &line.bbox);
continue;
}
// Any non-mono line ends the current code block (if any).
@@ -618,7 +622,10 @@ fn classify_region(
state.reset_list();
heading_run = None;
if is_rule {
- blocks.push(Block::HorizontalRule);
+ blocks.push(PositionedBlock::new(
+ Block::HorizontalRule,
+ Some(line.bbox.clone()),
+ ));
}
if debug {
eprintln!(
@@ -750,12 +757,19 @@ fn classify_region(
&& cont_looks_like_heading
&& let Some((run_level, run_idx)) = heading_run.as_ref()
&& continues_heading(&lines[*run_idx], line)
- && let Some(Block::Heading {
- level: last_level,
- text: htext,
+ && let Some(PositionedBlock {
+ block:
+ Block::Heading {
+ level: last_level,
+ text: htext,
+ },
+ bbox: heading_bbox,
+ ..
}) = blocks.last_mut()
&& *last_level == *run_level
{
+ // The continuation line is part of the same heading.
+ Rect::extend(heading_bbox, &line.bbox);
let combined_chars = htext.chars().count() + 1 + text.chars().count();
if combined_chars <= HEADING_MAX_TEXT_CHARS {
let run_level = *run_level;
@@ -784,9 +798,13 @@ fn classify_region(
if let Some((run_level, run_idx)) = heading_run.as_ref()
&& *run_level == level
&& continues_heading(&lines[*run_idx], line)
- && let Some(Block::Heading {
- level: last_level,
- text: htext,
+ && let Some(PositionedBlock {
+ block:
+ Block::Heading {
+ level: last_level,
+ text: htext,
+ },
+ ..
}) = blocks.last_mut()
&& *last_level == level
{
@@ -808,6 +826,7 @@ fn classify_region(
inline: demoted,
last: lines[*run_idx].clone(),
uniform: None,
+ bbox: Some(lines[*run_idx].bbox.clone()),
});
heading_run = None;
demoted_heading = true;
@@ -829,10 +848,13 @@ fn classify_region(
line.dominant_font_size,
);
}
- blocks.push(Block::Heading {
- level,
- text: collapse_whitespace(text),
- });
+ blocks.push(PositionedBlock::new(
+ Block::Heading {
+ level,
+ text: collapse_whitespace(text),
+ },
+ Some(line.bbox.clone()),
+ ));
heading_run = Some((level, line_idx));
continue;
}
@@ -874,10 +896,13 @@ fn classify_region(
state.flush_paragraph(&mut blocks);
state.reset_list();
let level = (heading_map.len() as u8 + 1).clamp(1, MAX_HEADING_LEVELS as u8);
- blocks.push(Block::Heading {
- level,
- text: collapse_whitespace(text),
- });
+ blocks.push(PositionedBlock::new(
+ Block::Heading {
+ level,
+ text: collapse_whitespace(text),
+ },
+ Some(line.bbox.clone()),
+ ));
continue;
}
state.flush_paragraph(&mut blocks);
@@ -893,14 +918,17 @@ fn classify_region(
// which still contain the marker span — render the line and then
// peel the marker off the front of the rendered string.
let item_text = render_list_item_text(line, &marker, rest);
- blocks.push(Block::ListItem {
- ordered,
- marker,
- level,
- text: item_text,
- bold: false,
- italic: false,
- });
+ blocks.push(PositionedBlock::new(
+ Block::ListItem {
+ ordered,
+ marker,
+ level,
+ text: item_text,
+ bold: false,
+ italic: false,
+ },
+ Some(line.bbox.clone()),
+ ));
continue;
}
@@ -911,14 +939,17 @@ fn classify_region(
if let Some(item_idx) = state.last_list_item_idx
&& let Some(prev_idx) = state.last_list_line
&& continues_list_item(&lines[prev_idx], line)
- && let Some(Block::ListItem {
+ && let Some(item) = blocks.get_mut(item_idx)
+ && let Block::ListItem {
text: prev_text, ..
- }) = blocks.get_mut(item_idx)
+ } = &mut item.block
{
// De-hyphenate against the prior rendered text, then append the
// inline-styled continuation.
let cont_inline = render_line_inline(line);
append_inline_continuation(prev_text, text, &cont_inline);
+ // The wrapped line belongs to the same item, so it grows its box.
+ Rect::extend(&mut item.bbox, &line.bbox);
state.last_list_line = Some(line_idx);
continue;
}
@@ -950,10 +981,13 @@ fn classify_region(
line.dominant_font_size,
);
}
- blocks.push(Block::Heading {
- level,
- text: collapse_whitespace(text),
- });
+ blocks.push(PositionedBlock::new(
+ Block::Heading {
+ level,
+ text: collapse_whitespace(text),
+ },
+ Some(line.bbox.clone()),
+ ));
// Arm the heading_run so a wrapped continuation on the next line
// merges into this heading instead of emitting as a second one.
heading_run = Some((level, line_idx));
@@ -978,6 +1012,7 @@ fn classify_region(
state.paragraph = Some(ParaAccum {
raw,
inline,
+ bbox: Some(line.bbox.clone()),
last: line.clone(),
uniform,
});
@@ -1112,13 +1147,13 @@ fn detect_code_language(lines: &[String]) -> Option<String> {
/// A bullet point split across columns is rare and a false merge is worse
/// than a true split; a table split across leaves indicates a projection-side
/// issue better fixed there than papered over here.
-fn stitch_regions(blocks: Vec<Block>, region_starts: &[usize]) -> Vec<Block> {
+fn stitch_regions(blocks: Vec<PositionedBlock>, region_starts: &[usize]) -> Vec<PositionedBlock> {
if region_starts.len() <= 1 {
return blocks;
}
let boundary_set: std::collections::HashSet<usize> =
region_starts.iter().skip(1).copied().collect();
- let mut out: Vec<Block> = Vec::with_capacity(blocks.len());
+ let mut out: Vec<PositionedBlock> = Vec::with_capacity(blocks.len());
for (i, block) in blocks.into_iter().enumerate() {
if boundary_set.contains(&i)
&& let Some(prev) = out.last_mut()
@@ -1131,8 +1166,15 @@ fn stitch_regions(blocks: Vec<Block>, region_starts: &[usize]) -> Vec<Block> {
bold: false,
italic: false,
},
- ) = (prev, &block)
+ ) = (&mut prev.block, &block.block)
{
+ // Either merge below fuses the two blocks, so the survivor covers
+ // both leaves. Computed up front because `prev_text` borrows
+ // `prev` for the rest of the arm.
+ let merged_bbox = match (&prev.bbox, &block.bbox) {
+ (Some(a), Some(b)) => Some(a.union(b)),
+ (some, None) | (None, some) => some.clone(),
+ };
let prev_trim = prev_text.trim_end();
let starts_lower = cur_text
.trim_start()
@@ -1149,6 +1191,7 @@ fn stitch_regions(blocks: Vec<Block>, region_starts: &[usize]) -> Vec<Block> {
}
prev_text.pop(); // the '-'
prev_text.push_str(cur_text.trim_start());
+ prev.bbox = merged_bbox;
continue;
}
let ends_open = !prev_trim.ends_with(|c: char| {
@@ -1160,6 +1203,7 @@ fn stitch_regions(blocks: Vec<Block>, region_starts: &[usize]) -> Vec<Block> {
if ends_open && starts_lower {
prev_text.push(' ');
prev_text.push_str(cur_text.trim_start());
+ prev.bbox = merged_bbox;
continue;
}
}
@@ -1179,6 +1223,53 @@ mod tests {
use super::*;
use crate::types::TextItem;
+ #[test]
+ fn blocks_report_the_region_they_were_read_from() {
+ // Same shape as the heading/paragraph case below: an 18pt title, a
+ // two-line paragraph, then a separate paragraph further down.
+ let p = page(vec![
+ line("Title of the document goes here", 50.0, 50.0, 18.0, 18.0),
+ line("First sentence of the para-", 50.0, 80.0, 10.0, 10.0),
+ line("graph continues here.", 50.0, 92.0, 10.0, 10.0),
+ line("Another paragraph.", 50.0, 130.0, 10.0, 10.0),
+ ]);
+ let pages = vec![p];
+ let body = compute_body_size(&pages);
+ let map = build_heading_map(&pages, body);
+ let blocks = classify_page(&pages[0], &map);
+
+ let bbox = |i: usize| blocks[i].bbox.clone().expect("block should be located");
+ // The heading is one line: its own band.
+ let h = bbox(0);
+ assert_eq!((h.y, h.height), (50.0, 18.0));
+ // The paragraph wraps two lines, so it spans from the top of the first
+ // to the bottom of the second (80.0 → 92.0 + 10.0), not just one line.
+ let para = bbox(1);
+ assert_eq!((para.y, para.height), (80.0, 22.0));
+ // The following paragraph keeps its own band rather than inheriting it.
+ let next = bbox(2);
+ assert_eq!((next.y, next.height), (130.0, 10.0));
+ }
+
+ #[test]
+ fn horizontal_rule_reports_the_stroke_it_came_from() {
+ let lines = vec![
+ line("before the rule", 50.0, 100.0, 10.0, 10.0),
+ line("after the rule", 50.0, 300.0, 10.0, 10.0),
+ ];
+ let p = page_with_graphics(lines, vec![stroke(50.0, 200.0, 450.0, 200.0, 0.5)]);
+ let blocks = classify_page(&p, &[]);
+ let hr = blocks
+ .iter()
+ .find(|b| matches!(b.block, Block::HorizontalRule))
+ .expect("expected an HR block");
+ // The rule carries the drawn stroke's x-extent, not just its y.
+ let r = hr.bbox.clone().expect("HR should be located");
+ assert_eq!(r.y, 200.0);
+ assert_eq!(r.x, 50.0);
+ assert_eq!(r.width, 400.0);
+ }
+
#[test]
fn classify_emits_heading_and_paragraph() {
let p = page(vec![
@@ -1192,21 +1283,21 @@ mod tests {
let map = build_heading_map(&pages, body);
let blocks = classify_page(&pages[0], &map);
assert_eq!(blocks.len(), 3);
- match &blocks[0] {
+ match &blocks[0].block {
Block::Heading { level, text } => {
assert_eq!(*level, 1);
assert_eq!(text, "Title of the document goes here");
}
other => panic!("expected heading, got {other:?}"),
}
- match &blocks[1] {
+ match &blocks[1].block {
Block::Paragraph { text: t, .. } => {
assert!(t.contains("paragraph continues"), "got: {t}");
assert!(!t.contains("para-"), "de-hyphenation failed: {t}");
}
other => panic!("expected paragraph, got {other:?}"),
}
- match &blocks[2] {
+ match &blocks[2].block {
Block::Paragraph { text: t, .. } => assert_eq!(t, "Another paragraph."),
other => panic!("expected paragraph, got {other:?}"),
}
@@ -1240,6 +1331,7 @@ mod tests {
let blocks = classify_page(&pages[0], &map);
let list_items: Vec<&Block> = blocks
.iter()
+ .map(|b| &b.block)
.filter(|b| matches!(b, Block::ListItem { .. }))
.collect();
assert_eq!(list_items.len(), 4);
@@ -1271,7 +1363,7 @@ mod tests {
let blocks = classify_page(&pages[0], &map);
// Expect: Paragraph("Intro line."), CodeBlock(2 lines), Paragraph("After...")
assert_eq!(blocks.len(), 3);
- match &blocks[1] {
+ match &blocks[1].block {
Block::CodeBlock { lines, .. } => {
assert_eq!(lines.len(), 2);
assert!(lines[0].contains("let x = 1;"));
@@ -1338,7 +1430,7 @@ mod tests {
let map = build_heading_map(&pages, body);
let blocks = classify_page(&pages[0], &map);
assert_eq!(blocks.len(), 1);
- match &blocks[0] {
+ match &blocks[0].block {
Block::Paragraph { bold, italic, .. } => {
assert!(*bold);
assert!(!*italic);
@@ -1371,7 +1463,7 @@ mod tests {
let map = build_heading_map(&pages, body);
let blocks = classify_page(&pages[0], &map);
assert_eq!(blocks.len(), 1, "got: {blocks:?}");
- match &blocks[0] {
+ match &blocks[0].block {
Block::Table { header, rows } => {
// Header isn't bold so no header row promoted.
assert!(header.is_none());
@@ -1426,7 +1518,7 @@ mod tests {
let map = build_heading_map(&pages, body);
let blocks = classify_page(&pages[0], &map);
assert_eq!(blocks.len(), 1, "got: {blocks:?}");
- match &blocks[0] {
+ match &blocks[0].block {
Block::Paragraph { text, bold, italic } => {
assert!(!*bold, "mixed-style paragraph shouldn't set block bold");
assert!(!*italic);
@@ -1454,7 +1546,7 @@ mod tests {
let map = build_heading_map(&pages, body);
let blocks = classify_page(&pages[0], &map);
assert_eq!(blocks.len(), 1);
- match &blocks[0] {
+ match &blocks[0].block {
Block::ListItem { text, .. } => {
assert_eq!(text, "**important item**");
}
@@ -1473,7 +1565,7 @@ mod tests {
let blocks = classify_page(&p, &[]);
let has_hr = blocks
.iter()
- .position(|b| matches!(b, Block::HorizontalRule));
+ .position(|b| matches!(b.block, Block::HorizontalRule));
assert!(has_hr.is_some(), "expected an HR block, got {blocks:?}");
// HR must land between the two paragraphs, not before/after both.
let pos = has_hr.unwrap();
diff --git a/crates/liteparse/src/markdown_layout/cross_region.rs b/crates/liteparse/src/markdown_layout/cross_region.rs
index 77246c6..ef08646 100644
--- a/crates/liteparse/src/markdown_layout/cross_region.rs
+++ b/crates/liteparse/src/markdown_layout/cross_region.rs
@@ -10,9 +10,18 @@
//! failed candidate leaves the page untouched, so the V-cut's wins on
//! multi-column prose are preserved.
-use super::blocks::Block;
+use super::blocks::{Block, Cell};
use super::tables::{TableRun, detect_tables};
-use crate::types::ProjectedLine;
+use crate::types::{ProjectedLine, Rect};
+
+/// Union of the boxes of every line in `lines`, or `None` when empty.
+fn union_line_rects(lines: &[&ProjectedLine]) -> Option<Rect> {
+ let mut out: Option<Rect> = None;
+ for l in lines {
+ Rect::extend(&mut out, &l.bbox);
+ }
+ out
+}
/// Minimum fraction of the smaller side's y-band that must overlap the other
/// side's. Side-by-side table halves overlap almost fully; a sidebar next to
@@ -290,7 +299,7 @@ fn validate_via_detectors(merged: &[ProjectedLine]) -> Option<Vec<TableRun>> {
let (mut cells, mut long) = (0usize, 0usize);
for row in rows {
for cell in row {
- let t = cell.trim();
+ let t = cell.text.trim();
if t.is_empty() {
continue;
}
@@ -321,7 +330,10 @@ fn validate_via_detectors(merged: &[ProjectedLine]) -> Option<Vec<TableRun>> {
/// continues the label cell, right-side lines append to the current row's
/// description cell.
fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Option<Vec<TableRun>> {
- let mut rows: Vec<(String, String, bool)> = Vec::new(); // (left, right, bold)
+ // (left, right, bold). Each side's cell box is the union of the lines that
+ // fed it, so wrapped labels and multi-line descriptions report the full band
+ // they occupy rather than just their first line.
+ let mut rows: Vec<(Cell, Cell, bool)> = Vec::new();
let mut last_label_bottom: Option<f32> = None;
for cluster in clusters {
@@ -347,15 +359,26 @@ fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Opti
(Some(lb), Some(_)) => top - lb <= CR_LABEL_WRAP_GAP_FACTOR * h.min(tol * 2.0),
_ => false,
};
+ let left_rect = union_line_rects(&cluster.left);
if wraps {
let row = rows.last_mut().unwrap();
- if !row.0.is_empty() {
- row.0.push(' ');
+ if !row.0.text.is_empty() {
+ row.0.text.push(' ');
+ }
+ row.0.text.push_str(&text);
+ if let Some(r) = &left_rect {
+ Rect::extend(&mut row.0.bbox, r);
}
- row.0.push_str(&text);
} else {
let bold = cluster.left.iter().all(|l| l.all_bold);
- rows.push((text, String::new(), bold));
+ rows.push((
+ Cell {
+ text,
+ bbox: left_rect,
+ },
+ Cell::default(),
+ bold,
+ ));
}
last_label_bottom = Some(bottom);
}
@@ -367,13 +390,16 @@ fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Opti
.collect::<Vec<_>>()
.join(" ");
if rows.is_empty() {
- rows.push((String::new(), String::new(), false));
+ rows.push((Cell::default(), Cell::default(), false));
}
let row = rows.last_mut().unwrap();
- if !row.1.is_empty() {
- row.1.push(' ');
+ if !row.1.text.is_empty() {
+ row.1.text.push(' ');
+ }
+ row.1.text.push_str(&text);
+ if let Some(r) = &union_line_rects(&cluster.right) {
+ Rect::extend(&mut row.1.bbox, r);
}
- row.1.push_str(&text);
}
}
@@ -384,13 +410,13 @@ fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Opti
// sentences is prose the anti-prose gate missed.
if rows
.iter()
- .any(|(l, _, _)| l.chars().count() > CR_LABEL_MAX_CHARS)
+ .any(|(l, _, _)| l.text.chars().count() > CR_LABEL_MAX_CHARS)
{
return None;
}
let both = rows
.iter()
- .filter(|(l, r, _)| !l.is_empty() && !r.is_empty())
+ .filter(|(l, r, _)| !l.text.is_empty() && !r.text.is_empty())
.count();
if both < 2 {
return None;
@@ -400,16 +426,16 @@ fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Opti
// header-ish words ("Area" / "Competence").
let header = {
let (l, r, bold) = &rows[0];
- if !l.is_empty()
- && !r.is_empty()
- && (*bold || (l.chars().count() <= 20 && r.chars().count() <= 20))
+ if !l.text.is_empty()
+ && !r.text.is_empty()
+ && (*bold || (l.text.chars().count() <= 20 && r.text.chars().count() <= 20))
{
Some(vec![l.clone(), r.clone()])
} else {
None
}
};
- let body: Vec<Vec<String>> = rows
+ let body: Vec<Vec<Cell>> = rows
.iter()
.skip(if header.is_some() { 1 } else { 0 })
.map(|(l, r, _)| vec![l.clone(), r.clone()])
@@ -417,10 +443,20 @@ fn try_two_col_direct(clusters: &[Cluster], merged_len: usize, tol: f32) -> Opti
if body.len() < 2 {
return None;
}
+ // The run's line indices address the synthetic fused rows, not the page, so
+ // its region comes from the clusters the rows were built from.
+ let bbox = clusters
+ .iter()
+ .flat_map(|c| c.members())
+ .fold(None, |mut acc: Option<Rect>, l| {
+ Rect::extend(&mut acc, &l.bbox);
+ acc
+ });
Some(vec![TableRun {
start: 0,
end: merged_len,
body_start: if header.is_some() { 1 } else { 0 },
+ bbox,
block: Block::Table { header, rows: body },
}])
}
@@ -732,12 +768,15 @@ mod tests {
assert_eq!(m.runs.len(), 1);
match &m.runs[0].block {
Block::Table { header, rows } => {
- assert_eq!(
- header.as_deref(),
- Some(&["Area".to_string(), "Competence".to_string()][..])
- );
+ let header_texts: Vec<&str> = header
+ .as_ref()
+ .expect("header should be present")
+ .iter()
+ .map(|c| c.as_str())
+ .collect();
+ assert_eq!(header_texts, ["Area", "Competence"]);
assert_eq!(rows.len(), 3);
- assert!(rows[0][1].contains("1.1 Valuing sustainability"));
+ assert!(rows[0][1].text.contains("1.1 Valuing sustainability"));
}
other => panic!("expected table, got {other:?}"),
}
diff --git a/crates/liteparse/src/markdown_layout/hr.rs b/crates/liteparse/src/markdown_layout/hr.rs
index 7e8f4ad..cd532a0 100644
--- a/crates/liteparse/src/markdown_layout/hr.rs
+++ b/crates/liteparse/src/markdown_layout/hr.rs
@@ -1,4 +1,4 @@
-use crate::types::{GraphicPrimitive, ParsedPage};
+use crate::types::{GraphicPrimitive, ParsedPage, Rect};
/// Maximum stroke thickness (or |y1-y2|) for a stroke to count as a candidate HR.
/// Thicker shapes are filled rects, not rules.
@@ -15,17 +15,19 @@ const HR_UNDERLINE_PROXIMITY_PT: f32 = 3.0;
/// Detect horizontal rules from a page's vector graphics.
///
-/// Returns the y-coordinates (viewport space) of accepted HRs, sorted ascending.
+/// Returns the accepted HRs (viewport space) as rects, sorted by y ascending.
+/// The rect spans the stroke's drawn x-extent and carries its thickness, so a
+/// rule reports the region it actually occupies rather than just its baseline.
/// An HR is a roughly horizontal stroke that spans at least
/// `HR_MIN_WIDTH_FRACTION` of the page width, is thinner than
/// `HR_MAX_THICKNESS_PT`, and does not sit on the baseline of any text line
/// (which would make it an underline).
-pub(super) fn detect_horizontal_rules(page: &ParsedPage) -> Vec<f32> {
+pub(super) fn detect_horizontal_rules(page: &ParsedPage) -> Vec<Rect> {
if page.graphics.is_empty() || page.page_width <= 0.0 {
return Vec::new();
}
let min_width = page.page_width * HR_MIN_WIDTH_FRACTION;
- let mut ys: Vec<f32> = Vec::new();
+ let mut rules: Vec<Rect> = Vec::new();
for g in &page.graphics {
let GraphicPrimitive::Stroke {
@@ -63,13 +65,20 @@ pub(super) fn detect_horizontal_rules(page: &ParsedPage) -> Vec<f32> {
if is_underline {
continue;
}
- ys.push(y);
+ rules.push(Rect {
+ x: xmin,
+ y,
+ width: (xmax - xmin).max(0.0),
+ // A hairline can report zero thickness; keep the drawn width so the
+ // rect is never degenerate.
+ height: dy.max(width),
+ });
}
// Sort + dedup near-duplicates (some PDFs draw the same rule twice).
- ys.sort_by(|a, b| a.total_cmp(b));
- ys.dedup_by(|a, b| (*a - *b).abs() < 1.0);
- ys
+ rules.sort_by(|a, b| a.y.total_cmp(&b.y));
+ rules.dedup_by(|a, b| (a.y - b.y).abs() < 1.0);
+ rules
}
#[cfg(test)]
@@ -81,8 +90,12 @@ mod tests {
fn hr_long_thin_horizontal_stroke_detected() {
// 400pt wide stroke on a 612pt page → comfortably above 30% threshold.
let p = page_with_graphics(vec![], vec![stroke(50.0, 200.0, 450.0, 200.5, 0.5)]);
- let ys = detect_horizontal_rules(&p);
+ let rules = detect_horizontal_rules(&p);
+ let ys: Vec<f32> = rules.iter().map(|r| r.y).collect();
assert_eq!(ys, vec![200.25]);
+ // The rule reports the stroke's drawn extent, not just its baseline.
+ assert_eq!(rules[0].x, 50.0);
+ assert_eq!(rules[0].width, 400.0);
}
#[test]
diff --git a/crates/liteparse/src/markdown_layout/mod.rs b/crates/liteparse/src/markdown_layout/mod.rs
index 80fe019..2865366 100644
--- a/crates/liteparse/src/markdown_layout/mod.rs
+++ b/crates/liteparse/src/markdown_layout/mod.rs
@@ -18,7 +18,7 @@ mod paragraphs;
mod repetition;
mod tables;
-pub use blocks::{Block, render_blocks};
+pub use blocks::{Block, Cell, PositionedBlock, render_blocks, splice_soft_hyphens};
pub use classify::classify_page_with_filters;
pub use headings::{build_heading_map, compute_body_size};
pub use repetition::{compute_header_footer_set, detect_single_page_chrome};
diff --git a/crates/liteparse/src/markdown_layout/paragraphs.rs b/crates/liteparse/src/markdown_layout/paragraphs.rs
index 0f2428b..e98fbf5 100644
--- a/crates/liteparse/src/markdown_layout/paragraphs.rs
+++ b/crates/liteparse/src/markdown_layout/paragraphs.rs
@@ -266,6 +266,9 @@ pub(super) struct ParaAccum {
pub(super) inline: String,
pub(super) last: ProjectedLine,
pub(super) uniform: Option<(bool, bool)>,
+ /// Union of every line folded into this paragraph, so the emitted block
+ /// reports the whole band it covers rather than its last line.
+ pub(super) bbox: Option<crate::types::Rect>,
}
/// Append `next_line` to a paragraph accumulator. Maintains both the `raw` and
@@ -283,6 +286,8 @@ pub(super) fn append_to_paragraph(accum: &mut ParaAccum, next_line: &ProjectedLi
// raw-text fast path — drop it to `None` to force the `inline` rendering.
let next_uniform: Option<SpanStyle> = line_uniform_style(next_line).filter(|s| !s.strike);
+ crate::types::Rect::extend(&mut accum.bbox, &next_line.bbox);
+
if accum.raw.is_empty() {
accum.raw.push_str(&next_raw);
accum.inline.push_str(&next_inline);
diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rs
index dbd6413..fe197e2 100644
--- a/crates/liteparse/src/markdown_layout/tables.rs
+++ b/crates/liteparse/src/markdown_layout/tables.rs
@@ -1,6 +1,6 @@
use crate::types::{GraphicPrimitive, ProjectedLine, Rect, TextItem};
-use super::blocks::Block;
+use super::blocks::{Block, Cell};
use super::paragraphs::collapse_whitespace;
use crate::projection::is_bold_item;
@@ -272,6 +272,39 @@ pub(super) struct TableRun {
/// re-extraction pass must not re-bin those header lines as body rows.
pub(super) body_start: usize,
pub(super) block: Block,
+ /// Region the whole table occupies. For ruled tables this is the drawn
+ /// grid; for the borderless detectors it is the union of the lines the run
+ /// consumed. `None` when the run was built without geometry (tests, and
+ /// synthetic merges with nothing to measure).
+ pub(super) bbox: Option<Rect>,
+}
+
+/// Union of the boxes of `lines[start..end]` — the region a table run covers
+/// when it has no drawn grid to fall back on.
+fn lines_bbox(lines: &[ProjectedLine], start: usize, end: usize) -> Option<Rect> {
+ let mut out: Option<Rect> = None;
+ for l in lines.get(start..end.min(lines.len()))? {
+ Rect::extend(&mut out, &l.bbox);
+ }
+ out
+}
+
+/// Region occupied by one borderless-table cell: its own x-extent (tracked by
+/// `split_cells` from the spans it absorbed) crossed with the vertical band of
+/// the line it sits on. A borderless table has no ruled boundaries, so a cell
+/// covers exactly the ink of its spans — not a full column track.
+fn cell_rect(cell: &TableCell, line: &ProjectedLine) -> Rect {
+ Rect {
+ x: cell.start_x,
+ y: line.bbox.y,
+ width: (cell.end_x - cell.start_x).max(0.0),
+ height: line.bbox.height,
+ }
+}
+
+/// Build a located `Cell` from a `TableCell` and its owning line.
+fn located_cell(cell: &TableCell, line: &ProjectedLine) -> Cell {
+ Cell::located(cell.text.clone(), cell_rect(cell, line))
}
/// Split a `ProjectedLine`'s spans into cells. A gap larger than
@@ -895,14 +928,19 @@ fn finalize_table_run(
Some((hstart, header_texts)) => (hstart, Some(header_texts), 0),
None if bold_header_qualifies => (
start_idx,
- Some(first_row.iter().map(|c| c.text.clone()).collect()),
+ Some(
+ first_row
+ .iter()
+ .map(|c| located_cell(c, rows[0].1))
+ .collect(),
+ ),
1,
),
None => (start_idx, None, 0),
};
- let body_rows: Vec<Vec<String>> = rows[row_start..]
+ let body_rows: Vec<Vec<Cell>> = rows[row_start..]
.iter()
- .map(|(_, _, cells)| cells.iter().map(|c| c.text.clone()).collect())
+ .map(|(_, line, cells)| cells.iter().map(|c| located_cell(c, line)).collect())
.collect();
if header.is_none() && body_rows.len() < TABLE_MIN_ROWS {
return None;
@@ -924,6 +962,7 @@ fn finalize_table_run(
start: run_start,
end,
body_start: start_idx,
+ bbox: lines_bbox(lines, run_start, end),
block: Block::Table {
header,
rows: body_rows,
@@ -1173,7 +1212,7 @@ fn two_row_run_plausible(lines: &[ProjectedLine], run: &TableRun) -> bool {
let mut non_empty = 0;
for cell in header {
- let t = cell.trim();
+ let t = cell.text.trim();
if t.is_empty() {
continue;
}
@@ -1365,6 +1404,7 @@ fn try_detect_table(lines: &[ProjectedLine], start_idx: usize, floor: usize) ->
start: start_idx,
end,
body_start: start_idx,
+ bbox: lines_bbox(lines, start_idx, end),
block: Block::GridFallback { lines: raw },
});
}
@@ -1395,9 +1435,12 @@ fn absorb_header_lines(
track_ranges: &[(f32, f32)],
column_count: usize,
floor: usize,
-) -> Option<(usize, Vec<String>)> {
+) -> Option<(usize, Vec<Cell>)> {
let dbgt = *super::flags::DEBUG_TABLE;
- let mut absorbed: Vec<Vec<TableCell>> = Vec::new();
+ // Line index is kept alongside the cells so the assembled header cells can
+ // report the band they were read from — a wrapped header spans every line
+ // that contributed to it, not just the last one.
+ let mut absorbed: Vec<(usize, Vec<TableCell>)> = Vec::new();
let mut j = start_idx;
while j > floor {
let cand = j - 1;
@@ -1458,7 +1501,7 @@ fn absorb_header_lines(
if !all_align {
break;
}
- absorbed.push(cells);
+ absorbed.push((cand, cells));
j = cand;
}
if absorbed.is_empty() {
@@ -1466,16 +1509,17 @@ fn absorb_header_lines(
}
// Collected bottom-up; reverse so text reads top-to-bottom per column.
absorbed.reverse();
- let mut header = vec![String::new(); column_count];
- for cells in &absorbed {
+ let mut header = vec![Cell::default(); column_count];
+ for (line_idx, cells) in &absorbed {
for c in cells {
let Some(idx) = match_track_idx(c, track_ranges) else {
continue;
};
- if !header[idx].is_empty() && !c.text.is_empty() {
- header[idx].push(' ');
+ if !header[idx].text.is_empty() && !c.text.is_empty() {
+ header[idx].text.push(' ');
}
- header[idx].push_str(&c.text);
+ header[idx].text.push_str(&c.text);
+ Rect::extend(&mut header[idx].bbox, &cell_rect(c, &lines[*line_idx]));
}
}
Some((j, header))
@@ -1931,8 +1975,11 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
return None;
}
- let mut rows: Vec<(usize, String, String)> =
- vec![(start_idx, first[0].text.clone(), first[1].text.clone())];
+ let mut rows: Vec<(usize, Cell, Cell)> = vec![(
+ start_idx,
+ located_cell(&first[0], &lines[start_idx]),
+ located_cell(&first[1], &lines[start_idx]),
+ )];
// Track how many rows came from the *actual* 2-cell path (i.e. PDFium
// emitted two distinct spans with a clear gap). The merged-span split path
// is a recovery hack for tight-kerning cases — when it's the only thing
@@ -1977,7 +2024,11 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
let c0_aligned = (cells[0].start_x - col0_x).abs() <= DESC_LIST_TRACK_TOL_PT;
let c1_aligned = (cells[1].start_x - col1_x).abs() <= DESC_LIST_TRACK_TOL_PT;
if c0_aligned && c1_aligned && is_label_like(&cells[0].text) {
- rows.push((j, cells[0].text.clone(), cells[1].text.clone()));
+ rows.push((
+ j,
+ located_cell(&cells[0], &lines[j]),
+ located_cell(&cells[1], &lines[j]),
+ ));
real_two_cell_rows += 1;
j += 1;
continue;
@@ -1989,10 +2040,15 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
let c0_aligned = (cell.start_x - col0_x).abs() <= DESC_LIST_TRACK_TOL_PT;
let c1_aligned = (cell.start_x - col1_x).abs() <= DESC_LIST_TRACK_TOL_PT;
if c1_aligned {
- if !rows.last().unwrap().2.is_empty() {
- rows.last_mut().unwrap().2.push(' ');
+ let tail = &mut rows.last_mut().unwrap().2;
+ if !tail.text.is_empty() {
+ tail.text.push(' ');
}
- rows.last_mut().unwrap().2.push_str(&cell.text);
+ tail.text.push_str(&cell.text);
+ // The wrapped continuation is part of the same logical
+ // cell, so it grows that cell's box rather than starting a
+ // new one.
+ Rect::extend(&mut tail.bbox, &cell_rect(cell, &lines[j]));
j += 1;
continue;
}
@@ -2004,7 +2060,10 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
split_merged_at_anchor(&cell.text, cell.start_x, cell.end_x, col1_x)
&& is_label_like(&left)
{
- rows.push((j, left, right));
+ // Split position is a linear estimate inside one merged
+ // span, not an observed boundary — the halves carry text
+ // only rather than a fabricated rect.
+ rows.push((j, left.into(), right.into()));
j += 1;
continue;
}
@@ -2031,7 +2090,7 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
// footnote lists (col 0 = footnote number). Real description-list tables
// have at least one row of word-on-word.
let has_alpha_pair = rows.iter().any(|(_, c0, c1)| {
- c0.chars().any(|c| c.is_alphabetic()) && c1.chars().any(|c| c.is_alphabetic())
+ c0.text.chars().any(|c| c.is_alphabetic()) && c1.text.chars().any(|c| c.is_alphabetic())
});
if !has_alpha_pair {
return None;
@@ -2040,7 +2099,7 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
// (digits or roman numerals), the run is a TOC. TOCs match the alpha
// pair check only when one of the page refs happens to be a roman
// numeral like "v" or "vi" alongside an alpha col 0.
- let all_page_refs = rows.iter().all(|(_, _, c1)| is_page_ref(c1));
+ let all_page_refs = rows.iter().all(|(_, _, c1)| is_page_ref(&c1.text));
if all_page_refs {
return None;
}
@@ -2049,14 +2108,14 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
// repeat 3+ times are tabular),
// (b) one row's col 1 is substantially longer than col 0 (paragraph
// cell next to a label cell — the classic description-list shape).
- let asymmetric = rows
- .iter()
- .any(|(_, c0, c1)| c1.chars().count() >= c0.chars().count().saturating_mul(2).max(20));
+ let asymmetric = rows.iter().any(|(_, c0, c1)| {
+ c1.text.chars().count() >= c0.text.chars().count().saturating_mul(2).max(20)
+ });
if rows.len() < 3 && !asymmetric {
return None;
}
- let body: Vec<Vec<String>> = rows
+ let body: Vec<Vec<Cell>> = rows
.iter()
.map(|(_, c0, c1)| vec![c0.clone(), c1.clone()])
.collect();
@@ -2064,6 +2123,7 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt
start: start_idx,
end: j,
body_start: start_idx,
+ bbox: lines_bbox(lines, start_idx, j),
block: Block::Table {
header: None,
rows: body,
@@ -2355,7 +2415,7 @@ fn union_tracks_in_window(lines: &[ProjectedLine], start: usize, end: usize) ->
/// the body-detection paths this accepts 1-cell rows — inside a confirmed
/// table cluster a lone label at a track is a sparse row (e.g. a row-label
/// city with every value column empty), not prose.
-fn sparse_row_via_cells(line: &ProjectedLine, tracks: &[f32]) -> Option<Vec<String>> {
+fn sparse_row_via_cells(line: &ProjectedLine, tracks: &[f32]) -> Option<Vec<Cell>> {
let cells = split_cells(line);
if cells.is_empty() {
return None;
@@ -2379,9 +2439,9 @@ fn sparse_row_via_cells(line: &ProjectedLine, tracks: &[f32]) -> Option<Vec<Stri
if distinct.len() != mapping.len() {
return None;
}
- let mut row = vec![String::new(); tracks.len()];
+ let mut row = vec![Cell::default(); tracks.len()];
for (c, &idx) in cells.iter().zip(&mapping) {
- row[idx] = c.text.clone();
+ row[idx] = located_cell(c, line);
}
Some(row)
}
@@ -2397,7 +2457,7 @@ fn union_header_from_above(
body_start: usize,
floor: usize,
tracks: &[f32],
-) -> Option<(usize, Vec<String>)> {
+) -> Option<(usize, Vec<Cell>)> {
let tol = TABLE_TRACK_TOLERANCE_PT;
// Fallback assignment for centered header cells whose extent doesn't
// reach the track anchor: nearest track within half the local gap.
@@ -2420,7 +2480,7 @@ fn union_header_from_above(
None
}
};
- let mut layers: Vec<Vec<String>> = Vec::new();
+ let mut layers: Vec<Vec<Cell>> = Vec::new();
let mut j = body_start;
while j > floor && layers.len() < TABLE_CLUSTER_MAX_HEADER_LINES {
let cand = j - 1;
@@ -2435,7 +2495,7 @@ fn union_header_from_above(
if spans.len() < 2 {
break;
}
- let mut layer = vec![String::new(); tracks.len()];
+ let mut layer = vec![Cell::default(); tracks.len()];
let mut ok = true;
for s in &spans {
let x0 = s.x;
@@ -2454,15 +2514,24 @@ fn union_header_from_above(
ok = false;
break;
};
+ // A span covering several tracks replicates into each of them, so
+ // every covered cell reports the span it was flattened from.
+ let span_rect = Rect {
+ x: s.x,
+ y: s.y,
+ width: s.width.max(0.0),
+ height: s.height.max(0.0),
+ };
for idx in targets {
let dst = &mut layer[idx];
- if !dst.is_empty() {
- dst.push(' ');
+ if !dst.text.is_empty() {
+ dst.text.push(' ');
}
- dst.push_str(s.text.trim());
+ dst.text.push_str(s.text.trim());
+ Rect::extend(&mut dst.bbox, &span_rect);
}
}
- if !ok || layer.iter().filter(|t| !t.is_empty()).count() < 2 {
+ if !ok || layer.iter().filter(|t| !t.text.is_empty()).count() < 2 {
break;
}
layers.push(layer);
@@ -2472,20 +2541,27 @@ fn union_header_from_above(
return None;
}
layers.reverse();
- let header: Vec<String> = (0..tracks.len())
+ let header: Vec<Cell> = (0..tracks.len())
.map(|col| {
let mut parts: Vec<&str> = Vec::new();
+ let mut bbox: Option<Rect> = None;
for layer in &layers {
let s = layer[col].as_str();
+ if let Some(r) = &layer[col].bbox {
+ Rect::extend(&mut bbox, r);
+ }
if s.is_empty() || parts.last() == Some(&s) {
continue;
}
parts.push(s);
}
- parts.join(" ")
+ Cell {
+ text: parts.join(" "),
+ bbox,
+ }
})
.collect();
- if header.iter().all(|h| h.is_empty()) {
+ if header.iter().all(|h| h.text.is_empty()) {
return None;
}
Some((j, header))
@@ -2572,12 +2648,12 @@ fn build_union_table(
// (merge). Re-extracted clusters keep one row per line; multi-line-cell
// recovery needs a stronger signal (ruled-grid row boundaries, or
// label-column row anchoring).
- let mut rows: Vec<Vec<String>> = Vec::new();
+ let mut rows: Vec<Vec<Cell>> = Vec::new();
let mut failed_count = 0usize;
for line in &lines[window_start..window_end] {
if let Some(cells) = cells_from_raw_items_with_tracks(line, &tracks) {
if cells.iter().any(|c| !c.text.is_empty()) {
- rows.push(cells.into_iter().map(|c| c.text).collect());
+ rows.push(cells.iter().map(|c| located_cell(c, line)).collect());
}
} else if let Some(row) = sparse_row_via_cells(line, &tracks) {
rows.push(row);
@@ -2588,8 +2664,10 @@ fn build_union_table(
failed_count += 1;
let text = line.text.trim();
if !text.is_empty() {
- let mut row = vec![String::new(); tracks.len()];
- row[0] = collapse_whitespace(text);
+ // Unbinnable line kept whole in column 0; it occupies the
+ // entire line, so that is the cell's box.
+ let mut row = vec![Cell::default(); tracks.len()];
+ row[0] = Cell::located(collapse_whitespace(text), line.bbox.clone());
rows.push(row);
}
}
@@ -2614,6 +2692,7 @@ fn build_union_table(
start,
end: window_end,
body_start: window_start,
+ bbox: lines_bbox(lines, start, window_end),
block: Block::Table { header, rows },
})
}
@@ -2728,8 +2807,10 @@ fn subset_mapping(a: &[(f32, f32)], b: &[(f32, f32)]) -> Option<Vec<usize>> {
/// Insert empty strings into `row` so that its content lands at the mapped
/// columns in a `target_len`-wide row.
-fn pad_row_to_layout(row: &[String], mapping: &[usize], target_len: usize) -> Vec<String> {
- let mut out: Vec<String> = vec![String::new(); target_len];
+fn pad_row_to_layout(row: &[Cell], mapping: &[usize], target_len: usize) -> Vec<Cell> {
+ // Padding cells are pure layout filler and stay geometry-less; the real
+ // cells carry their boxes across into the new column positions.
+ let mut out: Vec<Cell> = vec![Cell::default(); target_len];
for (a_idx, &b_idx) in mapping.iter().enumerate() {
if b_idx < target_len && a_idx < row.len() {
out[b_idx] = row[a_idx].clone();
@@ -2775,14 +2856,19 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option
if interstitial > TABLE_MERGE_MAX_INTERSTITIAL {
return None;
}
- let interstitial_texts: Vec<String> = if interstitial == 0 {
+ // Absorbed label lines become single-cell body rows; each keeps the box of
+ // the line it came from so the merged table's geometry stays complete.
+ let interstitial_texts: Vec<Cell> = if interstitial == 0 {
Vec::new()
} else {
let slice = &lines[a.end..b.start];
if !slice.iter().all(is_absorbable_interstitial) {
return None;
}
- slice.iter().map(|l| l.text.trim().to_string()).collect()
+ slice
+ .iter()
+ .map(|l| Cell::located(l.text.trim().to_string(), l.bbox.clone()))
+ .collect()
};
let (a_header, a_rows) = match &a.block {
Block::Table { header, rows } => (header.clone(), rows.clone()),
@@ -2823,7 +2909,7 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option
let mut rows = a_rows.clone();
// Preserve interstitial label lines as body rows, content in col 0.
for text in &interstitial_texts {
- let mut row = vec![String::new(); b_cols];
+ let mut row = vec![Cell::default(); b_cols];
row[0] = text.clone();
rows.push(row);
}
@@ -2840,6 +2926,9 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option
start: a.start,
end: b.end,
body_start: a.body_start,
+ // The merged run spans both source runs and anything absorbed
+ // between them.
+ bbox: lines_bbox(lines, a.start, b.end),
block: Block::Table { header, rows },
});
}
@@ -2849,7 +2938,7 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option
let mapping = subset_mapping(&a_tracks, &b_tracks)?;
// Compose header rows top-to-bottom: A.header -> A.rows -> B.header.
- let mut header_layers: Vec<Vec<String>> = Vec::new();
+ let mut header_layers: Vec<Vec<Cell>> = Vec::new();
if let Some(h) = &a_header {
header_layers.push(pad_row_to_layout(h, &mapping, b_cols));
}
@@ -2862,26 +2951,36 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option
if header_layers.is_empty() {
return None;
}
- let merged_header: Vec<String> = (0..b_cols)
+ let merged_header: Vec<Cell> = (0..b_cols)
.map(|col| {
let mut parts: Vec<String> = Vec::new();
+ let mut bbox: Option<Rect> = None;
for layer in &header_layers {
- let s = layer.get(col).map(|s| s.as_str()).unwrap_or("");
- if s.is_empty() {
+ let Some(cell) = layer.get(col) else {
continue;
+ };
+ // Union every contributing layer's box, including ones
+ // whose text de-duplicates away, so the merged header cell
+ // still covers the full stacked band it was built from.
+ if let Some(r) = &cell.bbox {
+ Rect::extend(&mut bbox, r);
}
- if parts.last().map(|p| p.as_str()) == Some(s) {
+ let s = cell.as_str();
+ if s.is_empty() || parts.last().map(|p| p.as_str()) == Some(s) {
continue;
}
parts.push(s.to_string());
}
- parts.join(" ")
+ Cell {
+ text: parts.join(" "),
+ bbox,
+ }
})
.collect();
// Preserve interstitial label lines as body rows ahead of B's rows.
- let mut merged_rows: Vec<Vec<String>> = Vec::new();
+ let mut merged_rows: Vec<Vec<Cell>> = Vec::new();
for text in &interstitial_texts {
- let mut row = vec![String::new(); b_cols];
+ let mut row = vec![Cell::default(); b_cols];
row[0] = text.clone();
merged_rows.push(row);
}
@@ -2889,6 +2988,7 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option
return Some(TableRun {
start: a.start,
end: b.end,
+ bbox: lines_bbox(lines, a.start, b.end),
// A was folded into B's header, so the merged table's body
// begins where B's body did.
body_start: b.body_start,
@@ -3230,8 +3330,8 @@ fn filter_by<T>(items: Vec<T>, keep: &[bool]) -> Vec<T> {
/// array" bug class.
struct CellGrid {
/// Rendered cell text (each multi-column span whitespace-split at the
- /// crossed column boundaries).
- text: Vec<Vec<String>>,
+ /// crossed column boundaries), each carrying the ruled cell it occupies.
+ text: Vec<Vec<Cell>>,
/// Per-cell bold flag — starts `true`, cleared when any non-bold span
/// lands in the cell.
is_bold: Vec<Vec<bool>>,
@@ -3258,9 +3358,30 @@ struct CellGrid {
}
impl CellGrid {
- fn new(n_rows: usize, n_cols: usize) -> Self {
+ /// `xs`/`ys` are the column/row boundaries (lengths `n_cols + 1` /
+ /// `n_rows + 1`). Unlike the borderless detectors, a ruled table has real
+ /// drawn boundaries, so every cell's box is known up front — before any
+ /// text lands in it — and the collapse/merge passes below carry those boxes
+ /// with the text they reshape instead of re-deriving them from indices that
+ /// no longer line up.
+ fn new(n_rows: usize, n_cols: usize, xs: &[f32], ys: &[f32]) -> Self {
+ let text = (0..n_rows)
+ .map(|r| {
+ (0..n_cols)
+ .map(|c| Cell {
+ text: String::new(),
+ bbox: Some(Rect {
+ x: xs[c],
+ y: ys[r],
+ width: xs[c + 1] - xs[c],
+ height: ys[r + 1] - ys[r],
+ }),
+ })
+ .collect()
+ })
+ .collect();
CellGrid {
- text: vec![vec![String::new(); n_cols]; n_rows],
+ text,
is_bold: vec![vec![true; n_cols]; n_rows],
has_text: vec![vec![false; n_cols]; n_rows],
repl: vec![vec![String::new(); n_cols]; n_rows],
@@ -3285,10 +3406,10 @@ impl CellGrid {
if txt.is_empty() {
return;
}
- if !self.text[row][col].is_empty() {
- self.text[row][col].push(' ');
+ if !self.text[row][col].text.is_empty() {
+ self.text[row][col].text.push(' ');
}
- self.text[row][col].push_str(txt);
+ self.text[row][col].text.push_str(txt);
self.has_text[row][col] = true;
}
@@ -3430,7 +3551,7 @@ fn assign_cells(
) -> Option<(CellGrid, Vec<usize>)> {
let n_rows = ys.len() - 1;
let n_cols = xs.len() - 1;
- let mut grid = CellGrid::new(n_rows, n_cols);
+ let mut grid = CellGrid::new(n_rows, n_cols, xs, ys);
let mut consumed_indices: Vec<usize> = Vec::new();
const GRID_X_SLACK_PT: f32 = 6.0;
// Straddle census: spans that cross an interior column boundary by a
@@ -3609,14 +3730,14 @@ fn assign_cells(
/// America Revenue") — that chain is what header-keyed consumers (and readers)
/// need. Returns `(header_row, body_start)` or `None`.
fn flatten_header_band(
- cells: &[Vec<String>],
+ cells: &[Vec<Cell>],
cell_has_text: &[Vec<bool>],
cells_repl: &[Vec<String>],
row_alpha_spanner: &[bool],
n_rows: usize,
n_cols: usize,
dbg: bool,
-) -> Option<(Vec<String>, usize)> {
+) -> Option<(Vec<Cell>, usize)> {
let row_fill =
|r: usize| cell_has_text[r].iter().filter(|t| **t).count() as f32 / n_cols as f32;
(0..n_rows)
@@ -3624,7 +3745,7 @@ fn flatten_header_band(
.and_then(|b| {
let nonempty = cell_has_text[b].iter().filter(|t| **t).count();
let alpha_cells = (0..n_cols)
- .filter(|c| cell_has_text[b][*c] && is_alpha_dominant(&cells[b][*c]))
+ .filter(|c| cell_has_text[b][*c] && is_alpha_dominant(cells[b][*c].as_str()))
.count();
// The bottom header layer may carry digit labels (years like
// "2024") but never measurement values. A decimal / % / $ /
@@ -3633,7 +3754,7 @@ fn flatten_header_band(
// missed the 0.9-fill anchor (colspan header covering <90% of
// columns) — folding it would eat a data row (DS5795A_page4).
let has_value_cell =
- (0..n_cols).any(|c| cell_has_text[b][c] && is_value_like(&cells[b][c]));
+ (0..n_cols).any(|c| cell_has_text[b][c] && is_value_like(cells[b][c].as_str()));
let qualifies = (1..=3).contains(&b)
&& b + 1 < n_rows
&& (0..b).any(|r| row_alpha_spanner[r])
@@ -3642,7 +3763,10 @@ fn flatten_header_band(
if !qualifies {
return None;
}
- let header: Vec<String> = (0..n_cols)
+ // Text comes from the colspan-replicated grid, but geometry comes
+ // from the real cell grid: the flattened header cell covers every
+ // band row 0..=b it was folded from.
+ let header: Vec<Cell> = (0..n_cols)
.map(|c| {
let mut parts: Vec<&str> = Vec::new();
for row in cells_repl.iter().take(b + 1) {
@@ -3652,14 +3776,24 @@ fn flatten_header_band(
}
parts.push(s);
}
- parts.join(" ")
+ let mut bbox: Option<Rect> = None;
+ for row in cells.iter().take(b + 1) {
+ if let Some(r) = &row[c].bbox {
+ Rect::extend(&mut bbox, r);
+ }
+ }
+ Cell {
+ text: parts.join(" "),
+ bbox,
+ }
})
.collect();
- if header.iter().all(|h| h.is_empty()) {
+ if header.iter().all(|h| h.text.is_empty()) {
return None;
}
if dbg {
- eprintln!("[ruled] colspan header flatten: rows 0..={b} -> {header:?}");
+ let texts: Vec<&str> = header.iter().map(|h| h.as_str()).collect();
+ eprintln!("[ruled] colspan header flatten: rows 0..={b} -> {texts:?}");
}
Some((header, b + 1))
})
@@ -3675,7 +3809,7 @@ fn flatten_header_band(
/// plus a flag for whether the merge happened.
#[allow(clippy::type_complexity)]
fn merge_stacked_header(
- cells: Vec<Vec<String>>,
+ cells: Vec<Vec<Cell>>,
cell_has_text: Vec<Vec<bool>>,
cell_is_bold: Vec<Vec<bool>>,
n_rows: usize,
@@ -3683,13 +3817,7 @@ fn merge_stacked_header(
kept_row_heights: &[f32],
flattened: bool,
dbg: bool,
-) -> (
- Vec<Vec<String>>,
- Vec<Vec<bool>>,
- Vec<Vec<bool>>,
- usize,
- bool,
-) {
+) -> (Vec<Vec<Cell>>, Vec<Vec<bool>>, Vec<Vec<bool>>, usize, bool) {
let row_fill =
|r: usize, has: &[Vec<bool>]| has[r].iter().filter(|t| **t).count() as f32 / n_cols as f32;
// Anchor on the first fully-dense row (the first real data row).
@@ -3720,16 +3848,22 @@ fn merge_stacked_header(
if dbg {
eprintln!("[ruled] stacked-header merge: top {k} rows → 1");
}
- let mut merged_row = vec![String::new(); n_cols];
+ let mut merged_row = vec![Cell::default(); n_cols];
let mut merged_has = vec![false; n_cols];
let mut merged_bold = vec![true; n_cols];
for r in 0..k {
for c in 0..n_cols {
+ // Every folded band row grows the merged cell's box, including the
+ // text-less ones: the logical header cell spans the whole band the
+ // generator sliced it into, not just the rows that carried glyphs.
+ if let Some(rect) = &cells[r][c].bbox {
+ Rect::extend(&mut merged_row[c].bbox, rect);
+ }
if cell_has_text[r][c] {
- if !merged_row[c].is_empty() {
- merged_row[c].push(' ');
+ if !merged_row[c].text.is_empty() {
+ merged_row[c].text.push(' ');
}
- merged_row[c].push_str(&cells[r][c]);
+ merged_row[c].text.push_str(cells[r][c].as_str());
merged_has[c] = true;
if !cell_is_bold[r][c] {
merged_bold[c] = false;
@@ -3820,7 +3954,7 @@ fn rowspan_mask(
}
fn passes_density_gate(
- cells: &[Vec<String>],
+ cells: &[Vec<Cell>],
cell_has_text: &[Vec<bool>],
cell_is_bold: &[Vec<bool>],
n_rows: usize,
@@ -3853,7 +3987,7 @@ fn passes_density_gate(
let col0_fill = (0..n_rows).filter(|r| cell_has_text[*r][0]).count() as f32 / n_rows as f32;
let col0_max_chars = (0..n_rows)
.filter(|r| cell_has_text[*r][0])
- .map(|r| cells[r][0].len())
+ .map(|r| cells[r][0].text.len())
.max()
.unwrap_or(0);
let col0_spine =
@@ -4364,7 +4498,7 @@ fn build_ruled_table_from(
None if header_qualifies => (Some(cells[0].clone()), 1),
None => (None, 0),
};
- let body_rows: Vec<Vec<String>> = cells[body_start..].to_vec();
+ let body_rows: Vec<Vec<Cell>> = cells[body_start..].to_vec();
if body_rows.is_empty() {
return None;
}
@@ -4378,6 +4512,8 @@ fn build_ruled_table_from(
start,
end,
body_start: start,
+ // A ruled table's region is the grid the generator actually drew.
+ bbox: Some(bbox),
block: Block::Table {
header,
rows: body_rows,
@@ -4719,12 +4855,12 @@ fn run_filled_cells(run: &TableRun) -> usize {
Block::Table { header, rows } => {
let header_filled = header
.as_ref()
- .map(|h| h.iter().filter(|c| !c.trim().is_empty()).count())
+ .map(|h| h.iter().filter(|c| !c.text.trim().is_empty()).count())
.unwrap_or(0);
let body_filled: usize = rows
.iter()
.flat_map(|r| r.iter())
- .filter(|c| !c.trim().is_empty())
+ .filter(|c| !c.text.trim().is_empty())
.count();
header_filled + body_filled
}
@@ -4816,7 +4952,7 @@ pub(super) fn merge_table_runs(
/// blank-label row holding one is a real data row (typically a `Total`);
/// - at least one extended cell reads as a soft wrap rather than a fresh
/// sentence after a completed one.
-fn merge_continuation_rows(rows: &mut Vec<Vec<String>>) {
+fn merge_continuation_rows(rows: &mut Vec<Vec<Cell>>) {
if rows.len() < 2 {
return;
}
@@ -4829,24 +4965,29 @@ fn merge_continuation_rows(rows: &mut Vec<Vec<String>>) {
// two.
let first_col_filled = rows
.iter()
- .filter(|r| r.first().is_some_and(|c| !c.trim().is_empty()))
+ .filter(|r| r.first().is_some_and(|c| !c.text.trim().is_empty()))
.count();
if first_col_filled * 2 < rows.len() {
return;
}
- let mut out: Vec<Vec<String>> = Vec::with_capacity(rows.len());
+ let mut out: Vec<Vec<Cell>> = Vec::with_capacity(rows.len());
for row in rows.drain(..) {
if let Some(prev) = out.last_mut() {
if is_continuation_row(prev, &row) {
for (i, cell) in row.iter().enumerate() {
- let t = cell.trim();
+ let t = cell.text.trim();
if t.is_empty() {
continue;
}
// `prev[i]` is non-empty for every filled column of `row`;
// that is the subset rule `is_continuation_row` enforces.
- prev[i].push(' ');
- prev[i].push_str(t);
+ prev[i].text.push(' ');
+ prev[i].text.push_str(t);
+ // The wrapped line is part of the same logical cell, so it
+ // grows that cell's box down to cover the continuation.
+ if let Some(r) = &cell.bbox {
+ Rect::extend(&mut prev[i].bbox, r);
+ }
}
continue;
}
@@ -4856,22 +4997,22 @@ fn merge_continuation_rows(rows: &mut Vec<Vec<String>>) {
*rows = out;
}
-fn is_continuation_row(prev: &[String], cur: &[String]) -> bool {
+fn is_continuation_row(prev: &[Cell], cur: &[Cell]) -> bool {
if cur.len() != prev.len() || cur.len() < 2 {
return false;
}
// The row label is never repeated on a wrapped line.
- if !cur[0].trim().is_empty() || prev[0].trim().is_empty() {
+ if !cur[0].text.trim().is_empty() || prev[0].text.trim().is_empty() {
return false;
}
let filled: Vec<usize> = (0..cur.len())
- .filter(|&i| !cur[i].trim().is_empty())
+ .filter(|&i| !cur[i].text.trim().is_empty())
.collect();
if filled.is_empty() {
return false;
}
// A continuation extends existing text; it cannot introduce a new column.
- if filled.iter().any(|&i| prev[i].trim().is_empty()) {
+ if filled.iter().any(|&i| prev[i].text.trim().is_empty()) {
return false;
}
// Numbers never soft-wrap. A blank-label row carrying any value-like cell is
@@ -4879,12 +5020,12 @@ fn is_continuation_row(prev: &[String], cur: &[String]) -> bool {
// precisely because it isn't the row's own label. Vetoing on *any* value
// (not all of them) is what separates it from a genuine wrap, since such
// rows pair a short summary word with the figures.
- if filled.iter().any(|&i| is_value_like(cur[i].trim())) {
+ if filled.iter().any(|&i| is_value_like(cur[i].text.trim())) {
return false;
}
filled
.iter()
- .any(|&i| cell_continues(prev[i].trim_end(), cur[i].trim_start()))
+ .any(|&i| cell_continues(prev[i].text.trim_end(), cur[i].text.trim_start()))
}
/// Whether `cur` reads as the tail of `prev` rather than a new statement. The
@@ -5007,9 +5148,9 @@ mod tests {
assert_eq!(piece_texts(&span), ["Added Relative"]);
}
- fn rows(v: &[&[&str]]) -> Vec<Vec<String>> {
+ fn rows(v: &[&[&str]]) -> Vec<Vec<Cell>> {
v.iter()
- .map(|r| r.iter().map(|s| s.to_string()).collect())
+ .map(|r| r.iter().map(|s| Cell::from(*s)).collect())
.collect()
}
@@ -5580,6 +5721,88 @@ mod tests {
}
}
+ #[test]
+ fn ruled_table_cells_carry_their_grid_rect() {
+ // Same 2×2 grid as above: column boundaries at x=50/150/250, row
+ // boundaries at y=100/140/180. A ruled table's cell geometry is the
+ // drawn cell itself, so each cell's box must be exactly one grid
+ // rectangle — independent of where the glyphs sit inside it.
+ let mut graphics = Vec::new();
+ for y in [100.0_f32, 140.0, 180.0] {
+ graphics.push(stroke(50.0, y, 250.0, y, 0.5));
+ }
+ for x in [50.0_f32, 150.0, 250.0] {
+ graphics.push(stroke(x, 100.0, x, 180.0, 0.5));
+ }
+ let lines = vec![
+ line("a", 90.0, 115.0, 10.0, 10.0),
+ line("b", 190.0, 115.0, 10.0, 10.0),
+ line("c", 90.0, 155.0, 10.0, 10.0),
+ line("d", 190.0, 155.0, 10.0, 10.0),
+ ];
+
+ let runs = detect_ruled_tables(&lines, &extract_rule_segments(&graphics), 612.0, 792.0);
+ let Block::Table { rows, .. } = &runs[0].block else {
+ panic!("expected Block::Table");
+ };
+ let rect = |r: usize, c: usize| {
+ let b = rows[r][c].bbox.clone().expect("ruled cell must be located");
+ (b.x, b.y, b.width, b.height)
+ };
+ assert_eq!(rows[0][0].text, "a");
+ assert_eq!(rect(0, 0), (50.0, 100.0, 100.0, 40.0));
+ assert_eq!(rect(0, 1), (150.0, 100.0, 100.0, 40.0));
+ assert_eq!(rect(1, 0), (50.0, 140.0, 100.0, 40.0));
+ assert_eq!(rect(1, 1), (150.0, 140.0, 100.0, 40.0));
+ }
+
+ #[test]
+ fn borderless_table_cells_carry_span_extents() {
+ // A borderless table has no drawn boundaries, so a cell covers the ink
+ // of its own spans on that row — not a full column track. Each cell's
+ // box must therefore start at its span's x and sit in its line's band.
+ let lines = vec![
+ line_with_spans(
+ &[("Name", 50.0), ("Qty", 150.0), ("Cost", 250.0)],
+ 100.0,
+ 10.0,
+ ),
+ line_with_spans(
+ &[("Bolt", 50.0), ("12", 150.0), ("3.50", 250.0)],
+ 115.0,
+ 10.0,
+ ),
+ line_with_spans(
+ &[("Nut", 50.0), ("40", 150.0), ("1.25", 250.0)],
+ 130.0,
+ 10.0,
+ ),
+ ];
+ let runs = detect_tables(&lines);
+ assert_eq!(runs.len(), 1, "expected 1 borderless table, got {runs:?}");
+ let Block::Table { rows, .. } = &runs[0].block else {
+ panic!("expected Block::Table");
+ };
+ // Every detected cell knows where it came from.
+ for row in rows {
+ for cell in row {
+ assert!(cell.bbox.is_some(), "cell {:?} lost its box", cell.text);
+ }
+ }
+ let first = rows[0][0].bbox.clone().unwrap();
+ assert_eq!(first.x, 50.0, "cell starts at its span's x");
+ // The row's own band, not the whole table's.
+ let row0_y = rows[0][0].bbox.clone().unwrap().y;
+ let row1_y = rows[1][0].bbox.clone().unwrap().y;
+ assert!(
+ row1_y > row0_y,
+ "rows must occupy distinct bands ({row0_y} then {row1_y})"
+ );
+ // Columns stay separated horizontally.
+ assert_eq!(rows[0][1].bbox.clone().unwrap().x, 150.0);
+ assert_eq!(rows[0][2].bbox.clone().unwrap().x, 250.0);
+ }
+
#[test]
fn ruled_table_rect_borders_detected() {
// Same 2×2 table but drawn as 4 individual cell rects (each cell is a
@@ -5670,6 +5893,7 @@ mod tests {
start: 5,
end: 10,
body_start: 5,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![vec!["ruled".into()]],
@@ -5679,6 +5903,7 @@ mod tests {
start: 6,
end: 11,
body_start: 6,
+ bbox: None,
block: Block::GridFallback {
lines: vec!["bl".into()],
},
@@ -5730,6 +5955,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: Some(vec!["A".into(), "B".into(), "C".into()]),
rows: vec![vec!["1".into(), "2".into(), "3".into()]],
@@ -5739,6 +5965,7 @@ mod tests {
start: 2,
end: 5,
body_start: 2,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5778,6 +6005,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5790,6 +6018,7 @@ mod tests {
start: 2,
end: 5,
body_start: 2,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5830,6 +6059,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: Some(vec!["A".into(), "B".into(), "C".into()]),
rows: vec![vec!["1".into(), "2".into(), "3".into()]],
@@ -5839,6 +6069,7 @@ mod tests {
start: 2,
end: 4,
body_start: 2,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5863,6 +6094,7 @@ mod tests {
start: 0,
end: 10,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: None,
rows: (0..10)
@@ -5874,6 +6106,7 @@ mod tests {
start: 10,
end: 13,
body_start: 10,
+ bbox: None,
block: Block::Table {
header: None,
rows: (0..3)
@@ -5919,6 +6152,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5931,6 +6165,7 @@ mod tests {
start: 2,
end: 4,
body_start: 2,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5954,6 +6189,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -5966,6 +6202,7 @@ mod tests {
start: 2,
end: 3,
body_start: 2,
+ bbox: None,
block: Block::GridFallback {
lines: vec!["fallback".into()],
},
@@ -5998,6 +6235,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: Some(vec!["A".into(), "B".into(), "C".into()]),
rows: vec![vec!["1".into(), "2".into(), "3".into()]],
@@ -6007,6 +6245,7 @@ mod tests {
start: 3,
end: 5,
body_start: 3,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -6036,6 +6275,7 @@ mod tests {
start: 0,
end: 2,
body_start: 0,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
@@ -6048,6 +6288,7 @@ mod tests {
start: 3,
end: 6,
body_start: 3,
+ bbox: None,
block: Block::Table {
header: None,
rows: vec![
diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rs
index 9f6874b..7bf298d 100644
--- a/crates/liteparse/src/markdown_layout/test_helpers.rs
+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs
@@ -49,6 +49,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
}
}
@@ -207,6 +208,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &st
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
}
}
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index 554de1a..5159cda 100644
--- a/crates/liteparse/src/output/json.rs
+++ b/crates/liteparse/src/output/json.rs
@@ -62,6 +62,8 @@ pub(crate) struct JsonPage {
pub form_fields: Option<Vec<FormField>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub structure_tree: Option<StructureTree>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blocks: Option<Vec<crate::layout::LayoutBlock>>,
}
#[derive(Debug, Serialize)]
@@ -160,6 +162,7 @@ pub(crate) fn build_json(pages: &[ParsedPage], extract_text_metadata: bool) -> P
annotations: page.annotations.clone(),
form_fields: page.form_fields.clone(),
structure_tree: page.structure_tree.clone(),
+ blocks: page.blocks.clone(),
})
.collect(),
}
@@ -252,6 +255,7 @@ mod tests {
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
}
}
diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rs
index 79899d0..6116b3a 100644
--- a/crates/liteparse/src/output/markdown.rs
+++ b/crates/liteparse/src/output/markdown.rs
@@ -1,7 +1,7 @@
use crate::config::ImageMode;
use crate::markdown_layout::{
- build_heading_map, classify_page_with_filters, compute_body_size, compute_header_footer_set,
- detect_single_page_chrome, render_blocks,
+ PositionedBlock, build_heading_map, classify_page_with_filters, compute_body_size,
+ compute_header_footer_set, detect_single_page_chrome, render_blocks, splice_soft_hyphens,
};
use crate::types::{OutlineTarget, ParsedPage};
@@ -42,6 +42,27 @@ pub fn format_markdown_pages(
image_mode: ImageMode,
keep_headers_footers: bool,
) -> Vec<String> {
+ let classified = classify_document(pages, outline, image_mode, keep_headers_footers);
+ render_classified(pages, &classified)
+}
+
+/// Classify every page into its final block sequence — the same decomposition
+/// [`format_markdown_pages`] renders, after chrome suppression, rule dedup, and
+/// soft-hyphen splicing.
+///
+/// A page yields `None` when it has no projected lines (blank, or fully-OCR
+/// without font metadata): there is no structural decomposition to report, and
+/// rendering falls back to fenced projection text.
+///
+/// Split out from rendering so callers that want the blocks *and* the markdown
+/// pay for classification once, and so blocks are available in JSON and text
+/// output modes, which never render markdown at all.
+pub fn classify_document(
+ pages: &[ParsedPage],
+ outline: &[OutlineTarget],
+ image_mode: ImageMode,
+ keep_headers_footers: bool,
+) -> Vec<Option<Vec<PositionedBlock>>> {
if pages.is_empty() {
return Vec::new();
}
@@ -58,15 +79,7 @@ pub fn format_markdown_pages(
.iter()
.map(|page| {
if page.projected_lines.is_empty() {
- // No structural metadata for this page — fall back to the
- // projection text inside a fence so nothing is dropped.
- let mut out = String::from("```text\n");
- out.push_str(&page.text);
- if !page.text.ends_with('\n') {
- out.push('\n');
- }
- out.push_str("```");
- return out;
+ return None;
}
// Filter outline entries to this page so the classifier's y/title
@@ -95,16 +108,42 @@ pub fn format_markdown_pages(
// of bare `---` separators.
let has_content = blocks.iter().any(|b| {
!matches!(
- b,
+ b.block,
crate::markdown_layout::Block::HorizontalRule
| crate::markdown_layout::Block::Figure { .. }
)
});
if !has_content {
- blocks.retain(|b| !matches!(b, crate::markdown_layout::Block::HorizontalRule));
+ blocks
+ .retain(|b| !matches!(b.block, crate::markdown_layout::Block::HorizontalRule));
}
dedupe_rules(&mut blocks);
- render_blocks(&blocks)
+ Some(splice_soft_hyphens(blocks))
+ })
+ .collect()
+}
+
+/// Render pre-classified pages to one markdown string per page. Pages that
+/// classified to `None` fall back to their projection text inside a fence so
+/// nothing is silently dropped.
+pub fn render_classified(
+ pages: &[ParsedPage],
+ classified: &[Option<Vec<PositionedBlock>>],
+) -> Vec<String> {
+ pages
+ .iter()
+ .zip(classified)
+ .map(|(page, blocks)| match blocks {
+ Some(blocks) => render_blocks(blocks),
+ None => {
+ let mut out = String::from("```text\n");
+ out.push_str(&page.text);
+ if !page.text.ends_with('\n') {
+ out.push('\n');
+ }
+ out.push_str("```");
+ out
+ }
})
.collect()
}
@@ -115,15 +154,15 @@ pub fn format_markdown_pages(
/// two sources — vector-graphics detection and decorative divider text — and
/// doubling up reads as sloppy output to a human, while carrying no extra
/// structure for an LLM.
-fn dedupe_rules(blocks: &mut Vec<crate::markdown_layout::Block>) {
+fn dedupe_rules(blocks: &mut Vec<crate::markdown_layout::PositionedBlock>) {
use crate::markdown_layout::Block::HorizontalRule;
- while matches!(blocks.first(), Some(HorizontalRule)) {
+ while matches!(blocks.first().map(|b| &b.block), Some(HorizontalRule)) {
blocks.remove(0);
}
- while matches!(blocks.last(), Some(HorizontalRule)) {
+ while matches!(blocks.last().map(|b| &b.block), Some(HorizontalRule)) {
blocks.pop();
}
- blocks.dedup_by(|a, b| matches!((a, b), (HorizontalRule, HorizontalRule)));
+ blocks.dedup_by(|a, b| matches!((&a.block, &b.block), (HorizontalRule, HorizontalRule)));
}
#[cfg(test)]
@@ -178,6 +217,7 @@ mod tests {
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
}
}
@@ -194,18 +234,21 @@ mod tests {
bold: false,
italic: false,
};
- let mut blocks = vec![
+ let mut blocks: Vec<crate::markdown_layout::PositionedBlock> = [
HorizontalRule,
p("a"),
HorizontalRule,
HorizontalRule,
p("b"),
HorizontalRule,
- ];
+ ]
+ .into_iter()
+ .map(crate::markdown_layout::PositionedBlock::unlocated)
+ .collect();
dedupe_rules(&mut blocks);
let kinds: Vec<bool> = blocks
.iter()
- .map(|b| matches!(b, Block::HorizontalRule))
+ .map(|b| matches!(b.block, Block::HorizontalRule))
.collect();
// Leading + trailing rules gone; the doubled interior run collapsed to one.
assert_eq!(kinds, vec![false, true, false]);
@@ -232,6 +275,7 @@ mod tests {
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
};
let out = format_markdown(&[p], &[], ImageMode::Placeholder);
assert!(out.contains("```text"));
diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rs
index 7e98d69..548650b 100644
--- a/crates/liteparse/src/output/text.rs
+++ b/crates/liteparse/src/output/text.rs
@@ -33,6 +33,7 @@ mod tests {
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
}
}
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index ee2b869..d636d06 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -231,6 +231,54 @@ pub struct LiteParse {
glyph_resolver: Option<std::sync::Arc<dyn crate::GlyphResolver>>,
}
+/// Run block classification once and fan the result out to everything that
+/// needs it: the rendered per-page markdown (when Markdown is the output
+/// format) and each page's `blocks` (when `extract_blocks` is on).
+///
+/// Classification is the expensive part of the markdown pipeline, so the two
+/// consumers share a single pass rather than each triggering their own. Returns
+/// the joined document markdown when that is the output format.
+fn apply_layout(
+ config: &crate::config::LiteParseConfig,
+ parsed_pages: &mut [ParsedPage],
+ outline: &[OutlineTarget],
+) -> Option<String> {
+ let wants_markdown = config.output_format == crate::config::OutputFormat::Markdown;
+ if !wants_markdown && !config.extract_blocks {
+ return None;
+ }
+ let classified = markdown::classify_document(
+ parsed_pages,
+ outline,
+ config.image_mode,
+ config.keep_headers_footers,
+ );
+ if config.extract_blocks {
+ for (page, blocks) in parsed_pages.iter_mut().zip(&classified) {
+ // A page with no structural decomposition reports an empty list,
+ // not `None` — extraction *was* enabled, there was just nothing to
+ // decompose.
+ page.blocks = Some(
+ blocks
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(crate::layout::LayoutBlock::from)
+ .collect(),
+ );
+ }
+ }
+ if !wants_markdown {
+ return None;
+ }
+ let page_md = markdown::render_classified(parsed_pages, &classified);
+ let md = page_md.join("\n\n-----\n\n");
+ for (page, page_md) in parsed_pages.iter_mut().zip(page_md) {
+ page.markdown = page_md;
+ }
+ Some(md)
+}
+
impl LiteParse {
pub fn new(config: LiteParseConfig) -> Self {
Self {
@@ -790,17 +838,8 @@ impl LiteParse {
t2.duration_since(t_ocr).as_secs_f64() * 1000.0
));
- let mut full_text = if self.config.output_format == crate::config::OutputFormat::Markdown {
- let page_md = markdown::format_markdown_pages(
- &parsed_pages,
- &outline,
- self.config.image_mode,
- self.config.keep_headers_footers,
- );
- let md = page_md.join("\n\n-----\n\n");
- for (page, md) in parsed_pages.iter_mut().zip(page_md) {
- page.markdown = md;
- }
+ let laid_out = apply_layout(&self.config, &mut parsed_pages, &outline);
+ let mut full_text = if let Some(md) = laid_out {
let t3 = web_time::Instant::now();
log(&format!(
"[liteparse] markdown: {:.1}ms",
@@ -857,17 +896,7 @@ impl LiteParse {
let total_pages = pages.len().min(u32::MAX as usize) as u32;
let mut parsed_pages = projection::project_pages_to_grid(pages);
- let full_text = if self.config.output_format == crate::config::OutputFormat::Markdown {
- let page_md = markdown::format_markdown_pages(
- &parsed_pages,
- &outline,
- self.config.image_mode,
- self.config.keep_headers_footers,
- );
- let md = page_md.join("\n\n-----\n\n");
- for (page, md) in parsed_pages.iter_mut().zip(page_md) {
- page.markdown = md;
- }
+ let full_text = if let Some(md) = apply_layout(&self.config, &mut parsed_pages, &outline) {
md
} else {
parsed_pages
@@ -1254,6 +1283,7 @@ mod tests {
annotations: None,
form_fields: None,
structure_tree: None,
+ blocks: None,
}];
let mut full_text = pages[0].markdown.clone();
let images = vec![
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 2690dca..f0ed986 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -2919,6 +2919,9 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
annotations: page.annotations,
form_fields: page.form_fields,
structure_tree: page.structure_tree,
+ // Filled in after classification, which needs the finished
+ // page (and whole-document signals) to run.
+ blocks: None,
}
})
.collect()
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 26ee753..07b6e82 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -471,6 +471,12 @@ pub struct ParsedPage {
/// Tagged-PDF logical structure when `extract_structure_tree` is true.
#[serde(skip_serializing_if = "Option::is_none")]
pub structure_tree: Option<StructureTree>,
+ /// Classified layout blocks when `extract_blocks` is true, in reading
+ /// order. `None` means extraction was disabled; `Some([])` means enabled
+ /// but the page had no structural decomposition (blank, or fully-OCR
+ /// without the font metadata the classifier needs).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub blocks: Option<Vec<crate::layout::LayoutBlock>>,
}
/// One embedded raster image on a page. `id` is a stable, page-scoped slug
@@ -528,6 +534,35 @@ pub struct Rect {
pub height: f32,
}
+impl Rect {
+ /// Smallest rect containing both inputs. Used by the block classifier to
+ /// grow a block's bbox as source lines are appended to it (paragraph
+ /// accumulation, wrapped headings, list-item continuations) and to merge
+ /// blocks that are spliced together after construction.
+ pub fn union(&self, other: &Rect) -> Rect {
+ let x = self.x.min(other.x);
+ let y = self.y.min(other.y);
+ let right = (self.x + self.width).max(other.x + other.width);
+ let bottom = (self.y + self.height).max(other.y + other.height);
+ Rect {
+ x,
+ y,
+ width: right - x,
+ height: bottom - y,
+ }
+ }
+
+ /// Fold `rect` into an optional accumulator. `None` adopts the rect; `Some`
+ /// unions. Blocks whose sources carry no geometry stay `None` rather than
+ /// reporting a bogus rect anchored at the origin.
+ pub fn extend(acc: &mut Option<Rect>, rect: &Rect) {
+ *acc = Some(match acc {
+ Some(existing) => existing.union(rect),
+ None => rect.clone(),
+ });
+ }
+}
+
/// Page-scoped vector path output. Coordinates use the same top-left,
/// 72-DPI viewport space as text items.
#[derive(Debug, Clone, Default, Serialize)]
diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rs
index 8181690..a2444fe 100644
--- a/crates/liteparse/tests/integration_test.rs
+++ b/crates/liteparse/tests/integration_test.rs
@@ -329,6 +329,66 @@ async fn test_doc_meta_absent_unless_requested() {
assert!(parsed.doc_meta.is_none());
}
+#[tokio::test]
+#[serial]
+async fn test_blocks_absent_unless_requested() {
+ let lit = LiteParse::new(LiteParseConfig {
+ ocr_enabled: false,
+ ..LiteParseConfig::default()
+ });
+ let parsed = lit
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .expect("Should be able to parse");
+ assert!(parsed.pages.iter().all(|p| p.blocks.is_none()));
+}
+
+/// Blocks are a parallel view of the same classification the Markdown renderer
+/// uses, so turning them on must not perturb the rendered Markdown, and every
+/// block must report where it came from.
+#[tokio::test]
+#[serial]
+async fn test_extract_blocks_carries_geometry_without_changing_markdown() {
+ let base = LiteParseConfig {
+ ocr_enabled: false,
+ ..LiteParseConfig::default()
+ };
+ let without = LiteParse::new(base.clone())
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .expect("Should be able to parse");
+ let with = LiteParse::new(LiteParseConfig {
+ extract_blocks: true,
+ ..base
+ })
+ .parse("../../integration_tests_data/sample.pdf")
+ .await
+ .expect("Should be able to parse");
+
+ assert_eq!(without.text, with.text, "markdown must be unchanged");
+
+ let blocks = with.pages[0]
+ .blocks
+ .as_ref()
+ .expect("blocks should be populated");
+ assert!(!blocks.is_empty());
+ assert!(
+ blocks.iter().all(|b| b.bbox.is_some()),
+ "every block on a text page should be located"
+ );
+ // Boxes describe real page regions, not placeholders.
+ assert!(blocks.iter().all(|b| {
+ let r = b.bbox.as_ref().unwrap();
+ r.width > 0.0 && r.height > 0.0
+ }));
+ // Blocks come back in reading order (top-to-bottom on a single-column page).
+ let ys: Vec<f32> = blocks.iter().map(|b| b.bbox.as_ref().unwrap().y).collect();
+ assert!(
+ ys.windows(2).all(|w| w[0] <= w[1]),
+ "blocks should be in reading order, got {ys:?}"
+ );
+}
+
#[tokio::test]
#[serial]
async fn test_parse_bytes_pdf_integration() {
diff --git a/docs/src/content/docs/liteparse/cli-reference.md b/docs/src/content/docs/liteparse/cli-reference.md
index d682275..6dbeca4 100644
--- a/docs/src/content/docs/liteparse/cli-reference.md
+++ b/docs/src/content/docs/liteparse/cli-reference.md
@@ -55,6 +55,7 @@ By default, JSON output contains only text, geometry, and page metadata. Each op
| `--extract-annotations` | `pages[].annotations` | PDF annotations: subtype, contents, timestamps, rects, link URIs |
| `--extract-form-fields` | `pages[].form_fields` | AcroForm widgets: type, name, value, flags, options, rect |
| `--extract-structure-tree` | `pages[].structure_tree` | Tagged-PDF logical structure tree (`{ roots }`), including per-element attributes |
+| `--extract-blocks` | `pages[].blocks` | Classified layout blocks in reading order (headings, paragraphs, list items, tables with per-cell boxes, code, rules, figures), each with a bounding box |
| `--extract-content-bounds` | `pages[].content_bounds` | Bounding box of actual content on the page, as a `Rect` |
| `--extract-xfa-packets` | `xfa_packets[]` (document level) | Raw XFA packets from XFA-based forms |
| `--extract-text-metadata` | extra keys on each `text_items[]` entry | Rich per-item typography: `font_height`, `font_ascent`, `font_descent`, `font_weight`, `text_width`, `font_is_buggy`, `mcid`, `fill_color`, `stroke_color`, plus `rotation` |
@@ -139,7 +140,7 @@ lit batch-parse [options] <input-dir> <output-dir>
| `--password <password>` | Password for encrypted/protected documents (applied to all files) | — |
| `-q, --quiet` | Suppress progress output | — |
-`batch-parse` accepts the same [extraction options](#extraction-options) as `lit parse`: `--extract-images`, `--extract-vector-graphics`, `--extract-annotations`, `--extract-form-fields`, `--extract-structure-tree`, `--extract-content-bounds`, `--extract-xfa-packets`, `--extract-text-metadata`, and `--complexity`.
+`batch-parse` accepts the same [extraction options](#extraction-options) as `lit parse`: `--extract-images`, `--extract-vector-graphics`, `--extract-annotations`, `--extract-form-fields`, `--extract-structure-tree`, `--extract-blocks`, `--extract-content-bounds`, `--extract-xfa-packets`, `--extract-text-metadata`, and `--complexity`.
It does **not** accept `--target-pages`, `--preserve-small-text`, `--image-mode`, `--image-output-dir`, `--no-links`, or `--keep-headers-footers`. Use `lit parse` per file when you need those.
diff --git a/docs/src/content/docs/liteparse/guides/extraction.mdx b/docs/src/content/docs/liteparse/guides/extraction.mdx
index ae4f7a0..cb2e97e 100644
--- a/docs/src/content/docs/liteparse/guides/extraction.mdx
+++ b/docs/src/content/docs/liteparse/guides/extraction.mdx
@@ -1,6 +1,6 @@
---
title: Extraction Options
-description: Opt-in flags that add images, vector graphics, annotations, form fields, structure trees, and typography metadata to LiteParse output.
+description: Opt-in flags that add images, vector graphics, annotations, form fields, structure trees, layout blocks, and typography metadata to LiteParse output.
sidebar:
order: 3
---
@@ -20,6 +20,7 @@ This keeps the default output shape small, stable, and cheap to produce. It also
| `extract_annotations` / `--extract-annotations` | `extractAnnotations` | `pages[].annotations` |
| `extract_form_fields` / `--extract-form-fields` | `extractFormFields` | `pages[].form_fields` |
| `extract_structure_tree` / `--extract-structure-tree` | `extractStructureTree` | `pages[].structure_tree` |
+| `extract_blocks` / `--extract-blocks` | `extractBlocks` | `pages[].blocks` |
| `extract_content_bounds` / `--extract-content-bounds` | `extractContentBounds` | `pages[].content_bounds` |
| `extract_xfa_packets` / `--extract-xfa-packets` | `extractXfaPackets` | `xfa_packets[]` |
| `extract_text_metadata` / `--extract-text-metadata` | `extractTextMetadata` | extra keys on `text_items[]` |
@@ -255,6 +256,114 @@ Related: `render_form_fields` draws filled-in field appearances into rendered ra
`marked_content_ids` join back to the `mcid` field on text items (available with `extract_text_metadata`), letting you map reconstructed text to its authored role.
+## Layout blocks
+
+`extract_blocks` returns the page decomposed into blocks — headings, paragraphs, list items, tables, code, rules, and figures — each with the region of the page it came from.
+
+This is the same classification the Markdown renderer runs on; the flag exposes it as data instead of only as rendered text. Blocks come back in reading order, so the Nth block is the Nth block of that page's Markdown. Enabling it never changes the Markdown output, and blocks are available in every output format, including `--format json` and `--format text`.
+
+```bash
+lit parse document.pdf --format json --extract-blocks
+```
+
+Only the fields that apply to a block's `kind` are present:
+
+```json
+{
+ "kind": "heading",
+ "text": "Quarterly Report",
+ "level": 1,
+ "bbox": { "x": 72.0, "y": 114.88, "width": 284.0, "height": 21.0 }
+}
+```
+
+| Field | Kinds | Meaning |
+|-------|-------|---------|
+| `kind` | all | `heading`, `paragraph`, `list_item`, `code`, `table`, `grid_fallback`, `rule`, `figure` |
+| `bbox` | all | Region occupied, in the same coordinate space as `text_items` |
+| `text` | `heading`, `paragraph`, `list_item` | Rendered text |
+| `level` | `heading`, `list_item` | Heading level 1–6, or list nesting depth |
+| `bold`, `italic` | `paragraph`, `list_item` | Set when the whole block is emphasized |
+| `ordered`, `marker` | `list_item` | Whether the list is ordered, and the marker as it appeared (`138.`, `iii)`, `•`) |
+| `lines`, `lang` | `code`, `grid_fallback` | Verbatim source lines, and a best-effort language hint |
+| `header`, `rows` | `table` | Cells, each with its own `text` and `bbox` |
+| `id`, `format` | `figure` | Matches the `img_{id}.{format}` target in Markdown output |
+
+`bbox` is the union of every source line that fed the block, so a wrapped heading or multi-line paragraph reports the whole band it occupies — not just its first line.
+
+### Tables
+
+Table cells are objects, not bare strings: each carries its own `bbox`, so a cell maps back to the region it was read from.
+
+```json
+{
+ "kind": "table",
+ "bbox": { "x": 67.9, "y": 511.1, "width": 458.4, "height": 111.0 },
+ "header": [
+ { "text": "Title of each class", "bbox": { "x": 132.7, "y": 511.1, "width": 64.0, "height": 8.0 } },
+ { "text": "Trading symbol(s)", "bbox": { "x": 288.7, "y": 511.1, "width": 35.0, "height": 8.0 } }
+ ],
+ "rows": [
+ [
+ { "text": "Common Stock", "bbox": { "x": 67.9, "y": 522.4, "width": 193.0, "height": 9.5 } },
+ { "text": "AAPL", "bbox": { "x": 293.8, "y": 522.4, "width": 24.0, "height": 9.5 } }
+ ]
+ ]
+}
+```
+
+For a ruled table, a cell's box is the drawn grid cell. For a borderless one, it is the extent of the spans the cell was built from. Cells that exist only to square off a ragged grid have no `bbox` — there is no ink behind them.
+
+Getting a table into a dataframe is then a two-line transform:
+
+<Tabs>
+<TabItem label="Python" value="python">
+
+```python
+import pandas as pd
+from liteparse import LiteParse
+
+result = LiteParse(extract_blocks=True).parse("10-k.pdf")
+
+for page in result.pages:
+ for block in page.blocks or []:
+ if block.kind == "table":
+ df = pd.DataFrame(
+ [[c.text for c in row] for row in block.rows],
+ columns=[c.text for c in block.header or []],
+ )
+```
+
+</TabItem>
+<TabItem label="TypeScript" value="typescript">
+
+```typescript
+import { LiteParse } from "@llamaindex/liteparse";
+
+const { pages } = await new LiteParse({ extractBlocks: true }).parse("10-k.pdf");
+
+for (const page of pages) {
+ for (const block of page.blocks ?? []) {
+ if (block.kind !== "table") continue;
+ const grid = [block.header ?? [], ...block.rows].map((r) => r.map((c) => c.text));
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
+### Blocks vs. the structure tree
+
+The two look similar and are not interchangeable:
+
+- **`extract_structure_tree`** is the *authored* structure, read from the PDF's tags. It is authoritative where it exists — and absent entirely from untagged PDFs, which is most of them.
+- **`extract_blocks`** is *inferred* structure, derived from font size, weight, indentation, and spacing. It is always available, and it is what Markdown output is built from.
+
+Reach for the structure tree when the file is tagged and you want ground truth; reach for blocks when you need structure from an arbitrary PDF, or you want the coordinates behind a chunk of Markdown.
+
+> Because blocks expose the classifier directly, they also expose its mistakes — a title promoted to the wrong level, or a caption read as a paragraph. Those judgements were always there in the Markdown; blocks just make them legible.
+
## Text metadata
`extract_text_metadata` enriches every entry in `text_items[]` with typography detail. Without it, a text item carries only `text`, `x`, `y`, `width`, `height`, `font_name`, and `font_size`.
@@ -363,5 +472,6 @@ parser = LiteParse(crop_box=(0.1, 0.0, 0.05, 0.0))
- [Document complexity](/liteparse/guides/complexity/): Route documents before you parse them.
- [Markdown output](/liteparse/guides/markdown/): Images, links, and header/footer handling in markdown.
+- [Visual citations](/liteparse/guides/visual-citations/): Turn block and text-item boxes into highlights on the rendered page.
- [CLI reference](/liteparse/cli-reference/): Every flag, per command.
- [API reference](/liteparse/api/): Full `LiteParseConfig` field list.
diff --git a/docs/src/content/docs/liteparse/guides/visual-citations.mdx b/docs/src/content/docs/liteparse/guides/visual-citations.mdx
index a07d69e..1abf2f4 100644
--- a/docs/src/content/docs/liteparse/guides/visual-citations.mdx
+++ b/docs/src/content/docs/liteparse/guides/visual-citations.mdx
@@ -197,3 +197,4 @@ From there, you (or an agent) can process the resulting JSON and screenshots as
- Use the same `dpi` value for both `parse()` and `screenshot()`. The default is `150` for both.
- Page `width` and `height` in the JSON are in PDF points, matching the coordinate space. Use these if you need to normalize coordinates to percentages.
- For multi-word phrase search, iterate `textItems` and check adjacent items — a phrase may span multiple text items.
+- To highlight a whole heading, paragraph, or table rather than individual words, parse with [`extract_blocks`](/liteparse/guides/extraction/#layout-blocks). Each block carries one `bbox` covering every line that fed it, so you can outline a region without stitching text items together yourself — and table cells carry their own boxes for cell-level citations.
diff --git a/packages/node/native.d.ts b/packages/node/native.d.ts
index c7eb8d2..3a6f4dd 100644
--- a/packages/node/native.d.ts
+++ b/packages/node/native.d.ts
@@ -68,6 +68,13 @@ export interface JsLiteParseConfig {
keepHeadersFooters?: boolean
/** Extract all PDF annotations as page-scoped structured data. */
extractAnnotations?: boolean
+ /**
+ * Emit each page's classified layout blocks (headings, paragraphs, list
+ * items, tables with per-cell boxes, code, rules, figures) with bounding
+ * boxes as `ParsedPage.blocks`. Default false. Independent of
+ * `outputFormat`; enabling it never changes the rendered markdown.
+ */
+ extractBlocks?: boolean
/** Extract AcroForm widget fields and values. */
extractFormFields?: boolean
/** Extract the tagged-PDF logical structure tree. */
@@ -247,6 +254,11 @@ export interface JsParsedPage {
complexity?: JsPageComplexityStats
vectorGraphics?: JsVectorGraphics
annotations?: Array<JsDocumentAnnotation>
+ /**
+ * Classified layout blocks in reading order; present only when
+ * `extractBlocks` is enabled.
+ */
+ blocks?: Array<JsLayoutBlock>
formFields?: Array<JsFormField>
structureTree?: JsStructureTree
}
@@ -334,6 +346,66 @@ export interface JsFormField {
options: Array<string>
selectedOptions: Array<string>
}
+/**
+ * One table cell: its rendered text and the region it occupied. `bbox` is
+ * absent for cells with no ink behind them (padding for a ragged grid, or a
+ * merged run split at an estimated boundary).
+ */
+export interface JsLayoutCell {
+ text: string
+ bbox?: JsAnnotationRect
+}
+/**
+ * A classified block plus where it sits on the page. Flat by design — `kind`
+ * discriminates the block and every field that doesn't apply to that kind is
+ * absent.
+ */
+export interface JsLayoutBlock {
+ /**
+ * One of `heading`, `paragraph`, `list_item`, `code`, `table`,
+ * `grid_fallback`, `rule`, `figure`.
+ */
+ kind: string
+ /**
+ * Rendered text for the text-bearing kinds (`heading`, `paragraph`,
+ * `list_item`). Table text lives in `header`/`rows`; code and grid text in
+ * `lines`.
+ */
+ text?: string
+ /** Heading level (1–6), or list nesting depth for `list_item`. */
+ level?: number
+ /**
+ * Whether the block's text is uniformly bold / italic. `paragraph` and
+ * `list_item` only; false otherwise.
+ */
+ bold: boolean
+ italic: boolean
+ /**
+ * `list_item`: whether the list is ordered, and the original marker as it
+ * appeared on the page (`138.`, `iii)`, `•`).
+ */
+ ordered?: boolean
+ marker?: string
+ /** Verbatim source lines for `code` and `grid_fallback`. */
+ lines?: Array<string>
+ /** Best-effort language hint for `code`. */
+ lang?: string
+ /** `table`: the header row, when one was detected. */
+ header?: Array<JsLayoutCell>
+ /** `table`: the body rows. */
+ rows?: Array<Array<JsLayoutCell>>
+ /**
+ * `figure`: the image's page-scoped id and encoded format, matching the
+ * `img_{id}.{format}` target the markdown renderer emits.
+ */
+ id?: string
+ format?: string
+ /**
+ * Region of the page this block occupies, in the same viewport space as
+ * `textItems`. Absent when the block has no page geometry behind it.
+ */
+ bbox?: JsAnnotationRect
+}
export interface JsParseResult {
/** Total source-document pages before target/max-page filtering. */
totalPages: number
@@ -356,10 +428,6 @@ export interface JsParseResult {
/** Raw XFA packets; present only when `extractXfaPackets` is enabled. */
xfaPackets?: Array<JsXfaPacket>
}
-export interface JsPageError {
- pageNum: number
- message: string
-}
/** One batch of pages from a `ParseSession`. */
export interface JsParseBatch {
/** First source page in this batch, 1-indexed. */
@@ -369,6 +437,10 @@ export interface JsParseBatch {
/** The pages in `startPage..=endPage`, as an ordinary parse result. */
result: JsParseResult
}
+export interface JsPageError {
+ pageNum: number
+ message: string
+}
export interface JsDocumentMetadata {
creationDate?: string
modDate?: string
diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.ts
index 2e0b8a4..55bc59e 100644
--- a/packages/node/src/cli.ts
+++ b/packages/node/src/cli.ts
@@ -72,6 +72,10 @@ program
.option("--extract-annotations", "Include all PDF annotations in page output")
.option("--extract-form-fields", "Include AcroForm widget fields and values")
.option("--extract-structure-tree", "Include the tagged-PDF logical structure tree")
+ .option(
+ "--extract-blocks",
+ "Include each page's classified layout blocks with bounding boxes",
+ )
.option(
"--extract-xfa-packets",
"Include raw XFA packets (name + XML content) in JSON output",
@@ -139,6 +143,7 @@ program
if (opts.extractAnnotations) config.extractAnnotations = true;
if (opts.extractFormFields) config.extractFormFields = true;
if (opts.extractStructureTree) config.extractStructureTree = true;
+ if (opts.extractBlocks) config.extractBlocks = true;
if (opts.extractXfaPackets) config.extractXfaPackets = true;
if (opts.extractContentBounds) config.extractContentBounds = true;
if (opts.ocrServerUrl)
@@ -352,6 +357,10 @@ program
.option("--extract-annotations", "Include all PDF annotations in page output")
.option("--extract-form-fields", "Include AcroForm widget fields and values")
.option("--extract-structure-tree", "Include the tagged-PDF logical structure tree")
+ .option(
+ "--extract-blocks",
+ "Include each page's classified layout blocks with bounding boxes",
+ )
.option(
"--extract-xfa-packets",
"Include raw XFA packets (name + XML content) in JSON output",
@@ -390,6 +399,7 @@ program
if (opts.extractAnnotations) config.extractAnnotations = true;
if (opts.extractFormFields) config.extractFormFields = true;
if (opts.extractStructureTree) config.extractStructureTree = true;
+ if (opts.extractBlocks) config.extractBlocks = true;
if (opts.extractXfaPackets) config.extractXfaPackets = true;
if (opts.extractContentBounds) config.extractContentBounds = true;
if (opts.extractContentBounds) config.extractContentBounds = true;
diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.ts
index 21df191..8ef08de 100644
--- a/packages/node/src/lib.ts
+++ b/packages/node/src/lib.ts
@@ -51,6 +51,12 @@ export interface LiteParseConfig {
extractFormFields: boolean;
/** Extract the tagged-PDF logical structure tree (default: false). */
extractStructureTree: boolean;
+ /**
+ * Emit each page's classified layout blocks with bounding boxes
+ * (default: false). This is the same decomposition the Markdown renderer
+ * consumes, exposed as data; enabling it never changes the rendered Markdown.
+ */
+ extractBlocks: boolean;
/** Extract raw XFA packets (name + XML content) into `ParseResult.xfaPackets` (default: false). */
extractXfaPackets: boolean;
/**
@@ -249,6 +255,59 @@ export interface ParsedPage {
formFields?: FormField[];
/** Present only when `extractStructureTree` is enabled. */
structureTree?: StructureTree;
+ /**
+ * Classified layout blocks in reading order — the same blocks, in the same
+ * order, the page's Markdown is built from. Present only when
+ * `extractBlocks` is enabled.
+ */
+ blocks?: LayoutBlock[];
+}
+
+/** One table cell: its text and the region of the page it was read from. */
+export interface LayoutCell {
+ text: string;
+ /**
+ * Absent for cells with no ink behind them — padding inserted to square off
+ * a ragged grid, or halves of a merged run split at an estimated position.
+ */
+ bbox?: Rect;
+}
+
+/** A classified block of page content, discriminated by `kind`. */
+export interface LayoutBlock {
+ kind:
+ | "heading"
+ | "paragraph"
+ | "list_item"
+ | "code"
+ | "table"
+ | "grid_fallback"
+ | "rule"
+ | "figure";
+ /** Rendered text for `heading`, `paragraph`, and `list_item`. */
+ text?: string;
+ /** Heading level (1-6), or list nesting depth for `list_item`. */
+ level?: number;
+ bold?: boolean;
+ italic?: boolean;
+ /** `list_item` only. `marker` is the marker as it appeared on the page. */
+ ordered?: boolean;
+ marker?: string;
+ /** Verbatim source lines for `code` and `grid_fallback`. */
+ lines?: string[];
+ /** Best-effort language hint for `code`. */
+ lang?: string;
+ /** `table` only. */
+ header?: LayoutCell[];
+ rows?: LayoutCell[][];
+ /** `figure` only, matching the `img_{id}.{format}` Markdown target. */
+ id?: string;
+ format?: string;
+ /**
+ * Region this block occupies, in the same top-left 72-DPI viewport space as
+ * `textItems`. The union of every source line that fed the block.
+ */
+ bbox?: Rect;
}
export type StructureAttributeValue = boolean | number | string;
@@ -569,6 +628,7 @@ export class LiteParse {
extractAnnotations: userConfig.extractAnnotations,
extractFormFields: userConfig.extractFormFields,
extractStructureTree: userConfig.extractStructureTree,
+ extractBlocks: userConfig.extractBlocks,
extractXfaPackets: userConfig.extractXfaPackets,
extractDocumentMetadata: userConfig.extractDocumentMetadata,
extractContentBounds: userConfig.extractContentBounds,
@@ -612,6 +672,7 @@ export class LiteParse {
extractAnnotations: resolved.extractAnnotations ?? false,
extractFormFields: resolved.extractFormFields ?? false,
extractStructureTree: resolved.extractStructureTree ?? false,
+ extractBlocks: resolved.extractBlocks ?? false,
extractXfaPackets: resolved.extractXfaPackets ?? false,
extractDocumentMetadata: resolved.extractDocumentMetadata ?? false,
extractContentBounds: resolved.extractContentBounds ?? false,
@@ -829,6 +890,7 @@ function toPage(p: NativeParsedPage): ParsedPage {
structureTree: p.structureTree
? { roots: p.structureTree.roots.map(toStructureTreeElement) }
: undefined,
+ blocks: p.blocks as LayoutBlock[] | undefined,
};
}
diff --git a/packages/node/src/native.ts b/packages/node/src/native.ts
index 4991dfb..d247d6d 100644
--- a/packages/node/src/native.ts
+++ b/packages/node/src/native.ts
@@ -39,6 +39,7 @@ export interface LiteParseNativeConfig {
extractAnnotations?: boolean;
extractFormFields?: boolean;
extractStructureTree?: boolean;
+ extractBlocks?: boolean;
extractXfaPackets?: boolean;
extractDocumentMetadata?: boolean;
extractContentBounds?: boolean;
@@ -142,6 +143,29 @@ export interface NativeParsedPage {
annotations?: NativeDocumentAnnotation[];
formFields?: NativeFormField[];
structureTree?: NativeStructureTree;
+ blocks?: NativeLayoutBlock[];
+}
+
+export interface NativeLayoutCell {
+ text: string;
+ bbox?: NativeRect;
+}
+
+export interface NativeLayoutBlock {
+ kind: string;
+ text?: string;
+ level?: number;
+ bold?: boolean;
+ italic?: boolean;
+ ordered?: boolean;
+ marker?: string;
+ lines?: string[];
+ lang?: string;
+ header?: NativeLayoutCell[];
+ rows?: NativeLayoutCell[][];
+ id?: string;
+ format?: string;
+ bbox?: NativeRect;
}
export interface NativeStructureAttribute {
diff --git a/packages/python/liteparse/__init__.py b/packages/python/liteparse/__init__.py
index 483bde5..53b9c7b 100644
--- a/packages/python/liteparse/__init__.py
+++ b/packages/python/liteparse/__init__.py
@@ -4,6 +4,8 @@ from .parser import LiteParse, search_items
from .types import (
AnnotationRect,
DocumentAnnotation,
+ LayoutBlock,
+ LayoutCell,
FormField,
StructureTree,
StructureTreeElement,
@@ -36,6 +38,8 @@ __all__ = [
"LiteParse",
"AnnotationRect",
"DocumentAnnotation",
+ "LayoutBlock",
+ "LayoutCell",
"FormField",
"StructureTree",
"StructureTreeElement",
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.py
index a3a2aaf..f48d566 100644
--- a/packages/python/liteparse/parser.py
+++ b/packages/python/liteparse/parser.py
@@ -9,6 +9,8 @@ from liteparse._liteparse import search_items as _native_search_items
from .types import (
AnnotationRect,
DocumentAnnotation,
+ LayoutBlock,
+ LayoutCell,
FormField,
StructureTree,
StructureTreeElement,
@@ -34,6 +36,45 @@ from .types import (
)
+def _convert_rect(rect: Any) -> Optional[AnnotationRect]:
+ if rect is None:
+ return None
+ return AnnotationRect(
+ x=rect.x, y=rect.y, width=rect.width, height=rect.height
+ )
+
+
+def _convert_cell(cell: Any) -> LayoutCell:
+ return LayoutCell(text=cell.text, bbox=_convert_rect(cell.bbox))
+
+
+def _convert_block(block: Any) -> LayoutBlock:
+ return LayoutBlock(
+ kind=block.kind,
+ text=block.text,
+ level=block.level,
+ bold=block.bold,
+ italic=block.italic,
+ ordered=block.ordered,
+ marker=block.marker,
+ lines=list(block.lines) if block.lines is not None else None,
+ lang=block.lang,
+ header=(
+ [_convert_cell(c) for c in block.header]
+ if block.header is not None
+ else None
+ ),
+ rows=(
+ [[_convert_cell(c) for c in row] for row in block.rows]
+ if block.rows is not None
+ else None
+ ),
+ id=block.id,
+ format=block.format,
+ bbox=_convert_rect(block.bbox),
+ )
+
+
def _convert_annotation(annotation: Any) -> DocumentAnnotation:
return DocumentAnnotation(
subtype=annotation.subtype,
@@ -158,6 +199,7 @@ def _convert_native_result(native_result: Any) -> ParseResult:
native_annotations = getattr(native_page, "annotations", None)
native_form_fields = getattr(native_page, "form_fields", None)
native_structure_tree = getattr(native_page, "structure_tree", None)
+ native_blocks = getattr(native_page, "blocks", None)
pages.append(
ParsedPage(
page_num=native_page.page_num,
@@ -287,6 +329,11 @@ def _convert_native_result(native_result: Any) -> ParseResult:
if native_structure_tree is not None
else None
),
+ blocks=(
+ [_convert_block(block) for block in native_blocks]
+ if native_blocks is not None
+ else None
+ ),
)
)
images = [
@@ -428,6 +475,7 @@ class LiteParse:
extract_annotations: Optional[bool] = None,
extract_form_fields: Optional[bool] = None,
extract_structure_tree: Optional[bool] = None,
+ extract_blocks: Optional[bool] = None,
extract_xfa_packets: Optional[bool] = None,
extract_document_metadata: Optional[bool] = None,
extract_content_bounds: Optional[bool] = None,
@@ -480,6 +528,10 @@ class LiteParse:
structured data (default: False).
extract_form_fields: Include AcroForm widget fields and values as
page-scoped structured data (default: False).
+ extract_blocks: Emit each page's classified layout blocks with
+ bounding boxes. This is the same decomposition the Markdown
+ renderer consumes, exposed as data; enabling it never changes
+ the rendered Markdown.
extract_structure_tree: Include the tagged-PDF logical structure
tree as page-scoped structured data (default: False).
ocr_failure_fatal: Whether a systemic OCR failure (every OCR task
@@ -564,6 +616,8 @@ class LiteParse:
kwargs["extract_form_fields"] = extract_form_fields
if extract_structure_tree is not None:
kwargs["extract_structure_tree"] = extract_structure_tree
+ if extract_blocks is not None:
+ kwargs["extract_blocks"] = extract_blocks
if extract_xfa_packets is not None:
kwargs["extract_xfa_packets"] = extract_xfa_packets
if extract_document_metadata is not None:
@@ -815,6 +869,7 @@ class LiteParse:
extract_annotations=cfg.extract_annotations,
extract_form_fields=cfg.extract_form_fields,
extract_structure_tree=cfg.extract_structure_tree,
+ extract_blocks=cfg.extract_blocks,
ocr_failure_fatal=cfg.ocr_failure_fatal,
ocr_hedge_delays_ms=list(cfg.ocr_hedge_delays_ms),
emit_word_boxes=cfg.emit_word_boxes,
diff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.py
index 9705fa9..c796c75 100644
--- a/packages/python/liteparse/types.py
+++ b/packages/python/liteparse/types.py
@@ -59,6 +59,51 @@ class AnnotationRect:
height: float
+@dataclass
+class LayoutCell:
+ """One table cell: its text and the region of the page it was read from.
+
+ ``bbox`` is ``None`` for cells with no ink behind them -- padding inserted
+ to square off a ragged grid, or halves of a merged run split at an
+ estimated position rather than an observed boundary.
+ """
+ text: str
+ bbox: Optional[AnnotationRect] = None
+
+
+@dataclass
+class LayoutBlock:
+ """A classified block of page content, discriminated by ``kind``.
+
+ ``kind`` is one of ``heading``, ``paragraph``, ``list_item``, ``code``,
+ ``table``, ``grid_fallback``, ``rule``, ``figure``. Fields that do not
+ apply to a block's kind are ``None``.
+ """
+ kind: str
+ #: Rendered text for ``heading``, ``paragraph`` and ``list_item``.
+ text: Optional[str] = None
+ #: Heading level (1-6), or list nesting depth for ``list_item``.
+ level: Optional[int] = None
+ bold: bool = False
+ italic: bool = False
+ #: ``list_item`` only; ``marker`` is the marker as it appeared on the page.
+ ordered: Optional[bool] = None
+ marker: Optional[str] = None
+ #: Verbatim source lines for ``code`` and ``grid_fallback``.
+ lines: Optional[List[str]] = None
+ #: Best-effort language hint for ``code``.
+ lang: Optional[str] = None
+ #: ``table`` only.
+ header: Optional[List[LayoutCell]] = None
+ rows: Optional[List[List[LayoutCell]]] = None
+ #: ``figure`` only, matching the ``img_{id}.{format}`` Markdown target.
+ id: Optional[str] = None
+ format: Optional[str] = None
+ #: Region this block occupies, in the same top-left 72-DPI viewport space
+ #: as ``text_items``. The union of every source line that fed the block.
+ bbox: Optional[AnnotationRect] = None
+
+
@dataclass
class DocumentAnnotation:
"""One PDF annotation extracted from a page."""
@@ -142,6 +187,10 @@ class ParsedPage:
form_fields: Optional[List[FormField]] = None
#: Present only when parsing with ``extract_structure_tree=True``.
structure_tree: Optional[StructureTree] = None
+ #: Classified layout blocks in reading order -- the same blocks, in the
+ #: same order, the page's Markdown is built from. Present only when
+ #: parsing with ``extract_blocks=True``.
+ blocks: Optional[List[LayoutBlock]] = None
#: Union bbox ``(x, y, width, height)`` of the page's top-level content
#: objects in viewport coords (visible content extent). Present only when
#: parsing with ``extract_content_bounds=True``; ``None`` otherwise (and
@@ -420,6 +469,7 @@ class LiteParseConfig:
extract_annotations: bool
extract_form_fields: bool
extract_structure_tree: bool
+ extract_blocks: bool
ocr_failure_fatal: bool
ocr_hedge_delays_ms: List[int]
emit_word_boxes: bool