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: add conversion function for VLM results to native list/dict format and update processing logic
myhloli3f9666b8b45e
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex e33caea5..534535a0 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -6,6 +6,7 @@ import osimport reimport timefrom collections import Counter+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom io import BytesIOfrom typing import Any, Literal@@ -401,6 +402,13 @@ def _build_vl_style_layout_blocks(return blocks_list+def _convert_vlm_results_to_model_list(+ vlm_results: Iterable[Iterable[Mapping[str, Any]]],+) -> list[list[dict[str, Any]]]:+ """将 VLM 返回的 ExtractResult/ContentBlock 转换为原生 list/dict。"""+ return [[dict(block) for block in page_blocks] for page_blocks in vlm_results]++def _normalize_xhigh_vlm_blocks(model_list: list[list[dict[str, Any]]]) -> None:"""归一化 xhigh VLM 注释类型,并移除正文块的 merge_prev。"""for page_model_list in model_list:@@ -2422,7 +2430,7 @@ def doc_analyze(image_analysis: bool = True,page_index_map: list[int] | None = None,file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",-):+) -> tuple[dict[str, Any], list[list[dict[str, Any]]]]:if file_suffix not in _SUPPORTED_FILE_SUFFIXES:raise ValueError(f"Unsupported file suffix: {file_suffix!r}")@@ -2533,12 +2541,6 @@ def doc_analyze(not_extract_list=NOT_EXTRACT_TYPES,image_analysis=image_analysis,)- _normalize_xhigh_vlm_blocks(window_model_list)- _apply_layout_title_split(- window_model_list,- images_layout_res,- [_normalize_page_size(image) for image in images_pil_list],- )else:raise ValueError(f"Unsupported analyze effort: {effort}")elif parse_mode == "ocr":@@ -2555,17 +2557,21 @@ def doc_analyze(images=images_pil_list,image_analysis=image_analysis,)- _normalize_xhigh_vlm_blocks(window_model_list)- _apply_layout_title_split(- window_model_list,- images_layout_res,- [_normalize_page_size(image) for image in images_pil_list],- )else:raise ValueError(f"Unsupported analyze effort: {effort}")else:raise ValueError(f"Unsupported parse mode: {parse_mode}")+ if effort in {"high", "xhigh"}:+ window_model_list = _convert_vlm_results_to_model_list(window_model_list)+ if effort == "xhigh":+ _normalize_xhigh_vlm_blocks(window_model_list)+ _apply_layout_title_split(+ window_model_list,+ images_layout_res,+ [_normalize_page_size(image) for image in images_pil_list],+ )+if effort == "low":window_model_list = _process_low_text(images_list,@@ -2639,15 +2645,15 @@ if __name__ == "__main__":demo_file_paths = [# os.path.join(project_root, "demo", "office_docs", "docx_01.docx"),# os.path.join(project_root, "demo", "pdfs", "NPU_开发环境部署_参考指南.pdf"),- # "/Users/myhloli/pdf/png/2407.00079v4_origi-10.pdf",- os.path.join(project_root, "demo", "pdfs", "demo1.pdf"),+ "/Users/myhloli/pdf/png/2407.00079v4_origi-10.pdf",+ # os.path.join(project_root, "demo", "pdfs", "demo1.pdf"),]for file_path in demo_file_paths: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="medium", file_suffix=file_suffix)+ middle_json, model_list = doc_analyze(file_bytes, effort="xhigh", 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/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex 15b28f0b..4a990e9a 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -5,6 +5,9 @@ from unittest.mock import MagicMockimport numpy as npimport pytest+from PIL import Image+from mineru_vl_utils.structs import ContentBlock as VlmContentBlock+from mineru_vl_utils.structs import ExtractResultfrom mineru.backend import analyzefrom mineru.backend.utils.span_pre_proc import (@@ -60,6 +63,144 @@ def _build_post_ocr_page_block_lines(return page_block_lines_list, spans+def test_convert_vlm_results_to_model_list_uses_builtin_containers() -> None:+ """验证 VLM 容器子类会转换为原生 list/dict,且不会修改源块。"""+ source_block = VlmContentBlock(+ type=BlockType.TEXT,+ bbox=[0.1, 0.2, 0.8, 0.4],+ angle=0,+ content="原始文本",+ merge_prev=True,+ )+ source_page = ExtractResult([source_block], layout_scored=object())++ model_list = analyze._convert_vlm_results_to_model_list([source_page, ExtractResult()])++ assert type(model_list) is list+ assert all(type(page) is list for page in model_list)+ assert type(model_list[0][0]) is dict+ assert list(model_list[0][0]) == list(source_block)+ assert model_list[0][0] == dict(source_block)+ assert model_list[1] == []+ assert model_list[0] is not source_page+ assert model_list[0][0] is not source_block++ model_list[0][0]["content"] = "转换后文本"+ assert source_block["content"] == "原始文本"+++ ("effort", "parse_mode", "vlm_method_name"),+ [+ ("high", "txt", "batch_extract_with_layout"),+ ("high", "ocr", "batch_extract_with_layout"),+ ("xhigh", "txt", "batch_two_step_extract"),+ ("xhigh", "ocr", "batch_two_step_extract"),+ ],+)+def test_doc_analyze_converts_vlm_results_before_downstream_processing(+ monkeypatch: pytest.MonkeyPatch,+ effort: str,+ parse_mode: str,+ vlm_method_name: str,+) -> None:+ """验证 high/xhigh 的 TXT/OCR 路径都只向后续阶段传递原生 list/dict。"""+ source_block = VlmContentBlock(+ type=BlockType.PAGE_NUMBER,+ bbox=[0.45, 0.9, 0.55, 0.95],+ angle=0,+ content="1",+ )+ source_page = ExtractResult([source_block], layout_scored=object())+ fake_document = MagicMock()+ fake_document.page_count = 1+ fake_document.__getitem__.return_value = MagicMock(size=(612.0, 792.0))++ hybrid_model = MagicMock()+ hybrid_model.device = "cpu"+ hybrid_model.layout_model.batch_predict.return_value = [[]]+ hybrid_singleton = MagicMock()+ hybrid_singleton.get_model.return_value = hybrid_model++ vlm_predictor = MagicMock()+ getattr(vlm_predictor, vlm_method_name).return_value = [source_page]+ vlm_singleton = MagicMock()+ vlm_singleton.get_model.return_value = vlm_predictor+ serial_wrapper = MagicMock(return_value=vlm_predictor)+ page_image = Image.new("RGB", (64, 96), "white")++ def fake_process_text_and_formulas(+ _images_list: object,+ _pdf_pages: object,+ window_model_list: list[list[dict[str, object]]],+ _parse_mode: object,+ _effort: object,+ _hybrid_model: object,+ _images_layout_res: object,+ ) -> list[list[dict[str, object]]]:+ """原样返回窗口结果,并在后处理入口校验精确容器类型。"""+ assert type(window_model_list) is list+ assert all(type(page) is list for page in window_model_list)+ assert all(type(block) is dict for page in window_model_list for block in page)+ return window_model_list++ xhigh_normalizer = MagicMock(wraps=analyze._normalize_xhigh_vlm_blocks)+ monkeypatch.setattr(analyze, "PDFDocument", MagicMock(return_value=fake_document))+ monkeypatch.setattr(analyze, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))+ monkeypatch.setattr(+ analyze,+ "_load_vlm_runtime",+ MagicMock(+ return_value={+ "ModelSingleton": MagicMock(return_value=vlm_singleton),+ "_maybe_enable_serial_execution": serial_wrapper,+ }+ ),+ )+ monkeypatch.setattr(analyze, "get_vlm_engine", MagicMock(return_value="transformers"))+ monkeypatch.setattr(+ analyze,+ "load_images_from_pdf_bytes_range",+ MagicMock(return_value=[{"img_pil": page_image, "scale": 1.0}]),+ )+ monkeypatch.setattr(analyze, "_process_text_and_formulas", fake_process_text_and_formulas)+ monkeypatch.setattr(analyze, "_normalize_xhigh_vlm_blocks", xhigh_normalizer)+ monkeypatch.setattr(analyze, "_apply_seal_ocr", MagicMock())+ monkeypatch.setattr(analyze, "_supplement_missing_image_block_containers", MagicMock())+ monkeypatch.setattr(analyze, "_attach_visual_block_images", MagicMock())+ monkeypatch.setattr(analyze, "model_list_to_pages", MagicMock(return_value=[]))+ monkeypatch.setattr(analyze, "clean_memory", MagicMock())++ middle_json, model_list = analyze.doc_analyze(+ b"fake-pdf",+ effort=effort, # type: ignore[arg-type]+ parse_mode=parse_mode, # type: ignore[arg-type]+ )++ assert type(model_list) is list+ assert type(model_list[0]) is list+ assert type(model_list[0][0]) is dict+ assert model_list == [[{"type": BlockType.PAGE_NUMBER, "bbox": [0.45, 0.9, 0.55, 0.95], "content": "1"}]]+ assert middle_json["pages"] == []+ assert middle_json["effort"] == effort+ assert middle_json["parse_mode"] == parse_mode+ assert type(source_page) is ExtractResult+ assert type(source_block) is VlmContentBlock+ assert source_block["angle"] == 0++ if effort == "xhigh":+ xhigh_normalizer.assert_called_once()+ normalized_model_list = xhigh_normalizer.call_args.args[0]+ assert all(type(page) is list for page in normalized_model_list)+ assert all(type(block) is dict for page in normalized_model_list for block in page)+ vlm_predictor.batch_two_step_extract.assert_called_once()+ vlm_predictor.batch_extract_with_layout.assert_not_called()+ else:+ xhigh_normalizer.assert_not_called()+ vlm_predictor.batch_extract_with_layout.assert_called_once()+ vlm_predictor.batch_two_step_extract.assert_not_called()++def test_xhigh_vlm_blocks_normalize_visual_annotation_types() -> None:"""验证 xhigh VLM 的细分视觉标题和脚注会统一成通用类型。"""page_blocks = [