Skip to content

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

fix: preserve DOCX TOC anchors and nested tables

myhloli2af74573bbec
diff --git a/mineru/backend/postprocess/lists.py b/mineru/backend/postprocess/lists.py
index 8629922d..26f6d4e8 100644
--- a/mineru/backend/postprocess/lists.py
+++ b/mineru/backend/postprocess/lists.py
@@ -51,27 +51,30 @@ def fix_office_paragraph_titles(model_list: list[list[dict[str, Any]]]) -> None:
def fix_office_index_title_blocks(model_list: list[list[dict[str, Any]]]) -> None:
- """按目标标题 anchor 将 Office 目录文本叶子转换为对应标题类型。"""
- title_by_anchor: dict[str, tuple[str, int]] = {}
+ """按正文目标 anchor 将 Office 目录文本叶子转换为对应正文或标题类型。"""
+ target_by_anchor: dict[str, tuple[str, int | None]] = {}
for page_model_list in model_list:
for block in page_model_list:
- if block.get("type") not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
+ block_type = block.get("type")
+ if block_type not in {BlockType.TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
continue
anchor = block.get("anchor")
level = block.get("level")
- if not isinstance(anchor, str) or not anchor.strip() or type(level) is not int:
+ if not isinstance(anchor, str) or not anchor.strip():
continue
- title_by_anchor.setdefault(anchor.strip(), (block["type"], level))
+ if block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE} and type(level) is not int:
+ continue
+ target_by_anchor.setdefault(anchor.strip(), (block_type, level if type(level) is int else None))
for page_model_list in model_list:
for block in page_model_list:
if block.get("type") == BlockType.INDEX:
- _rewrite_office_index_title_leaves(block, title_by_anchor)
+ _rewrite_office_index_title_leaves(block, target_by_anchor)
def _rewrite_office_index_title_leaves(
index_block: dict[str, Any],
- title_by_anchor: dict[str, tuple[str, int]],
+ target_by_anchor: dict[str, tuple[str, int | None]],
) -> None:
"""递归改写目录叶子;未匹配 anchor 时降级为不带 anchor 的普通文本。"""
content = index_block.get("content")
@@ -81,17 +84,22 @@ def _rewrite_office_index_title_leaves(
if not isinstance(child, dict):
continue
if child.get("type") == BlockType.INDEX:
- _rewrite_office_index_title_leaves(child, title_by_anchor)
+ _rewrite_office_index_title_leaves(child, target_by_anchor)
continue
if child.get("type") != BlockType.TEXT:
continue
anchor = child.get("anchor")
normalized_anchor = anchor.strip() if isinstance(anchor, str) else ""
- target = title_by_anchor.get(normalized_anchor)
+ target = target_by_anchor.get(normalized_anchor)
if target is None:
child.pop("anchor", None)
continue
- child["type"], child["level"] = target
+ target_type, target_level = target
+ child["type"] = target_type
+ if target_level is None:
+ child.pop("level", None)
+ else:
+ child["level"] = target_level
child["anchor"] = normalized_anchor
diff --git a/mineru/model/flash/html/wire/materializer.py b/mineru/model/flash/html/wire/materializer.py
index 3d142124..68aad0ba 100644
--- a/mineru/model/flash/html/wire/materializer.py
+++ b/mineru/model/flash/html/wire/materializer.py
@@ -108,7 +108,7 @@ def _materialize_text(spec: TextWireSpec, projector: MarkupProjector) -> dict[st
}
if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
block["level"] = int(spec.wrapper.get("data-level") or 1)
- if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:
+ if spec.block_type in {BlockType.TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:
anchor = (spec.wrapper.get("data-anchor") or "").strip()
if anchor:
block["anchor"] = anchor
@@ -254,8 +254,9 @@ def _materialize_index_leaf(spec: IndexLeafWireSpec, projector: MarkupProjector)
"""恢复目录叶子的内容和标题元数据。"""
content = _project_inline_content(projector, spec.content_element) if spec.content_element is not None else []
block: dict[str, object] = {"type": spec.block_type, "content": content}
- if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
+ if spec.anchor:
block["anchor"] = spec.anchor
+ if spec.block_type in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
block["level"] = spec.level or 1
if spec.block_index is not None:
block["index"] = spec.block_index
diff --git a/mineru/model/flash/html/wire/parser.py b/mineru/model/flash/html/wire/parser.py
index 19a98171..1c150e22 100644
--- a/mineru/model/flash/html/wire/parser.py
+++ b/mineru/model/flash/html/wire/parser.py
@@ -127,7 +127,7 @@ def _parse_wire_root(root: etree._Element) -> MineruHtmlWirePlan:
]
if len(nested_wrappers) != len(wrappers):
raise NonCanonicalWire
- target_ids = _collect_title_target_ids(wrappers)
+ target_ids = _collect_anchor_target_ids(wrappers)
blocks = tuple(_parse_top_block(wrapper, section_page_idx, target_ids) for wrapper, section_page_idx in wrappers)
return MineruHtmlWirePlan(root, mode, blocks)
@@ -214,7 +214,12 @@ def _validate_top_metadata(wrapper: etree._Element, block_type: BlockType) -> No
raise NonCanonicalWire
elif level is not None:
raise NonCanonicalWire
- if anchor and block_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, BlockType.PAGE_FOOTNOTE}:
+ if anchor and block_type not in {
+ BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.PAGE_FOOTNOTE,
+ }:
raise NonCanonicalWire
@@ -595,14 +600,14 @@ def _parse_index_leaf(
return IndexLeafWireSpec(item_type, block_index, content_element, anchor, level)
-def _collect_title_target_ids(
+def _collect_anchor_target_ids(
wrappers: list[tuple[etree._Element, int | None]],
) -> dict[str, frozenset[str]]:
- """预收集 renderer 标题 id,供目录 linked carrier 做确定性判定。"""
+ """预收集 renderer 正文和标题 id,供目录 linked carrier 做确定性判定。"""
collected: dict[str, set[str]] = {}
for wrapper, _ in wrappers:
block_type = (wrapper.get("data-block-type") or "").strip()
- if block_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
+ if block_type not in {BlockType.TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE}:
continue
anchor = (wrapper.get("data-anchor") or "").strip()
children = _element_children(wrapper)
@@ -626,7 +631,7 @@ def _is_canonical_index_link(
target_ids: dict[str, frozenset[str]],
) -> bool:
"""判断直属 anchor 是否为 renderer 生成的目录目标外壳。"""
- if item_type not in {BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE} or local_name(element) != "a":
+ if item_type not in {BlockType.TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE} or local_name(element) != "a":
return False
href = (element.get("href") or "").strip()
if not href.startswith("#"):
@@ -635,9 +640,9 @@ def _is_canonical_index_link(
def _validate_index_leaf_metadata(item_type: BlockType, anchor: str, level: int | None) -> None:
- """校验目录标题叶子的 anchor/level 与普通文本互斥。"""
+ """校验目录叶子的 anchor 与标题 level 组合。"""
if item_type == BlockType.TEXT:
- if anchor or level is not None:
+ if level is not None:
raise NonCanonicalWire
return
if not anchor:
diff --git a/mineru/model/flash/office/docx/docx_converter.py b/mineru/model/flash/office/docx/docx_converter.py
index 1911138b..7a6bcb8f 100644
--- a/mineru/model/flash/office/docx/docx_converter.py
+++ b/mineru/model/flash/office/docx/docx_converter.py
@@ -1,9 +1,10 @@
# Copyright (c) Opendatalab. All rights reserved.
import hashlib
import re
+from dataclasses import dataclass, field
from io import BytesIO
from pathlib import Path
-from typing import Any, BinaryIO, Final, Iterator, Optional, Union
+from typing import Any, BinaryIO, Final, Iterator, Optional, TypeAlias, Union
from docx import Document
from docx.document import Document as DocxDocument
@@ -56,6 +57,19 @@ from ..rich_text import (
)
+_ParagraphHyperlink: TypeAlias = Optional[Union[AnyUrl, Path, str]]
+_ParagraphElement: TypeAlias = tuple[str, Optional[Formatting], _ParagraphHyperlink]
+
+
+@dataclass(slots=True)
+class _DocxComplexFieldFrame:
+ """保存一个 DOCX 复杂字段的指令、阶段与已解析结果元素。"""
+
+ instruction_parts: list[str] = field(default_factory=list)
+ phase: str = "instr"
+ result_elements: list[_ParagraphElement] = field(default_factory=list)
+
+
class DocxConverter:
_BLIP_NAMESPACES: Final = {
"a": "http://schemas.openxmlformats.org/drawingml/2006/main",
@@ -796,13 +810,21 @@ class DocxConverter:
self.plain_toc_base_level = None
def _collect_toc_anchor_set(self) -> set[str]:
- """Collect TOC hyperlink anchors from the entire document body."""
+ """从真实超链接和复杂域中收集整份文档的 TOC bookmark 目标。"""
anchor_attr = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}anchor"
anchors: set[str] = set()
for hl in self.docx_obj.element.body.findall(".//w:hyperlink", namespaces=DocxConverter._BLIP_NAMESPACES):
anchor = hl.get(anchor_attr, "").strip()
if anchor and anchor.startswith("_Toc"):
anchors.add(anchor)
+ for instruction in self.docx_obj.element.body.findall(
+ ".//w:instrText",
+ namespaces=DocxConverter._BLIP_NAMESPACES,
+ ):
+ target, is_internal = self._complex_field_hyperlink_target(instruction.text or "")
+ anchor = target.removeprefix("#") if target and is_internal else ""
+ if anchor.startswith("_Toc"):
+ anchors.add(anchor)
return anchors
def _walk_linear(
@@ -1106,7 +1128,7 @@ class DocxConverter:
)
text = "".join(DocxConverter._xml_table_char_fragment(node) for node in xml_table.iter() if node.tag in char_tags)
return {
- "row_count": len(xml_table.xpath('./*[local-name()="tr"]')),
+ "row_count": len(xml_table.xpath('.//*[local-name()="tr"]')),
"cell_count": len(xml_table.xpath('.//*[local-name()="tc"]')),
"image_count": len(xml_table.xpath('.//*[local-name()="blip" or local-name()="imagedata"]')),
"text": DocxConverter._normalize_table_match_text(text),
@@ -1670,7 +1692,142 @@ class DocxConverter:
}
self.cur_page.append(image_block)
- def _get_paragraph_elements(self, paragraph: Paragraph):
+ @staticmethod
+ def _complex_field_hyperlink_target(instruction: str) -> tuple[str | None, bool]:
+ """从复杂字段指令中提取外部 URL 或内部 bookmark fragment。"""
+ internal_match = re.search(r'\bHYPERLINK\s+\\l\s+"([^"]+)"', instruction, re.IGNORECASE)
+ if internal_match:
+ anchor = internal_match.group(1).strip()
+ return (f"#{anchor}" if anchor else None), True
+
+ external_match = re.search(r'\bHYPERLINK\s+"([^"]+)"', instruction, re.IGNORECASE)
+ if external_match:
+ target = external_match.group(1).strip()
+ return (target or None), False
+ return None, False
+
+ @staticmethod
+ def _python_docx_hyperlink_target(hyperlink: Hyperlink) -> _ParagraphHyperlink:
+ """把 python-docx Hyperlink 的地址或 fragment 转换为行内目标。"""
+ address = hyperlink.address
+ fragment = hyperlink.fragment
+ if address and fragment:
+ return f"{address}#{fragment}"
+ if address and "://" in address:
+ return address
+ if address:
+ return Path(address)
+ if fragment:
+ return f"#{fragment}"
+ return Path(".")
+
+ def _resolve_complex_field_elements(
+ self,
+ frame: _DocxComplexFieldFrame,
+ *,
+ suppress_internal_links: bool,
+ ) -> list[_ParagraphElement]:
+ """闭合复杂字段,并把字段结果绑定到解析出的超链接目标。"""
+ target, is_internal = self._complex_field_hyperlink_target("".join(frame.instruction_parts))
+ if target is None or (is_internal and suppress_internal_links):
+ return frame.result_elements
+ return [(text, format_obj, existing_target or target) for text, format_obj, existing_target in frame.result_elements]
+
+ def _flatten_paragraph_elements(
+ self,
+ paragraph: Paragraph,
+ inner_contents: list[Union[Run, Hyperlink]],
+ ) -> list[_ParagraphElement]:
+ """按文档顺序展开普通 run、真实超链接与可嵌套复杂字段。"""
+ elements: list[_ParagraphElement] = []
+ field_stack: list[_DocxComplexFieldFrame] = []
+ suppress_internal_links = self._get_toc_item_level(paragraph) is not None
+ word_namespace = DocxConverter._BLIP_NAMESPACES["w"]
+
+ for content_index, content in enumerate(inner_contents):
+ if isinstance(content, Hyperlink):
+ hyperlink_target = self._python_docx_hyperlink_target(content)
+ if suppress_internal_links and isinstance(hyperlink_target, str) and hyperlink_target.startswith("#"):
+ hyperlink_target = None
+ hyperlink_elements: list[_ParagraphElement] = []
+ for hyperlink_run in content.runs:
+ if self._is_hidden_run(hyperlink_run):
+ continue
+ text = hyperlink_run.text or ""
+ format_obj = self._normalize_format_for_text(
+ self._get_format_from_run(hyperlink_run),
+ text,
+ preserve_blank_non_visible_style=True,
+ )
+ if text != "" or self._has_visible_style(format_obj):
+ hyperlink_elements.append((text, format_obj, hyperlink_target))
+ if field_stack and field_stack[-1].phase == "result":
+ field_stack[-1].result_elements.extend(hyperlink_elements)
+ else:
+ elements.extend(hyperlink_elements)
+ continue
+
+ if not isinstance(content, Run):
+ continue
+
+ field_char = content._element.find(f"{{{word_namespace}}}fldChar")
+ if field_char is not None:
+ field_type = field_char.get(f"{{{word_namespace}}}fldCharType")
+ if field_type == "begin":
+ field_stack.append(_DocxComplexFieldFrame())
+ elif field_type == "separate" and field_stack:
+ field_stack[-1].phase = "result"
+ elif field_type == "end" and field_stack:
+ frame = field_stack.pop()
+ resolved = self._resolve_complex_field_elements(
+ frame,
+ suppress_internal_links=suppress_internal_links,
+ )
+ if field_stack and field_stack[-1].phase == "result":
+ field_stack[-1].result_elements.extend(resolved)
+ else:
+ elements.extend(resolved)
+ continue
+
+ instruction = content._element.find(f"{{{word_namespace}}}instrText")
+ if instruction is not None and field_stack and field_stack[-1].phase == "instr":
+ if instruction.text:
+ field_stack[-1].instruction_parts.append(instruction.text)
+ continue
+
+ text = content.text or ""
+ raw_format = self._get_format_from_run(content)
+ preserve_blank_non_visible_style = self._should_preserve_blank_non_visible_style(
+ inner_contents,
+ content_index,
+ text,
+ raw_format,
+ )
+ format_obj = self._normalize_format_for_text(
+ raw_format,
+ text,
+ preserve_blank_non_visible_style=preserve_blank_non_visible_style,
+ )
+ element = (text, format_obj, None)
+ if field_stack:
+ if field_stack[-1].phase == "result":
+ field_stack[-1].result_elements.append(element)
+ continue
+ elements.append(element)
+
+ while field_stack:
+ frame = field_stack.pop()
+ resolved = self._resolve_complex_field_elements(
+ frame,
+ suppress_internal_links=suppress_internal_links,
+ )
+ if field_stack and field_stack[-1].phase == "result":
+ field_stack[-1].result_elements.extend(resolved)
+ else:
+ elements.extend(resolved)
+ return elements
+
+ def _get_paragraph_elements(self, paragraph: Paragraph) -> list[_ParagraphElement]:
"""
提取段落元素及其格式和超链接信息。
@@ -1678,7 +1835,7 @@ class DocxConverter:
paragraph: 段落对象
Returns:
- list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]]:
+ list[_ParagraphElement]:
段落元素列表,每个元素包含文本、格式和超链接信息
"""
@@ -1696,152 +1853,25 @@ class DocxConverter:
if not has_visible_style_run:
return [("", None, None)]
- paragraph_elements: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]] = []
+ paragraph_elements: list[_ParagraphElement] = []
group_text = ""
- previous_format = None
-
- # 字段代码超链接内联检测状态(处理 w:fldChar + w:instrText 形式的超链接)
- _W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
- _field_in = False # 当前是否在字段域内
- _field_url = None # 当前字段域解析出的 URL
- _field_phase = None # 'instr' 或 'result'
- _field_acc_text = "" # 累积的显示文本
- _field_acc_format = None # 首个显示 run 的格式
-
- # 遍历段落的 runs 并按格式分组
- for content_index, c in enumerate(inner_contents):
- if isinstance(c, Hyperlink):
- # 若地址为 URL(含 ://),直接保留字符串,避免 Path 将 // 规范化为 /
- address = c.address
- if address and "://" in address:
- hyperlink = address
- else:
- hyperlink = Path(address) if address else Path(".")
- # Hyperlink 内可能包含多个 run(且样式不同,如 TOC 项中的删除线/斜体)。
- # 按 run 粒度展开,避免只取首个 run 导致样式丢失。
- if c.runs and len(c.runs) > 0:
- # 先落盘当前累积的普通文本分组
- prev_has_visible = self._should_keep_group_text(
- group_text,
- previous_format,
- )
- if prev_has_visible:
- paragraph_elements.append((group_text, previous_format, None))
- group_text = ""
-
- for h_run in c.runs:
- # Skip hidden runs in hyperlinks, especially TOC page-number fields.
- if self._is_hidden_run(h_run):
- continue
- h_text = h_run.text or ""
- h_format = self._normalize_format_for_text(
- self._get_format_from_run(h_run),
- h_text,
- preserve_blank_non_visible_style=True,
- )
- # 保留非空文本(含制表符)以及带可见样式的空白 run
- if h_text != "" or self._has_visible_style(h_format):
- self._append_paragraph_element(
- paragraph_elements,
- h_text,
- h_format,
- hyperlink,
- )
- # 保持 previous_format 为最近的普通文本格式,不跨越超链接合并
- continue
- else:
- text = c.text
- format = None
- elif isinstance(c, Run):
- # ---- 字段代码超链接内联检测 ----
- fld_char = c._element.find(f"{{{_W_NS}}}fldChar")
- if fld_char is not None:
- fld_type = fld_char.get(f"{{{_W_NS}}}fldCharType")
- if fld_type == "begin":
- _field_in = True
- _field_url = None
- _field_phase = "instr"
- _field_acc_text = ""
- _field_acc_format = None
- continue
- elif fld_type == "separate":
- _field_phase = "result"
- continue
- elif fld_type == "end":
- if _field_url and _field_acc_text.strip():
- # 将累积的字段代码超链接作为一个整体处理
- text = _field_acc_text
- hyperlink = _field_url
- format = _field_acc_format
- elif _field_acc_text.strip():
- # 非超链接字段(如 SEQ 序号字段),将累积的显示文本作为普通文本处理
- text = _field_acc_text
- hyperlink = None
- format = _field_acc_format
- else:
- _field_in = False
- _field_url = None
- _field_phase = None
- _field_acc_text = ""
- _field_acc_format = None
- continue
- _field_in = False
- _field_url = None
- _field_phase = None
- _field_acc_text = ""
- _field_acc_format = None
- # 继续执行下方的 hyperlink 统一处理逻辑
- else:
- continue
- else:
- instr_elem = c._element.find(f"{{{_W_NS}}}instrText")
- if instr_elem is not None and _field_phase == "instr":
- # 捕获 HYPERLINK 指令中的 URL
- if instr_elem.text:
- m = re.search(r'HYPERLINK\s+"([^"]+)"', instr_elem.text)
- if m:
- _field_url = m.group(1)
- continue
-
- if _field_in and _field_phase == "result":
- # 显示文本 run:累积到字段文本
- t_elem = c._element.find(f"{{{_W_NS}}}t")
- if t_elem is not None:
- _field_acc_text += c.text
- if _field_acc_format is None:
- _field_acc_format = self._get_format_from_run(c)
- continue
-
- # 普通 run
- text = c.text
- hyperlink = None
- raw_format = self._get_format_from_run(c)
- preserve_blank_non_visible_style = self._should_preserve_blank_non_visible_style(
- inner_contents,
- content_index,
- text,
- raw_format,
- )
- format = self._normalize_format_for_text(
- raw_format,
- text,
- preserve_blank_non_visible_style=preserve_blank_non_visible_style,
- )
- else:
- continue
+ previous_format: Optional[Formatting] = None
+ # 遍历已经展开的普通 run、超链接与复杂字段结果,并按格式分组。
+ flattened_elements = self._flatten_paragraph_elements(paragraph, inner_contents)
+ for text, format_obj, hyperlink in flattened_elements:
# 当新 run 有可见内容(非空或带可见样式的空白)且格式变化时触发分组
- has_visible_content = len(text.strip()) > 0 or self._has_visible_style(format)
+ has_visible_content = len(text.strip()) > 0 or self._has_visible_style(format_obj)
is_blank_text = bool(text) and not text.strip()
- format_changed = format != previous_format
- has_visible_boundary = self._has_visible_style(previous_format) or self._has_visible_style(format)
+ format_changed = format_obj != previous_format
+ has_visible_boundary = self._has_visible_style(previous_format) or self._has_visible_style(format_obj)
should_split_blank_boundary = is_blank_text and bool(group_text) and format_changed and has_visible_boundary
if (has_visible_content and format_changed) or should_split_blank_boundary or (hyperlink is not None):
# 前一组有实质内容(非空或带可见样式的空白)时才保存
preserve_plain_blank = (
bool(group_text)
and not group_text.strip()
- and (self._has_visible_style(previous_format) or self._has_visible_style(format))
+ and (self._has_visible_style(previous_format) or self._has_visible_style(format_obj))
)
prev_has_visible = self._should_keep_group_text(
group_text,
@@ -1854,10 +1884,10 @@ class DocxConverter:
# 如果有超链接,则立即添加
if hyperlink is not None:
- paragraph_elements.append((text.strip(), format, hyperlink))
+ self._append_paragraph_element(paragraph_elements, text.strip(), format_obj, hyperlink)
text = ""
else:
- previous_format = format
+ previous_format = format_obj
group_text += text
@@ -2926,19 +2956,32 @@ class DocxConverter:
return names[0]
def _extract_toc_target_anchor(self, paragraph_element: BaseOxmlElement) -> Optional[str]:
- """Extract internal bookmark target from a TOC paragraph hyperlink."""
+ """从真实超链接或复杂域中提取 TOC 段落的内部 bookmark。"""
anchor_attr = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}anchor"
anchors = []
for hl in paragraph_element.findall(".//w:hyperlink", namespaces=DocxConverter._BLIP_NAMESPACES):
anchor = hl.get(anchor_attr, "").strip()
if anchor:
anchors.append(anchor)
- if not anchors:
- return None
for anchor in anchors:
if anchor.startswith("_Toc"):
return anchor
- return anchors[0]
+ if anchors:
+ return anchors[0]
+
+ field_anchors: list[str] = []
+ for instruction in paragraph_element.findall(
+ ".//w:instrText",
+ namespaces=DocxConverter._BLIP_NAMESPACES,
+ ):
+ target, is_internal = self._complex_field_hyperlink_target(instruction.text or "")
+ anchor = target.removeprefix("#") if target and is_internal else ""
+ if anchor:
+ field_anchors.append(anchor)
+ for anchor in field_anchors:
+ if anchor.startswith("_Toc"):
+ return anchor
+ return field_anchors[0] if field_anchors else None
def _handle_plain_toc_paragraph_as_index(
self,
diff --git a/mineru/render/_internal/common/planner.py b/mineru/render/_internal/common/planner.py
index e1ff7819..82b8247d 100644
--- a/mineru/render/_internal/common/planner.py
+++ b/mineru/render/_internal/common/planner.py
@@ -57,12 +57,17 @@ def build_render_plan(
def _merge_continued_text_blocks(blocks: list[PlannedBlock], mode: RenderMode) -> None:
- """把 continues_prev 文本吸收到最近的前序文本逻辑块。"""
+ """把无独立正文锚点的 continues_prev 文本吸收到最近的前序文本逻辑块。"""
for current_index, current in enumerate(blocks):
if (
current.removed
or not isinstance(current.block, ContinuableTextBlockBase)
or current.block.continues_prev is not True
+ or (
+ isinstance(current.block, TextBlock)
+ and isinstance(current.block.anchor, str)
+ and bool(current.block.anchor.strip())
+ )
):
continue
previous = _find_previous_planned_text(blocks, current_index)
diff --git a/mineru/render/_internal/content_list/v1.py b/mineru/render/_internal/content_list/v1.py
index 266d7ba8..8b51e23b 100644
--- a/mineru/render/_internal/content_list/v1.py
+++ b/mineru/render/_internal/content_list/v1.py
@@ -108,7 +108,9 @@ def _render_unit_content(
"list_items": [render_inline_content(block.content, delimiters) for block in unit.blocks if block.content],
}
if isinstance(unit, TextBlock):
- return {"type": "text", "text": render_inline_content(unit.content, delimiters)}
+ item = {"type": "text", "text": render_inline_content(unit.content, delimiters)}
+ _add_anchor(item, unit.anchor)
+ return item
if isinstance(unit, (DocTitleBlock, ParagraphTitleBlock)):
item: dict[str, Any] = {
"type": "text",
@@ -163,7 +165,7 @@ def _render_index_items(block: IndexBlock, delimiters: LatexDelimitersConfig) ->
label = render_inline_content(content, delimiters).strip()
if not label:
continue
- if isinstance(leaf.block, (DocTitleBlock, ParagraphTitleBlock)) and leaf.block.anchor:
+ if leaf.block.anchor:
label = render_internal_link(label, leaf.block.anchor)
items.append(f"{' ' * leaf.depth}- {label}")
return items
diff --git a/mineru/render/_internal/content_list/v2.py b/mineru/render/_internal/content_list/v2.py
index 5a0aa760..bb983962 100644
--- a/mineru/render/_internal/content_list/v2.py
+++ b/mineru/render/_internal/content_list/v2.py
@@ -102,7 +102,9 @@ def _render_unit_content(
if isinstance(unit, ReferenceGroup):
return _reference_list_item(unit)
if isinstance(unit, TextBlock):
- return {"type": "paragraph", "content": {"paragraph_content": serialize_v2_spans(unit.content)}}
+ item = {"type": "paragraph", "content": {"paragraph_content": serialize_v2_spans(unit.content)}}
+ _add_anchor(item, unit.anchor)
+ return item
if isinstance(unit, (DocTitleBlock, ParagraphTitleBlock)):
item: dict[str, Any] = {
"type": "title",
@@ -203,8 +205,7 @@ def _render_index(block: IndexBlock) -> dict[str, Any]:
"item_type": "text",
"item_content": serialize_v2_spans(content),
}
- if isinstance(leaf.block, (DocTitleBlock, ParagraphTitleBlock)):
- _add_anchor(item, leaf.block.anchor)
+ _add_anchor(item, leaf.block.anchor)
list_items.append(item)
return {
"type": "index",
diff --git a/mineru/render/_internal/docx/renderer.py b/mineru/render/_internal/docx/renderer.py
index f8ea099f..395a2f95 100644
--- a/mineru/render/_internal/docx/renderer.py
+++ b/mineru/render/_internal/docx/renderer.py
@@ -160,6 +160,8 @@ class _DocxRenderer:
planned.text_contents or [block.content],
context=context,
)
+ if isinstance(block, TextBlock):
+ self.bookmarks.attach(paragraph, block.anchor)
return
if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
self._render_title(block, context)
@@ -320,8 +322,7 @@ class _DocxRenderer:
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, content, anchor=anchor, context=context)
+ append_internal_link(paragraph, content, anchor=child.anchor, context=context)
def _render_image_block(self, block: ImageBlock, context: InlineRenderContext) -> None:
"""按原始子块顺序写图片主体、caption 与 footnote。"""
@@ -813,10 +814,10 @@ def render_docx(
def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:
- """遍历标题和默认可见页面脚注实际会写入的 bookmark anchor。"""
+ """遍历正文、标题和默认可见页面脚注实际会写入的 bookmark anchor。"""
for page in middle_json.pages:
for block in page.blocks:
- if isinstance(block, TitleBlockBase) and block.anchor:
+ if isinstance(block, (TextBlock, TitleBlockBase)) and block.anchor:
yield block.anchor
elif isinstance(block, PageFootnoteBlock) and block.anchor:
yield block.anchor
diff --git a/mineru/render/_internal/epub/renderer.py b/mineru/render/_internal/epub/renderer.py
index c2c6e1a5..bbee6f40 100644
--- a/mineru/render/_internal/epub/renderer.py
+++ b/mineru/render/_internal/epub/renderer.py
@@ -171,7 +171,7 @@ class _TitleTarget:
class _AnchorRegistry:
- """为正文标题和页面脚注分配文档级唯一 XHTML id。"""
+ """为正文文本、标题和页面脚注分配文档级唯一 XHTML id。"""
def __init__(self, middle_json: MiddleJson) -> None:
"""按页面与 block 顺序建立目标、来源 anchor 和标题索引。"""
@@ -181,6 +181,7 @@ class _AnchorRegistry:
self.title_targets: list[_TitleTarget] = []
used_ids: set[str] = {"content-start"}
heading_position = 0
+ text_position = 0
footnote_position = 0
for page in middle_json.pages:
for block in page.blocks:
@@ -195,6 +196,16 @@ class _AnchorRegistry:
used_ids=used_ids,
)
self.title_targets.append(_TitleTarget(visible, block.level, target_id))
+ elif isinstance(block, TextBlock):
+ visible = inline_plain_text(block.content).strip()
+ if not visible or not (block.anchor or "").strip():
+ continue
+ text_position += 1
+ target_id = _allocate_target_id(
+ block.anchor,
+ fallback=f"text-{text_position}",
+ used_ids=used_ids,
+ )
elif isinstance(block, PageFootnoteBlock):
visible = inline_plain_text(block.content).strip()
if not visible:
@@ -320,6 +331,10 @@ class _EpubXhtmlRenderer:
_xhtml("p"),
attrib={"class": "mineru-ref-text" if isinstance(block, RefTextBlock) else "mineru-text"},
)
+ if isinstance(block, TextBlock):
+ target_id = self.anchors.target_for_block(planned.page_idx, block)
+ if target_id:
+ paragraph.set("id", target_id)
self._append_inline_spans(paragraph, content)
return paragraph if _has_visible_content(paragraph) else None
if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
@@ -447,7 +462,7 @@ class _EpubXhtmlRenderer:
if not inline_plain_text(content).strip():
continue
item = etree.SubElement(parent, _xhtml("li"))
- target = self.anchors.target_for_anchor(child.anchor) if isinstance(child, TitleBlockBase) else None
+ target = self.anchors.target_for_anchor(child.anchor)
inline_parent = item
if target:
inline_parent = etree.SubElement(item, _xhtml("a"), href=f"#{quote(target, safe='-._~')}")
@@ -874,8 +889,6 @@ def _navigation_from_index(block: IndexBlock, anchors: _AnchorRegistry) -> list[
else:
result.extend(nested)
continue
- if not isinstance(child, TitleBlockBase):
- continue
target = anchors.target_for_anchor(child.anchor)
title = inline_plain_text(strip_index_page_tail(child.content)).strip()
if not target or not title:
diff --git a/mineru/render/_internal/html/renderer.py b/mineru/render/_internal/html/renderer.py
index ca99d689..3f5b478a 100644
--- a/mineru/render/_internal/html/renderer.py
+++ b/mineru/render/_internal/html/renderer.py
@@ -202,7 +202,11 @@ class _HtmlRenderer:
if isinstance(block, TextBlock):
rendered = render_joined_inline_contents_html(planned.text_contents or [block.content])
self._observe_inline(rendered)
- return f'<p class="mineru-text">{rendered.html}</p>' if rendered.html else ""
+ if not rendered.html:
+ return ""
+ attrs = ['class="mineru-text"']
+ self._append_anchor_attribute(attrs, block.anchor, block_type=str(block.type))
+ return f"<p {' '.join(attrs)}>{rendered.html}</p>"
if isinstance(block, RefTextBlock):
rendered = render_joined_inline_contents_html(planned.text_contents or [block.content])
self._observe_inline(rendered)
@@ -413,7 +417,7 @@ class _HtmlRenderer:
self._observe_inline(rendered)
if not rendered.html:
return "", _wire_block_attributes(block)
- anchor = _anchor_key(block.anchor) if isinstance(block, TitleBlockBase) else ""
+ anchor = _anchor_key(block.anchor)
if anchor and (anchor_id := self.anchor_targets.get(anchor)):
href = quote(anchor_id, safe="-._~")
return f'<a href="#{href}">{rendered.html}</a>', _wire_block_attributes(block)
@@ -810,12 +814,12 @@ def _wrap_visual_body(
def _collect_document_anchor_ids(middle_json: MiddleJson) -> dict[str, str]:
- """为标题和页面脚注的首次非空 anchor 分配 document-wide 唯一 HTML id。"""
+ """为正文、标题和页面脚注的首次非空 anchor 分配文档级唯一 HTML id。"""
anchor_ids: dict[str, str] = {}
used_ids: set[str] = set()
for page in middle_json.pages:
for block in page.blocks:
- if isinstance(block, TitleBlockBase):
+ if isinstance(block, (TextBlock, TitleBlockBase)):
visible_content = inline_plain_text(block.content).strip()
elif isinstance(block, PageFootnoteBlock):
visible_content = inline_plain_text(block.content).strip()
diff --git a/mineru/render/_internal/markdown/blocks.py b/mineru/render/_internal/markdown/blocks.py
index 96f34a8f..d2fa9762 100644
--- a/mineru/render/_internal/markdown/blocks.py
+++ b/mineru/render/_internal/markdown/blocks.py
@@ -63,19 +63,22 @@ def render_planned_block(
delimiters: LatexDelimitersConfig,
asset_base_url: str,
image_renderer: ImageRenderer | None = None,
+ anchor_targets: set[str] | None = None,
+ emitted_anchors: set[str] | None = None,
) -> str:
"""按具体 Pydantic block 类型分发 Markdown 渲染。"""
block = planned.block
if isinstance(block, TextBlock):
content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
- return escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
+ rendered = escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
+ return _prepend_markdown_anchor(rendered, block.anchor, emitted_anchors)
if isinstance(block, RefTextBlock):
content = render_joined_inline_contents(planned.text_contents or [block.content], delimiters)
return escape_standalone_marker_rule(content)
if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
- return _render_title(block, delimiters)
+ return _render_title(block, delimiters, emitted_anchors)
if isinstance(block, PageFootnoteBlock):
- return _render_page_footnote(block, delimiters)
+ return _render_page_footnote(block, delimiters, emitted_anchors)
if isinstance(block, PageAuxTextBlock):
content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))
return escape_standalone_marker_rule(content)
@@ -84,7 +87,7 @@ def render_planned_block(
if isinstance(block, ListBlock):
return _render_list(block, delimiters)
if isinstance(block, IndexBlock):
- return _render_index(block, delimiters)
+ return _render_index(block, delimiters, anchor_targets=anchor_targets)
if isinstance(block, ImageBlock):
return _render_image_block(block, delimiters, asset_base_url, image_renderer)
if isinstance(block, TableBlock):
@@ -96,7 +99,33 @@ def render_planned_block(
raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
-def _render_page_footnote(block: PageFootnoteBlock, delimiters: LatexDelimitersConfig) -> str:
+def _claim_markdown_anchor(anchor: str | None, emitted_anchors: set[str] | None) -> str:
+ """规范化 Markdown 目标,并在文档级集合中只登记首次出现的 anchor。"""
+ normalized = (anchor or "").strip()
+ if not normalized:
+ return ""
+ if emitted_anchors is not None:
+ if normalized in emitted_anchors:
+ return ""
+ emitted_anchors.add(normalized)
+ return normalized
+
+
+def _prepend_markdown_anchor(content: str, anchor: str | None, emitted_anchors: set[str] | None) -> str:
+ """给非空 Markdown 正文添加独立 HTML anchor,避免污染正文文本。"""
+ if not content.strip():
+ return content
+ normalized = _claim_markdown_anchor(anchor, emitted_anchors)
+ if not normalized:
+ return content
+ return f'<a id="{html.escape(normalized, quote=True)}"></a>\n{content}'
+
+
+def _render_page_footnote(
+ block: PageFootnoteBlock,
+ delimiters: LatexDelimitersConfig,
+ emitted_anchors: set[str] | None = None,
+) -> str:
"""用非折叠的小字号浅色 HTML 标识输出页面脚注。"""
content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))
rendered = escape_standalone_marker_rule(content)
@@ -108,7 +137,7 @@ def _render_page_footnote(block: PageFootnoteBlock, delimiters: LatexDelimitersC
'data-block-type="page_footnote"',
'style="color:#6b7280"',
]
- anchor = (block.anchor or "").strip()
+ anchor = _claim_markdown_anchor(block.anchor, emitted_anchors)
if anchor:
attrs.insert(0, f'id="{html.escape(anchor, quote=True)}"')
return f"<small><span {' '.join(attrs)}>{rendered}</span></small>"
@@ -135,14 +164,15 @@ def render_single_block(
def _render_title(
block: DocTitleBlock | ParagraphTitleBlock,
delimiters: LatexDelimitersConfig,
+ emitted_anchors: set[str] | None = None,
) -> str:
"""渲染带可选 HTML anchor 的 Markdown 标题。"""
level = min(max(block.level, 1), 6)
title = f"{'#' * level} {render_title_inline_content(block, delimiters)}"
- if not block.anchor:
+ anchor = _claim_markdown_anchor(block.anchor, emitted_anchors)
+ if not anchor:
return title
- anchor = html.escape(block.anchor.strip(), quote=True)
- return f'<a id="{anchor}"></a>\n{title}'
+ return f'<a id="{html.escape(anchor, quote=True)}"></a>\n{title}'
def render_title_inline_content(
@@ -195,12 +225,18 @@ def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: int
return "\n".join(lines)
-def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:
+def _render_index(
+ block: IndexBlock,
+ delimiters: LatexDelimitersConfig,
+ depth: int = 0,
+ *,
+ anchor_targets: set[str] | None = None,
+) -> str:
"""递归渲染目录列表,并给标题叶子添加内部 anchor 链接。"""
lines: list[str] = []
for child in block.content:
if isinstance(child, IndexBlock):
- nested = _render_index(child, delimiters, depth + 1)
+ nested = _render_index(child, delimiters, depth + 1, anchor_targets=anchor_targets)
if nested:
lines.extend(nested.splitlines())
continue
@@ -208,8 +244,9 @@ def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: i
label = render_inline_content(content, delimiters).strip()
if not label:
continue
- if isinstance(child, (DocTitleBlock, ParagraphTitleBlock)) and child.anchor:
- label = render_internal_link(label, child.anchor)
+ anchor = (child.anchor or "").strip()
+ if anchor and (anchor_targets is None or anchor in anchor_targets):
+ label = render_internal_link(label, anchor)
lines.append(f"{' ' * depth}- {label}")
return "\n".join(lines)
diff --git a/mineru/render/_internal/markdown/renderer.py b/mineru/render/_internal/markdown/renderer.py
index e621771c..0e275f98 100644
--- a/mineru/render/_internal/markdown/renderer.py
+++ b/mineru/render/_internal/markdown/renderer.py
@@ -4,7 +4,8 @@
from __future__ import annotations
from ....config import LatexDelimitersConfig, config
-from ....types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson
+from ....backend.postprocess.inline import inline_plain_text
+from ....types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson, PageFootnoteBlock, TextBlock, TitleBlockBase
from ...contracts import ImageRenderer, RenderMode
from ..common.planner import PlannedBlock, build_render_plan
from .blocks import render_planned_block
@@ -27,6 +28,8 @@ def render_markdown(
delimiters = config.render.latex_delimiters
planned_pages = build_render_plan(middle_json, mode)
+ anchor_targets = _collect_markdown_anchor_targets(middle_json)
+ emitted_anchors: set[str] = set()
rendered_pages = [
_render_page(
page,
@@ -34,6 +37,8 @@ def render_markdown(
delimiters=delimiters,
asset_base_url=asset_base_url,
image_renderer=image_renderer,
+ anchor_targets=anchor_targets,
+ emitted_anchors=emitted_anchors,
)
for page in planned_pages
]
@@ -49,6 +54,8 @@ def _render_page(
delimiters: LatexDelimitersConfig,
asset_base_url: str,
image_renderer: ImageRenderer | None = None,
+ anchor_targets: set[str] | None = None,
+ emitted_anchors: set[str] | None = None,
) -> str:
"""渲染单页逻辑块,并在默认模式中过滤重复页元素。"""
rendered: list[str] = []
@@ -62,10 +69,25 @@ def _render_page(
delimiters=delimiters,
asset_base_url=asset_base_url,
image_renderer=image_renderer,
+ anchor_targets=anchor_targets,
+ emitted_anchors=emitted_anchors,
)
if text and text.strip():
rendered.append(text.strip("\n"))
return "\n\n".join(rendered)
+def _collect_markdown_anchor_targets(middle_json: MiddleJson) -> set[str]:
+ """收集真实可见的顶层正文、标题和页面脚注 anchor,供目录链接判定。"""
+ targets: set[str] = set()
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if not isinstance(block, (TextBlock, TitleBlockBase, PageFootnoteBlock)):
+ continue
+ anchor = (block.anchor or "").strip()
+ if anchor and inline_plain_text(block.content).strip():
+ targets.add(anchor)
+ return targets
+
+
__all__ = ["render_markdown"]
diff --git a/mineru/render/_internal/pdf/renderer.py b/mineru/render/_internal/pdf/renderer.py
index 010cf117..a1973d95 100644
--- a/mineru/render/_internal/pdf/renderer.py
+++ b/mineru/render/_internal/pdf/renderer.py
@@ -221,7 +221,8 @@ class _PdfRenderer:
block = planned.block
if isinstance(block, (TextBlock, RefTextBlock)):
spans = join_inline_spans(planned.text_contents or [block.content])
- return [self._paragraph(spans, self.styles.body, planned.page_idx, block)]
+ anchor = block.anchor if isinstance(block, TextBlock) else None
+ return [self._paragraph(spans, self.styles.body, planned.page_idx, block, anchor=anchor)]
if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
return [
self._paragraph(
@@ -348,7 +349,7 @@ class _PdfRenderer:
if not content:
continue
spans: list[InlineSpan] = [TextSpan(type="text", content="• ")]
- if isinstance(child, TitleBlockBase) and child.anchor:
+ if child.anchor:
link_content = _flatten_non_link_spans(content)
if link_content:
spans.append(HyperlinkSpan(type="hyperlink", url=f"#{child.anchor}", content=link_content))
@@ -695,10 +696,10 @@ def _resolve_document_title(middle_json: MiddleJson, explicit: str | None) -> st
def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:
- """按文档顺序枚举标题和页面脚注的非空 anchor。"""
+ """按文档顺序枚举正文、标题和页面脚注的非空 anchor。"""
for page in middle_json.pages:
for block in page.blocks:
- if isinstance(block, TitleBlockBase) and block.anchor:
+ if isinstance(block, (TextBlock, TitleBlockBase)) and block.anchor:
yield block.anchor
elif isinstance(block, PageFootnoteBlock) and block.anchor:
yield block.anchor
diff --git a/mineru/render/_internal/structured_content/renderer.py b/mineru/render/_internal/structured_content/renderer.py
index 9d179bfe..43600b55 100644
--- a/mineru/render/_internal/structured_content/renderer.py
+++ b/mineru/render/_internal/structured_content/renderer.py
@@ -33,6 +33,7 @@ from ....types import (
PageFootnoteBlock,
PageBlock,
ParagraphTitleBlock,
+ TextBlock,
TableAnnotationBlock,
TableBlock,
TableBodyBlock,
@@ -104,6 +105,10 @@ def _render_content_block(
content = render_title_inline_content(block, delimiters)
payload["content"] = escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
return payload
+ if isinstance(block, TextBlock):
+ content = render_inline_content(block.content, delimiters)
+ payload["content"] = escape_standalone_marker_rule(escape_text_block_markdown_prefix(content))
+ return payload
if isinstance(block, EquationBlock):
payload["content"] = block.content.strip()
image_source = _resolve_content_image_source(block, asset_base_url)
diff --git a/mineru/types.py b/mineru/types.py
index 8aae206c..bb974657 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -645,6 +645,7 @@ class ContinuableTextBlockBase(InlineContentBlock):
class TextBlock(ContinuableTextBlockBase):
type: Literal[BlockType.TEXT] # type: ignore[reportIncompatibleVariableOverride]
+ anchor: str | None = None
class RefTextBlock(ContinuableTextBlockBase):
diff --git a/tests/unittest/test_docx_complex_fields.py b/tests/unittest/test_docx_complex_fields.py
new file mode 100644
index 00000000..86721c68
--- /dev/null
+++ b/tests/unittest/test_docx_complex_fields.py
@@ -0,0 +1,144 @@
+from __future__ import annotations
+
+from io import BytesIO
+
+from docx import Document
+from docx.enum.style import WD_STYLE_TYPE
+from docx.oxml import OxmlElement
+from docx.oxml.ns import qn
+from docx.text.paragraph import Paragraph
+
+from mineru.backend.analyze import doc_analyze
+from mineru.backend.postprocess.inline import inline_plain_text
+from mineru.model.flash import DocxModel
+from mineru.model.flash._shared.spans import inline_span_plain_text
+from mineru.types import IndexBlock, ParagraphTitleBlock, TextBlock
+
+
+def _append_field_char(paragraph: Paragraph, field_type: str) -> None:
+ """向段落追加一个复杂字段边界 run。"""
+ run = OxmlElement("w:r")
+ field_char = OxmlElement("w:fldChar")
+ field_char.set(qn("w:fldCharType"), field_type)
+ run.append(field_char)
+ paragraph._p.append(run)
+
+
+def _append_instruction(paragraph: Paragraph, instruction: str) -> None:
+ """向段落追加复杂字段指令 run。"""
+ run = OxmlElement("w:r")
+ instruction_element = OxmlElement("w:instrText")
+ instruction_element.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+ instruction_element.text = instruction
+ run.append(instruction_element)
+ paragraph._p.append(run)
+
+
+def _append_result_text(paragraph: Paragraph, text: str) -> None:
+ """向字段结果追加一个可见文本 run。"""
+ run = OxmlElement("w:r")
+ text_element = OxmlElement("w:t")
+ text_element.text = text
+ run.append(text_element)
+ paragraph._p.append(run)
+
+
+def _append_result_tab(paragraph: Paragraph) -> None:
+ """向字段结果追加 Word 制表符 run。"""
+ run = OxmlElement("w:r")
+ run.append(OxmlElement("w:tab"))
+ paragraph._p.append(run)
+
+
+def _append_toc_complex_field(
+ paragraph: Paragraph,
+ *,
+ title: str,
+ page_number: str,
+ anchor: str,
+ include_outer_toc: bool,
+) -> None:
+ """构造 WPS 常见的 TOC、HYPERLINK 与 PAGEREF 嵌套复杂域。"""
+ if include_outer_toc:
+ _append_field_char(paragraph, "begin")
+ _append_instruction(paragraph, ' TOC \\o "1-1" \\h \\z \\u ')
+ _append_field_char(paragraph, "separate")
+
+ _append_field_char(paragraph, "begin")
+ _append_instruction(paragraph, f' HYPERLINK \\l "{anchor}" ')
+ _append_field_char(paragraph, "separate")
+ _append_result_text(paragraph, title)
+ _append_result_tab(paragraph)
+ _append_field_char(paragraph, "begin")
+ _append_instruction(paragraph, f" PAGEREF {anchor} \\h ")
+ _append_field_char(paragraph, "separate")
+ _append_result_text(paragraph, page_number)
+ _append_field_char(paragraph, "end")
+ _append_field_char(paragraph, "end")
+
+ if include_outer_toc:
+ _append_field_char(paragraph, "end")
+
+
+def _attach_bookmark(paragraph: Paragraph, anchor: str, bookmark_id: int) -> None:
+ """把 bookmark 包围段落现有正文,模拟 TOC 的真实跳转目标。"""
+ start = OxmlElement("w:bookmarkStart")
+ start.set(qn("w:id"), str(bookmark_id))
+ start.set(qn("w:name"), anchor)
+ end = OxmlElement("w:bookmarkEnd")
+ end.set(qn("w:id"), str(bookmark_id))
+ insert_at = 1 if paragraph._p.pPr is not None else 0
+ paragraph._p.insert(insert_at, start)
+ paragraph._p.append(end)
+
+
+def _build_complex_toc_docx() -> bytes:
+ """生成一个包含匹配目标和缺失目标的最小复杂域目录 DOCX。"""
+ document = Document()
+ toc_style = document.styles.add_style("TOC 1", WD_STYLE_TYPE.PARAGRAPH)
+
+ first = document.add_paragraph(style=toc_style)
+ _append_toc_complex_field(
+ first,
+ title="一、建设项目基本情况",
+ page_number="1",
+ anchor="_TocTarget",
+ include_outer_toc=True,
+ )
+ second = document.add_paragraph(style=toc_style)
+ _append_toc_complex_field(
+ second,
+ title="二、缺失章节",
+ page_number="9",
+ anchor="_TocMissing",
+ include_outer_toc=False,
+ )
+
+ heading = document.add_heading("一、建设项目基本情况", level=1)
+ _attach_bookmark(heading, "_TocTarget", 7)
+
+ output = BytesIO()
+ document.save(output)
+ return output.getvalue()
+
+
+def test_nested_complex_toc_fields_preserve_titles_and_strict_index_targets() -> None:
+ """验证嵌套复杂域不会只剩页码,并按真实正文目标收敛目录 anchor。"""
+ file_bytes = _build_complex_toc_docx()
+ model_pages = DocxModel().predict(BytesIO(file_bytes))
+ raw_index = next(block for page in model_pages for block in page if block["type"] == "index")
+
+ assert [inline_span_plain_text(child["content"]) for child in raw_index["content"]] == [
+ "一、建设项目基本情况\t1",
+ "二、缺失章节\t9",
+ ]
+ assert [child.get("anchor") for child in raw_index["content"]] == ["_TocTarget", "_TocMissing"]
+
+ middle_json, _ = doc_analyze(file_bytes, effort="flash", parse_mode="auto", file_suffix="docx")
+ typed_index = next(block for page in middle_json.pages for block in page.blocks if isinstance(block, IndexBlock))
+ assert isinstance(typed_index.content[0], ParagraphTitleBlock)
+ assert typed_index.content[0].anchor == "_TocTarget"
+ assert inline_plain_text(typed_index.content[0].content) == "一、建设项目基本情况\t1"
+ assert isinstance(typed_index.content[1], TextBlock)
+ assert typed_index.content[1].anchor is None
+ assert inline_plain_text(typed_index.content[1].content) == "二、缺失章节\t9"
diff --git a/tests/unittest/test_docx_special_char_tables.py b/tests/unittest/test_docx_special_char_tables.py
index 4afa750f..71cdc0e6 100644
--- a/tests/unittest/test_docx_special_char_tables.py
+++ b/tests/unittest/test_docx_special_char_tables.py
@@ -80,6 +80,21 @@ def _build_plain_docx_table() -> bytes:
return _save_docx_bytes(doc)
+def _build_nested_merged_docx_table() -> bytes:
+ """构造含嵌套行、纵向合并和编号样式的完整上下文表格。"""
+ doc = Document()
+ table = doc.add_table(rows=2, cols=2)
+ merged = table.cell(0, 0).merge(table.cell(1, 0))
+ merged.paragraphs[0].add_run("纵向合并")
+ nested = table.cell(0, 1).add_table(rows=2, cols=1)
+ nested.cell(0, 0).paragraphs[0].add_run("嵌套首行")
+ numbered = nested.cell(1, 0).paragraphs[0]
+ numbered.style = doc.styles["List Number"]
+ numbered.add_run("嵌套编号行")
+ table.cell(1, 1).paragraphs[0].add_run("外层尾行")
+ return _save_docx_bytes(doc)
+
+
def test_no_break_hyphen_table_not_lost() -> None:
"""验证不间断连字符与编号列表并存时整表不会丢失。"""
tables = _table_blocks(_convert_docx_bytes(_build_docx_with_no_break_hyphen_table()))
@@ -117,6 +132,22 @@ def test_plain_table_still_emitted() -> None:
assert "APTT" in tables[0]["content"]
+def test_nested_merged_table_uses_recursive_row_signature_and_full_context() -> None:
+ """验证 XML/HTML 递归行数对齐后不会进入缺少编号上下文的孤立回退。"""
+ file_bytes = _build_nested_merged_docx_table()
+ converter = DocxConverter()
+ preparsed = converter._preparse_tables_with_mammoth(file_bytes)
+
+ assert len(preparsed) == 1
+ assert preparsed[0] is not None
+ tables = _table_blocks(_convert_docx_bytes(file_bytes))
+ assert len(tables) == 1
+ assert "纵向合并" in tables[0]["content"]
+ assert "嵌套首行" in tables[0]["content"]
+ assert "嵌套编号行" in tables[0]["content"]
+ assert "外层尾行" in tables[0]["content"]
+
+
def test_xml_table_signature_renders_special_chars() -> None:
"""验证 XML 签名保留不间断连字符和软连字符。"""
doc = Document()
diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.py
index 9540f340..b760ecda 100644
--- a/tests/unittest/test_middle_json_block_models.py
+++ b/tests/unittest/test_middle_json_block_models.py
@@ -295,19 +295,21 @@ def test_formula_number_is_rejected_by_middle_json_boundary_and_schema() -> None
)
-def test_continuable_text_models_share_marker_and_reject_unknown_fields() -> None:
- """验证 Text/RefText 共用续接基类,同时继续执行严格字段校验。"""
+def test_continuable_text_models_share_marker_and_keep_text_anchor_strict() -> None:
+ """验证 Text 独有 anchor、Text/RefText 续接字段及未知字段校验。"""
text = parse_block({"type": "text", "content": _inline("x"), "continues_prev": True})
+ anchored_text = parse_block({"type": "text", "content": _inline("x"), "anchor": "a"})
ref_text = parse_block({"type": "ref_text", "content": _inline("r"), "continues_prev": True})
assert isinstance(text, ContinuableTextBlockBase)
assert isinstance(ref_text, RefTextBlock)
assert isinstance(ref_text, ContinuableTextBlockBase)
- assert set(TextBlock.model_fields) == set(RefTextBlock.model_fields)
+ assert set(TextBlock.model_fields) == {*RefTextBlock.model_fields, "anchor"}
assert text.continues_prev is True
+ assert isinstance(anchored_text, TextBlock) and anchored_text.anchor == "a"
assert ref_text.continues_prev is True
with pytest.raises(ValidationError):
- parse_block({"type": "text", "content": _inline("x"), "anchor": "a"})
+ parse_block({"type": "ref_text", "content": _inline("r"), "anchor": "a"})
with pytest.raises(ValidationError):
parse_block({"type": "text", "content": _inline("x"), "unknown": 1})
diff --git a/tests/unittest/test_text_block_anchor.py b/tests/unittest/test_text_block_anchor.py
new file mode 100644
index 00000000..d0776c7d
--- /dev/null
+++ b/tests/unittest/test_text_block_anchor.py
@@ -0,0 +1,199 @@
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from io import BytesIO
+from zipfile import ZipFile
+
+from bs4 import BeautifulSoup
+from lxml import etree
+from pydantic import ValidationError
+from pypdf import PdfReader
+import pytest
+
+from mineru.backend.analyze import doc_analyze
+from mineru.render import (
+ render_content_list,
+ render_content_list_v2,
+ render_docx,
+ render_epub,
+ render_html,
+ render_markdown,
+ render_pdf,
+ render_structured_content,
+)
+from mineru.render._internal.common.planner import build_render_plan
+from mineru.types import IndexBlock, MiddleJson, PageInfo, RefTextBlock, TextBlock
+
+
+def _inline(text: str) -> list[dict[str, str]]:
+ """构造最小结构化文本 span。"""
+ return [{"type": "text", "content": text}]
+
+
+def _middle_with_text_anchor() -> MiddleJson:
+ """构造目录前向引用顶层 TextBlock 的严格文档。"""
+ return MiddleJson(
+ pages=[
+ PageInfo(
+ page_idx=0,
+ blocks=[
+ IndexBlock(
+ type="index",
+ index=0,
+ content=[TextBlock(type="text", anchor="body target", content=_inline("Body target\t3"))],
+ )
+ ],
+ ),
+ PageInfo(
+ page_idx=1,
+ blocks=[TextBlock(type="text", index=0, anchor="body target", content=_inline("Body paragraph"))],
+ ),
+ ],
+ is_full_document=True,
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _zip_text(payload: bytes, name: str) -> str:
+ """读取 ZIP 容器中的 UTF-8 XML 文本。"""
+ with ZipFile(BytesIO(payload)) as archive:
+ return archive.read(name).decode("utf-8")
+
+
+def test_text_anchor_is_strict_and_blocks_continuation_merge() -> None:
+ """验证 TextBlock 接受 anchor,而带目标的续段不会被规划器吸收。"""
+ anchored = TextBlock(type="text", anchor="target", content=_inline("continued"), continues_prev=True)
+ middle = MiddleJson(
+ pages=[
+ PageInfo(page_idx=0, blocks=[TextBlock(type="text", index=0, content=_inline("first"))]),
+ PageInfo(page_idx=1, blocks=[anchored.model_copy(update={"index": 0})]),
+ ],
+ is_full_document=True,
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+ planned = build_render_plan(middle)
+ assert planned[1][0].removed is False
+ assert TextBlock.model_validate(anchored.model_dump()).anchor == "target"
+ with pytest.raises(ValidationError):
+ RefTextBlock.model_validate({"type": "ref_text", "anchor": "target", "content": _inline("ref")})
+
+
+def test_duplicate_and_empty_text_anchors_emit_only_the_first_visible_target() -> None:
+ """验证重复正文 anchor 仅首项生效,空正文不会产生悬空目标。"""
+ middle = MiddleJson(
+ pages=[
+ PageInfo(
+ page_idx=0,
+ blocks=[
+ TextBlock(type="text", index=0, anchor="same", content=_inline("First")),
+ TextBlock(type="text", index=1, anchor="same", content=_inline("Second")),
+ TextBlock(type="text", index=2, anchor="empty", content=[]),
+ ],
+ )
+ ],
+ is_full_document=True,
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+ assert render_markdown(middle).count('<a id="same"></a>') == 1
+ rendered_html = BeautifulSoup(render_html(middle), "html.parser")
+ assert len(rendered_html.select('[id="same"]')) == 1
+ assert rendered_html.select_one('[id="empty"]') is None
+
+
+def test_text_anchor_markdown_html_and_html_wire_roundtrip() -> None:
+ """验证 Markdown、HTML 目标与 canonical HTML v1 往返保持 TextBlock anchor。"""
+ middle = _middle_with_text_anchor()
+
+ markdown = render_markdown(middle)
+ assert "[Body target](#body%20target)" in markdown
+ assert '<a id="body target"></a>\nBody paragraph' in markdown
+
+ rendered_html = render_html(middle)
+ soup = BeautifulSoup(rendered_html, "html.parser")
+ target_wrapper = soup.select_one('.mineru-block[data-block-type="text"][data-anchor="body target"]')
+ assert target_wrapper is not None
+ assert target_wrapper.find("p")["id"] == "body-target"
+ assert soup.select_one('[data-block-type="index"] a')["href"] == "#body-target"
+
+ decoded, _ = doc_analyze(rendered_html.encode("utf-8"), effort="flash", parse_mode="auto", file_suffix="html")
+ decoded_target = next(
+ block
+ for page in decoded.pages
+ for block in page.blocks
+ if isinstance(block, TextBlock) and block.anchor == "body target"
+ )
+ decoded_index = next(block for page in decoded.pages for block in page.blocks if isinstance(block, IndexBlock))
+ assert decoded_target.anchor == "body target"
+ assert isinstance(decoded_index.content[0], TextBlock)
+ assert decoded_index.content[0].anchor == "body target"
+
+ missing = MiddleJson.model_validate(
+ {
+ **middle.model_dump(mode="python", exclude={"pages"}),
+ "pages": [
+ {
+ "page_idx": 0,
+ "blocks": [
+ {
+ "type": "index",
+ "index": 0,
+ "content": [{"type": "text", "anchor": "missing", "content": _inline("Missing\t1")}],
+ }
+ ],
+ }
+ ],
+ }
+ )
+ assert "#missing" not in render_markdown(missing)
+ assert BeautifulSoup(render_html(missing), "html.parser").select_one('[data-block-type="index"] a') is None
+
+
+def test_text_anchor_docx_pdf_and_epub_targets() -> None:
+ """验证 DOCX bookmark、PDF 内链和 EPUB XHTML 目标均指向 TextBlock。"""
+ middle = _middle_with_text_anchor()
+
+ document_xml = _zip_text(render_docx(middle), "word/document.xml")
+ assert 'w:bookmarkStart w:id="0" w:name="body_target"' in document_xml
+ assert 'w:hyperlink w:anchor="body_target"' in document_xml
+
+ pdf_reader = PdfReader(BytesIO(render_pdf(middle)))
+ annotations = [annotation.get_object() for page in pdf_reader.pages for annotation in (page.get("/Annots") or [])]
+ assert any("/Dest" in annotation for annotation in annotations)
+
+ epub = render_epub(middle, modified_at=datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc))
+ content = etree.fromstring(_zip_text(epub, "EPUB/text/content.xhtml").encode("utf-8"))
+ namespaces = {"xhtml": "http://www.w3.org/1999/xhtml"}
+ assert content.xpath("//xhtml:p[@id='body-target']/text()", namespaces=namespaces) == ["Body paragraph"]
+ navigation = etree.fromstring(_zip_text(epub, "EPUB/nav.xhtml").encode("utf-8"))
+ assert "text/content.xhtml#body-target" in navigation.xpath("//xhtml:a/@href", namespaces=namespaces)
+
+
+def test_text_anchor_structured_and_content_list_metadata() -> None:
+ """验证结构化输出只保留 anchor 元数据,不向正文内容注入目标标签。"""
+ middle = _middle_with_text_anchor()
+
+ structured = render_structured_content(middle)
+ structured_target = structured["pages"][1]["blocks"][0]
+ assert structured_target["anchor"] == "body target"
+ assert structured_target["content"] == "Body paragraph"
+ assert "<a " not in structured_target["content"]
+
+ content_list = render_content_list(middle)
+ target_v1 = next(item for item in content_list if item.get("text") == "Body paragraph")
+ assert target_v1["anchor"] == "body target"
+ assert content_list[0]["list_items"] == ["- [Body target](#body%20target)"]
+
+ content_list_v2 = render_content_list_v2(middle)
+ assert content_list_v2[1][0]["anchor"] == "body target"
+ assert content_list_v2[0][0]["content"]["list_items"][0]["anchor"] == "body target"