A fast, helpful, and open-source document parser
wip
Logan Markewich9cf15638c772
diff --git a/crates/liteparse-napi/Cargo.toml b/crates/liteparse-napi/Cargo.tomlindex 88e779e..0bbb11b 100644--- a/crates/liteparse-napi/Cargo.toml+++ b/crates/liteparse-napi/Cargo.toml@@ -10,9 +10,11 @@ description = "Node.js native bindings for LiteParse"crate-type = ["cdylib"][features]-default = ["tesseract", "docx-native"]+default = ["tesseract", "docx-native", "pptx-native", "xlsx-native"]tesseract = ["liteparse/tesseract"]docx-native = ["liteparse/docx-native"]+pptx-native = ["liteparse/pptx-native"]+xlsx-native = ["liteparse/xlsx-native"][dependencies]liteparse = { package = "liteparse", version = "2.11.0", path = "../liteparse", default-features = false }diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex c44dd4d..6fd423d 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -59,9 +59,10 @@ pub struct JsLiteParseConfig {/// Keep running headers/footers in markdown output instead of stripping/// repeated page-band lines and page chrome (default false).pub keep_headers_footers: Option<bool>,- /// Parse DOCX natively instead of converting via LibreOffice (default- /// true in builds with the docx-native feature; other formats always use- /// the conversion path). Set false to force the LibreOffice path.+ /// Parse DOCX/PPTX/XLSX natively instead of converting via LibreOffice+ /// (default true in builds with the docx-native/pptx-native/xlsx-native+ /// features; other formats always use the conversion path). Set false to+ /// force the LibreOffice path.pub office_native: Option<bool>,/// Extract all PDF annotations as page-scoped structured data.pub extract_annotations: Option<bool>,diff --git a/crates/liteparse-ooxml/src/xlsx/drawings.rs b/crates/liteparse-ooxml/src/xlsx/drawings.rsnew file mode 100644index 0000000..d35b432--- /dev/null+++ b/crates/liteparse-ooxml/src/xlsx/drawings.rs@@ -0,0 +1,432 @@+//! SpreadsheetML DrawingML: the pictures floating over a sheet's grid.+//!+//! A worksheet references at most one drawing part (`<drawing r:id>`); the+//! part holds a list of *anchors* (ECMA-376 §20.5), each placing one object —+//! a picture, a shape, a chart frame, or a group — against the grid. This+//! module reads **pictures only**: the corpus census (1,248 workbooks) found+//! 2,276 `xdr:pic` against 386 chart frames and 28,745 shapes, and a chart+//! has no image bytes to extract while a shape's text is a separate content+//! gap, recorded in the plan doc rather than half-solved here.+//!+//! Census-driven decisions:+//!+//! * **All three anchor kinds are read.** `oneCellAnchor` is the majority+//! (19,228 against 9,157 `twoCellAnchor`), so treating the two-cell form as+//! canonical would misplace most of the population. `absoluteAnchor` holds+//! exactly 1 corpus picture but costs ~10 lines.+//! * **A grouped picture inherits its group's anchor.** 161 of 2,276 pictures+//! sit inside `xdr:grpSp`, whose children carry their own EMU offsets+//! relative to a child coordinate space. Composing those matrices is the+//! PPTX group-geometry problem again; here every picture found anywhere in+//! an anchor's subtree is placed at the anchor's box. The bytes are exact,+//! the box is the group's — an approximation the geometry pass records.+//! * **`r:embed` resolves against the drawing part's own rels** — the same+//! per-part scoping rule every other OOXML reader in this crate has had to+//! learn. When a `blip` also carries an SVG extension, `r:embed` is the+//! raster fallback and is what we take; an SVG-only blip has no `r:embed`+//! and yields nothing, matching the PPTX figure policy.++use std::sync::Arc;++use quick_xml::Reader;+use quick_xml::events::Event;++use crate::docx::error::Result;+use crate::model::ImageFormat;+use crate::xlsx::xml::{attr, local_name};++/// One corner of a cell anchor: a grid position plus an EMU offset into it.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct CellAnchor {+ /// Zero-based column.+ pub col: u32,+ pub col_off_emu: i64,+ /// Zero-based row.+ pub row: u32,+ pub row_off_emu: i64,+}++/// Where an anchor places its object, in the three forms §20.5.2 allows.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PicAnchor {+ /// `xdr:oneCellAnchor`: a top-left cell plus an explicit extent.+ OneCell {+ from: CellAnchor,+ ext_emu: (i64, i64),+ },+ /// `xdr:twoCellAnchor`: a top-left and bottom-right cell.+ TwoCell { from: CellAnchor, to: CellAnchor },+ /// `xdr:absoluteAnchor`: a canvas position, ignoring the grid.+ Absolute {+ pos_emu: (i64, i64),+ ext_emu: (i64, i64),+ },+}++impl PicAnchor {+ /// The anchor's top-left grid corner, `None` for the absolute form.+ /// Sorting and page assignment key on this.+ pub fn from_cell(&self) -> Option<CellAnchor> {+ match self {+ PicAnchor::OneCell { from, .. } | PicAnchor::TwoCell { from, .. } => Some(*from),+ PicAnchor::Absolute { .. } => None,+ }+ }+}++/// One picture placed on a sheet, bytes in hand.+#[derive(Clone, Debug)]+pub struct SheetPic {+ pub anchor: PicAnchor,+ /// `xdr:cNvPr@name`, when the producer wrote one.+ pub name: Option<String>,+ /// Package path of the media part — the dedup key across placements.+ pub media_path: String,+ pub format: ImageFormat,+ /// Shared with every other placement of the same media part.+ pub bytes: Arc<Vec<u8>>,+}++/// A picture as the drawing part states it, before media resolution.+pub(crate) struct RawPic {+ pub(crate) anchor: PicAnchor,+ pub(crate) name: Option<String>,+ pub(crate) rel_id: String,+}++/// Parse one `xl/drawings/drawingN.xml` part into its placed pictures.+///+/// Fail-open like the rest of the reader: a malformed drawing part costs its+/// pictures, never the workbook.+pub(crate) fn parse_drawing(data: &[u8]) -> Result<Vec<RawPic>> {+ let mut reader = Reader::from_reader(data);+ let mut buf = Vec::new();+ let mut out = Vec::new();++ // State for the anchor currently open. `object_depth` counts how far+ // inside a placed object (pic/sp/grpSp/graphicFrame/cxnSp) the cursor is:+ // the anchor's own `from`/`to`/`ext`/`pos` children are only read at+ // depth 0, because `ext` also names `a:ext` inside every shape transform+ // and `local_name` cannot tell the prefixes apart.+ let mut anchor_kind: Option<&'static str> = None;+ let mut from = CellAnchor::default();+ let mut to = CellAnchor::default();+ let mut has_to = false;+ let mut ext: Option<(i64, i64)> = None;+ let mut pos: Option<(i64, i64)> = None;+ let mut object_depth: u32 = 0;+ let mut pic_depth: u32 = 0;+ let mut pending: Vec<(Option<String>, Option<String>)> = Vec::new(); // (name, rel_id)++ // Corner currently being filled and the element text being accumulated.+ let mut corner: Option<bool> = None; // true = from, false = to+ let mut text_target: Option<&'static str> = None;+ let mut text = String::new();++ loop {+ let event = reader+ .read_event_into(&mut buf)+ .map_err(quick_xml::DeError::from)?;+ match event {+ Event::Eof => break,+ Event::Start(ref e) | Event::Empty(ref e) => {+ let qname = e.name();+ let name = local_name(qname.as_ref());+ let empty = matches!(event, Event::Empty(_));+ match name {+ b"oneCellAnchor" | b"twoCellAnchor" | b"absoluteAnchor" if !empty => {+ anchor_kind = Some(match name {+ b"oneCellAnchor" => "one",+ b"twoCellAnchor" => "two",+ _ => "abs",+ });+ from = CellAnchor::default();+ to = CellAnchor::default();+ has_to = false;+ ext = None;+ pos = None;+ object_depth = 0;+ pic_depth = 0;+ pending.clear();+ }+ b"pic" | b"sp" | b"grpSp" | b"graphicFrame" | b"cxnSp"+ if anchor_kind.is_some() =>+ {+ if name == b"pic" {+ pending.push((None, None));+ if !empty {+ pic_depth += 1;+ }+ }+ if !empty {+ object_depth += 1;+ }+ }+ b"from" if anchor_kind.is_some() && object_depth == 0 && !empty => {+ corner = Some(true);+ }+ b"to" if anchor_kind.is_some() && object_depth == 0 && !empty => {+ corner = Some(false);+ has_to = true;+ }+ b"col" | b"colOff" | b"row" | b"rowOff" if corner.is_some() && !empty => {+ text_target = Some(match name {+ b"col" => "col",+ b"colOff" => "colOff",+ b"row" => "row",+ _ => "rowOff",+ });+ text.clear();+ }+ b"ext" if anchor_kind.is_some() && object_depth == 0 => {+ let cx = attr(e, b"cx").and_then(|v| v.parse().ok()).unwrap_or(0);+ let cy = attr(e, b"cy").and_then(|v| v.parse().ok()).unwrap_or(0);+ ext = Some((cx, cy));+ }+ b"pos" if anchor_kind.is_some() && object_depth == 0 => {+ let x = attr(e, b"x").and_then(|v| v.parse().ok()).unwrap_or(0);+ let y = attr(e, b"y").and_then(|v| v.parse().ok()).unwrap_or(0);+ pos = Some((x, y));+ }+ // `cNvPr` also names shapes and groups; only a picture's+ // own (the first at its depth) is its display name.+ b"cNvPr" if pic_depth > 0 => {+ if let Some(last) = pending.last_mut()+ && last.0.is_none()+ {+ last.0 = attr(e, b"name").filter(|n| !n.is_empty());+ }+ }+ // The blip inside `xdr:blipFill`. A shape's background+ // fill also uses `a:blip`, so only capture inside a pic.+ b"blip" if pic_depth > 0 => {+ if let Some(last) = pending.last_mut()+ && last.1.is_none()+ {+ last.1 = attr(e, b"r:embed");+ }+ }+ _ => {}+ }+ }+ Event::Text(ref t) if text_target.is_some() => {+ text.push_str(&t.decode().map_err(quick_xml::DeError::from)?);+ }+ Event::End(ref e) => match local_name(e.name().as_ref()) {+ b"oneCellAnchor" | b"twoCellAnchor" | b"absoluteAnchor" => {+ if let Some(kind) = anchor_kind.take() {+ let anchor = match kind {+ "one" => PicAnchor::OneCell {+ from,+ ext_emu: ext.unwrap_or((0, 0)),+ },+ "two" => {+ if has_to {+ PicAnchor::TwoCell { from, to }+ } else {+ // A malformed two-cell anchor with no+ // `to` degrades to a zero-extent one-cell.+ PicAnchor::OneCell {+ from,+ ext_emu: ext.unwrap_or((0, 0)),+ }+ }+ }+ _ => PicAnchor::Absolute {+ pos_emu: pos.unwrap_or((0, 0)),+ ext_emu: ext.unwrap_or((0, 0)),+ },+ };+ for (name, rel_id) in pending.drain(..) {+ if let Some(rel_id) = rel_id {+ out.push(RawPic {+ anchor,+ name: name.clone(),+ rel_id,+ });+ }+ }+ }+ }+ b"pic" if pic_depth > 0 => {+ pic_depth -= 1;+ object_depth = object_depth.saturating_sub(1);+ }+ b"sp" | b"grpSp" | b"graphicFrame" | b"cxnSp" => {+ object_depth = object_depth.saturating_sub(1);+ }+ b"from" | b"to" => corner = None,+ b"col" | b"colOff" | b"row" | b"rowOff" => {+ if let (Some(target), Some(is_from)) = (text_target.take(), corner) {+ let c = if is_from { &mut from } else { &mut to };+ let v = text.trim();+ match target {+ "col" => c.col = v.parse().unwrap_or(0),+ "colOff" => c.col_off_emu = v.parse().unwrap_or(0),+ "row" => c.row = v.parse().unwrap_or(0),+ _ => c.row_off_emu = v.parse().unwrap_or(0),+ }+ }+ }+ _ => {}+ },+ _ => {}+ }+ buf.clear();+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ const NS: &str = r#"xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;++ fn pic(rel: &str, name: &str) -> String {+ format!(+ r#"<xdr:pic><xdr:nvPicPr><xdr:cNvPr id="2" name="{name}"/><xdr:cNvPicPr/></xdr:nvPicPr>+ <xdr:blipFill><a:blip r:embed="{rel}"/></xdr:blipFill>+ <xdr:spPr><a:xfrm><a:off x="1" y="2"/><a:ext cx="999" cy="888"/></a:xfrm></xdr:spPr></xdr:pic>"#+ )+ }++ #[test]+ fn a_two_cell_anchor_reads_both_corners() {+ let xml = format!(+ r#"<xdr:wsDr {NS}><xdr:twoCellAnchor>+ <xdr:from><xdr:col>1</xdr:col><xdr:colOff>9525</xdr:colOff><xdr:row>2</xdr:row><xdr:rowOff>19050</xdr:rowOff></xdr:from>+ <xdr:to><xdr:col>4</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>7</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>+ {}+ <xdr:clientData/></xdr:twoCellAnchor></xdr:wsDr>"#,+ pic("rId1", "Logo")+ );+ let pics = parse_drawing(xml.as_bytes()).unwrap();+ assert_eq!(pics.len(), 1);+ assert_eq!(pics[0].rel_id, "rId1");+ assert_eq!(pics[0].name.as_deref(), Some("Logo"));+ assert_eq!(+ pics[0].anchor,+ PicAnchor::TwoCell {+ from: CellAnchor {+ col: 1,+ col_off_emu: 9525,+ row: 2,+ row_off_emu: 19050+ },+ to: CellAnchor {+ col: 4,+ col_off_emu: 0,+ row: 7,+ row_off_emu: 0+ },+ }+ );+ }++ /// The trap this parser's depth counter exists for: the pic's own+ /// `a:ext cx="999"` must not overwrite the anchor's `xdr:ext`, because+ /// `local_name` strips both prefixes to `ext`.+ #[test]+ fn a_one_cell_anchor_takes_the_anchor_ext_not_the_shape_transform() {+ let xml = format!(+ r#"<xdr:wsDr {NS}><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"/>+ {}+ <xdr:clientData/></xdr:oneCellAnchor></xdr:wsDr>"#,+ pic("rId2", "P")+ );+ let pics = parse_drawing(xml.as_bytes()).unwrap();+ assert_eq!(+ pics[0].anchor,+ PicAnchor::OneCell {+ from: CellAnchor::default(),+ ext_emu: (914400, 457200)+ }+ );+ }++ /// Pictures inside a group inherit the group's anchor; the shapes around+ /// them contribute nothing.+ #[test]+ fn grouped_pictures_take_the_group_anchor() {+ let xml = format!(+ r#"<xdr:wsDr {NS}><xdr:twoCellAnchor>+ <xdr:from><xdr:col>3</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>4</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:to><xdr:col>6</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>9</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>+ <xdr:grpSp><xdr:nvGrpSpPr><xdr:cNvPr id="1" name="Group 1"/></xdr:nvGrpSpPr>+ <xdr:sp><xdr:nvSpPr><xdr:cNvPr id="5" name="Box"/></xdr:nvSpPr><xdr:spPr><a:xfrm><a:ext cx="7" cy="8"/></a:xfrm></xdr:spPr></xdr:sp>+ {}{}+ </xdr:grpSp>+ <xdr:clientData/></xdr:twoCellAnchor></xdr:wsDr>"#,+ pic("rId3", "A"),+ pic("rId4", "B")+ );+ let pics = parse_drawing(xml.as_bytes()).unwrap();+ assert_eq!(pics.len(), 2);+ assert_eq!(pics[0].rel_id, "rId3");+ assert_eq!(pics[0].name.as_deref(), Some("A"));+ assert_eq!(pics[1].rel_id, "rId4");+ let expect = PicAnchor::TwoCell {+ from: CellAnchor {+ col: 3,+ row: 4,+ ..Default::default()+ },+ to: CellAnchor {+ col: 6,+ row: 9,+ ..Default::default()+ },+ };+ assert_eq!(pics[0].anchor, expect);+ assert_eq!(pics[1].anchor, expect);+ }++ /// A shape's `a:blip` background fill is not a picture.+ #[test]+ fn a_shape_fill_blip_is_not_captured() {+ let xml = format!(+ r#"<xdr:wsDr {NS}><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="1" cy="1"/>+ <xdr:sp><xdr:spPr><a:blipFill><a:blip r:embed="rId9"/></a:blipFill></xdr:spPr></xdr:sp>+ <xdr:clientData/></xdr:oneCellAnchor></xdr:wsDr>"#+ );+ assert!(parse_drawing(xml.as_bytes()).unwrap().is_empty());+ }++ #[test]+ fn an_absolute_anchor_reads_pos_and_ext() {+ let xml = format!(+ r#"<xdr:wsDr {NS}><xdr:absoluteAnchor>+ <xdr:pos x="100000" y="200000"/><xdr:ext cx="300000" cy="400000"/>+ {}+ <xdr:clientData/></xdr:absoluteAnchor></xdr:wsDr>"#,+ pic("rId5", "Abs")+ );+ let pics = parse_drawing(xml.as_bytes()).unwrap();+ assert_eq!(+ pics[0].anchor,+ PicAnchor::Absolute {+ pos_emu: (100000, 200000),+ ext_emu: (300000, 400000)+ }+ );+ }++ /// A chart frame is not a picture and yields nothing — the census's 386+ /// `graphicFrame`s are recorded as out of scope, not silently absorbed.+ #[test]+ fn a_chart_frame_yields_no_picture() {+ let xml = format!(+ r#"<xdr:wsDr {NS}><xdr:twoCellAnchor>+ <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:to><xdr:col>5</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>10</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>+ <xdr:graphicFrame><a:graphic><a:graphicData uri="chart"/></a:graphic></xdr:graphicFrame>+ <xdr:clientData/></xdr:twoCellAnchor></xdr:wsDr>"#+ );+ assert!(parse_drawing(xml.as_bytes()).unwrap().is_empty());+ }+}diff --git a/crates/liteparse-ooxml/src/xlsx/mod.rs b/crates/liteparse-ooxml/src/xlsx/mod.rsindex c03cfa7..52dbe7f 100644--- a/crates/liteparse-ooxml/src/xlsx/mod.rs+++ b/crates/liteparse-ooxml/src/xlsx/mod.rs@@ -43,6 +43,7 @@//! keeping it out of here is what lets this module be tested against a//! corpus with no renderer in the loop.+pub mod drawings;pub mod numfmt;pub mod package;pub mod refs;@@ -51,6 +52,7 @@ pub mod styles;pub mod text;mod xml;+pub use drawings::{CellAnchor, PicAnchor, SheetPic};pub use package::{SheetEntry, WorkbookPackage, walk};pub use refs::{CellRef, RangeRef, column_label, parse_cell, parse_column, parse_range};pub use sheet::{Cell, CellValue, ColInfo, Hyperlink, Row, Sheet, SheetStats};@@ -59,6 +61,7 @@ pub use text::{RichText, RunProps, TextRun, VertAlign, parse_shared_strings};use crate::docx::error::Result;use crate::docx::relationships::TargetMode;+use crate::docx::zip::{part_directory, resolve_target};/// A workbook read end to end.pub struct Workbook {@@ -89,7 +92,7 @@ pub struct Workbook {/// malformed is the fail-closed behaviour this vendor has already had to/// retire repeatedly.pub fn read(data: &[u8]) -> Result<Workbook> {- let pkg = walk(data)?;+ let mut pkg = walk(data)?;let shared_strings = match pkg.shared_strings_xml.as_deref() {Some(xml) => parse_shared_strings(xml).unwrap_or_else(|e| {@@ -111,6 +114,10 @@ pub fn read(data: &[u8]) -> Result<Workbook> {let mut sheets = Vec::new();let mut non_worksheet_sheets = Vec::new();+ // Pictures found while walking the sheets, resolved down to a media part+ // path. The bytes move out of the package afterwards, when the immutable+ // borrows this loop holds are gone.+ let mut pending_pics: Vec<(usize, drawings::PicAnchor, Option<String>, String)> = Vec::new();for entry in &pkg.sheets {if !entry.is_worksheet {non_worksheet_sheets.push(entry.name.clone());@@ -133,12 +140,77 @@ pub fn read(data: &[u8]) -> Result<Workbook> {.filter(|r| r.target_mode == TargetMode::External).map(|r| r.target.clone());}+ // The drawing part hangs off the same per-part rels; a+ // picture's `r:embed` then resolves against the *drawing's*+ // rels, one scope further down. Fail-open at every rung: a+ // broken drawing costs its pictures, never the sheet.+ if let Some(id) = s.drawing_rel_id.as_deref()+ && let Some(rel) = entry.rels.find_by_id(id)+ {+ let drawing_path = resolve_target(part_directory(&entry.path), &rel.target);+ if let Some(dxml) = pkg.package.get_part(&drawing_path) {+ match drawings::parse_drawing(dxml) {+ Ok(raws) if !raws.is_empty() => {+ let drels = package::load_rels(&pkg.package, &drawing_path);+ let ddir = part_directory(&drawing_path).to_string();+ for raw in raws {+ let Some(r) = drels+ .find_by_id(&raw.rel_id)+ .filter(|r| r.target_mode != TargetMode::External)+ else {+ continue;+ };+ pending_pics.push((+ sheets.len(),+ raw.anchor,+ raw.name,+ resolve_target(&ddir, &r.target),+ ));+ }+ }+ Ok(_) => {}+ Err(e) => {+ log::warn!("drawing part {drawing_path} failed to parse: {e}")+ }+ }+ }+ }sheets.push(s);}Err(e) => log::warn!("sheet {:?} failed to parse: {e}", entry.name),}}+ // Move each referenced media part out of the package exactly once; every+ // placement of the same part shares the one `Arc`, which is the identity+ // downstream dedup keys on.+ let mut media: std::collections::HashMap<String, std::sync::Arc<Vec<u8>>> =+ std::collections::HashMap::new();+ for (si, anchor, name, media_path) in pending_pics {+ let bytes = match media.get(&media_path) {+ Some(b) => b.clone(),+ None => match pkg.package.take_part(&media_path) {+ Some(b) => {+ let arc = std::sync::Arc::new(b);+ media.insert(media_path.clone(), arc.clone());+ arc+ }+ None => {+ log::warn!("picture media part missing: {media_path}");+ continue;+ }+ },+ };+ let format = crate::model::ImageFormat::detect(&media_path, &bytes);+ sheets[si].pics.push(drawings::SheetPic {+ anchor,+ name,+ media_path,+ format,+ bytes,+ });+ }+Ok(Workbook {sheets,shared_strings,@@ -375,6 +447,67 @@ mod tests {assert_eq!(links[1].location.as_deref(), Some("Sheet2!A1"));}+ /// End to end through the two rels scopes: sheet → drawing part via the+ /// sheet's rels, blip → media via the *drawing's* rels — and one media+ /// part referenced twice becomes one `Arc` shared by both placements.+ #[test]+ fn pictures_resolve_through_the_drawing_part_to_shared_media_bytes() {+ 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 sheet_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>+</Relationships>"#;+ let drawing = r#"<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">+ <xdr:oneCellAnchor>+ <xdr:from><xdr:col>2</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>3</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:ext cx="914400" cy="457200"/>+ <xdr:pic><xdr:nvPicPr><xdr:cNvPr id="2" name="Logo"/></xdr:nvPicPr><xdr:blipFill><a:blip r:embed="rId1"/></xdr:blipFill></xdr:pic>+ <xdr:clientData/>+ </xdr:oneCellAnchor>+ <xdr:oneCellAnchor>+ <xdr:from><xdr:col>5</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>9</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:ext cx="914400" cy="457200"/>+ <xdr:pic><xdr:nvPicPr><xdr:cNvPr id="3" name="Logo again"/></xdr:nvPicPr><xdr:blipFill><a:blip r:embed="rId1"/></xdr:blipFill></xdr:pic>+ <xdr:clientData/>+ </xdr:oneCellAnchor>+</xdr:wsDr>"#;+ let drawing_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image1.png"/>+</Relationships>"#;+ // A real PNG signature so `ImageFormat::detect`'s magic fallback also+ // has something honest to look at.+ let png = "\u{89}PNG-not-really-but-the-extension-decides";+ let wb = read(&build(&[+ ("[Content_Types].xml", "<Types/>"),+ ("_rels/.rels", ROOT_RELS),+ ("xl/workbook.xml", WORKBOOK),+ ("xl/_rels/workbook.xml.rels", WB_RELS),+ ("xl/worksheets/sheet1.xml", sheet),+ ("xl/worksheets/_rels/sheet1.xml.rels", sheet_rels),+ ("xl/drawings/drawing1.xml", drawing),+ ("xl/drawings/_rels/drawing1.xml.rels", drawing_rels),+ ("xl/media/image1.png", png),+ ]))+ .unwrap();+ let pics = &wb.sheets[0].pics;+ assert_eq!(pics.len(), 2);+ assert_eq!(pics[0].name.as_deref(), Some("Logo"));+ assert_eq!(pics[0].media_path, "xl/media/image1.png");+ assert_eq!(pics[0].format, crate::model::ImageFormat::Png);+ assert_eq!(pics[0].bytes.as_slice(), png.as_bytes());+ // One media part, one allocation: both placements share the Arc.+ assert!(std::sync::Arc::ptr_eq(&pics[0].bytes, &pics[1].bytes));+ assert_eq!(+ pics[1].anchor.from_cell().unwrap(),+ drawings::CellAnchor {+ col: 5,+ row: 9,+ ..Default::default()+ }+ );+ }+#[test]fn a_missing_workbook_part_is_the_one_fatal_error() {let data = build(&[diff --git a/crates/liteparse-ooxml/src/xlsx/package.rs b/crates/liteparse-ooxml/src/xlsx/package.rsindex 257a281..1f0030c 100644--- a/crates/liteparse-ooxml/src/xlsx/package.rs+++ b/crates/liteparse-ooxml/src/xlsx/package.rs@@ -121,7 +121,7 @@ pub fn walk(data: &[u8]) -> Result<WorkbookPackage> {})}-fn load_rels(package: &PackageContents, part_path: &str) -> Relationships {+pub(crate) fn load_rels(package: &PackageContents, part_path: &str) -> Relationships {let rels_path = if part_path.is_empty() {"_rels/.rels".to_string()} else {diff --git a/crates/liteparse-ooxml/src/xlsx/sheet.rs b/crates/liteparse-ooxml/src/xlsx/sheet.rsindex 15f7669..17d1b16 100644--- a/crates/liteparse-ooxml/src/xlsx/sheet.rs+++ b/crates/liteparse-ooxml/src/xlsx/sheet.rs@@ -147,6 +147,13 @@ pub struct Sheet {pub frozen_cols: u32,/// `<autoFilter ref=…>`, the other explicit header signal.pub auto_filter: Option<RangeRef>,+ /// `<drawing r:id>`: the sheet's DrawingML part, scoped to the sheet's+ /// own relationships. At most one per §18.3.1.36.+ pub drawing_rel_id: Option<String>,+ /// Pictures placed over the grid, resolved by [`crate::xlsx::read`] from+ /// the drawing part — empty until then, and empty for the 69% of corpus+ /// workbooks whose sheets draw nothing.+ pub pics: Vec<crate::xlsx::drawings::SheetPic>,pub stats: SheetStats,}@@ -322,6 +329,9 @@ pub fn parse(name: &str, visible: bool, data: &[u8]) -> Result<Sheet> {b"autoFilter" => {sheet.auto_filter = attr(e, b"ref").as_deref().and_then(parse_range);}+ b"drawing" => {+ sheet.drawing_rel_id = attr(e, b"r:id");+ }_ => {}}}diff --git a/crates/liteparse-python/Cargo.toml b/crates/liteparse-python/Cargo.tomlindex 8e62cff..499cdc0 100644--- a/crates/liteparse-python/Cargo.toml+++ b/crates/liteparse-python/Cargo.toml@@ -11,9 +11,11 @@ name = "_liteparse"crate-type = ["cdylib"][features]-default = ["tesseract", "docx-native"]+default = ["tesseract", "docx-native", "pptx-native", "xlsx-native"]tesseract = ["liteparse/tesseract"]docx-native = ["liteparse/docx-native"]+pptx-native = ["liteparse/pptx-native"]+xlsx-native = ["liteparse/xlsx-native"][dependencies]liteparse = { package = "liteparse", version = "2.11.0", path = "../liteparse", default-features = false }diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rsindex 9cc4989..73f0e44 100644--- a/crates/liteparse-python/src/cli.rs+++ b/crates/liteparse-python/src/cli.rs@@ -37,8 +37,8 @@ struct ParseCommand {format: String,#[arg(long)]no_ocr: bool,- /// Force the LibreOffice conversion path for DOCX instead of the native- /// parser.+ /// Force the LibreOffice conversion path for DOCX/PPTX/XLSX instead of+ /// the native parsers.#[arg(long)]no_office_native: bool,#[arg(long, default_value = "eng")]@@ -153,8 +153,8 @@ struct BatchParseCommand {format: String,#[arg(long)]no_ocr: bool,- /// Force the LibreOffice conversion path for DOCX instead of the native- /// parser.+ /// Force the LibreOffice conversion path for DOCX/PPTX/XLSX instead of+ /// the native parsers.#[arg(long)]no_office_native: bool,#[arg(long, default_value = "eng")]diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rsindex a74d906..9de9496 100644--- a/crates/liteparse-wasm/src/lib.rs+++ b/crates/liteparse-wasm/src/lib.rs@@ -59,7 +59,7 @@ pub struct LiteParseConfig {/// Keep running headers/footers in markdown output instead of stripping/// repeated page-band lines and page chrome. Default false.keep_headers_footers: Option<bool>,- /// Parse DOCX natively instead of converting via LibreOffice. Accepted+ /// Parse DOCX/PPTX/XLSX natively instead of converting via LibreOffice. Accepted/// and echoed for config round-trip parity; the native path is not/// compiled into the wasm build yet, so it has no effect here.office_native: Option<bool>,diff --git a/crates/liteparse/Cargo.toml b/crates/liteparse/Cargo.tomlindex e027747..da3c88a 100644--- a/crates/liteparse/Cargo.toml+++ b/crates/liteparse/Cargo.toml@@ -42,6 +42,10 @@ required-features = ["pptx-native"]name = "xlsx_emit"required-features = ["xlsx-native"]+[[example]]+name = "xlsx_pics_check"+required-features = ["xlsx-native"]+[[example]]name = "xlsx_layout_check"required-features = ["xlsx-native"]diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rsindex b74033b..dd905d9 100644--- a/crates/liteparse/src/config.rs+++ b/crates/liteparse/src/config.rs@@ -53,15 +53,15 @@ pub struct LiteParseConfig {/// downstream than risk losing content. Only affects Markdown output.#[serde(default)]pub keep_headers_footers: bool,- /// Parse DOCX natively (vendored layout engine) instead of converting via- /// LibreOffice. Default `true`; effective only when built with the- /// `docx-native` cargo feature and the input is a `.docx` — every other- /// format always takes the conversion path. Set `false` to force the- /// LibreOffice path (A/B comparison). The native path never runs OCR- /// (text is born digital; a text-sparse DOCX falls back to conversion so- /// scanned images still OCR), produces no screenshots, and falls back to- /// conversion for config it cannot honor (image/annotation/form/structure- /// extraction, crop, complexity).+ /// Parse DOCX/PPTX/XLSX natively (vendored readers + layout) instead of+ /// converting via LibreOffice. Default `true`; each format is gated by+ /// its cargo feature (`docx-native`, `pptx-native`, `xlsx-native`) and+ /// every other format always takes the conversion path. Set `false` to+ /// force the LibreOffice path (A/B comparison). The native paths never+ /// run OCR (text is born digital; a text-sparse document falls back to+ /// conversion so scanned images still OCR), produce no screenshots, and+ /// fall back to conversion for config they cannot honor (image/+ /// annotation/form/structure extraction, crop, complexity).#[serde(default = "default_true")]pub office_native: bool,/// Extract all PDF annotations into each parsed page. Default `false`.diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rsindex 504a71d..12bc397 100644--- a/crates/liteparse/src/main.rs+++ b/crates/liteparse/src/main.rs@@ -54,9 +54,9 @@ struct ParseCommand {#[arg(long)]no_ocr: bool,- /// Force the LibreOffice conversion path for DOCX instead of the native- /// parser (builds with the docx-native feature parse DOCX natively by- /// default)+ /// Force the LibreOffice conversion path for DOCX/PPTX/XLSX instead of+ /// the native parsers (builds with the docx-native/pptx-native/+ /// xlsx-native features parse those formats natively by default)#[arg(long)]no_office_native: bool,@@ -218,9 +218,9 @@ struct BatchParseCommand {#[arg(long)]no_ocr: bool,- /// Force the LibreOffice conversion path for DOCX instead of the native- /// parser (builds with the docx-native feature parse DOCX natively by- /// default)+ /// Force the LibreOffice conversion path for DOCX/PPTX/XLSX instead of+ /// the native parsers (builds with the docx-native/pptx-native/+ /// xlsx-native features parse those formats natively by default)#[arg(long)]no_office_native: bool,diff --git a/crates/liteparse/src/office/figures.rs b/crates/liteparse/src/office/figures.rsnew file mode 100644index 0000000..c6744da--- /dev/null+++ b/crates/liteparse/src/office/figures.rs@@ -0,0 +1,247 @@+//! The figure/image sink shared by the native office paths.+//!+//! Assigns figure ids and accumulates the bytes behind them, document-wide.+//! Grown in `office/pptx.rs` and moved here unchanged when the XLSX path+//! needed the same dedup; the id *scope* is the one generalization — PPTX+//! passes `p{page}` (a slide is a page), XLSX passes `s{sheet}` (a sheet's+//! pictures stay numbered together however its rows paginate).+//!+//! Ids follow the platform extractor's `{scope}_{n}` naming, 1-based, so+//! `img_{id}.{ext}` file names line up with the PDF and DOCX paths'.+//!+//! **`n` counts in reading order, not draw order.** Draw order is available —+//! it is source order — but using it would mean a second walk purely to+//! number things, and reading order is the order the `` refs appear in+//! the markdown, so a reader scanning down the page sees `_1` before `_2`.+//! The platform's caveat about index drift (its extractor increments even for+//! images it skips) already means these indices are names, not positions.++use std::collections::HashMap;++use liteparse_ooxml::model::ImageFormat;++use crate::types::{ExtractedImage, Rect};++#[derive(Default)]+pub(crate) struct FigureSink {+ pub(crate) images: Vec<ExtractedImage>,+ /// Same source allocation ⇒ same bytes. Free dedup for the repeated-logo+ /// case — on the PPTX corpus, 3,602 placements behind 1,322 distinct+ /// images — because both readers pool media bytes per package path, so a+ /// part referenced twice shares one buffer and hits here rather than in+ /// the hash map below.+ by_ptr: HashMap<usize, usize>,+ /// Distinct rels can still hold identical bytes; hash → candidate+ /// canonical indices, confirmed by full compare like the DOCX path's.+ by_hash: HashMap<u64, Vec<usize>>,+ /// 1-based within the current scope, reset by+ /// [`FigureSink::reset_ordinal`].+ n: u32,+}++impl FigureSink {+ /// Restart `n` — at each slide for PPTX, each sheet for XLSX.+ pub(crate) fn reset_ordinal(&mut self) {+ self.n = 0;+ }++ /// Record one placed picture and return the `(id, extension)` its+ /// `Block::Figure` should carry, or `None` for media we do not surface+ /// bytes for (EMF/WMF/SVG with no raster fallback), which then consumes+ /// no id — a ref numbered around skipped media would name a file nothing+ /// writes.+ pub(crate) fn place(+ &mut self,+ data: &[u8],+ format: ImageFormat,+ scope: &str,+ page: u32,+ bbox: Rect,+ ) -> Option<(String, String)> {+ use std::hash::{Hash, Hasher};++ let ext = super::docx_layout::media_extension(format)?;+ self.n += 1;+ let id = format!("{scope}_{}", self.n);+ let ptr = data.as_ptr() as usize;++ let canonical = self.by_ptr.get(&ptr).copied().or_else(|| {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ data.hash(&mut h);+ self.by_hash+ .get(&h.finish())?+ .iter()+ .copied()+ .find(|&i| *self.images[i].bytes == *data)+ });++ let entry = match canonical {+ Some(ci) => {+ let canonical = &self.images[ci];+ ExtractedImage {+ id: id.clone(),+ name: format!("img_{id}.{ext}"),+ path: None,+ page,+ bbox,+ width: canonical.width,+ height: canonical.height,+ rotation: 0.0,+ format: ext.to_string(),+ duplicate_of: Some(canonical.id.clone()),+ bytes: std::sync::Arc::clone(&canonical.bytes),+ }+ }+ None => {+ let bytes = std::sync::Arc::new(data.to_vec());+ // The *natural* size of the image, not the placed box —+ // `bbox` already carries the placement. A crop is not applied+ // to either: `src_rect` describes a visible sub-rectangle the+ // bytes still contain, and 44% of PPTX corpus pictures+ // declare one, so re-encoding to honour it would re-encode+ // nearly half the corpus to change a number no consumer+ // reads.+ let (width, height) =+ image::ImageReader::new(std::io::Cursor::new(bytes.as_slice()))+ .with_guessed_format()+ .ok()+ .and_then(|r| r.into_dimensions().ok())+ .unwrap_or((0, 0));+ let mut h = std::collections::hash_map::DefaultHasher::new();+ data.hash(&mut h);+ self.by_hash+ .entry(h.finish())+ .or_default()+ .push(self.images.len());+ self.by_ptr.insert(ptr, self.images.len());+ ExtractedImage {+ id: id.clone(),+ name: format!("img_{id}.{ext}"),+ path: None,+ page,+ bbox,+ width,+ height,+ rotation: 0.0,+ format: ext.to_string(),+ duplicate_of: None,+ bytes,+ }+ }+ };+ self.images.push(entry);+ Some((id, ext.to_string()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rect() -> Rect {+ Rect {+ x: 1.0,+ y: 2.0,+ width: 3.0,+ height: 4.0,+ }+ }++ /// A 1x1 PNG, so `image::ImageReader` reports real dimensions.+ fn png() -> Vec<u8> {+ vec![+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,+ 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,+ 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,+ 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,+ 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,+ ]+ }++ /// Ids are `{scope}_{n}`, 1-based on both halves and restarted per scope,+ /// so they line up with the platform extractor's and the PDF path's.+ #[test]+ fn figure_ids_are_scope_local_and_one_based() {+ let mut sink = FigureSink::default();+ let a = png();+ let b = {+ let mut v = png();+ v.extend_from_slice(&[0u8; 4]);+ v+ };+ sink.reset_ordinal();+ let place = |s: &mut FigureSink, d: &[u8], scope: &str, page| {+ s.place(d, ImageFormat::Png, scope, page, rect())+ };+ assert_eq!(place(&mut sink, &a, "p1", 1).unwrap().0, "p1_1");+ assert_eq!(place(&mut sink, &b, "p1", 1).unwrap().0, "p1_2");+ sink.reset_ordinal();+ assert_eq!(place(&mut sink, &b, "p2", 2).unwrap().0, "p2_1");+ }++ /// The repeated-logo case: every placement keeps its own name, and all+ /// but the first point at one canonical entry's bytes.+ #[test]+ fn a_repeated_picture_collapses_onto_one_canonical_entry() {+ let mut sink = FigureSink::default();+ let logo = png();+ for page in 1..=3u32 {+ sink.reset_ordinal();+ sink.place(&logo, ImageFormat::Png, &format!("p{page}"), page, rect())+ .expect("placed");+ }+ assert_eq!(sink.images.len(), 3, "one entry per placement");+ assert_eq!(sink.images[0].duplicate_of, None);+ assert_eq!(+ sink.images[1].duplicate_of.as_deref(),+ Some("p1_1"),+ "later placements name the canonical id"+ );+ assert_eq!(sink.images[2].duplicate_of.as_deref(), Some("p1_1"));+ // Distinct names, shared bytes — the platform's contract exactly.+ assert_eq!(sink.images[1].name, "img_p2_1.png");+ assert!(std::sync::Arc::ptr_eq(+ &sink.images[0].bytes,+ &sink.images[2].bytes+ ));+ }++ /// Two *different* source buffers can hold identical bytes — a logo+ /// pasted into a slide and into its master. The pointers differ, so only+ /// the content hash catches this one.+ #[test]+ fn identical_bytes_behind_different_buffers_still_dedupe() {+ let mut sink = FigureSink::default();+ let one = png();+ let two = png();+ assert_ne!(one.as_ptr(), two.as_ptr(), "distinct allocations");+ sink.reset_ordinal();+ sink.place(&one, ImageFormat::Png, "p1", 1, rect())+ .expect("placed");+ sink.place(&two, ImageFormat::Png, "p1", 1, rect())+ .expect("placed");+ assert_eq!(sink.images[1].duplicate_of.as_deref(), Some("p1_1"));+ }++ /// Media we do not surface bytes for is not a figure and does not consume+ /// an id — EMF references and SVG-only blips land here, and a ref+ /// numbered around them would name a file nothing writes.+ #[test]+ fn media_we_cannot_surface_takes_no_id() {+ let mut sink = FigureSink::default();+ let bytes = png();+ sink.reset_ordinal();+ assert!(+ sink.place(&bytes, ImageFormat::Emf, "p1", 1, rect())+ .is_none()+ );+ assert!(sink.images.is_empty());+ // The next real picture is still `_1`.+ assert_eq!(+ sink.place(&bytes, ImageFormat::Png, "p1", 1, rect())+ .unwrap()+ .0,+ "p1_1"+ );+ }+}diff --git a/crates/liteparse/src/office/mod.rs b/crates/liteparse/src/office/mod.rsindex ae2d910..d10eb84 100644--- a/crates/liteparse/src/office/mod.rs+++ b/crates/liteparse/src/office/mod.rs@@ -19,6 +19,8 @@ pub mod docx;#[cfg(feature = "office-native")]pub mod docx_layout;#[cfg(feature = "office-native")]+pub(crate) mod figures;+#[cfg(feature = "office-native")]pub(crate) mod inline;#[cfg(feature = "pptx-native")]pub mod pptx;diff --git a/crates/liteparse/src/office/pptx.rs b/crates/liteparse/src/office/pptx.rsindex d3c127f..cb8df6e 100644--- a/crates/liteparse/src/office/pptx.rs+++ b/crates/liteparse/src/office/pptx.rs@@ -26,6 +26,7 @@ use std::collections::HashMap;use crate::error::LiteParseError;use crate::markdown_layout::{Block, Cell};+use crate::office::figures::FigureSink;use crate::office::inline::{Chunk, Fmt, render_chunks};use crate::types::{ExtractedImage, Rect};@@ -556,7 +557,7 @@ impl Deck {let Some(prepared) = self.prepare(pkg, slide) else {continue;};- figures.start_slide();+ figures.reset_ordinal();let mut ctx = SlideCtx {cascade: prepared.cascade(),part: &slide.slide,@@ -709,125 +710,6 @@ fn inherited_shapes(shapes: &[Shape]) -> Vec<Shape> {// ── figures ─────────────────────────────────────────────────────────────────-/// Assigns figure ids and accumulates the bytes behind them, deck-wide.-///-/// Ids follow the platform extractor's `p{page}_{n}` naming, 1-based on both-/// halves, so `img_{id}.{ext}` file names line up with the PDF and DOCX paths'.-/// A slide *is* a page, so `page` is intrinsic here rather than recovered.-///-/// **`n` counts in reading order, not draw order**, which is the one place this-/// diverges from its siblings. Draw order is available — it is source order —-/// but using it would mean a second walk purely to number things, and reading-/// order is the order the `` refs appear in the markdown, so a reader-/// scanning down the page sees `_1` before `_2`. The platform's caveat about-/// index drift (its extractor increments even for images it skips) already-/// means these indices are names, not positions.-#[derive(Default)]-struct FigureSink {- images: Vec<ExtractedImage>,- /// Same media `Arc` ⇒ same bytes. Free dedup for the repeated-logo case,- /// which on this corpus is 3,602 placements behind 1,322 distinct images —- /// and `MediaCache` pools bytes by package path, so a logo a slide and its- /// master both reference is one allocation and hits here rather than in- /// the hash map below.- by_ptr: HashMap<usize, usize>,- /// Distinct rels can still hold identical bytes; hash → candidate- /// canonical indices, confirmed by full compare like the DOCX path's.- by_hash: HashMap<u64, Vec<usize>>,- /// 1-based within the current slide, reset by [`FigureSink::start_slide`].- n: u32,-}--impl FigureSink {- fn start_slide(&mut self) {- self.n = 0;- }-- /// Record one placed picture and return the `(id, extension)` its- /// `Block::Figure` should carry, or `None` for media we do not surface- /// bytes for — the 29 corpus EMF references and the 154 SVG-only blips,- /// which have no raster fallback anywhere in the package.- fn place(- &mut self,- blip: &liteparse_ooxml::render::layout::draw_command::ResolvedBlip,- page: u32,- bbox: Rect,- ) -> Option<(String, String)> {- use std::hash::{Hash, Hasher};-- let ext = super::docx_layout::media_extension(blip.format)?;- self.n += 1;- let id = format!("p{page}_{}", self.n);- let ptr = blip.data.as_ptr() as usize;-- let canonical = self.by_ptr.get(&ptr).copied().or_else(|| {- let mut h = std::collections::hash_map::DefaultHasher::new();- blip.data.hash(&mut h);- self.by_hash- .get(&h.finish())?- .iter()- .copied()- .find(|&i| *self.images[i].bytes == *blip.data)- });-- let entry = match canonical {- Some(ci) => {- let canonical = &self.images[ci];- ExtractedImage {- id: id.clone(),- name: format!("img_{id}.{ext}"),- path: None,- page,- bbox,- width: canonical.width,- height: canonical.height,- rotation: 0.0,- format: ext.to_string(),- duplicate_of: Some(canonical.id.clone()),- bytes: std::sync::Arc::clone(&canonical.bytes),- }- }- None => {- let bytes = std::sync::Arc::new(blip.data.to_vec());- // The *natural* size of the image, not the placed box —- // `bbox` already carries the placement. A crop is not applied- // to either: `src_rect` describes a visible sub-rectangle the- // bytes still contain, and 44% of corpus pictures declare one,- // so re-encoding to honour it would re-encode nearly half the- // corpus to change a number no consumer reads.- let (width, height) =- image::ImageReader::new(std::io::Cursor::new(bytes.as_slice()))- .with_guessed_format()- .ok()- .and_then(|r| r.into_dimensions().ok())- .unwrap_or((0, 0));- let mut h = std::collections::hash_map::DefaultHasher::new();- blip.data.hash(&mut h);- self.by_hash- .entry(h.finish())- .or_default()- .push(self.images.len());- self.by_ptr.insert(ptr, self.images.len());- ExtractedImage {- id: id.clone(),- name: format!("img_{id}.{ext}"),- path: None,- page,- bbox,- width,- height,- rotation: 0.0,- format: ext.to_string(),- duplicate_of: None,- bytes,- }- }- };- self.images.push(entry);- Some((id, ext.to_string()))- }-}-/// The blip fill a shape carries as its *picture*, if it is one.////// Two shapes qualify and the second is the one the census had to find:@@ -1184,7 +1066,13 @@ fn emit_figure(width: emu_to_pt(box_.size.width.raw()),height: emu_to_pt(box_.size.height.raw()),};- let Some((id, format)) = ctx.figures.place(&blip, ctx.page, bbox) else {+ let Some((id, format)) = ctx.figures.place(+ &blip.data,+ blip.format,+ &format!("p{}", ctx.page),+ ctx.page,+ bbox,+ ) else {return;};if ctx.opts.figures {@@ -1915,111 +1803,6 @@ mod tests {assert!(picture_fill(&shapes[0]).is_none());}- fn blip(bytes: &std::sync::Arc<[u8]>) -> ResolvedBlipFor {- liteparse_ooxml::render::layout::draw_command::ResolvedBlip {- data: std::sync::Arc::clone(bytes),- format: liteparse_ooxml::model::ImageFormat::Png,- src_rect: None,- }- }- type ResolvedBlipFor = liteparse_ooxml::render::layout::draw_command::ResolvedBlip;-- /// A 1x1 PNG, so `image::ImageReader` reports real dimensions.- fn png() -> Vec<u8> {- vec![- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,- 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,- 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,- 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,- 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,- ]- }-- fn rect() -> Rect {- Rect {- x: 1.0,- y: 2.0,- width: 3.0,- height: 4.0,- }- }-- /// Ids are `p{page}_{n}`, 1-based on both halves and restarted per slide,- /// so they line up with the platform extractor's and the PDF path's.- #[test]- fn figure_ids_are_page_scoped_and_one_based() {- let mut sink = FigureSink::default();- let a: std::sync::Arc<[u8]> = png().into();- let b: std::sync::Arc<[u8]> = {- let mut v = png();- v.extend_from_slice(&[0u8; 4]);- v.into()- };- sink.start_slide();- assert_eq!(sink.place(&blip(&a), 1, rect()).unwrap().0, "p1_1");- assert_eq!(sink.place(&blip(&b), 1, rect()).unwrap().0, "p1_2");- sink.start_slide();- assert_eq!(sink.place(&blip(&b), 2, rect()).unwrap().0, "p2_1");- }-- /// The repeated-logo case, which is what makes emitting a master's picture- /// on all 47 of its slides affordable: every placement keeps its own name,- /// and all but the first point at one canonical entry's bytes.- #[test]- fn a_repeated_picture_collapses_onto_one_canonical_entry() {- let mut sink = FigureSink::default();- let logo: std::sync::Arc<[u8]> = png().into();- for page in 1..=3 {- sink.start_slide();- sink.place(&blip(&logo), page, rect()).expect("placed");- }- assert_eq!(sink.images.len(), 3, "one entry per placement");- assert_eq!(sink.images[0].duplicate_of, None);- assert_eq!(- sink.images[1].duplicate_of.as_deref(),- Some("p1_1"),- "later placements name the canonical id"- );- assert_eq!(sink.images[2].duplicate_of.as_deref(), Some("p1_1"));- // Distinct names, shared bytes — the platform's contract exactly.- assert_eq!(sink.images[1].name, "img_p2_1.png");- assert!(std::sync::Arc::ptr_eq(- &sink.images[0].bytes,- &sink.images[2].bytes- ));- }-- /// Two *different* relationships can hold identical bytes — a logo the- /// author pasted into the slide and into the master. The `Arc` pointers- /// differ, so only the content hash catches this one.- #[test]- fn identical_bytes_behind_different_rels_still_dedupe() {- let mut sink = FigureSink::default();- let one: std::sync::Arc<[u8]> = png().into();- let two: std::sync::Arc<[u8]> = png().into();- assert!(!std::sync::Arc::ptr_eq(&one, &two), "distinct allocations");- sink.start_slide();- sink.place(&blip(&one), 1, rect()).expect("placed");- sink.place(&blip(&two), 1, rect()).expect("placed");- assert_eq!(sink.images[1].duplicate_of.as_deref(), Some("p1_1"));- }-- /// Media we do not surface bytes for is not a figure and does not consume- /// an id — 29 corpus EMF references and 154 SVG-only blips land here, and- /// a ref numbered around them would name a file nothing writes.- #[test]- fn media_we_cannot_surface_takes_no_id() {- let mut sink = FigureSink::default();- let emf: std::sync::Arc<[u8]> = png().into();- sink.start_slide();- let mut b = blip(&emf);- b.format = liteparse_ooxml::model::ImageFormat::Emf;- assert!(sink.place(&b, 1, rect()).is_none());- assert!(sink.images.is_empty());- // The next real picture is still `_1`.- assert_eq!(sink.place(&blip(&emf), 1, rect()).unwrap().0, "p1_1");- }-/// A rung's pictures reach the reading order, and they arrive flagged as/// figures — `inherited_text_laid_out` keys on that flag, so a picture/// counted as inherited *text* would corrupt the metric that step's A/Bdiff --git a/crates/liteparse/src/office/xlsx.rs b/crates/liteparse/src/office/xlsx.rsindex b9ae7be..e349649 100644--- a/crates/liteparse/src/office/xlsx.rs+++ b/crates/liteparse/src/office/xlsx.rs@@ -41,7 +41,7 @@use std::collections::HashMap;use std::ops::Range;-use liteparse_ooxml::xlsx::{self, Cell as GridCell, CellValue, Row, Sheet, Workbook};+use liteparse_ooxml::xlsx::{self, Cell as GridCell, CellValue, Row, Sheet, SheetPic, Workbook};use crate::error::LiteParseError;use crate::markdown_layout::{Block, Cell, apply_link, escape_inline};@@ -67,6 +67,13 @@ pub struct EmitOptions {/// Render external hyperlinks as `[text](url)` on the cell the link/// anchors to. Mirrors `LiteParseConfig::extract_links`.pub links: bool,+ /// Emit `Block::Figure` refs for the sheet's pictures. Mirrors the PDF,+ /// DOCX and PPTX paths' `image_mode != Off`.+ pub figures: bool,+ /// Collect picture bytes as `ExtractedImage`s. Read by the geometry pass+ /// (`xlsx_layout`), which is where pages — and so image ids' page+ /// numbers — exist; the block emitter ignores it.+ pub images: bool,}/// What one native-parsed workbook yields: the block stream, tagged with the@@ -121,6 +128,11 @@ pub fn emit_workbook(wb: &Workbook, opts: EmitOptions) -> NativeWorkbook {}}}+ if opts.figures {+ for b in figure_blocks(sheet, si) {+ blocks.push((b, si));+ }+ }}NativeWorkbook {blocks,@@ -128,6 +140,46 @@ pub fn emit_workbook(wb: &Workbook, opts: EmitOptions) -> NativeWorkbook {}}+/// A sheet's pictures in reading order — sorted by anchor cell, top-left+/// first, with the (single corpus) absolute anchor sorting after every cell+/// anchor. This order is the id order: the geometry pass numbers+/// `s{sheet}_{n}` walking the same list, so a `` ref and its+/// `ExtractedImage` cannot disagree.+pub(crate) fn ordered_pics(sheet: &Sheet) -> Vec<&SheetPic> {+ let mut pics: Vec<&SheetPic> = sheet.pics.iter().collect();+ pics.sort_by_key(|p| match p.anchor.from_cell() {+ Some(c) => (c.row as i64, c.col as i64, c.row_off_emu, c.col_off_emu),+ None => match p.anchor {+ xlsx::PicAnchor::Absolute { pos_emu, .. } => (i64::MAX, pos_emu.1, pos_emu.0, 0),+ _ => unreachable!("from_cell is None only for Absolute"),+ },+ });+ pics+}++/// The `Block::Figure` refs for a sheet's pictures, in [`ordered_pics`]+/// order. Emitted after the sheet's table: the pictures float *over* the+/// grid, so any interleaving with specific rows would be false precision —+/// and it keeps the doc emitter geometry-free.+///+/// Media the platform does not surface (EMF, SVG with no raster fallback)+/// takes no ref and no id, matching `FigureSink::place`.+pub(crate) fn figure_blocks(sheet: &Sheet, sheet_index: usize) -> Vec<Block> {+ let mut out = Vec::new();+ let mut n = 0u32;+ for pic in ordered_pics(sheet) {+ let Some(ext) = super::docx_layout::media_extension(pic.format) else {+ continue;+ };+ n += 1;+ out.push(Block::Figure {+ id: format!("s{}_{n}", sheet_index + 1),+ format: ext.to_string(),+ });+ }+ out+}+/// A merge's place in the emitted grid: spans counted over *emitted* rows and/// *retained* columns, so a merge across skipped-empty rows does not claim/// table rows that do not exist.@@ -925,7 +977,13 @@ pub(crate) mod tests {<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/></Relationships>"#;let wb = workbook_from(sheet, &[("xl/worksheets/_rels/sheet1.xml.rels", rels)]);- let with = emit_workbook(&wb, EmitOptions { links: true });+ let with = emit_workbook(+ &wb,+ EmitOptions {+ links: true,+ ..Default::default()+ },+ );let without = emit_workbook(&wb, EmitOptions::default());let cell = |nw: &NativeWorkbook| match &nw.blocks[1].0 {Block::MergedTable { rows, .. } => rows[0][0].text.clone(),diff --git a/crates/liteparse/src/office/xlsx_layout.rs b/crates/liteparse/src/office/xlsx_layout.rsindex 17bbd82..251ada0 100644--- a/crates/liteparse/src/office/xlsx_layout.rs+++ b/crates/liteparse/src/office/xlsx_layout.rs@@ -33,11 +33,12 @@use std::ops::Range;-use liteparse_ooxml::xlsx::{Sheet, Workbook};+use liteparse_ooxml::xlsx::{CellAnchor, PicAnchor, Sheet, Workbook};+use super::figures::FigureSink;use super::xlsx::{EmitOptions, SHEET_HEADING_LEVEL, SheetPlan};use crate::markdown_layout::{Block, escape_inline};-use crate::types::{OutlineTarget, Page, Rect, TextItem};+use crate::types::{ExtractedImage, OutlineTarget, Page, Rect, TextItem};/// The write-side constants from rust_xlsxwriter: Calibri 11's max digit/// width is 7 px at 96 DPI, plus 5 px of cell padding.@@ -77,6 +78,77 @@ pub struct NativeXlsx {/// One level-1 entry per sheet at its first page, matching the emitter's/// heading rank.pub outline: Vec<OutlineTarget>,+ /// Extracted picture bytes, populated only under `EmitOptions::images`.+ /// Ids are `s{sheet}_{n}` in [`super::xlsx::ordered_pics`] order, the+ /// same numbering the `Block::Figure` refs carry.+ pub images: Vec<ExtractedImage>,+ /// Per-page picture rectangles, aligned with `pages` — the media-rect+ /// input to page complexity, computed whether or not images were asked+ /// for (a rectangle costs no byte copies).+ pub pic_rects: Vec<Vec<Rect>>,+}++/// EMU → points: 914,400 EMU to the inch, 72 points to the inch.+fn emu_pt(v: i64) -> f64 {+ v as f64 / 12_700.0+}++/// The *declared* grid, for measuring picture extents: every column and row+/// the sheet addresses, written or not, at its declared (or default) size.+/// Row sums are arithmetic over a map of explicit heights — never an+/// iteration over the span, which the row-1,048,576 stray cell would turn+/// into a hang.+struct CanvasGrid<'a> {+ sheet: &'a Sheet,+ /// Rows with an explicit `ht`, by index.+ explicit_rows: std::collections::BTreeMap<u32, f64>,+ default_row_h: f64,+}++impl<'a> CanvasGrid<'a> {+ fn build(sheet: &'a Sheet) -> Self {+ CanvasGrid {+ sheet,+ explicit_rows: sheet+ .rows+ .iter()+ .filter_map(|r| r.height.map(|h| (r.index, h.max(0.0))))+ .collect(),+ default_row_h: sheet.default_row_height.unwrap_or(DEFAULT_ROW_HEIGHT_PT),+ }+ }++ /// Canvas width between two anchor corners, in points.+ fn col_span(&self, from: CellAnchor, to: CellAnchor) -> f64 {+ // Columns are bounded at 16,384 (§18.17.2), so direct iteration is+ // safe; a malformed `to` past the bound is clamped.+ let hi = to.col.min(16_384);+ let mut w = 0.0;+ for c in from.col..hi {+ w += col_px(+ self.sheet+ .col_width(c)+ .unwrap_or(DEFAULT_COL_WIDTH)+ .max(0.0),+ ) * PX_TO_PT;+ }+ w - emu_pt(from.col_off_emu).max(0.0) + emu_pt(to.col_off_emu).max(0.0)+ }++ /// Canvas height between two anchor corners, in points.+ fn row_span(&self, from: CellAnchor, to: CellAnchor) -> f64 {+ if to.row <= from.row {+ return emu_pt(to.row_off_emu - from.row_off_emu);+ }+ let (mut sum, mut counted) = (0.0, 0u64);+ for (_, h) in self.explicit_rows.range(from.row..to.row) {+ sum += h;+ counted += 1;+ }+ let n = u64::from(to.row - from.row);+ sum += (n - counted) as f64 * self.default_row_h;+ sum - emu_pt(from.row_off_emu).max(0.0) + emu_pt(to.row_off_emu).max(0.0)+ }}/// Excel width units → pixels, the xlsxwriter algorithm: sub-unit widths@@ -97,9 +169,15 @@ pub fn workbook_to_pages(wb: &Workbook, opts: EmitOptions) -> NativeXlsx {page_blocks: Vec::new(),all_blocks: Vec::new(),outline: Vec::new(),+ images: Vec::new(),+ pic_rects: Vec::new(),};+ // One sink across the workbook: a logo placed on every sheet dedups to+ // one canonical entry, the same cross-page rule the PPTX path applies+ // across slides.+ let mut sink = FigureSink::default();- for sheet in &wb.sheets {+ for (si, sheet) in wb.sheets.iter().enumerate() {let heading = Block::Heading {level: SHEET_HEADING_LEVEL,text: escape_inline(&sheet.name),@@ -112,29 +190,109 @@ pub fn workbook_to_pages(wb: &Workbook, opts: EmitOptions) -> NativeXlsx {});out.all_blocks.push(heading.clone());- let Some(plan) = SheetPlan::build(wb, sheet, opts) else {- out.pages.push(empty_page(out.pages.len() + 1));- out.page_blocks.push(vec![heading]);- continue;- };-- // Doc-level: the unsplit emission (one full-range slice).- let n = plan.rows.len();- for page in plan.page_blocks(wb, &[0..n]) {- out.all_blocks.extend(page);+ let plan = SheetPlan::build(wb, sheet, opts);+ // A sheet with no written cells still needs geometry when it draws+ // pictures — the image-only sheet is exactly the `extract_images`+ // case — so the plan-less path gets an empty grid rather than a+ // bail-out: every anchor collapses to the page origin and the+ // picture's own extent survives.+ let (geo, ranges, row_indices, cols): (SheetGeometry, Vec<Range<usize>>, Vec<u32>, &[u32]) =+ match &plan {+ Some(p) => {+ let geo = SheetGeometry::build(sheet, p);+ let ranges = geo.page_ranges();+ let rows: Vec<u32> = p.rows.iter().map(|(r, _)| r.index).collect();+ (geo, ranges, rows, &p.cols)+ }+ None => (+ SheetGeometry {+ x_off: vec![0.0],+ y_off: vec![0.0],+ },+ vec![0..0],+ Vec::new(),+ &[],+ ),+ };++ // Doc-level: the unsplit emission (one full-range slice), then the+ // sheet's figures — the same order `emit_workbook` writes, so the+ // two doc emissions stay byte-identical.+ if let Some(p) = &plan {+ let n = p.rows.len();+ for page in p.page_blocks(wb, &[0..n]) {+ out.all_blocks.extend(page);+ }+ }+ if opts.figures {+ out.all_blocks.extend(super::xlsx::figure_blocks(sheet, si));}- let geo = SheetGeometry::build(sheet, &plan);- let ranges = geo.page_ranges();- let mut blocks_per_page = plan.page_blocks(wb, &ranges);+ let mut blocks_per_page: Vec<Vec<Block>> = match &plan {+ Some(p) => p.page_blocks(wb, &ranges),+ None => vec![Vec::new()],+ };blocks_per_page[0].insert(0, heading);- for (range, blocks) in ranges.into_iter().zip(blocks_per_page) {- let page = geo.build_page(wb, &plan, range, out.pages.len() + 1);+ // Pictures: page assignment + rect from the packed grid, figure+ // blocks on the page the anchor lands on, bytes into the sink. The+ // local ordinal mirrors `figure_blocks` (both skip media we do not+ // surface), and the sink's id must agree with it by construction.+ let grid_w = *geo.x_off.last().unwrap() as f32;+ let page_width = (grid_w + 2.0 * MARGIN).max(MIN_PAGE_WIDTH);+ let mut rects_per_page: Vec<Vec<Rect>> = vec![Vec::new(); ranges.len()];+ let canvas = CanvasGrid::build(sheet);+ sink.reset_ordinal();+ let mut n_fig = 0u32;+ for pic in super::xlsx::ordered_pics(sheet) {+ let Some(ext) = super::docx_layout::media_extension(pic.format) else {+ continue;+ };+ n_fig += 1;+ let id = format!("s{}_{n_fig}", si + 1);+ let (page_local, rect) = geo.place_pic(+ cols,+ &row_indices,+ &ranges,+ page_width,+ &canvas,+ &pic.anchor,+ );+ rects_per_page[page_local].push(rect.clone());+ if opts.figures {+ blocks_per_page[page_local].push(Block::Figure {+ id: id.clone(),+ format: ext.to_string(),+ });+ }+ if opts.images {+ let page_number = (out.pages.len() + 1 + page_local) as u32;+ let placed = sink.place(+ &pic.bytes,+ pic.format,+ &format!("s{}", si + 1),+ page_number,+ rect,+ );+ debug_assert_eq!(+ placed.as_ref().map(|(i, _)| i.as_str()),+ Some(id.as_str()),+ "figure ref and image entry numbered apart"+ );+ }+ }++ for (i, blocks) in blocks_per_page.into_iter().enumerate() {+ let page = match &plan {+ Some(p) => geo.build_page(wb, p, ranges[i].clone(), out.pages.len() + 1),+ None => empty_page(out.pages.len() + 1),+ };out.pages.push(page);out.page_blocks.push(blocks);+ out.pic_rects.push(std::mem::take(&mut rects_per_page[i]));}}+ out.images = sink.images;out}@@ -194,6 +352,99 @@ impl SheetGeometry {self.y_off[i + 1] - self.y_off[i]}+ /// A cell-anchor corner in packed-grid points. A retained column /+ /// emitted row keeps its EMU offset (clamped inside the cell); an anchor+ /// on a compacted column or unwritten row collapses to the boundary+ /// where the packed grid resumes, and the offset — which measures into+ /// space the packed grid does not have — is dropped.+ fn corner_pt(&self, cols: &[u32], row_indices: &[u32], c: CellAnchor) -> (f64, f64) {+ let ci = cols.partition_point(|&x| x < c.col);+ let x = if ci < cols.len() && cols[ci] == c.col {+ let w = self.x_off[ci + 1] - self.x_off[ci];+ self.x_off[ci] + emu_pt(c.col_off_emu).clamp(0.0, w)+ } else {+ self.x_off[ci]+ };+ let ri = row_indices.partition_point(|&r| r < c.row);+ let y = if ri < row_indices.len() && row_indices[ri] == c.row {+ let h = self.y_off[ri + 1] - self.y_off[ri];+ self.y_off[ri] + emu_pt(c.row_off_emu).clamp(0.0, h)+ } else {+ self.y_off[ri]+ };+ (x, y)+ }++ /// Where a picture lands: the local page index within `ranges` plus its+ /// rect on that page, clamped into the page box. The page is the one+ /// whose rows contain the picture's *top* edge — a picture crossing the+ /// break truncates at its anchor page's bottom, the merge-item precedent+ /// — and the page's width stays the text grid's, so a picture hanging+ /// past it truncates at the right edge rather than growing every item's+ /// page.+ ///+ /// Position is packed, **extent is canvas**: a two-cell anchor's corners+ /// are measured over the *declared* grid (`canvas`), because the corpus+ /// says the packed difference is a lie — 818 of 2,126 pictures anchor+ /// across rows or columns the packed grid does not have (a logo floating+ /// right of the data, a photo below the table) and collapse to 1 pt+ /// slivers under a packed reading. The top-left still snaps to the+ /// packed corner so the picture sits next to the text it belongs with.+ fn place_pic(+ &self,+ cols: &[u32],+ row_indices: &[u32],+ ranges: &[Range<usize>],+ page_width: f32,+ canvas: &CanvasGrid<'_>,+ anchor: &PicAnchor,+ ) -> (usize, Rect) {+ let (gx, gy, gw, gh) = match *anchor {+ PicAnchor::OneCell { from, ext_emu } => {+ let (x, y) = self.corner_pt(cols, row_indices, from);+ (x, y, emu_pt(ext_emu.0).max(1.0), emu_pt(ext_emu.1).max(1.0))+ }+ PicAnchor::TwoCell { from, to } => {+ let (x0, y0) = self.corner_pt(cols, row_indices, from);+ (+ x0,+ y0,+ canvas.col_span(from, to).max(1.0),+ canvas.row_span(from, to).max(1.0),+ )+ }+ PicAnchor::Absolute { pos_emu, ext_emu } => (+ emu_pt(pos_emu.0).max(0.0),+ emu_pt(pos_emu.1).max(0.0),+ emu_pt(ext_emu.0).max(1.0),+ emu_pt(ext_emu.1).max(1.0),+ ),+ };+ let mut page = 0;+ for (i, r) in ranges.iter().enumerate() {+ if self.y_off[r.start] <= gy {+ page = i;+ } else {+ break;+ }+ }+ let y_base = self.y_off[ranges[page].start];+ let usable_w = (page_width - 2.0 * MARGIN) as f64;+ let x_rel = gx.max(0.0).min(usable_w - 1.0);+ let w = gw.min(usable_w - x_rel).max(1.0);+ let y_rel = (gy - y_base).max(0.0).min(USABLE_HEIGHT - 1.0);+ let h = gh.min(USABLE_HEIGHT - y_rel).max(1.0);+ (+ page,+ Rect {+ x: (f64::from(MARGIN) + x_rel) as f32,+ y: (f64::from(MARGIN) + y_rel) as f32,+ width: w as f32,+ height: h as f32,+ },+ )+ }+/// Greedy pagination over emitted rows: break before the row that would/// overflow the page, never breaking an empty page (a row taller than/// the page — the corpus max is 410 pt — gets a page to itself).@@ -496,7 +747,13 @@ mod tests {<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://example.com" TargetMode="External"/></Relationships>"#;let wb = workbook_from(sheet, &[("xl/worksheets/_rels/sheet1.xml.rels", rels)]);- let nx = workbook_to_pages(&wb, EmitOptions { links: true });+ let nx = workbook_to_pages(+ &wb,+ EmitOptions {+ links: true,+ ..Default::default()+ },+ );let site = &nx.pages[0].text_items[0];assert_eq!(site.text, "site");assert_eq!(site.link.as_deref(), Some("https://example.com"));@@ -513,4 +770,230 @@ mod tests {}s}++ // ── pictures ────────────────────────────────────────────────────────────++ /// Parts that hang one PNG picture off sheet1 via a drawing part. The+ /// anchor XML is the caller's, so each test states its own placement.+ fn drawing_parts(anchor_xml: &str) -> Vec<(String, String)> {+ let sheet_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>+</Relationships>"#;+ let drawing = format!(+ r#"<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">{anchor_xml}</xdr:wsDr>"#+ );+ let drawing_rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image1.png"/>+</Relationships>"#;+ // Real 1x1 PNG bytes are not valid UTF-8, and `workbook_from` writes+ // string parts; the extension decides the format, and dimensions+ // failing to parse is the (0, 0) fallback the sink already has.+ vec![+ (+ "xl/worksheets/_rels/sheet1.xml.rels".to_string(),+ sheet_rels.to_string(),+ ),+ ("xl/drawings/drawing1.xml".to_string(), drawing),+ (+ "xl/drawings/_rels/drawing1.xml.rels".to_string(),+ drawing_rels.to_string(),+ ),+ (+ "xl/media/image1.png".to_string(),+ "not-really-png-but-bytes".to_string(),+ ),+ ]+ }++ fn pic_anchor(body: &str) -> String {+ format!(+ r#"{body}<xdr:pic><xdr:nvPicPr><xdr:cNvPr id="2" name="P"/></xdr:nvPicPr><xdr:blipFill><a:blip r:embed="rId1"/></xdr:blipFill></xdr:pic><xdr:clientData/>"#+ )+ }++ fn layout_with_pic(sheet_xml: &str, anchor_xml: &str, opts: EmitOptions) -> NativeXlsx {+ let parts = drawing_parts(anchor_xml);+ let extra: Vec<(&str, &str)> = parts+ .iter()+ .map(|(a, b)| (a.as_str(), b.as_str()))+ .collect();+ let wb = workbook_from(sheet_xml, &extra);+ workbook_to_pages(&wb, opts)+ }++ /// A picture anchored on page 2's rows gets its figure block and rect on+ /// page 2, page-relative — and the `ExtractedImage` id, page and bbox all+ /// agree with the block ref.+ #[test]+ fn a_picture_lands_on_its_anchor_row_page() {+ // 15 rows at 100 pt = 3 pages of 7/7/1 (the pagination test's grid).+ let rows_xml: String = (1..=15)+ .map(|r| format!(r#"<row r="{r}" ht="100"><c r="A{r}"><v>{r}</v></c><c r="B{r}"><v>{r}</v></c></row>"#))+ .collect();+ let sheet = format!(+ r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>{rows_xml}</sheetData><drawing r:id="rId7"/></worksheet>"#+ );+ // Anchor on row index 8 (sheet row 9): page 2 locally, rows 8..14.+ let anchor = pic_anchor(+ r#"<xdr:twoCellAnchor>+ <xdr:from><xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>8</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:to><xdr:col>1</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>10</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>"#,+ );+ let nx = layout_with_pic(+ &sheet,+ &format!("<xdr:twoCellAnchor>{}</xdr:twoCellAnchor>", ""),+ EmitOptions::default(),+ );+ // Guard against the helper silently producing nothing.+ assert!(nx.pic_rects.iter().all(|r| r.is_empty()));++ let nx = layout_with_pic(+ &sheet,+ &format!("{anchor}</xdr:twoCellAnchor>"),+ EmitOptions {+ figures: true,+ images: true,+ ..Default::default()+ },+ );+ assert_eq!(nx.pages.len(), 3);+ assert!(nx.pic_rects[0].is_empty() && nx.pic_rects[2].is_empty());+ assert_eq!(nx.pic_rects[1].len(), 1);+ let rect = &nx.pic_rects[1][0];+ // Page 2 starts at emitted row 7 (y 700 in grid space); row 8 is+ // 100 pt below that, page-relative y = MARGIN + 100.+ assert_eq!(rect.y, MARGIN + 100.0);+ assert_eq!(rect.x, MARGIN);+ assert_eq!(rect.height, 200.0, "rows 8..10 at 100 pt each");+ // The figure block sits on page 2, after the table.+ assert!(+ nx.page_blocks[1]+ .iter()+ .any(|b| matches!(b, Block::Figure { id, .. } if id == "s1_1")),+ "page 2 carries the figure ref: {:?}",+ nx.page_blocks[1]+ );+ assert!(+ !nx.page_blocks[0]+ .iter()+ .any(|b| matches!(b, Block::Figure { .. }))+ );+ // Doc-level: the figure ref follows the sheet's table.+ assert!(matches!(+ nx.all_blocks.last().unwrap(),+ Block::Figure { id, format } if id == "s1_1" && format == "png"+ ));+ // The image entry names the same id, the workbook-level page, and+ // the same rect.+ assert_eq!(nx.images.len(), 1);+ assert_eq!(nx.images[0].id, "s1_1");+ assert_eq!(nx.images[0].page, 2);+ assert_eq!(nx.images[0].bbox.y, rect.y);+ assert_eq!(nx.images[0].bytes.as_slice(), b"not-really-png-but-bytes");+ }++ /// `figures` without `images`: refs appear, no bytes are collected —+ /// the default-config (placeholder image mode) shape.+ #[test]+ fn figure_refs_do_not_require_byte_collection() {+ let sheet = r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>+ <row r="1"><c r="A1"><v>1</v></c><c r="B1"><v>2</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 {+ figures: true,+ ..Default::default()+ },+ );+ assert!(nx.images.is_empty());+ assert_eq!(nx.pic_rects[0].len(), 1);+ // 914,400 EMU = 72 pt; 457,200 EMU = 36 pt.+ assert_eq!(nx.pic_rects[0][0].width, 72.0);+ assert_eq!(nx.pic_rects[0][0].height, 36.0);+ assert!(+ nx.page_blocks[0]+ .iter()+ .any(|b| matches!(b, Block::Figure { .. }))+ );+ }++ /// An image-only sheet — no written cells at all — still surfaces its+ /// picture, on its single empty page. This is the case `extract_images`+ /// exists for.+ #[test]+ fn an_image_only_sheet_still_extracts_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>3</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>10</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 {+ figures: true,+ images: true,+ ..Default::default()+ },+ );+ assert_eq!(nx.pages.len(), 1);+ assert!(nx.pages[0].text_items.is_empty());+ assert_eq!(nx.images.len(), 1);+ assert_eq!(nx.images[0].page, 1);+ // The empty grid collapses the anchor to the origin; the extent+ // survives and the rect stays inside the page box.+ let r = &nx.pic_rects[0][0];+ assert_eq!((r.x, r.y), (MARGIN, MARGIN));+ assert_eq!((r.width, r.height), (72.0, 72.0));+ assert!(+ nx.page_blocks[0]+ .iter()+ .any(|b| matches!(b, Block::Figure { .. }))+ );+ }++ /// The doc-level block stream from the geometry pass must equal the+ /// emitter's, figures included — the emitter is what the corpus gates+ /// score, and the CLI ships the geometry pass's.+ #[test]+ fn doc_blocks_match_the_emitter_with_figures_on() {+ let sheet = r#"<worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheetData>+ <row r="1"><c r="A1"><v>1</v></c><c r="B1"><v>2</v></c></row>+ <row r="2"><c r="A2"><v>3</v></c><c r="B2"><v>4</v></c></row>+ </sheetData><drawing r:id="rId7"/></worksheet>"#;+ let anchor = pic_anchor(+ r#"<xdr:oneCellAnchor>+ <xdr:from><xdr:col>1</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>1</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>+ <xdr:ext cx="914400" cy="457200"/>"#,+ );+ let parts = drawing_parts(&format!("{anchor}</xdr:oneCellAnchor>"));+ let extra: Vec<(&str, &str)> = parts+ .iter()+ .map(|(a, b)| (a.as_str(), b.as_str()))+ .collect();+ let wb = workbook_from(sheet, &extra);+ let opts = EmitOptions {+ figures: true,+ ..Default::default()+ };+ let emitted: Vec<Block> = crate::office::xlsx::emit_workbook(&wb, opts)+ .blocks+ .into_iter()+ .map(|(b, _)| b)+ .collect();+ let nx = workbook_to_pages(&wb, opts);+ assert_eq!(+ format!("{emitted:?}"),+ format!("{:?}", nx.all_blocks),+ "geometry-pass doc blocks diverge from the emitter's"+ );+ }}diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex 18bda74..dcf5be4 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -900,18 +900,17 @@ impl LiteParse {/// Config options the native XLSX path cannot honor. Hitting one with/// `office_native` on is a hard `Config` error, not a fallback.///- /// Two entries are XLSX-specific:+ /// One entry is XLSX-specific:////// * `extract_annotations` — hyperlinks reach `TextItem::link`, but no/// `DocumentAnnotation` list is built (same v1 state the PPTX path/// started in).- /// * `extract_images` / `image_mode = embed` — the reader does not parse- /// `xl/drawings`, so a workbook's embedded pictures and charts are- /// invisible to the native path; an explicit ask routes to the- /// conversion path instead of silently under-delivering. The default- /// `image_mode = placeholder` is *not* gated: a native parse emits no- /// figure refs where the conversion path could — accepted and recorded,- /// because gating the default would turn the native path off.+ ///+ /// `extract_images` / `image_mode = embed` **were** here, for as long as+ /// the reader ignored `xl/drawings`. The drawing layer's pictures now+ /// extract (charts and drawing shapes remain out of scope — a chart has+ /// no image bytes and either engine's conversion path also extracts none+ /// for it), so both flags are honored rather than rejected.#[cfg(all(feature = "xlsx-native", not(target_arch = "wasm32")))]fn native_xlsx_ineligible_reason(&self) -> Option<&'static str> {let c = &self.config;@@ -927,8 +926,6 @@ impl LiteParse {Some("skip_diagonal_text")} else if c.extract_annotations {Some("extract_annotations")- } else if c.effective_extract_images() {- Some("extract_images")} else {None}@@ -955,10 +952,15 @@ impl LiteParse {let wb = liteparse_ooxml::xlsx::read(data).map_err(|e| LiteParseError::Conversion(format!("xlsx parse failed: {e}")))?;+ // Same two gates as the PDF, DOCX and PPTX paths: figures interleave+ // when `image_mode != Off`, pixel bytes surface under+ // `effective_extract_images`.let nx = xlsx_layout::workbook_to_pages(&wb,xlsx::EmitOptions {links: self.config.extract_links,+ figures: self.config.image_mode != crate::config::ImageMode::Off,+ images: self.config.effective_extract_images(),},);@@ -977,8 +979,8 @@ impl LiteParse {}// Per-page complexity from native facts: the page's table blocks- // (exact, not detected), no media rects (drawings are unparsed), and- // a column count of 1 — a spreadsheet has no section columns.+ // (exact, not detected), the drawing layer's picture rects, and a+ // column count of 1 — a spreadsheet has no section columns.let complexity: Vec<Option<crate::ocr_merge::PageComplexityStats>> =if self.config.include_complexity {nx.pages@@ -997,7 +999,7 @@ impl LiteParse {.count();Some(crate::ocr_merge::calculate_native_page_complexity(p,- &[],+ nx.pic_rects.get(i).map(Vec::as_slice).unwrap_or(&[]),tables,1,))@@ -1036,14 +1038,27 @@ impl LiteParse {page_stats.push(s);}- Ok(Some(self.parse_from_native_blocks(+ let mut result = self.parse_from_native_blocks(pages,page_blocks,(!page_filtered).then_some(nx.all_blocks),nx.outline,- Vec::new(),+ nx.images,page_stats,- )))+ );++ // Same post-passes as the PDF, DOCX and PPTX paths, same order:+ // duplicate figure refs point at the canonical name, then only+ // canonical files are written.+ if self.config.output_format == crate::config::OutputFormat::Markdown {+ rewrite_duplicate_image_refs(&mut result.pages, &mut result.text, &result.images);+ }+ if self.config.effective_extract_images()+ && let Some(output_dir) = self.config.image_output_dir.as_deref()+ {+ write_extracted_images(output_dir, &mut result.images)?;+ }+ Ok(Some(result))}/// Run the native PPTX pipeline. Contract matches the DOCX sibling:diff --git a/packages/node/src/cli.ts b/packages/node/src/cli.tsindex 91a4aa3..ccdf412 100644--- a/packages/node/src/cli.ts+++ b/packages/node/src/cli.ts@@ -89,7 +89,7 @@ program.option("--no-ocr", "Disable OCR").option("--no-office-native",- "Force the LibreOffice conversion path for DOCX instead of the native parser",+ "Force the LibreOffice conversion path for DOCX/PPTX/XLSX instead of the native parsers",).option("--ocr-language <lang>", "OCR language (default: eng)").option("--max-pages <n>", "Max pages to parse", parseInt)@@ -324,7 +324,7 @@ program.option("--no-ocr", "Disable OCR").option("--no-office-native",- "Force the LibreOffice conversion path for DOCX instead of the native parser",+ "Force the LibreOffice conversion path for DOCX/PPTX/XLSX instead of the native parsers",).option("--ocr-language <lang>", "OCR language (default: eng)").option("--ocr-server-url <url>", "HTTP OCR server URL")diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.tsindex 4861c03..d9120bf 100644--- a/packages/node/src/lib.ts+++ b/packages/node/src/lib.ts@@ -40,7 +40,7 @@ export interface LiteParseConfig {extractLinks: boolean;/** Keep running headers/footers in markdown output instead of stripping repeated page-band lines and page chrome (default: false). */keepHeadersFooters: boolean;- /** Parse DOCX natively instead of converting via LibreOffice (default: true; other formats always use the conversion path). */+ /** Parse DOCX/PPTX/XLSX natively instead of converting via LibreOffice (default: true; other formats always use the conversion path). */officeNative: boolean;/** Extract all PDF annotations into each parsed page (default: false). */extractAnnotations: boolean;diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex 5c2829c..b012525 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -436,8 +436,8 @@ class LiteParse:keep_headers_footers: Keep running headers/footers in markdownoutput instead of stripping repeated page-band lines and pagechrome (default: False).- office_native: Parse DOCX natively instead of converting via- LibreOffice (default: True; other formats always use the+ office_native: Parse DOCX/PPTX/XLSX natively instead of converting+ via LibreOffice (default: True; other formats always use theconversion path). Set False to force the LibreOffice path.image_output_dir: Directory where extracted embedded images arewritten. Requires ``extract_images=True`` and returns filediff --git a/packages/python/liteparse/types.py b/packages/python/liteparse/types.pyindex 7fa9517..e2addf4 100644--- a/packages/python/liteparse/types.py+++ b/packages/python/liteparse/types.py@@ -406,8 +406,8 @@ class LiteParseConfig:#: Keep running headers/footers in markdown output instead of stripping#: repeated page-band lines and page chrome.keep_headers_footers: bool = False- #: Parse DOCX natively instead of converting via LibreOffice (other- #: formats always use the conversion path).+ #: Parse DOCX/PPTX/XLSX natively instead of converting via LibreOffice+ #: (other formats always use the conversion path).office_native: bool = Trueextract_images: bool = Falseextract_vector_graphics: bool = False