A fast, helpful, and open-source document parser
wip
Logan Markewichedab6b9088de
diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rsindex 63d783f..09ed005 100644--- a/crates/liteparse/src/markdown_layout/inline.rs+++ b/crates/liteparse/src/markdown_layout/inline.rs@@ -47,7 +47,7 @@ pub fn escape_inline(s: &str) -> String {/// Wrap `inner` in a markdown inline link to `url`. Uses the angle-bracket/// destination form when the URL contains characters that would otherwise/// terminate or break the `(url)` form (whitespace or parentheses).-fn apply_link(inner: &str, url: &str) -> String {+pub(crate) fn apply_link(inner: &str, url: &str) -> String {if url.contains([' ', '\t', '(', ')']) {format!("[{}](<{}>)", inner, url)} else {diff --git a/crates/liteparse/src/markdown_layout/mod.rs b/crates/liteparse/src/markdown_layout/mod.rsindex 8f6bccb..c06cd2e 100644--- a/crates/liteparse/src/markdown_layout/mod.rs+++ b/crates/liteparse/src/markdown_layout/mod.rs@@ -21,6 +21,8 @@ mod tables;pub use blocks::{Block, Cell, render_blocks};pub use classify::classify_page_with_filters;pub use headings::{build_heading_map, compute_body_size};+#[cfg(feature = "docx-native")]+pub(crate) use inline::apply_link;pub use inline::escape_inline;pub use repetition::{compute_header_footer_set, detect_single_page_chrome};pub use tables::detect_table_rects;diff --git a/crates/liteparse/src/office/docx.rs b/crates/liteparse/src/office/docx.rsindex 3b23a5a..56647d6 100644--- a/crates/liteparse/src/office/docx.rs+++ b/crates/liteparse/src/office/docx.rs@@ -10,32 +10,65 @@//! and flattens numbering (including `lvlOverride`/`startOverride`), but leaves//! the per-run merge to the caller. That merge is [`Emitter::effective_fmt`].-use std::collections::HashMap;+use std::collections::{HashMap, VecDeque};+use liteparse_docx::field::FieldInstruction;use liteparse_docx::model::{- Block as DocxBlock, Inline, NoteId, NumId, NumberFormat, OutlineLevel, Paragraph,- ParagraphProperties, RunElement, RunProperties, StrikeStyle, StyleId, Table, VerticalMerge,+ Block as DocxBlock, HyperlinkTarget, Inline, NoteId, NumId, NumberFormat, OutlineLevel,+ Paragraph, ParagraphProperties, RunElement, RunProperties, StrikeStyle, StyleId, Table,+ VerticalMerge,};use liteparse_docx::render::resolve::ResolvedDocument;use crate::error::LiteParseError;-use crate::markdown_layout::{Block, Cell, escape_inline};+use crate::markdown_layout::{Block, Cell, apply_link, escape_inline};++/// What the emitter should produce beyond the always-on structure.+#[derive(Default)]+pub struct EmitOptions {+ /// Render external hyperlinks as `[text](url)`. Mirrors+ /// `LiteParseConfig::extract_links`, which the PDF path honors too.+ pub links: bool,+ /// Layout-assigned figure ids: media identity (`MediaEntry::data`+ /// allocation pointer) → FIFO of `(id, extension)` in draw order, from+ /// `docx_layout::collect_images`. `Some` enables `Block::Figure`+ /// emission; `None` (structure-only callers, `image_mode == Off`) keeps+ /// the block stream figure-free. Ids must come from the layout because+ /// they are page-scoped (`p{page}_{n}`) and the structure walk does not+ /// know pages.+ pub figures: Option<HashMap<usize, VecDeque<(String, String)>>>,+}/// Parse a DOCX and emit the shared block model.///+/// `extract_links` mirrors `LiteParseConfig::extract_links`: when true,+/// external hyperlinks render as `[text](url)`, matching the PDF path.+///+/// Structure-only: no layout runs, so no `Block::Figure`s are emitted (their+/// ids are page-scoped and require layout — see [`EmitOptions::figures`]).+////// Errors only when the archive itself is unreadable — the vendored parser is/// fail-open on unknown elements, unknown attribute values and malformed/// scalars, so a document with unmodeled markup still yields blocks.-pub fn docx_to_blocks(data: &[u8]) -> Result<Vec<Block>, LiteParseError> {+pub fn docx_to_blocks(data: &[u8], extract_links: bool) -> Result<Vec<Block>, LiteParseError> {let parsed = liteparse_docx::docx::parse(data).map_err(|e| LiteParseError::Conversion(format!("docx parse failed: {e}")))?;let resolved = liteparse_docx::render::resolve::resolve(parsed);- Ok(emit(&resolved))+ Ok(emit(&resolved, extract_links))}-/// Emit blocks for an already-resolved document.-pub fn emit(doc: &ResolvedDocument) -> Vec<Block> {- emit_with_sources(doc).into_iter().map(|(b, _)| b).collect()+/// Emit blocks for an already-resolved document, structure-only (no figures).+pub fn emit(doc: &ResolvedDocument, extract_links: bool) -> Vec<Block> {+ emit_with_sources(+ doc,+ EmitOptions {+ links: extract_links,+ figures: None,+ },+ )+ .into_iter()+ .map(|(b, _)| b)+ .collect()}/// Where an emitted [`Block`] came from, for the layout block→page join.@@ -54,8 +87,8 @@ pub enum BlockSource {/// One source block maps to zero or one emitted blocks today (empty paragraphs/// and section breaks emit nothing; nothing merges across source blocks), but/// the tagging tolerates zero-or-more either way.-pub fn emit_with_sources(doc: &ResolvedDocument) -> Vec<(Block, BlockSource)> {- let mut em = Emitter::new(doc);+pub fn emit_with_sources(doc: &ResolvedDocument, opts: EmitOptions) -> Vec<(Block, BlockSource)> {+ let mut em = Emitter::new(doc, opts);let mut out: Vec<(Block, BlockSource)> = Vec::new();// One Emitter across all blocks: list counters must persist so an ordered// list interrupted by prose continues its count.@@ -106,6 +139,15 @@ impl Fmt {}}+/// A formatting-tagged run of text, plus the external URL of the hyperlink it+/// sits inside, if any.+#[derive(Clone, PartialEq)]+struct Chunk {+ fmt: Fmt,+ link: Option<String>,+ text: String,+}+struct Emitter<'a> {doc: &'a ResolvedDocument,/// `(numId, level)` → next counter, so ordered lists number correctly and@@ -117,14 +159,34 @@ struct Emitter<'a> {/// either double the backslashes (`\\*`) or surface them literally inside/// an HTML block, where markdown escapes mean nothing.in_cell: bool,+ /// Render external hyperlinks as `[text](url)`. Mirrors+ /// `LiteParseConfig::extract_links`, which the PDF path honors too.+ links: bool,+ /// Figure-id queues from the layout (see [`EmitOptions::figures`]).+ figures: Option<HashMap<usize, VecDeque<(String, String)>>>,+ /// Figures encountered during the current paragraph/table walk, flushed+ /// as standalone [`Block::Figure`]s after the enclosing block — images+ /// are inline in the model but block-level in markdown, same as the PDF+ /// path's y-interleaved figures.+ pending_figures: Vec<(String, String)>,}impl<'a> Emitter<'a> {- fn new(doc: &'a ResolvedDocument) -> Self {+ fn new(doc: &'a ResolvedDocument, opts: EmitOptions) -> Self {Self {doc,counters: HashMap::new(),in_cell: false,+ links: opts.links,+ figures: opts.figures,+ pending_figures: Vec::new(),+ }+ }++ /// Drain figures gathered while walking the current block's inlines.+ fn flush_figures(&mut self, out: &mut Vec<Block>) {+ for (id, format) in self.pending_figures.drain(..) {+ out.push(Block::Figure { id, format });}}@@ -206,14 +268,26 @@ impl<'a> Emitter<'a> {}/// Flatten a paragraph's inlines into formatting-tagged text chunks, in- /// document order.- fn chunks(&self, para: &Paragraph, content: &[Inline]) -> Vec<(Fmt, String)> {+ /// document order. Figures encountered along the way accumulate in+ /// `pending_figures` for the caller to flush after its block.+ fn chunks(&mut self, para: &Paragraph, content: &[Inline]) -> Vec<Chunk> {let mut out = Vec::new();- self.collect(para, content, &mut out);+ self.collect(para, content, None, &mut out);out}- fn collect(&self, para: &Paragraph, content: &[Inline], out: &mut Vec<(Fmt, String)>) {+ fn collect(+ &mut self,+ para: &Paragraph,+ content: &[Inline],+ link: Option<&str>,+ out: &mut Vec<Chunk>,+ ) {+ // Links are emitted only outside table cells: cell text travels+ // unescaped and is escaped per dialect by the renderer, which would+ // mangle a baked-in `[text](url)`. The PDF path's cells are plain+ // text too, so this keeps the two pipelines rendering cells alike.+ let emit_links = self.links && !self.in_cell;for inline in content {match inline {Inline::TextRun(run) => {@@ -231,11 +305,57 @@ impl<'a> Emitter<'a> {}}if !text.is_empty() {- out.push((fmt, text));+ out.push(Chunk {+ fmt,+ link: link.map(str::to_string),+ text,+ });+ }+ }+ Inline::Hyperlink(h) => {+ // Only resolved external URLs become markdown links.+ // Internal bookmark anchors (TOC entries, cross-refs) have+ // no addressable target in a markdown document, and an+ // unresolved rel id is not a URL.+ let url = match &h.target {+ HyperlinkTarget::ExternalUrl(u) if emit_links => Some(u.as_str()),+ _ => None,+ };+ self.collect(para, &h.content, url.or(link), out);+ }+ Inline::Field(f) => {+ // HYPERLINK fields carry the URL in the instruction+ // itself; an empty target with `\l` is an internal+ // anchor, skipped for the same reason as above.+ let url = match &f.instruction {+ FieldInstruction::Hyperlink { target, .. }+ if emit_links && !target.is_empty() =>+ {+ Some(target.as_str())+ }+ _ => None,+ };+ self.collect(para, &f.content, url.or(link), out);+ }+ Inline::Image(img) => {+ // Pop the layout-assigned id for this media's next+ // placement. The queue is keyed by media identity and+ // both walks visit body images in document order, so the+ // nth structure occurrence pairs with the nth drawn+ // placement. A miss (queue absent or drained — e.g. a+ // format the image collector skips) emits nothing rather+ // than a dangling reference.+ if let Some(queues) = self.figures.as_mut()+ && let Some(rel) =+ liteparse_docx::render::resolve::images::extract_image_rel_id(img)+ && let Some(media) = self.doc.media.get(rel)+ && let Some(fig) = queues+ .get_mut(&(media.data.as_ptr() as usize))+ .and_then(|q| q.pop_front())+ {+ self.pending_figures.push(fig);}}- Inline::Hyperlink(h) => self.collect(para, &h.content, out),- Inline::Field(f) => self.collect(para, &f.content, out),_ => {}}}@@ -244,15 +364,19 @@ impl<'a> Emitter<'a> {fn paragraph(&mut self, para: &Paragraph, out: &mut Vec<Block>) {let props = self.para_props(para);let chunks = self.chunks(para, ¶.content);- if chunks.iter().all(|(_, t)| t.trim().is_empty()) {+ if chunks.iter().all(|c| c.text.trim().is_empty()) {+ // An image in its own paragraph is the common case: no text, but+ // the walk collected figures that must still be emitted.+ self.flush_figures(out);return;}// Headings win over list formatting: a numbered heading is a heading.if let Some(lvl) = props.outline_level {// Deliberately plain — no `**` inside the `#`. The `#` *is* the- // emphasis, and `# **Heading**` is redundant markup.- let text: String = chunks.iter().map(|(_, t)| t.as_str()).collect();+ // emphasis, and `# **Heading**` is redundant markup. Links are+ // flattened too: heading text feeds the outline and anchors.+ let text: String = chunks.iter().map(|c| c.text.as_str()).collect();out.push(Block::Heading {// Emitted as declared. A dense 1..N remap was measured on the// 48-doc corpus and lost 39 of 66 heading rules; see the@@ -260,6 +384,7 @@ impl<'a> Emitter<'a> {level: OutlineLevel::value(lvl).clamp(1, 6) as u8,text: self.escape(text.trim()),});+ self.flush_figures(out);return;}@@ -297,10 +422,12 @@ impl<'a> Emitter<'a> {bold,italic,});+ self.flush_figures(out);return;}out.push(Block::Paragraph { text, bold, italic });+ self.flush_figures(out);}/// Emit a table as [`Block::MergedTable`], which is the whole point of the@@ -380,6 +507,10 @@ impl<'a> Emitter<'a> {if rows.iter().any(|r| !r.is_empty()) {out.push(Block::MergedTable { rows, header_rows });}+ // Figures found inside cells (bubbled up by `cell_text`) land after+ // the table: both table dialects are text-only per cell, so an image+ // reference inside one would be mangled by the cell escaping.+ self.flush_figures(out);}/// Flatten a cell's block content to a single line of inline markdown.@@ -395,12 +526,13 @@ impl<'a> Emitter<'a> {self.blocks(content, &mut inner);self.in_cell = outer;let mut parts: Vec<String> = Vec::new();- for b in &inner {+ for b in inner {match b {- Block::Heading { text, .. } | Block::Paragraph { text, .. } => {- parts.push(text.clone())- }- Block::ListItem { text, .. } => parts.push(text.clone()),+ Block::Heading { text, .. } | Block::Paragraph { text, .. } => parts.push(text),+ Block::ListItem { text, .. } => parts.push(text),+ // A figure inside a cell can't live in single-line cell text;+ // requeue it so the enclosing `table` emits it afterwards.+ Block::Figure { id, format } => self.pending_figures.push((id, format)),_ => {}}}@@ -429,30 +561,32 @@ impl<'a> Emitter<'a> {/// carry it and the text stays clean; otherwise emphasis is baked inline and/// the flags are cleared. This mirrors `paragraph_from_accum` on the PDF path,/// so the same prose looks the same whichever pipeline produced it.-fn render_chunks(chunks: &[(Fmt, String)], escape: bool) -> (String, bool, bool) {- // Coalesce adjacent runs that share formatting first. Word splits a run at- // every property change, including ones that don't survive the cascade- // (language, spell-check state, rsid), so a single bold phrase routinely- // arrives as several identically-formatted chunks. Emitting each one- // separately would produce `**a****b**`, which no markdown parser reads as- // one bold span.- let mut merged: Vec<(Fmt, String)> = Vec::new();- for (fmt, text) in chunks {+fn render_chunks(chunks: &[Chunk], escape: bool) -> (String, bool, bool) {+ // Coalesce adjacent runs that share formatting and link first. Word splits+ // a run at every property change, including ones that don't survive the+ // cascade (language, spell-check state, rsid), so a single bold phrase+ // routinely arrives as several identically-formatted chunks. Emitting each+ // one separately would produce `**a****b**`, which no markdown parser+ // reads as one bold span.+ let mut merged: Vec<Chunk> = Vec::new();+ for c in chunks {match merged.last_mut() {- Some((prev, buf)) if prev == fmt => buf.push_str(text),- _ => merged.push((*fmt, text.clone())),+ Some(prev) if prev.fmt == c.fmt && prev.link == c.link => prev.text.push_str(&c.text),+ _ => merged.push(c.clone()),}}let chunks = &merged[..];- let uniform = chunks.first().map(|(f, _)| *f).filter(|f| {+ let uniform = chunks.first().map(|c| c.fmt).filter(|f| {// Strike has no block-level flag, so a uniformly-struck paragraph still- // takes the inline path.- !f.strike && chunks.iter().all(|(g, _)| g == f)+ // takes the inline path. Likewise a link: it must wrap exactly its+ // anchor text, so any linked chunk forces the inline path (mirroring+ // the PDF path's rule in `render_line_inline`).+ !f.strike && chunks.iter().all(|c| c.fmt == *f) && chunks.iter().all(|c| c.link.is_none())});if let Some(fmt) = uniform {- let raw: String = chunks.iter().map(|(_, t)| t.as_str()).collect();+ let raw: String = chunks.iter().map(|c| c.text.as_str()).collect();let raw = raw.trim();let text = if escape {escape_inline(raw)@@ -463,7 +597,7 @@ fn render_chunks(chunks: &[(Fmt, String)], escape: bool) -> (String, bool, bool)}let mut out = String::new();- for (fmt, text) in chunks {+ for Chunk { fmt, link, text } in chunks {// Emphasis markers must hug non-space content to be valid markdown, so// surrounding whitespace is hoisted outside the markers.let lead: String = text.chars().take_while(|c| c.is_whitespace()).collect();@@ -489,8 +623,8 @@ fn render_chunks(chunks: &[(Fmt, String)], escape: bool) -> (String, bool, bool)} else {core.to_string()};- if fmt.is_plain() {- out.push_str(&escaped);+ let mut rendered = if fmt.is_plain() {+ escaped} else {let (mut open, mut close) = (String::new(), String::new());if fmt.bold {@@ -505,10 +639,14 @@ fn render_chunks(chunks: &[(Fmt, String)], escape: bool) -> (String, bool, bool)open.push_str("~~");close.insert_str(0, "~~");}- out.push_str(&open);- out.push_str(&escaped);- out.push_str(&close);+ format!("{open}{escaped}{close}")+ };+ // Link wraps outside emphasis — `[*anchor*](url)` — matching+ // `render_line_inline` on the PDF path.+ if let Some(url) = link {+ rendered = apply_link(&rendered, url);}+ out.push_str(&rendered);out.push_str(&trail);}(out.trim().to_string(), false, false)@@ -526,8 +664,22 @@ mod tests {}}- fn chunks(v: &[(Fmt, &str)]) -> Vec<(Fmt, String)> {- v.iter().map(|(f, t)| (*f, t.to_string())).collect()+ fn chunks(v: &[(Fmt, &str)]) -> Vec<Chunk> {+ v.iter()+ .map(|(f, t)| Chunk {+ fmt: *f,+ link: None,+ text: t.to_string(),+ })+ .collect()+ }++ fn linked(f: Fmt, url: &str, t: &str) -> Chunk {+ Chunk {+ fmt: f,+ link: Some(url.to_string()),+ text: t.to_string(),+ }}#[test]@@ -597,6 +749,64 @@ mod tests {assert_eq!(text, "**ab**!");}+ /// A link wraps exactly its anchor text, with emphasis inside the+ /// brackets — `[*anchor*](url)` — matching the PDF path's rendering.+ #[test]+ fn link_wraps_anchor_outside_emphasis() {+ let (text, bold, italic) = render_chunks(+ &[+ chunks(&[(fmt(false, false, false), "see ")]).remove(0),+ linked(fmt(false, true, false), "https://example.com", "the docs"),+ ],+ true,+ );+ assert_eq!(+ (text.as_str(), bold, italic),+ ("see [*the docs*](https://example.com)", false, false)+ );+ }++ /// A uniformly-formatted paragraph that is entirely one link must still+ /// take the inline path — block flags cannot carry a URL.+ #[test]+ fn uniform_link_paragraph_stays_inline() {+ let (text, bold, ..) = render_chunks(+ &[linked(+ fmt(false, false, false),+ "https://example.com",+ "home",+ )],+ true,+ );+ assert_eq!(text, "[home](https://example.com)");+ assert!(!bold);+ }++ /// Word splits runs inside one hyperlink too; adjacent chunks sharing+ /// format and link must coalesce into a single `[anchor](url)`.+ #[test]+ fn adjacent_runs_in_one_link_coalesce() {+ let (text, ..) = render_chunks(+ &[+ linked(fmt(false, false, false), "https://example.com", "run"),+ linked(fmt(false, false, false), "https://example.com", "llama"),+ ],+ true,+ );+ assert_eq!(text, "[runllama](https://example.com)");+ }++ /// URLs containing spaces or parentheses take the angle-bracket form so+ /// the destination cannot terminate early.+ #[test]+ fn link_url_with_space_uses_angle_brackets() {+ let (text, ..) = render_chunks(+ &[linked(fmt(false, false, false), "https://e.com/a b", "x")],+ true,+ );+ assert_eq!(text, "[x](<https://e.com/a b>)");+ }+/// Provenance tagging must not change what is emitted; body indices must/// be non-decreasing (the block→page join walks them with a forward/// cursor); and note bodies must form a `Note`-tagged tail behind the@@ -611,8 +821,14 @@ mod tests {let parsed = liteparse_docx::docx::parse(&data).expect("fixture parses");let doc = liteparse_docx::render::resolve::resolve(parsed);- let tagged = emit_with_sources(&doc);- let plain = emit(&doc);+ let tagged = emit_with_sources(+ &doc,+ EmitOptions {+ links: true,+ figures: None,+ },+ );+ let plain = emit(&doc, true);assert_eq!(format!("{plain:?}"),format!("{:?}", tagged.iter().map(|(b, _)| b).collect::<Vec<_>>()),diff --git a/crates/liteparse/src/office/docx_layout.rs b/crates/liteparse/src/office/docx_layout.rsindex 7140cdf..d02e778 100644--- a/crates/liteparse/src/office/docx_layout.rs+++ b/crates/liteparse/src/office/docx_layout.rs@@ -10,21 +10,20 @@//!//! Facts that are geometric inferences on the PDF path arrive here as data://! `LinkAnnotation` → [`TextItem::link`], `Outline` marks →-//! [`OutlineTarget`]s. Two deliberate v1 gaps, both documented in the plan:-//! `TextItem::strike` stays `false` (the vendored layout never draws-//! strikethrough lines — markdown strike comes from the block emitter's-//! cascade, which reads the source instead of geometry), and `Image`/`Path`-//! commands feed nothing (no Figure blocks exist on the native markdown path-//! yet; `ParseResult.images` stays empty).+//! [`OutlineTarget`]s, `Image` commands → [`ExtractedImage`]s with the+//! *original* embedded bytes (see [`collect_images`]). One deliberate v1 gap,+//! documented in the plan: `TextItem::strike` stays `false` (the vendored+//! layout never draws strikethrough lines — markdown strike comes from the+//! block emitter's cascade, which reads the source instead of geometry).-use std::collections::HashMap;+use std::collections::{HashMap, VecDeque};use liteparse_docx::render::fonts::FontRegistry;use liteparse_docx::render::layout::draw_command::{DrawCommand, LayoutedPage, OutlineMark};use liteparse_docx::render::layout::fragment::FontProps;use liteparse_docx::render::layout::measurer::TextMeasurer;-use crate::types::{OutlineTarget, Page, Rect, TextItem, WordBox};+use crate::types::{ExtractedImage, OutlineTarget, Page, Rect, TextItem, WordBox};/// Everything the native pipeline taps out of a laid-out document.pub struct NativeLayout {@@ -282,6 +281,147 @@ fn assign_links(items: &mut [TextItem], links: &[(Rect, String)]) {}}+/// Native images tapped from the draw-command stream.+pub struct NativeImages {+ /// One entry per surfaced placement, in (page, draw-order). Duplicate+ /// placements of one media entry carry `duplicate_of` and share the+ /// canonical entry's bytes, matching the PDF path's dedup contract.+ pub images: Vec<ExtractedImage>,+ /// Media identity (`MediaEntry::data` allocation pointer) → FIFO of+ /// `(figure id, extension)` in draw order. The block emitter pops from+ /// these queues to give its `Block::Figure`s the layout-assigned+ /// page-scoped ids, joining the two walks without guessing.+ pub figure_ids: HashMap<usize, VecDeque<(String, String)>>,+}++/// File extension for a media format we surface as an extracted image.+///+/// `None` skips the image entirely: EMF/WMF are vector metafiles and SVG is+/// XML — the PDF path only ever emits raster jpg/png (PDFium rasterizes+/// everything), so surfacing bytes most consumers cannot decode would be a+/// worse contract than omitting them. Word's SVG embeds normally carry a PNG+/// fallback blip, which is the one the layout draws.+fn media_extension(format: liteparse_docx::model::ImageFormat) -> Option<&'static str> {+ use liteparse_docx::model::ImageFormat as F;+ match format {+ F::Png => Some("png"),+ F::Jpeg => Some("jpg"),+ F::Gif => Some("gif"),+ F::Bmp => Some("bmp"),+ F::Tiff => Some("tiff"),+ F::WebP => Some("webp"),+ F::Svg | F::Emf | F::Wmf | F::Unknown => None,+ }+}++/// Collect embedded images from the draw-command stream.+///+/// Ids follow the platform extractor's `p{page}_{n}` naming (1-based, per+/// page, in draw order) so `img_{id}.{ext}` file names line up with the PDF+/// path's. Bytes are the *original* embedded media — no re-encode, unlike the+/// PDF path which rasterizes through PDFium — so a JPEG stays the exact JPEG+/// the author inserted. `src_rect` crops are not applied to the bytes; `bbox`+/// is the placed rectangle either way.+pub fn collect_images(layouted: &[LayoutedPage]) -> NativeImages {+ use std::hash::{Hash, Hasher};++ let mut images: Vec<ExtractedImage> = Vec::new();+ let mut figure_ids: HashMap<usize, VecDeque<(String, String)>> = HashMap::new();+ // Same media Arc ⇒ same bytes, free dedup for the common repeated-rel+ // case (a logo in every page's header is ONE relationship).+ let mut by_ptr: HashMap<usize, usize> = HashMap::new();+ // Distinct rels can still hold identical bytes; hash → candidate+ // canonical indices, confirmed by full compare like the PDF path's cache.+ let mut by_hash: HashMap<u64, Vec<usize>> = HashMap::new();++ for (page_idx, lp) in layouted.iter().enumerate() {+ let page_number = (page_idx + 1) as u32;+ let mut n = 0u32;+ for cmd in &lp.commands {+ let DrawCommand::Image {+ rect, image_data, ..+ } = cmd+ else {+ continue;+ };+ let Some(ext) = media_extension(image_data.format) else {+ continue;+ };+ n += 1;+ let id = format!("p{page_number}_{n}");+ let bbox = Rect {+ x: rect.origin.x.raw(),+ y: rect.origin.y.raw(),+ width: rect.size.width.raw(),+ height: rect.size.height.raw(),+ };+ let ptr = image_data.data.as_ptr() as usize;++ let canonical_idx = by_ptr.get(&ptr).copied().or_else(|| {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ image_data.data.hash(&mut h);+ by_hash+ .get(&h.finish())?+ .iter()+ .copied()+ .find(|&i| *images[i].bytes == *image_data.data)+ });++ let entry = if let Some(ci) = canonical_idx {+ let canonical = &images[ci];+ ExtractedImage {+ id: id.clone(),+ name: format!("img_{id}.{ext}"),+ path: None,+ page: page_number,+ 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),+ }+ } else {+ let bytes = std::sync::Arc::new(image_data.data.to_vec());+ 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));+ ExtractedImage {+ id: id.clone(),+ name: format!("img_{id}.{ext}"),+ path: None,+ page: page_number,+ bbox,+ width,+ height,+ rotation: 0.0,+ format: ext.to_string(),+ duplicate_of: None,+ bytes,+ }+ };++ if canonical_idx.is_none() {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ image_data.data.hash(&mut h);+ by_hash.entry(h.finish()).or_default().push(images.len());+ by_ptr.insert(ptr, images.len());+ }+ figure_ids+ .entry(ptr)+ .or_default()+ .push_back((id, ext.to_string()));+ images.push(entry);+ }+ }++ NativeImages { images, figure_ids }+}+fn union_bounds(items: &[TextItem]) -> Option<Rect> {let mut it = items.iter();let first = it.next()?;diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex b9425c2..15f1b11 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -363,17 +363,26 @@ impl LiteParse {self.validate_output_config()?;// Native DOCX path: parse + resolve + layout in-process, no- // LibreOffice, no PDFium, no OCR. Fail-open: any error (or panic — the- // layout engine is young) logs and falls through to the conversion- // path, as does a config asking for something the native path cannot- // honor and a text-sparse document when OCR is on.+ // LibreOffice, no PDFium, no OCR. Fail-open only for *engine*+ // failures: any error (or panic — the layout engine is young) logs+ // and falls through to the conversion path, as does a text-sparse+ // document when OCR is on. A config asking for something the native+ // path cannot honor is a hard error instead — the user picks the+ // engine, the engine never silently swaps itself out.#[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]if self.config.office_native {if let Some(reason) = self.native_docx_ineligible_reason() {+ // Unsupported option + native mode = a hard error, not a+ // silent engine swap: falling back to LibreOffice here would+ // hand back different geometry/pagination than every other+ // parse of the same document. The user opts into the+ // conversion path explicitly instead.if crate::office::docx_bytes(&input).is_some() {- log(&format!(- "[liteparse] office_native: conversion path ({reason})"- ));+ return Err(LiteParseError::Config(format!(+ "`{reason}` is not supported by the native DOCX path; \+ disable it, or set office_native = false \+ (CLI: --no-office-native) to parse via the conversion path"+ )));}} else if let Some(bytes) = crate::office::docx_bytes(&input) {match self.try_parse_docx_native(&bytes) {@@ -756,18 +765,19 @@ impl LiteParse {/// in the list: it is `None` for converted inputs already, and the native/// path keeps that rule.#[cfg(all(feature = "docx-native", not(target_arch = "wasm32")))]+ /// Config options the native DOCX path cannot honor. Hitting one with+ /// `office_native` on is a hard `Config` error, not a fallback — see the+ /// check in `parse_input`. `extract_images` (native media bytes) and+ /// `extract_xfa_packets` (honestly empty — DOCX has no XFA) are+ /// supported and deliberately absent from this list.fn native_docx_ineligible_reason(&self) -> Option<&'static str> {let c = &self.config;- if c.effective_extract_images() {- Some("extract_images")- } else if c.extract_annotations {+ if c.extract_annotations {Some("extract_annotations")} else if c.extract_form_fields {Some("extract_form_fields")} else if c.extract_structure_tree {Some("extract_structure_tree")- } else if c.extract_xfa_packets {- Some("extract_xfa_packets")} else if c.extract_vector_graphics {Some("extract_vector_graphics")} else if c.include_complexity {@@ -834,7 +844,32 @@ impl LiteParse {}}- let tagged = docx::emit_with_sources(&resolved);+ // Figures mirror the PDF path's gate (interleaved only when+ // `image_mode != Off`); pixel bytes surface only under+ // `effective_extract_images`, also as on the PDF path.+ let want_figures = self.config.image_mode != crate::config::ImageMode::Off;+ let want_images = self.config.effective_extract_images();+ let native_images = if want_figures || want_images {+ docx_layout::collect_images(&layouted)+ } else {+ docx_layout::NativeImages {+ images: Vec::new(),+ figure_ids: std::collections::HashMap::new(),+ }+ };+ let images = if want_images {+ native_images.images+ } else {+ Vec::new()+ };++ let tagged = docx::emit_with_sources(+ &resolved,+ docx::EmitOptions {+ links: self.config.extract_links,+ figures: want_figures.then_some(native_images.figure_ids),+ },+ );let n_pages = native.pages.len();let page_blocks = split_blocks_by_page(&tagged, &native.block_pages, n_pages);let all_blocks: Vec<crate::markdown_layout::Block> =@@ -859,12 +894,23 @@ impl LiteParse {}let (pages, page_blocks): (Vec<_>, Vec<_>) = selected.into_iter().unzip();- Ok(Some(self.parse_from_native_blocks(+ let mut result = self.parse_from_native_blocks(pages,page_blocks,(!page_filtered).then_some(all_blocks),native.outline,- )))+ images,+ );++ // Same post-passes as the PDF path, 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 want_images && let Some(output_dir) = self.config.image_output_dir.as_deref() {+ write_extracted_images(output_dir, &mut result.images)?;+ }+ Ok(Some(result))}/// `parse_from_pages`'s native sibling: no projection — the block model@@ -887,6 +933,7 @@ impl LiteParse {page_blocks: Vec<Vec<crate::markdown_layout::Block>>,all_blocks: Option<Vec<crate::markdown_layout::Block>>,outline: Vec<OutlineTarget>,+ images: Vec<crate::types::ExtractedImage>,) -> ParseResult {let markdown_out = self.config.output_format == crate::config::OutputFormat::Markdown;let parsed_pages: Vec<ParsedPage> = pages@@ -947,13 +994,16 @@ impl LiteParse {pages: parsed_pages,text: full_text,outline,- images: Vec::new(),+ images,image_error_count: 0,form_type: None,creator: None,producer: None,doc_meta: None,- xfa_packets: None,+ // XFA is a PDF/LiveCycle container; a DOCX cannot carry packets.+ // `Some([])` keeps the JSON shape identical to the conversion+ // path, which also finds none in a LibreOffice-produced PDF.+ xfa_packets: self.config.extract_xfa_packets.then(Vec::new),}}diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rsindex 3f71d7d..0719e21 100644--- a/crates/liteparse/tests/integration_test.rs+++ b/crates/liteparse/tests/integration_test.rs@@ -102,6 +102,11 @@ async fn test_parse_bytes_office_integration() {{return;}+ // `sample3.doc` is a renamed Word 2007+ (.docx) file, so byte input has no+ // extension to go on and the container sniff routes it down the native+ // DOCX path when that feature is on. Native pagination is host-dependent+ // (font substitution can spill a page — see NATIVE_OFFICE_PLAN.md), so+ // assert a page range rather than pinning LibreOffice's exact count.let fixture_path = "../../integration_tests_data/sample3.doc";let lit = LiteParse::new(LiteParseConfig::default());let data = tokio::fs::read(fixture_path)@@ -112,7 +117,12 @@ async fn test_parse_bytes_office_integration() {.parse_input(input).await.expect("Should be able to parse");- assert_eq!(parsed.pages.len(), 2);+ assert!(+ (2..=3).contains(&parsed.pages.len()),+ "expected 2-3 pages, got {}",+ parsed.pages.len()+ );+ assert!(parsed.pages.iter().all(|p| !p.text_items.is_empty()));}#[tokio::test]@@ -291,6 +301,12 @@ async fn test_annotation_text_complexity_reason() {/// doc-level markdown byte-identical to the pure structure path/// (`docx_to_blocks` → `render_blocks`) — the invariant that pins the/// docx_rules_eval corpus score.+///+/// The byte-identity holds under the default `image_mode` because this+/// fixture's only images are header decorations, which the body walk never+/// reaches — no `Block::Figure`s are emitted. A fixture with body images+/// would need `image_mode: Off` here, since the structure-only path cannot+/// produce the layout-assigned figure ids.#[cfg(feature = "docx-native")]#[tokio::test]#[serial]@@ -304,7 +320,8 @@ async fn test_parse_docx_native_integration() {let parsed = lit.parse(path).await.expect("native parse succeeds");let data = std::fs::read(path).expect("fixture readable");- let blocks = liteparse::office::docx::docx_to_blocks(&data).expect("blocks");+ // `true` mirrors the default `extract_links` the parse above ran with.+ let blocks = liteparse::office::docx::docx_to_blocks(&data, true).expect("blocks");let expected = liteparse::markdown_layout::render_blocks(&blocks);assert_eq!(parsed.text, expected,@@ -339,3 +356,71 @@ async fn test_parse_docx_native_integration() {"real page dimensions");}++/// Native image extraction: original embedded bytes surface on+/// `ParseResult.images` with platform naming, markdown carries matching+/// figure refs for body images, and repeated media (the per-page header+/// logo case) dedups to one canonical entry.+#[cfg(feature = "docx-native")]+#[tokio::test]+#[serial]+async fn test_parse_docx_native_images_integration() {+ let lit = LiteParse::new(LiteParseConfig {+ output_format: liteparse::config::OutputFormat::Markdown,+ extract_images: true,+ quiet: true,+ ..Default::default()+ });++ // Body images: every extracted entry has bytes and a matching markdown+ // figure reference.+ let parsed = lit+ .parse("../../docx_files/financial/fdic_srs_user_guide.docx")+ .await+ .expect("native parse succeeds");+ assert!(+ !parsed.images.is_empty(),+ "drawing commands surface as extracted images"+ );+ for img in &parsed.images {+ assert!(!img.bytes.is_empty(), "{}: bytes present", img.id);+ assert!(+ img.width > 0 && img.height > 0,+ "{}: real pixel dims",+ img.id+ );+ assert!(+ parsed+ .text+ .contains(&format!("", img.id, img.format)),+ "{}: figure ref in markdown",+ img.id+ );+ }++ // Header-logo dedup: one canonical entry, every other placement points+ // at it and shares its bytes.+ let parsed = lit+ .parse("../../docx_files/enterprise/nitaac_sow_template.docx")+ .await+ .expect("native parse succeeds");+ let canonical: Vec<_> = parsed+ .images+ .iter()+ .filter(|i| i.duplicate_of.is_none())+ .collect();+ let dups: Vec<_> = parsed+ .images+ .iter()+ .filter(|i| i.duplicate_of.is_some())+ .collect();+ assert_eq!(canonical.len(), 1, "one canonical logo");+ assert!(!dups.is_empty(), "repeated placements dedup");+ for d in &dups {+ assert_eq!(d.duplicate_of.as_deref(), Some(canonical[0].id.as_str()));+ assert!(+ std::sync::Arc::ptr_eq(&d.bytes, &canonical[0].bytes),+ "duplicates share the canonical buffer"+ );+ }+}