Skip to content

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

fix: 增加索引块的 Markdown 转换支持,并优化标题锚点生成

myhlolic698f1e92f3a
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index b7995173..db4151ca 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -87,6 +87,197 @@ 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 _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 _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_spans(index_block: dict, result: list) -> None:
+ """Depth-first collect all leaf text spans from an index block tree."""
+ for child in index_block.get('blocks', []):
+ if child.get('type') == BlockType.INDEX:
+ _collect_toc_spans(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)
+
+
+def _link_index_spans_to_body_blocks(middle_json: dict) -> None:
+ """Annotate each leaf span inside index blocks with target_page_idx / target_block_idx.
+
+ 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_spans: list[dict] = []
+ for page_info in pdf_info:
+ for block in page_info.get('para_blocks', []):
+ if block.get('type') == BlockType.INDEX:
+ _collect_toc_spans(block, toc_spans)
+
+ # ------------------------------------------------------------------
+ # 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 span in toc_spans:
+ content = span.get('content', '')
+ if '\t' in content:
+ toc_text = content.split('\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]
+ span['target_anchor'] = f"block-p{pid}-b{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 span in toc_spans:
+ if 'target_anchor' in span:
+ continue
+ content = span.get('content', '')
+ toc_text = content.split('\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]
+ span['target_anchor'] = [pid, bidx]
+ remaining.pop(j)
+ break
+ if 'target_anchor' in span:
+ break
+
+
def result_to_middle_json(model_output_blocks_list, image_writer):
middle_json = {"pdf_info": [], "_backend":"office", "_version_name": __version__}
for index, page_blocks in enumerate(model_output_blocks_list):
@@ -131,4 +322,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)
return middle_json
\ No newline at end of file
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index 8f2e23ab..8d42cbb0 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -125,18 +125,73 @@ def merge_list_to_markdown(list_block):
return '\n'.join(_flatten_list_items(list_block)) + '\n'
-def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path=''):
+def _flatten_index_items(index_block):
+ """Recursively flatten index (TOC) blocks into markdown list items.
+
+ Strips the trailing tab+page-number from span content and, when target
+ location fields are present on a span, wraps the text in a markdown
+ hyperlink pointing to the body-block anchor.
+ """
+ items = []
+ ilevel = index_block.get('ilevel', 0)
+ indent = ' ' * ilevel
+
+ for child in index_block.get('blocks', []):
+ if child.get('type') == BlockType.INDEX:
+ items.extend(_flatten_index_items(child))
+ elif child.get('type') == BlockType.TEXT:
+ text_parts = []
+ target_anchor = None
+ for line in child.get('lines', []):
+ for span in line.get('spans', []):
+ content = span.get('content', '')
+ # Strip trailing tab + page number (e.g. "引言\t1" -> "引言")
+ if '\t' in content:
+ content = content.split('\t', 1)[0]
+ content = content.strip()
+ if content:
+ text_parts.append(content)
+ if 'target_anchor' in span and target_anchor is None:
+ pid, bidx = span['target_anchor']
+ target_anchor = f"block-p{pid}-b{bidx}"
+
+ item_text = ''.join(text_parts).strip()
+ if not item_text:
+ continue
+
+ if target_anchor is not None:
+ item_text = f"[{item_text}](#{target_anchor})"
+
+ items.append(f"{indent}- {item_text}")
+
+ return items
+
+
+def merge_index_to_markdown(index_block):
+ """Convert a nested index (TOC) block to markdown with hyperlinks."""
+ return '\n'.join(_flatten_index_items(index_block)) + '\n'
+
+
+def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path='', page_idx=None):
page_markdown = []
for para_block in para_blocks:
para_text = ''
para_type = para_block['type']
if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:
para_text = merge_para_with_text(para_block)
- elif para_type in [BlockType.LIST, BlockType.INDEX]:
+ elif para_type == BlockType.LIST:
para_text = merge_list_to_markdown(para_block)
+ elif para_type == BlockType.INDEX:
+ para_text = merge_index_to_markdown(para_block)
elif para_type == BlockType.TITLE:
title_level = get_title_level(para_block)
- para_text = f'{"#" * title_level} {merge_para_with_text(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}'
+ else:
+ para_text = f'{"#" * title_level} {title_text}'
elif para_type == BlockType.IMAGE:
if make_mode == MakeMode.NLP_MD:
continue
@@ -420,7 +475,8 @@ def union_make(pdf_info_dict: list,
if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
if not paras_of_layout:
continue
- page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path)
+ page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, img_buket_path,
+ page_idx=page_idx)
output_content.extend(page_markdown)
elif make_mode == MakeMode.CONTENT_LIST:
para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])