Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: refactor LaTeX handling functions for improved mathring argument formatting
myhloli9d9b3c514e1a
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/processors.py b/mineru/model/mfr/pp_formulanet_plus_m/processors.pyindex 452d7049..18d90e06 100644--- a/mineru/model/mfr/pp_formulanet_plus_m/processors.py+++ b/mineru/model/mfr/pp_formulanet_plus_m/processors.py@@ -12,8 +12,7 @@ from loguru import loggerfrom tokenizers import AddedTokenfrom tokenizers import Tokenizer as TokenizerFast-from mineru.model.mfr.utils import fix_latex_left_right, fix_latex_environments, remove_up_commands, \- remove_unsupported_commands+from mineru.model.mfr.utils import fix_pp_formulanet_latexclass UniMERNetImgDecode(object):@@ -622,12 +621,7 @@ class UniMERNetDecode(object):Returns:str: Fixed string."""- text = fix_latex_left_right(text, fix_delimiter=False)- text = fix_latex_environments(text)- text = remove_up_commands(text)- text = remove_unsupported_commands(text)- # text = self.normalize(text)- return text+ return fix_pp_formulanet_latex(text)def __call__(self,diff --git a/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py b/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.pyindex 0a574bad..6e480091 100644--- a/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py+++ b/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py@@ -13,7 +13,7 @@ from transformers.models.vision_encoder_decoder.modeling_vision_encoder_decoderfrom .unimer_swin import UnimerSwinConfig, UnimerSwinModel, UnimerSwinImageProcessorfrom .unimer_mbart import UnimerMBartConfig, UnimerMBartForCausalLM-from ...utils import latex_rm_whitespace+from ...utils import fix_unimernet_latexAutoConfig.register(UnimerSwinConfig.model_type, UnimerSwinConfig)AutoConfig.register(UnimerMBartConfig.model_type, UnimerMBartConfig)@@ -149,7 +149,7 @@ class UnimernetModel(VisionEncoderDecoderModel):token_ids = outputs[:, 1:].cpu()result_tokens = token_ids.numpy() if return_full_result else token_idspred_str = self.tokenizer.token2str(result_tokens)- fixed_str = [latex_rm_whitespace(s) for s in pred_str]+ fixed_str = [fix_unimernet_latex(s) for s in pred_str]if not return_full_result:return {"fixed_str": fixed_str}diff --git a/mineru/model/mfr/utils.py b/mineru/model/mfr/utils.pyindex 67c0a0fa..cae05547 100644--- a/mineru/model/mfr/utils.py+++ b/mineru/model/mfr/utils.py@@ -250,6 +250,9 @@ ENV_TYPES = ['array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix',ENV_BEGIN_PATTERNS = {env: re.compile(r'\\begin\{' + env + r'\}') for env in ENV_TYPES}ENV_END_PATTERNS = {env: re.compile(r'\\end\{' + env + r'\}') for env in ENV_TYPES}ENV_FORMAT_PATTERNS = {env: re.compile(r'\\begin\{' + env + r'\}\{([^}]*)\}') for env in ENV_TYPES}+MATHRING_FONT_ARGUMENT_PATTERN = re.compile(+ r"\\mathring(?!\s*\{)\s*(?P<argument>\\mathrm\s*\{[^{}]*\})"+)def fix_latex_environments(s):"""@@ -277,6 +280,16 @@ def fix_latex_environments(s):return s+def fix_mathring_font_arguments(s: str) -> str:+ """为 mathring 后未分组的 mathrm 参数补充显式花括号。"""++ def _replace(match: re.Match[str]) -> str:+ """把单个 mathrm 字体参数包装成 mathring 的完整参数。"""+ return "\\mathring{" + match.group("argument") + "}"++ return MATHRING_FONT_ARGUMENT_PATTERN.sub(_replace, s)++REPLACEMENTS_PATTERNS = {re.compile(r'\\underbar'): r'\\underline',re.compile(r'\\Bar'): r'\\hat',@@ -314,14 +327,24 @@ def remove_unsupported_commands(s: str):return s-def latex_rm_whitespace(s: str):- """Remove unnecessary whitespace from LaTeX code."""- s = fix_unbalanced_braces(s)- s = fix_latex_left_right(s)+def _apply_shared_latex_repairs(s: str, *, fix_delimiter: bool) -> str:+ """执行 PP-FormulaNet 与 UniMERNet 共有的 LaTeX 修复步骤。"""+ s = fix_latex_left_right(s, fix_delimiter=fix_delimiter)s = fix_latex_environments(s)-+ s = fix_mathring_font_arguments(s)s = remove_up_commands(s)- s = remove_unsupported_commands(s)+ return remove_unsupported_commands(s)+++def fix_pp_formulanet_latex(s: str) -> str:+ """执行 PP-FormulaNet 专用 LaTeX 后处理,不补写 left/right 分隔符。"""+ return _apply_shared_latex_repairs(s, fix_delimiter=False)+++def fix_unimernet_latex(s: str) -> str:+ """执行 UniMERNet 专用 LaTeX 后处理与输出规范化。"""+ s = fix_unbalanced_braces(s)+ s = _apply_shared_latex_repairs(s, fix_delimiter=True)# 应用所有替换for pattern, replacement in REPLACEMENTS_PATTERNS.items():diff --git a/tests/unittest/test_mfr_latex_utils.py b/tests/unittest/test_mfr_latex_utils.pynew file mode 100644index 00000000..17399a4b--- /dev/null+++ b/tests/unittest/test_mfr_latex_utils.py@@ -0,0 +1,92 @@+from __future__ import annotations++import pytest+import torch++from mineru.model.mfr import utils as mfr_utils+from mineru.model.mfr.pp_formulanet_plus_m.processors import UniMERNetDecode+from mineru.model.mfr.unimernet.unimernet_hf.modeling_unimernet import UnimernetModel+++ ("source", "expected"),+ [+ (r"\mathring \mathrm { A }", r"\mathring{\mathrm { A }}"),+ (r"\mathring\mathrm{A}", r"\mathring{\mathrm{A}}"),+ (r"\mathring{\mathrm{A}}", r"\mathring{\mathrm{A}}"),+ (r"\mathring {\mathrm{A}}", r"\mathring {\mathrm{A}}"),+ (r"\mathring A", r"\mathring A"),+ (r"\mathrm{A}", r"\mathrm{A}"),+ ],+)+def test_fix_mathring_font_arguments_is_narrow_and_idempotent(source: str, expected: str) -> None:+ """验证 mathring 只修复未分组 mathrm 参数,并保持合法输入幂等。"""+ fixed = mfr_utils.fix_mathring_font_arguments(source)++ assert fixed == expected+ assert mfr_utils.fix_mathring_font_arguments(fixed) == expected+++def test_fix_mathring_font_arguments_repairs_multiple_occurrences() -> None:+ """验证同一公式中的多个未分组 mathring 参数均会修复。"""+ source = r"\mathring \mathrm{A} + \mathring\mathrm { B }"++ assert mfr_utils.fix_mathring_font_arguments(source) == (+ r"\mathring{\mathrm{A}} + \mathring{\mathrm { B }}"+ )+++ ("source", "pp_expected", "unimernet_expected"),+ [+ (r"\left x \right y", r"\left x \right y", r"\left. x \right. y"),+ (r"\Dot{x}", r"\Dot{x}", r"\dot{x}"),+ (r"{x", r"{x", r"x"),+ (r"\upalpha + \emph{x}", r"\alpha + {x}", r"\alpha + {x}"),+ ],+)+def test_model_specific_latex_repairs_keep_existing_differences(+ source: str,+ pp_expected: str,+ unimernet_expected: str,+) -> None:+ """验证共享重构不会把任一模型的专属修复带入另一模型。"""+ assert mfr_utils.fix_pp_formulanet_latex(source) == pp_expected+ assert mfr_utils.fix_unimernet_latex(source) == unimernet_expected+++def test_pp_formulanet_fix_latex_uses_shared_mathring_repair() -> None:+ """验证 PP-FormulaNet 的真实 processor 入口应用共享修复。"""+ source = r"R , { \mathring \mathrm { A } }"++ assert UniMERNetDecode.fix_latex(None, source) == r"R , { \mathring{\mathrm { A }} }"+++def test_unimernet_decode_entry_uses_renamed_latex_repair() -> None:+ """验证 UniMERNet 解码入口通过新名称应用共享修复。"""++ class _TokenizerStub:+ """为轻量解码入口返回固定 LaTeX 文本。"""++ @staticmethod+ def token2str(_token_ids: object) -> list[str]:+ """返回含未分组 mathring 参数的模型文本。"""+ return [r"R , { \mathring \mathrm { A } }"]++ class _ModelStub:+ """仅提供解码方法实际访问的 tokenizer。"""++ tokenizer = _TokenizerStub()++ result = UnimernetModel._decode_generate_outputs(+ _ModelStub(),+ torch.tensor([[0, 1, 2]]),+ return_full_result=False,+ )++ assert result == {"fixed_str": [r"R , { \mathring{\mathrm { A }} }"]}+++def test_latex_rm_whitespace_name_is_removed() -> None:+ """验证旧职责不符名称不再作为兼容入口保留。"""+ assert not hasattr(mfr_utils, "latex_rm_whitespace")