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
refactor: introduce NotExtractType enum for improved block type management in hybrid processing
myhlolia3d2d9a64daf
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex 7d1d840c..9a10d61b 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -12,7 +12,7 @@ from mineru.backend.hybrid.hybrid_model_output_to_middle_json import result_to_mfrom mineru.backend.pipeline.model_init import HybridModelSingletonfrom mineru.backend.vlm.vlm_analyze import ModelSingletonfrom mineru.data.data_reader_writer import DataWriter-from mineru.utils.enum_class import ImageType+from mineru.utils.enum_class import ImageType, NotExtractTypefrom mineru.utils.model_utils import crop_imgfrom mineru.utils.ocr_utils import get_adjusted_mfdetrec_res, get_ocr_result_list, sorted_boxes, merge_det_boxes, \update_det_boxes, OcrConfidence@@ -25,20 +25,7 @@ os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新MFR_BASE_BATCH_SIZE = 16OCR_DET_BASE_BATCH_SIZE = 16-not_extract_list = [- BlockType.TEXT,- BlockType.TITLE,- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,- BlockType.REF_TEXT,- BlockType.TABLE_CAPTION,- BlockType.IMAGE_CAPTION,- BlockType.TABLE_FOOTNOTE,- BlockType.IMAGE_FOOTNOTE,- BlockType.CODE_CAPTION,-]+not_extract_list = [item.value for item in NotExtractType]def ocr_classify(pdf_bytes, parse_method: str = 'auto',) -> bool:# 确定OCR设置@@ -340,6 +327,7 @@ async def doc_analyze_core(image_writer,_ocr_enable,_vlm_ocr_enable,+ hybrid_pipeline_model,)return middle_json, resultsdiff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 095e3515..0640931f 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -4,11 +4,13 @@ from typing import Literalfrom loguru import loggerfrom mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio-from mineru.utils.enum_class import ContentType, BlockType+from mineru.utils.enum_class import ContentType, BlockType, NotExtractTypefrom mineru.utils.guess_suffix_or_lang import guess_language_by_textfrom mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_distance_v3+from mineru.utils.span_block_fix import fix_text_blockfrom mineru.utils.span_pre_proc import txt_spans_extract+not_extract_list = [item.value for item in NotExtractType]class MagicModel:def __init__(self,@@ -54,9 +56,7 @@ class MagicModel:"content": ocr_res["text"],"score": ocr_res["score"],})- if _ocr_enable:- pass- else:+ if not _ocr_enable:virtual_block = [0, 0, width, height, None, None, None, "text"]page_text_inline_formula_spans = txt_spans_extract(page, page_text_inline_formula_spans, page_pil_img, scale, [virtual_block],[])@@ -118,6 +118,7 @@ class MagicModel:# code 和 algorithm 类型的块,如果内容中包含行内公式,则需要将块类型切换为algorithmswitch_code_to_algorithm = False+ span = Noneif span_type in ["image", "table"]:span = {"bbox": block_bbox,@@ -131,8 +132,9 @@ class MagicModel:"type": span_type,"content": isolated_formula_clean(block_content),}- else:-+ elif _vlm_ocr_enable or block_type not in not_extract_list:+ # vlm_ocr_enable模式下,所有文本块都直接使用block的内容+ # 非vlm_ocr_enable模式下,非提取块需要使用span填充方式if block_content:block_content = clean_content(block_content)@@ -186,33 +188,59 @@ class MagicModel:"content": block_content,}- # 处理span类型并添加到all_spans- if isinstance(span, dict) and "bbox" in span:- self.all_spans.append(span)- spans = [span]- elif isinstance(span, list):- self.all_spans.extend(span)- spans = span- else:- raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")-- # 构造line对象- if block_type in [BlockType.CODE_BODY]:- if switch_code_to_algorithm and code_block_sub_type == "code":- code_block_sub_type = "algorithm"- line = {"bbox": block_bbox, "spans": spans, "extra": {"type": code_block_sub_type, "guess_lang": guess_lang}}- else:- line = {"bbox": block_bbox, "spans": spans}+ if (+ span_type in ["image", "table", ContentType.INTERLINE_EQUATION]+ or (_vlm_ocr_enable or block_type not in not_extract_list)+ ):+ if span is None:+ continue+ # 处理span类型并添加到all_spans+ if isinstance(span, dict) and "bbox" in span:+ self.all_spans.append(span)+ spans = [span]+ elif isinstance(span, list):+ self.all_spans.extend(span)+ spans = span+ else:+ raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")++ # 构造line对象+ if block_type in [BlockType.CODE_BODY]:+ if switch_code_to_algorithm and code_block_sub_type == "code":+ code_block_sub_type = "algorithm"+ line = {"bbox": block_bbox, "spans": spans,+ "extra": {"type": code_block_sub_type, "guess_lang": guess_lang}}+ else:+ line = {"bbox": block_bbox, "spans": spans}- blocks.append(- {+ block = {"bbox": block_bbox,"type": block_type,"angle": block_angle,"lines": [line],"index": index,}- )++ else: # 使用span填充方式+ block_spans = []+ for span in page_text_inline_formula_spans:+ if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], block_bbox) > 0.5:+ block_spans.append(span)+ # 从spans删除已经放入block_spans中的span+ if len(block_spans) > 0:+ for span in block_spans:+ page_text_inline_formula_spans.remove(span)++ block = {+ "bbox": block_bbox,+ "type": block_type,+ "angle": block_angle,+ "spans": block_spans,+ "index": index,+ }+ block = fix_text_block(block)++ blocks.append(block)self.image_blocks = []self.table_blocks = []diff --git a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.pyindex 5d7fa240..4457232f 100644--- a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py+++ b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py@@ -13,6 +13,7 @@ from mineru.utils.config_reader import get_table_enable, get_llm_aided_configfrom mineru.utils.cut_image import cut_image_and_tablefrom mineru.utils.enum_class import ContentTypefrom mineru.utils.hash_utils import bytes_md5+from mineru.utils.ocr_utils import OcrConfidencefrom mineru.utils.pdf_image_tools import get_crop_imgfrom mineru.version import __version__@@ -140,6 +141,7 @@ def result_to_middle_json(image_writer,_ocr_enable,_vlm_ocr_enable,+ hybrid_pipeline_model,):middle_json = {"pdf_info": [], "_backend":"hybrid", "_version_name": __version__}@@ -153,6 +155,41 @@ def result_to_middle_json()middle_json["pdf_info"].append(page_info)+ if not (_vlm_ocr_enable or _ocr_enable):+ """后置ocr处理"""+ need_ocr_list = []+ img_crop_list = []+ text_block_list = []+ for page_info in middle_json["pdf_info"]:+ for block in page_info['para_blocks']:+ if block['type'] in ['table', 'image', 'list', 'code']:+ for sub_block in block['blocks']:+ if not sub_block['type'].endswith('body'):+ text_block_list.append(sub_block)+ elif block['type'] in ['text', 'title', 'ref_text']:+ text_block_list.append(block)+ for block in page_info['discarded_blocks']:+ text_block_list.append(block)+ for block in text_block_list:+ for line in block['lines']:+ for span in line['spans']:+ if 'np_img' in span:+ need_ocr_list.append(span)+ img_crop_list.append(span['np_img'])+ span.pop('np_img')+ if len(img_crop_list) > 0:+ ocr_res_list = hybrid_pipeline_model.ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]+ assert len(ocr_res_list) == len(+ need_ocr_list), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_list)}'+ for index, span in enumerate(need_ocr_list):+ ocr_text, ocr_score = ocr_res_list[index]+ if ocr_score > OcrConfidence.min_confidence:+ span['content'] = ocr_text+ span['score'] = float(f"{ocr_score:.3f}")+ else:+ span['content'] = ''+ span['score'] = 0.0+"""表格跨页合并"""table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')if table_enable:diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex d15411d2..7bf49867 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -1,3 +1,5 @@+from enum import Enum+class BlockType:IMAGE = 'image'TABLE = 'table'@@ -112,4 +114,19 @@ class SplitFlag:class ImageType:PIL = 'pil_img'- BASE64 = 'base64_img'\ No newline at end of file+ BASE64 = 'base64_img'+++class NotExtractType(Enum):+ TEXT = BlockType.TEXT+ TITLE = BlockType.TITLE+ HEADER = BlockType.HEADER+ FOOTER = BlockType.FOOTER+ PAGE_NUMBER = BlockType.PAGE_NUMBER+ PAGE_FOOTNOTE = BlockType.PAGE_FOOTNOTE+ REF_TEXT = BlockType.REF_TEXT+ TABLE_CAPTION = BlockType.TABLE_CAPTION+ IMAGE_CAPTION = BlockType.IMAGE_CAPTION+ TABLE_FOOTNOTE = BlockType.TABLE_FOOTNOTE+ IMAGE_FOOTNOTE = BlockType.IMAGE_FOOTNOTE+ CODE_CAPTION = BlockType.CODE_CAPTION\ No newline at end of file