Skip to content

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

fix: add anchor extraction for TOC and index items in DocxConverter and MagicModel

myhloli424d8e47fc06
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index 06bbed35..3fc87d47 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -6,22 +6,9 @@ from collections import defaultdict
from loguru import logger
from mineru.backend.office.office_magic_model import MagicModel
-from mineru.utils.enum_class import BlockType, ContentType
+from mineru.utils.enum_class import BlockType
from mineru.utils.hash_utils import str_sha256
from mineru.version import __version__
-from mineru.utils.config_reader import get_latex_delimiter_config
-
-
-latex_delimiters_config = get_latex_delimiter_config()
-
-default_delimiters = {
- 'display': {'left': '$$', 'right': '$$'},
- 'inline': {'left': '$', 'right': '$'}
-}
-
-delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
-inline_left_delimiter = delimiters['inline']['left']
-inline_right_delimiter = delimiters['inline']['right']
def _save_base64_image(b64_data_uri: str, image_writer, page_index: int):
@@ -142,543 +129,45 @@ def _extract_section_parts_from_content(content: str, level: int):
return None
-_FULLWIDTH_TO_HALFWIDTH = str.maketrans(
- ':;,。()!?【】{}\u201c\u201d\u2018\u2019/\&@#$%^*+=|~<>',
- ':;,.()!?[]{}""\'\'/\\@&#$%^*+=|~<>',
-)
-
-
-def _normalize_for_match(text: str) -> str:
- """Aggressively normalize text for TOC-to-body matching.
-
- * fullwidth punctuation → halfwidth
- * unicode minus / en-dash / em-dash → ASCII hyphen
- * strip ALL whitespace
- * lowercase
- """
- text = text.translate(_FULLWIDTH_TO_HALFWIDTH)
- text = text.replace('\u2212', '-') # − MINUS SIGN
- text = text.replace('\u2013', '-') # – EN DASH
- text = text.replace('\u2014', '-') # — EM DASH
- text = re.sub(r'\s+', '', text)
- return text.lower()
-
-
-def _strip_section_number(text: str) -> str:
- """Strip a leading section number like '1.', '1.2', '1.2.3.' from *raw* text."""
- return re.sub(r'^\d+(\.\d+)*\.?\s*', '', text.strip())
-
+def _collect_index_text_blocks(index_block: dict, result: list[dict]) -> None:
+ """Depth-first collect TOC leaf text blocks."""
+ for child in index_block.get("blocks", []):
+ if child.get("type") == BlockType.INDEX:
+ _collect_index_text_blocks(child, result)
+ elif child.get("type") == BlockType.TEXT:
+ result.append(child)
-def _strip_fig_tab_number(text: str) -> str:
- """Strip a leading figure/table number like '图1.3.1' or '表2.1' from *raw* text.
-
- These prefixes start with the Chinese character 图 or 表 followed by a
- dotted number. Stripping them allows matching even when the TOC and body
- use different numbering (common in informally formatted documents).
- """
- return re.sub(r'^[图表]\s*\d+(?:[.\-]\d+)*\s*', '', text.strip())
-
-
-def _extract_section_number_key(text: str) -> str:
- """Extract the leading section number from raw text.
-
- Examples: '2. 标题' → '2', '2.2.formula' → '2.2', '1.2.3 Title' → '1.2.3'
- Returns empty string when no leading numeric section is found.
- """
- m = re.match(r'^(\d+(?:\.\d+)*)\.?\s*', text.strip())
- if m and m.group(1):
- return m.group(1)
- return ''
+def _link_index_entries_by_anchor(middle_json: dict) -> None:
+ """Keep TOC anchors only when they exist on parsed body blocks."""
+ pdf_info = middle_json.get("pdf_info", [])
+ valid_anchors: set[str] = set()
-def _has_equation_spans(block: dict) -> bool:
- """Return True if *any* span inside a block is an inline equation."""
- for line in block.get('lines', []):
- for span in line.get('spans', []):
- if span.get('type') == ContentType.INLINE_EQUATION:
- return True
- return False
-
-
-def _build_toc_text_from_block(block: dict) -> str:
- """Build a display text string from a block, wrapping inline equations
- with ``$...$`` delimiters.
+ for page_info in pdf_info:
+ for block in page_info.get("para_blocks", []):
+ anchor = block.get("anchor")
+ if isinstance(anchor, str) and anchor.strip():
+ valid_anchors.add(anchor.strip())
- Used to replace Word-simplified TOC entry text (which often omits text
- that appears before an inline equation) with the full heading text.
- """
- parts = []
- for line in block.get('lines', []):
- for span in line.get('spans', []):
- c = span.get('content', '')
- if not c:
- continue
- if span.get('type') == ContentType.INLINE_EQUATION:
- parts.append(f'{inline_left_delimiter}{c}{inline_right_delimiter}')
- else:
- parts.append(c)
- return ''.join(parts).strip()
-
-
-def _get_block_text(block: dict) -> str:
- """Concatenate all span content from a block's lines."""
- parts = []
- for line in block.get('lines', []):
- for span in line.get('spans', []):
- c = span.get('content', '')
- if c:
- parts.append(c)
- return ''.join(parts).strip()
-
-
-def _collect_toc_span_entries(index_block: dict, result: list) -> None:
- """Depth-first collect (span, owner text-block) pairs from index tree."""
- for child in index_block.get('blocks', []):
- if child.get('type') == BlockType.INDEX:
- _collect_toc_span_entries(child, result)
- elif child.get('type') == BlockType.TEXT:
- for line in child.get('lines', []):
- for span in line.get('spans', []):
- if span.get('content', '').strip():
- result.append({
- "span": span,
- "text_block": child,
- })
-
-
-def _build_index_spans_from_title_block(
- title_block: dict,
- section_prefix: str = "",
- default_style: list | None = None,
-) -> list[dict]:
- """Build TOC spans from a matched title block while preserving equations.
-
- Hyperlink spans inside body titles are converted to plain TEXT spans in the
- TOC so the whole TOC item can use a single internal anchor target.
- """
- rebuilt_spans: list[dict] = []
- for line in title_block.get('lines', []):
- for span in line.get('spans', []):
- content = span.get('content', '')
- if not content:
- continue
+ if not valid_anchors:
+ return
- span_type = span.get('type')
- if span_type == ContentType.HYPERLINK:
- span_type = ContentType.TEXT
-
- new_span = {
- "type": span_type,
- "content": content,
- }
- if span_type != ContentType.INLINE_EQUATION:
- style = span.get('style') or default_style
- if style:
- new_span["style"] = list(style)
- rebuilt_spans.append(new_span)
-
- if not rebuilt_spans:
- return []
-
- if section_prefix:
- for span in rebuilt_spans:
- if span.get('type') != ContentType.INLINE_EQUATION:
- span['content'] = section_prefix + span.get('content', '')
- break
- else:
- prefix_span = {
- "type": ContentType.TEXT,
- "content": section_prefix,
- }
- if default_style:
- prefix_span["style"] = list(default_style)
- rebuilt_spans.insert(0, prefix_span)
-
- # Merge adjacent TEXT spans with identical styles for cleaner output.
- merged_spans: list[dict] = []
- for span in rebuilt_spans:
- if (
- merged_spans
- and span.get('type') == ContentType.TEXT
- and merged_spans[-1].get('type') == ContentType.TEXT
- and tuple(span.get('style', [])) == tuple(merged_spans[-1].get('style', []))
- ):
- merged_spans[-1]['content'] = (
- merged_spans[-1].get('content', '') + span.get('content', '')
- )
- else:
- merged_spans.append(span)
-
- return merged_spans
-
-
-def _link_index_spans_to_body_blocks(middle_json: dict) -> None:
- """Annotate index entries with matched body heading anchors.
-
- Uses sequential order-based matching so that duplicate titles (e.g.
- multiple "本章小结") are correctly assigned to successive body blocks
- in document order. Matches against title blocks only.
- """
- pdf_info = middle_json.get('pdf_info', [])
-
- # ------------------------------------------------------------------
- # 1. Collect body targets in document order
- # Each entry: (page_idx, block_idx, raw_text)
- # Only title blocks are matched.
- # ------------------------------------------------------------------
- body_targets: list[tuple[int, int, str]] = []
for page_info in pdf_info:
- page_idx = page_info.get('page_idx', 0)
- for block in page_info.get('para_blocks', []):
- block_idx = block.get('index')
- if block_idx is None:
- continue
- btype = block.get('type')
- if btype == BlockType.TITLE:
- text = _get_block_text(block)
- if text:
- body_targets.append((page_idx, block_idx, text))
-
- # ------------------------------------------------------------------
- # 2. Build lookup: normalized_text -> ordered list of indices into body_targets
- # ------------------------------------------------------------------
- norm_to_indices: dict[str, list[int]] = defaultdict(list)
- for i, (_pid, _bidx, raw) in enumerate(body_targets):
- seen_keys: set[str] = set()
- for key in (
- _normalize_for_match(raw),
- _normalize_for_match(_strip_section_number(raw)),
- _normalize_for_match(_strip_fig_tab_number(raw)),
- ):
- if key and key not in seen_keys:
- norm_to_indices[key].append(i)
- seen_keys.add(key)
-
- # ------------------------------------------------------------------
- # 3. Collect TOC spans in document order
- # ------------------------------------------------------------------
- toc_span_entries: list[dict] = []
- for page_info in pdf_info:
- for block in page_info.get('para_blocks', []):
- if block.get('type') == BlockType.INDEX:
- _collect_toc_span_entries(block, toc_span_entries)
-
- # ------------------------------------------------------------------
- # 4. Pass 1 — exact-normalized sequential matching.
- # A counter per key ensures the n-th TOC entry for "X" maps to the
- # n-th body block with the same normalized text (handles duplicates
- # like multiple "本章小结" chapters).
- # ------------------------------------------------------------------
- used_counts: dict[str, int] = defaultdict(int)
- consumed_targets: set[int] = set()
-
- for entry in toc_span_entries:
- span = entry['span']
- text_block = entry['text_block']
- if text_block.get('target_anchor') is not None:
- continue
- content = span.get('content', '')
- if '\t' in content:
- # The last tab separates the page number; strip it.
- # Internal tabs separate section number from title (e.g. "1.1\t研究对象\t5"
- # -> "1.1\t研究对象"). _normalize_for_match removes \t via \s+, and
- # _strip_section_number's \s* already consumes the tab after the number.
- toc_text = content.rsplit('\t', 1)[0].strip()
- else:
- toc_text = content.strip()
-
- if not toc_text:
- continue
-
- for normalized in (
- _normalize_for_match(toc_text),
- _normalize_for_match(_strip_section_number(toc_text)),
- _normalize_for_match(_strip_fig_tab_number(toc_text)),
- ):
- if not normalized or normalized not in norm_to_indices:
- continue
- indices = norm_to_indices[normalized]
- count = used_counts[normalized]
- # Skip indices already consumed by another normalization key
- while count < len(indices) and indices[count] in consumed_targets:
- count += 1
- if count < len(indices):
- target_idx = indices[count]
- pid, bidx, _ = body_targets[target_idx]
- text_block['target_anchor'] = [pid, bidx]
- consumed_targets.add(target_idx)
- used_counts[normalized] = count + 1
- break
-
- # ------------------------------------------------------------------
- # 5. Pass 2 — prefix / coverage-based fuzzy matching for unresolved spans.
- # One of the two texts must be a prefix of the other (handles truncated
- # captions), AND the coverage ratio min/max >= 0.5 (prevents matching
- # a short TOC entry against a long body paragraph).
- # ------------------------------------------------------------------
- _MIN_COVERAGE = 0.5
- remaining = sorted(set(range(len(body_targets))) - consumed_targets)
-
- for entry in toc_span_entries:
- span = entry['span']
- text_block = entry['text_block']
- if text_block.get('target_anchor') is not None:
- continue
- content = span.get('content', '')
- toc_text = content.rsplit('\t', 1)[0].strip() if '\t' in content else content.strip()
- if not toc_text:
- continue
-
- for toc_norm in (
- _normalize_for_match(toc_text),
- _normalize_for_match(_strip_section_number(toc_text)),
- _normalize_for_match(_strip_fig_tab_number(toc_text)),
- ):
- if not toc_norm or len(toc_norm) < 5:
- continue
- for j, body_idx in enumerate(remaining):
- body_norm = _normalize_for_match(body_targets[body_idx][2])
- if not body_norm:
- continue
- len_t, len_b = len(toc_norm), len(body_norm)
- coverage = min(len_t, len_b) / max(len_t, len_b)
- if coverage < _MIN_COVERAGE:
- continue
- if body_norm.startswith(toc_norm) or toc_norm.startswith(body_norm):
- pid, bidx, _ = body_targets[body_idx]
- text_block['target_anchor'] = [pid, bidx]
- consumed_targets.add(body_idx)
- remaining.pop(j)
- break
- if text_block.get('target_anchor') is not None:
- break
-
- # ------------------------------------------------------------------
- # 6. Pass 3 — equation-stripped, TEXT-block-level matching.
- #
- # When Word auto-generates a TOC for headings with inline equations
- # it stores a simplified representation of the formula and splits
- # the entry into multiple spans within one TEXT block:
- #
- # span 1 (TEXT): "2.\t标题内包含公式 " ← section# + title text
- # span 2 (INLINE_EQ): "x=-b\pm b2-4ac2a" ← simplified formula
- # span 3 (TEXT): "\tIII" ← page number
- #
- # Because Pass 1/2 match individual spans (and the tab in span 1
- # causes "标题内包含公式" to be misidentified as the page-number
- # side), none of the spans match the corresponding body heading
- # "标题内包含公式 $x=\frac{...}{2a}$".
- #
- # Strategy:
- # • Build block_lookup and a text-only body-heading index that
- # concatenates only non-equation (TEXT/HYPERLINK) span content.
- # • Collect TOC entries as complete TEXT blocks (one block = one
- # original TOC paragraph).
- # • For each unmatched TEXT block that has INLINE_EQUATION spans,
- # compute its text-only content, strip the trailing page-number
- # tab, and strip the leading section number.
- # • Match against text-only body headings using exact or
- # prefix/coverage matching (same thresholds as Pass 2).
- # • After matching, update the first span to show the full heading
- # text (with $...$ equations) and clear the other spans to avoid
- # duplicate content in the rendered TOC.
- # ------------------------------------------------------------------
-
- # Build (page_idx, block_idx) → block lookup for full span access.
- block_lookup: dict[tuple, dict] = {}
- for page_info in pdf_info:
- p_idx = page_info.get('page_idx', 0)
- for blk in page_info.get('para_blocks', []):
- b_idx = blk.get('index')
- if b_idx is not None:
- block_lookup[(p_idx, b_idx)] = blk
-
- def _text_only_from_block(blk: dict) -> str:
- """Join only non-equation span contents from a block."""
- return ''.join(
- span.get('content', '')
- for line in blk.get('lines', [])
- for span in line.get('spans', [])
- if span.get('type') != ContentType.INLINE_EQUATION
- ).strip()
-
- # Build text-only body heading index: normalized → list of target indices.
- text_only_to_indices: dict[str, list[int]] = defaultdict(list)
- for i, (pid, bidx, _raw) in enumerate(body_targets):
- blk = block_lookup.get((pid, bidx))
- if not blk:
- continue
- text_only = _text_only_from_block(blk)
- if not text_only:
- continue
- seen: set[str] = set()
- for key in (
- _normalize_for_match(text_only),
- _normalize_for_match(_strip_section_number(text_only)),
- ):
- if key and key not in seen:
- text_only_to_indices[key].append(i)
- seen.add(key)
-
- # Collect TOC TEXT blocks (one per original TOC paragraph / entry).
- def _collect_toc_text_blocks(idx_blk: dict, result: list) -> None:
- for child in idx_blk.get('blocks', []):
- if child.get('type') == BlockType.INDEX:
- _collect_toc_text_blocks(child, result)
- elif child.get('type') == BlockType.TEXT:
- result.append(child)
-
- toc_text_blocks: list[dict] = []
- for page_info in pdf_info:
- for blk in page_info.get('para_blocks', []):
- if blk.get('type') == BlockType.INDEX:
- _collect_toc_text_blocks(blk, toc_text_blocks)
-
- _MIN_COVERAGE_P3 = 0.5
- text_only_used_counts: dict[str, int] = defaultdict(int)
- remaining_p3 = sorted(set(range(len(body_targets))) - consumed_targets)
-
- for text_block in toc_text_blocks:
- all_spans = [
- span
- for line in text_block.get('lines', [])
- for span in line.get('spans', [])
- ]
-
- # Skip if already matched.
- if text_block.get('target_anchor') is not None:
- continue
-
- # Only process entries that contain an inline-equation span
- # (Word simplified a formula heading into this TOC entry).
- has_eq = any(s.get('type') == ContentType.INLINE_EQUATION for s in all_spans)
- if not has_eq:
- continue
-
- # Compute text-only content: skip INLINE_EQUATION spans.
- text_only_parts = [
- s.get('content', '')
- for s in all_spans
- if s.get('content', '') and s.get('type') != ContentType.INLINE_EQUATION
- ]
- raw_text_only = ''.join(text_only_parts)
- # Strip trailing tab + page number, then replace internal tabs with spaces.
- if '\t' in raw_text_only:
- raw_text_only = raw_text_only.rsplit('\t', 1)[0]
- raw_text_only = raw_text_only.replace('\t', ' ').strip()
-
- if not raw_text_only:
- continue
-
- matched = False
-
- # --- Pass 3a: exact-normalized lookup ---
- for norm_key in (
- _normalize_for_match(raw_text_only),
- _normalize_for_match(_strip_section_number(raw_text_only)),
- ):
- if not norm_key or norm_key not in text_only_to_indices:
- continue
- indices = text_only_to_indices[norm_key]
- count = text_only_used_counts[norm_key]
- while count < len(indices) and indices[count] in consumed_targets:
- count += 1
- if count < len(indices):
- target_idx = indices[count]
- t_pid, t_bidx, _ = body_targets[target_idx]
- _apply_match(text_block, all_spans, t_pid, t_bidx, block_lookup)
- consumed_targets.add(target_idx)
- if target_idx in remaining_p3:
- remaining_p3.remove(target_idx)
- text_only_used_counts[norm_key] = count + 1
- matched = True
- break
-
- if matched:
- continue
-
- # --- Pass 3b: prefix/coverage fuzzy lookup against text-only bodies ---
- toc_norm = _normalize_for_match(raw_text_only)
- toc_norm_stripped = _normalize_for_match(_strip_section_number(raw_text_only))
- for toc_n in (toc_norm, toc_norm_stripped):
- if not toc_n or len(toc_n) < 5:
+ for block in page_info.get("para_blocks", []):
+ if block.get("type") != BlockType.INDEX:
continue
- for j, body_idx in enumerate(remaining_p3):
- blk = block_lookup.get(
- (body_targets[body_idx][0], body_targets[body_idx][1])
- )
- if not blk:
+ toc_text_blocks: list[dict] = []
+ _collect_index_text_blocks(block, toc_text_blocks)
+ for text_block in toc_text_blocks:
+ anchor = text_block.get("anchor")
+ if not isinstance(anchor, str):
+ text_block.pop("anchor", None)
continue
- body_text_only = _text_only_from_block(blk)
- if not body_text_only:
+ anchor = anchor.strip()
+ if not anchor or anchor not in valid_anchors:
+ text_block.pop("anchor", None)
continue
- body_n = _normalize_for_match(body_text_only)
- if not body_n:
- continue
- len_t, len_b = len(toc_n), len(body_n)
- cov = min(len_t, len_b) / max(len_t, len_b)
- if cov < _MIN_COVERAGE_P3:
- continue
- if body_n.startswith(toc_n) or toc_n.startswith(body_n):
- t_pid, t_bidx, _ = body_targets[body_idx]
- _apply_match(
- text_block, all_spans, t_pid, t_bidx, block_lookup
- )
- consumed_targets.add(body_idx)
- remaining_p3.pop(j)
- matched = True
- break
- if matched:
- break
-
-def _apply_match(
- text_block: dict,
- all_spans: list,
- t_pid: int,
- t_bidx: int,
- block_lookup: dict,
-) -> None:
- """Set target_anchor on the block and restore full heading spans.
-
- Used by Pass 3 after an equation-stripped match has been found.
- Rebuilds the TOC entry from the matched title block spans so inline
- equations remain separate spans in middle-json output.
- """
- if not all_spans:
- return
-
- text_block['target_anchor'] = [t_pid, t_bidx]
-
- # Extract the section-number prefix from the first span, if present.
- # e.g. "2.\t标题内包含公式 " → left side before \t is "2." → prefix "2. "
- section_prefix = ''
- default_style = None
- for s in all_spans:
- if s.get('type') != ContentType.INLINE_EQUATION and default_style is None:
- if s.get('style'):
- default_style = list(s.get('style', []))
-
- if s.get('type') == ContentType.INLINE_EQUATION:
- continue
- orig = s.get('content', '')
- if '\t' in orig:
- left = orig.rsplit('\t', 1)[0].rstrip()
- # The left part is a pure section number (digits + dots) when the
- # title text is on the right-hand side of the tab.
- if re.match(r'^\d+(?:\.\d+)*\.?$', left):
- section_prefix = left.rstrip('.') + '. '
- break
-
- # Rebuild the TOC spans from the matched body heading.
- body_blk = block_lookup.get((t_pid, t_bidx))
- if body_blk:
- rebuilt_spans = _build_index_spans_from_title_block(
- body_blk,
- section_prefix=section_prefix,
- default_style=default_style,
- )
- if rebuilt_spans:
- text_block['lines'] = [{"spans": rebuilt_spans}]
+ text_block["anchor"] = anchor
def result_to_middle_json(model_output_blocks_list, image_writer):
@@ -725,5 +214,5 @@ def result_to_middle_json(model_output_blocks_list, image_writer):
if deeper > level:
section_counters[deeper] = 0
- _link_index_spans_to_body_blocks(middle_json)
+ _link_index_entries_by_anchor(middle_json)
return middle_json
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index df7e6c92..081d47d9 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -92,6 +92,9 @@ class MagicModel:
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 = []
@@ -405,6 +408,9 @@ def parse_index_block(index_block: dict):
"type": BlockType.TEXT,
"lines": [{"spans": spans}]
}
+ anchor = item.get("anchor")
+ if isinstance(anchor, str) and anchor.strip():
+ text_block["anchor"] = anchor.strip()
blocks.append(text_block)
elif item_type == "index":
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index cd768ab7..d760e164 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -195,12 +195,16 @@ def _flatten_list_items_v2(list_block):
ordered_counter += 1
else:
prefix = f"{' ' * ilevel}-"
- items.append({
+ item = {
'item_type': 'text',
'ilevel': ilevel,
'prefix': prefix,
'item_content': item_content,
- })
+ }
+ anchor = block.get("anchor")
+ if isinstance(anchor, str) and anchor.strip():
+ item["anchor"] = anchor.strip()
+ items.append(item)
return items
@@ -235,12 +239,11 @@ def _flatten_index_items(index_block):
items.extend(_flatten_index_items(child))
elif child.get('type') == BlockType.TEXT:
span_items = [] # list of (content, span_type, span_style)
- target_anchor = child.get('target_anchor')
- if isinstance(target_anchor, list) and len(target_anchor) == 2:
- pid, bidx = target_anchor
- target_anchor = f"block-p{pid}-b{bidx}"
+ anchor = child.get('anchor')
+ if not isinstance(anchor, str) or not anchor.strip():
+ anchor = None
else:
- target_anchor = None
+ anchor = anchor.strip()
for line in child.get('lines', []):
for span in line.get('spans', []):
@@ -346,8 +349,8 @@ def _flatten_index_items(index_block):
if not item_text:
continue
- if target_anchor is not None:
- item_text = f"[{item_text}](#{target_anchor})"
+ if anchor is not None:
+ item_text = f"[{item_text}](#{anchor})"
items.append(f"{indent}- {item_text}")
@@ -373,10 +376,9 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=No
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
title_text = merge_para_with_text(para_block)
- block_idx = para_block.get('index')
- if page_idx is not None and block_idx is not None:
- anchor = f'<a id="block-p{page_idx}-b{block_idx}"></a>'
- para_text = f'{anchor}\n{"#" * title_level} {title_text}'
+ bookmark_anchor = para_block.get("anchor")
+ if isinstance(bookmark_anchor, str) and bookmark_anchor.strip():
+ para_text = f'<a id="{bookmark_anchor.strip()}"></a>\n{"#" * title_level} {title_text}'
else:
para_text = f'{"#" * title_level} {title_text}'
elif para_type == BlockType.IMAGE:
@@ -476,6 +478,9 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx):
para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
para_content['page_idx'] = page_idx
+ anchor = para_block.get("anchor")
+ if isinstance(anchor, str) and anchor.strip():
+ para_content["anchor"] = anchor.strip()
return para_content
@@ -598,6 +603,10 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):
}
}
+ anchor = para_block.get("anchor")
+ if isinstance(anchor, str) and anchor.strip():
+ para_content["anchor"] = anchor.strip()
+
return para_content
diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.py
index fb0a995e..dcbc9e06 100644
--- a/mineru/model/docx/docx_converter.py
+++ b/mineru/model/docx/docx_converter.py
@@ -905,6 +905,7 @@ class DocxConverter:
is_section_end = True
paragraph = Paragraph(element, self.docx_obj)
paragraph_elements = self._get_paragraph_elements(paragraph)
+ paragraph_anchor = self._extract_paragraph_bookmark(element)
text, equations = self._handle_equations_in_text(
element=element, text=paragraph.text
)
@@ -949,6 +950,8 @@ class DocxConverter:
"is_numbered_style": is_numbered,
"content": content_text,
}
+ if paragraph_anchor:
+ title_block["anchor"] = paragraph_anchor
self.cur_page.append(title_block)
else:
self._add_list_item(
@@ -984,6 +987,8 @@ class DocxConverter:
"is_numbered_style": False,
"content": content_text,
}
+ if paragraph_anchor:
+ title_block["anchor"] = paragraph_anchor
self.cur_page.append(title_block)
elif "Heading" in p_style_id:
@@ -1005,6 +1010,8 @@ class DocxConverter:
"is_numbered_style": is_numbered_style,
"content": content_text,
}
+ if paragraph_anchor:
+ h_block["anchor"] = paragraph_anchor
self.cur_page.append(h_block)
elif len(equations) > 0:
@@ -1952,7 +1959,7 @@ class DocxConverter:
return None
def _is_flat_list_toc(
- self, items: list[tuple[int, str, list, list]]
+ self, items: list[tuple[int, str, list, list, Optional[str]]]
) -> bool:
"""
检测目录是否为扁平列表(插图清单、列表清单等),
@@ -1962,7 +1969,7 @@ class DocxConverter:
"""
match_count = 0
total_count = 0
- for _level, text, _elements, _equations in items:
+ for _level, text, _elements, _equations, _anchor in items:
stripped = text.strip()
if not stripped:
continue
@@ -2002,6 +2009,7 @@ class DocxConverter:
elements: list,
text: str = "",
equations: list = None,
+ anchor: Optional[str] = None,
) -> None:
"""
添加目录项到索引块。
@@ -2045,6 +2053,8 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if anchor:
+ index_item["anchor"] = anchor
index_block["content"].append(index_item)
self.pre_index_ilevel = ilevel
@@ -2063,6 +2073,8 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if anchor:
+ index_item["anchor"] = anchor
child_index_block["content"].append(index_item)
self.pre_index_ilevel = ilevel
@@ -2079,6 +2091,8 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if anchor:
+ index_item["anchor"] = anchor
index_block["content"].append(index_item)
self.pre_index_ilevel = ilevel
@@ -2090,8 +2104,52 @@ class DocxConverter:
"type": BlockType.TEXT,
"content": content_text,
}
+ if anchor:
+ index_item["anchor"] = anchor
index_block["content"].append(index_item)
+ def _extract_paragraph_bookmark(self, paragraph_element: BaseOxmlElement) -> Optional[str]:
+ """Extract a bookmark name from a paragraph, prioritizing TOC bookmarks."""
+ bookmark_name_attr = (
+ "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}name"
+ )
+ names = []
+ for bm in paragraph_element.findall(
+ ".//w:bookmarkStart", namespaces=DocxConverter._BLIP_NAMESPACES
+ ):
+ name = bm.get(bookmark_name_attr, "").strip()
+ if not name:
+ continue
+ # skip Word navigation artifacts
+ if name.startswith("_GoBack"):
+ continue
+ names.append(name)
+ if not names:
+ return None
+ for name in names:
+ if name.startswith("_Toc"):
+ return name
+ return names[0]
+
+ def _extract_toc_target_anchor(self, paragraph_element: BaseOxmlElement) -> Optional[str]:
+ """Extract internal bookmark target from a TOC paragraph hyperlink."""
+ 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]
+
def _handle_sdt_as_index(self, sdt_content: BaseOxmlElement) -> None:
"""
处理目录SDT内容,将其转换为层级化的INDEX块。
@@ -2108,7 +2166,7 @@ class DocxConverter:
)
# --- 第一阶段:收集所有条目 ---
- toc_items: list[tuple[int, str, list, list]] = []
+ toc_items: list[tuple[int, str, list, list, Optional[str]]] = []
for p in paragraphs:
try:
p_obj = Paragraph(p, self.docx_obj)
@@ -2116,6 +2174,7 @@ class DocxConverter:
text, equations = self._handle_equations_in_text(
element=p, text=p_obj.text
)
+ target_anchor = self._extract_toc_target_anchor(p)
if text is None:
continue
text = text.strip()
@@ -2126,7 +2185,9 @@ class DocxConverter:
if toc_level is None:
toc_level = 0
- toc_items.append((toc_level, text, paragraph_elements, equations))
+ toc_items.append(
+ (toc_level, text, paragraph_elements, equations, target_anchor)
+ )
except Exception as e:
logger.debug(f"Error collecting TOC paragraph: {e}")
continue
@@ -2138,7 +2199,7 @@ class DocxConverter:
self.index_block_stack = []
self.pre_index_ilevel = -1
- for toc_level, text, elements, equations in toc_items:
+ for toc_level, text, elements, equations, target_anchor in toc_items:
if is_flat:
# 插图/列表清单:强制全部扁平(层级 0)
corrected_level = 0
@@ -2151,6 +2212,7 @@ class DocxConverter:
elements=elements,
text=text,
equations=equations,
+ anchor=target_anchor,
)
# 处理完成后重置索引状态