Skip to content

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

fix: enhance handling of inline equations and improve text processing in index items

myhloli2fb590dcab3d
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index cd656220..0119ca6c 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -6,7 +6,7 @@ from collections import defaultdict
from loguru import logger
from mineru.backend.office.office_magic_model import MagicModel
-from mineru.utils.enum_class import BlockType
+from mineru.utils.enum_class import BlockType, ContentType
from mineru.utils.hash_utils import str_sha256
from mineru.version import __version__
@@ -166,6 +166,47 @@ def _strip_fig_tab_number(text: str) -> str:
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 _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.
+
+ 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'${c}$')
+ 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 = []
@@ -323,6 +364,238 @@ def _link_index_spans_to_body_blocks(middle_json: dict) -> None:
if 'target_anchor' in span:
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 any('target_anchor' in s for s in all_spans):
+ 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:
+ 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:
+ continue
+ body_text_only = _text_only_from_block(blk)
+ if not body_text_only:
+ 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 first non-empty span and restore full heading text.
+
+ Used by Pass 3 after an equation-stripped match has been found.
+ The first non-empty span receives the ``target_anchor`` and its content
+ is replaced with the full body-heading text (inline equations wrapped
+ with ``$...$``). Surplus spans are removed from the TEXT block's lines
+ so that no empty ``inline_equation`` or ``text`` remnants appear in the
+ middle-JSON output.
+ """
+ if not all_spans:
+ return
+
+ # Set target_anchor on the first non-empty span.
+ for s in all_spans:
+ if s.get('content', '').strip():
+ s['target_anchor'] = [t_pid, t_bidx]
+ break
+
+ # 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 = ''
+ for s in all_spans:
+ 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 first span with the full heading text and remove all
+ # other spans from the TEXT block so no empty remnants are left behind.
+ body_blk = block_lookup.get((t_pid, t_bidx))
+ if body_blk:
+ new_text = _build_toc_text_from_block(body_blk)
+ if new_text:
+ first_span = all_spans[0]
+ first_span['content'] = section_prefix + new_text
+ # Trim every line's spans list to contain only the first span,
+ # removing the surplus inline_equation / text fragments.
+ for line in text_block.get('lines', []):
+ line['spans'] = [s for s in line['spans'] if s is first_span]
+
def result_to_middle_json(model_output_blocks_list, image_writer):
middle_json = {"pdf_info": [], "_backend":"office", "_version_name": __version__}
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
index 25ec1ca1..2c7d14b6 100644
--- a/mineru/backend/office/office_middle_json_mkcontent.py
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -225,23 +225,32 @@ def _flatten_index_items(index_block):
if child.get('type') == BlockType.INDEX:
items.extend(_flatten_index_items(child))
elif child.get('type') == BlockType.TEXT:
- text_parts = []
+ raw_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" -> "引言",
- # "1.1\t研究对象\t5" -> "1.1 研究对象")
- if '\t' in content:
- content = content.rsplit('\t', 1)[0].replace('\t', ' ')
- content = content.strip()
if content:
- text_parts.append(content)
+ # Wrap inline equations with configured delimiters
+ if span.get('type') == ContentType.INLINE_EQUATION:
+ raw_parts.append(
+ f'{inline_left_delimiter}{content}{inline_right_delimiter}'
+ )
+ else:
+ raw_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()
+ # Combine all span content into one string, then strip the trailing
+ # tab + page-number in a single pass (e.g. "2.\t标题\t5" → "2. 标题").
+ # Applying rsplit once ensures that an internal tab between section
+ # number and title text (e.g. "1.1\t研究对象") becomes a space while
+ # only the rightmost tab separator (before the page count) is removed.
+ combined = ''.join(raw_parts)
+ if '\t' in combined:
+ combined = combined.rsplit('\t', 1)[0].replace('\t', ' ')
+ item_text = combined.strip()
if not item_text:
continue