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: enhance spatial table handling and improve LaTeX to OMML conversion
myhlolid58f6ae8a004
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex 4a6864a0..ee281d9c 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -89,17 +89,21 @@ docx_bytes = render_docx(DOCX 输出固定使用 A4 纵向与 20 mm 页边距。标题是 Word Heading 1–9,anchor 是document-wide bookmark,Index 标题叶子写成内部链接;正文直接消费共享 inline AST,-保留粗体、斜体、下划线、删除线、emphasis、上下标、外链及行内公式。列表保留 producer-已经内化的 marker,只用缩进表达层级,不重建 `numbering.xml`。+保留粗体、斜体、下划线、删除线、emphasis、上下标、外链及行内公式。emphasis 使用下方+着重号;带可见装饰的边界空格会等量写为 NBSP,避免 Word 隐藏下划线或删除线。列表保留+producer 已经内化的 marker,只用缩进表达层级,不重建 `numbering.xml`。公式通过 `latex2mathml -> mathml2omml -> OMML` 输出为可编辑 Office Math。末端`\tag{...}` 会从公式主体剥离并通过右对齐 tab 单独写编号;转换失败的块公式依次回退公式图片和可见 LaTeX,行内公式回退可见 LaTeX,所有回退均记录 page/block 定位。+Office producer 生成的规范无横线 `\genfrac{}{}{0pt}{}{num}{den}` 会在 DOCX adapter 内+转换为双行 matrix,不改写 MiddleJson 中的原始 LaTeX。HTML table 使用 occupancy grid 生成原生 Word table,支持 `rowspan/colspan`、嵌套表格、单元格富文本、公式、链接和图片。HTML 结构无效时只在存在表格图片时回退;空间投影-文本表格使用独立的等宽预格式样式,仅输出原始文本并保留空格、换行与 Tab,不读取或-嵌入其表格图片。Image body 文本写入图片 alt description;Chart+文本表格在 content 非空时使用独立的等宽预格式样式,仅输出原始文本并保留空格、换行+与 Tab;content 为空或纯空白时改用其图片,两者都缺失才报错。Image body 文本写入图片+alt description;Chart在图片后继续输出可用的 HTML 数据表。视觉父块仍严格保持 body/caption/footnote 原顺序。`RenderMode.DEFAULT` 与下文 Markdown DEFAULT 使用同一份续段/续表 planner;diff --git a/mineru/render/_internal/docx/inline.py b/mineru/render/_internal/docx/inline.pyindex 2dd50b2b..f8f59e8e 100644--- a/mineru/render/_internal/docx/inline.py+++ b/mineru/render/_internal/docx/inline.py@@ -33,6 +33,8 @@ _BOOKMARK_SAFE_RE = re.compile(r"[^A-Za-z0-9_]+")_BOOKMARK_MAX_LENGTH = 40_INVALID_XML_TEXT_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]")_BARE_SCRIPT_RE = re.compile(r"^\s*(?P<marker>[\^_])\s*\{(?P<content>[^{}]+)\}\s*$")+_VISIBLE_SPACE_STYLES = frozenset({"underline", "strikethrough", "emphasis"})+_NONBREAKING_SPACE = "\u00a0"@dataclass(frozen=True, slots=True)@@ -315,7 +317,8 @@ def _append_text_run(run_xml = OxmlElement("w:r")container.append(run_xml)run = Run(run_xml, paragraph)- run.text = sanitize_xml_text(content, context=context)+ sanitized = sanitize_xml_text(content, context=context)+ run.text = _make_visible_style_spaces(sanitized, styles)_apply_run_styles(run, styles)if hyperlink:run.font.color.rgb = _rgb_color("0563C1")@@ -327,6 +330,22 @@ def _append_text_run(return run+def _make_visible_style_spaces(content: str, styles: tuple[str, ...]) -> str:+ """把可见样式 run 的边界 ASCII 空格等量转为 NBSP,避免 Word 隐藏装饰线。"""+ if not content or not _VISIBLE_SPACE_STYLES.intersection(styles):+ return content++ leading_count = len(content) - len(content.lstrip(" "))+ trailing_count = len(content) - len(content.rstrip(" "))+ if leading_count == 0 and trailing_count == 0:+ return content+ if leading_count + trailing_count >= len(content):+ return _NONBREAKING_SPACE * len(content)++ content_end = len(content) - trailing_count if trailing_count else len(content)+ return _NONBREAKING_SPACE * leading_count + content[leading_count:content_end] + _NONBREAKING_SPACE * trailing_count++def sanitize_xml_text(content: str, *, context: InlineRenderContext) -> str:"""把 XML 1.0 禁止字符替换为 U+FFFD,并记录可定位的 renderer 告警。"""sanitized, replacement_count = _INVALID_XML_TEXT_RE.subn("\ufffd", content)@@ -351,7 +370,7 @@ def _apply_run_styles(run: Run, styles: tuple[str, ...]) -> None:if "emphasis" in style_set:run_properties = run._element.get_or_add_rPr()emphasis = OxmlElement("w:em")- emphasis.set(qn("w:val"), "dot")+ emphasis.set(qn("w:val"), "underDot")run_properties.append(emphasis)diff --git a/mineru/render/_internal/docx/math.py b/mineru/render/_internal/docx/math.pyindex d675cb62..36208371 100644--- a/mineru/render/_internal/docx/math.py+++ b/mineru/render/_internal/docx/math.py@@ -10,6 +10,8 @@ import re_OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math"_EMPTY_SCRIPT_RE = re.compile(r"(?:_\s*\{\s*\}|\^\s*\{\s*\})")+_GENFRAC_COMMAND = r"\genfrac"+_GENFRAC_ARGUMENT_COUNT = 6class DocxFormulaError(ValueError):@@ -40,7 +42,8 @@ def split_formula_tag(content: str) -> tuple[str, str | None]:def latex_to_omml(latex: str, *, display: bool) -> etree._Element:"""把 LaTeX 转换为带命名空间、可直接插入 DOCX 的 OMML 节点。"""try:- normalized_latex = _EMPTY_SCRIPT_RE.sub("", latex)+ normalized_latex = _normalize_supported_genfrac(latex)+ normalized_latex = _EMPTY_SCRIPT_RE.sub("", normalized_latex)mathml = latex_to_mathml(normalized_latex, display="block" if display else "inline")omml_xml = _repair_mathml2omml_xml(mathml_to_omml(mathml))equation = _parse_omml(omml_xml)@@ -58,6 +61,66 @@ def latex_to_omml(latex: str, *, display: bool) -> etree._Element:raise DocxFormulaError(f"LaTeX 公式无法转换为 OMML: {latex!r}") from exc+def _normalize_supported_genfrac(content: str) -> str:+ """把规范无横线 genfrac 转为 latex2mathml 支持的双行 matrix。"""+ chunks: list[str] = []+ preserved_start = 0+ search_start = 0+ while (command_start := content.find(_GENFRAC_COMMAND, search_start)) >= 0:+ command_end = command_start + len(_GENFRAC_COMMAND)+ if _is_escaped_command(content, command_start):+ search_start = command_end+ continue++ parsed = _parse_braced_arguments(content, command_end, _GENFRAC_ARGUMENT_COUNT)+ if parsed is None:+ search_start = command_end+ continue+ arguments, expression_end = parsed+ left_delimiter, right_delimiter, thickness, math_style, numerator, denominator = arguments+ if left_delimiter.strip() or right_delimiter.strip() or thickness.strip() != "0pt" or math_style.strip():+ search_start = expression_end+ continue++ normalized_numerator = _normalize_supported_genfrac(numerator)+ normalized_denominator = _normalize_supported_genfrac(denominator)+ replacement = (+ rf"\begin{{matrix}}{{{normalized_numerator}}}"+ r"\\"+ rf"{{{normalized_denominator}}}\end{{matrix}}"+ )+ chunks.append(content[preserved_start:command_start])+ chunks.append(replacement)+ preserved_start = expression_end+ search_start = expression_end++ if not chunks:+ return content+ chunks.append(content[preserved_start:])+ return "".join(chunks)+++def _parse_braced_arguments(+ content: str,+ cursor: int,+ count: int,+) -> tuple[tuple[str, ...], int] | None:+ """从指定位置读取固定数量的平衡花括号参数,并返回参数与结束位置。"""+ arguments: list[str] = []+ content_end = len(content)+ for _ in range(count):+ while cursor < content_end and content[cursor].isspace():+ cursor += 1+ if cursor >= content_end or content[cursor] != "{":+ return None+ closing_brace = _find_balanced_closing_brace(content, cursor, content_end)+ if closing_brace is None:+ return None+ arguments.append(content[cursor + 1 : closing_brace])+ cursor = closing_brace + 1+ return tuple(arguments), cursor++def _repair_mathml2omml_xml(omml_xml: str) -> str:"""修复 mathml2omml 0.0.2 对 groupChrPr 写出的错误闭合标签。"""return omml_xml.replace(diff --git a/mineru/render/docx.py b/mineru/render/docx.pyindex d5982194..4ca26796 100644--- a/mineru/render/docx.py+++ b/mineru/render/docx.py@@ -363,10 +363,16 @@ class _DocxRenderer:) from excself._append_block_image(child, context=context, alt_text="table")else:- 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))+ if child.content and not child.content.isspace():+ paragraph = self.document.add_paragraph(style=SPATIAL_TABLE_STYLE)+ paragraph.add_run(sanitize_xml_text(child.content, context=context))+ elif child.image_base64 is not None or child.image_path is not None:+ self._append_block_image(child, context=context, alt_text="table")+ else:+ raise self._render_error(+ "Spatial table does not contain text content or image",+ context,+ )elif isinstance(child, TableAnnotationBlock):self._render_annotation(child, context)else:diff --git a/tests/unittest/test_docx_math.py b/tests/unittest/test_docx_math.pyindex 1d97c5f1..b65f660d 100644--- a/tests/unittest/test_docx_math.py+++ b/tests/unittest/test_docx_math.py@@ -104,15 +104,51 @@ def test_latex_to_omml_removes_explicitly_empty_operator_limits() -> None:assert "<m:sub>" not in serialized and "<m:sup>" not in serialized+def test_latex_to_omml_normalizes_no_bar_genfrac_in_binomial_formula() -> None:+ """验证 Office 无横线分式可转为带定界符的双行 OMML matrix。"""+ formula = (+ r"\left(x+a\right)^{n}=\sum_{k=0}^{n}"+ r"\left(\genfrac{}{}{0pt}{}{n}{k}\right)x^{k}a^{n-k}"+ )++ equation = latex_to_omml(formula, display=False)+ matrix = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}m")+ delimiter = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}d")++ assert matrix is not None+ assert delimiter is not None+ rows = matrix.findall(f"{{{_OFFICE_MATH_NAMESPACE}}}mr")+ assert ["".join(row.itertext()) for row in rows] == ["n", "k"]+++ ("latex", "expected_matrix_count"),+ [+ (r"\genfrac{}{}{0pt}{}{a_{i}}{\frac{b}{c}}", 1),+ (r"\genfrac{}{}{0pt}{}{a}{b}+\genfrac{}{}{0pt}{}{c}{d}", 2),+ (r"\genfrac{}{}{0pt}{}{\genfrac{}{}{0pt}{}{a}{b}}{c}", 2),+ ],+)+def test_latex_to_omml_normalizes_nested_and_multiple_genfrac(+ latex: str,+ expected_matrix_count: int,+) -> None:+ """验证 genfrac 参数可含嵌套结构,且一条公式可转换多个实例。"""+ equation = latex_to_omml(latex, display=False)++ assert len(equation.findall(f".//{{{_OFFICE_MATH_NAMESPACE}}}m")) == expected_matrix_count++@pytest.mark.parametrize("latex",[- r"\genfrac{}{}{0pt}{}{a}{b}",+ r"\frac{a",+ r"\genfrac{(}{)}{1pt}{}{a}{b}","x\x00y",],)def test_latex_to_omml_wraps_conversion_failures_with_original_cause(latex: str) -> None:- """验证已知不支持或非法输入失败时保留原异常链。"""+ """验证损坏或非规范输入失败时保留原异常链。"""with pytest.raises(DocxFormulaError, match="无法转换为 OMML") as exc_info:latex_to_omml(latex, display=True)diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.pyindex 9a1e3647..d10ffe57 100644--- a/tests/unittest/test_docx_render.py+++ b/tests/unittest/test_docx_render.py@@ -139,10 +139,36 @@ def test_heading_bookmark_forward_index_link_and_rich_inline_ooxml() -> None:assert "<w:u" in document_xml and "<w:strike" in document_xmlassert '<w:vertAlign w:val="superscript"' in document_xmlassert '<w:vertAlign w:val="subscript"' in document_xml- assert '<w:em w:val="dot"' in document_xml+ assert '<w:em w:val="underDot"' in document_xmlassert "<m:oMath" in document_xml+def test_visible_styled_boundary_spaces_use_nbsp_without_mutating_input() -> None:+ """验证可见样式的边界空格转为等量 NBSP,普通样式和内部空格保持原样。"""+ content = (+ '<text style="underline"> left</text>|'+ '<text style="strikethrough">right </text>|'+ '<text style="underline,strikethrough"> </text>|'+ '<text style="emphasis"> emphasis </text>|'+ '<text style="bold"> bold </text>|'+ '<text style="underline">a b</text>'+ )+ middle = _middle(_page(0, TextBlock(type="text", index=0, content=content)))+ original = deepcopy(middle)++ result = render_docx(middle)+ document = Document(BytesIO(result))+ document_xml = _part(result, "word/document.xml")++ assert document.paragraphs[0].text == (+ "\u00a0\u00a0left|right\u00a0\u00a0|\u00a0\u00a0\u00a0|\u00a0\u00a0emphasis\u00a0\u00a0| bold |a b"+ )+ assert document.paragraphs[0].text.count("\u00a0") == 11+ assert '<w:em w:val="underDot"' in document_xml+ assert '<w:em w:val="dot"' not in document_xml+ assert middle == original++def test_bookmark_names_are_sanitized_and_collision_safe() -> None:"""验证不同原 anchor 清洗后冲突时仍生成唯一 Word bookmark。"""first = ParagraphTitleBlock(@@ -270,7 +296,7 @@ def test_display_formula_without_tag_uses_math_paragraph() -> None:def test_formula_conversion_failure_falls_back_to_image_then_visible_latex() -> None:"""验证块公式优先图片回退,行内公式保留可见 LaTeX。"""- unsupported = r"\genfrac{}{}{0pt}{}{a}{b}"+ unsupported = r"\frac{a"middle = _middle(_page(0,@@ -293,6 +319,33 @@ def test_formula_conversion_failure_falls_back_to_image_then_visible_latex() ->assert "<a:blip" in document_xml+def test_genfrac_formula_renders_native_omml_in_title_and_list() -> None:+ """验证正文标题和列表中的规范 genfrac 均输出原生双行 OMML。"""+ formula = (+ r"\left(x+a\right)^{n}=\sum_{k=0}^{n}"+ r"\left(\genfrac{}{}{0pt}{}{n}{k}\right)x^{k}a^{n-k}"+ )+ title = ParagraphTitleBlock(+ type="paragraph_title",+ index=0,+ level=2,+ content=f"Title <eq>{formula}</eq>",+ )+ list_block = ListBlock(+ type="list",+ index=1,+ content=[TextBlock(type="text", content=f"1. before <eq>{formula}</eq> after")],+ )++ result = render_docx(_middle(_page(0, title, list_block)))+ document_xml = _part(result, "word/document.xml")++ assert document_xml.count("<m:oMath") == 2+ assert document_xml.count("<m:m>") == 2+ assert document_xml.count("<m:d>") >= 2+ assert r"\genfrac" not in document_xml++def test_inline_bare_scripts_use_word_superscript_runs_without_placeholder_boxes() -> None:"""验证无底数公式片段改用上下标 run,避免 OMML 可见占位框。"""block = TextBlock(@@ -567,8 +620,8 @@ def test_spatial_table_preserves_preformatted_text_without_assets(image_payload:@pytest.mark.parametrize("content", ["", " \n\t"])-def test_spatial_table_without_text_raises_contextual_error(content: str) -> None:- """验证空空间表格即使带图也以父表格定位抛出公共异常。"""+def test_spatial_table_without_text_uses_base64_image(content: str) -> None:+ """验证空或纯空白空间表格优先使用内嵌图片。"""spatial = TableBlock(type="table",index=7,@@ -578,11 +631,73 @@ def test_spatial_table_without_text_raises_contextual_error(content: str) -> Nonindex=7,content=content,image_base64=_png_uri(),+ image_path="images/unused.png",+ )+ ],+ )+ resolver = Mock(side_effect=AssertionError("内嵌图片存在时不应解析 sidecar"))++ document = Document(BytesIO(render_docx(_middle(_page(3, spatial)), asset_resolver=resolver)))++ resolver.assert_not_called()+ assert len(document.inline_shapes) == 1+++def test_spatial_table_without_text_uses_sidecar_resolver() -> None:+ """验证空空间表格的相对图片路径只通过注入的 resolver 加载。"""+ spatial = TableBlock(+ type="table",+ index=7,+ content=[+ TableBodyBlock(+ type="table_body",+ index=7,+ content="",+ image_path="images/table.png",+ )+ ],+ )+ resolver = Mock(return_value=_png_bytes())++ document = Document(BytesIO(render_docx(_middle(_page(3, spatial)), asset_resolver=resolver)))++ resolver.assert_called_once_with("images/table.png")+ assert len(document.inline_shapes) == 1++[email protected]("content", ["", " \n\t"])+def test_spatial_table_without_text_or_image_raises_contextual_error(content: str) -> None:+ """验证空间表格既无有效文本也无图片时抛出带父表格定位的异常。"""+ spatial = TableBlock(+ type="table",+ index=7,+ content=[TableBodyBlock(type="table_body", index=7, content=content)],+ )++ with pytest.raises(DocxRenderError, match="does not contain text content or image") 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_without_text_rejects_invalid_fallback_image() -> None:+ """验证空空间表格的损坏图片不会被静默忽略。"""+ spatial = TableBlock(+ type="table",+ index=7,+ content=[+ TableBodyBlock(+ type="table_body",+ index=7,+ content="",+ image_base64="data:image/png;base64,bm90LWEtcG5n",)],)- with pytest.raises(DocxRenderError, match="Spatial table does not contain text content") as exc_info:+ with pytest.raises(DocxRenderError) as exc_info:render_docx(_middle(_page(3, spatial)))assert exc_info.value.page_idx == 3