Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: add support for spatial tables with preformatted text and strict image handling
myhloli2ddd25b2e380
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex 9f9810f5..4c19019d 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -98,7 +98,8 @@ document-wide bookmark,Index 标题叶子写成内部链接;正文直接消HTML table 使用 occupancy grid 生成原生 Word table,支持 `rowspan/colspan`、嵌套表格、单元格富文本、公式、链接和图片。HTML 结构无效时只在存在表格图片时回退;空间投影-文本表格按 v1 契约只输出表格图片。Image body 文本写入图片 alt description;Chart+文本表格使用独立的等宽预格式样式,仅输出原始文本并保留空格、换行与 Tab,不读取或+嵌入其表格图片。Image body 文本写入图片 alt description;Chart在图片后继续输出可用的 HTML 数据表。视觉父块仍严格保持 body/caption/footnote 原顺序。`RenderMode.DEFAULT` 与下文 Markdown DEFAULT 使用同一份续段/续表 planner;diff --git a/mineru/render/_internal/docx/styles.py b/mineru/render/_internal/docx/styles.pyindex 357c6a17..d84c2996 100644--- a/mineru/render/_internal/docx/styles.py+++ b/mineru/render/_internal/docx/styles.py@@ -13,6 +13,7 @@ from docx.styles.style import _ParagraphStyleBODY_STYLE = "Normal"CODE_STYLE = "MinerU Code"+SPATIAL_TABLE_STYLE = "MinerU Spatial Table"CAPTION_STYLE = "MinerU Caption"FOOTNOTE_STYLE = "MinerU Footnote"AUXILIARY_STYLE = "MinerU Auxiliary"@@ -67,6 +68,17 @@ def configure_document(document: Document) -> None:)_set_paragraph_shading(code, "F3F4F6")+ spatial_table = _get_or_add_paragraph_style(document, SPATIAL_TABLE_STYLE)+ _configure_paragraph_style(+ spatial_table,+ western_font="Courier New",+ east_asia_font="宋体",+ size_pt=9,+ space_before_pt=4,+ space_after_pt=6,+ line_spacing=1.0,+ )+caption = _get_or_add_paragraph_style(document, CAPTION_STYLE)_configure_paragraph_style(caption,@@ -192,6 +204,7 @@ __all__ = ["CODE_STYLE","FOOTNOTE_STYLE","FORMULA_FALLBACK_STYLE",+ "SPATIAL_TABLE_STYLE","configure_document","usable_width_emu","usable_width_twips",diff --git a/mineru/render/docx.py b/mineru/render/docx.pyindex 05ea4e01..d5982194 100644--- a/mineru/render/docx.py+++ b/mineru/render/docx.py@@ -54,6 +54,7 @@ from mineru.render._internal.docx.styles import (CODE_STYLE,FOOTNOTE_STYLE,FORMULA_FALLBACK_STYLE,+ SPATIAL_TABLE_STYLE,configure_document,usable_width_emu,usable_width_twips,@@ -347,7 +348,7 @@ class _DocxRenderer:raise TypeError(f"Unsupported image child: {type(child).__name__}")def _render_table_block(self, block: TableBlock, context: InlineRenderContext) -> None:- """按原始子块顺序写原生 HTML table 或用户选定的空间表格图片。"""+ """按原始子块顺序写原生 HTML table 或预格式空间投影文本。"""for child in block.content:if isinstance(child, TableBodyBlock):if _HTML_TABLE_RE.search(child.content):@@ -362,7 +363,10 @@ class _DocxRenderer:) from excself._append_block_image(child, context=context, alt_text="table")else:- self._append_block_image(child, context=context, alt_text="table")+ if not child.content or child.content.isspace():+ raise self._render_error("Spatial table does not contain text content", context)+ paragraph = self.document.add_paragraph(style=SPATIAL_TABLE_STYLE)+ paragraph.add_run(sanitize_xml_text(child.content, context=context))elif isinstance(child, TableAnnotationBlock):self._render_annotation(child, context)else:@@ -774,6 +778,7 @@ def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:if isinstance(block, TitleBlockBase) and block.anchor:yield block.anchor+def _plain_html_text(content: str) -> str:"""把图片或图表 body 内容收敛为适合 alt description 的纯文本。"""if not content.strip():diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.pyindex 97ffb42f..9a1e3647 100644--- a/tests/unittest/test_docx_render.py+++ b/tests/unittest/test_docx_render.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport base64from copy import deepcopyfrom io import BytesIO+from unittest.mock import Mockimport zipfilefrom docx import Document@@ -26,6 +27,7 @@ from mineru.types import (PageBlock,PageInfo,ParagraphTitleBlock,+ TableAnnotationBlock,TableBlock,TableBodyBlock,TextBlock,@@ -518,8 +520,17 @@ def test_invalid_html_table_falls_back_to_table_image() -> None:render_docx(_middle(_page(0, without_fallback)))-def test_spatial_table_outputs_only_image_and_requires_it() -> None:- """验证空间投影文本不进入 DOCX,并严格要求表格图片。"""+ "image_payload",+ [+ pytest.param({}, id="without-image"),+ pytest.param({"image_base64": _png_uri()}, id="base64-image"),+ pytest.param({"image_path": "images/table.png"}, id="sidecar-image"),+ ],+)+def test_spatial_table_preserves_preformatted_text_without_assets(image_payload: dict[str, str]) -> None:+ """验证空间表格原样保留排版字符,并完全忽略可选图片素材。"""+ content = " A B\t说明\n\n1 2\t中\x01文\n" + "X" * 240spatial = TableBlock(type="table",index=0,@@ -527,23 +538,82 @@ def test_spatial_table_outputs_only_image_and_requires_it() -> None:TableBodyBlock(type="table_body",index=0,- content="A B\n1 2",+ content=content,+ **image_payload,+ )+ ],+ )+ resolver = Mock(side_effect=AssertionError("空间表格不应解析图片"))++ result = render_docx(_middle(_page(0, spatial)), asset_resolver=resolver)+ document = Document(BytesIO(result))+ document_xml = _part(result, "word/document.xml")+ relationships = _part(result, "word/_rels/document.xml.rels")++ resolver.assert_not_called()+ assert document.paragraphs[0].text == content.replace("\x01", "\ufffd")+ assert document.paragraphs[0].style.name == "MinerU Spatial Table"+ assert document.styles["MinerU Spatial Table"].font.name == document.styles["MinerU Code"].font.name+ assert document.styles["MinerU Spatial Table"].font.size == document.styles["MinerU Code"].font.size+ assert document.styles["MinerU Spatial Table"].paragraph_format.line_spacing == 1.0+ assert 'w:pStyle w:val="MinerUSpatialTable"' in document_xml+ assert 'xml:space="preserve"' in document_xml+ assert "<w:tab/>" in document_xml+ assert document_xml.count("<w:br/>") == 3+ assert len(document.inline_shapes) == 0+ assert "relationships/image" not in relationships+ with zipfile.ZipFile(BytesIO(result)) as archive:+ assert not any(name.startswith("word/media/") for name in archive.namelist())++[email protected]("content", ["", " \n\t"])+def test_spatial_table_without_text_raises_contextual_error(content: str) -> None:+ """验证空空间表格即使带图也以父表格定位抛出公共异常。"""+ spatial = TableBlock(+ type="table",+ index=7,+ content=[+ TableBodyBlock(+ type="table_body",+ index=7,+ content=content,image_base64=_png_uri(),)],)- missing = TableBlock(++ with pytest.raises(DocxRenderError, match="Spatial table does not contain text content") as exc_info:+ render_docx(_middle(_page(3, spatial)))++ assert exc_info.value.page_idx == 3+ assert exc_info.value.block_index == 7+ assert exc_info.value.block_type == "table"+++def test_spatial_table_preserves_caption_body_footnote_order() -> None:+ """验证空间表格正文仍严格位于原始 caption 与 footnote 之间。"""+ spatial = TableBlock(type="table",- index=0,- content=[TableBodyBlock(type="table_body", index=0, content="A B")],+ index=1,+ content=[+ TableAnnotationBlock(type="table_caption", index=0, content="Table caption"),+ TableBodyBlock(type="table_body", index=1, content=" A B\n 1 2"),+ TableAnnotationBlock(type="table_footnote", index=2, content="Table footnote"),+ ],)- result = render_docx(_middle(_page(0, spatial)))- document = Document(BytesIO(result))- assert "A B" not in "".join(paragraph.text for paragraph in document.paragraphs)- assert len(document.inline_shapes) == 1- with pytest.raises(DocxRenderError, match="does not contain"):- render_docx(_middle(_page(0, missing)))+ document = Document(BytesIO(render_docx(_middle(_page(0, spatial)))))++ assert [paragraph.text for paragraph in document.paragraphs] == [+ "Table caption",+ " A B\n 1 2",+ "Table footnote",+ ]+ assert [paragraph.style.name for paragraph in document.paragraphs] == [+ "MinerU Caption",+ "MinerU Spatial Table",+ "MinerU Footnote",+ ]def test_chart_renders_image_then_structured_html_table() -> None: