Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: add DOCX rendering support with LaTeX to OMML conversion and enhance image handling

myhlolid0577ffef966
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 64882a7c..fa703641 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -1,8 +1,8 @@
# Rendering Contract
-状态: Markdown v1
+状态: Markdown / Content List / DOCX v1
读者: render 开发者、backend 开发者、SDK 开发者
-范围: 严格 MiddleJson 到 Markdown 的消费契约
+范围: 严格 MiddleJson 到 Markdown、Content List 和 DOCX 的消费契约
## 公共入口
@@ -23,6 +23,46 @@ backend 参数或旧 `Line/Span` renderer。渲染过程基于深拷贝,不修
图片优先使用 `image_path`,缺失时使用 `image_base64` data URI。
`asset_base_url` 只给相对 `image_path` 和 HTML 内相对 `img src` 添加前缀。
+## 可编辑 DOCX
+
+```python
+from pathlib import Path
+
+from mineru.render import RenderMode, render_docx
+
+asset_dir = Path("output/document")
+docx_bytes = render_docx(
+ middle_json,
+ mode=RenderMode.DEFAULT,
+ asset_resolver=lambda relative_path: (asset_dir / relative_path).read_bytes(),
+)
+```
+
+`render_docx()` 只接受严格 `MiddleJson`,返回完整 `.docx` bytes,不写文件、不读取 cwd,
+也不访问网络。block 同时携带两种图片来源时优先解码 `image_base64`;仅有
+`image_path` 时必须提供 `asset_resolver(relative_path) -> bytes`。必需图片缺失、路径
+不安全、格式损坏或 SVG 输入会抛出带 `page_idx/block_index/block_type` 的
+`DocxRenderError`;WebP 在内存中转为 PNG。
+
+DOCX 输出固定使用 A4 纵向与 20 mm 页边距。标题是 Word Heading 1–9,anchor 是
+document-wide bookmark,Index 标题叶子写成内部链接;正文直接消费共享 inline AST,
+保留粗体、斜体、下划线、删除线、emphasis、上下标、外链及行内公式。列表保留 producer
+已经内化的 marker,只用缩进表达层级,不重建 `numbering.xml`。
+
+公式通过 `latex2mathml -> mathml2omml -> OMML` 输出为可编辑 Office Math。末端
+`\tag{...}` 会从公式主体剥离并通过右对齐 tab 单独写编号;转换失败的块公式依次回退
+公式图片和可见 LaTeX,行内公式回退可见 LaTeX,所有回退均记录 page/block 定位。
+
+HTML table 使用 occupancy grid 生成原生 Word table,支持 `rowspan/colspan`、嵌套表格、
+单元格富文本、公式、链接和图片。HTML 结构无效时只在存在表格图片时回退;空间投影
+文本表格按 v1 契约只输出表格图片。Image body 文本写入图片 alt description;Chart
+在图片后继续输出可用的 HTML 数据表。视觉父块仍严格保持 body/caption/footnote 原顺序。
+
+`RenderMode.DEFAULT` 与下文 Markdown DEFAULT 使用同一份续段/续表 planner;
+`RenderMode.FULL` 保留全部页面辅助块,不跨源页合并,并在相邻 `PageInfo` 间写硬分页。
+`MarkdownRenderMode` 是 `RenderMode` 的既有公共别名。DOCX 是语义化可编辑输出,不承诺
+复刻源 PDF/Office 的字体、分栏、断行和页数;CLI、doclib 与 v1 API 不在本契约范围。
+
## 树形 Markdown Content List
严格 render 层还提供不合并、不丢块的树形内容输出:
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index 81e8695e..2371fe99 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1,6 +1,15 @@
# Copyright (c) Opendatalab. All rights reserved.
from .content_list import render_content_list
+from .docx import DocxRenderError, render_docx
from .markdown import MarkdownRenderMode, render_markdown
+from .utils.logical_blocks import RenderMode
-__all__ = ["MarkdownRenderMode", "render_content_list", "render_markdown"]
+__all__ = [
+ "DocxRenderError",
+ "MarkdownRenderMode",
+ "RenderMode",
+ "render_content_list",
+ "render_docx",
+ "render_markdown",
+]
diff --git a/mineru/render/docx.py b/mineru/render/docx.py
new file mode 100644
index 00000000..6ebed5f3
--- /dev/null
+++ b/mineru/render/docx.py
@@ -0,0 +1,873 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到可编辑 DOCX bytes 的公共渲染实现。"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from io import BytesIO
+import re
+
+from bs4 import BeautifulSoup, NavigableString, Tag
+from docx import Document
+from docx.document import Document as DocumentType
+from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
+from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_TAB_ALIGNMENT
+from docx.oxml import OxmlElement
+from docx.oxml.ns import qn
+from docx.shared import Emu, Mm, Pt, Twips
+from docx.table import _Cell
+from docx.text.paragraph import Paragraph
+from lxml import etree
+from loguru import logger
+
+from mineru.render.utils.docx_assets import (
+ AssetResolver,
+ DocxAssetError,
+ PreparedImage,
+ prepare_block_image,
+ prepare_html_image,
+)
+from mineru.render.utils.docx_inline import (
+ BookmarkRegistry,
+ InlineRenderContext,
+ append_inline_content,
+ append_inline_nodes,
+ append_internal_link,
+ append_joined_inline_contents,
+ plain_inline_text,
+ sanitize_xml_text,
+)
+from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml, split_formula_tag
+from mineru.render.utils.docx_styles import (
+ AUXILIARY_STYLE,
+ BODY_STYLE,
+ CAPTION_STYLE,
+ CODE_STYLE,
+ FOOTNOTE_STYLE,
+ FORMULA_FALLBACK_STYLE,
+ configure_document,
+ usable_width_emu,
+ usable_width_twips,
+)
+from mineru.render.utils.docx_table import DocxTableError, NestedTableWriter, materialize_docx_tables
+from mineru.render.utils.inline import InlineEquation, InlineLink, InlineNode, InlineStyled, InlineText, parse_inline_content
+from mineru.render.utils.logical_blocks import PlannedBlock, RenderMode, build_render_plan
+from mineru.types import (
+ PAGE_AUXILIARY_BLOCK_TYPES,
+ RAW_ALGORITHM,
+ BlockBase,
+ BlockType,
+ BBox,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ ImagePayloadBlock,
+ IndexBlock,
+ ListBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ ParagraphTitleBlock,
+ RefTextBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+ TitleBlockBase,
+)
+
+_INDEX_ROMAN_RE = re.compile(r"[ivxlcdm]+", re.IGNORECASE)
+_LIST_MARKER_RE = re.compile(
+ r"^(?P<leading>\s*)(?P<marker>[-*+]|\[[^\]\n]+\]|\(?\d+[.)]|[A-Za-z][.)]|[IVXLCDMivxlcdm]+[.)])(?P<space>\s+)"
+)
+_HTML_TABLE_RE = re.compile(r"<table\b", re.IGNORECASE)
+_ANNOTATION_CAPTION_TYPES = {
+ BlockType.IMAGE_CAPTION,
+ BlockType.TABLE_CAPTION,
+ BlockType.CHART_CAPTION,
+ BlockType.CODE_CAPTION,
+}
+_ANNOTATION_FOOTNOTE_TYPES = {
+ BlockType.IMAGE_FOOTNOTE,
+ BlockType.TABLE_FOOTNOTE,
+ BlockType.CHART_FOOTNOTE,
+ BlockType.CODE_FOOTNOTE,
+}
+
+
+class DocxRenderError(RuntimeError):
+ """表示 renderer 无法在不丢失必需内容的前提下生成 DOCX。"""
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ page_idx: int,
+ block_index: int | None,
+ block_type: str,
+ ) -> None:
+ """保存错误消息及稳定的 page/block 定位字段。"""
+ self.page_idx = page_idx
+ self.block_index = block_index
+ self.block_type = block_type
+ super().__init__(f"{message} (page_idx={page_idx}, block_index={block_index}, block_type={block_type})")
+
+
+class _DocxRenderer:
+ """持有单次 DOCX 渲染所需的 document、素材解析器和书签状态。"""
+
+ def __init__(
+ self,
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode,
+ asset_resolver: AssetResolver | None,
+ ) -> None:
+ """初始化 renderer,并预注册全部标题 anchor。"""
+ self.middle_json = middle_json
+ self.mode = mode
+ self.asset_resolver = asset_resolver
+ self.document = Document()
+ configure_document(self.document)
+ self.bookmarks = BookmarkRegistry(_iter_document_anchors(middle_json))
+ self.usable_width_emu = usable_width_emu(self.document)
+ self.usable_width_twips = usable_width_twips(self.document)
+
+ def render(self) -> bytes:
+ """执行逐页 visitor,并把 python-docx document 序列化为 bytes。"""
+ planned_pages = build_render_plan(self.middle_json, self.mode)
+ for page_position, planned_blocks in enumerate(planned_pages):
+ if self.mode is RenderMode.FULL and page_position > 0:
+ self.document.add_page_break()
+ for planned in planned_blocks:
+ if planned.removed:
+ continue
+ if self.mode is RenderMode.DEFAULT and planned.block.type in PAGE_AUXILIARY_BLOCK_TYPES:
+ continue
+ self._render_planned_block(planned)
+
+ output = BytesIO()
+ self.document.save(output)
+ return output.getvalue()
+
+ def _render_planned_block(self, planned: PlannedBlock) -> None:
+ """按严格 PageBlock 具体类型分派 Word 写入逻辑。"""
+ block = planned.block
+ context = self._context(planned.page_idx, block)
+ if isinstance(block, (TextBlock, RefTextBlock)):
+ paragraph = self.document.add_paragraph(style=BODY_STYLE)
+ append_joined_inline_contents(
+ paragraph,
+ planned.text_contents or [block.content],
+ context=context,
+ )
+ return
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ self._render_title(block, context)
+ return
+ if isinstance(block, PageAuxTextBlock):
+ paragraph = self.document.add_paragraph(style=AUXILIARY_STYLE)
+ append_inline_content(paragraph, block.content, context=context)
+ return
+ if isinstance(block, EquationBlock):
+ self._render_equation(block, context)
+ return
+ if isinstance(block, ListBlock):
+ self._render_list(block, context, depth=0)
+ return
+ if isinstance(block, IndexBlock):
+ self._render_index(block, context, depth=0)
+ return
+ if isinstance(block, ImageBlock):
+ self._render_image_block(block, context)
+ return
+ if isinstance(block, TableBlock):
+ self._render_table_block(block, context)
+ return
+ if isinstance(block, ChartBlock):
+ self._render_chart_block(block, context)
+ return
+ if isinstance(block, CodeBlock):
+ self._render_code_block(block, context)
+ return
+ raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
+
+ def _context(self, page_idx: int, block: BlockBase) -> InlineRenderContext:
+ """为当前 block 构造行内渲染上下文。"""
+ return InlineRenderContext(
+ bookmarks=self.bookmarks,
+ page_idx=page_idx,
+ block_index=block.index,
+ block_type=block.type,
+ )
+
+ def _render_title(
+ self,
+ block: DocTitleBlock | ParagraphTitleBlock,
+ context: InlineRenderContext,
+ ) -> None:
+ """用 Heading 1–9 写标题,并在段落内容外添加 bookmark。"""
+ level = min(max(block.level, 1), 9)
+ paragraph = self.document.add_paragraph(style=f"Heading {level}")
+ append_inline_content(paragraph, block.content, context=context)
+ self.bookmarks.attach(paragraph, block.anchor)
+
+ def _render_equation(self, block: EquationBlock, context: InlineRenderContext) -> None:
+ """优先写可编辑 OMML,失败时按图片、可见 LaTeX 的顺序回退。"""
+ content = block.content.strip()
+ if content:
+ formula, tag = split_formula_tag(content)
+ try:
+ math_element = latex_to_omml(formula, display=True)
+ self._append_display_formula(math_element, tag, context=context)
+ return
+ except DocxFormulaError as exc:
+ logger.warning("DOCX display formula fallback: {} ({})", exc, context.location())
+
+ if block.image_base64 is not None or block.image_path is not None:
+ try:
+ self._append_block_image(block, context=context, alt_text="formula")
+ return
+ except DocxRenderError:
+ if not content:
+ raise
+ logger.warning("DOCX formula image fallback failed; preserving LaTeX ({})", context.location())
+
+ if content:
+ paragraph = self.document.add_paragraph(style=FORMULA_FALLBACK_STYLE)
+ paragraph.add_run(sanitize_xml_text(content, context=context))
+ return
+ raise self._render_error("Equation does not contain usable LaTeX or image", context)
+
+ def _append_display_formula(
+ self,
+ math_element: etree._Element,
+ tag: str | None,
+ *,
+ context: InlineRenderContext,
+ ) -> None:
+ """把块公式居中写入;带 tag 时使用中心与右对齐 tab。"""
+ if tag is None:
+ properties = OxmlElement("m:oMathParaPr")
+ justification = OxmlElement("m:jc")
+ justification.set(qn("m:val"), "center")
+ properties.append(justification)
+ math_element.insert(0, properties)
+ paragraph = self.document.add_paragraph(style=BODY_STYLE)
+ paragraph.paragraph_format.space_before = Pt(4)
+ paragraph.paragraph_format.space_after = Pt(5)
+ paragraph._p.append(math_element)
+ return
+
+ equation = math_element.find(qn("m:oMath"))
+ if equation is None:
+ raise ValueError("Display OMML does not contain m:oMath")
+ math_element.remove(equation)
+ paragraph = self.document.add_paragraph(style=BODY_STYLE)
+ paragraph.paragraph_format.space_before = Pt(4)
+ paragraph.paragraph_format.space_after = Pt(5)
+ paragraph.paragraph_format.tab_stops.add_tab_stop(
+ Twips(self.usable_width_twips // 2),
+ WD_TAB_ALIGNMENT.CENTER,
+ )
+ paragraph.paragraph_format.tab_stops.add_tab_stop(
+ Twips(self.usable_width_twips),
+ WD_TAB_ALIGNMENT.RIGHT,
+ )
+ paragraph.add_run().add_tab()
+ paragraph._p.append(equation)
+ paragraph.add_run().add_tab()
+ rendered_tag = tag if tag.startswith("(") and tag.endswith(")") else f"({tag})"
+ paragraph.add_run(sanitize_xml_text(rendered_tag, context=context))
+
+ def _render_list(
+ self,
+ block: ListBlock,
+ context: InlineRenderContext,
+ *,
+ depth: int,
+ ) -> None:
+ """保留叶子原 marker,并仅用缩进表达递归列表层级。"""
+ for child in block.content:
+ if isinstance(child, ListBlock):
+ self._render_list(child, context, depth=depth + 1)
+ continue
+ paragraph = self.document.add_paragraph(style=BODY_STYLE)
+ marker = _LIST_MARKER_RE.match(child.content)
+ if marker is None:
+ paragraph.paragraph_format.left_indent = Mm(depth * 6)
+ else:
+ paragraph.paragraph_format.left_indent = Mm((depth + 1) * 6)
+ paragraph.paragraph_format.first_line_indent = Mm(-6)
+ append_inline_content(paragraph, child.content, context=context)
+
+ def _render_index(
+ self,
+ block: IndexBlock,
+ context: InlineRenderContext,
+ *,
+ depth: int,
+ ) -> None:
+ """递归输出目录项,并把标题叶子链接到预注册 bookmark。"""
+ for child in block.content:
+ if isinstance(child, IndexBlock):
+ self._render_index(child, context, depth=depth + 1)
+ continue
+ content = _strip_index_page_tail(child.content)
+ nodes = parse_inline_content(content)
+ if not nodes:
+ continue
+ paragraph = self.document.add_paragraph(style=BODY_STYLE)
+ paragraph.paragraph_format.left_indent = Mm((depth + 1) * 6)
+ paragraph.paragraph_format.first_line_indent = Mm(-4)
+ paragraph.add_run("• ")
+ anchor = child.anchor if isinstance(child, TitleBlockBase) else None
+ append_internal_link(paragraph, nodes, anchor=anchor, context=context)
+
+ def _render_image_block(self, block: ImageBlock, context: InlineRenderContext) -> None:
+ """按原始子块顺序写图片主体、caption 与 footnote。"""
+ for child in block.content:
+ if isinstance(child, ImageBodyBlock):
+ alt_text = _plain_html_text(child.content) or block.sub_type or "image"
+ self._append_block_image(child, context=context, alt_text=alt_text)
+ elif isinstance(child, ImageAnnotationBlock):
+ self._render_annotation(child, context)
+ else:
+ raise TypeError(f"Unsupported image child: {type(child).__name__}")
+
+ def _render_table_block(self, block: TableBlock, context: InlineRenderContext) -> None:
+ """按原始子块顺序写原生 HTML table 或用户选定的空间表格图片。"""
+ for child in block.content:
+ if isinstance(child, TableBodyBlock):
+ if _HTML_TABLE_RE.search(child.content):
+ try:
+ self._append_html_tables(child.content, context=context, depth=0)
+ except DocxRenderError as exc:
+ logger.warning("DOCX HTML table fallback: {}", exc)
+ if child.image_base64 is None and child.image_path is None:
+ raise self._render_error(
+ "HTML table cannot be materialized and has no image fallback",
+ context,
+ ) from exc
+ self._append_block_image(child, context=context, alt_text="table")
+ else:
+ self._append_block_image(child, context=context, alt_text="table")
+ elif isinstance(child, TableAnnotationBlock):
+ self._render_annotation(child, context)
+ else:
+ raise TypeError(f"Unsupported table child: {type(child).__name__}")
+
+ def _render_chart_block(self, block: ChartBlock, context: InlineRenderContext) -> None:
+ """先写图表图片,再把 HTML 结构化数据追加为原生表格。"""
+ for child in block.content:
+ if isinstance(child, ChartBodyBlock):
+ has_image = child.image_base64 is not None or child.image_path is not None
+ if has_image:
+ self._append_block_image(
+ child,
+ context=context,
+ alt_text=_plain_html_text(child.content) or block.sub_type or "chart",
+ )
+ if _HTML_TABLE_RE.search(child.content):
+ try:
+ self._append_html_tables(child.content, context=context, depth=0)
+ except DocxRenderError as exc:
+ if not has_image:
+ raise
+ logger.warning("DOCX chart data table omitted after image fallback: {}", exc)
+ elif child.content.strip() and not has_image:
+ paragraph = self.document.add_paragraph(style=BODY_STYLE)
+ append_inline_content(paragraph, child.content, context=context)
+ elif not has_image and not child.content.strip():
+ raise self._render_error("Chart does not contain image or structured content", context)
+ elif isinstance(child, ChartAnnotationBlock):
+ self._render_annotation(child, context)
+ else:
+ raise TypeError(f"Unsupported chart child: {type(child).__name__}")
+
+ def _render_code_block(self, block: CodeBlock, context: InlineRenderContext) -> None:
+ """按原始子块顺序写代码或算法主体及说明。"""
+ for child in block.content:
+ if isinstance(child, CodeBodyBlock):
+ paragraph = self.document.add_paragraph(style=CODE_STYLE)
+ if block.sub_type == BlockType.CODE:
+ paragraph.add_run(sanitize_xml_text(child.content, context=context))
+ elif block.sub_type == RAW_ALGORITHM:
+ append_inline_content(paragraph, child.content, context=context)
+ else:
+ raise ValueError(f"Unsupported code subtype: {block.sub_type}")
+ elif isinstance(child, CodeAnnotationBlock):
+ self._render_annotation(child, context)
+ else:
+ raise TypeError(f"Unsupported code child: {type(child).__name__}")
+
+ def _render_annotation(
+ self,
+ block: ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock,
+ context: InlineRenderContext,
+ ) -> None:
+ """根据说明类型选择 Caption 或 Footnote 样式并写入行内内容。"""
+ if block.type in _ANNOTATION_CAPTION_TYPES:
+ style = CAPTION_STYLE
+ elif block.type in _ANNOTATION_FOOTNOTE_TYPES:
+ style = FOOTNOTE_STYLE
+ else:
+ raise TypeError(f"Unsupported annotation type: {block.type}")
+ paragraph = self.document.add_paragraph(style=style)
+ append_inline_content(paragraph, block.content, context=context)
+
+ def _append_block_image(
+ self,
+ block: ImagePayloadBlock,
+ *,
+ context: InlineRenderContext,
+ alt_text: str,
+ ) -> None:
+ """安全加载 block 图片,并按 bbox/自然尺寸限制到可用页面范围。"""
+ try:
+ prepared = prepare_block_image(block, self.asset_resolver)
+ except DocxAssetError as exc:
+ raise self._render_error(str(exc), context) from exc
+ self._append_prepared_image(
+ prepared,
+ bbox=block.bbox,
+ alt_text=alt_text,
+ max_width_emu=self.usable_width_emu,
+ context=context,
+ )
+
+ def _append_prepared_image(
+ self,
+ prepared: PreparedImage,
+ *,
+ bbox: BBox | None,
+ alt_text: str,
+ max_width_emu: int,
+ context: InlineRenderContext,
+ paragraph: Paragraph | None = None,
+ ) -> None:
+ """把准备好的图片按比例插入居中段落并写入 alt description。"""
+ target_paragraph = paragraph or self.document.add_paragraph(style=BODY_STYLE)
+ target_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
+ natural_width = round(prepared.width_px / 96 * 914400)
+ desired_width = natural_width
+ if bbox is not None:
+ desired_width = round(max_width_emu * max(0.0, min(1.0, bbox[2] - bbox[0])))
+ minimum_width = min(int(Mm(5)), max_width_emu)
+ desired_width = max(minimum_width, min(desired_width, max_width_emu))
+
+ usable_height = int(Mm(257))
+ rendered_height = round(desired_width * prepared.height_px / max(prepared.width_px, 1))
+ if rendered_height > usable_height:
+ desired_width = round(usable_height * prepared.width_px / max(prepared.height_px, 1))
+
+ shape = target_paragraph.add_run().add_picture(
+ BytesIO(prepared.data),
+ width=Emu(max(1, desired_width)),
+ )
+ description = sanitize_xml_text(
+ re.sub(r"\s+", " ", alt_text).strip()[:2048],
+ context=context,
+ )
+ if description:
+ shape._inline.docPr.set("descr", description)
+
+ def _append_html_tables(
+ self,
+ markup: str,
+ *,
+ context: InlineRenderContext,
+ depth: int,
+ container: DocumentType | _Cell | None = None,
+ ) -> None:
+ """物化 HTML 表格,并通过共享行内/素材逻辑填充 origin cell。"""
+ if depth >= 4:
+ raise self._render_error("Nested HTML table depth exceeds 4", context)
+ target_container = container or self.document
+ target_xml = target_container._element.body if isinstance(target_container, DocumentType) else target_container._tc
+ existing_child_count = len(target_xml)
+ insertion_index = existing_child_count - 1 if isinstance(target_container, DocumentType) else existing_child_count
+ existing_relationship_ids = set(self.document.part.rels)
+
+ def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:
+ """填充一个 origin cell,并在遇到 nested table 时调用递归 writer。"""
+ self._fill_html_cell(
+ cell,
+ source,
+ write_nested=write_nested,
+ context=context,
+ )
+
+ try:
+ materialize_docx_tables(
+ target_container,
+ markup,
+ width_twips=self.usable_width_twips,
+ fill_cell=fill_cell,
+ )
+ except DocxRenderError:
+ self._rollback_table_materialization(
+ target_xml,
+ existing_child_count=existing_child_count,
+ insertion_index=insertion_index,
+ existing_relationship_ids=existing_relationship_ids,
+ )
+ raise
+ except DocxTableError as exc:
+ self._rollback_table_materialization(
+ target_xml,
+ existing_child_count=existing_child_count,
+ insertion_index=insertion_index,
+ existing_relationship_ids=existing_relationship_ids,
+ )
+ raise self._render_error(str(exc), context) from exc
+
+ def _rollback_table_materialization(
+ self,
+ target_xml: etree._Element,
+ *,
+ existing_child_count: int,
+ insertion_index: int,
+ existing_relationship_ids: set[str],
+ ) -> None:
+ """回滚本轮表格新增的 XML 根节点和 relationship,避免残留半成品。"""
+ while len(target_xml) > existing_child_count:
+ target_xml.remove(target_xml[insertion_index])
+ for relationship_id in tuple(self.document.part.rels):
+ if relationship_id not in existing_relationship_ids:
+ self.document.part.drop_rel(relationship_id)
+
+ def _fill_html_cell(
+ self,
+ cell: _Cell,
+ source: Tag,
+ *,
+ write_nested: NestedTableWriter,
+ context: InlineRenderContext,
+ ) -> None:
+ """按源顺序填充单元格文本、图片和任意包装层中的嵌套表格。"""
+ cell.text = ""
+ cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
+ _set_cell_margins(cell, top=100, start=120, bottom=100, end=120)
+ max_image_width_emu = _cell_content_width_emu(cell, horizontal_margin_twips=240)
+ paragraph = cell.paragraphs[0]
+ paragraph.paragraph_format.space_after = Pt(0)
+ paragraph.paragraph_format.line_spacing = 1.0
+
+ for child in source.children:
+ if not isinstance(child, (NavigableString, Tag)):
+ continue
+ if isinstance(child, Tag) and child.name.lower() in {"p", "div"} and _paragraph_has_content(paragraph):
+ paragraph = cell.add_paragraph()
+ paragraph.paragraph_format.space_after = Pt(0)
+ paragraph.paragraph_format.line_spacing = 1.0
+ styles = ("bold",) if source.name == "th" else ()
+ paragraph, _ = self._append_html_node(
+ paragraph,
+ child,
+ cell=cell,
+ write_nested=write_nested,
+ context=context,
+ inherited_styles=styles,
+ max_image_width_emu=max_image_width_emu,
+ )
+
+ def _append_html_node(
+ self,
+ paragraph: Paragraph,
+ node: NavigableString | Tag,
+ *,
+ cell: _Cell,
+ write_nested: NestedTableWriter,
+ context: InlineRenderContext,
+ inherited_styles: tuple[str, ...],
+ max_image_width_emu: int,
+ ) -> tuple[Paragraph, bool]:
+ """按 HTML 源顺序写入单元格行内文本、样式、公式和图片。"""
+ if isinstance(node, NavigableString):
+ text = str(node)
+ if not text:
+ return paragraph, False
+ nodes: list[InlineNode] = [InlineText(text)]
+ if inherited_styles:
+ nodes = [InlineStyled(nodes, inherited_styles)]
+ append_inline_nodes(paragraph, nodes, context=context)
+ return paragraph, bool(text.strip())
+
+ name = node.name.lower()
+ if name == "table":
+ write_nested(node)
+ trailing_paragraph = cell.paragraphs[-1]
+ trailing_paragraph.paragraph_format.space_after = Pt(0)
+ trailing_paragraph.paragraph_format.line_spacing = 1.0
+ return trailing_paragraph, True
+ if name == "img":
+ self._append_html_image(
+ paragraph,
+ str(node.get("src", "")),
+ context=context,
+ alt_text=str(node.get("alt", "")),
+ max_width_emu=max_image_width_emu,
+ )
+ return paragraph, True
+ if name == "br":
+ paragraph.add_run().add_break()
+ return paragraph, True
+ if name == "eq":
+ latex = node.get_text().strip()
+ nodes = [InlineEquation(latex)] if latex else []
+ if inherited_styles and nodes:
+ nodes = [InlineStyled(nodes, inherited_styles)]
+ append_inline_nodes(paragraph, nodes, context=context)
+ return paragraph, bool(nodes)
+ if name == "a":
+ children = _html_inline_nodes(node)
+ if inherited_styles and children:
+ children = [InlineStyled(children, inherited_styles)]
+ append_inline_nodes(
+ paragraph,
+ [InlineLink(children, str(node.get("href", "")).strip())],
+ context=context,
+ )
+ return paragraph, bool(children)
+ if name in {"ul", "ol"}:
+ start_value = node.get("start", "1")
+ try:
+ ordered_number = int(str(start_value))
+ except ValueError:
+ ordered_number = 1
+ rendered = False
+ for item in node.find_all("li", recursive=False):
+ if _paragraph_has_content(paragraph) or rendered:
+ paragraph.add_run().add_break()
+ marker = f"{ordered_number}. " if name == "ol" else "- "
+ paragraph.add_run(marker)
+ if name == "ol":
+ ordered_number += 1
+ for child in item.children:
+ if isinstance(child, (NavigableString, Tag)):
+ paragraph, child_rendered = self._append_html_node(
+ paragraph,
+ child,
+ cell=cell,
+ write_nested=write_nested,
+ context=context,
+ inherited_styles=inherited_styles,
+ max_image_width_emu=max_image_width_emu,
+ )
+ rendered = child_rendered or rendered
+ return paragraph, rendered
+ if name == "li":
+ rendered = False
+ for child in node.children:
+ if isinstance(child, (NavigableString, Tag)):
+ paragraph, child_rendered = self._append_html_node(
+ paragraph,
+ child,
+ cell=cell,
+ write_nested=write_nested,
+ context=context,
+ inherited_styles=inherited_styles,
+ max_image_width_emu=max_image_width_emu,
+ )
+ rendered = child_rendered or rendered
+ return paragraph, rendered
+ if name == "text":
+ nodes = parse_inline_content(str(node))
+ if inherited_styles and nodes:
+ nodes = [InlineStyled(nodes, inherited_styles)]
+ append_inline_nodes(paragraph, nodes, context=context)
+ return paragraph, bool(nodes)
+
+ style = {
+ "strong": "bold",
+ "b": "bold",
+ "em": "italic",
+ "i": "italic",
+ "u": "underline",
+ "s": "strikethrough",
+ "sup": "superscript",
+ "sub": "subscript",
+ }.get(name)
+ styles = tuple(dict.fromkeys((*inherited_styles, style))) if style else inherited_styles
+ rendered = False
+ for child in node.children:
+ if isinstance(child, (NavigableString, Tag)):
+ paragraph, child_rendered = self._append_html_node(
+ paragraph,
+ child,
+ cell=cell,
+ write_nested=write_nested,
+ context=context,
+ inherited_styles=styles,
+ max_image_width_emu=max_image_width_emu,
+ )
+ rendered = child_rendered or rendered
+ return paragraph, rendered
+
+ def _append_html_image(
+ self,
+ paragraph: Paragraph,
+ source: str,
+ *,
+ context: InlineRenderContext,
+ alt_text: str,
+ max_width_emu: int,
+ ) -> None:
+ """安全加载表格单元格 img,并限制到紧凑的单元格宽度。"""
+ try:
+ prepared = prepare_html_image(source, self.asset_resolver)
+ except DocxAssetError as exc:
+ raise self._render_error(str(exc), context) from exc
+ self._append_prepared_image(
+ prepared,
+ bbox=None,
+ alt_text=alt_text or "table image",
+ max_width_emu=min(self.usable_width_emu, max_width_emu),
+ context=context,
+ paragraph=paragraph,
+ )
+
+ def _render_error(self, message: str, context: InlineRenderContext) -> DocxRenderError:
+ """用当前 context 构造带 page/block 定位的公共异常。"""
+ return DocxRenderError(
+ message,
+ page_idx=context.page_idx,
+ block_index=context.block_index,
+ block_type=context.block_type,
+ )
+
+
+def render_docx(
+ middle_json: MiddleJson,
+ *,
+ mode: RenderMode = RenderMode.DEFAULT,
+ asset_resolver: AssetResolver | None = None,
+) -> bytes:
+ """把严格 MiddleJson 无副作用地渲染为完整 DOCX bytes。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render_docx expects a MiddleJson instance")
+ if not isinstance(mode, RenderMode):
+ raise TypeError("mode must be a RenderMode value")
+ return _DocxRenderer(
+ middle_json,
+ mode=mode,
+ asset_resolver=asset_resolver,
+ ).render()
+
+
+def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:
+ """按文档顺序遍历实际会写入 bookmark 的正文标题 anchor。"""
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if isinstance(block, TitleBlockBase) and block.anchor:
+ yield block.anchor
+
+
+def _strip_index_page_tail(content: str) -> str:
+ """删除目录末尾可信页码,并把其余 tab 转换为普通空格。"""
+ if "\t" not in content:
+ return content
+ head, tail = content.rsplit("\t", 1)
+ tail_text = plain_inline_text(tail).strip()
+ if _looks_like_index_page_token(tail_text):
+ content = head
+ return content.replace("\t", " ")
+
+
+def _looks_like_index_page_token(content: str) -> bool:
+ """判断目录 tab 后缀是否为数字、罗马数字或单字母页码。"""
+ if not content or len(content) > 12:
+ return False
+ return bool(content.isdigit() or _INDEX_ROMAN_RE.fullmatch(content) or re.fullmatch(r"[A-Za-z]", content))
+
+
+def _plain_html_text(content: str) -> str:
+ """把图片或图表 body 内容收敛为适合 alt description 的纯文本。"""
+ if not content.strip():
+ return ""
+ return BeautifulSoup(content, "html.parser").get_text(" ", strip=True)
+
+
+def _html_inline_nodes(node: Tag) -> list[InlineNode]:
+ """把表格单元格中的安全 HTML 行内标签转换为共享 InlineNode。"""
+ nodes: list[InlineNode] = []
+ for child in node.children:
+ if isinstance(child, NavigableString):
+ if str(child):
+ nodes.append(InlineText(str(child)))
+ continue
+ if not isinstance(child, Tag):
+ continue
+ name = child.name.lower()
+ children = _html_inline_nodes(child)
+ if name == "eq":
+ latex = child.get_text().strip()
+ if latex:
+ nodes.append(InlineEquation(latex))
+ elif name in {"strong", "b"}:
+ nodes.append(InlineStyled(children, ("bold",)))
+ elif name in {"em", "i"}:
+ nodes.append(InlineStyled(children, ("italic",)))
+ elif name == "u":
+ nodes.append(InlineStyled(children, ("underline",)))
+ elif name == "s":
+ nodes.append(InlineStyled(children, ("strikethrough",)))
+ elif name == "sup":
+ nodes.append(InlineStyled(children, ("superscript",)))
+ elif name == "sub":
+ nodes.append(InlineStyled(children, ("subscript",)))
+ elif name == "a":
+ nodes.append(InlineLink(children, str(child.get("href", "")).strip()))
+ elif name == "br":
+ nodes.append(InlineText("\n"))
+ elif name == "text":
+ nodes.extend(parse_inline_content(str(child)))
+ elif name not in {"img", "table"}:
+ nodes.extend(children)
+ return nodes
+
+
+def _set_cell_margins(
+ cell: _Cell,
+ *,
+ top: int,
+ start: int,
+ bottom: int,
+ end: int,
+) -> None:
+ """用 DXA 为 Word 单元格写入四边内边距。"""
+ cell_properties = cell._tc.get_or_add_tcPr()
+ margins = cell_properties.find(qn("w:tcMar"))
+ if margins is None:
+ margins = OxmlElement("w:tcMar")
+ cell_properties.append(margins)
+ for side, value in (("top", top), ("start", start), ("bottom", bottom), ("end", end)):
+ element = margins.find(qn(f"w:{side}"))
+ if element is None:
+ element = OxmlElement(f"w:{side}")
+ margins.append(element)
+ element.set(qn("w:w"), str(value))
+ element.set(qn("w:type"), "dxa")
+
+
+def _cell_content_width_emu(cell: _Cell, *, horizontal_margin_twips: int) -> int:
+ """从当前物理或合并单元格 tcW 计算扣除左右内边距后的可用宽度。"""
+ cell_width = cell._tc.get_or_add_tcPr().get_or_add_tcW().w
+ width_twips = int(cell_width) if cell_width is not None else 1
+ return int(Twips(max(1, width_twips - horizontal_margin_twips)))
+
+
+def _paragraph_has_content(paragraph: Paragraph) -> bool:
+ """判断段落是否包含 pPr 之外的 run、公式、链接或 drawing。"""
+ return any(child.tag != qn("w:pPr") for child in paragraph._p)
+
+
+__all__ = ["DocxRenderError", "render_docx"]
diff --git a/mineru/render/utils/docx_assets.py b/mineru/render/utils/docx_assets.py
new file mode 100644
index 00000000..baae2b84
--- /dev/null
+++ b/mineru/render/utils/docx_assets.py
@@ -0,0 +1,191 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""DOCX renderer 使用的安全图片素材解析与格式准备。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from io import BytesIO
+from pathlib import PurePosixPath
+import re
+from typing import Callable, TypeAlias
+from urllib.parse import urlsplit
+
+from PIL import Image, UnidentifiedImageError
+
+from mineru.types import ImagePayloadBlock
+from mineru.utils.image_payload import parse_image_data_uri_strict, validate_image_sidecar_path
+
+AssetResolver: TypeAlias = Callable[[str], bytes]
+
+_PIL_FORMAT_EXTENSIONS = {
+ "BMP": "bmp",
+ "GIF": "gif",
+ "JPEG": "jpg",
+ "PNG": "png",
+ "TIFF": "tiff",
+ "WEBP": "webp",
+}
+_EXTENSION_ALIASES = {
+ "jpeg": "jpg",
+ "jpe": "jpg",
+ "tif": "tiff",
+}
+_SVG_START_RE = re.compile(rb"^(?:\xef\xbb\xbf)?\s*(?:<\?xml\b.*?\?>\s*)?<svg\b", re.IGNORECASE | re.DOTALL)
+
+
+class DocxAssetError(ValueError):
+ """表示 DOCX renderer 无法安全加载或识别图片素材。"""
+
+
+@dataclass(frozen=True, slots=True)
+class PreparedImage:
+ """保存可直接交给 DOCX 的图片字节、格式与像素尺寸。"""
+
+ data: bytes
+ extension: str
+ width_px: int
+ height_px: int
+
+
+def prepare_block_image(
+ block: ImagePayloadBlock,
+ asset_resolver: AssetResolver | None = None,
+) -> PreparedImage:
+ """从图片载荷 block 加载图片,始终优先使用内嵌 data URI。"""
+ if not isinstance(block, ImagePayloadBlock):
+ raise TypeError("block must be an ImagePayloadBlock")
+ if block.image_base64 is not None:
+ return _prepare_data_uri(block.image_base64)
+ if block.image_path is not None:
+ return _prepare_relative_asset(block.image_path, asset_resolver)
+ raise DocxAssetError("Image block does not contain image_base64 or image_path")
+
+
+def prepare_html_image(
+ source: str,
+ asset_resolver: AssetResolver | None = None,
+) -> PreparedImage:
+ """从 HTML ``img`` 的 src 加载 data URI 或安全的相对 sidecar 图片。"""
+ if not isinstance(source, str):
+ raise TypeError("HTML image source must be a string")
+ normalized_source = source.strip()
+ if not normalized_source:
+ raise DocxAssetError("HTML image source must not be empty")
+ if normalized_source.lower().startswith("data:"):
+ if not normalized_source.lower().startswith("data:image/"):
+ raise DocxAssetError("Only image data URIs are supported")
+ return _prepare_data_uri(normalized_source)
+ return _prepare_relative_asset(normalized_source, asset_resolver)
+
+
+def prepare_image_bytes(
+ data: bytes,
+ *,
+ declared_extension: str | None = None,
+) -> PreparedImage:
+ """严格解码图片字节,并将 Word 不直接支持的 WebP 在内存中转为 PNG。"""
+ if not isinstance(data, bytes):
+ raise DocxAssetError("Image resolver must return bytes")
+ if not data:
+ raise DocxAssetError("Image payload must not be empty")
+
+ expected_extension = _normalize_extension(declared_extension)
+ if expected_extension == "svg" or _looks_like_svg(data):
+ raise DocxAssetError("SVG images are not supported by the DOCX renderer")
+
+ try:
+ with Image.open(BytesIO(data)) as image:
+ detected_extension = _PIL_FORMAT_EXTENSIONS.get((image.format or "").upper())
+ if detected_extension is None:
+ raise DocxAssetError(f"Unsupported image format: {image.format or 'unknown'}")
+ width_px, height_px = image.size
+ image.load()
+ if expected_extension is not None and expected_extension != detected_extension:
+ raise DocxAssetError(
+ f"Image bytes do not match declared format: expected {expected_extension}, detected {detected_extension}"
+ )
+ if detected_extension == "webp":
+ return _convert_webp_to_png(image, width_px, height_px)
+ except DocxAssetError:
+ raise
+ except (UnidentifiedImageError, OSError, ValueError) as exc:
+ raise DocxAssetError("Invalid or corrupted image payload") from exc
+
+ return PreparedImage(
+ data=data,
+ extension=detected_extension,
+ width_px=width_px,
+ height_px=height_px,
+ )
+
+
+def _prepare_data_uri(data_uri: str) -> PreparedImage:
+ """严格解析 data URI,并校验 MIME、签名和完整图片数据。"""
+ try:
+ data, extension = parse_image_data_uri_strict(data_uri)
+ except ValueError as exc:
+ raise DocxAssetError(str(exc)) from exc
+ if extension == "svg":
+ raise DocxAssetError("SVG images are not supported by the DOCX renderer")
+ return prepare_image_bytes(data, declared_extension=extension)
+
+
+def _prepare_relative_asset(
+ image_path: str,
+ asset_resolver: AssetResolver | None,
+) -> PreparedImage:
+ """校验相对 sidecar 路径,通过调用方 resolver 读取字节且不访问文件系统或网络。"""
+ parsed_source = urlsplit(image_path)
+ if parsed_source.scheme or parsed_source.netloc:
+ raise DocxAssetError(f"Remote or scheme-based image source is not supported: {image_path}")
+ try:
+ safe_path = validate_image_sidecar_path(image_path)
+ except ValueError as exc:
+ raise DocxAssetError(str(exc)) from exc
+ if asset_resolver is None:
+ raise DocxAssetError(f"asset_resolver is required for image_path: {safe_path}")
+ try:
+ data = asset_resolver(safe_path)
+ except Exception as exc:
+ raise DocxAssetError(f"Failed to resolve image asset: {safe_path}") from exc
+
+ extension = PurePosixPath(safe_path).suffix.removeprefix(".") or None
+ return prepare_image_bytes(data, declared_extension=extension)
+
+
+def _normalize_extension(extension: str | None) -> str | None:
+ """规范化可识别的扩展名;未知扩展名不作为图片格式声明。"""
+ if extension is None:
+ return None
+ normalized = extension.lower().lstrip(".").split("+", 1)[0]
+ normalized = _EXTENSION_ALIASES.get(normalized, normalized)
+ if normalized == "svg":
+ return normalized
+ return normalized if normalized in set(_PIL_FORMAT_EXTENSIONS.values()) else None
+
+
+def _looks_like_svg(data: bytes) -> bool:
+ """识别带可选 BOM/XML 声明的 SVG 字节,以便给出明确的不支持错误。"""
+ return _SVG_START_RE.match(data[:4096]) is not None
+
+
+def _convert_webp_to_png(image: Image.Image, width_px: int, height_px: int) -> PreparedImage:
+ """在内存中把已解码 WebP 转换为 PNG,保留透明通道与像素尺寸。"""
+ output = BytesIO()
+ image.save(output, format="PNG")
+ return PreparedImage(
+ data=output.getvalue(),
+ extension="png",
+ width_px=width_px,
+ height_px=height_px,
+ )
+
+
+__all__ = [
+ "AssetResolver",
+ "DocxAssetError",
+ "PreparedImage",
+ "prepare_block_image",
+ "prepare_html_image",
+ "prepare_image_bytes",
+]
diff --git a/mineru/render/utils/docx_inline.py b/mineru/render/utils/docx_inline.py
new file mode 100644
index 00000000..851e1c58
--- /dev/null
+++ b/mineru/render/utils/docx_inline.py
@@ -0,0 +1,377 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""MiddleJson 行内节点到 Word run、超链接、书签和 OMML 的写入工具。"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+from hashlib import sha1
+import re
+
+from docx.opc.constants import RELATIONSHIP_TYPE
+from docx.oxml import OxmlElement
+from docx.oxml.ns import qn
+from docx.text.paragraph import Paragraph
+from docx.text.run import Run
+from docx.shared import Pt, RGBColor
+from lxml import etree
+from loguru import logger
+
+from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml
+from mineru.render.utils.inline import (
+ InlineEquation,
+ InlineLink,
+ InlineNode,
+ InlineStyled,
+ InlineText,
+ inline_plain_text,
+ join_inline_contents,
+ parse_inline_content,
+)
+
+_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*$")
+
+
+@dataclass(frozen=True, slots=True)
+class InlineRenderContext:
+ """保存行内渲染告警所需的 block 定位与书签表。"""
+
+ bookmarks: BookmarkRegistry
+ page_idx: int
+ block_index: int | None
+ block_type: str
+
+ def location(self) -> str:
+ """返回稳定、可读的 page/block 定位文本。"""
+ return f"page_idx={self.page_idx}, block_index={self.block_index}, block_type={self.block_type}"
+
+
+class BookmarkRegistry:
+ """把 MiddleJson anchor 映射为合法且唯一的 Word bookmark 名称。"""
+
+ def __init__(self, anchors: Iterable[str]) -> None:
+ """预注册全部 anchor,保证目录前向引用可在写正文前解析。"""
+ self._names: dict[str, str] = {}
+ self._attached: set[str] = set()
+ self._used_names: set[str] = set()
+ self._next_id = 0
+ for anchor in anchors:
+ normalized = anchor.strip()
+ if normalized and normalized not in self._names:
+ self._names[normalized] = self._allocate_name(normalized)
+
+ def _allocate_name(self, anchor: str) -> str:
+ """为一个原始 anchor 分配满足 Word 限制的确定性名称。"""
+ base = _BOOKMARK_SAFE_RE.sub("_", anchor).strip("_")
+ if not base or not base[0].isalpha():
+ base = f"b_{base}"
+ candidate = base[:_BOOKMARK_MAX_LENGTH]
+ if candidate not in self._used_names:
+ self._used_names.add(candidate)
+ return candidate
+
+ digest = sha1(anchor.encode("utf-8")).hexdigest()[:8]
+ prefix_length = _BOOKMARK_MAX_LENGTH - len(digest) - 1
+ candidate = f"{base[:prefix_length]}_{digest}"
+ ordinal = 1
+ while candidate in self._used_names:
+ suffix = f"_{ordinal}"
+ candidate = f"{base[: _BOOKMARK_MAX_LENGTH - len(suffix)]}{suffix}"
+ ordinal += 1
+ self._used_names.add(candidate)
+ return candidate
+
+ def resolve(self, anchor: str | None) -> str | None:
+ """解析已注册 anchor;空值或未知 anchor 返回 None。"""
+ if not anchor:
+ return None
+ return self._names.get(anchor.strip())
+
+ def attach(self, paragraph: Paragraph, anchor: str | None) -> bool:
+ """把 anchor bookmark 包围当前段落内容;重复正文 anchor 只保留首个。"""
+ normalized = (anchor or "").strip()
+ name = self.resolve(normalized)
+ if name is None:
+ return False
+ if normalized in self._attached:
+ logger.warning("Duplicate DOCX bookmark anchor ignored: {}", normalized)
+ return False
+
+ bookmark_id = str(self._next_id)
+ self._next_id += 1
+ start = OxmlElement("w:bookmarkStart")
+ start.set(qn("w:id"), bookmark_id)
+ start.set(qn("w:name"), name)
+ end = OxmlElement("w:bookmarkEnd")
+ end.set(qn("w:id"), bookmark_id)
+
+ paragraph_xml = paragraph._p
+ insert_at = 1 if paragraph_xml.pPr is not None else 0
+ paragraph_xml.insert(insert_at, start)
+ paragraph_xml.append(end)
+ self._attached.add(normalized)
+ return True
+
+
+def append_inline_content(
+ paragraph: Paragraph,
+ content: str,
+ *,
+ context: InlineRenderContext,
+) -> None:
+ """解析并把一段 MiddleJson 行内内容追加到 Word 段落。"""
+ append_inline_nodes(paragraph, parse_inline_content(content), context=context)
+
+
+def append_joined_inline_contents(
+ paragraph: Paragraph,
+ contents: list[str],
+ *,
+ context: InlineRenderContext,
+) -> None:
+ """按共享边界规则合并续段,并把中性行内节点写入 Word。"""
+ append_inline_nodes(paragraph, join_inline_contents(contents), context=context)
+
+
+def append_inline_nodes(
+ paragraph: Paragraph,
+ nodes: list[InlineNode],
+ *,
+ context: InlineRenderContext,
+ inherited_styles: tuple[str, ...] = (),
+) -> None:
+ """把行内节点写入段落,同时保留嵌套样式、链接与公式语义。"""
+ _append_nodes_to_container(
+ paragraph._p,
+ paragraph,
+ nodes,
+ context=context,
+ inherited_styles=inherited_styles,
+ hyperlink=False,
+ )
+
+
+def append_internal_link(
+ paragraph: Paragraph,
+ label_nodes: list[InlineNode],
+ *,
+ anchor: str | None,
+ context: InlineRenderContext,
+) -> bool:
+ """把目录标签写为内部链接;目标缺失时退回普通行内内容。"""
+ bookmark_name = context.bookmarks.resolve(anchor)
+ if bookmark_name is None:
+ append_inline_nodes(paragraph, label_nodes, context=context)
+ if anchor:
+ logger.warning("Unmatched DOCX index anchor: {} ({})", anchor, context.location())
+ return False
+
+ hyperlink = OxmlElement("w:hyperlink")
+ hyperlink.set(qn("w:anchor"), bookmark_name)
+ hyperlink.set(qn("w:history"), "1")
+ paragraph._p.append(hyperlink)
+ _append_nodes_to_container(
+ hyperlink,
+ paragraph,
+ label_nodes,
+ context=context,
+ inherited_styles=(),
+ hyperlink=True,
+ )
+ return True
+
+
+def _append_nodes_to_container(
+ container: etree._Element,
+ paragraph: Paragraph,
+ nodes: list[InlineNode],
+ *,
+ context: InlineRenderContext,
+ inherited_styles: tuple[str, ...],
+ hyperlink: bool,
+) -> None:
+ """递归写入一个段落或 hyperlink XML 容器。"""
+ for node in nodes:
+ if isinstance(node, InlineText):
+ _append_text_run(
+ container,
+ paragraph,
+ node.content,
+ styles=inherited_styles,
+ hyperlink=hyperlink,
+ context=context,
+ )
+ continue
+ if isinstance(node, InlineStyled):
+ styles = tuple(dict.fromkeys((*inherited_styles, *node.styles)))
+ _append_nodes_to_container(
+ container,
+ paragraph,
+ node.children,
+ context=context,
+ inherited_styles=styles,
+ hyperlink=hyperlink,
+ )
+ continue
+ if isinstance(node, InlineEquation):
+ bare_script = _BARE_SCRIPT_RE.fullmatch(node.latex)
+ if bare_script is not None:
+ script_style = "superscript" if bare_script.group("marker") == "^" else "subscript"
+ styles = tuple(dict.fromkeys((*inherited_styles, script_style)))
+ _append_text_run(
+ container,
+ paragraph,
+ bare_script.group("content"),
+ styles=styles,
+ hyperlink=hyperlink,
+ context=context,
+ )
+ continue
+ if hyperlink:
+ _append_text_run(
+ container,
+ paragraph,
+ node.latex,
+ styles=inherited_styles,
+ hyperlink=True,
+ context=context,
+ )
+ continue
+ try:
+ container.append(latex_to_omml(node.latex, display=False))
+ except DocxFormulaError as exc:
+ logger.warning("DOCX inline formula fallback: {} ({})", exc, context.location())
+ _append_text_run(
+ container,
+ paragraph,
+ node.latex,
+ styles=inherited_styles,
+ hyperlink=False,
+ formula_fallback=True,
+ context=context,
+ )
+ continue
+ if isinstance(node, InlineLink):
+ if hyperlink or not node.url or node.url == ".":
+ _append_nodes_to_container(
+ container,
+ paragraph,
+ node.children,
+ context=context,
+ inherited_styles=inherited_styles,
+ hyperlink=hyperlink,
+ )
+ continue
+ _append_external_link(
+ paragraph,
+ node,
+ context=context,
+ inherited_styles=inherited_styles,
+ )
+ continue
+ raise TypeError(f"Unsupported inline node: {type(node).__name__}")
+
+
+def _append_external_link(
+ paragraph: Paragraph,
+ node: InlineLink,
+ *,
+ context: InlineRenderContext,
+ inherited_styles: tuple[str, ...],
+) -> None:
+ """创建外部 hyperlink relationship,并写入完整标签内容。"""
+ relation_id = paragraph.part.relate_to(
+ sanitize_xml_text(node.url, context=context),
+ RELATIONSHIP_TYPE.HYPERLINK,
+ is_external=True,
+ )
+ hyperlink = OxmlElement("w:hyperlink")
+ hyperlink.set(qn("r:id"), relation_id)
+ paragraph._p.append(hyperlink)
+ _append_nodes_to_container(
+ hyperlink,
+ paragraph,
+ node.children,
+ context=context,
+ inherited_styles=inherited_styles,
+ hyperlink=True,
+ )
+
+
+def _append_text_run(
+ container: etree._Element,
+ paragraph: Paragraph,
+ content: str,
+ *,
+ styles: tuple[str, ...],
+ hyperlink: bool,
+ context: InlineRenderContext,
+ formula_fallback: bool = False,
+) -> Run:
+ """向 XML 容器追加一个 run,并应用 MiddleJson 行内样式。"""
+ run_xml = OxmlElement("w:r")
+ container.append(run_xml)
+ run = Run(run_xml, paragraph)
+ run.text = sanitize_xml_text(content, context=context)
+ _apply_run_styles(run, styles)
+ if hyperlink:
+ run.font.color.rgb = _rgb_color("0563C1")
+ run.underline = True
+ if formula_fallback:
+ run.font.name = "Courier New"
+ run.font.size = Pt(9)
+ run.font.color.rgb = _rgb_color("555555")
+ return run
+
+
+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)
+ if replacement_count:
+ logger.warning(
+ "DOCX replaced {} XML-incompatible character(s) with U+FFFD ({})",
+ replacement_count,
+ context.location(),
+ )
+ return sanitized
+
+
+def _apply_run_styles(run: Run, styles: tuple[str, ...]) -> None:
+ """把已解析的行内样式应用到 Word run。"""
+ style_set = set(styles)
+ run.bold = "bold" in style_set
+ run.italic = "italic" in style_set
+ run.underline = "underline" in style_set
+ run.font.strike = "strikethrough" in style_set
+ run.font.superscript = "superscript" in style_set
+ run.font.subscript = "subscript" in style_set and "superscript" not in style_set
+ if "emphasis" in style_set:
+ run_properties = run._element.get_or_add_rPr()
+ emphasis = OxmlElement("w:em")
+ emphasis.set(qn("w:val"), "dot")
+ run_properties.append(emphasis)
+
+
+def _rgb_color(value: str) -> RGBColor:
+ """延迟构造 RGBColor,避免在模块常量阶段加载额外对象。"""
+ return RGBColor.from_string(value)
+
+
+def plain_inline_text(content: str) -> str:
+ """提取一段 MiddleJson 行内内容的可见文本。"""
+ return inline_plain_text(parse_inline_content(content))
+
+
+__all__ = [
+ "BookmarkRegistry",
+ "InlineRenderContext",
+ "append_inline_content",
+ "append_inline_nodes",
+ "append_internal_link",
+ "append_joined_inline_contents",
+ "plain_inline_text",
+ "sanitize_xml_text",
+]
diff --git a/mineru/render/utils/docx_math.py b/mineru/render/utils/docx_math.py
new file mode 100644
index 00000000..72a34a71
--- /dev/null
+++ b/mineru/render/utils/docx_math.py
@@ -0,0 +1,158 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""DOCX 渲染使用的 LaTeX 与 OMML 转换工具。"""
+
+from __future__ import annotations
+
+from latex2mathml.converter import convert as latex_to_mathml
+from lxml import etree
+from mathml2omml import convert as mathml_to_omml
+import re
+
+_OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+_EMPTY_SCRIPT_RE = re.compile(r"(?:_\s*\{\s*\}|\^\s*\{\s*\})")
+
+
+class DocxFormulaError(ValueError):
+ """表示 LaTeX 无法转换为可插入 DOCX 的 OMML。"""
+
+
+def split_formula_tag(content: str) -> tuple[str, str | None]:
+ """剥离公式末尾括号平衡的 ``\\tag{...}``,并返回正文与编号。"""
+ stripped_end = len(content.rstrip())
+ if stripped_end == 0 or content[stripped_end - 1] != "}":
+ return content, None
+
+ search_end = stripped_end
+ while (tag_start := content.rfind(r"\tag", 0, search_end)) >= 0:
+ if not _is_escaped_command(content, tag_start):
+ opening_brace = _find_tag_opening_brace(content, tag_start, stripped_end)
+ if opening_brace is not None:
+ closing_brace = _find_balanced_closing_brace(content, opening_brace, stripped_end)
+ if closing_brace == stripped_end - 1:
+ formula = content[:tag_start].rstrip()
+ tag = content[opening_brace + 1 : closing_brace].strip()
+ return formula, tag
+ search_end = tag_start
+
+ return content, None
+
+
+def latex_to_omml(latex: str, *, display: bool) -> etree._Element:
+ """把 LaTeX 转换为带命名空间、可直接插入 DOCX 的 OMML 节点。"""
+ try:
+ normalized_latex = _EMPTY_SCRIPT_RE.sub("", 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)
+ _normalize_omml(equation)
+ if not display:
+ return equation
+
+ paragraph = etree.Element(
+ etree.QName(_OFFICE_MATH_NAMESPACE, "oMathPara"),
+ nsmap={"m": _OFFICE_MATH_NAMESPACE},
+ )
+ paragraph.append(equation)
+ return paragraph
+ except Exception as exc:
+ raise DocxFormulaError(f"LaTeX 公式无法转换为 OMML: {latex!r}") from exc
+
+
+def _repair_mathml2omml_xml(omml_xml: str) -> str:
+ """修复 mathml2omml 0.0.2 对 groupChrPr 写出的错误闭合标签。"""
+ return omml_xml.replace(
+ "</m:groupChr><m:e>",
+ "</m:groupChrPr><m:e>",
+ )
+
+
+def _normalize_omml(equation: etree._Element) -> None:
+ """补齐 Word 要求的根号属性,并隐藏无显式底数的脚本占位框。"""
+ namespace = f"{{{_OFFICE_MATH_NAMESPACE}}}"
+ for radical in equation.findall(f".//{namespace}rad"):
+ if radical.find(f"{namespace}deg") is not None:
+ continue
+ properties = etree.Element(etree.QName(_OFFICE_MATH_NAMESPACE, "radPr"))
+ degree_hidden = etree.SubElement(
+ properties,
+ etree.QName(_OFFICE_MATH_NAMESPACE, "degHide"),
+ )
+ degree_hidden.set(etree.QName(_OFFICE_MATH_NAMESPACE, "val"), "1")
+ degree = etree.Element(etree.QName(_OFFICE_MATH_NAMESPACE, "deg"))
+ radical.insert(0, properties)
+ radical.insert(1, degree)
+
+ for script_name in ("sSup", "sSub", "sSubSup"):
+ for script in equation.findall(f".//{namespace}{script_name}"):
+ base = script.find(f"{namespace}e")
+ if base is None or "".join(base.itertext()).strip():
+ continue
+ text = base.find(f".//{namespace}t")
+ if text is None:
+ run = etree.SubElement(base, etree.QName(_OFFICE_MATH_NAMESPACE, "r"))
+ text = etree.SubElement(run, etree.QName(_OFFICE_MATH_NAMESPACE, "t"))
+ text.text = "\u200b"
+
+
+def _is_escaped_command(content: str, command_start: int) -> bool:
+ """判断命令起始反斜杠是否被前一个反斜杠转义。"""
+ preceding_backslashes = 0
+ cursor = command_start - 1
+ while cursor >= 0 and content[cursor] == "\\":
+ preceding_backslashes += 1
+ cursor -= 1
+ return preceding_backslashes % 2 == 1
+
+
+def _find_tag_opening_brace(content: str, tag_start: int, content_end: int) -> int | None:
+ """查找 tag 命令允许空白后的左花括号。"""
+ cursor = tag_start + len(r"\tag")
+ while cursor < content_end and content[cursor].isspace():
+ cursor += 1
+ if cursor >= content_end or content[cursor] != "{":
+ return None
+ return cursor
+
+
+def _find_balanced_closing_brace(content: str, opening_brace: int, content_end: int) -> int | None:
+ """查找与 tag 左花括号配对的右花括号,并忽略转义花括号。"""
+ depth = 0
+ for cursor in range(opening_brace, content_end):
+ character = content[cursor]
+ if character not in "{}" or _is_escaped_character(content, cursor):
+ continue
+ depth += 1 if character == "{" else -1
+ if depth == 0:
+ return cursor
+ if depth < 0:
+ return None
+ return None
+
+
+def _is_escaped_character(content: str, position: int) -> bool:
+ """判断指定字符前是否存在奇数个连续反斜杠。"""
+ preceding_backslashes = 0
+ cursor = position - 1
+ while cursor >= 0 and content[cursor] == "\\":
+ preceding_backslashes += 1
+ cursor -= 1
+ return preceding_backslashes % 2 == 1
+
+
+def _parse_omml(omml_xml: str) -> etree._Element:
+ """为第三方库返回的未绑定 ``m`` 前缀补充命名空间并解析节点。"""
+ wrapper_xml = f'<docx-math-root xmlns:m="{_OFFICE_MATH_NAMESPACE}">{omml_xml}</docx-math-root>'
+ parser = etree.XMLParser(resolve_entities=False, no_network=True, recover=False)
+ wrapper = etree.fromstring(wrapper_xml.encode("utf-8"), parser=parser)
+ if len(wrapper) != 1:
+ raise ValueError("OMML 转换结果必须只包含一个根节点")
+
+ equation = wrapper[0]
+ expected_tag = etree.QName(_OFFICE_MATH_NAMESPACE, "oMath")
+ if equation.tag != expected_tag:
+ raise ValueError("OMML 转换结果的根节点必须是 m:oMath")
+ wrapper.remove(equation)
+ return equation
+
+
+__all__ = ["DocxFormulaError", "latex_to_omml", "split_formula_tag"]
diff --git a/mineru/render/utils/docx_styles.py b/mineru/render/utils/docx_styles.py
new file mode 100644
index 00000000..8d9e6f74
--- /dev/null
+++ b/mineru/render/utils/docx_styles.py
@@ -0,0 +1,198 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""DOCX renderer 的页面几何与显式 Word 样式定义。"""
+
+from __future__ import annotations
+
+from docx.document import Document
+from docx.enum.style import WD_STYLE_TYPE
+from docx.enum.text import WD_ALIGN_PARAGRAPH
+from docx.oxml import OxmlElement
+from docx.oxml.ns import qn
+from docx.shared import Mm, Pt, RGBColor
+from docx.styles.style import _ParagraphStyle
+
+BODY_STYLE = "Normal"
+CODE_STYLE = "MinerU Code"
+CAPTION_STYLE = "MinerU Caption"
+FOOTNOTE_STYLE = "MinerU Footnote"
+AUXILIARY_STYLE = "MinerU Auxiliary"
+FORMULA_FALLBACK_STYLE = "MinerU Formula Fallback"
+
+_HEADING_SIZES = (20, 18, 16, 14, 13, 12, 11, 10.5, 10.5)
+
+
+def configure_document(document: Document) -> None:
+ """设置 A4 页面几何,并创建 renderer 使用的全部显式样式。"""
+ section = document.sections[0]
+ section.page_width = Mm(210)
+ section.page_height = Mm(297)
+ section.top_margin = Mm(20)
+ section.bottom_margin = Mm(20)
+ section.left_margin = Mm(20)
+ section.right_margin = Mm(20)
+
+ normal = document.styles[BODY_STYLE]
+ _configure_paragraph_style(
+ normal,
+ western_font="Times New Roman",
+ east_asia_font="宋体",
+ size_pt=10.5,
+ space_before_pt=0,
+ space_after_pt=6,
+ line_spacing=1.15,
+ )
+ for level, size_pt in enumerate(_HEADING_SIZES, start=1):
+ heading = document.styles[f"Heading {level}"]
+ _configure_paragraph_style(
+ heading,
+ western_font="Arial",
+ east_asia_font="黑体",
+ size_pt=size_pt,
+ bold=True,
+ space_before_pt=10 if level <= 3 else 8,
+ space_after_pt=5 if level <= 3 else 4,
+ line_spacing=1.0,
+ )
+ heading.paragraph_format.keep_with_next = True
+
+ code = _get_or_add_paragraph_style(document, CODE_STYLE)
+ _configure_paragraph_style(
+ code,
+ western_font="Courier New",
+ east_asia_font="宋体",
+ size_pt=9,
+ space_before_pt=4,
+ space_after_pt=6,
+ line_spacing=1.0,
+ )
+ _set_paragraph_shading(code, "F3F4F6")
+
+ caption = _get_or_add_paragraph_style(document, CAPTION_STYLE)
+ _configure_paragraph_style(
+ caption,
+ western_font="Times New Roman",
+ east_asia_font="宋体",
+ size_pt=9,
+ space_before_pt=3,
+ space_after_pt=5,
+ line_spacing=1.0,
+ )
+ caption.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
+ caption.paragraph_format.keep_with_next = True
+
+ footnote = _get_or_add_paragraph_style(document, FOOTNOTE_STYLE)
+ _configure_paragraph_style(
+ footnote,
+ western_font="Times New Roman",
+ east_asia_font="宋体",
+ size_pt=8,
+ color="666666",
+ space_before_pt=2,
+ space_after_pt=4,
+ line_spacing=1.0,
+ )
+
+ auxiliary = _get_or_add_paragraph_style(document, AUXILIARY_STYLE)
+ _configure_paragraph_style(
+ auxiliary,
+ western_font="Times New Roman",
+ east_asia_font="宋体",
+ size_pt=8,
+ italic=True,
+ color="777777",
+ space_before_pt=2,
+ space_after_pt=3,
+ line_spacing=1.0,
+ )
+
+ formula_fallback = _get_or_add_paragraph_style(document, FORMULA_FALLBACK_STYLE)
+ _configure_paragraph_style(
+ formula_fallback,
+ western_font="Courier New",
+ east_asia_font="宋体",
+ size_pt=9,
+ color="555555",
+ space_before_pt=4,
+ space_after_pt=5,
+ line_spacing=1.0,
+ )
+ formula_fallback.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
+
+
+def usable_width_twips(document: Document) -> int:
+ """返回首个 section 扣除左右页边距后的可用宽度,单位 twip。"""
+ section = document.sections[0]
+ usable_emu = int(section.page_width) - int(section.left_margin) - int(section.right_margin)
+ return max(1, round(usable_emu / 635))
+
+
+def usable_width_emu(document: Document) -> int:
+ """返回首个 section 扣除左右页边距后的可用宽度,单位 EMU。"""
+ section = document.sections[0]
+ return max(1, int(section.page_width) - int(section.left_margin) - int(section.right_margin))
+
+
+def _get_or_add_paragraph_style(document: Document, name: str) -> _ParagraphStyle:
+ """获取既有段落样式,缺失时创建同名样式。"""
+ styles = document.styles
+ try:
+ style = styles[name]
+ except KeyError:
+ style = styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH)
+ if not isinstance(style, _ParagraphStyle):
+ raise TypeError(f"Style is not a paragraph style: {name}")
+ return style
+
+
+def _configure_paragraph_style(
+ style: _ParagraphStyle,
+ *,
+ western_font: str,
+ east_asia_font: str,
+ size_pt: float,
+ bold: bool = False,
+ italic: bool = False,
+ color: str | None = None,
+ space_before_pt: float,
+ space_after_pt: float,
+ line_spacing: float,
+) -> None:
+ """给一个 Word 段落样式写入确定性的字体与段落节奏。"""
+ style.font.name = western_font
+ style.font.size = Pt(size_pt)
+ style.font.bold = bold
+ style.font.italic = italic
+ if color is not None:
+ style.font.color.rgb = RGBColor.from_string(color)
+ run_properties = style._element.get_or_add_rPr()
+ run_fonts = run_properties.get_or_add_rFonts()
+ run_fonts.set(qn("w:ascii"), western_font)
+ run_fonts.set(qn("w:hAnsi"), western_font)
+ run_fonts.set(qn("w:eastAsia"), east_asia_font)
+ paragraph_format = style.paragraph_format
+ paragraph_format.space_before = Pt(space_before_pt)
+ paragraph_format.space_after = Pt(space_after_pt)
+ paragraph_format.line_spacing = line_spacing
+
+
+def _set_paragraph_shading(style: _ParagraphStyle, fill: str) -> None:
+ """给段落样式设置稳定的背景色。"""
+ paragraph_properties = style._element.get_or_add_pPr()
+ shading = paragraph_properties.find(qn("w:shd"))
+ if shading is None:
+ shading = OxmlElement("w:shd")
+ paragraph_properties.append(shading)
+ shading.set(qn("w:fill"), fill)
+
+
+__all__ = [
+ "AUXILIARY_STYLE",
+ "BODY_STYLE",
+ "CAPTION_STYLE",
+ "CODE_STYLE",
+ "FOOTNOTE_STYLE",
+ "FORMULA_FALLBACK_STYLE",
+ "configure_document",
+ "usable_width_emu",
+ "usable_width_twips",
+]
diff --git a/mineru/render/utils/docx_table.py b/mineru/render/utils/docx_table.py
new file mode 100644
index 00000000..7d2c2600
--- /dev/null
+++ b/mineru/render/utils/docx_table.py
@@ -0,0 +1,443 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""HTML 表格占位网格解析与 python-docx 表格物化。"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any, Protocol, TypeAlias
+
+from bs4 import BeautifulSoup
+from bs4.element import Tag
+from docx.document import Document as DocxDocument
+from docx.exceptions import InvalidSpanError
+from docx.oxml import OxmlElement
+from docx.oxml.ns import qn
+from docx.shared import Twips
+from docx.table import Table, _Cell
+
+
+DEFAULT_TABLE_WIDTH_TWIPS = 8640
+MAX_NESTED_TABLE_DEPTH = 4
+_POSITIVE_INTEGER_RE = re.compile(r"[0-9]+")
+
+HtmlTableSource: TypeAlias = str | BeautifulSoup | Tag
+
+
+class DocxTableError(ValueError):
+ """表示 HTML 表格结构或 DOCX 表格几何无法安全物化。"""
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlTableCell:
+ """保存一个 HTML 原始单元格在逻辑占位网格中的位置。"""
+
+ tag: Tag
+ row: int
+ column: int
+ rowspan: int
+ colspan: int
+ is_header: bool
+
+ @property
+ def end_row(self) -> int:
+ """返回单元格占用的末行下标。"""
+ return self.row + self.rowspan - 1
+
+ @property
+ def end_column(self) -> int:
+ """返回单元格占用的末列下标。"""
+ return self.column + self.colspan - 1
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlTableGrid:
+ """保存一个经过完整矩形校验的 HTML 表格占位网格。"""
+
+ tag: Tag
+ row_count: int
+ column_count: int
+ cells: tuple[HtmlTableCell, ...]
+ occupancy: tuple[tuple[HtmlTableCell, ...], ...]
+ header_rows: tuple[int, ...]
+
+
+class NestedTableWriter(Protocol):
+ """定义单元格回调可调用的嵌套表格写入函数。"""
+
+ def __call__(
+ self,
+ source: HtmlTableSource,
+ width_twips: int | None = None,
+ ) -> tuple[Table, ...]:
+ """把 source 中的直接嵌套表格写入当前 Word 单元格。"""
+ ...
+
+
+class CellFillCallback(Protocol):
+ """定义由上层 renderer 填充原始单元格内容的回调。"""
+
+ def __call__(
+ self,
+ cell: _Cell,
+ source: Tag,
+ write_nested: NestedTableWriter,
+ ) -> None:
+ """使用原始 td/th 标签填充 origin cell,并按需递归写入嵌套表格。"""
+ ...
+
+
+def parse_html_table(table: Tag) -> HtmlTableGrid:
+ """把单个 table 标签解析为经过重叠、越界和矩形校验的占位网格。"""
+ if table.name != "table":
+ raise DocxTableError("Expected a <table> tag")
+
+ rows = tuple(row for row in table.find_all("tr") if row.find_parent("table") is table)
+ if not rows:
+ raise DocxTableError("Table must contain at least one row")
+
+ occupied: dict[tuple[int, int], HtmlTableCell] = {}
+ cells: list[HtmlTableCell] = []
+
+ for row_index, row in enumerate(rows):
+ column_index = 0
+ source_cells = row.find_all(("td", "th"), recursive=False)
+ for source_cell in source_cells:
+ while (row_index, column_index) in occupied:
+ column_index += 1
+
+ rowspan = _parse_span(source_cell, "rowspan")
+ colspan = _parse_span(source_cell, "colspan")
+ if row_index + rowspan > len(rows):
+ raise DocxTableError(f"rowspan exceeds table bounds at row={row_index}, column={column_index}")
+
+ coordinates = tuple(
+ (target_row, target_column)
+ for target_row in range(row_index, row_index + rowspan)
+ for target_column in range(column_index, column_index + colspan)
+ )
+ overlap = next((coordinate for coordinate in coordinates if coordinate in occupied), None)
+ if overlap is not None:
+ raise DocxTableError(f"Cell span overlaps an occupied coordinate at row={overlap[0]}, column={overlap[1]}")
+
+ placement = HtmlTableCell(
+ tag=source_cell,
+ row=row_index,
+ column=column_index,
+ rowspan=rowspan,
+ colspan=colspan,
+ is_header=source_cell.name == "th",
+ )
+ cells.append(placement)
+ occupied.update(dict.fromkeys(coordinates, placement))
+ column_index += colspan
+
+ if not occupied:
+ raise DocxTableError("Table must contain at least one cell")
+
+ column_count = max(column for _, column in occupied) + 1
+ missing = next(
+ (
+ (row_index, column_index)
+ for row_index in range(len(rows))
+ for column_index in range(column_count)
+ if (row_index, column_index) not in occupied
+ ),
+ None,
+ )
+ if missing is not None:
+ raise DocxTableError(f"Table occupancy must be rectangular; missing row={missing[0]}, column={missing[1]}")
+
+ occupancy = tuple(
+ tuple(occupied[(row_index, column_index)] for column_index in range(column_count)) for row_index in range(len(rows))
+ )
+ header_rows = tuple(
+ row_index
+ for row_index, row in enumerate(rows)
+ if _row_belongs_to_thead(row, table) or all(cell.is_header for cell in occupancy[row_index])
+ )
+ return HtmlTableGrid(
+ tag=table,
+ row_count=len(rows),
+ column_count=column_count,
+ cells=tuple(cells),
+ occupancy=occupancy,
+ header_rows=header_rows,
+ )
+
+
+def parse_html_tables(source: HtmlTableSource) -> tuple[HtmlTableGrid, ...]:
+ """解析 source 中相对当前上下文的一个或多个顶层 table。"""
+ root = BeautifulSoup(source, "html.parser") if isinstance(source, str) else source
+ if not isinstance(root, (BeautifulSoup, Tag)):
+ raise DocxTableError("HTML table source must be a string or BeautifulSoup Tag")
+
+ if isinstance(root, Tag) and root.name == "table":
+ table_tags = (root,)
+ else:
+ parent_table = root.find_parent("table") if isinstance(root, Tag) else None
+ table_tags = tuple(table for table in root.find_all("table") if table.find_parent("table") is parent_table)
+ if not table_tags:
+ raise DocxTableError("HTML does not contain a top-level table")
+ return tuple(parse_html_table(table) for table in table_tags)
+
+
+def materialize_docx_tables(
+ container: Any,
+ source: HtmlTableSource,
+ *,
+ width_twips: int = DEFAULT_TABLE_WIDTH_TWIPS,
+ fill_cell: CellFillCallback,
+) -> tuple[Table, ...]:
+ """把 source 中的全部顶层表格物化到 Document、Header/Footer 或 Cell。"""
+ grids = parse_html_tables(source)
+ return _materialize_grids(
+ container,
+ grids,
+ width_twips=width_twips,
+ fill_cell=fill_cell,
+ depth=1,
+ )
+
+
+def materialize_docx_table(
+ container: Any,
+ grid: HtmlTableGrid,
+ *,
+ width_twips: int = DEFAULT_TABLE_WIDTH_TWIPS,
+ fill_cell: CellFillCallback,
+) -> Table:
+ """把一个已解析表格网格物化到指定 python-docx 容器。"""
+ return _materialize_grid(
+ container,
+ grid,
+ width_twips=width_twips,
+ fill_cell=fill_cell,
+ depth=1,
+ )
+
+
+def _materialize_grids(
+ container: Any,
+ grids: tuple[HtmlTableGrid, ...],
+ *,
+ width_twips: int,
+ fill_cell: CellFillCallback,
+ depth: int,
+) -> tuple[Table, ...]:
+ """在同一递归层级内按源码顺序物化全部表格网格。"""
+ if depth > MAX_NESTED_TABLE_DEPTH:
+ raise DocxTableError(f"Nested table depth exceeds {MAX_NESTED_TABLE_DEPTH}")
+ _validate_width(width_twips)
+ return tuple(
+ _materialize_grid(
+ container,
+ grid,
+ width_twips=width_twips,
+ fill_cell=fill_cell,
+ depth=depth,
+ )
+ for grid in grids
+ )
+
+
+def _materialize_grid(
+ container: Any,
+ grid: HtmlTableGrid,
+ *,
+ width_twips: int,
+ fill_cell: CellFillCallback,
+ depth: int,
+) -> Table:
+ """创建单个 Word 表格、应用合并几何并回调填充所有 origin cell。"""
+ if depth > MAX_NESTED_TABLE_DEPTH:
+ raise DocxTableError(f"Nested table depth exceeds {MAX_NESTED_TABLE_DEPTH}")
+ column_widths = _split_width(width_twips, grid.column_count)
+ table = _add_table(container, grid.row_count, grid.column_count, width_twips)
+ _configure_table_geometry(table, width_twips, column_widths)
+ _apply_cell_merges(table, grid)
+ _normalize_cell_widths(table, column_widths)
+ _clear_fixed_row_heights(table)
+ _mark_header_rows(table, grid.header_rows)
+
+ for placement in grid.cells:
+ origin_cell = table.cell(placement.row, placement.column)
+ origin_width = sum(column_widths[placement.column : placement.column + placement.colspan])
+
+ def write_nested(
+ nested_source: HtmlTableSource,
+ nested_width_twips: int | None = None,
+ *,
+ _origin_cell: _Cell = origin_cell,
+ _origin_width: int = origin_width,
+ _depth: int = depth,
+ ) -> tuple[Table, ...]:
+ """在当前 origin cell 内继续物化直接嵌套表格。"""
+ if _depth >= MAX_NESTED_TABLE_DEPTH:
+ raise DocxTableError(f"Nested table depth exceeds {MAX_NESTED_TABLE_DEPTH}")
+ nested_grids = parse_html_tables(nested_source)
+ return _materialize_grids(
+ _origin_cell,
+ nested_grids,
+ width_twips=_origin_width if nested_width_twips is None else nested_width_twips,
+ fill_cell=fill_cell,
+ depth=_depth + 1,
+ )
+
+ fill_cell(origin_cell, placement.tag, write_nested)
+ return table
+
+
+def _parse_span(cell: Tag, attribute: str) -> int:
+ """读取严格正整数 rowspan/colspan,缺失属性时返回一。"""
+ raw_value = cell.get(attribute, "1")
+ if isinstance(raw_value, list):
+ raise DocxTableError(f"Invalid {attribute}: {raw_value!r}")
+ value = str(raw_value).strip()
+ if _POSITIVE_INTEGER_RE.fullmatch(value) is None:
+ raise DocxTableError(f"Invalid {attribute}: {raw_value!r}")
+ span = int(value)
+ if span < 1:
+ raise DocxTableError(f"Invalid {attribute}: {raw_value!r}")
+ return span
+
+
+def _row_belongs_to_thead(row: Tag, table: Tag) -> bool:
+ """判断当前 tr 是否位于本 table 的 thead 内。"""
+ parent = row.parent
+ while isinstance(parent, Tag) and parent is not table:
+ if parent.name == "thead":
+ return True
+ parent = parent.parent
+ return False
+
+
+def _validate_width(width_twips: int) -> None:
+ """校验调用方传入的 DXA/twips 表格宽度。"""
+ if isinstance(width_twips, bool) or not isinstance(width_twips, int) or width_twips <= 0:
+ raise DocxTableError("width_twips must be a positive integer")
+
+
+def _split_width(width_twips: int, column_count: int) -> tuple[int, ...]:
+ """把总宽度确定性地均分到列,并保证列宽之和严格等于总宽。"""
+ _validate_width(width_twips)
+ if column_count <= 0:
+ raise DocxTableError("Table must contain at least one column")
+ if width_twips < column_count:
+ raise DocxTableError("width_twips is too small for the table column count")
+ base_width, remainder = divmod(width_twips, column_count)
+ return tuple(base_width + (1 if column_index < remainder else 0) for column_index in range(column_count))
+
+
+def _add_table(container: Any, row_count: int, column_count: int, width_twips: int) -> Table:
+ """按 python-docx 容器的不同 add_table 签名创建空表格。"""
+ if not hasattr(container, "add_table"):
+ raise DocxTableError("DOCX container must provide add_table()")
+ try:
+ if isinstance(container, (DocxDocument, _Cell)):
+ return container.add_table(rows=row_count, cols=column_count)
+ return container.add_table(
+ rows=row_count,
+ cols=column_count,
+ width=Twips(width_twips),
+ )
+ except (AttributeError, TypeError, ValueError) as exc:
+ raise DocxTableError("Failed to create DOCX table in the target container") from exc
+
+
+def _configure_table_geometry(
+ table: Table,
+ width_twips: int,
+ column_widths: tuple[int, ...],
+) -> None:
+ """设置固定布局、Table Grid 样式及确定性的 tblW、tblGrid、tcW。"""
+ try:
+ table.style = "Table Grid"
+ except KeyError as exc:
+ raise DocxTableError("DOCX template does not define the 'Table Grid' style") from exc
+ table.autofit = False
+
+ table_width = table._tbl.tblPr.find(qn("w:tblW"))
+ if table_width is None:
+ table_width = OxmlElement("w:tblW")
+ table._tbl.tblPr.insert(0, table_width)
+ table_width.set(qn("w:type"), "dxa")
+ table_width.set(qn("w:w"), str(width_twips))
+
+ grid_columns = table._tbl.tblGrid.gridCol_lst
+ if len(grid_columns) != len(column_widths):
+ raise DocxTableError("DOCX table grid column count is inconsistent")
+ for grid_column, column_width in zip(grid_columns, column_widths):
+ grid_column.w = Twips(column_width)
+
+ for row in table._tbl.tr_lst:
+ if len(row.tc_lst) != len(column_widths):
+ raise DocxTableError("DOCX table row is inconsistent before cell merging")
+ for cell, column_width in zip(row.tc_lst, column_widths):
+ cell_width = cell.get_or_add_tcPr().get_or_add_tcW()
+ cell_width.type = "dxa"
+ cell_width.w = column_width
+
+
+def _apply_cell_merges(table: Table, grid: HtmlTableGrid) -> None:
+ """按已验证 origin placement 为 Word 表格应用水平和垂直合并。"""
+ for placement in grid.cells:
+ if placement.rowspan == 1 and placement.colspan == 1:
+ continue
+ try:
+ table.cell(placement.row, placement.column).merge(table.cell(placement.end_row, placement.end_column))
+ except (IndexError, InvalidSpanError, ValueError) as exc:
+ raise DocxTableError(f"Failed to merge cell at row={placement.row}, column={placement.column}") from exc
+
+
+def _normalize_cell_widths(table: Table, column_widths: tuple[int, ...]) -> None:
+ """合并后按 gridSpan 重新写入每个物理 tc 的确定性 DXA 宽度。"""
+ for row_index, row in enumerate(table._tbl.tr_lst):
+ column_index = 0
+ for cell in row.tc_lst:
+ colspan = cell.grid_span
+ if colspan < 1 or column_index + colspan > len(column_widths):
+ raise DocxTableError(f"DOCX cell geometry is invalid at row={row_index}")
+ width = sum(column_widths[column_index : column_index + colspan])
+ cell_width = cell.get_or_add_tcPr().get_or_add_tcW()
+ cell_width.type = "dxa"
+ cell_width.w = width
+ column_index += colspan
+ if column_index != len(column_widths):
+ raise DocxTableError(f"DOCX row width is inconsistent at row={row_index}")
+
+
+def _clear_fixed_row_heights(table: Table) -> None:
+ """删除所有固定 trHeight,使 Word 根据单元格内容自然扩展行高。"""
+ for row in table._tbl.tr_lst:
+ row_properties = row.trPr
+ if row_properties is None:
+ continue
+ for height in tuple(row_properties.findall(qn("w:trHeight"))):
+ row_properties.remove(height)
+
+
+def _mark_header_rows(table: Table, header_rows: tuple[int, ...]) -> None:
+ """把 thead 或全 th 行标记为可跨页重复的 Word 表头行。"""
+ for row_index in header_rows:
+ row_properties = table.rows[row_index]._tr.get_or_add_trPr()
+ header = row_properties.find(qn("w:tblHeader"))
+ if header is None:
+ header = OxmlElement("w:tblHeader")
+ row_properties.append(header)
+ header.set(qn("w:val"), "1")
+
+
+__all__ = [
+ "CellFillCallback",
+ "DEFAULT_TABLE_WIDTH_TWIPS",
+ "DocxTableError",
+ "HtmlTableCell",
+ "HtmlTableGrid",
+ "MAX_NESTED_TABLE_DEPTH",
+ "NestedTableWriter",
+ "materialize_docx_table",
+ "materialize_docx_tables",
+ "parse_html_table",
+ "parse_html_tables",
+]
diff --git a/mineru/render/utils/inline.py b/mineru/render/utils/inline.py
index 01df1181..bacb1875 100644
--- a/mineru/render/utils/inline.py
+++ b/mineru/render/utils/inline.py
@@ -150,7 +150,7 @@ def _parse_hyperlink(inner: str) -> InlineLink | None:
match = _URL_RE.search(inner)
if match is None:
return None
- label_content = f"{inner[:match.start()]}{inner[match.end():]}"
+ label_content = f"{inner[: match.start()]}{inner[match.end() :]}"
url = html.unescape(match.group("url")).strip()
if not url:
return None
@@ -190,6 +190,11 @@ def render_inline_content(content: str, delimiters: LatexDelimitersConfig) -> st
def render_joined_inline_contents(contents: list[str], delimiters: LatexDelimitersConfig) -> str:
"""按物理段落边界规则合并多段 content 后渲染 Markdown。"""
+ return render_inline_nodes(join_inline_contents(contents), delimiters)
+
+
+def join_inline_contents(contents: list[str]) -> list[InlineNode]:
+ """按物理段落边界规则合并多段 content,并保留中性的行内节点。"""
merged: list[InlineNode] = []
for content in contents:
current = parse_inline_content(content)
@@ -198,7 +203,7 @@ def render_joined_inline_contents(contents: list[str], delimiters: LatexDelimite
if merged:
_join_inline_node_sequences(merged, current)
merged.extend(current)
- return render_inline_nodes(merged, delimiters)
+ return merged
def _join_inline_node_sequences(previous: list[InlineNode], current: list[InlineNode]) -> None:
@@ -306,9 +311,7 @@ def _apply_styles(content: str, plain_text: str, styles: tuple[str, ...]) -> str
rendered_markers = _render_visible_space_marker_text(content, plain_text, styles, marker)
if rendered_markers is not None:
return rendered_markers
- if plain_text and not plain_text.strip() and any(
- style in styles for style in ("underline", "strikethrough", "emphasis")
- ):
+ if plain_text and not plain_text.strip() and any(style in styles for style in ("underline", "strikethrough", "emphasis")):
return _render_visible_whitespace(plain_text, styles)
return _apply_style_wrappers(content, styles)
@@ -455,6 +458,7 @@ def inline_plain_text(nodes: list[InlineNode]) -> str:
__all__ = [
"InlineNode",
"inline_plain_text",
+ "join_inline_contents",
"parse_inline_content",
"render_inline_content",
"render_inline_nodes",
diff --git a/mineru/render/utils/logical_blocks.py b/mineru/render/utils/logical_blocks.py
index b09b964d..3560e21a 100644
--- a/mineru/render/utils/logical_blocks.py
+++ b/mineru/render/utils/logical_blocks.py
@@ -1,5 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""Markdown 渲染前的逻辑块复制、延续合并与页面规划。"""
+"""MiddleJson 渲染前的逻辑块复制、延续合并与页面规划。"""
from __future__ import annotations
@@ -20,13 +20,17 @@ from mineru.types import (
)
-class MarkdownRenderMode(str, Enum):
- """Markdown 的默认合并视图与完整分页视图。"""
+class RenderMode(str, Enum):
+ """MiddleJson renderer 共用的默认合并视图与完整分页视图。"""
DEFAULT = "default"
FULL = "full"
+# 保留既有 Markdown 公共名称,同时让新增 renderer 共用同一枚举类型。
+MarkdownRenderMode = RenderMode
+
+
@dataclass(slots=True)
class PlannedBlock:
"""保存一个待渲染块及其来源页和文本延续片段。"""
@@ -37,7 +41,7 @@ class PlannedBlock:
removed: bool = False
-def build_render_plan(middle_json: MiddleJson, mode: MarkdownRenderMode) -> list[list[PlannedBlock]]:
+def build_render_plan(middle_json: MiddleJson, mode: RenderMode) -> list[list[PlannedBlock]]:
"""深拷贝 MiddleJson,并按模式生成不污染输入的逐页逻辑块计划。"""
copied = middle_json.model_copy(deep=True)
pages = [
@@ -54,12 +58,12 @@ def build_render_plan(middle_json: MiddleJson, mode: MarkdownRenderMode) -> list
flattened = [planned for page in pages for planned in page]
_merge_continued_text_blocks(flattened, mode)
_merge_continued_list_blocks(flattened, mode)
- if mode is MarkdownRenderMode.DEFAULT:
+ if mode is RenderMode.DEFAULT:
_merge_continued_table_blocks(flattened)
return pages
-def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: MarkdownRenderMode) -> None:
+def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: RenderMode) -> None:
"""把 continues_prev 文本吸收到最近的前序文本逻辑块。"""
for current_index, current in enumerate(blocks):
if (
@@ -72,7 +76,7 @@ def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: MarkdownRende
if previous is None:
continue
is_cross_page = previous.page_idx != current.page_idx
- if is_cross_page and mode is MarkdownRenderMode.FULL:
+ if is_cross_page and mode is RenderMode.FULL:
continue
previous.text_contents.extend(current.text_contents)
current.removed = True
@@ -102,7 +106,7 @@ def _find_previous_planned_text(blocks: list[PlannedBlock], current_index: int)
return None
-def _merge_continued_list_blocks(blocks: list[PlannedBlock], mode: MarkdownRenderMode) -> None:
+def _merge_continued_list_blocks(blocks: list[PlannedBlock], mode: RenderMode) -> None:
"""把续接列表吸收到子类型一致的前序列表,参考文献可跨过页面辅助块。"""
for current_index, current in enumerate(blocks):
if current.removed or not isinstance(current.block, ListBlock) or current.block.continues_prev is not True:
@@ -113,7 +117,7 @@ def _merge_continued_list_blocks(blocks: list[PlannedBlock], mode: MarkdownRende
if previous.block.sub_type != current.block.sub_type:
continue
is_cross_page = previous.page_idx != current.page_idx
- if is_cross_page and mode is MarkdownRenderMode.FULL:
+ if is_cross_page and mode is RenderMode.FULL:
continue
previous.block.content.extend(current.block.content)
current.removed = True
@@ -171,4 +175,4 @@ def _find_previous_planned_table(blocks: list[PlannedBlock], current_index: int)
return None
-__all__ = ["MarkdownRenderMode", "PlannedBlock", "build_render_plan"]
+__all__ = ["MarkdownRenderMode", "PlannedBlock", "RenderMode", "build_render_plan"]
diff --git a/pyproject.toml b/pyproject.toml
index 20ccafd5..c91710fd 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,6 +47,7 @@ dependencies = [
"modelscope>=1.26.0",
"huggingface-hub>=0.32.4",
"json-repair>=0.46.2",
+ "latex2mathml>=3.81.0,<4",
"opencv-python>=4.11.0.86",
"fast-langdetect>=0.2.3,<0.3.0",
"openai>=1.70.0,<3",
@@ -56,6 +57,7 @@ dependencies = [
"python-docx>=1.2.0,<2",
'pypptx-with-oxml>=1.0.3,<2',
"mammoth>=1.11.0,<2",
+ "mathml2omml==0.0.2",
"pylatexenc>=2.10,<3",
"lxml>=4.0.0,<7.0.0",
"openpyxl>=3.1.5,<4",
diff --git a/tests/unittest/test_docx_assets.py b/tests/unittest/test_docx_assets.py
new file mode 100644
index 00000000..20e1f60f
--- /dev/null
+++ b/tests/unittest/test_docx_assets.py
@@ -0,0 +1,203 @@
+from __future__ import annotations
+
+import base64
+from dataclasses import FrozenInstanceError
+from io import BytesIO
+from pathlib import Path
+
+from PIL import Image, features
+import pytest
+
+from mineru.render.utils.docx_assets import (
+ DocxAssetError,
+ PreparedImage,
+ prepare_block_image,
+ prepare_html_image,
+ prepare_image_bytes,
+)
+from mineru.types import ImageBodyBlock
+
+
+def _image_bytes(image_format: str, *, size: tuple[int, int] = (7, 5)) -> bytes:
+ """生成指定格式的有效测试图片字节。"""
+ output = BytesIO()
+ Image.new("RGBA" if image_format == "PNG" else "RGB", size, (20, 40, 60, 128)).save(
+ output,
+ format=image_format,
+ )
+ return output.getvalue()
+
+
+def _data_uri(mime_subtype: str, payload: bytes) -> str:
+ """把测试图片包装成严格 base64 data URI。"""
+ encoded = base64.b64encode(payload).decode("ascii")
+ return f"data:image/{mime_subtype};base64,{encoded}"
+
+
+def _image_block(**values: str | None) -> ImageBodyBlock:
+ """构造最小图片 body block。"""
+ return ImageBodyBlock(type="image_body", index=0, content="", **values)
+
+
+def test_block_prefers_base64_over_sidecar() -> None:
+ """验证同时存在两种载荷时只解析 image_base64,不调用 resolver。"""
+ png_data = _image_bytes("PNG", size=(11, 9))
+
+ def unexpected_resolver(_path: str) -> bytes:
+ """若错误访问 sidecar,则立即让测试失败。"""
+ raise AssertionError("resolver must not be called")
+
+ prepared = prepare_block_image(
+ _image_block(image_base64=_data_uri("png", png_data), image_path="images/fallback.png"),
+ unexpected_resolver,
+ )
+
+ assert prepared == PreparedImage(png_data, "png", 11, 9)
+
+
+def test_block_loads_safe_sidecar_through_resolver() -> None:
+ """验证 sidecar 仅通过 resolver 读取,并返回真实格式和尺寸。"""
+ jpeg_data = _image_bytes("JPEG", size=(13, 8))
+ requested_paths: list[str] = []
+
+ def resolver(path: str) -> bytes:
+ """记录 renderer 交给调用方的规范化路径。"""
+ requested_paths.append(path)
+ return jpeg_data
+
+ prepared = prepare_block_image(_image_block(image_path="images/photo.jpeg"), resolver)
+
+ assert requested_paths == ["images/photo.jpeg"]
+ assert prepared == PreparedImage(jpeg_data, "jpg", 13, 8)
+
+
+def test_existing_cwd_file_is_never_read_without_resolver(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证即使 cwd 存在同名文件,helper 也不会自行读取。"""
+ image_path = tmp_path / "images/local.png"
+ image_path.parent.mkdir()
+ image_path.write_bytes(_image_bytes("PNG"))
+ monkeypatch.chdir(tmp_path)
+
+ with pytest.raises(DocxAssetError, match="asset_resolver is required"):
+ prepare_block_image(_image_block(image_path="images/local.png"))
+
+
+def test_resolver_error_is_wrapped_with_safe_path() -> None:
+ """验证 resolver 的底层异常被统一包装,并保留原始异常链。"""
+
+ def failing_resolver(_path: str) -> bytes:
+ """模拟调用方无法读取 sidecar。"""
+ raise OSError("disk unavailable")
+
+ with pytest.raises(DocxAssetError, match="images/missing.png") as error:
+ prepare_html_image("images/missing.png", failing_resolver)
+
+ assert isinstance(error.value.__cause__, OSError)
+
+
+ "source",
+ [
+ "https://example.com/image.png",
+ "http://example.com/image.png",
+ "//example.com/image.png",
+ "file:///tmp/image.png",
+ "/tmp/image.png",
+ "../image.png",
+ r"C:\\image.png",
+ ],
+)
+def test_html_image_rejects_remote_absolute_and_unsafe_sources(source: str) -> None:
+ """验证 HTML 图片不会触发联网、绝对路径读取或目录逃逸。"""
+ resolver_called = False
+
+ def resolver(_path: str) -> bytes:
+ """记录非法来源是否越过安全校验。"""
+ nonlocal resolver_called
+ resolver_called = True
+ return _image_bytes("PNG")
+
+ with pytest.raises(DocxAssetError):
+ prepare_html_image(source, resolver)
+
+ assert resolver_called is False
+
+
+def test_html_data_uri_and_relative_sidecar_use_the_expected_source() -> None:
+ """验证 HTML src 支持内联 data URI 以及由 resolver 提供的相对 sidecar。"""
+ gif_data = _image_bytes("GIF", size=(6, 4))
+ inline = prepare_html_image(_data_uri("gif", gif_data))
+ sidecar = prepare_html_image("images/figure.gif", lambda path: gif_data if path == "images/figure.gif" else b"")
+
+ assert inline == PreparedImage(gif_data, "gif", 6, 4)
+ assert sidecar == inline
+
+
[email protected](not features.check("webp"), reason="Pillow build does not support WebP")
+def test_webp_is_converted_to_png_in_memory() -> None:
+ """验证 WebP 会转为可嵌入 Word 的 PNG,且尺寸和像素保持有效。"""
+ webp_data = _image_bytes("WEBP", size=(9, 7))
+ prepared = prepare_html_image(_data_uri("webp", webp_data))
+
+ assert prepared.extension == "png"
+ assert prepared.data.startswith(b"\x89PNG\r\n\x1a\n")
+ assert (prepared.width_px, prepared.height_px) == (9, 7)
+ with Image.open(BytesIO(prepared.data)) as image:
+ assert image.format == "PNG"
+ assert image.size == (9, 7)
+
+
+ ("image_format", "extension"),
+ [
+ ("PNG", "png"),
+ ("JPEG", "jpg"),
+ ("GIF", "gif"),
+ ("TIFF", "tiff"),
+ ("BMP", "bmp"),
+ ],
+)
+def test_supported_word_image_formats_keep_original_bytes(image_format: str, extension: str) -> None:
+ """验证 Word 可直接使用的五种格式不发生重编码。"""
+ data = _image_bytes(image_format)
+
+ prepared = prepare_image_bytes(data)
+
+ assert prepared.data is data
+ assert prepared.extension == extension
+ assert (prepared.width_px, prepared.height_px) == (7, 5)
+
+
+def test_svg_is_rejected_explicitly_for_data_uri_and_sidecar() -> None:
+ """验证内联与 sidecar SVG 都返回明确的不支持错误。"""
+ svg = b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'
+
+ with pytest.raises(DocxAssetError, match="SVG images are not supported"):
+ prepare_html_image(_data_uri("svg+xml", svg))
+ with pytest.raises(DocxAssetError, match="SVG images are not supported"):
+ prepare_html_image("images/vector.svg", lambda _path: svg)
+
+
+ "action",
+ [
+ lambda: prepare_html_image(_data_uri("jpeg", _image_bytes("PNG"))),
+ lambda: prepare_html_image("data:image/png;base64,not-base64!"),
+ lambda: prepare_image_bytes(b""),
+ lambda: prepare_image_bytes(b"\x89PNG\r\n\x1a\ntruncated"),
+ lambda: prepare_html_image("images/empty.png", lambda _path: b""),
+ lambda: prepare_html_image("images/wrong.jpg", lambda _path: _image_bytes("PNG")),
+ ],
+)
+def test_invalid_mime_empty_and_corrupt_payloads_are_rejected(action: object) -> None:
+ """验证 MIME 不符、坏 base64、空字节、坏签名和扩展名不符都报错。"""
+ with pytest.raises(DocxAssetError):
+ action() # type: ignore[operator]
+
+
+def test_prepared_image_is_immutable() -> None:
+ """验证 PreparedImage 是不可变的值对象。"""
+ prepared = PreparedImage(b"image", "png", 1, 1)
+
+ with pytest.raises(FrozenInstanceError):
+ prepared.extension = "jpg" # type: ignore[misc]
diff --git a/tests/unittest/test_docx_math.py b/tests/unittest/test_docx_math.py
new file mode 100644
index 00000000..8308fabd
--- /dev/null
+++ b/tests/unittest/test_docx_math.py
@@ -0,0 +1,119 @@
+from __future__ import annotations
+
+import pytest
+from lxml import etree
+
+from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml, split_formula_tag
+
+_OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+
+
+ ("content", "expected"),
+ [
+ (r"x + y\tag{1}", ("x + y", "1")),
+ (r"x + y\tag { A_{n} } ", ("x + y", "A_{n}")),
+ (r"x + y\tag{\mathrm{A}_{n}}", ("x + y", r"\mathrm{A}_{n}")),
+ (r"x + y\tag{\{1\}}", ("x + y", r"\{1\}")),
+ ],
+)
+def test_split_formula_tag_strips_only_balanced_terminal_tag(
+ content: str,
+ expected: tuple[str, str | None],
+) -> None:
+ """验证末端 tag 支持空白、嵌套花括号和转义花括号。"""
+ assert split_formula_tag(content) == expected
+
+
+ "content",
+ [
+ r"x + y\tag{1} + z",
+ r"x + y\tag{1",
+ r"x + y\tag{1}}",
+ r"x + y\tagged{1}",
+ r"x + y\\tag{1}",
+ "plain formula ",
+ ],
+)
+def test_split_formula_tag_preserves_non_terminal_or_malformed_content(content: str) -> None:
+ """验证非末端、损坏或并非命令的 tag 文本不会被误剥离。"""
+ assert split_formula_tag(content) == (content, None)
+
+
+def test_latex_to_omml_returns_inline_equation_with_bound_namespace() -> None:
+ """验证行内公式返回可独立序列化的 m:oMath 节点。"""
+ equation = latex_to_omml(r"x^2 + \frac{a}{b}", display=False)
+
+ assert equation.tag == etree.QName(_OFFICE_MATH_NAMESPACE, "oMath")
+ assert equation.getparent() is None
+ assert equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}f") is not None
+ reparsed = etree.fromstring(etree.tostring(equation))
+ assert reparsed.tag == equation.tag
+
+
+def test_latex_to_omml_wraps_display_matrix_in_math_paragraph() -> None:
+ """验证块公式以 m:oMathPara 包装,并保留矩阵 OMML。"""
+ paragraph = latex_to_omml(r"\begin{matrix}a&b\\c&d\end{matrix}", display=True)
+
+ assert paragraph.tag == etree.QName(_OFFICE_MATH_NAMESPACE, "oMathPara")
+ equations = paragraph.findall(f"{{{_OFFICE_MATH_NAMESPACE}}}oMath")
+ assert len(equations) == 1
+ assert equations[0].find(f".//{{{_OFFICE_MATH_NAMESPACE}}}m") is not None
+
+
[email protected]("latex", [r"\bar p", r"\vec{u}"])
+def test_latex_to_omml_repairs_group_character_property_closing_tag(latex: str) -> None:
+ """验证横线和向量符号不会因第三方库的错误闭合标签退化为文本。"""
+ equation = latex_to_omml(latex, display=False)
+
+ assert equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}groupChr") is not None
+ etree.fromstring(etree.tostring(equation))
+
+
+def test_latex_to_omml_hides_square_root_degree_placeholder() -> None:
+ """验证普通平方根包含隐藏 degree,避免 Word/LibreOffice 显示占位框。"""
+ equation = latex_to_omml(r"\sqrt{x}", display=False)
+
+ radical = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}rad")
+ assert radical is not None
+ assert radical.find(f"{{{_OFFICE_MATH_NAMESPACE}}}deg") is not None
+ degree_hidden = radical.find(f"{{{_OFFICE_MATH_NAMESPACE}}}radPr/{{{_OFFICE_MATH_NAMESPACE}}}degHide")
+ assert degree_hidden is not None
+ assert degree_hidden.get(f"{{{_OFFICE_MATH_NAMESPACE}}}val") == "1"
+
+
[email protected]("latex", [r"^{2}", r"_{0}"])
+def test_latex_to_omml_uses_zero_width_script_base(latex: str) -> None:
+ """验证无显式底数的上下标使用零宽字符抑制可见方框。"""
+ equation = latex_to_omml(latex, display=False)
+ base = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}sSup/{{{_OFFICE_MATH_NAMESPACE}}}e")
+ if base is None:
+ base = equation.find(f".//{{{_OFFICE_MATH_NAMESPACE}}}sSub/{{{_OFFICE_MATH_NAMESPACE}}}e")
+
+ assert base is not None
+ assert "\u200b" in "".join(base.itertext())
+
+
+def test_latex_to_omml_removes_explicitly_empty_operator_limits() -> None:
+ """验证空上下限不会在积分或其他算子旁生成可见占位框。"""
+ equation = latex_to_omml(r"\int_{}^{} x + E_{}", display=False)
+ serialized = etree.tostring(equation, encoding="unicode")
+
+ assert "<m:t></m:t>" not in serialized
+ assert "<m:sub>" not in serialized and "<m:sup>" not in serialized
+
+
+ "latex",
+ [
+ r"\genfrac{}{}{0pt}{}{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)
+
+ assert exc_info.value.__cause__ is not None
diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.py
new file mode 100644
index 00000000..97ffb42f
--- /dev/null
+++ b/tests/unittest/test_docx_render.py
@@ -0,0 +1,627 @@
+from __future__ import annotations
+
+import base64
+from copy import deepcopy
+from io import BytesIO
+import zipfile
+
+from docx import Document
+from docx.shared import Mm, Twips
+from lxml import etree
+from PIL import Image
+import pytest
+
+from mineru.render import DocxRenderError, MarkdownRenderMode, RenderMode, render_docx
+from mineru.types import (
+ ChartBlock,
+ ChartBodyBlock,
+ CodeBlock,
+ EquationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ ListBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+
+def _middle(*pages: PageInfo) -> MiddleJson:
+ """构造最小严格 MiddleJson 测试对象。"""
+ return MiddleJson(
+ pages=list(pages),
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """构造保持调用方 block 顺序的严格页面。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def _png_bytes(*, size: tuple[int, int] = (12, 8)) -> bytes:
+ """生成可被 Pillow 和 python-docx 完整读取的 PNG。"""
+ output = BytesIO()
+ Image.new("RGB", size, (30, 60, 90)).save(output, format="PNG")
+ return output.getvalue()
+
+
+def _png_uri(*, size: tuple[int, int] = (12, 8)) -> str:
+ """生成严格 PNG data URI。"""
+ payload = base64.b64encode(_png_bytes(size=size)).decode("ascii")
+ return f"data:image/png;base64,{payload}"
+
+
+def _part(docx_bytes: bytes, name: str) -> str:
+ """读取 DOCX ZIP 中一个 XML part。"""
+ with zipfile.ZipFile(BytesIO(docx_bytes)) as archive:
+ return archive.read(name).decode("utf-8")
+
+
+def test_public_contract_returns_reopenable_docx_without_mutation() -> None:
+ """验证严格入口、枚举别名、可重开 bytes 和输入无副作用。"""
+ middle = _middle(_page(0, TextBlock(type="text", index=0, content="hello")))
+ original = deepcopy(middle)
+
+ result = render_docx(middle, mode=MarkdownRenderMode.DEFAULT)
+
+ assert result.startswith(b"PK\x03\x04")
+ assert Document(BytesIO(result)).paragraphs[0].text == "hello"
+ assert middle == original
+ assert MarkdownRenderMode is RenderMode
+ with pytest.raises(TypeError, match="MiddleJson"):
+ render_docx(middle.to_dict()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="RenderMode"):
+ render_docx(middle, mode="full") # type: ignore[arg-type]
+
+
+def test_xml_incompatible_text_is_replaced_with_visible_marker() -> None:
+ """验证真实语料中的 XML 控制字符会转为 U+FFFD,而不是中止或静默删除。"""
+ middle = _middle(_page(0, TextBlock(type="text", index=0, content="before\x01after")))
+
+ document = Document(BytesIO(render_docx(middle)))
+
+ assert document.paragraphs[0].text == "before\ufffdafter"
+
+
+def test_heading_bookmark_forward_index_link_and_rich_inline_ooxml() -> None:
+ """验证 Heading、前向目录链接、外链、组合样式和行内 OMML。"""
+ index = IndexBlock(
+ type="index",
+ index=0,
+ content=[
+ ParagraphTitleBlock(
+ type="paragraph_title",
+ level=2,
+ anchor="section a",
+ content="Section\t12",
+ )
+ ],
+ )
+ text = TextBlock(
+ type="text",
+ index=1,
+ content=(
+ '<text style="bold,italic,underline,strikethrough,emphasis">Styled</text>'
+ "<sup>2</sup><sub>i</sub>"
+ "<hyperlink><text>Link</text><url>https://example.com/a</url></hyperlink>"
+ "<eq>x^2</eq>"
+ ),
+ )
+ title = ParagraphTitleBlock(
+ type="paragraph_title",
+ index=2,
+ level=2,
+ anchor="section a",
+ content="Section",
+ )
+
+ result = render_docx(_middle(_page(0, index, text, title)))
+ document_xml = _part(result, "word/document.xml")
+ relationships = _part(result, "word/_rels/document.xml.rels")
+
+ assert 'w:pStyle w:val="Heading2"' in document_xml
+ assert 'w:bookmarkStart w:id="0" w:name="section_a"' in document_xml
+ assert 'w:hyperlink w:anchor="section_a"' in document_xml
+ assert "https://example.com/a" in relationships
+ assert "<w:b" in document_xml and "<w:i" in document_xml
+ assert "<w:u" in document_xml and "<w:strike" in document_xml
+ assert '<w:vertAlign w:val="superscript"' in document_xml
+ assert '<w:vertAlign w:val="subscript"' in document_xml
+ assert '<w:em w:val="dot"' in document_xml
+ assert "<m:oMath" in document_xml
+
+
+def test_bookmark_names_are_sanitized_and_collision_safe() -> None:
+ """验证不同原 anchor 清洗后冲突时仍生成唯一 Word bookmark。"""
+ first = ParagraphTitleBlock(
+ type="paragraph_title",
+ index=0,
+ level=2,
+ anchor="section-a",
+ content="First",
+ )
+ second = ParagraphTitleBlock(
+ type="paragraph_title",
+ index=1,
+ level=2,
+ anchor="section a",
+ content="Second",
+ )
+
+ document_xml = _part(render_docx(_middle(_page(0, first, second))), "word/document.xml")
+
+ assert 'w:name="section_a"' in document_xml
+ assert document_xml.count("<w:bookmarkStart") == 2
+ names = document_xml.split('w:bookmarkStart w:id="')[1:]
+ assert len({value.split('w:name="', 1)[1].split('"', 1)[0] for value in names}) == 2
+
+
+def test_index_only_anchor_falls_back_to_plain_text_without_dangling_link() -> None:
+ """验证目录独有 anchor 不会被误注册为没有正文 bookmark 的内部链接。"""
+ index = IndexBlock(
+ type="index",
+ index=0,
+ content=[
+ ParagraphTitleBlock(
+ type="paragraph_title",
+ level=2,
+ anchor="missing-target",
+ content="Missing target\t8",
+ )
+ ],
+ )
+
+ document_xml = _part(render_docx(_middle(_page(0, index))), "word/document.xml")
+
+ assert "Missing target" in document_xml
+ assert "w:anchor=" not in document_xml
+ assert "w:bookmarkStart" not in document_xml
+
+
+def test_default_and_full_modes_share_planner_but_keep_page_semantics() -> None:
+ """验证 DEFAULT 隐藏辅助块并合并续段,FULL 保留辅助块与硬分页。"""
+ middle = _middle(
+ _page(
+ 0,
+ TextBlock(type="text", index=0, content="international"),
+ PageAuxTextBlock(type="header", index=1, content="HEADER"),
+ ),
+ _page(1, TextBlock(type="text", index=0, content="continuation", continues_prev=True)),
+ )
+
+ default_doc = Document(BytesIO(render_docx(middle)))
+ full_bytes = render_docx(middle, mode=RenderMode.FULL)
+ full_doc = Document(BytesIO(full_bytes))
+
+ assert [paragraph.text for paragraph in default_doc.paragraphs] == ["international continuation"]
+ assert "HEADER" in [paragraph.text for paragraph in full_doc.paragraphs]
+ assert "international" in [paragraph.text for paragraph in full_doc.paragraphs]
+ assert "continuation" in [paragraph.text for paragraph in full_doc.paragraphs]
+ assert 'w:br w:type="page"' in _part(full_bytes, "word/document.xml")
+
+
+def test_list_preserves_markers_and_uses_hanging_indents_without_numbering() -> None:
+ """验证列表不重建 numbering.xml,只保留 marker 和递归缩进。"""
+ nested = ListBlock(
+ type="list",
+ content=[TextBlock(type="text", content="- nested item")],
+ )
+ block = ListBlock(
+ type="list",
+ index=0,
+ content=[TextBlock(type="text", content="1. first item"), nested],
+ )
+
+ result = render_docx(_middle(_page(0, block)))
+ document = Document(BytesIO(result))
+ document_xml = _part(result, "word/document.xml")
+
+ assert [paragraph.text for paragraph in document.paragraphs] == ["1. first item", "- nested item"]
+ assert abs(int(document.paragraphs[0].paragraph_format.left_indent) - int(Mm(6))) < 635
+ assert abs(int(document.paragraphs[0].paragraph_format.first_line_indent) + int(Mm(6))) < 635
+ assert abs(int(document.paragraphs[1].paragraph_format.left_indent) - int(Mm(12))) < 635
+ assert "<w:numPr" not in document_xml
+
+
+def test_display_formula_tag_uses_center_and_right_tabs() -> None:
+ """验证公式主体为 OMML,tag 通过右对齐 tab 单独输出。"""
+ block = EquationBlock(type="equation", index=0, content=r"x^2=1\tag{9}")
+
+ result = render_docx(_middle(_page(0, block)))
+ document_xml = _part(result, "word/document.xml")
+ document = Document(BytesIO(result))
+
+ assert "<m:oMath" in document_xml
+ assert "<m:oMathPara" not in document_xml
+ assert document.paragraphs[0].text == "\t\t(9)"
+ assert document_xml.count("<w:tab/>") == 2
+ assert 'w:val="center"' in document_xml
+ assert 'w:val="right"' in document_xml
+
+
+def test_display_formula_without_tag_uses_math_paragraph() -> None:
+ """验证无编号块公式使用居中的 m:oMathPara。"""
+ result = render_docx(_middle(_page(0, EquationBlock(type="equation", index=0, content=r"x^2=1"))))
+ document_xml = _part(result, "word/document.xml")
+ root = etree.fromstring(document_xml.encode("utf-8"))
+ namespace = {
+ "m": "http://schemas.openxmlformats.org/officeDocument/2006/math",
+ "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
+ }
+ math_paragraph = root.find(".//m:oMathPara", namespaces=namespace)
+
+ assert "<m:oMathPara" in document_xml
+ assert '<m:jc m:val="center"' in document_xml
+ assert math_paragraph is not None
+ assert math_paragraph.getparent().tag == f"{{{namespace['w']}}}p"
+
+
+def test_formula_conversion_failure_falls_back_to_image_then_visible_latex() -> None:
+ """验证块公式优先图片回退,行内公式保留可见 LaTeX。"""
+ unsupported = r"\genfrac{}{}{0pt}{}{a}{b}"
+ middle = _middle(
+ _page(
+ 0,
+ EquationBlock(
+ type="equation",
+ index=0,
+ content=unsupported,
+ image_base64=_png_uri(),
+ ),
+ TextBlock(type="text", index=1, content=f"before <eq>{unsupported}</eq> after"),
+ )
+ )
+
+ result = render_docx(middle)
+ document = Document(BytesIO(result))
+ document_xml = _part(result, "word/document.xml")
+
+ assert len(document.inline_shapes) == 1
+ assert unsupported in "".join(paragraph.text for paragraph in document.paragraphs)
+ assert "<a:blip" in document_xml
+
+
+def test_inline_bare_scripts_use_word_superscript_runs_without_placeholder_boxes() -> None:
+ """验证无底数公式片段改用上下标 run,避免 OMML 可见占位框。"""
+ block = TextBlock(
+ type="text",
+ index=0,
+ content="S K<eq>^{1/2}</eq>/cm<eq>^{-1}</eq>",
+ )
+
+ result = render_docx(_middle(_page(0, block)))
+ document_xml = _part(result, "word/document.xml")
+
+ assert Document(BytesIO(result)).paragraphs[0].text == "S K1/2/cm-1"
+ assert document_xml.count('w:vertAlign w:val="superscript"') == 2
+ assert "<m:oMath" not in document_xml
+
+
+def test_required_image_error_contains_public_block_location() -> None:
+ """验证缺少 resolver 的必需图片通过公共异常暴露完整定位。"""
+ image = ImageBlock(
+ type="image",
+ index=3,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=3,
+ content="description",
+ image_path="images/missing.png",
+ )
+ ],
+ )
+
+ with pytest.raises(DocxRenderError, match="asset_resolver") as exc_info:
+ render_docx(_middle(_page(7, image)))
+
+ assert exc_info.value.page_idx == 7
+ assert exc_info.value.block_index == 3
+ assert exc_info.value.block_type == "image"
+
+
+def test_image_alt_text_and_visual_child_order_are_preserved() -> None:
+ """验证图片 alt description 及 caption/body/footnote 源顺序。"""
+ image = ImageBlock.model_validate(
+ {
+ "type": "image",
+ "index": 0,
+ "content": [
+ {"type": "image_caption", "content": "before"},
+ {
+ "type": "image_body",
+ "index": 0,
+ "content": "<p>diagram description</p>",
+ "image_base64": _png_uri(),
+ },
+ {"type": "image_footnote", "content": "after"},
+ ],
+ }
+ )
+
+ document_xml = _part(render_docx(_middle(_page(0, image))), "word/document.xml")
+
+ assert document_xml.index("before") < document_xml.index("diagram description")
+ assert document_xml.index("diagram description") < document_xml.index("after")
+ assert 'descr="diagram description"' in document_xml
+
+
+def test_html_table_materializes_merges_inline_content_link_and_image() -> None:
+ """验证复杂 HTML 表格生成合并几何,并复用单元格行内与素材 visitor。"""
+ html = (
+ "<table><thead><tr><th rowspan='2'>A</th><th colspan='2'>B</th></tr></thead>"
+ "<tbody><tr><td><strong>x</strong><eq>y</eq>"
+ "<a href='https://example.com/table'>link</a></td>"
+ f"<td><img src='{_png_uri()}' alt='cell image'/></td></tr></tbody></table>"
+ )
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[TableBodyBlock(type="table_body", index=0, content=html)],
+ )
+
+ result = render_docx(_middle(_page(0, table)))
+ document_xml = _part(result, "word/document.xml")
+ relationships = _part(result, "word/_rels/document.xml.rels")
+ document = Document(BytesIO(result))
+
+ assert len(document.tables) == 1
+ assert '<w:gridSpan w:val="2"' in document_xml
+ assert "<w:vMerge" in document_xml
+ assert "<w:tblHeader" in document_xml
+ assert "<m:oMath" in document_xml
+ assert "<a:blip" in document_xml
+ assert "https://example.com/table" in relationships
+
+
+def test_html_table_cell_lists_keep_item_boundaries() -> None:
+ """验证 HTML 单元格中的有序和无序列表不会串成连续文本。"""
+ html = (
+ "<table><tr><td>Items:<ul><li>first</li><li>second</li></ul>"
+ "<ol start='3'><li>third</li><li>fourth</li></ol></td></tr></table>"
+ )
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[TableBodyBlock(type="table_body", index=0, content=html)],
+ )
+
+ document = Document(BytesIO(render_docx(_middle(_page(0, table)))))
+
+ assert document.tables[0].cell(0, 0).text == "Items:\n- first\n- second\n3. third\n4. fourth"
+
+
+def test_html_table_direct_nested_table_is_materialized_recursively() -> None:
+ """验证单元格直接子 table 通过绑定 writer 递归物化,而不是压成纯文本。"""
+ html = "<table><tr><td>before<table><tr><td>nested</td></tr></table>after</td></tr></table>"
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[TableBodyBlock(type="table_body", index=0, content=html)],
+ )
+
+ result = render_docx(_middle(_page(0, table)))
+ document_xml = _part(result, "word/document.xml")
+ cell = Document(BytesIO(result)).tables[0].cell(0, 0)
+
+ assert document_xml.count("<w:tbl>") == 2
+ assert "before" in document_xml and "nested" in document_xml and "after" in document_xml
+ assert len(cell.tables) == 1
+ assert [paragraph.text for paragraph in cell.paragraphs if paragraph.text] == ["before", "after"]
+
+
+def test_html_table_nested_inside_wrapper_keeps_table_and_source_order() -> None:
+ """验证 div 等包装层中的嵌套表格不会被压平成连续文本。"""
+ html = "<table><tr><td><div>before<table><tr><td>nested</td></tr></table>after</div></td></tr></table>"
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[TableBodyBlock(type="table_body", index=0, content=html)],
+ )
+
+ result = render_docx(_middle(_page(0, table)))
+ cell = Document(BytesIO(result)).tables[0].cell(0, 0)
+
+ assert len(cell.tables) == 1
+ assert [paragraph.text for paragraph in cell.paragraphs if paragraph.text] == ["before", "after"]
+ assert _part(result, "word/document.xml").count("<w:tbl>") == 2
+
+
+def test_html_table_fallback_rolls_back_partial_table_and_relationships() -> None:
+ """验证单元格素材失败时移除半成品表格和其新增关系,再只写整体图片。"""
+ html = f"<table><tr><td><img src='{_png_uri(size=(8, 8))}'/></td><td><img src='images/missing.png'/></td></tr></table>"
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content=html,
+ image_base64=_png_uri(size=(10, 10)),
+ )
+ ],
+ )
+
+ result = render_docx(_middle(_page(0, table)))
+ document = Document(BytesIO(result))
+ with zipfile.ZipFile(BytesIO(result)) as archive:
+ media = [name for name in archive.namelist() if name.startswith("word/media/")]
+
+ assert len(document.tables) == 0
+ assert len(document.inline_shapes) == 1
+ assert len(media) == 1
+
+
+def test_html_table_cell_image_is_limited_to_merged_cell_width() -> None:
+ """验证窄列图片宽度不超过扣除单元格左右内边距后的 tcW。"""
+ cells = [f"<td>{'<img src=' + repr(_png_uri(size=(300, 100))) + '/>' if index == 0 else index}</td>" for index in range(10)]
+ html = f"<table><tr>{''.join(cells)}</tr></table>"
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[TableBodyBlock(type="table_body", index=0, content=html)],
+ )
+
+ document = Document(BytesIO(render_docx(_middle(_page(0, table)))))
+ cell = document.tables[0].cell(0, 0)
+ cell_width_twips = int(cell._tc.get_or_add_tcPr().get_or_add_tcW().w)
+ available_width_emu = int(Twips(cell_width_twips - 240))
+
+ assert len(document.inline_shapes) == 1
+ assert int(document.inline_shapes[0].width) <= available_width_emu
+
+
+def test_invalid_html_table_falls_back_to_table_image() -> None:
+ """验证 HTML 占位网格非法时使用表格图片,不留下损坏表格。"""
+ table = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table><tr><td rowspan='2'>A</td></tr></table>",
+ image_base64=_png_uri(),
+ )
+ ],
+ )
+
+ result = render_docx(_middle(_page(0, table)))
+ document = Document(BytesIO(result))
+
+ assert len(document.tables) == 0
+ assert len(document.inline_shapes) == 1
+
+ without_fallback = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="<table><tr><td rowspan='2'>A</td></tr></table>",
+ )
+ ],
+ )
+ with pytest.raises(DocxRenderError, match="no image fallback"):
+ render_docx(_middle(_page(0, without_fallback)))
+
+
+def test_spatial_table_outputs_only_image_and_requires_it() -> None:
+ """验证空间投影文本不进入 DOCX,并严格要求表格图片。"""
+ spatial = TableBlock(
+ type="table",
+ index=0,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=0,
+ content="A B\n1 2",
+ image_base64=_png_uri(),
+ )
+ ],
+ )
+ missing = TableBlock(
+ type="table",
+ index=0,
+ content=[TableBodyBlock(type="table_body", index=0, content="A B")],
+ )
+
+ 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)))
+
+
+def test_chart_renders_image_then_structured_html_table() -> None:
+ """验证图表图片后继续输出可编辑的 HTML 数据表。"""
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content="<table><tr><th>A</th></tr><tr><td>1</td></tr></table>",
+ image_base64=_png_uri(),
+ )
+ ],
+ )
+
+ result = render_docx(_middle(_page(0, chart)))
+ document = Document(BytesIO(result))
+ document_xml = _part(result, "word/document.xml")
+
+ assert len(document.inline_shapes) == 1
+ assert len(document.tables) == 1
+ assert document_xml.index("<a:blip") < document_xml.index("<w:tbl>")
+
+
+def test_chart_invalid_html_keeps_successful_image_fallback() -> None:
+ """验证图表结构表损坏时保留已成功写入的图片,而不是终止文档。"""
+ chart = ChartBlock(
+ type="chart",
+ index=0,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=0,
+ content="<table><tr><td rowspan='2'>broken</td></tr></table>",
+ image_base64=_png_uri(),
+ )
+ ],
+ )
+
+ document = Document(BytesIO(render_docx(_middle(_page(0, chart)))))
+
+ assert len(document.inline_shapes) == 1
+ assert len(document.tables) == 0
+
+
+def test_code_and_algorithm_keep_line_breaks_styles_and_inline_math() -> None:
+ """验证代码换行与算法行内公式、上下标均保留。"""
+ code = CodeBlock.model_validate(
+ {
+ "type": "code",
+ "index": 0,
+ "sub_type": "code",
+ "guess_lang": "python",
+ "content": [{"type": "code_body", "index": 0, "content": "a = 1\nb = 2"}],
+ }
+ )
+ algorithm = CodeBlock.model_validate(
+ {
+ "type": "code",
+ "index": 1,
+ "sub_type": "algorithm",
+ "content": [
+ {
+ "type": "code_body",
+ "index": 1,
+ "content": "T<sub>n</sub> = <eq>x^2</eq>\nnext",
+ }
+ ],
+ }
+ )
+
+ result = render_docx(_middle(_page(0, code, algorithm)))
+ document = Document(BytesIO(result))
+ document_xml = _part(result, "word/document.xml")
+
+ assert [paragraph.style.name for paragraph in document.paragraphs] == ["MinerU Code", "MinerU Code"]
+ assert "a = 1\nb = 2" == document.paragraphs[0].text
+ assert "<m:oMath" in document_xml
+ assert 'w:vertAlign w:val="subscript"' in document_xml
diff --git a/tests/unittest/test_docx_table.py b/tests/unittest/test_docx_table.py
new file mode 100644
index 00000000..ff436980
--- /dev/null
+++ b/tests/unittest/test_docx_table.py
@@ -0,0 +1,252 @@
+from __future__ import annotations
+
+from collections.abc import Callable
+
+import pytest
+from bs4.element import Tag
+from docx import Document
+from docx.oxml.ns import qn
+from docx.table import _Cell
+
+from mineru.render.utils.docx_table import (
+ DocxTableError,
+ NestedTableWriter,
+ materialize_docx_table,
+ materialize_docx_tables,
+ parse_html_table,
+ parse_html_tables,
+)
+
+
+def _text_filler(
+ observed: list[tuple[str, str]],
+) -> Callable[[_Cell, Tag, NestedTableWriter], None]:
+ """构造记录原始 Tag 并把直接文本写入 Word 单元格的测试回调。"""
+
+ def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:
+ """记录回调来源,并忽略本用例不涉及的嵌套写入器。"""
+ del write_nested
+ observed.append((source.name, source.get_text(" ", strip=True)))
+ cell.paragraphs[0].add_run(source.get_text(" ", strip=True))
+
+ return fill_cell
+
+
+def _xml_value(element: object, attribute: str) -> str | None:
+ """读取测试 XML 元素中的 WordprocessingML 属性。"""
+ return element.get(qn(attribute)) # type: ignore[union-attr]
+
+
+def test_parse_and_materialize_simple_table_with_header_tags() -> None:
+ """验证简单表格、th 回调、Table Grid 和重复表头标记。"""
+ html = (
+ '<table><thead><tr><th data-id="h1">Name</th><th data-id="h2">Value</th></tr></thead>'
+ '<tbody><tr><td data-id="c1">A</td><td data-id="c2">1</td></tr></tbody></table>'
+ )
+ grid = parse_html_tables(html)[0]
+
+ assert (grid.row_count, grid.column_count) == (2, 2)
+ assert grid.header_rows == (0,)
+ assert [(cell.row, cell.column, cell.is_header) for cell in grid.cells] == [
+ (0, 0, True),
+ (0, 1, True),
+ (1, 0, False),
+ (1, 1, False),
+ ]
+
+ document = Document()
+ observed: list[tuple[str, str]] = []
+ table = materialize_docx_table(
+ document,
+ grid,
+ width_twips=6000,
+ fill_cell=_text_filler(observed),
+ )
+
+ assert observed == [("th", "Name"), ("th", "Value"), ("td", "A"), ("td", "1")]
+ assert table.style.name == "Table Grid"
+ assert table.cell(0, 0).text == "Name"
+ assert table.cell(1, 1).text == "1"
+ assert len(table.rows[0]._tr.xpath("./w:trPr/w:tblHeader")) == 1
+
+
+def test_materialize_rowspan_and_colspan_as_gridspan_and_vmerge() -> None:
+ """验证二维合并写出一致的 gridSpan、vMerge 和 origin 回调。"""
+ html = '<table><tr><th rowspan="2" colspan="2">A</th><th>B</th></tr><tr><td>C</td></tr></table>'
+ document = Document()
+ observed: list[tuple[str, str]] = []
+
+ table = materialize_docx_tables(
+ document,
+ html,
+ width_twips=6000,
+ fill_cell=_text_filler(observed),
+ )[0]
+
+ assert observed == [("th", "A"), ("th", "B"), ("td", "C")]
+ first_row_cells = table._tbl.tr_lst[0].tc_lst
+ second_row_cells = table._tbl.tr_lst[1].tc_lst
+ assert _xml_value(first_row_cells[0].tcPr.gridSpan, "w:val") == "2"
+ assert _xml_value(first_row_cells[0].tcPr.vMerge, "w:val") == "restart"
+ assert _xml_value(second_row_cells[0].tcPr.gridSpan, "w:val") == "2"
+ assert _xml_value(second_row_cells[0].tcPr.vMerge, "w:val") is None
+ assert first_row_cells[0].tcPr.tcW.w == 4000
+ assert second_row_cells[0].tcPr.tcW.w == 4000
+
+
+def test_parse_and_materialize_multiple_top_level_tables() -> None:
+ """验证同一 HTML 片段中的多个顶层表格按源码顺序独立创建。"""
+ html = '<table data-id="one"><tr><td>A</td></tr></table><div><table data-id="two"><tr><td>B</td></tr></table></div>'
+ grids = parse_html_tables(html)
+ assert [grid.tag.get("data-id") for grid in grids] == ["one", "two"]
+
+ document = Document()
+ observed: list[tuple[str, str]] = []
+ tables = materialize_docx_tables(document, html, fill_cell=_text_filler(observed))
+
+ assert len(tables) == 2
+ assert len(document.tables) == 2
+ assert [table.cell(0, 0).text for table in tables] == ["A", "B"]
+
+
+ "html",
+ [
+ "<table></table>",
+ "<table><tr></tr></table>",
+ ],
+)
+def test_parse_rejects_table_without_cells(html: str) -> None:
+ """验证无行或无任何单元格的表格被安全拒绝。"""
+ with pytest.raises(DocxTableError):
+ parse_html_tables(html)
+
+
+ ("attribute", "value"),
+ [
+ ("rowspan", "0"),
+ ("rowspan", "-1"),
+ ("rowspan", "1.5"),
+ ("rowspan", "x"),
+ ("colspan", "0"),
+ ("colspan", ""),
+ ],
+)
+def test_parse_rejects_invalid_spans(attribute: str, value: str) -> None:
+ """验证 rowspan/colspan 只接受严格正整数。"""
+ html = f'<table><tr><td {attribute}="{value}">A</td></tr></table>'
+
+ with pytest.raises(DocxTableError, match=f"Invalid {attribute}"):
+ parse_html_tables(html)
+
+
+def test_parse_rejects_rowspan_out_of_bounds() -> None:
+ """验证跨出最后一行的 rowspan 被判定为越界。"""
+ with pytest.raises(DocxTableError, match="rowspan exceeds table bounds"):
+ parse_html_tables('<table><tr><td rowspan="2">A</td></tr></table>')
+
+
+def test_parse_rejects_span_overlap_after_skipping_occupied_coordinate() -> None:
+ """验证跳过行首占位后,colspan 仍不得覆盖后方 rowspan 占位。"""
+ html = '<table><tr><td rowspan="2">A</td><td>B</td><td rowspan="2">C</td></tr><tr><td colspan="2">D</td></tr></table>'
+
+ with pytest.raises(DocxTableError, match="overlaps an occupied coordinate"):
+ parse_html_tables(html)
+
+
+def test_parse_rejects_non_rectangular_occupancy() -> None:
+ """验证逻辑行宽不一致且没有 rowspan 补位时拒绝非矩形表格。"""
+ html = "<table><tr><td>A</td><td>B</td></tr><tr><td>C</td></tr></table>"
+
+ with pytest.raises(DocxTableError, match="occupancy must be rectangular"):
+ parse_html_tables(html)
+
+
+def test_materialized_geometry_uses_exact_dxa_widths_without_fixed_row_height() -> None:
+ """验证 tblW、tblGrid、每行 tcW 的总宽完全一致且不存在固定行高。"""
+ html = '<table><tr><td colspan="2">A</td><td>B</td></tr><tr><td>C</td><td>D</td><td>E</td></tr></table>'
+ document = Document()
+ table = materialize_docx_tables(
+ document,
+ html,
+ width_twips=10001,
+ fill_cell=_text_filler([]),
+ )[0]
+
+ table_width = table._tbl.tblPr.find(qn("w:tblW"))
+ table_layout = table._tbl.tblPr.find(qn("w:tblLayout"))
+ assert table_width is not None
+ assert (_xml_value(table_width, "w:type"), _xml_value(table_width, "w:w")) == (
+ "dxa",
+ "10001",
+ )
+ assert table_layout is not None
+ assert _xml_value(table_layout, "w:type") == "fixed"
+
+ grid_widths = [column.w.twips for column in table._tbl.tblGrid.gridCol_lst]
+ assert grid_widths == [3334, 3334, 3333]
+ for row in table._tbl.tr_lst:
+ assert sum(cell.tcPr.tcW.w for cell in row.tc_lst) == 10001
+ assert row.xpath("./w:trPr/w:trHeight") == []
+
+
+def test_callback_can_materialize_four_nested_table_levels() -> None:
+ """验证回调可使用绑定写入器递归创建最多四层嵌套表格。"""
+ html = _nested_table_html(4)
+ document = Document()
+ seen_levels: list[str] = []
+
+ def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:
+ """记录当前层级,并递归写入当前单元格中的直接子表。"""
+ parent_table = source.find_parent("table")
+ assert parent_table is not None
+ seen_levels.append(str(parent_table.get("data-level")))
+ for nested in source.find_all("table"):
+ if nested.find_parent("table") is parent_table:
+ write_nested(nested)
+ cell.paragraphs[0].add_run(f"L{parent_table.get('data-level')}")
+
+ materialize_docx_tables(document, html, width_twips=6000, fill_cell=fill_cell)
+
+ assert seen_levels == ["1", "2", "3", "4"]
+ assert len(document.element.body.xpath(".//w:tbl")) == 4
+
+
+def test_callback_rejects_fifth_nested_table_level() -> None:
+ """验证第五层嵌套表格在回调尝试写入时抛出明确错误。"""
+ document = Document()
+
+ def fill_cell(cell: _Cell, source: Tag, write_nested: NestedTableWriter) -> None:
+ """只递归写入直接子表,以触发统一深度保护。"""
+ del cell
+ parent_table = source.find_parent("table")
+ assert parent_table is not None
+ for nested in source.find_all("table"):
+ if nested.find_parent("table") is parent_table:
+ write_nested(nested)
+
+ with pytest.raises(DocxTableError, match="depth exceeds 4"):
+ materialize_docx_tables(
+ document,
+ _nested_table_html(5),
+ width_twips=6000,
+ fill_cell=fill_cell,
+ )
+
+
+def test_parse_single_tag_preserves_the_original_cell_tag_objects() -> None:
+ """验证中性解析器保留调用方提供的原始 td/th Tag,而不是复制文本。"""
+ soup_grid = parse_html_tables('<table><tr><th data-key="a">A</th><td data-key="b">B</td></tr></table>')[0]
+ table_tag = soup_grid.tag
+ parsed_again = parse_html_table(table_tag)
+ source_cells = table_tag.find_all(("th", "td"), recursive=True)
+
+ assert [cell.tag is source for cell, source in zip(parsed_again.cells, source_cells)] == [True, True]
+ assert [cell.tag.get("data-key") for cell in parsed_again.cells] == ["a", "b"]
+
+
+def _nested_table_html(depth: int, level: int = 1) -> str:
+ """生成指定总层数的单单元格嵌套表格 HTML。"""
+ nested = _nested_table_html(depth - 1, level + 1) if depth > 1 else ""
+ return f'<table data-level="{level}"><tr><td>{nested}</td></tr></table>'