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 enabling logic and remove deprecated VLM-related code
myhlolid1bb49d8a0d1
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.mdindex 1b30fc6e..7374e2bc 100644--- a/docs/en/usage/cli_tools.md+++ b/docs/en/usage/cli_tools.md@@ -194,10 +194,6 @@ Here are the environment variables and their descriptions:<= 3 GB | 2<= 2 GB | 1-- `MINERU_HYBRID_FORCE_PIPELINE_ENABLE`:- * Used to force the text extraction part in `hybrid-*` backends to be processed using small models.- * Defaults to `false`. Can be set to `true` via environment variable to enable this feature, thereby reducing hallucinations in certain extreme cases.-- `MINERU_VL_MODEL_NAME`:* Used to specify the model name for the vlm/hybrid backend, allowing you to designate the model required for MinerU to run when multiple models exist on a remote openai-server.diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.mdindex f747bc18..7fd17059 100644--- a/docs/zh/usage/cli_tools.md+++ b/docs/zh/usage/cli_tools.md@@ -186,10 +186,6 @@ MinerU命令行工具的某些参数存在相同功能的环境变量配置,<= 3 GB | 2<= 2 GB | 1-- `MINERU_HYBRID_FORCE_PIPELINE_ENABLE`:- * 用于强制将 hybrid-* 后端中的 文本提取部分使用 小模型 进行处理- * 默认为`false`,可通过环境变量设置为`true`来启用该功能,从而在某些极端情况下减少幻觉的发生。-- `MINERU_VL_MODEL_NAME`:* 用于指定 vlm/hybrid 后端使用的模型名称,这将允许您在同时存在多个模型的远程openai-server中指定 MinerU 运行所需的模型。diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex 0dcc36ef..99923f0b 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -40,7 +40,7 @@ from mineru.utils.config_reader import get_device, get_processing_window_sizefrom mineru.utils.enum_class import ImageType, NotExtractType, BlockType as MineruBlockTypefrom mineru.utils.model_utils import crop_img, get_vram, clean_memoryfrom mineru.utils.ocr_utils import get_adjusted_mfdetrec_res, get_ocr_result_list, sorted_boxes, merge_det_boxes, \- update_det_boxes, OcrConfidence+ update_det_boxesfrom mineru.utils.pdf_classify import classifyfrom mineru.utils.pdf_image_tools import (aio_load_images_from_pdf_bytes_range,@@ -681,12 +681,13 @@ def _predict_layout_for_window(images_pil_list,inline_formula_enable,batch_ratio,- vlm_ocr_enable,+ ocr_enable,):"""为单个处理窗口执行一次 pipeline layout,并返回可复用的小模型实例。"""hybrid_model_singleton = HybridModelSingleton()+ # OCR 模式下文本由 VLM 抽取,pipeline 侧只需要 layout,不再启用公式识别模型。hybrid_pipeline_model = hybrid_model_singleton.get_model(- formula_enable=inline_formula_enable and not vlm_ocr_enable,+ formula_enable=inline_formula_enable and not ocr_enable,)images_layout_res = _predict_layout_for_title_split(hybrid_pipeline_model,@@ -701,7 +702,6 @@ def _process_ocr_and_formulas(images_pil_list,model_list,inline_formula_enable,- _ocr_enable,batch_ratio: int = 1,*,images_layout_res,@@ -710,7 +710,7 @@ def _process_ocr_and_formulas("""处理OCR和公式识别"""# 遍历model_list,对文本块截图交由OCR识别- # 根据_ocr_enable决定ocr只开det还是det+rec+ # 此函数只在非 OCR 模式调用,因此 OCR 只开 det,不做 rec。# 根据inline_formula_enable决定是使用mfd和ocr结合的方式,还是纯ocr方式# 将PIL图片转换为numpy数组@@ -745,72 +745,11 @@ def _process_ocr_and_formulas(np_images,model_list,mfd_res,- _ocr_enable,+ False,batch_ratio=batch_ratio,+ fill_text=False,)- # 如果需要ocr则做ocr_rec- if _ocr_enable:- need_ocr_list = []- img_crop_list = []- for page_ocr_res_list in ocr_res_list:- for ocr_res in page_ocr_res_list:- if 'np_img' in ocr_res:- need_ocr_list.append((page_ocr_res_list, ocr_res))- img_crop_list.append(ocr_res.pop('np_img'))- if len(img_crop_list) > 0:- # Process OCR- ocr_result_list = run_ocr_inference(- hybrid_pipeline_model.ocr_model.ocr,- img_crop_list,- det=False,- tqdm_enable=True,- )[0]-- # Verify we have matching counts- assert len(ocr_result_list) == len(need_ocr_list), f'ocr_result_list: {len(ocr_result_list)}, need_ocr_list: {len(need_ocr_list)}'-- items_to_remove = []- # Process OCR results for this language- for index, (page_ocr_res_list, need_ocr_res) in enumerate(need_ocr_list):- ocr_text, ocr_score = ocr_result_list[index]- need_ocr_res['text'] = ocr_text- need_ocr_res['score'] = float(f"{ocr_score:.3f}")- should_remove = False- if ocr_score < OcrConfidence.min_confidence:- should_remove = True- else:- layout_res_bbox = need_ocr_res.get("bbox")- if layout_res_bbox is None and need_ocr_res.get("poly") is not None:- layout_res_bbox = [- need_ocr_res['poly'][0],- need_ocr_res['poly'][1],- need_ocr_res['poly'][4],- need_ocr_res['poly'][5],- ]- if layout_res_bbox is None:- should_remove = True- continue- layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]- layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]- if (- ocr_text in [- '(204号', '(20', '(2', '(2号', '(20号', '号','(204',- '(cid:)', '(ci:)', '(cd:1)', 'cd:)', 'c)', '(cd:)', 'c', 'id:)',- ':)', '√:)', '√i:)', '−i:)', '−:' , 'i:)',- ]- and ocr_score < 0.8- and layout_res_width < layout_res_height- ):- should_remove = True-- if should_remove:- items_to_remove.append((page_ocr_res_list, need_ocr_res))-- for page_ocr_res_list, need_ocr_res in items_to_remove:- if need_ocr_res in page_ocr_res_list:- page_ocr_res_list.remove(need_ocr_res)-_normalize_bbox(inline_formula_list, ocr_res_list, images_pil_list)merged_model_list = _merge_page_sidecar_items(model_list,@@ -959,19 +898,6 @@ def get_batch_ratio(device):return batch_ratio-def _should_enable_vlm_ocr(ocr_enable: bool) -> bool:- """根据OCR解析需求和强制开关判断是否启用VLM OCR。"""- force_enable = os.getenv("MINERU_FORCE_VLM_OCR_ENABLE", "0").lower() in ("1", "true", "yes")- if force_enable:- return True-- force_pipeline = os.getenv("MINERU_HYBRID_FORCE_PIPELINE_ENABLE", "0").lower() in ("1", "true", "yes")- return (- ocr_enable- and not force_pipeline- )--def _close_images(images_list):for image_dict in images_list or []:pil_img = image_dict.get("img_pil")@@ -1006,12 +932,10 @@ def doc_analyze(device = get_device()_ocr_enable = ocr_classify(pdf_bytes, parse_method=parse_method)- _vlm_ocr_enable = _should_enable_vlm_ocr(_ocr_enable)pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)middle_json = init_middle_json(_ocr_enable,- _vlm_ocr_enable,effort=effort,)model_list = []@@ -1031,7 +955,7 @@ def doc_analyze(f'window_size={configured_window_size}, total_windows={total_windows}')- batch_ratio = get_batch_ratio(device) if not _vlm_ocr_enable else 1+ batch_ratio = get_batch_ratio(device) if not _ocr_enable else 1infer_start = time.time()progress_bar = None@@ -1058,7 +982,7 @@ def doc_analyze(images_pil_list,inline_formula_enable,batch_ratio,- _vlm_ocr_enable,+ _ocr_enable,)if effort == "medium":_apply_medium_table_orientation_labels(@@ -1079,11 +1003,11 @@ def doc_analyze(window_model_list = predictor.batch_extract_with_layout(images_pil_list,vlm_blocks_list,- not_extract_list=None if _vlm_ocr_enable else not_extract_list,+ not_extract_list=None if _ocr_enable else not_extract_list,image_analysis=effective_image_analysis,)optimize_hybrid_formula_number_blocks(window_model_list)- if _vlm_ocr_enable:+ if _ocr_enable:_apply_vlm_ocr_det_sidecars_for_window(images_pil_list,window_model_list,@@ -1096,13 +1020,12 @@ def doc_analyze(images_pil_list,window_model_list,inline_formula_enable,- _ocr_enable,batch_ratio=batch_ratio,images_layout_res=images_layout_res,hybrid_pipeline_model=hybrid_pipeline_model,)elif effort == "high":- if _vlm_ocr_enable:+ if _ocr_enable:with predictor_execution_guard(predictor):window_model_list = predictor.batch_two_step_extract(images=images_pil_list,@@ -1126,7 +1049,6 @@ def doc_analyze(images_pil_list,window_model_list,inline_formula_enable,- _ocr_enable,batch_ratio=batch_ratio,images_layout_res=images_layout_res,hybrid_pipeline_model=hybrid_pipeline_model,@@ -1156,7 +1078,6 @@ def doc_analyze(image_writer,page_start_index=window_start,_ocr_enable=_ocr_enable,- _vlm_ocr_enable=_vlm_ocr_enable,progress_bar=progress_bar,)last_append_end_time = time.time()@@ -1178,20 +1099,18 @@ def doc_analyze(middle_json["pdf_info"],hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,)else:finalize_middle_json(middle_json["pdf_info"],hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,effort=effort,)close_pdfium_document(pdf_doc)doc_closed = Trueclean_memory(device)- return middle_json, model_list, _vlm_ocr_enable+ return middle_json, model_listfinally:if not doc_closed:close_pdfium_document(pdf_doc)@@ -1221,12 +1140,10 @@ async def aio_doc_analyze(device = get_device()_ocr_enable = ocr_classify(pdf_bytes, parse_method=parse_method)- _vlm_ocr_enable = _should_enable_vlm_ocr(_ocr_enable)pdf_doc = open_pdfium_document(pdfium.PdfDocument, pdf_bytes)middle_json = init_middle_json(_ocr_enable,- _vlm_ocr_enable,effort=effort,)model_list = []@@ -1246,7 +1163,7 @@ async def aio_doc_analyze(f'window_size={configured_window_size}, total_windows={total_windows}')- batch_ratio = get_batch_ratio(device) if not _vlm_ocr_enable else 1+ batch_ratio = get_batch_ratio(device) if not _ocr_enable else 1infer_start = time.time()progress_bar = None@@ -1273,7 +1190,7 @@ async def aio_doc_analyze(images_pil_list,inline_formula_enable,batch_ratio,- _vlm_ocr_enable,+ _ocr_enable,)if effort == "medium":await asyncio.to_thread(@@ -1295,11 +1212,11 @@ async def aio_doc_analyze(window_model_list = await predictor.aio_batch_extract_with_layout(images_pil_list,vlm_blocks_list,- not_extract_list=None if _vlm_ocr_enable else not_extract_list,+ not_extract_list=None if _ocr_enable else not_extract_list,image_analysis=effective_image_analysis,)optimize_hybrid_formula_number_blocks(window_model_list)- if _vlm_ocr_enable:+ if _ocr_enable:await asyncio.to_thread(_apply_vlm_ocr_det_sidecars_for_window,images_pil_list,@@ -1314,13 +1231,12 @@ async def aio_doc_analyze(images_pil_list,window_model_list,inline_formula_enable,- _ocr_enable,batch_ratio=batch_ratio,images_layout_res=images_layout_res,hybrid_pipeline_model=hybrid_pipeline_model,)elif effort == "high":- if _vlm_ocr_enable:+ if _ocr_enable:async with aio_predictor_execution_guard(predictor):window_model_list = await predictor.aio_batch_two_step_extract(images=images_pil_list,@@ -1346,7 +1262,6 @@ async def aio_doc_analyze(images_pil_list,window_model_list,inline_formula_enable,- _ocr_enable,batch_ratio=batch_ratio,images_layout_res=images_layout_res,hybrid_pipeline_model=hybrid_pipeline_model,@@ -1377,7 +1292,6 @@ async def aio_doc_analyze(image_writer,page_start_index=window_start,_ocr_enable=_ocr_enable,- _vlm_ocr_enable=_vlm_ocr_enable,progress_bar=progress_bar,)last_append_end_time = time.time()@@ -1400,7 +1314,6 @@ async def aio_doc_analyze(middle_json["pdf_info"],hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,)else:await asyncio.to_thread(@@ -1408,13 +1321,12 @@ async def aio_doc_analyze(middle_json["pdf_info"],hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,effort=effort,)close_pdfium_document(pdf_doc)doc_closed = Trueclean_memory(device)- return middle_json, model_list, _vlm_ocr_enable+ return middle_json, model_listfinally:if not doc_closed:close_pdfium_document(pdf_doc)diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex a2a19629..1d963f74 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -56,7 +56,6 @@ class MagicModel:width,height,_ocr_enable,- _vlm_ocr_enable,):(self.page_blocks,@@ -74,7 +73,7 @@ class MagicModel:for inline_formula in self.page_inline_formula:inline_formula["bbox"] = list(self.cal_real_bbox(inline_formula["bbox"]))inline_formula_latex = inline_formula.pop("latex", "")- if inline_formula_latex or _vlm_ocr_enable:+ if inline_formula_latex or _ocr_enable:page_text_inline_formula_spans.append({"bbox": inline_formula["bbox"],@@ -93,7 +92,7 @@ class MagicModel:"score": ocr_res["score"],})- if not _vlm_ocr_enable and not _ocr_enable:+ if not _ocr_enable:virtual_block = [0, 0, width, height, None, None, None, "text"]page_text_inline_formula_spans = txt_spans_extract(page,@@ -193,9 +192,9 @@ class MagicModel:"type": span_type,"content": isolated_formula_clean(block_content),}- elif _vlm_ocr_enable or block_type not in not_extract_list:- # vlm_ocr_enable 模式下,所有文本块都直接使用 block 的内容- # 非 vlm_ocr_enable 模式下,非提取块仍沿用直接内容模式+ elif _ocr_enable or block_type not in not_extract_list:+ # OCR 模式下,所有文本块都直接使用 VLM block 内容。+ # 非 OCR 模式下,非提取块仍沿用直接内容模式。if block_content:block_content = clean_content(block_content)@@ -263,7 +262,7 @@ class MagicModel:ContentType.CHART,ContentType.INTERLINE_EQUATION,]- or (_vlm_ocr_enable or block_type not in not_extract_list)+ or (_ocr_enable or block_type not in not_extract_list)):if span is None:continue@@ -303,7 +302,7 @@ class MagicModel:block["sub_type"] = block_sub_typeif raw_block_type == "table" and "cell_merge" in block_info:block["cell_merge"] = block_info["cell_merge"]- if _vlm_ocr_enable and self._supports_ocr_det_lines(block_type):+ if _ocr_enable and self._supports_ocr_det_lines(block_type):ocr_det_lines = self._build_ocr_det_lines(span_matcher.collect_for_block(block_bbox))diff --git a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.pyindex d9264e41..74754ae6 100644--- a/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py+++ b/mineru/backend/hybrid/hybrid_model_output_to_middle_json.py@@ -56,7 +56,6 @@ def blocks_to_page_info(image_writer,page_index,_ocr_enable,- _vlm_ocr_enable,) -> dict:"""将blocks转换为页面信息"""@@ -74,7 +73,6 @@ def blocks_to_page_info(width,height,_ocr_enable,- _vlm_ocr_enable,)image_blocks = magic_model.get_image_blocks()table_blocks = magic_model.get_table_blocks()@@ -180,14 +178,13 @@ def _normalize_split_title_blocks(pdf_info_list):block["level"] = title_level-def init_middle_json(_ocr_enable, _vlm_ocr_enable, effort="medium"):+def init_middle_json(_ocr_enable, effort="medium"):"""初始化 Hybrid middle json,使用公开 effort 元数据描述解析强度。"""return {"pdf_info": [],"_backend": "hybrid","_effort": effort,"_ocr_enable": _ocr_enable,- "_vlm_ocr_enable": _vlm_ocr_enable,"_version_name": __version__}@@ -200,7 +197,6 @@ def append_page_results_to_middle_json(image_writer,page_start_index=0,_ocr_enable=False,- _vlm_ocr_enable=False,progress_bar=None,):for offset, (page_model_list, image_dict) in enumerate(@@ -218,7 +214,6 @@ def append_page_results_to_middle_json(image_writer,page_index,_ocr_enable,- _vlm_ocr_enable,)finally:close_pdfium_child(page)@@ -235,7 +230,6 @@ def append_page_model_list_to_middle_json(image_writer,page_start_index=0,_ocr_enable=False,- _vlm_ocr_enable=False,progress_bar=None,):append_page_results_to_middle_json(@@ -246,7 +240,6 @@ def append_page_model_list_to_middle_json(image_writer,page_start_index=page_start_index,_ocr_enable=_ocr_enable,- _vlm_ocr_enable=_vlm_ocr_enable,progress_bar=progress_bar,)@@ -255,10 +248,9 @@ def apply_server_side_postprocess(pdf_info_list,hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,):"""执行 Hybrid 只能在服务端完成的 post-OCR,避免客户端依赖 pipeline OCR 模型。"""- if not (_vlm_ocr_enable or _ocr_enable):+ if not _ocr_enable:_apply_post_ocr(pdf_info_list, hybrid_pipeline_model)@@ -284,7 +276,6 @@ def finalize_middle_json(pdf_info_list,hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,effort="medium",):"""服务端先做必要 post-OCR,再按公开 effort 执行完整 finalize。"""@@ -292,7 +283,6 @@ def finalize_middle_json(pdf_info_list,hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,)finalize_middle_json_from_preproc(pdf_info_list, effort=effort)@@ -303,10 +293,9 @@ def result_to_middle_json(pdf_doc,image_writer,_ocr_enable,- _vlm_ocr_enable,hybrid_pipeline_model,):- middle_json = init_middle_json(_ocr_enable, _vlm_ocr_enable)+ middle_json = init_middle_json(_ocr_enable)with tqdm(total=len(model_list), desc="Processing pages") as progress_bar:append_page_model_list_to_middle_json(@@ -316,7 +305,6 @@ def result_to_middle_json(pdf_doc,image_writer,_ocr_enable=_ocr_enable,- _vlm_ocr_enable=_vlm_ocr_enable,progress_bar=progress_bar,)@@ -324,7 +312,6 @@ def result_to_middle_json(middle_json["pdf_info"],hybrid_pipeline_model,_ocr_enable,- _vlm_ocr_enable,)close_pdfium_document(pdf_doc)return middle_jsondiff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex b559de38..5f25889a 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -537,7 +537,7 @@ def _process_hybrid(local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)- middle_json, infer_result, _vlm_ocr_enable = hybrid_doc_analyze(+ middle_json, infer_result = hybrid_doc_analyze(pdf_bytes,image_writer=image_writer,backend=backend,@@ -550,7 +550,6 @@ def _process_hybrid(pdf_info = middle_json["pdf_info"]- # f_draw_span_bbox = not _vlm_ocr_enablef_draw_span_bbox = False_process_output(@@ -593,7 +592,7 @@ async def _async_process_hybrid(local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)- middle_json, infer_result, _vlm_ocr_enable = await aio_hybrid_doc_analyze(+ middle_json, infer_result = await aio_hybrid_doc_analyze(pdf_bytes,image_writer=image_writer,backend=backend,@@ -606,7 +605,6 @@ async def _async_process_hybrid(pdf_info = middle_json["pdf_info"]- # f_draw_span_bbox = not _vlm_ocr_enablef_draw_span_bbox = False_process_output(