Skip to content

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

feat: implement formula tagging logic to serialize and normalize formula numbers as LaTeX tags

myhlolibd7e8d52727e
diff --git a/mineru/backend/analysis/pdf/formulas.py b/mineru/backend/analysis/pdf/formulas.py
index 62b68076..64afa467 100644
--- a/mineru/backend/analysis/pdf/formulas.py
+++ b/mineru/backend/analysis/pdf/formulas.py
@@ -13,10 +13,9 @@ from PIL import Image
from mineru.backend.local_model_runtime import HybridLocalModelContext
from mineru.utils.bbox_utils import normalize_to_int_bbox
from mineru.utils.ocr_utils import get_rotate_crop_image_for_text_rec
+from mineru.utils.text_utils import build_tagged_formula_content
from ....types import RAW_FORMULA_NUMBER, BlockType
-from mineru.utils.text_utils import full_to_half
-from mineru.utils.text_utils import clean_isolated_formula
from .geometry import (
_bbox_to_pixel_bbox,
@@ -27,30 +26,6 @@ from .geometry import (
)
-def normalize_formula_tag_content(tag_content: str) -> str:
- """归一化公式编号文本,去掉全角字符和包裹括号后用于 \\tag{}。"""
- tag_content = full_to_half(str(tag_content or "").strip())
- if tag_content.startswith("("):
- tag_content = tag_content[1:].strip()
- if tag_content.endswith(")"):
- tag_content = tag_content[:-1].strip()
- return tag_content
-
-
-def normalize_formula_content_for_tag(formula_content: str) -> str:
- """归一化待合并编号的公式正文,去掉 VLM/Hybrid 可能携带的展示公式分隔符。"""
- return clean_isolated_formula(str(formula_content or ""))
-
-
-def build_tagged_formula_content(formula_content: str, tag_content: str) -> str | None:
- """将公式正文和编号文本合成为带 LaTeX tag 的纯公式内容。"""
- formula_content = normalize_formula_content_for_tag(formula_content)
- tag_content = normalize_formula_tag_content(tag_content)
- if not formula_content or not tag_content:
- return None
- return f"{formula_content}\\tag{{{tag_content}}}"
-
-
def _is_hybrid_equation_block(block: dict[str, Any]) -> bool:
"""判断 raw Hybrid/VLM block 是否表示可合并编号的行间公式。"""
return str(block.get("type") or "").lower() in {
diff --git a/mineru/model/flash/native_pdf/formulas.py b/mineru/model/flash/native_pdf/formulas.py
index 34215c1f..6583dc22 100644
--- a/mineru/model/flash/native_pdf/formulas.py
+++ b/mineru/model/flash/native_pdf/formulas.py
@@ -12,6 +12,7 @@ from typing import Any
from mineru.types import BBox
from mineru.utils.pdf_document import PDFPathInfo
+from mineru.utils.text_utils import build_tagged_formula_content
from .models import (
_FormulaAnchor,
@@ -1592,8 +1593,17 @@ def _formula_members_to_block(
*,
anchor_source_index: int,
) -> dict[str, Any] | None:
- """把公式空间分量按视觉行聚类,并将非末视觉行的离散右侧 sidecar 后置。"""
+ """把公式空间分量按视觉行聚类,将编号序列化为 tag 并后置其他 sidecar。"""
+ anchor_line = next(
+ (line for line, _bbox in members if line.source_index == anchor_source_index),
+ None,
+ )
+ anchor_formula_number_parts = (
+ _split_trailing_formula_number(anchor_line.text)
+ if anchor_line is not None
+ else None
+ )
heights = [_line_effective_height(line, bbox) for line, bbox in members]
median_height = statistics.median(heights) if heights else 1.0
row_tolerance = max(1.5, 0.35 * median_height)
@@ -1641,6 +1651,14 @@ def _formula_members_to_block(
if trailing_sidecar_content is not None:
row_contents.append(trailing_sidecar_content)
content = _sanitize_pdf_control_text("\n".join(filter(None, row_contents)), preserve_newlines=True)
+ if anchor_formula_number_parts is not None:
+ _anchor_prefix, tag_content = anchor_formula_number_parts
+ stripped_content = content.rstrip()
+ if stripped_content.endswith(tag_content):
+ formula_content = stripped_content[: -len(tag_content)].rstrip()
+ tagged_content = build_tagged_formula_content(formula_content, tag_content)
+ if tagged_content is not None:
+ content = tagged_content
if not content.strip():
return None
return {
diff --git a/mineru/utils/text_utils.py b/mineru/utils/text_utils.py
index ea36b437..f83e8961 100644
--- a/mineru/utils/text_utils.py
+++ b/mineru/utils/text_utils.py
@@ -77,3 +77,27 @@ def clean_isolated_formula(content: str) -> str:
if latex.endswith("\\]"):
latex = latex[:-2]
return latex.strip()
+
+
+def normalize_formula_tag_content(tag_content: str) -> str:
+ """归一化公式编号文本,去掉全角字符和包裹括号后用于 \\tag{}。"""
+ tag_content = full_to_half(str(tag_content or "").strip())
+ if tag_content.startswith(("(", "﹙")):
+ tag_content = tag_content[1:].strip()
+ if tag_content.endswith((")", "﹚")):
+ tag_content = tag_content[:-1].strip()
+ return tag_content
+
+
+def normalize_formula_content_for_tag(formula_content: str) -> str:
+ """归一化待合并编号的公式正文,去掉模型可能携带的展示公式分隔符。"""
+ return clean_isolated_formula(str(formula_content or ""))
+
+
+def build_tagged_formula_content(formula_content: str, tag_content: str) -> str | None:
+ """将公式正文和编号文本合成为带 LaTeX tag 的纯公式内容。"""
+ formula_content = normalize_formula_content_for_tag(formula_content)
+ tag_content = normalize_formula_tag_content(tag_content)
+ if not formula_content or not tag_content:
+ return None
+ return f"{formula_content}\\tag{{{tag_content}}}"
diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.py
index f6765e16..f3fae5fd 100644
--- a/tests/unittest/test_flash_pdf_formulas.py
+++ b/tests/unittest/test_flash_pdf_formulas.py
@@ -245,8 +245,8 @@ def test_detached_formula_sidecar_sharing_middle_row_moves_to_trailing_line() ->
@pytest.mark.parametrize("marker", ["(4)", "(4)", "﹙4﹚", "(4)"])
-def test_adjacent_parenthesized_formula_number_moves_to_trailing_line(marker: str) -> None:
- """验证贴近公式主体的多种圆括号序号后置,且前导逗号留在原视觉行。"""
+def test_adjacent_parenthesized_formula_number_serializes_as_tag(marker: str) -> None:
+ """验证贴近公式主体的多种圆括号序号转为 tag,且前导逗号留在正文。"""
members = [
_formula_member("numerator", (20.0, 0.0, 90.0, 10.0), 0),
@@ -266,7 +266,7 @@ def test_adjacent_parenthesized_formula_number_moves_to_trailing_line(marker: st
"type": "equation",
"bbox": (10.0, 0.0, 110.0, 30.0),
"angle": 0,
- "content": f"numerator,\nbody\ndenominator\n{marker}",
+ "content": "numerator,\nbody\ndenominator\\tag{4}",
}
@@ -1232,7 +1232,8 @@ def test_split_visual_row_with_right_number_forms_one_equation() -> None:
assert len(blocks) == 1
assert blocks[0]["type"] == "equation"
- assert "(8)" in blocks[0]["content"]
+ assert blocks[0]["content"].endswith(r"\tag{8}")
+ assert "(8)" not in blocks[0]["content"]
assert {line.source_index for line in remaining} == {0, 4}
@@ -1361,7 +1362,7 @@ def test_split_visual_row_formula_tail_defers_to_spatial_growth() -> None:
"type": "equation",
"bbox": (10.0, 52.0, 100.0, 82.0),
"angle": 0,
- "content": "at = 1 ( 1 - εt)\n2 ln\nεt\n(3)",
+ "content": "at = 1 ( 1 - εt)\n2 ln\nεt\\tag{3}",
}
]
assert {line.source_index for line in remaining} == {0, 1, 2, 9, 10}
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 2b2e553c..6db75ba2 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -1,10 +1,11 @@
from __future__ import annotations
+import re
+import unicodedata
from collections import Counter
from copy import deepcopy
from pathlib import Path
from typing import Any
-import unicodedata
from mineru.backend.postprocess.page_blocks import process_page_blocks
from mineru.backend.postprocess.pages import model_list_to_pages
@@ -84,8 +85,9 @@ def _grouped_visual_blocks(
def _normalized_content_probe(text: str) -> str:
- """去除空白、标点与 dash 差异,生成原生行内容覆盖检查使用的探针。"""
+ """还原 LaTeX tag 并去除排版差异,生成原生行内容覆盖检查使用的探针。"""
+ text = re.sub(r"\\tag\{([^{}]+)\}", r"\1", text)
return "".join(char.casefold() for char in text if char.isalnum())
@@ -314,7 +316,7 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
humans = next(content for content in page2_contents if content.startswith("Humans group shapes"))
matching = next(content for content in page2_contents if content.startswith("To identify a match"))
dissimilarity = next(content for content in page2_contents if content.startswith("where the pixel dissimilarity"))
- formula3 = next(content for content in page2_contents if content.endswith("(3)"))
+ formula3 = next(content for content in page2_contents if content.endswith(r"\tag{3}"))
assert not [content for content in page2_contents if content.strip() == "by"]
assert humans.endswith("is given by")
assert "Sp denotes a set of matching candidates" in matching
@@ -329,15 +331,15 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert "O(ω2) to O(ω)" in page3_contents[0]
assert "disparity estimates Dip" in page3_contents[13]
for formula_number in range(4, 10):
- marker = f"({formula_number})"
+ marker = rf"\tag{{{formula_number}}}"
assert sum(marker in content for content in page3_contents) == 1
- formula7 = next(content for content in page3_contents if "(7)" in content)
- formula4 = next(content for content in page3_contents if "(4)" in content)
- formula8 = next(content for content in page3_contents if "(8)" in content)
- assert formula4.splitlines()[-1] == "(4)"
- assert formula8.splitlines()[-1] == "(8)"
- assert "(4)" not in "\n".join(formula4.splitlines()[:-1])
- assert "(8)" not in "\n".join(formula8.splitlines()[:-1])
+ formula7 = next(content for content in page3_contents if r"\tag{7}" in content)
+ formula4 = next(content for content in page3_contents if r"\tag{4}" in content)
+ formula8 = next(content for content in page3_contents if r"\tag{8}" in content)
+ assert formula4.endswith(r"\tag{4}")
+ assert formula8.endswith(r"\tag{8}")
+ assert "\n(4)" not in formula4
+ assert "\n(8)" not in formula8
assert "Fp =" in formula7
assert "otherwise" in formula7
assert not [content for content in page3_contents if content.strip() in {"2", "p", "otherwise", "(7)"}]
@@ -692,12 +694,16 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->
attention_bias = next(block for block in page7 if block["content"].startswith("Attention Bias Scaling."))
positional_ids = next(block for block in page7 if block["content"].startswith("Row, Column, & Global Positional IDs."))
- formula6 = next(block for block in page7 if block["type"] == "equation" and "(6)" in block["content"])
+ formula6 = next(
+ block
+ for block in page7
+ if block["type"] == "equation" and r"\tag{6}" in block["content"]
+ )
assert attention_bias["type"] == "text"
assert attention_bias["content"].endswith("attention score by:")
assert positional_ids["type"] == "text"
assert "With TAPASBASE" in positional_ids["content"]
- assert formula6["content"].splitlines()[-1] == "(6)"
+ assert formula6["content"].endswith(r"\tag{6}")
assert not [
block
for block in page7
@@ -743,7 +749,7 @@ def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> N
assert "This example corresponds to table (a)" in caption_blocks[0]["content"]
assert "associated text." in caption_blocks[0]["content"]
- formula1 = next(block for block in page if "(1)" in block["content"])
+ formula1 = next(block for block in page if r"\tag{1}" in block["content"])
section3 = next(block for block in page if block["content"].startswith("3 TABLEFORMER:"))
inline_item = next(block for block in page if block["content"].startswith("2) Per cell positional ids."))
inline_heading = next(block for block in page if block["content"].startswith("Positional Encoding in TABLEFORMER."))
@@ -768,12 +774,12 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> N
assert attention_biases["type"] == "text"
assert "13 bias types" in attention_biases["content"]
- formula3 = next(block for block in page4 if "(3)" in block["content"])
- formula4 = next(block for block in page4 if "(4)" in block["content"])
+ formula3 = next(block for block in page4 if r"\tag{3}" in block["content"])
+ formula4 = next(block for block in page4 if r"\tag{4}" in block["content"])
assert formula3["type"] == formula4["type"] == "equation"
assert formula3 is not formula4
- assert "A =" in formula3["content"] and "(4)" not in formula3["content"]
- assert "(3)" not in formula4["content"]
+ assert "A =" in formula3["content"] and r"\tag{4}" not in formula3["content"]
+ assert r"\tag{3}" not in formula4["content"]
relation_blocks = [
block
@@ -1433,23 +1439,26 @@ def test_npu_numbered_figure_captions_are_independent_annotations() -> None:
def test_frozen_soil_page3_formula3_remains_one_equation() -> None:
- """验证中文论文第三页公式(3)完整归入单个公式块。"""
+ """验证中文论文第三页公式编号完整转为 tag 并归入单个公式块。"""
page = _txt_model_list("中文论文.pdf")[2]
equations = [block for block in page if block["type"] == "equation"]
- formula3 = [block for block in equations if "(3)" in str(block.get("content", ""))]
+ formula3 = [block for block in equations if r"\tag{3}" in str(block.get("content", ""))]
assert len(page) == 30
assert len(equations) == 4
assert len(formula3) == 1
assert formula3[0]["bbox"] == [0.653, 0.703, 0.898, 0.751]
- assert all(probe in str(formula3[0]["content"]) for probe in ("at = 1", "2 ln", "1 - εt", "εt", "(3)"))
+ assert all(
+ probe in str(formula3[0]["content"])
+ for probe in ("at = 1", "2 ln", "1 - εt", "εt", r"\tag{3}")
+ )
assert not [
block
for block in page
if block["type"] == "text" and any(probe in str(block.get("content", "")) for probe in ("at = 1", "2 ln", "1 - εt"))
]
- for marker in ("(1)", "(2)", "(3)", "(4)"):
+ for marker in (r"\tag{1}", r"\tag{2}", r"\tag{3}", r"\tag{4}"):
assert sum(marker in str(block.get("content", "")) for block in equations) == 1
@@ -1679,8 +1688,8 @@ def test_mixed_elements_pages_39_40_force_txt_regressions() -> None:
equations = [block for block in page40 if block["type"] == "equation"]
assert len(equations) == 3
- assert sum("(8)" in str(block["content"]) for block in equations) == 1
- assert sum("(9)" in str(block["content"]) for block in equations) == 1
+ assert sum(r"\tag{8}" in str(block["content"]) for block in equations) == 1
+ assert sum(r"\tag{9}" in str(block["content"]) for block in equations) == 1
inequality = _blocks_containing(equations, "Mπ(Xn)")
assert len(inequality) == 1
assert inequality[0]["type"] == "equation"
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index bb47eb9e..66a62c63 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -755,6 +755,13 @@ def test_formula_number_optimizer_recognizes_canonical_and_upstream_equation_typ
]
[email protected]("tag_content", ["(4)", "(4)", "﹙4﹚", "(4)"])
+def test_formula_tag_builder_normalizes_supported_parentheses(tag_content: str) -> None:
+ """验证共享 tag 构造器兼容 Flash 已识别的多种圆括号编号。"""
+
+ assert formulas.build_tagged_formula_content("x=4", tag_content) == r"x=4\tag{4}"
+
+
def test_formula_number_optimizer_merges_leading_number_bbox() -> None:
"""验证前置公式编号按既有相邻规则合并,并扩展后续公式 bbox。"""
optimized = formulas.optimize_hybrid_formula_number_blocks(
@@ -1572,7 +1579,7 @@ def test_doc_analyze_flash_real_pdf_returns_typed_middle_json() -> None:
def test_doc_analyze_flash_demo1_uses_canonical_equation_type() -> None:
- """验证真实 demo1.pdf 的 model list 与 MiddleJson 统一输出 equation。"""
+ """验证真实 demo1.pdf 的两层 Flash 输出统一使用 equation 与 LaTeX tag。"""
sample_path = _PROJECT_ROOT / "demo" / "pdfs" / "demo1.pdf"
middle_json, model_list = analyze.doc_analyze(
@@ -1589,6 +1596,21 @@ def test_doc_analyze_flash_demo1_uses_canonical_equation_type() -> None:
assert model_equations
assert len(middle_equations) == len(model_equations)
+ assert [block.content for block in middle_equations] == [
+ block["content"]
+ for block in model_equations
+ ]
+ for formula_number in range(1, 8):
+ marker = rf"\tag{{{formula_number}}}"
+ assert sum(marker in block["content"] for block in model_equations) == 1
+ assert not [
+ block
+ for block in model_equations
+ if any(
+ block["content"].rstrip().endswith(f"({formula_number})")
+ for formula_number in range(1, 8)
+ )
+ ]
assert "interline_equation" not in middle_json.to_json()