Skip to content

A fast, helpful, and open-source document parser

fix: report correct markdown layout bbox for rotated items

Logan Markewich59281893203c
diff --git a/crates/liteparse/src/layout.rs b/crates/liteparse/src/layout.rs
index 3187110..790e456 100644
--- a/crates/liteparse/src/layout.rs
+++ b/crates/liteparse/src/layout.rs
@@ -15,7 +15,7 @@
use serde::Serialize;
use crate::markdown_layout::{Block, Cell, PositionedBlock, SpanCell};
-use crate::types::Rect;
+use crate::types::{ParsedPage, Rect};
/// One table cell: its rendered text and the region it occupied.
///
@@ -209,3 +209,127 @@ impl From<&PositionedBlock> for LayoutBlock {
}
}
}
+
+/// Public block list for one page: the classifier's blocks converted to the
+/// flat serializable shape, with geometry in the page's viewport frame.
+///
+/// Block and cell boxes are unioned from `ProjectedLine.bbox`, which lives in
+/// the *projection* frame. On pages where rotation handling moved text (see
+/// `ParsedPage::projected_item_frames`) that frame is a virtual canvas —
+/// unrotated sidebars, body text pushed a page-height down — so those boxes
+/// are mapped back here. Pages without rotated text have an empty table and
+/// pass through unchanged.
+pub(crate) fn blocks_for_page(page: &ParsedPage, blocks: &[PositionedBlock]) -> Vec<LayoutBlock> {
+ let mut out: Vec<LayoutBlock> = blocks.iter().map(LayoutBlock::from).collect();
+ if !page.projected_item_frames.is_empty() {
+ remap_to_page_frame(&mut out, &page.projected_item_frames);
+ }
+ out
+}
+
+/// Map text-derived block and cell boxes from the projection frame back to
+/// the page frame. A box is the union of the text items it was built from,
+/// so its page-frame counterpart is the union of those items' original
+/// rects — found by testing which projected items sit inside it. `figure`
+/// and `rule` boxes come from graphics, already in page coordinates, and are
+/// left alone; so is any box that contains no projected item (nothing to
+/// map it through).
+fn remap_to_page_frame(blocks: &mut [LayoutBlock], frames: &[(Rect, Rect)]) {
+ for block in blocks.iter_mut() {
+ if matches!(block.kind, "figure" | "rule") {
+ continue;
+ }
+ remap_opt(&mut block.bbox, frames);
+ for cell in block.header.iter_mut().flatten() {
+ remap_opt(&mut cell.bbox, frames);
+ }
+ for cell in block.rows.iter_mut().flatten().flatten() {
+ remap_opt(&mut cell.bbox, frames);
+ }
+ }
+}
+
+fn remap_opt(bbox: &mut Option<Rect>, frames: &[(Rect, Rect)]) {
+ if let Some(r) = bbox.as_ref().and_then(|r| remap_rect(r, frames)) {
+ *bbox = Some(r);
+ }
+}
+
+/// Union of the original rects of every item whose projected centre lies in
+/// `rect` (with a small tolerance for float drift in the unions). `None` when
+/// no item does.
+fn remap_rect(rect: &Rect, frames: &[(Rect, Rect)]) -> Option<Rect> {
+ const TOL: f32 = 0.5;
+ let x0 = rect.x - TOL;
+ let y0 = rect.y - TOL;
+ let x1 = rect.x + rect.width + TOL;
+ let y1 = rect.y + rect.height + TOL;
+ let mut acc: Option<Rect> = None;
+ for (projected, original) in frames {
+ let cx = projected.x + projected.width / 2.0;
+ let cy = projected.y + projected.height / 2.0;
+ if cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1 {
+ Rect::extend(&mut acc, original);
+ }
+ }
+ acc
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect {
+ Rect {
+ x,
+ y,
+ width: w,
+ height: h,
+ }
+ }
+
+ fn para(bbox: Rect) -> LayoutBlock {
+ LayoutBlock {
+ text: Some("t".into()),
+ ..LayoutBlock::of("paragraph", Some(bbox))
+ }
+ }
+
+ #[test]
+ fn remap_unions_original_rects_of_contained_items() {
+ // Body text displaced one page-height (792pt) down by rotation handling.
+ let frames = vec![
+ (
+ rect(50.0, 892.0, 100.0, 10.0),
+ rect(50.0, 100.0, 100.0, 10.0),
+ ),
+ (
+ rect(50.0, 904.0, 120.0, 10.0),
+ rect(50.0, 112.0, 120.0, 10.0),
+ ),
+ // A rotated sidebar, unrotated in the projection frame.
+ (
+ rect(20.0, 30.0, 200.0, 12.0),
+ rect(14.0, 300.0, 12.0, 200.0),
+ ),
+ ];
+ let mut blocks = vec![
+ para(rect(50.0, 892.0, 120.0, 22.0)),
+ para(rect(20.0, 30.0, 200.0, 12.0)),
+ LayoutBlock::of("figure", Some(rect(300.0, 300.0, 50.0, 50.0))),
+ ];
+ remap_to_page_frame(&mut blocks, &frames);
+ assert_eq!(blocks[0].bbox, Some(rect(50.0, 100.0, 120.0, 22.0)));
+ assert_eq!(blocks[1].bbox, Some(rect(14.0, 300.0, 12.0, 200.0)));
+ // Graphics-derived boxes are already in page space.
+ assert_eq!(blocks[2].bbox, Some(rect(300.0, 300.0, 50.0, 50.0)));
+ }
+
+ #[test]
+ fn remap_leaves_boxes_with_no_items_untouched() {
+ let frames = vec![(rect(0.0, 900.0, 10.0, 10.0), rect(0.0, 100.0, 10.0, 10.0))];
+ let mut blocks = vec![para(rect(200.0, 200.0, 50.0, 10.0))];
+ remap_to_page_frame(&mut blocks, &frames);
+ assert_eq!(blocks[0].bbox, Some(rect(200.0, 200.0, 50.0, 10.0)));
+ }
+}
diff --git a/crates/liteparse/src/markdown_layout/test_helpers.rs b/crates/liteparse/src/markdown_layout/test_helpers.rs
index 7bf298d..aff4f01 100644
--- a/crates/liteparse/src/markdown_layout/test_helpers.rs
+++ b/crates/liteparse/src/markdown_layout/test_helpers.rs
@@ -43,6 +43,7 @@ pub(crate) fn page(lines: Vec<ProjectedLine>) -> ParsedPage {
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
@@ -202,6 +203,7 @@ pub(crate) fn header_footer_page(n: usize, header: &str, footer: &str, body: &st
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rs
index 5159cda..467a419 100644
--- a/crates/liteparse/src/output/json.rs
+++ b/crates/liteparse/src/output/json.rs
@@ -249,6 +249,7 @@ mod tests {
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rs
index 6116b3a..05d202d 100644
--- a/crates/liteparse/src/output/markdown.rs
+++ b/crates/liteparse/src/output/markdown.rs
@@ -211,6 +211,7 @@ mod tests {
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
@@ -269,6 +270,7 @@ mod tests {
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rs
index 548650b..ff01137 100644
--- a/crates/liteparse/src/output/text.rs
+++ b/crates/liteparse/src/output/text.rs
@@ -27,6 +27,7 @@ mod tests {
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rs
index 77a0c9d..c32ae69 100644
--- a/crates/liteparse/src/parser.rs
+++ b/crates/liteparse/src/parser.rs
@@ -258,14 +258,10 @@ fn apply_layout(
// 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(),
- );
+ page.blocks = Some(crate::layout::blocks_for_page(
+ page,
+ blocks.as_deref().unwrap_or_default(),
+ ));
}
}
if !wants_markdown {
@@ -1025,12 +1021,7 @@ impl LiteParse {
page.markdown = crate::markdown_layout::render_blocks(blocks);
}
if self.config.extract_blocks {
- page.blocks = Some(
- blocks
- .iter()
- .map(crate::layout::LayoutBlock::from)
- .collect(),
- );
+ page.blocks = Some(crate::layout::blocks_for_page(page, blocks));
}
page.complexity = stats;
if !self.config.extract_content_bounds {
@@ -1498,6 +1489,7 @@ mod tests {
graphics: vec![],
vector_graphics: None,
figures: vec![],
+ projected_item_frames: vec![],
struct_nodes: vec![],
image_refs: vec![],
complexity: None,
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 633eed6..e7d21b7 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -2891,6 +2891,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
page.page_height,
&obstacles,
);
+ let projected_item_frames = projected_item_frames(&projected_items);
ParsedPage {
page_number: page.page_number,
page_width: page.page_width,
@@ -2914,6 +2915,7 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
graphics: page.graphics,
vector_graphics: page.vector_graphics,
figures,
+ projected_item_frames,
struct_nodes: page.struct_nodes,
image_refs: page.image_refs,
complexity: None,
@@ -2928,6 +2930,38 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {
.collect()
}
+/// `(projected, original)` rect per text item when rotation handling moved
+/// any item on the page (see `ParsedPage::projected_item_frames`); empty
+/// otherwise. Gated on the `rotated` flag rather than on coordinate drift:
+/// projection also rounds sizes and merges neighbours, and those small
+/// deltas are not the frame change block boxes need mapping through — so
+/// the common no-rotation page pays nothing and its boxes pass through
+/// untouched.
+fn projected_item_frames(items: &[ProjectedTextItem]) -> Vec<(Rect, Rect)> {
+ if !items.iter().any(|p| p.rotated) {
+ return Vec::new();
+ }
+ items
+ .iter()
+ .map(|p| {
+ (
+ Rect {
+ x: p.item.x,
+ y: p.item.y,
+ width: p.item.width,
+ height: p.item.height,
+ },
+ Rect {
+ x: p.orig_x,
+ y: p.orig_y,
+ width: p.orig_width,
+ height: p.orig_height,
+ },
+ )
+ })
+ .collect()
+}
+
// ── ProjectedLine derivation ────────────────────────────────────────────────
//
// `build_projected_lines` groups already-projected items (in reading order)
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 07b6e82..654a521 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -444,6 +444,17 @@ pub struct ParsedPage {
/// obstacles, and reused downstream for figure classification.
#[serde(skip)]
pub figures: Vec<Rect>,
+ /// `(projected, original)` geometry of every text item, populated only
+ /// when the two differ for at least one item on the page. Rotation
+ /// reading-order handling unrotates 90°/270° text and can displace whole
+ /// groups onto a virtual canvas below the page so they read in the right
+ /// order; `ProjectedLine.bbox` (and so every block bbox unioned from it)
+ /// lives in that projected frame. Block/cell boxes are mapped back
+ /// through this table before they are reported, so they land in the
+ /// same viewport space as `text_items`. Empty for pages without rotated
+ /// text, which is the overwhelming majority.
+ #[serde(skip)]
+ pub projected_item_frames: Vec<(Rect, Rect)>,
/// Structure-tree nodes for this page (tagged PDFs only). Pre-flattened in
/// pre-order. Consumed by the markdown classifier for highest-priority
/// heading / figure / table detection.
@@ -526,7 +537,7 @@ pub struct ExtractedImage {
}
#[doc(hidden)]
-#[derive(Debug, Clone, Default, Serialize)]
+#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Rect {
pub x: f32,
pub y: f32,