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 OCR processing by removing unused types and optimizing block handling
myhloli6201e3b0c974
diff --git a/mineru/backend/hybrid/analyze.py b/mineru/backend/hybrid/analyze.pyindex 08bdf557..4f4dec9f 100644--- a/mineru/backend/hybrid/analyze.py+++ b/mineru/backend/hybrid/analyze.py@@ -129,7 +129,6 @@ PIPELINE_DET_TYPE = {VLM_TXT_DET_TYPE = NOT_EXTRACT_TYPESVLM_OCR_DET_TYPE = {BlockType.TEXT,- BlockType.TITLE,BlockType.DOC_TITLE,BlockType.PARAGRAPH_TITLE,}@@ -2345,8 +2344,8 @@ def doc_analyze(if __name__ == "__main__":# pdf_path = "/Users/myhloli/pdf/截断合并/demo1-3.pdf"- pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png- # pdf_path = "/Users/myhloli/pdf/demo1.pdf"+ # pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png+ pdf_path = "/Users/myhloli/pdf/demo1.pdf"pdf_bytes = read_fn(pdf_path)middle_json, model_list = doc_analyze(pdf_bytes, effort="medium")logger.info(f"middle_json: {middle_json}")diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 5c449ba7..0b2da513 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -1,21 +1,15 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations-import copyimport refrom typing import Anyfrom loguru import logger-from PIL import Image-from ...types import EMPTY_BBOX, NOT_EXTRACT_TYPES, BBox, Block, BlockType, ContentType, IntBBox, Line, Span+from ...types import BBox, Block, BlockType, ContentType, Line, Spanfrom ...utils.guess_suffix_or_lang import guess_language_by_text-from ...utils.image_payload import ImagePayloadCache-from ...utils.pdf_document import PDFPagefrom ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom ..utils.content_block_draft import VlmContentBlockDraft-from ..utils.span_block_fix import fix_text_block-from ..utils.span_pre_proc import SpanBlockMatcher, txt_spans_extractfrom ..utils.visual_magic_model_utils import (GENERIC_CHILD_TYPES,IMAGE_BLOCK_BODY,@@ -28,32 +22,6 @@ from ..utils.visual_magic_model_utils import (regroup_visual_blocks,)-not_extract_list = [- *NOT_EXTRACT_TYPES,- BlockType.CAPTION,- BlockType.FOOTNOTE,- BlockType.DOC_TITLE,- BlockType.PARAGRAPH_TITLE,-]--OCR_DET_LINE_BLOCK_TYPES = {- *not_extract_list,- BlockType.LIST,- BlockType.INDEX,- BlockType.ABSTRACT,- BlockType.ASIDE_TEXT,- BlockType.PHONETIC,- BlockType.CHART_CAPTION,- BlockType.CHART_FOOTNOTE,- BlockType.CODE_FOOTNOTE,-}---EMPTY_CONTENT_INLINE_FILL_BLOCK_TYPES = {- BlockType.INDEX,- BlockType.CODE_BODY,-}-def _has_inline_formula_content(content: str | None) -> bool:"""判断 content 是否包含可安全拆分的成对行内公式标记。"""@@ -88,64 +56,6 @@ def _split_inline_formula_content_to_spans(content: str | None, bbox: BBox) -> lreturn spans-def _should_fill_empty_content_from_spans(- block_type: str,- block_content: str | None,- use_vlm_text_content: bool,-) -> bool:- """判断空内容块是否需要复用 OCR/PDF span 回填,避免生成空目录或空代码块。"""- return (- block_type in EMPTY_CONTENT_INLINE_FILL_BLOCK_TYPES- and not use_vlm_text_content- and not (block_content or "").strip()- )---def _line_to_inline_formula_content(line: Line) -> str:- """将一行中的文本和行内公式 span 拼回统一 content 字符串。"""- parts: list[str] = []- for span in line.spans:- if span.type == ContentType.TEXT:- parts.append(span.content or "")- elif span.type == ContentType.INLINE_EQUATION and span.content:- parts.append(f"\\({span.content}\\)")- return "".join(parts)---def _collapse_lines_to_inline_content_spans(block: Block) -> None:- """将多行回填结果折叠为一个 line,并复用统一规则拆分文本和行内公式 span。"""- line_texts: list[str] = []- for line in block.lines:- line_text = _line_to_inline_formula_content(line)- if line_text.strip():- line_texts.append(line_text)- if not line_texts:- block.lines = []- return-- content = "\n".join(line_texts)- spans = _split_inline_formula_content_to_spans(content, block.bbox)- block.lines = [- Line(- bbox=block.bbox,- spans=spans,- )- ]---def _code_body_has_inline_formula(block: Block) -> bool:- """判断代码块回填后的 span 是否包含行内公式,用于决定是否升级为 algorithm。"""- return any(span.type == ContentType.INLINE_EQUATION for line in block.lines for span in line.spans)---def _ensure_code_body_metadata_line(block: Block, code_type: str | None, guess_lang: str | None) -> None:- """为空代码块补一行元数据,确保父 code block 能保留 code/algorithm 子类型。"""- if not block.lines:- block.lines = [Line(spans=[Span(type=ContentType.TEXT, bbox=block.bbox, content="")], bbox=block.bbox)]- block.lines[0]._code_type = code_type- block.lines[0]._code_guess_lang = guess_lang--def _copy_raw_text_block_metadata(draft: VlmContentBlockDraft, block: Block) -> None:if draft.raw_type != BlockType.TEXT:return@@ -156,69 +66,16 @@ class MagicModel:def __init__(self,page_model_list: list[dict[str, Any]],- pdf_page: PDFPage,- scale: float,- page_pil_img: Image.Image,width: int,height: int,- _ocr_enable: bool,- use_vlm_text_content: bool | None = None,- _vlm_ocr_enable: bool | None = None,- image_cache: ImagePayloadCache | None = None,) -> None:- if use_vlm_text_content is None:- use_vlm_text_content = bool(_vlm_ocr_enable)- # 表格 HTML 内联图片在 middle_json 公开输出前统一外置到图片缓存。- self.image_cache = image_cache or ImagePayloadCache()- (- page_blocks,- self.page_inline_formula,- self.page_ocr_res,- ) = self._split_page_model_list(copy.deepcopy(page_model_list))-self.width = widthself.height = heightblocks: list[Block] = []- page_text_inline_formula_spans: list[Span] = []-- for inline_formula in self.page_inline_formula:- inline_formula["bbox"] = self.cal_real_bbox(inline_formula["bbox"])- inline_formula_latex = inline_formula.pop("latex", "")- if inline_formula_latex:- page_text_inline_formula_spans.append(- Span(- type=ContentType.INLINE_EQUATION,- bbox=inline_formula["bbox"],- content=inline_formula_latex,- score=inline_formula["score"],- )- )- for ocr_res in self.page_ocr_res:- ocr_res["bbox"] = self.cal_real_bbox(ocr_res["bbox"])- page_text_inline_formula_spans.append(- Span(- type=ContentType.TEXT,- bbox=ocr_res["bbox"],- content=ocr_res.get("text", ""),- score=ocr_res["score"],- )- )- if not use_vlm_text_content and not _ocr_enable:- # Bad code- virtual_block = (0, 0, width, height, None, None, None, "text")- page_text_inline_formula_spans = txt_spans_extract(- pdf_page,- page_text_inline_formula_spans,- page_pil_img,- scale,- [virtual_block],- [],- )- span_matcher = SpanBlockMatcher(page_text_inline_formula_spans)# 解析每个块- for index, block_info in enumerate(page_blocks):+ for index, block_info in enumerate(page_model_list):try:draft = VlmContentBlockDraft.from_content_block(block_info, width, height)block_bbox = draft.bbox@@ -232,32 +89,14 @@ class MagicModel:logger.warning(f"Invalid block format: {block_info}, error: {e}")continue- span_type = "unknown"+ span_type = ""code_block_sub_type = Noneguess_lang = None- if block_type in [- "text",- "index",- "title",- "doc_title",- "paragraph_title",- "ref_text",- "phonetic",- "header",- "footer",- "page_number",- "aside_text",- "page_footnote",- "list",- ]:- span_type = ContentType.TEXT- elif block_type in ["image_caption", "table_caption", "code_caption"]:+ if block_type in ["image_caption", "table_caption", "code_caption"]:block_type = BlockType.CAPTION- span_type = ContentType.TEXTelif block_type in ["image_footnote", "table_footnote"]:block_type = BlockType.FOOTNOTE- span_type = ContentType.TEXTelif block_type == "image":block_type = BlockType.IMAGE_BODYspan_type = ContentType.IMAGE@@ -274,30 +113,18 @@ class MagicModel:block_content = code_content_clean(block_content)code_block_sub_type = block_typeblock_type = BlockType.CODE_BODY- span_type = ContentType.TEXTguess_lang = guess_language_by_text(block_content)elif block_type == "equation":block_type = BlockType.INTERLINE_EQUATIONspan_type = ContentType.INTERLINE_EQUATION- if span_type == ContentType.TEXT and block_content is None:- # 文本类块缺失 content 时按空文本处理,避免 VLM 渲染阶段遇到 None。- block_content = ""- fill_empty_content_from_spans = _should_fill_empty_content_from_spans(- block_type,- block_content,- use_vlm_text_content,- )-# code 和 algorithm 类型的块,如果内容中包含行内公式,则需要将块类型切换为 algorithmswitch_code_to_algorithm = Falsespan = Noneif span_type in [ContentType.IMAGE, ContentType.TABLE, ContentType.CHART]:span = Span(type=span_type, bbox=block_bbox)- if span_type == ContentType.TABLE and block_content is not None:- span.content = self.image_cache.replace_html_data_uri_sources(block_content)- elif raw_block_type in ["image", "chart"] and block_content is not None:+ if raw_block_type in ["table", "image", "chart"] and block_content is not None:span.content = block_contentelif span_type == ContentType.INTERLINE_EQUATION:span = Span(@@ -305,9 +132,8 @@ class MagicModel:bbox=block_bbox,content=isolated_formula_clean(block_content or ""),)- elif not fill_empty_content_from_spans and (use_vlm_text_content or block_type not in not_extract_list):- # 使用 VLM 文本内容时,所有文本块都直接消费 block content。- # 非 VLM 文本路径下,非提取块仍沿用直接内容模式。+ else:+ # 所有文本块都直接消费 block content。if block_content:block_content = clean_content(block_content)@@ -320,59 +146,37 @@ class MagicModel:span = _split_inline_formula_content_to_spans(block_content, block_bbox)else:span = Span(- type=span_type,+ type=ContentType.TEXT,bbox=block_bbox,content=block_content or "",)- if span_type in [- ContentType.IMAGE,- ContentType.TABLE,- ContentType.CHART,- ContentType.INTERLINE_EQUATION,- ] or (not fill_empty_content_from_spans and (use_vlm_text_content or block_type not in not_extract_list)):- if span is None:- continue- if isinstance(span, Span):- spans = [span]- elif isinstance(span, list):- spans = span- else:- raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")+ if span is None:+ continue+ if isinstance(span, Span):+ spans = [span]+ elif isinstance(span, list):+ spans = span+ else:+ raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")- if block_type == BlockType.CODE_BODY:- if switch_code_to_algorithm and code_block_sub_type == "code":- code_block_sub_type = "algorithm"- line = Line(spans=spans, bbox=block_bbox, _code_type=code_block_sub_type, _code_guess_lang=guess_lang)- else:- line = Line(spans=spans, bbox=block_bbox)-- block = Block(index=index, type=block_type, bbox=block_bbox, lines=[line], angle=block_angle)- if block_sub_type:- block.sub_type = block_sub_type- if raw_block_type == "table" and draft.cell_merge:- block._cell_merge = draft.cell_merge- if use_vlm_text_content and self._supports_ocr_det_lines(block_type):- ocr_det_lines = self._build_ocr_det_lines(span_matcher.collect_for_block(block_bbox))- if ocr_det_lines:- block._ocr_det_lines = ocr_det_lines- _copy_raw_text_block_metadata(draft, block)+ if block_type == BlockType.CODE_BODY:+ if switch_code_to_algorithm and code_block_sub_type == "code":+ code_block_sub_type = "algorithm"+ line = Line(spans=spans, bbox=block_bbox, _code_type=code_block_sub_type, _code_guess_lang=guess_lang)else:- block_spans = span_matcher.collect_for_block(block_bbox)- block = Block(index=index, type=block_type, bbox=block_bbox, angle=block_angle)- block._fix_spans = block_spans- block = fix_text_block(block)- if fill_empty_content_from_spans:- _collapse_lines_to_inline_content_spans(block)- if block_type == BlockType.CODE_BODY:- if code_block_sub_type == BlockType.CODE and _code_body_has_inline_formula(block):- code_block_sub_type = BlockType.ALGORITHM- _ensure_code_body_metadata_line(block, code_block_sub_type, guess_lang)- _copy_raw_text_block_metadata(draft, block)-- if block.type == BlockType.INDEX:- # Hybrid VLM 路径使用 INDEX 作为 content 内部哨兵;内容构造完成后再对齐 3.4 输出为 text。- block.type = BlockType.TEXT+ line = Line(spans=spans, bbox=block_bbox)++ block = Block(index=index, type=block_type, bbox=block_bbox, lines=[line], angle=block_angle)+ if block_sub_type:+ block.sub_type = block_sub_type+ if raw_block_type == "table" and draft.cell_merge:+ block._cell_merge = draft.cell_merge+ if block_type == BlockType.TEXT:+ block._ocr_det_lines = draft.ocr_det_lines+ if block_type in [BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE]:+ block._line_avg_height = draft.line_avg_height+ _copy_raw_text_block_metadata(draft, block)blocks.append(block)@@ -449,58 +253,6 @@ class MagicModel:block.type = BlockType.TEXTself.text_blocks.append(block)- @staticmethod- def _split_page_model_list(- page_model_list: list[dict[str, Any]],- ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:- page_blocks = []- page_inline_formula = []- page_ocr_res = []-- for item in page_model_list:- item_type = item.get("type") or item.get("label")- if item_type == "inline_formula":- page_inline_formula.append(item)- elif item_type == "ocr_text":- page_ocr_res.append(item)- else:- page_blocks.append(item)-- return page_blocks, page_inline_formula, page_ocr_res-- @staticmethod- def _supports_ocr_det_lines(block_type: str) -> bool:- """判断当前块类型是否需要保留 OCR det 行提示供 Hybrid 段落合并使用。"""- return block_type in OCR_DET_LINE_BLOCK_TYPES-- @staticmethod- def _build_ocr_det_lines(block_spans: list[Span]) -> list[Line]:- """将 OCR det span 聚合成 line,但不改变 VLM-OCR 的 canonical 文本内容。"""- if not block_spans:- return []-- fix_block = Block(- index=0,- type="",- bbox=EMPTY_BBOX,- _fix_spans=copy.deepcopy(block_spans),- )- return fix_text_block(fix_block).lines-- def cal_real_bbox(self, bbox: BBox) -> IntBBox:- x1, y1, x2, y2 = bbox- x_1, y_1, x_2, y_2 = (- int(x1 * self.width),- int(y1 * self.height),- int(x2 * self.width),- int(y2 * self.height),- )- if x_2 < x_1:- x_1, x_2 = x_2, x_1- if y_2 < y_1:- y_1, y_2 = y_2, y_1- return (x_1, y_1, x_2, y_2)-def get_list_blocks(self) -> list[Block]:return self.list_blocksdiff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.pyindex d18b263c..c7a12c0d 100644--- a/mineru/backend/hybrid/model_output_to_middle_json.py+++ b/mineru/backend/hybrid/model_output_to_middle_json.py@@ -44,19 +44,11 @@ def blocks_to_page_info(image_dict: dict[str, Any],pdf_page: PDFPage,page_index: int,- _ocr_enable: bool,- use_vlm_text_content: bool | None = None,image_cache: ImagePayloadCache | None = None,- _vlm_ocr_enable: bool | None = None,) -> PageInfo:"""将blocks转换为页面信息"""- if use_vlm_text_content is None:- use_vlm_text_content = bool(_vlm_ocr_enable)-- page_model_list = optimize_hybrid_formula_number_blocks(page_model_list)scale = image_dict["scale"]page_pil_img = image_dict["img_pil"]- page_img_md5 = bytes_md5(page_pil_img.tobytes())page_size = getattr(pdf_page, "size", None)if page_size is None and hasattr(pdf_page, "get_size"):page_size = pdf_page.get_size()@@ -64,14 +56,8 @@ def blocks_to_page_info(magic_model = MagicModel(page_model_list,- pdf_page,- scale,- page_pil_img,width,height,- _ocr_enable,- use_vlm_text_content,- image_cache=image_cache,)image_blocks = magic_model.get_image_blocks()table_blocks = magic_model.get_table_blocks()diff --git a/mineru/backend/utils/content_block_draft.py b/mineru/backend/utils/content_block_draft.pyindex 41836778..96dba86e 100644--- a/mineru/backend/utils/content_block_draft.py+++ b/mineru/backend/utils/content_block_draft.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import Any, Mapping-from ...types import BBox+from ...types import BBox, OcrDetLineItem@dataclass(slots=True)@@ -18,6 +18,8 @@ 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)+ line_avg_height: int = 0@classmethoddef from_content_block(cls, content_block: Mapping[str, Any], width: int, height: int) -> VlmContentBlockDraft:@@ -42,4 +44,6 @@ 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),)diff --git a/mineru/types.py b/mineru/types.pyindex dc5dcaee..fb3c4e0f 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import MISSING, Field, InitVar, dataclass, field, fields-from typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hints+from typing import Any, Iterator, Literal, TypeAlias, TypeVar, get_type_hints, TypedDictT = TypeVar("T", bound="_DocElement")@@ -415,6 +415,14 @@ class Line(_DocElement):_code_guess_lang: str | None = None+@dataclass+class OcrDetLineItem(TypedDict):+ """OCR 检测得到的归一化行框。"""++ bbox: list[float]+ type: Literal["line"]++@dataclassclass Block(_DocElement):"""A layout block on a page. May nest child blocks (e.g. list items, image body)."""@@ -451,7 +459,7 @@ class Block(_DocElement):_merge_prev: bool = False_is_numbered_style: bool = False_lines_deleted: bool = False- _ocr_det_lines: list[Line] = field(default_factory=list)+ _ocr_det_lines: list[OcrDetLineItem] = field(default_factory=list)_line_avg_height: int = 0_cell_merge: list[int] = field(default_factory=list)_fix_spans: list[Span] = field(default_factory=list)