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: enhance analyze.py and visual magic model utilities for improved block processing and content handling
myhloli8ac855b7d80b
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex d63a9f6f..acadfb70 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -59,7 +59,7 @@ from mineru.utils.ocr_utils import (from mineru.utils.pdf_image_tools import load_images_from_pdf_bytes_range, get_crop_np_imgfrom tqdm import tqdm-from ..types import BBox, Block, BlockType, ContentType, Line, NOT_EXTRACT_TYPES, PageInfo, Span+from ..types import BBox, Block, BlockType, ContentType, Line, NOT_EXTRACT_TYPES, Spanfrom ..utils.config_reader import get_processing_window_sizefrom ..utils.pdf_document import PDFDocument, PDFPage, get_lines_from_chars@@ -2397,7 +2397,7 @@ def doc_analyze(image_analysis: bool = True,page_index_map: list[int] | None = None,file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",-) -> tuple[list[PageInfo], list[list[dict[str, Any]]]]:+):if file_suffix not in _SUPPORTED_FILE_SUFFIXES:raise ValueError(f"Unsupported file suffix: {file_suffix!r}")@@ -2612,7 +2612,7 @@ 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/demo2_page4.png"+ "/Users/myhloli/pdf/png/2407.00079v4_origi-10.pdf"]for file_path in demo_file_paths:@@ -2623,4 +2623,5 @@ if __name__ == "__main__":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}")+ logger.info(f"model_json: {model_json}")logger.info(f"model_list: {model_list}")diff --git a/mineru/backend/magic_model.py b/mineru/backend/magic_model.pyindex 1e17167c..178a897b 100644--- a/mineru/backend/magic_model.py+++ b/mineru/backend/magic_model.py@@ -1 +1,291 @@# Copyright (c) Opendatalab. All rights reserved.+import re+from typing import Any++from loguru import logger++from mineru.backend.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio+from mineru.backend.utils.visual_magic_model_utils import (+ code_content_clean,+ isolated_formula_clean,+ clean_content,+ fallback_inline_caption_fragments,+ fallback_leading_table_continuation_captions,+ VISUAL_MAIN_TYPES,+ regroup_visual_blocks,+)+from mineru.types import BlockType+from mineru.utils.guess_suffix_or_lang import guess_language_by_text+++def _has_inline_formula_content(content: str | None) -> bool:+ """判断 content 是否包含成对 <eq> 行内公式标记,用于 code/algorithm 分类。"""+ return bool(content) and content.count("<eq>") == content.count("</eq>") and content.count("<eq>") > 0+++class MagicModel:+ def __init__(+ self,+ page_model_list: list[dict[str, Any]],+ ) -> None:+ blocks = []+ is_block_has_bbox = False+ # 解析每个块+ for index, block_info in enumerate(page_model_list):++ if block_info.get("bbox"):+ is_block_has_bbox = True++ guess_lang = None+ code_block_sub_type = None+ block_type = block_info.get("type", "")+ block_content = block_info.get("content", "")++ if block_type in ["image_caption", "table_caption", "code_caption"]:+ block_type = BlockType.CAPTION+ elif block_type in ["image_footnote", "table_footnote"]:+ block_type = BlockType.FOOTNOTE+ elif block_type == "image":+ block_type = BlockType.IMAGE_BODY+ elif block_type == "table":+ block_type = BlockType.TABLE_BODY+ elif block_type == "chart":+ block_type = BlockType.CHART_BODY+ elif block_type in ["code", "algorithm"]:+ code_block_sub_type = block_type+ block_content = code_content_clean(block_content)+ block_type = BlockType.CODE_BODY+ elif block_type == "equation":+ block_type = BlockType.INTERLINE_EQUATION+ block_content = isolated_formula_clean(block_content)++ if block_type not in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CHART_BODY]:+ # 文本类块继续沿用现有 content 清洗规则,但不再拆分为 line/span。+ if block_content:+ block_content = clean_content(block_content) or ""+ # 对于标题类块,去除换行符和多余空格+ if block_type in [BlockType.TITLE, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE] and block_content:+ block_content = re.sub(r"\n\s*", " ", block_content).strip()+ # 处理 code/algorithm 分类的特殊情况:如果 code 类型的块中包含成对的行内公式标记,则将其分类为 algorithm。+ if (+ block_type == BlockType.CODE_BODY+ and code_block_sub_type == "code"+ and _has_inline_formula_content(block_content)+ ):+ code_block_sub_type = "algorithm"++ block = block_info+ block["type"] = block_type+ block["content"] = block_content+ if code_block_sub_type:+ block["sub_type"] = code_block_sub_type+ blocks.append(block)++ if is_block_has_bbox:+ fallback_inline_caption_fragments(blocks, VISUAL_MAIN_TYPES)+ fallback_leading_table_continuation_captions(blocks, VISUAL_MAIN_TYPES)+++ self.text_blocks = []+ self.ref_text_blocks = []+ self.list_blocks = []+ self.index_blocks = []++ for block in blocks:+ if block.type == BlockType.TEXT:+ self.text_blocks.append(block)+ elif block.type == BlockType.REF_TEXT:+ self.ref_text_blocks.append(block)+ elif block.type == BlockType.LIST:+ self.list_blocks.append(block)+ elif block.type == BlockType.INDEX:+ self.index_blocks.append(block)++ if is_block_has_bbox:+ self.list_blocks, self.text_blocks, self.ref_text_blocks = fix_pdf_list_blocks(+ self.list_blocks,+ self.text_blocks,+ self.ref_text_blocks,+ )+ self.index_blocks = fix_pdf_index_blocks(self.index_blocks)+ else:+ self.list_blocks = fix_office_list_blocks(self.list_blocks)+ self.index_blocks = fix_office_index_blocks(self.index_blocks)+++ visual_groups, unmatched_child_blocks = regroup_visual_blocks(blocks)+ self.image_blocks = visual_groups[BlockType.IMAGE]+ self.table_blocks = visual_groups[BlockType.TABLE]+ self.chart_blocks = visual_groups[BlockType.CHART]+ self.code_blocks = visual_groups[BlockType.CODE]++ for code_block in self.code_blocks:+ if code_block.sub_type == "code":+ for sub_block in code_block["blocks"]:+ if sub_block.get("type") == BlockType.CODE_BODY:+ guess_lang = guess_language_by_text(sub_block.get("content", ""))+ code_block.guess_lang = guess_lang+ break++ for block in unmatched_child_blocks:+ block.type = BlockType.TEXT+++def fix_pdf_list_blocks(+ list_blocks, text_blocks, ref_text_blocks+):+ for list_block in list_blocks:+ list_block["content"] = []++ temp_text_blocks = text_blocks + ref_text_blocks+ need_remove_blocks = []+ for block in temp_text_blocks:+ for list_block in list_blocks:+ if (+ calculate_overlap_area_in_bbox1_area_ratio(+ block.bbox,+ list_block.bbox,+ )+ >= 0.8+ ):+ list_block["content"].append(block)+ need_remove_blocks.append(block)+ break++ for block in need_remove_blocks:+ if block in text_blocks:+ text_blocks.remove(block)+ elif block in ref_text_blocks:+ ref_text_blocks.remove(block)++ list_blocks = [lb for lb in list_blocks if lb["content"]]++ for list_block in list_blocks:+ type_count = {}+ for sub_block in list_block["content"]:+ sub_block_type = sub_block.type+ if sub_block_type not in type_count:+ type_count[sub_block_type] = 0+ type_count[sub_block_type] += 1++ if type_count:+ list_block["sub_type"] = max(type_count, key=type_count.get) # type: ignore+ else:+ list_block["sub_type"] = "text"++ return list_blocks, text_blocks, ref_text_blocks+++def fix_pdf_index_blocks(index_blocks):+ """将 PDF 目录块的多行内容拆分为多个文本子块。"""+ for index_block in index_blocks:+ index_block["content"] = [+ {"type": "text", "content": content}+ for content in index_block["content"].split("\n")+ ]++ return index_blocks+++def fix_office_index_blocks(index_blocks):+ """递归移除 Office 目录块及其子块中的 ilevel 字段。"""+ pending_blocks = list(index_blocks)+ while pending_blocks:+ block = pending_blocks.pop()+ block.pop("ilevel", None)++ content = block.get("content")+ if isinstance(content, list):+ pending_blocks.extend(+ child_block+ for child_block in content+ if isinstance(child_block, dict)+ )++ return index_blocks+++def fix_office_list_blocks(+ list_blocks: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ """将 Office 列表层级和起始序号写入文本内容,并移除原始列表元数据。"""++ def get_list_ilevel(list_block: dict[str, Any], parent_ilevel: int | None) -> int:+ """读取列表层级,非法值按当前结构中的递归深度回退。"""+ fallback_ilevel = 0 if parent_ilevel is None else parent_ilevel + 1+ try:+ ilevel = int(list_block.get("ilevel"))+ except (TypeError, ValueError):+ return fallback_ilevel+ return ilevel if ilevel >= 0 else fallback_ilevel++ def get_ordered_list_start(list_block: dict[str, Any]) -> int:+ """读取有序列表起始编号,保留合法的 0 并将非法值回退为 1。"""+ start = list_block.get("start")+ if start is None:+ return 1+ try:+ start = int(start)+ except (TypeError, ValueError):+ return 1+ return start if start >= 0 else 1++ def format_ordered_prefix(ordered_numbers: dict[int, int]) -> str:+ """按列表层级拼接有序编号,单级编号保留末尾句点。"""+ number_parts = [str(number) for _, number in sorted(ordered_numbers.items())]+ if len(number_parts) == 1:+ return f"{number_parts[0]}. "+ return f"{'.'.join(number_parts)} "++ def fix_list_block(+ list_block: dict[str, Any],+ inherited_ordered_numbers: dict[int, int],+ parent_ilevel: int | None,+ ) -> None:+ """递归处理单个列表块,并把当前位置的有序编号传给嵌套列表。"""+ ilevel = get_list_ilevel(list_block, parent_ilevel)+ base_ordered_numbers = {+ level: number+ for level, number in inherited_ordered_numbers.items()+ if level < ilevel+ }+ active_ordered_numbers = dict(base_ordered_numbers)+ is_ordered = list_block.get("attribute") == "ordered"+ ordered_number = get_ordered_list_start(list_block)++ content = list_block.get("content")+ if isinstance(content, list):+ for child_block in content:+ if not isinstance(child_block, dict):+ continue++ child_type = child_block.get("type")+ if child_type == BlockType.TEXT:+ child_content = child_block.get("content")+ if not isinstance(child_content, str):+ continue++ if is_ordered:+ active_ordered_numbers = dict(base_ordered_numbers)+ active_ordered_numbers[ilevel] = ordered_number+ prefix = format_ordered_prefix(active_ordered_numbers)+ ordered_number += 1+ else:+ prefix = "- "+ child_block["content"] = f"{prefix}{child_content}"+ elif child_type == BlockType.LIST:+ fix_list_block(+ child_block,+ dict(active_ordered_numbers),+ ilevel,+ )++ list_block.pop("attribute", None)+ list_block.pop("ilevel", None)+ list_block.pop("start", None)++ for list_block in list_blocks:+ if isinstance(list_block, dict):+ fix_list_block(list_block, {}, None)++ return list_blocksdiff --git a/mineru/backend/model_list_to_midlle_json.py b/mineru/backend/model_list_to_midlle_json.pyindex f64ba567..7b8a3a0c 100644--- a/mineru/backend/model_list_to_midlle_json.py+++ b/mineru/backend/model_list_to_midlle_json.py@@ -1 +1,97 @@-# Copyright (c) Opendatalab. All rights reserved.\ No newline at end of file+# Copyright (c) Opendatalab. All rights reserved.+from typing import Any+from mineru.backend.magic_model import MagicModel+++def model_list_to_pages(+ model_list: list[list[dict[str, Any]]],+ page_index_map: list[int] | None = None,+):+ """将 model_list 转换为 pages"""+ if page_index_map is None:+ page_index_map = list(range(len(model_list)))+ pages: list[list[dict[str, Any]]] = []+ for page_model_list, page_index in zip(model_list, page_index_map):+ page_info = blocks_to_page_info(+ page_model_list,+ )+ page_info["page_idx"] = page_index+ pages.append(page_info)+ return pages+++def blocks_to_page_info(+ page_model_list: list[dict[str, Any]],+):+ """将blocks转换为页面信息"""+ magic_model = MagicModel(+ page_model_list,+ )+ image_blocks = magic_model.get_image_blocks()+ table_blocks = magic_model.get_table_blocks()+ chart_blocks = magic_model.get_chart_blocks()+ title_blocks = magic_model.get_title_blocks()+ discarded_blocks = magic_model.get_discarded_blocks()+ code_blocks = magic_model.get_code_blocks()+ ref_text_blocks = magic_model.get_ref_text_blocks()+ phonetic_blocks = magic_model.get_phonetic_blocks()+ list_blocks = magic_model.get_list_blocks()++ text_blocks = magic_model.get_text_blocks()+ interline_equation_blocks = magic_model.get_interline_equation_blocks()++ page_blocks = []+ page_blocks.extend(+ [+ *image_blocks,+ *table_blocks,+ *chart_blocks,+ *code_blocks,+ *ref_text_blocks,+ *phonetic_blocks,+ *title_blocks,+ *text_blocks,+ *interline_equation_blocks,+ *list_blocks,+ ]+ )+ # 对page_blocks根据index的值进行排序+ page_blocks.sort(key=lambda x: x.index)++ cut_visual_spans_in_blocks(+ [*page_blocks, *discarded_blocks],+ page_pil_img,+ page_index,+ scale=scale,+ image_cache=image_cache,+ )++ page_info = PageInfo(+ blocks=[*page_blocks, *discarded_blocks],+ page_idx=page_index,+ _backend="hybrid",+ )+ return page_info+++def finalize_middle_json_from_preproc(pages: list[PageInfo], effort: str = DEFAULT_HYBRID_EFFORT) -> None:+ """从 Hybrid preproc_blocks 执行完整 finalize,供服务端完整路径和客户端复用。"""+ effort = validate_effort(effort)+ build_para_blocks_from_preproc(pages)+ merge_para_text_blocks(+ pages,+ auto_merge_by_det=True,+ auto_merge_vertical_by_det=effort in {LOCAL_HYBRID_EFFORT, LAYOUT_HYBRID_EFFORT},+ )++ cross_page_table_merge(pages)++ apply_title_leveling_to_pdf_info(pages)+ cleanup_internal_para_block_metadata(pages)+++def finalize_middle_json(+ pages: list[PageInfo],+ effort: str = DEFAULT_HYBRID_EFFORT,+) -> None:+ finalize_middle_json_from_preproc(pages, effort=effort)diff --git a/mineru/backend/utils/content_block_draft.py b/mineru/backend/utils/content_block_draft.pyindex 96dba86e..fe1be49f 100644--- a/mineru/backend/utils/content_block_draft.py+++ b/mineru/backend/utils/content_block_draft.py@@ -18,7 +18,7 @@ class VlmContentBlockDraft:merge_prev: bool = Falsesub_type: str | None = Nonecell_merge: list[int] = field(default_factory=list)- ocr_det_lines: list[OcrDetLineItem] = field(default_factory=list)+ ocr_det_lines: list[dict] = field(default_factory=list)line_avg_height: int = 0@classmethod@@ -44,6 +44,5 @@ class VlmContentBlockDraft:merge_prev=bool(content_block.get("merge_prev", False)),sub_type=content_block.get("sub_type"),cell_merge=list(content_block.get("cell_merge") or []),- ocr_det_lines=content_block.get("_ocr_det_lines", []),- line_avg_height=content_block.get("_line_avg_height", 0),+ _lines=content_block.get("_lines", []),)diff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.pyindex 11be3d97..960cfb54 100644--- a/mineru/backend/utils/visual_magic_model_utils.py+++ b/mineru/backend/utils/visual_magic_model_utils.py@@ -6,7 +6,7 @@ from copy import deepcopyfrom typing import Anyfrom ...types import BBox, Block, BlockType-from .boxbase import bbox_center_distance, bbox_distance, calculate_overlap_area_in_bbox1_area_ratio+from .boxbase import bbox_center_distance, bbox_distancefrom .table_continuation import is_table_continuation_textIMAGE_BLOCK_BODY = "image_block_body"@@ -351,9 +351,7 @@ def is_inline_caption_fragment(previous_caption: Block, text_block: Block, next_def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]], list[Block]]:ordered_blocks = sorted(blocks, key=lambda x: x.index or 0)- absorbed_member_indices, sub_images_by_index = absorb_image_block_members(ordered_blocks)- effective_blocks = [block for block in ordered_blocks if block.index not in absorbed_member_indices]- visual_relation_blocks = [block for block in effective_blocks if not is_transparent_visual_relation_block(block)]+ visual_relation_blocks = [block for block in ordered_blocks if not is_transparent_visual_relation_block(block)]position_by_index = {block.index: pos for pos, block in enumerate(visual_relation_blocks)}main_blocks = [block for block in visual_relation_blocks if block.type in VISUAL_MAIN_TYPES]child_blocks = [block for block in visual_relation_blocks if block.type in GENERIC_CHILD_TYPES]@@ -363,10 +361,6 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],}unmatched_child_blocks = []- for main_block in main_blocks:- if main_block.index in sub_images_by_index:- main_block._sub_images = sub_images_by_index[main_block.index]-for child_block in child_blocks:parent_block = find_best_visual_parent(child_block,@@ -393,7 +387,6 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],mapping = VISUAL_TYPE_MAPPING[visual_type]body_block = deepcopy(main_block)body_block.type = mapping["body"]- body_block._sub_images = []body_block.sub_type = ""captions = []@@ -422,8 +415,6 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],)if visual_type in [BlockType.IMAGE, BlockType.CHART] and main_block.sub_type:two_layer_block.sub_type = main_block.sub_type- if visual_type == BlockType.IMAGE and main_block._sub_images:- two_layer_block._sub_images = main_block._sub_imagesif visual_type == BlockType.TABLE and main_block._cell_merge:two_layer_block._cell_merge = main_block._cell_mergetwo_layer_block.blocks.sort(key=lambda x: x.index or 0)@@ -436,54 +427,6 @@ def regroup_visual_blocks(blocks: list[Block]) -> tuple[dict[Any, list[Block]],return grouped_blocks, unmatched_child_blocks-def absorb_image_block_members(blocks: list[Block]) -> tuple[set[int], dict[int, list[Block]]]:- image_block_bodies = [block for block in blocks if block.type == IMAGE_BLOCK_BODY]- member_candidates = [block for block in blocks if block.type in [BlockType.IMAGE_BODY, BlockType.CHART_BODY]]-- assignments = {}- for member in member_candidates:- best_key = None- best_parent_index = None- for image_block in image_block_bodies:- overlap_ratio = calculate_overlap_area_in_bbox1_area_ratio(- member.bbox,- image_block.bbox,- )- if overlap_ratio < 0.9:- continue-- candidate_key = (- -overlap_ratio,- bbox_area(image_block.bbox),- image_block.index,- )- if best_key is None or candidate_key < best_key:- best_key = candidate_key- best_parent_index = image_block.index-- if best_parent_index is not None:- assignments[member.index] = best_parent_index-- absorbed_member_indices = set()- sub_images_by_index = {}- for image_block in image_block_bodies:- members = [member for member in member_candidates if assignments.get(member.index) == image_block.index]- if not members:- continue-- members.sort(key=lambda x: x.index or 0)- absorbed_member_indices.update(member.index for member in members)- sub_images_by_index[image_block.index] = [- {- "type": child_visual_type(member.type),- "bbox": relative_bbox(member.bbox, image_block.bbox),- }- for member in members- ]-- return absorbed_member_indices, sub_images_by_index--def find_best_visual_parent(child_block: Block,main_blocks: list[Block],@@ -680,29 +623,3 @@ def child_kind_from_type(block_type: str) -> str:if block_type == BlockType.CAPTION:return "caption"return "footnote"---def child_visual_type(block_type: str) -> str:- if block_type == BlockType.CHART_BODY:- return BlockType.CHART- return BlockType.IMAGE---def bbox_area(bbox: BBox) -> float:- return max(0, bbox[2] - bbox[0]) * max(0, bbox[3] - bbox[1])---def relative_bbox(child_bbox: BBox, parent_bbox: BBox) -> BBox:- parent_x0, parent_y0, parent_x1, parent_y1 = parent_bbox- parent_w = max(parent_x1 - parent_x0, 1)- parent_h = max(parent_y1 - parent_y0, 1)- return (- clamp_and_round((child_bbox[0] - parent_x0) / parent_w),- clamp_and_round((child_bbox[1] - parent_y0) / parent_h),- clamp_and_round((child_bbox[2] - parent_x0) / parent_w),- clamp_and_round((child_bbox[3] - parent_y0) / parent_h),- )---def clamp_and_round(value: float) -> float:- return round(min(max(value, 0.0), 1.0), 3)