A fast, helpful, and open-source document parser
wip
Logan Markewich1249c6b0e5a6
diff --git a/crates/liteparse-ooxml/src/render/layout/draw_command.rs b/crates/liteparse-ooxml/src/render/layout/draw_command.rsindex 7c5b7ed..d410ce1 100644--- a/crates/liteparse-ooxml/src/render/layout/draw_command.rs+++ b/crates/liteparse-ooxml/src/render/layout/draw_command.rs@@ -133,6 +133,20 @@ pub enum DrawCommand {/// relative to the image's natural extent, applied before the image/// is stretched into `rect`. `None` draws the whole image.src_rect: Option<PtRect>,+ /// Whether this image floats *above* the text rather than sitting in+ /// the flow with it — the one z-order fact a `DrawCommand` carries,+ /// because the painter's pass order cannot infer it.+ ///+ /// `false` for every image placed by a DOCX layout: an inline picture+ /// belongs to the line it sits on, and the `Media < Ink` pass order+ /// is what keeps a run of text over a cell-shading image readable.+ ///+ /// `true` for an XLSX floating picture, where the relation inverts:+ /// Excel draws a picture on top of the grid *and* its values, and a+ /// corpus census put painted glyphs on 618 of 2,114 placements+ /// (29.2%, 245 workbooks) — a banner with the sheet's text bleeding+ /// through it, not a rare artifact.+ float: bool,},/// One emoji grapheme cluster placed at `rect`. The painter rasterizes/// the cluster against `typeface` (Skia raster backend honours the color@@ -705,6 +719,7 @@ mod tests {format: crate::model::ImageFormat::Png,},src_rect: None,+ float: false,},),(diff --git a/crates/liteparse-ooxml/src/render/layout/header_footer.rs b/crates/liteparse-ooxml/src/render/layout/header_footer.rsindex 4ad15f6..e0a93cb 100644--- a/crates/liteparse-ooxml/src/render/layout/header_footer.rs+++ b/crates/liteparse-ooxml/src/render/layout/header_footer.rs@@ -341,6 +341,7 @@ fn render_header(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});}@@ -365,6 +366,7 @@ fn render_header(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});}// Paragraph-anchored shapes ride through `result.commands` above (their@@ -410,6 +412,7 @@ fn render_footer(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});}@@ -433,6 +436,7 @@ fn render_footer(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});}// Paragraph-anchored shapes ride through `result.commands` above (theirdiff --git a/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs b/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rsindex 3cf59ca..30187d0 100644--- a/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs+++ b/crates/liteparse-ooxml/src/render/layout/paragraph/line_emit.rs@@ -557,6 +557,7 @@ pub(super) fn emit_line_commands(),image_data: data.clone(),src_rect: *src_rect,+ float: false,});}x += size.widthdiff --git a/crates/liteparse-ooxml/src/render/layout/section/layout.rs b/crates/liteparse-ooxml/src/render/layout/section/layout.rsindex 368dd7d..52f555c 100644--- a/crates/liteparse-ooxml/src/render/layout/section/layout.rs+++ b/crates/liteparse-ooxml/src/render/layout/section/layout.rs@@ -458,6 +458,7 @@ fn register_paragraph_floats(rect: PtRect::from_xywh(fi.x.resolve(parity), img_y, fi.size.width, fi.size.height),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});if y_end > state.cursor_y {state.cursor_y = y_end;@@ -1857,6 +1858,7 @@ pub(crate) fn layout_section_with_clearance(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});}diff --git a/crates/liteparse-ooxml/src/render/layout/section/stacker.rs b/crates/liteparse-ooxml/src/render/layout/section/stacker.rsindex c4f0fd9..dc24c76 100644--- a/crates/liteparse-ooxml/src/render/layout/section/stacker.rs+++ b/crates/liteparse-ooxml/src/render/layout/section/stacker.rs@@ -157,6 +157,7 @@ pub fn stack_blocks(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});let bottom = img_y + fi.size.height;band_bottom = Some(match band_bottom {@@ -323,6 +324,7 @@ pub fn stack_blocks(),image_data: fi.image_data.clone(),src_rect: fi.src_rect,+ float: false,});// Extend cursor to encompass the image so table cells// expand to contain floating images.diff --git a/crates/liteparse-ooxml/src/render/raster.rs b/crates/liteparse-ooxml/src/render/raster.rsindex 43c76e8..0a0b4b4 100644--- a/crates/liteparse-ooxml/src/render/raster.rs+++ b/crates/liteparse-ooxml/src/render/raster.rs@@ -170,9 +170,17 @@ pub fn rasterize_page(// < Shading (highlight/cell-shading rects, tied to the text flow)// < Media (placed images; inline ones must beat cell shading)// < Ink (glyphs, rules, borders)+ // < Float (images that declared themselves above the flow)//- // Cost of the approximation: a deliberately in-front float no longer- // covers text/shading — rare, and its fill still paints. A shape's own+ // The last layer is the exception a producer can ask for, and it exists+ // because for one format the approximation below is not rare but the+ // norm: an XLSX picture floats over the grid *and* its values, and a+ // corpus census found painted glyphs on 29.2% of placements. Everything+ // a DOCX layout emits stays `float: false` and keeps the flow order.+ //+ // Cost of the approximation: a deliberately in-front float that does not+ // set that flag no longer covers text/shading — rare, and its fill still+ // paints. A shape's own// text-box text is emitted as separate `Text` commands, so it stays over// its fill in the ink pass.// Outside the pass loop: the same image can be a shape fill and a placed@@ -183,6 +191,7 @@ pub fn rasterize_page(RasterPass::Shading,RasterPass::Media,RasterPass::Ink,+ RasterPass::Float,] {// The shape-local → page transform opened by the innermost// `DrawCommand::Transform` bracket, or the identity outside one.@@ -253,6 +262,9 @@ pub fn rasterize_page(rect,image_data,src_rect,+ // Read by `raster_pass` to pick the layer; the paint+ // itself is identical either way.+ float: _,} => {draw_image(&mut pixmap, image_data, rect, src_rect.as_ref(), device);}@@ -327,17 +339,25 @@ enum RasterPass {Shape,/// Highlight and cell/paragraph shading rects.Shading,- /// Placed raster images.+ /// Placed raster images that sit in the flow — an inline DOCX picture.Media,/// Glyphs, emoji, underlines, table/border lines.Ink,+ /// Images that float above the text (`DrawCommand::Image { float: true }`)+ /// — the XLSX floating layer. The one place a producer can say the flow+ /// order does not apply to it.+ Float,}fn raster_pass(cmd: &DrawCommand) -> Option<RasterPass> {match cmd {DrawCommand::Path { .. } => Some(RasterPass::Shape),DrawCommand::Rect { .. } => Some(RasterPass::Shading),- DrawCommand::Image { .. } => Some(RasterPass::Media),+ DrawCommand::Image { float, .. } => Some(if *float {+ RasterPass::Float+ } else {+ RasterPass::Media+ }),DrawCommand::Text { .. }| DrawCommand::Underline { .. }| DrawCommand::Line { .. }@@ -1020,6 +1040,59 @@ mod tests {assert!(!inked(&r, 5, 15), "neither drew at the page origin");}+ /// A page holding one black ink line, and one white image covering it.+ fn line_under_image(float: bool) -> LayoutedPage {+ let mut png = std::io::Cursor::new(Vec::new());+ image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255]))+ .write_to(&mut png, image::ImageFormat::Png)+ .expect("encode");+ LayoutedPage {+ commands: vec![+ DrawCommand::Line {+ line: crate::render::geometry::PtLineSegment {+ start: PtOffset::new(Pt::new(10.0), Pt::new(30.0)),+ end: PtOffset::new(Pt::new(50.0), Pt::new(30.0)),+ },+ color: RgbColor { r: 0, g: 0, b: 0 },+ width: Pt::new(4.0),+ },+ DrawCommand::Image {+ rect: rect(0.0, 10.0, 60.0, 40.0),+ image_data: crate::render::resolve::images::MediaEntry {+ data: std::sync::Arc::from(png.into_inner().as_slice()),+ format: crate::model::ImageFormat::Png,+ },+ src_rect: None,+ float,+ },+ ],+ page_size: PtSize::new(Pt::new(100.0), Pt::new(100.0)),+ block_starts: Vec::new(),+ }+ }++ /// The flow order, and the one exception to it. Command order is the same+ /// in both pages — only the flag differs — because the painter reads+ /// layers, not position: an inline image cannot hide the line of text it+ /// sits on, and an XLSX float has to hide the grid values under it.+ #[test]+ fn a_floating_image_covers_ink_and_an_inline_one_does_not() {+ let inline =+ rasterize_page(&line_under_image(false), &FontRegistry::new(), 1.0).expect("raster");+ assert!(inked(&inline, 30, 30), "ink paints over an in-flow image");++ let floating =+ rasterize_page(&line_under_image(true), &FontRegistry::new(), 1.0).expect("raster");+ assert!(!inked(&floating, 30, 30), "a float paints over the ink");+ // Same page, outside the picture: the float covers what it covers and+ // nothing else — this is what separates a fifth pass from disabling+ // the ink pass.+ assert!(+ inked(&floating, 30, 5) == inked(&inline, 30, 5),+ "pixels outside the image are untouched by the flag"+ );+ }+/// The clamp must be inert for every page that already fits, or it is a/// silent quality regression on 99.4% of the corpus rather than a/// backstop for the 0.6%. Letter at 150 DPI is 1.6 MP.diff --git a/crates/liteparse/src/office/xlsx_layout.rs b/crates/liteparse/src/office/xlsx_layout.rsindex bf63c75..99ea50e 100644--- a/crates/liteparse/src/office/xlsx_layout.rs+++ b/crates/liteparse/src/office/xlsx_layout.rs@@ -48,6 +48,7 @@ use liteparse_ooxml::render::layout::draw_command::{DrawCommand, LayoutedPage};use liteparse_ooxml::render::layout::fragment::FontProps;use liteparse_ooxml::render::layout::measurer::TextMeasurer;use liteparse_ooxml::render::resolve::color::RgbColor;+use liteparse_ooxml::render::resolve::images::MediaEntry;use liteparse_ooxml::xlsx::{Alignment, Border, BorderEdge, CellAnchor, CellValue, HorizontalAlign, PatternType, PicAnchor,Row, Sheet, SheetShape, VerticalAlign, Workbook,@@ -116,9 +117,16 @@ pub struct NativeXlsx {pub pic_rects: Vec<Vec<Rect>>,/// The paint of each page, aligned with `pages`: gridlines, cell fills/// and cell borders as [`DrawCommand::Rect`]s, then the cell text as- /// [`DrawCommand::Text`]s — ready for `render::raster::rasterize_page`.+ /// [`DrawCommand::Text`]s, then each picture on the page as a+ /// [`DrawCommand::Image`] — ready for `render::raster::rasterize_page`./// Empty unless `EmitOptions::paint`; textless unless a font registry was/// supplied too.+ ///+ /// Command order carries no z-order here: the rasterizer paints in fixed+ /// passes (`Path` → `Rect` → `Image` → ink), so a picture always covers+ /// the grid beneath it and cell text always covers the picture. Excel+ /// floats a picture above cell text, so that last relation is inverted —+ /// see the overlap census for how often it can be seen.pub layouts: Vec<LayoutedPage>,/// What the text pass met, summed over the workbook. Zero when nothing/// was painted; read by the corpus gate, not by `parser.rs`.@@ -226,6 +234,10 @@ pub fn workbook_to_pages(// one canonical entry, the same cross-page rule the PPTX path applies// across slides.let mut sink = FigureSink::default();+ // Workbook-scoped so every placement of one media part shares one `Arc`,+ // which is the identity the painter's bitmap cache keys on. Populated+ // only under `EmitOptions::paint`.+ let mut media: std::collections::HashMap<&str, MediaEntry> = std::collections::HashMap::new();for (si, sheet) in wb.sheets.iter().enumerate() {let heading = Block::Heading {@@ -324,6 +336,7 @@ pub fn workbook_to_pages(// local ordinal mirrors `figure_blocks` (both skip media we do not// surface), and the sink's id must agree with it by construction.let mut rects_per_page: Vec<Vec<Rect>> = vec![Vec::new(); ranges.len()];+ let mut pic_cmds_per_page: Vec<Vec<DrawCommand>> = vec![Vec::new(); ranges.len()];sink.reset_ordinal();let mut n_fig = 0u32;for pic in super::xlsx::ordered_pics(sheet) {@@ -341,6 +354,41 @@ pub fn workbook_to_pages(&pic.anchor,);rects_per_page[page_local].push(rect.clone());+ if opts.paint {+ // One `MediaEntry` per media part for the whole workbook, not+ // per placement: the painter's bitmap cache keys on the `Arc`+ // pointer, so a logo anchored on every sheet decodes once.+ // The copy out of the reader's `Arc<Vec<u8>>` is paid here+ // rather than at read time so a parse — which never paints —+ // keeps costing zero byte copies.+ let entry = media+ .entry(pic.media_path.as_str())+ .or_insert_with(|| MediaEntry {+ data: std::sync::Arc::from(pic.bytes.as_slice()),+ format: pic.format,+ })+ .clone();+ pic_cmds_per_page[page_local].push(DrawCommand::Image {+ rect: PtRect::from_xywh(+ Pt::new(rect.x),+ Pt::new(rect.y),+ Pt::new(rect.width),+ Pt::new(rect.height),+ ),+ image_data: entry,+ // `a:srcRect` is not read by the XLSX drawing parser, so+ // a cropped picture paints uncropped. Recorded, not+ // guessed: the crop math already exists for the DOCX and+ // PPTX paths and can be threaded through when the anchor+ // parser grows the element.+ src_rect: None,+ // Excel floats a picture above the grid *and* its values,+ // so this is the one producer that opts out of the+ // painter's flow order — without it 29.2% of corpus+ // placements have cell text drawn through them.+ float: true,+ });+ }if opts.figures {blocks_per_page[page_local].push(Block::Figure {id: id.clone(),@@ -378,17 +426,23 @@ pub fn workbook_to_pages(Pt::new(page.page_width),Pt::new(page.page_height),));- if let (true, Some(p)) = (opts.paint, &plan) {- let (cmds, stats) = geo.paint_page(- wb,- sheet,- p,- &col_styles,- ranges[i].clone(),- measurer.as_ref(),- );- layout.commands = cmds;- out.text_stats.add(stats);+ if opts.paint {+ if let Some(p) = &plan {+ let (cmds, stats) = geo.paint_page(+ wb,+ sheet,+ p,+ &col_styles,+ ranges[i].clone(),+ measurer.as_ref(),+ );+ layout.commands = cmds;+ out.text_stats.add(stats);+ }+ // Outside the `plan` arm on purpose: a sheet whose only+ // content is a picture has no grid to paint and still has+ // something to draw.+ layout.commands.append(&mut pic_cmds_per_page[i]);}out.layouts.push(layout);out.pages.push(page);@@ -1889,6 +1943,118 @@ mod tests {assert_eq!(nx.images[0].bytes.as_slice(), b"not-really-png-but-bytes");}+ /// `paint` alone paints the picture: neither `figures` nor `images` is+ /// what reaches the bytes, which is the contract the screenshot path+ /// depends on (it asks for neither). The command's rect is the same rect+ /// `pic_rects` reports, so a raster and a bbox consumer cannot disagree.+ #[test]+ fn paint_emits_one_image_command_per_placement() {+ let sheet = r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>+ <row r="1"><c r="A1"><v>1</v></c></row>+ </sheetData><drawing r:id="rId7"/></worksheet>"#;+ let anchor = pic_anchor(+ r#"<xdr:oneCellAnchor>+ <xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:ext cx="914400" cy="457200"/>"#,+ );+ let nx = layout_with_pic(+ sheet,+ &format!("{anchor}</xdr:oneCellAnchor>"),+ EmitOptions {+ paint: true,+ ..Default::default()+ },+ );+ assert!(nx.images.is_empty(), "paint collects no extraction entries");+ let images: Vec<_> = nx.layouts[0]+ .commands+ .iter()+ .filter_map(|c| match c {+ DrawCommand::Image {+ rect,+ image_data,+ src_rect,+ float,+ } => Some((rect, image_data, src_rect, float)),+ _ => None,+ })+ .collect();+ assert_eq!(images.len(), 1);+ let (rect, data, src_rect, float) = images[0];+ assert!(src_rect.is_none(), "a:srcRect is not read for XLSX yet");+ assert!(*float, "an XLSX picture paints above the grid's text");+ assert_eq!(&*data.data, b"not-really-png-but-bytes");+ let r = &nx.pic_rects[0][0];+ assert_eq!(+ (+ rect.origin.x.raw(),+ rect.origin.y.raw(),+ rect.size.width.raw(),+ rect.size.height.raw()+ ),+ (r.x, r.y, r.width, r.height),+ "the painted box and the reported box are one box"+ );+ // The grid still painted underneath — the floating layer appends, it+ // does not replace.+ assert!(+ nx.layouts[0]+ .commands+ .iter()+ .any(|c| matches!(c, DrawCommand::Rect { .. }))+ );+ }++ /// Without `paint` there is no image command and no byte copy — the+ /// parse path's cost is unchanged by this layer existing.+ #[test]+ fn a_parse_paints_no_pictures() {+ let sheet = r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>+ <row r="1"><c r="A1"><v>1</v></c></row>+ </sheetData><drawing r:id="rId7"/></worksheet>"#;+ let anchor = pic_anchor(+ r#"<xdr:oneCellAnchor>+ <xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:ext cx="914400" cy="457200"/>"#,+ );+ let nx = layout_with_pic(+ sheet,+ &format!("{anchor}</xdr:oneCellAnchor>"),+ EmitOptions::default(),+ );+ assert_eq!(nx.pic_rects[0].len(), 1, "the rect is still reported");+ assert!(nx.layouts[0].commands.is_empty());+ }++ /// An image-only sheet has no grid to paint and still has something to+ /// draw: the picture command lives outside the `SheetPlan` arm.+ #[test]+ fn a_plan_less_sheet_still_paints_its_picture() {+ let sheet = r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData/><drawing r:id="rId7"/></worksheet>"#;+ let anchor = pic_anchor(+ r#"<xdr:oneCellAnchor>+ <xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:ext cx="914400" cy="914400"/>"#,+ );+ let nx = layout_with_pic(+ sheet,+ &format!("{anchor}</xdr:oneCellAnchor>"),+ EmitOptions {+ paint: true,+ ..Default::default()+ },+ );+ assert_eq!(nx.layouts.len(), 1);+ assert_eq!(+ nx.layouts[0]+ .commands+ .iter()+ .filter(|c| matches!(c, DrawCommand::Image { .. }))+ .count(),+ 1+ );+ }+/// `figures` without `images`: refs appear, no bytes are collected —/// the default-config (placeholder image mode) shape.#[test]diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex fcb41ae..3d1803e 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -1582,10 +1582,11 @@ impl LiteParse {let registry = liteparse_ooxml::render::fonts::FontRegistry::build(&[], &[]).map_err(|e| LiteParseError::Conversion(format!("font registry: {e}")))?;// The one call that differs from the parse side: `paint: true` plus a- // registry, which is what turns the pass's grid and cell values into- // draw commands. Figures and image bytes stay off — the floating- // layer does not paint yet, so asking for it would only copy bytes- // nothing draws.+ // registry, which is what turns the pass's grid, cell values and+ // pictures into draw commands. `figures` and `images` stay off —+ // those are the *emission* side (markdown refs and extracted byte+ // entries), which a raster has no use for; `paint` reaches the+ // picture bytes on its own.let nx = xlsx_layout::workbook_to_pages(&wb,xlsx::EmitOptions {