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: normalize PDF model list by cleaning metadata and replacing inline formula delimiters
myhlolia173e1b6d776
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex 7226fc67..e33caea5 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -2391,10 +2391,12 @@ def _apply_layout_title_split(block["type"] = BlockType.PARAGRAPH_TITLE-def _replace_inline_formula_delimiters(model_list: list[list[dict[str, Any]]]) -> None:- """将 model JSON content 中的行内公式定界符原地替换为 eq 标签。"""+def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:+ """清理 model JSON block 元数据,并原地替换 content 中的行内公式定界符。"""for page_model_list in model_list:for block in page_model_list:+ block.pop("angle", None)+ block.pop("score", None)content = block.get("content")if not isinstance(content, str):continue@@ -2602,8 +2604,8 @@ def doc_analyze(finally:_close_images(images_list)- # 仅 PDF 模型结果需要将行内公式定界符统一替换为 eq 标签。- _replace_inline_formula_delimiters(model_list)+ # 仅 PDF 模型结果需要统一清理块元数据并规范化行内公式。+ _normalize_pdf_model_list(model_list)infer_elapsed = time.perf_counter() - infer_started_atdocument.close()@@ -2645,7 +2647,7 @@ if __name__ == "__main__":file_bytes = read_fn(file_path)file_suffix = os.path.splitext(file_path)[1].lstrip(".").lower()file_suffix = "pdf"- middle_json, model_list = doc_analyze(file_bytes, effort="flash", file_suffix=file_suffix)+ middle_json, model_list = doc_analyze(file_bytes, effort="medium", file_suffix=file_suffix)model_json = json.dumps(model_list, ensure_ascii=False, indent=4)logger.info(f"file_path: {file_path}")logger.info(f"middle_json: {middle_json}")diff --git a/mineru/backend/magic_model.py b/mineru/backend/magic_model.pyindex 8eb91177..c280eb9a 100644--- a/mineru/backend/magic_model.py+++ b/mineru/backend/magic_model.py@@ -119,7 +119,7 @@ class MagicModel:for code_block in self.code_blocks:if code_block["sub_type"] == "code":- for sub_block in code_block["blocks"]:+ for sub_block in code_block["content"]:if sub_block.get("type") == BlockType.CODE_BODY:guess_lang = guess_language_by_text(sub_block.get("content", ""))code_block["guess_lang"] = guess_langdiff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.pyindex 4f62979c..5dd31305 100644--- a/mineru/backend/utils/visual_magic_model_utils.py+++ b/mineru/backend/utils/visual_magic_model_utils.py@@ -533,9 +533,14 @@ def regroup_visual_blocks(main_index = _block_index(main_block)visual_type = VISUAL_MAIN_TYPES[_block_type(main_block)]mapping = VISUAL_TYPE_MAPPING[visual_type]+ main_sub_type = str(_get_block_field(main_block, "sub_type", "") or "")body_block = deepcopy(main_block)_set_block_field(body_block, "type", mapping["body"])- _set_block_field(body_block, "sub_type", "")+ if main_sub_type:+ if isinstance(body_block, dict):+ body_block.pop("sub_type", None)+ else:+ body_block.sub_type = ""captions: list[BlockLike] = []for caption in sorted(@@ -544,6 +549,8 @@ def regroup_visual_blocks():child_block = deepcopy(caption)_set_block_field(child_block, "type", mapping["caption"])+ if isinstance(child_block, dict):+ child_block.pop("_lines", None)captions.append(child_block)footnotes: list[BlockLike] = []@@ -553,21 +560,23 @@ def regroup_visual_blocks():child_block = deepcopy(footnote)_set_block_field(child_block, "type", mapping["footnote"])+ if isinstance(child_block, dict):+ child_block.pop("_lines", None)footnotes.append(child_block)child_items = sorted([body_block, *captions, *footnotes],key=_block_index,)- main_sub_type = str(_get_block_field(main_block, "sub_type", "") or "")cell_merge = _get_block_field(main_block, "_cell_merge", [])if isinstance(main_block, dict):two_layer_block: BlockLike = {"index": main_index,"type": visual_type,"content": child_items,- "sub_type": main_sub_type,}+ if main_sub_type:+ two_layer_block["sub_type"] = main_sub_typeif "bbox" in main_block:two_layer_block["bbox"] = deepcopy(main_block["bbox"])if visual_type == BlockType.TABLE and cell_merge:@@ -579,7 +588,7 @@ def regroup_visual_blocks(bbox=main_block.bbox,content=cast(Any, child_items),)- if visual_type in [BlockType.IMAGE, BlockType.CHART] and main_sub_type:+ if main_sub_type:two_layer_block.sub_type = main_sub_typeif visual_type == BlockType.TABLE and cell_merge:two_layer_block._cell_merge = cell_mergediff --git a/tests/unittest/test_magic_model.py b/tests/unittest/test_magic_model.pyindex 300dafda..dd2b4abb 100644--- a/tests/unittest/test_magic_model.py+++ b/tests/unittest/test_magic_model.py@@ -54,7 +54,7 @@ def test_magic_model_groups_bbox_dict_visual_blocks() -> None:assert len(magic_model.image_blocks) == 1image_block = magic_model.image_blocks[0]assert isinstance(image_block, dict)- assert [block["type"] for block in image_block["blocks"]] == [+ assert [block["type"] for block in image_block["content"]] == [BlockType.IMAGE_CAPTION,BlockType.IMAGE_BODY,]@@ -78,7 +78,7 @@ def test_magic_model_groups_no_bbox_office_caption_by_prefix() -> None:assert magic_model.text_blocks == []assert len(magic_model.image_blocks) == 1image_block = magic_model.image_blocks[0]- assert [block["type"] for block in image_block["blocks"]] == [+ assert [block["type"] for block in image_block["content"]] == [BlockType.IMAGE_BODY,BlockType.IMAGE_CAPTION,]@@ -95,14 +95,14 @@ def test_magic_model_groups_no_bbox_chart_and_code_captions() -> None:])- assert [block["type"] for block in magic_model.chart_blocks[0]["blocks"]] == [+ assert [block["type"] for block in magic_model.chart_blocks[0]["content"]] == [BlockType.CHART_CAPTION,BlockType.CHART_BODY,]code_block = magic_model.code_blocks[0]assert code_block["sub_type"] == "code"assert code_block["guess_lang"]- assert [block["type"] for block in code_block["blocks"]] == [+ assert [block["type"] for block in code_block["content"]] == [BlockType.CODE_CAPTION,BlockType.CODE_BODY,]diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex 142f7909..9391dfb1 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -528,23 +528,36 @@ def test_visual_block_crop_rejects_page_count_mismatch() -> None:analyze._attach_visual_block_images([[]], [])-def test_replace_inline_formula_delimiters_updates_model_list_in_place() -> None:- """验证行内公式定界符会在 model JSON 原对象上统一替换为 eq 标签。"""+def test_normalize_pdf_model_list_updates_in_place() -> None:+ """验证 block 元数据清理和行内公式替换会原地更新 model JSON。"""model_list = [[- {"type": BlockType.TEXT, "content": "前 \\(a+b\\) 中 \\(c_d\\) 后"},- {"type": BlockType.TEXT, "content": "已有 <eq>x</eq> 保持不变"},- {"type": BlockType.TEXT, "content": "未闭合 \\(formula"},+ {+ "type": BlockType.TEXT,+ "content": "前 \\(a+b\\) 中 \\(c_d\\) 后",+ "angle": 0,+ "score": 0.98,+ },+ {+ "type": BlockType.TEXT,+ "content": "已有 <eq>x</eq> 保持不变",+ "angle": 90,+ },+ {+ "type": BlockType.TEXT,+ "content": "未闭合 \\(formula",+ "score": 0.75,+ },],[{"type": BlockType.TEXT, "content": ""},- {"type": BlockType.TEXT, "content": None},- {"type": BlockType.TEXT, "content": ["非字符串"]},- {"type": BlockType.TEXT, "content": "跨行 \\(a\nb\\)"},+ {"type": BlockType.TEXT, "content": None, "angle": 180, "score": 0.5},+ {"type": BlockType.TEXT, "content": ["非字符串"], "score": 0.25},+ {"type": BlockType.TEXT, "content": "跨行 \\(a\nb\\)", "angle": 270},],]- result = analyze._replace_inline_formula_delimiters(model_list)+ result = analyze._normalize_pdf_model_list(model_list)assert result is Noneassert model_list[0][0]["content"] == "前 <eq>a+b</eq> 中 <eq>c_d</eq> 后"@@ -554,6 +567,11 @@ def test_replace_inline_formula_delimiters_updates_model_list_in_place() -> Noneassert model_list[1][1]["content"] is Noneassert model_list[1][2]["content"] == ["非字符串"]assert model_list[1][3]["content"] == "跨行 \\(a\nb\\)"+ assert all(+ "angle" not in block and "score" not in block+ for page_model_list in model_list+ for block in page_model_list+ )@pytest.mark.parametrize(@@ -618,7 +636,7 @@ def test_doc_analyze_office_returns_model_list_without_pdf_processing(window_builder = MagicMock()image_loader = MagicMock()visual_image_attacher = MagicMock()- formula_replacer = MagicMock()+ model_list_normalizer = MagicMock()monkeypatch.setattr(analyze, "_OFFICE_MODEL_MAP", model_factories)monkeypatch.setattr(analyze, "PDFDocument", pdf_document)monkeypatch.setattr(analyze, "HybridLocalModelContextSingleton", hybrid_model_factory)@@ -626,7 +644,7 @@ def test_doc_analyze_office_returns_model_list_without_pdf_processing(monkeypatch.setattr(analyze, "_build_processing_windows", window_builder)monkeypatch.setattr(analyze, "load_images_from_pdf_bytes_range", image_loader)monkeypatch.setattr(analyze, "_attach_visual_block_images", visual_image_attacher)- monkeypatch.setattr(analyze, "_replace_inline_formula_delimiters", formula_replacer)+ monkeypatch.setattr(analyze, "_normalize_pdf_model_list", model_list_normalizer)monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)middle_json, model_list = analyze.doc_analyze(@@ -652,7 +670,7 @@ def test_doc_analyze_office_returns_model_list_without_pdf_processing(window_builder.assert_not_called()image_loader.assert_not_called()visual_image_attacher.assert_not_called()- formula_replacer.assert_not_called()+ model_list_normalizer.assert_not_called()def test_doc_analyze_rejects_unsupported_suffix_before_resource_initialization(@@ -718,9 +736,9 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(events.append(f"timer_{value}")return value- def fake_replace_formula(_model_list: list[list[dict[str, object]]]) -> None:- """记录 PDF model_list 公式规范化顺序。"""- events.append("formula_replace")+ def fake_normalize_model_list(_model_list: list[list[dict[str, object]]]) -> None:+ """记录 PDF model_list 规范化顺序。"""+ events.append("normalize_model_list")def fake_clean_memory(_device: str) -> None:"""记录设备缓存清理顺序。"""@@ -738,7 +756,7 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup()monkeypatch.setattr(analyze, "get_vlm_engine", MagicMock(return_value="transformers"))monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)- monkeypatch.setattr(analyze, "_replace_inline_formula_delimiters", fake_replace_formula)+ monkeypatch.setattr(analyze, "_normalize_pdf_model_list", fake_normalize_model_list)monkeypatch.setattr(analyze, "clean_memory", fake_clean_memory)middle_json, model_list = analyze.doc_analyze(@@ -754,7 +772,7 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup("vlm_init","vlm_wrap","timer_20.0",- "formula_replace",+ "normalize_model_list","timer_22.0","document_close","clean_memory",@@ -856,12 +874,12 @@ def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monkeevents.append("attach_visual")original_attach_visual_block_images(*args, **kwargs) # type: ignore[arg-type]- original_replace_formula = analyze._replace_inline_formula_delimiters+ original_normalize_model_list = analyze._normalize_pdf_model_list- def tracked_replace_formula(model_list: list[list[dict[str, object]]]) -> None:- """记录 PDF 公式规范化顺序并调用真实实现。"""- events.append("formula_replace")- original_replace_formula(model_list) # type: ignore[arg-type]+ def tracked_normalize_model_list(model_list: list[list[dict[str, object]]]) -> None:+ """记录 PDF model_list 规范化顺序并调用真实实现。"""+ events.append("normalize_model_list")+ original_normalize_model_list(model_list) # type: ignore[arg-type]perf_counter_values = iter([30.0, 33.0])@@ -875,7 +893,7 @@ def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monkemonkeypatch.setattr(analyze, "get_processing_window_size", lambda default: 2)monkeypatch.setattr(analyze, "load_images_from_pdf_bytes_range", fake_load_images_for_window)monkeypatch.setattr(analyze, "_attach_visual_block_images", tracked_attach_visual_block_images)- monkeypatch.setattr(analyze, "_replace_inline_formula_delimiters", tracked_replace_formula)+ monkeypatch.setattr(analyze, "_normalize_pdf_model_list", tracked_normalize_model_list)monkeypatch.setattr(analyze.time, "perf_counter", fake_perf_counter)monkeypatch.setattr(flash_model, "PdfModel", MagicMock(return_value=fake_pdf_model))@@ -908,7 +926,7 @@ def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monke"attach_visual","render_window","attach_visual",- "formula_replace",+ "normalize_model_list","timer_33.0","document_close",]diff --git a/tests/unittest/test_visual_magic_model_utils.py b/tests/unittest/test_visual_magic_model_utils.pyindex 3e68550b..b878e68a 100644--- a/tests/unittest/test_visual_magic_model_utils.py+++ b/tests/unittest/test_visual_magic_model_utils.py@@ -266,6 +266,8 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:"type": BlockType.CAPTION,"bbox": [0.0, 0.0, 80.0, 10.0],"content": "Figure 1",+ "_lines": [{"bbox": [0.0, 0.0, 80.0, 10.0]}],+ "merge_prev": True,}body = {"index": 1,@@ -278,6 +280,7 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:"type": BlockType.FOOTNOTE,"bbox": [0.0, 65.0, 80.0, 75.0],"content": "source",+ "_lines": [{"bbox": [0.0, 65.0, 80.0, 75.0]}],}grouped_blocks, unmatched_blocks = regroup_visual_blocks(@@ -290,11 +293,17 @@ def test_regroup_visual_blocks_supports_bbox_dicts() -> None:assert isinstance(image_block, dict)assert image_block["type"] == BlockType.IMAGEassert image_block["bbox"] == body["bbox"]- assert [block["type"] for block in image_block["blocks"]] == [+ assert [block["type"] for block in image_block["content"]] == [BlockType.IMAGE_CAPTION,BlockType.IMAGE_BODY,BlockType.IMAGE_FOOTNOTE,]+ image_caption, _, image_footnote = image_block["content"]+ assert "_lines" not in image_caption+ assert image_caption["merge_prev"] is True+ assert "_lines" not in image_footnote+ assert "_lines" in caption+ assert "_lines" in footnoteassert caption["type"] == BlockType.CAPTIONassert footnote["type"] == BlockType.FOOTNOTE@@ -311,6 +320,7 @@ def test_regroup_visual_blocks_keeps_block_output_compatibility() -> None:index=1,type=BlockType.IMAGE_BODY,bbox=(0.0, 15.0, 80.0, 60.0),+ sub_type="seal",),]@@ -319,10 +329,12 @@ def test_regroup_visual_blocks_keeps_block_output_compatibility() -> None:assert unmatched_blocks == []image_block = grouped_blocks[BlockType.IMAGE][0]assert isinstance(image_block, Block)- assert [block.type for block in image_block.blocks] == [+ assert image_block.sub_type == "seal"+ assert [block.type for block in image_block.content] == [BlockType.IMAGE_CAPTION,BlockType.IMAGE_BODY,]+ assert image_block.content[1].sub_type == ""def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:@@ -344,6 +356,8 @@ def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:"index": 2,"type": BlockType.TABLE_BODY,"content": "<table></table>",+ "angle": 0,+ "score": 0.0,"_cell_merge": [1, 0],},]@@ -354,9 +368,15 @@ def test_regroup_visual_blocks_preserves_dict_visual_metadata() -> None:image_block = grouped_blocks[BlockType.IMAGE][0]table_block = grouped_blocks[BlockType.TABLE][0]assert code_block["sub_type"] == "code"- assert code_block["blocks"][0]["sub_type"] == ""+ assert "sub_type" not in code_block["content"][0]assert image_block["sub_type"] == "seal"+ assert "sub_type" not in image_block["content"][0]+ assert "sub_type" not in table_block+ assert "sub_type" not in table_block["content"][0]+ assert table_block["content"][0]["angle"] == 0+ assert table_block["content"][0]["score"] == 0.0assert table_block["_cell_merge"] == [1, 0]+ assert table_block["content"][0]["_cell_merge"] == [1, 0]def test_regroup_visual_blocks_without_bbox_prefers_previous_parent() -> None:@@ -374,11 +394,11 @@ def test_regroup_visual_blocks_without_bbox_prefers_previous_parent() -> None:assert "bbox" not in grouped_blocks[BlockType.IMAGE][0]assert [block["type"]- for block in grouped_blocks[BlockType.IMAGE][0]["blocks"]+ for block in grouped_blocks[BlockType.IMAGE][0]["content"]] == [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION]assert [block["type"]- for block in grouped_blocks[BlockType.TABLE][0]["blocks"]+ for block in grouped_blocks[BlockType.TABLE][0]["content"]] == [BlockType.TABLE_BODY]@@ -396,7 +416,7 @@ def test_regroup_visual_blocks_without_bbox_keeps_text_as_barrier() -> None:assert unmatched_blocks == [caption]assert [block["type"]- for block in grouped_blocks[BlockType.TABLE][0]["blocks"]+ for block in grouped_blocks[BlockType.TABLE][0]["content"]] == [BlockType.TABLE_BODY]