Skip to content

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

fix: enhance TOC anchor handling and visibility in DocxConverter

myhloli4adee72f5a3d
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index 081d47d9..cdbdb213 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -89,12 +89,16 @@ class MagicModel:
"lines": [line],
"index": index,
}
+ anchor = block_info.get("anchor")
+ if (
+ isinstance(anchor, str)
+ and anchor.strip()
+ and block_type in [BlockType.TITLE, BlockType.TEXT, BlockType.INTERLINE_EQUATION]
+ ):
+ block["anchor"] = anchor.strip()
if block_type == BlockType.TITLE:
block["is_numbered_style"] = block_info.get("is_numbered_style", False)
block["level"] = block_info.get("level", 1)
- anchor = block_info.get("anchor")
- if isinstance(anchor, str) and anchor.strip():
- block["anchor"] = anchor.strip()
blocks.append(block)
self.image_blocks = []
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index d760e164..0ed4e227 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -260,20 +260,45 @@ def _flatten_index_items(index_block):
# (unstyled) content BEFORE applying markdown markers.
#
# Find the last non-equation span that contains a tab; strip
- # everything after its last tab (the page-number separator).
+ # everything after its last tab ONLY when the trailing token
+ # actually looks like a page number.
# Then replace any remaining internal tabs with spaces so that
# "1.1\t研究对象" → "1.1 研究对象".
# ----------------------------------------------------------
+ def _looks_like_page_token(token: str) -> bool:
+ token = token.strip()
+ if not token:
+ return False
+ # Page tokens are usually short and contain no CJK characters.
+ if len(token) > 12:
+ return False
+ if re.search(r'[\u4e00-\u9fff]', token):
+ return False
+ # Arabic / Roman / single-letter page styles.
+ if re.fullmatch(r'\d+', token):
+ return True
+ if re.fullmatch(r'[ivxlcdm]+', token.lower()):
+ return True
+ if re.fullmatch(r'[a-zA-Z]', token):
+ return True
+ return False
+
last_tab_span_idx = -1
for i, (content, span_type, _) in enumerate(span_items):
if span_type != ContentType.INLINE_EQUATION and '\t' in content:
last_tab_span_idx = i
+ should_strip_page_tail = False
+ if last_tab_span_idx != -1:
+ last_tab_content = span_items[last_tab_span_idx][0]
+ tab_tail = last_tab_content.rsplit('\t', 1)[1]
+ should_strip_page_tail = _looks_like_page_token(tab_tail)
+
# Build stripped span_items
stripped_span_items = []
for i, (content, span_type, span_style) in enumerate(span_items):
if span_type != ContentType.INLINE_EQUATION:
- if i == last_tab_span_idx:
+ if i == last_tab_span_idx and should_strip_page_tail:
# Strip from last tab onwards (removes tab + page number)
content = content.rsplit('\t', 1)[0]
# Replace remaining internal tabs with spaces
@@ -369,6 +394,14 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
para_type = para_block['type']
if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:
para_text = merge_para_with_text(para_block)
+ if para_type == BlockType.TEXT:
+ bookmark_anchor = para_block.get("anchor")
+ if (
+ isinstance(bookmark_anchor, str)
+ and bookmark_anchor.strip()
+ and bookmark_anchor.strip().startswith("_Toc")
+ ):
+ para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{para_text}'
elif para_type == BlockType.LIST:
para_text = merge_list_to_markdown(para_block)
elif para_type == BlockType.INDEX:
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.py
index dcbc9e06..4367f002 100644
--- a/mineru/model/docx/docx_converter.py
+++ b/mineru/model/docx/docx_converter.py
@@ -83,6 +83,7 @@ class DocxConverter:
self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式
self.chart_list = [] # 图表列表
self.processed_textbox_elements: list = []
+ self.toc_anchor_set: set[str] = set() # TOC 超链接目标锚点集合
@staticmethod
def _escape_hyperlink_text(text: str) -> str:
@@ -178,6 +179,21 @@ class DocxConverter:
return False
return bool(format_obj.underline or format_obj.strikethrough)
+ @staticmethod
+ def _is_hidden_run(run: Run) -> bool:
+ """Check whether a run is marked as hidden text in Word."""
+ _W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ rpr = run._element.find(f"{{{_W}}}rPr")
+ if rpr is None:
+ return False
+ # webHidden: commonly used by TOC page-number field runs
+ if rpr.find(f"{{{_W}}}webHidden") is not None:
+ return True
+ # vanish: generic hidden text
+ if rpr.find(f"{{{_W}}}vanish") is not None:
+ return True
+ return False
+
@classmethod
def _format_text_with_hyperlink(
cls,
@@ -438,6 +454,7 @@ class DocxConverter:
self.heading_list_numids = set()
self.chart_list = []
self.processed_textbox_elements = []
+ self.toc_anchor_set = set()
# 读取文件字节,以便 mammoth 和 python-docx 各自使用独立读取流
file_bytes = file_stream.read()
@@ -447,6 +464,7 @@ class DocxConverter:
self._mammoth_tables_html = self._preparse_tables_with_mammoth(file_bytes)
self._mammoth_table_idx = 0
self.docx_obj = Document(BytesIO(file_bytes))
+ self.toc_anchor_set = self._collect_toc_anchor_set()
# 预扫描文档,识别用作章节标题的列表numId
self.heading_list_numids = self._detect_heading_list_numids()
self.pages.append(self.cur_page)
@@ -454,6 +472,20 @@ class DocxConverter:
self._add_header_footer(self.docx_obj)
self._add_chart_table()
+ def _collect_toc_anchor_set(self) -> set[str]:
+ """Collect TOC hyperlink anchors from the entire document body."""
+ 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)
+ return anchors
+
def _walk_linear(
self,
body: BaseOxmlElement,
@@ -1033,6 +1065,8 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if paragraph_anchor:
+ text_with_inline_eq_block["anchor"] = paragraph_anchor
self.cur_page.append(text_with_inline_eq_block)
elif p_style_id in [
"Paragraph",
@@ -1053,6 +1087,8 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if paragraph_anchor:
+ text_block["anchor"] = paragraph_anchor
self.cur_page.append(text_block)
# 判断是否是 Caption
elif self._is_caption(element):
@@ -1078,6 +1114,8 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if paragraph_anchor:
+ text_block["anchor"] = paragraph_anchor
self.cur_page.append(text_block)
if is_section_end:
@@ -1214,6 +1252,9 @@ class DocxConverter:
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._get_format_from_run(h_run)
# 保留非空文本(含制表符)以及带可见样式的空白 run
@@ -2126,9 +2167,13 @@ class DocxConverter:
names.append(name)
if not names:
return None
- for name in names:
- if name.startswith("_Toc"):
- return name
+ toc_names = [name for name in names if name.startswith("_Toc")]
+ if toc_names:
+ # Prefer anchors that are actually referenced by TOC hyperlinks.
+ for name in toc_names:
+ if name in self.toc_anchor_set:
+ return name
+ return toc_names[0]
return names[0]
def _extract_toc_target_anchor(self, paragraph_element: BaseOxmlElement) -> Optional[str]:
@@ -2175,6 +2220,8 @@ class DocxConverter:
element=p, text=p_obj.text
)
target_anchor = self._extract_toc_target_anchor(p)
+ if target_anchor and target_anchor.startswith("_Toc"):
+ self.toc_anchor_set.add(target_anchor)
if text is None:
continue
text = text.strip()