Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: update hybrid backend effort levels to include low option and adjust related descriptions

myhloli36f656fc96fb
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.md
index dcb5791a..bf1cee14 100644
--- a/docs/en/usage/cli_tools.md
+++ b/docs/en/usage/cli_tools.md
@@ -14,7 +14,7 @@ Options:
-m, --method [auto|txt|ocr] Parsing method: auto (default), txt, ocr (pipeline and hybrid* backend only)
-b, --backend [pipeline|hybrid-engine|hybrid-http-client]
Parsing backend (default: hybrid-engine)
- --effort [medium|high] Hybrid parsing effort (default: medium)
+ --effort [low|medium|high] Hybrid parsing effort (default: medium)
-l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
Specify document language (improves OCR accuracy, pipeline and hybrid* backend only)
-u, --url TEXT OpenAI-compatible backend URL passed through to the server when using http-client
@@ -23,8 +23,9 @@ Options:
-f, --formula BOOLEAN Enable formula parsing (default: enabled)
-t, --table BOOLEAN Enable table parsing (default: enabled)
--image-analysis BOOLEAN Enable image/chart analysis for hybrid
- backend. Hybrid medium effort automatically
- disables image/chart analysis (default: enabled)
+ backend. Hybrid low and medium efforts
+ automatically disable image/chart analysis
+ (default: enabled)
--client-side-output-generation BOOLEAN
Generate Markdown and content lists locally
from server-returned middle JSON, images, and
diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.md
index f15cb2d3..99442d66 100644
--- a/docs/zh/usage/cli_tools.md
+++ b/docs/zh/usage/cli_tools.md
@@ -14,7 +14,7 @@ Options:
-m, --method [auto|txt|ocr] 解析方法:auto(默认)、txt、ocr(仅用于 pipeline 与 hybrid* 后端)
-b, --backend [pipeline|hybrid-engine|hybrid-http-client]
解析后端(默认为 hybrid-engine)
- --effort [medium|high] Hybrid 解析强度(默认:medium)
+ --effort [low|medium|high] Hybrid 解析强度(默认:medium)
-l, --lang [ch|ch_server|korean|ta|te|ka|th|el|arabic|east_slavic|cyrillic|devanagari]
指定文档语言(可提升 OCR 准确率,仅用于 pipeline 与 hybrid* 后端)
-u, --url TEXT 当使用 http-client 时,传给服务端后端的 OpenAI 兼容地址
@@ -23,7 +23,7 @@ Options:
-f, --formula BOOLEAN 是否启用公式解析(默认开启)
-t, --table BOOLEAN 是否启用表格解析(默认开启)
--image-analysis BOOLEAN 是否启用 hybrid 的图片/图表分析;Hybrid
- medium 强度会自动关闭图片/图表分析(默认开启)
+ low 和 medium 强度会自动关闭图片/图表分析(默认开启)
--client-side-output-generation BOOLEAN
在客户端基于服务端返回的 middle JSON、图片与原文件
生成 Markdown 和 content list(默认关闭)
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 3af763e7..01398218 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -2,30 +2,30 @@
from __future__ import annotations
import asyncio
+import html
import os
import time
+from collections import defaultdict
from typing import Any, Literal
import cv2
import numpy as np
from loguru import logger
-from mineru_vl_utils import MinerUClient
-from mineru_vl_utils.structs import ContentBlock
-from mineru_vl_utils.structs import BlockType
from PIL import Image
from tqdm import tqdm
from ...types import NOT_EXTRACT_TYPES, BBox, PageInfo
from ...types import BlockType as MineruBlockType
-from ...utils.config_reader import get_device, get_processing_window_size
-from ...utils.enum_class import ImageType
from ...utils.backend_options import validate_effort
+from ...utils.config_reader import get_device, get_processing_window_size, get_table_enable
+from ...utils.enum_class import ImageType
from ...utils.image_payload import ImagePayloadCache
from ...utils.model_utils import clean_memory, crop_img, get_vram
from ...utils.ocr_utils import (
OcrConfidence,
get_adjusted_mfdetrec_res,
get_ocr_result_list,
+ get_rotate_crop_image_for_text_rec,
mask_formula_regions_for_ocr_det,
merge_det_boxes,
sorted_boxes,
@@ -33,6 +33,8 @@ from ...utils.ocr_utils import (
)
from ...utils.pdf_document import PDFDocument
from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_bytes_range
+from ...utils.bbox_utils import normalize_to_int_bbox
+from ...utils.pdf_image_tools import get_crop_np_img
from ..pipeline.model_init import (
HybridModelSingleton,
MineruHybridModel,
@@ -40,16 +42,10 @@ from ..pipeline.model_init import (
run_mfr_inference,
run_ocr_inference,
)
+from ..pipeline.model_list import AtomicModel
from ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio
from ..utils.middle_json_utils import append_pages
from ..utils.runtime_utils import exclude_progress_bar_idle_time
-from ...model.vlm.runtime import (
- ModelSingleton,
- _get_model_async,
- _maybe_enable_serial_execution,
- aio_predictor_execution_guard,
- predictor_execution_guard,
-)
from .model_output_to_middle_json import (
apply_server_side_postprocess,
blocks_to_page_info,
@@ -63,36 +59,88 @@ MFR_BASE_BATCH_SIZE = 16
OCR_DET_BASE_BATCH_SIZE = 8
LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8
HYBRID_MEDIUM_LAYOUT_LABEL_MAP = {
- "abstract": BlockType.TEXT,
- "algorithm": BlockType.ALGORITHM,
- "aside_text": BlockType.ASIDE_TEXT,
- "chart": BlockType.CHART,
- "content": BlockType.INDEX,
- "display_formula": BlockType.EQUATION,
- "doc_title": BlockType.TITLE,
- "figure_title": BlockType.IMAGE_CAPTION,
- "footer": BlockType.FOOTER,
- "footer_image": BlockType.FOOTER,
- "footnote": BlockType.PAGE_FOOTNOTE,
- "formula_number": BlockType.FORMULA_NUMBER,
- "header": BlockType.HEADER,
- "header_image": BlockType.HEADER,
- "image": BlockType.IMAGE,
- "number": BlockType.PAGE_NUMBER,
- "paragraph_title": BlockType.TITLE,
- "reference_content": BlockType.REF_TEXT,
- "seal": BlockType.IMAGE,
- "table": BlockType.TABLE,
- "text": BlockType.TEXT,
- "vertical_text": BlockType.TEXT,
+ "abstract": MineruBlockType.TEXT,
+ "algorithm": MineruBlockType.ALGORITHM,
+ "aside_text": MineruBlockType.ASIDE_TEXT,
+ "chart": MineruBlockType.CHART,
+ "content": MineruBlockType.INDEX,
+ "display_formula": MineruBlockType.EQUATION,
+ "doc_title": MineruBlockType.TITLE,
+ "figure_title": MineruBlockType.IMAGE_CAPTION,
+ "footer": MineruBlockType.FOOTER,
+ "footer_image": MineruBlockType.FOOTER,
+ "footnote": MineruBlockType.PAGE_FOOTNOTE,
+ "formula_number": MineruBlockType.FORMULA_NUMBER,
+ "header": MineruBlockType.HEADER,
+ "header_image": MineruBlockType.HEADER,
+ "image": MineruBlockType.IMAGE,
+ "number": MineruBlockType.PAGE_NUMBER,
+ "paragraph_title": MineruBlockType.TITLE,
+ "reference_content": MineruBlockType.REF_TEXT,
+ "seal": MineruBlockType.IMAGE,
+ "table": MineruBlockType.TABLE,
+ "text": MineruBlockType.TEXT,
+ "vertical_text": MineruBlockType.TEXT,
}
+HYBRID_LOW_LAYOUT_LABEL_MAP = {
+ **HYBRID_MEDIUM_LAYOUT_LABEL_MAP,
+ "doc_title": MineruBlockType.DOC_TITLE,
+ "paragraph_title": MineruBlockType.PARAGRAPH_TITLE,
+ "figure_title": MineruBlockType.IMAGE_CAPTION,
+ "vision_footnote": MineruBlockType.PAGE_FOOTNOTE,
+}
+
+
+def _load_vlm_content_block() -> Any:
+ """按需加载 VLM ContentBlock,避免 Hybrid low 导入阶段依赖 mineru_vl_utils。"""
+ from mineru_vl_utils.structs import ContentBlock
+
+ return ContentBlock
+
+
+def _load_vlm_runtime() -> dict[str, Any]:
+ """按需加载 VLM runtime 组件,确保只有 medium/high 路径触发 VLM 依赖。"""
+ from ...model.vlm.runtime import (
+ ModelSingleton,
+ _get_model_async,
+ _maybe_enable_serial_execution,
+ aio_predictor_execution_guard,
+ predictor_execution_guard,
+ )
+
+ return {
+ "ModelSingleton": ModelSingleton,
+ "_get_model_async": _get_model_async,
+ "_maybe_enable_serial_execution": _maybe_enable_serial_execution,
+ "aio_predictor_execution_guard": aio_predictor_execution_guard,
+ "predictor_execution_guard": predictor_execution_guard,
+ }
+
def _is_hybrid_ocr_det_candidate(block: dict[str, Any]) -> bool:
"""判断 Hybrid 文本类块是否需要 OCR det 生成行级视觉信息。"""
return (block.get("type") or block.get("label")) in NOT_EXTRACT_TYPES
+def _is_hybrid_low_ocr_det_candidate(block: dict[str, Any]) -> bool:
+ """判断 Hybrid low 本地 layout 块是否需要 OCR det,覆盖 doc/index/list 等 layout 标签。"""
+ item_type = block.get("type") or block.get("label")
+ return item_type in {
+ *NOT_EXTRACT_TYPES,
+ MineruBlockType.DOC_TITLE,
+ MineruBlockType.PARAGRAPH_TITLE,
+ MineruBlockType.INDEX,
+ MineruBlockType.ABSTRACT,
+ MineruBlockType.ASIDE_TEXT,
+ MineruBlockType.PHONETIC,
+ MineruBlockType.LIST,
+ MineruBlockType.CHART_CAPTION,
+ MineruBlockType.CHART_FOOTNOTE,
+ MineruBlockType.CODE_FOOTNOTE,
+ }
+
+
def ocr_classify(pdf_doc: PDFDocument, parse_method: str = "auto") -> bool:
# 确定OCR设置
_ocr_enable = False
@@ -113,12 +161,15 @@ def _ocr_det(
batch_ratio: int = 1,
*,
fill_text: bool = True,
+ candidate_fn: Any = _is_hybrid_ocr_det_candidate,
) -> list[list[dict[str, Any]]]:
def _set_temp_pixel_bbox(res: dict[str, Any], pixel_bbox: list[int]) -> None:
+ """临时切换为像素 bbox,便于复用已有裁剪逻辑。"""
res["_normalized_bbox"] = list(res["bbox"])
res["bbox"] = pixel_bbox
def _restore_normalized_bbox(res: dict[str, Any]) -> None:
+ """恢复归一化 bbox,避免 OCR det 过程污染 Hybrid 输出。"""
normalized_bbox = res.pop("_normalized_bbox", None)
if normalized_bbox is not None:
res["bbox"] = normalized_bbox
@@ -133,7 +184,7 @@ def _ocr_det(
ocr_res_list.append([])
img_height, img_width = np_image.shape[:2]
for res in page_results:
- if not _is_hybrid_ocr_det_candidate(res):
+ if not candidate_fn(res):
continue
x0 = max(0, int(res["bbox"][0] * img_width))
y0 = max(0, int(res["bbox"][1] * img_height))
@@ -174,7 +225,7 @@ def _ocr_det(
ocr_res_list.append([])
img_height, img_width = np_image.shape[:2]
for res in page_results:
- if not _is_hybrid_ocr_det_candidate(res):
+ if not candidate_fn(res):
continue
x0 = max(0, int(res["bbox"][0] * img_width))
y0 = max(0, int(res["bbox"][1] * img_height))
@@ -237,7 +288,7 @@ def _mask_image_regions(np_images: list[Any], model_list: list[list[dict[str, An
# 收集需要mask的区域
mask_regions = []
for block in vlm_page_results:
- if block["type"] in [BlockType.IMAGE, BlockType.TABLE, BlockType.EQUATION]:
+ if block["type"] in [MineruBlockType.IMAGE, MineruBlockType.TABLE, MineruBlockType.EQUATION]:
bbox = block["bbox"]
# 批量转换归一化坐标到像素坐标,并进行边界检查
x0 = max(0, int(bbox[0] * img_width))
@@ -423,7 +474,7 @@ def _normalize_layout_bbox_to_unit(bbox: BBox | None, page_size: tuple[int, int]
return unit_bbox
-def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[int, int]) -> ContentBlock | None:
+def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[int, int]) -> Any | None:
"""将 Pipeline layout 检测项转换为 mineru-vl-utils 的 ContentBlock。"""
label = layout_item.get("label") or layout_item.get("type")
block_type = HYBRID_MEDIUM_LAYOUT_LABEL_MAP.get(str(label))
@@ -434,6 +485,7 @@ def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[
if bbox is None:
return None
+ ContentBlock = _load_vlm_content_block()
try:
return ContentBlock(type=block_type, bbox=bbox, angle=layout_item.get("angle", 0) or 0)
except AssertionError:
@@ -444,9 +496,9 @@ def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[
def _build_medium_layout_blocks(
images_layout_res: list[list[dict[str, Any]]],
images_pil_list: list[Image.Image],
-) -> list[list[ContentBlock]]:
+) -> list[list[Any]]:
"""按页构造 Hybrid medium 模式传给 VLM 的外部 layout blocks。"""
- blocks_list: list[list[ContentBlock]] = []
+ blocks_list: list[list[Any]] = []
for layout_res, image in zip(images_layout_res, images_pil_list):
page_size = _normalize_page_size(image)
page_blocks = []
@@ -458,6 +510,415 @@ def _build_medium_layout_blocks(
return blocks_list
+def _is_low_table_enabled() -> bool:
+ """读取 Hybrid low 的表格开关,复用 Hybrid 当前通过环境变量传入的表格配置。"""
+ return get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
+
+
+def _normalize_low_content(value: Any) -> str:
+ """将 low 本地模型输出的文本字段规范成 Hybrid block 可消费的字符串。"""
+ if isinstance(value, list):
+ return "\n".join(str(item) for item in value if str(item).strip())
+ if isinstance(value, str):
+ return value.strip()
+ return ""
+
+
+def _low_layout_item_to_hybrid_item(
+ layout_item: dict[str, Any],
+ page_size: tuple[int, int],
+) -> dict[str, Any] | None:
+ """将本地 layout/OCR 结果转换为 Hybrid MagicModel 可消费的 block 或 sidecar。"""
+ label = str(layout_item.get("label") or layout_item.get("type") or "")
+ bbox = _normalize_layout_bbox_to_unit(layout_item.get("bbox"), page_size)
+ if bbox is None:
+ return None
+
+ score = float(layout_item.get("score", 0.0) or 0.0)
+ if label == "inline_formula":
+ latex = _normalize_low_content(layout_item.get("latex", ""))
+ if not latex:
+ return None
+ return {"type": "inline_formula", "bbox": bbox, "latex": latex, "score": score}
+ if label == "ocr_text":
+ return {
+ "type": "ocr_text",
+ "bbox": bbox,
+ "text": _normalize_low_content(layout_item.get("text", "")),
+ "score": score,
+ }
+
+ block_type = HYBRID_LOW_LAYOUT_LABEL_MAP.get(label)
+ if block_type is None:
+ return None
+
+ hybrid_item: dict[str, Any] = {
+ "type": block_type,
+ "bbox": bbox,
+ "angle": layout_item.get("angle", 0) or 0,
+ }
+ if label == "seal":
+ hybrid_item["sub_type"] = "seal"
+
+ if block_type == MineruBlockType.TABLE:
+ hybrid_item["content"] = _normalize_low_content(layout_item.get("html", ""))
+ elif block_type == MineruBlockType.EQUATION:
+ hybrid_item["content"] = _normalize_low_content(layout_item.get("latex", ""))
+ else:
+ content = _normalize_low_content(layout_item.get("text", ""))
+ if content:
+ hybrid_item["content"] = content
+
+ return hybrid_item
+
+
+def _build_low_hybrid_model_list(
+ images_layout_res: list[list[dict[str, Any]]],
+ images_pil_list: list[Image.Image],
+) -> list[list[dict[str, Any]]]:
+ """按页构造 Hybrid low 的模型输出,保持最终 middle-json 为 Hybrid 形态。"""
+ model_list: list[list[dict[str, Any]]] = []
+ for layout_res, image in zip(images_layout_res, images_pil_list):
+ page_size = _normalize_page_size(image)
+ page_items = []
+ for layout_item in layout_res:
+ hybrid_item = _low_layout_item_to_hybrid_item(layout_item, page_size)
+ if hybrid_item is not None:
+ page_items.append(hybrid_item)
+ model_list.append(page_items)
+ return model_list
+
+
+def _run_low_formula_recognition(
+ hybrid_pipeline_model: MineruHybridModel,
+ images_layout_res: list[list[dict[str, Any]]],
+ np_images: list[np.ndarray],
+ formula_enable: bool,
+ batch_ratio: int,
+) -> list[list[dict[str, Any]]]:
+ """执行 Hybrid low 的本地公式识别,并返回供 OCR det 遮罩使用的公式框。"""
+ if not formula_enable:
+ for layout_res in images_layout_res:
+ layout_res[:] = [item for item in layout_res if item.get("label") != "inline_formula"]
+ return [[] for _ in images_layout_res]
+
+ images_mfd_res = []
+ for layout_res in images_layout_res:
+ page_formula_res = []
+ for res in layout_res:
+ if res.get("label") in ["display_formula", "inline_formula"]:
+ res.setdefault("latex", "")
+ page_formula_res.append(res)
+ images_mfd_res.append(page_formula_res)
+
+ if any(images_mfd_res):
+ images_formula_list = run_mfr_inference(
+ hybrid_pipeline_model.mfr_model.batch_predict,
+ images_mfd_res,
+ np_images,
+ batch_size=batch_ratio * MFR_BASE_BATCH_SIZE,
+ )
+ for page_formula_res, page_formula_with_latex in zip(images_mfd_res, images_formula_list):
+ for formula_res, formula_with_latex in zip(page_formula_res, page_formula_with_latex):
+ formula_res["latex"] = formula_with_latex.get("latex", "")
+
+ mfd_res = []
+ for layout_res in images_layout_res:
+ page_mfd_res = []
+ for formula in layout_res:
+ if formula.get("label") not in ["display_formula", "inline_formula"]:
+ continue
+ bbox = _formula_item_to_pixel_bbox(formula)
+ if bbox is not None:
+ page_mfd_res.append({"bbox": bbox})
+ mfd_res.append(page_mfd_res)
+ return mfd_res
+
+
+def _apply_low_table_rotate_label(table_res_dict: dict[str, Any], rotate_label: str) -> None:
+ """写回表格方向预测结果,并同步旋转无线和有线表格裁剪图。"""
+ rotate_label = str(rotate_label or "0")
+ table_res_dict["rotate_label"] = rotate_label
+ if rotate_label == "270":
+ rotate_code = cv2.ROTATE_90_CLOCKWISE
+ elif rotate_label == "90":
+ rotate_code = cv2.ROTATE_90_COUNTERCLOCKWISE
+ else:
+ return
+ table_res_dict["table_img"] = cv2.rotate(np.asarray(table_res_dict["table_img"]), rotate_code)
+ table_res_dict["wired_table_img"] = cv2.rotate(np.asarray(table_res_dict["wired_table_img"]), rotate_code)
+
+
+def _collect_low_table_items(
+ images_layout_res: list[list[dict[str, Any]]],
+ np_images: list[np.ndarray],
+ lang_list: list[str | None],
+) -> list[dict[str, Any]]:
+ """收集 Hybrid low 单文件窗口中的表格裁剪项,不跨文件聚合。"""
+ table_items = []
+ for layout_res, np_img, lang in zip(images_layout_res, np_images, lang_list):
+ for table_res in layout_res:
+ if table_res.get("label") != "table":
+ continue
+
+ def get_crop_table_img(scale: float) -> np.ndarray:
+ """按指定缩放裁剪表格图,保持 low 表格处理只使用当前文件窗口图像。"""
+ bbox = normalize_to_int_bbox([float(v) / float(scale) for v in table_res["bbox"]])
+ if bbox is None:
+ return np_img[0:0, 0:0]
+ return get_crop_np_img(bbox, np_img, scale=scale)
+
+ table_img = get_crop_table_img(scale=1)
+ wired_table_img = get_crop_table_img(scale=10 / 3)
+ if table_img.size == 0 or wired_table_img.size == 0:
+ continue
+ table_items.append(
+ {
+ "table_res": table_res,
+ "lang": lang,
+ "table_img": table_img,
+ "wired_table_img": wired_table_img,
+ }
+ )
+ return table_items
+
+
+def _collect_low_table_ocr_rec_inputs(
+ atom_model_manager: Any,
+ table_items: list[dict[str, Any]],
+ batch_ratio: int,
+) -> dict[str | None, list[dict[str, Any]]]:
+ """对表格裁剪图执行 OCR det,并按语言收集 OCR rec 输入。"""
+ rec_img_lang_group: dict[str | None, list[dict[str, Any]]] = defaultdict(list)
+ det_ocr_engine = atom_model_manager.get_atom_model(
+ atom_model_name=AtomicModel.OCR,
+ det_db_box_thresh=0.5,
+ det_db_unclip_ratio=1.6,
+ enable_merge_det_boxes=False,
+ )
+ det_images = [cv2.cvtColor(item["table_img"], cv2.COLOR_RGB2BGR) for item in table_items]
+ if not det_images:
+ return rec_img_lang_group
+
+ det_batch_size = max(1, min(len(det_images), batch_ratio * OCR_DET_BASE_BATCH_SIZE))
+ batch_results = run_ocr_inference(
+ det_ocr_engine.text_detector.batch_predict,
+ det_images,
+ det_batch_size,
+ tqdm_enable=True,
+ tqdm_desc="Hybrid-low table OCR-det",
+ )
+ if len(batch_results) != len(table_items):
+ raise ValueError("Hybrid low table OCR det batch result count mismatch")
+
+ for table_id, (table_item, bgr_image, (dt_boxes, _)) in enumerate(zip(table_items, det_images, batch_results)):
+ if dt_boxes is None or len(dt_boxes) == 0:
+ continue
+ for dt_box in sorted_boxes(dt_boxes):
+ dt_box_array = np.asarray(dt_box, dtype=np.float32)
+ rec_img_lang_group[table_item["lang"]].append(
+ {
+ "cropped_img": get_rotate_crop_image_for_text_rec(bgr_image, dt_box_array.copy()),
+ "dt_box": dt_box_array.copy(),
+ "table_id": table_id,
+ }
+ )
+ return rec_img_lang_group
+
+
+def _apply_low_table_recognition(
+ hybrid_pipeline_model: MineruHybridModel,
+ images_layout_res: list[list[dict[str, Any]]],
+ np_images: list[np.ndarray],
+ lang_list: list[str | None],
+ batch_ratio: int,
+) -> None:
+ """执行 Hybrid low 的本地表格识别,结果写回 layout table 项的 html 字段。"""
+ if not _is_low_table_enabled():
+ return
+
+ table_items = _collect_low_table_items(images_layout_res, np_images, lang_list)
+ if not table_items:
+ return
+
+ atom_model_manager = hybrid_pipeline_model.atom_model_manager
+ table_orientation_cls_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.TableOrientationCls)
+ try:
+ rotate_labels = table_orientation_cls_model.batch_predict(
+ table_items,
+ det_batch_size=batch_ratio * OCR_DET_BASE_BATCH_SIZE,
+ )
+ if len(rotate_labels) != len(table_items):
+ raise ValueError("Hybrid low table orientation result count mismatch")
+ for table_item, rotate_label in zip(table_items, rotate_labels):
+ _apply_low_table_rotate_label(table_item, rotate_label)
+ except Exception as exc:
+ logger.warning(f"Hybrid low table orientation classification failed: {exc}, using original image")
+
+ table_cls_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.TableCls)
+ try:
+ table_cls_model.batch_predict(table_items)
+ except Exception as exc:
+ logger.warning(f"Hybrid low table classification failed: {exc}, using default model")
+
+ rec_img_lang_group = _collect_low_table_ocr_rec_inputs(atom_model_manager, table_items, batch_ratio)
+ for lang, rec_img_list in rec_img_lang_group.items():
+ if not rec_img_list:
+ continue
+ ocr_engine = atom_model_manager.get_atom_model(
+ atom_model_name=AtomicModel.OCR,
+ det_db_box_thresh=0.5,
+ det_db_unclip_ratio=1.6,
+ lang=lang,
+ enable_merge_det_boxes=False,
+ )
+ ocr_res_list = run_ocr_inference(
+ ocr_engine.ocr,
+ [item["cropped_img"] for item in rec_img_list],
+ det=False,
+ tqdm_enable=True,
+ tqdm_desc=f"Hybrid-low table OCR-rec {lang}",
+ )[0]
+ for img_dict, ocr_res in zip(rec_img_list, ocr_res_list):
+ table_item = table_items[img_dict["table_id"]]
+ ocr_result_item = [img_dict["dt_box"], html.escape(str(ocr_res[0])), ocr_res[1]]
+ table_item.setdefault("ocr_result", []).append(ocr_result_item)
+
+ wireless_table_model = atom_model_manager.get_atom_model(atom_model_name=AtomicModel.WirelessTable)
+ wireless_table_model.batch_predict(table_items)
+
+ wired_table_items = []
+ for table_item in table_items:
+ cls_label = table_item["table_res"].get("cls_label")
+ cls_score = table_item["table_res"].get("cls_score", 0.0)
+ if (cls_label == AtomicModel.WirelessTable and cls_score < 0.9) or cls_label == AtomicModel.WiredTable:
+ wired_table_items.append(table_item)
+ table_item["table_res"].pop("cls_label", None)
+ table_item["table_res"].pop("cls_score", None)
+
+ for table_item in tqdm(wired_table_items, desc="Hybrid-low table-wired predict"):
+ if not table_item.get("ocr_result"):
+ continue
+ wired_table_model = atom_model_manager.get_atom_model(
+ atom_model_name=AtomicModel.WiredTable,
+ lang=table_item["lang"],
+ )
+ table_item["table_res"]["html"] = wired_table_model.predict(
+ table_item["wired_table_img"],
+ table_item["ocr_result"],
+ table_item["table_res"].get("html", None),
+ )
+
+ for table_item in table_items:
+ html_code = table_item["table_res"].get("html", "") or ""
+ if "<table>" in html_code and "</table>" in html_code:
+ start_index = html_code.find("<table>")
+ end_index = html_code.rfind("</table>") + len("</table>")
+ table_item["table_res"]["html"] = html_code[start_index:end_index]
+
+
+def _apply_low_seal_ocr(
+ hybrid_pipeline_model: MineruHybridModel,
+ images_layout_res: list[list[dict[str, Any]]],
+ np_images: list[np.ndarray],
+) -> None:
+ """执行 Hybrid low 的印章 OCR,并将识别文本写回 seal layout 项。"""
+ seal_ocr_model = None
+ for layout_res, np_img in zip(images_layout_res, np_images):
+ for layout_item in layout_res:
+ if layout_item.get("label") != "seal":
+ continue
+ layout_item["text"] = ""
+ seal_bbox = normalize_to_int_bbox(layout_item.get("bbox"), image_size=np_img.shape[:2])
+ if seal_bbox is None:
+ continue
+ x0, y0, x1, y1 = seal_bbox
+ seal_crop_rgb = np_img[y0:y1, x0:x1]
+ if seal_crop_rgb.size == 0:
+ continue
+ if seal_ocr_model is None:
+ seal_ocr_model = hybrid_pipeline_model.atom_model_manager.get_atom_model(
+ atom_model_name=AtomicModel.OCR,
+ lang="seal",
+ )
+ seal_crop_bgr = cv2.cvtColor(seal_crop_rgb, cv2.COLOR_RGB2BGR)
+ seal_ocr_res = run_ocr_inference(seal_ocr_model.ocr, seal_crop_bgr, det=True, rec=True)[0]
+ seal_texts = []
+ for seal_item in seal_ocr_res or []:
+ if not seal_item or len(seal_item) != 2:
+ continue
+ rec_result = seal_item[1]
+ if rec_result and rec_result[0]:
+ seal_texts.append(rec_result[0])
+ layout_item["text"] = seal_texts
+
+
+def _prune_low_empty_ocr_text_blocks(images_layout_res: list[list[dict[str, Any]]], ocr_enable: bool) -> None:
+ """清理低置信 OCR 后留下的空 ocr_text,避免空块进入 Hybrid MagicModel。"""
+ if not ocr_enable:
+ return
+ for layout_res in images_layout_res:
+ layout_res[:] = [
+ item
+ for item in layout_res
+ if item.get("label") != "ocr_text" or bool(_normalize_low_content(item.get("text", "")))
+ ]
+
+
+def _extract_with_local_layout(
+ images_pil_list: list[Image.Image],
+ language: str | None,
+ inline_formula_enable: bool,
+ _ocr_enable: bool,
+ batch_ratio: int,
+) -> tuple[list[list[dict[str, Any]]], MineruHybridModel]:
+ """Hybrid low 路径:单文件窗口内执行本地 layout/OCR/table/formula,不跨文件 batch。"""
+ hybrid_model_singleton = HybridModelSingleton()
+ hybrid_pipeline_model = hybrid_model_singleton.get_model(
+ lang=language,
+ formula_enable=inline_formula_enable,
+ )
+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
+ images_layout_res = run_layout_inference(
+ hybrid_pipeline_model.layout_model.batch_predict,
+ images_pil_list,
+ batch_size=min(8, batch_ratio * LAYOUT_BASE_BATCH_SIZE),
+ )
+ mfd_res = _run_low_formula_recognition(
+ hybrid_pipeline_model,
+ images_layout_res,
+ np_images,
+ inline_formula_enable,
+ batch_ratio,
+ )
+ _apply_low_table_recognition(
+ hybrid_pipeline_model,
+ images_layout_res,
+ np_images,
+ [language for _ in images_pil_list],
+ batch_ratio,
+ )
+ _apply_low_seal_ocr(hybrid_pipeline_model, images_layout_res, np_images)
+ _prune_low_empty_ocr_text_blocks(images_layout_res, _ocr_enable)
+ low_model_list = _build_low_hybrid_model_list(images_layout_res, images_pil_list)
+ ocr_res_list = _ocr_det(
+ hybrid_pipeline_model,
+ np_images,
+ low_model_list,
+ mfd_res,
+ _ocr_enable,
+ batch_ratio=batch_ratio,
+ candidate_fn=_is_hybrid_low_ocr_det_candidate,
+ )
+ _normalize_bbox([[] for _ in images_pil_list], ocr_res_list, images_pil_list)
+ merged_model_list = _merge_page_sidecar_items(
+ low_model_list,
+ [[] for _ in images_pil_list],
+ ocr_res_list,
+ )
+ return merged_model_list, hybrid_pipeline_model
+
+
def _process_ocr_and_formulas(
images_pil_list: list[Image.Image],
model_list: list[list[dict[str, Any]]],
@@ -618,7 +1079,7 @@ def _process_ocr_and_formulas(
def _extract_with_pipeline_layout(
- predictor: MinerUClient,
+ predictor: Any,
images_pil_list: list[Image.Image],
language: str | None,
inline_formula_enable: bool,
@@ -652,7 +1113,7 @@ def _extract_with_pipeline_layout(
async def _aio_extract_with_pipeline_layout(
- predictor: MinerUClient,
+ predictor: Any,
images_pil_list: list[Image.Image],
language: str | None,
inline_formula_enable: bool,
@@ -857,7 +1318,7 @@ def _close_images(images_list: list[dict[str, Any]]) -> None:
def doc_analyze(
pdf_bytes: bytes,
- predictor: MinerUClient | None = None,
+ predictor: Any | None = None,
backend: Literal[
"http-client",
"transformers",
@@ -871,7 +1332,7 @@ def doc_analyze(
inline_formula_enable: bool = True,
model_path: str | None = None,
server_url: str | None = None,
- effort: Literal["medium", "high"] = "medium",
+ effort: Literal["low", "medium", "high"] = "medium",
image_analysis: bool = True,
page_index_map: list[int] | None = None,
image_cache: ImagePayloadCache | None = None,
@@ -880,9 +1341,13 @@ def doc_analyze(
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
effort = validate_effort(effort)
image_analysis = image_analysis if effort == "high" else False
- if predictor is None:
- predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)
- predictor = _maybe_enable_serial_execution(predictor, backend)
+ if effort == "low":
+ predictor = None
+ else:
+ vlm_runtime = _load_vlm_runtime()
+ if predictor is None:
+ predictor = vlm_runtime["ModelSingleton"]().get_model(backend, model_path, server_url, **kwargs)
+ predictor = vlm_runtime["_maybe_enable_serial_execution"](predictor, backend)
device = get_device()
@@ -925,8 +1390,16 @@ def doc_analyze(
f"pages {window_start + 1}-{window_end + 1}/{page_count} "
f"({len(images_pil_list)} pages)"
)
- if effort == "medium":
- with predictor_execution_guard(predictor):
+ if effort == "low":
+ window_model_list, hybrid_pipeline_model = _extract_with_local_layout(
+ images_pil_list,
+ language,
+ inline_formula_enable,
+ _ocr_enable,
+ batch_ratio,
+ )
+ elif effort == "medium":
+ with vlm_runtime["predictor_execution_guard"](predictor):
window_model_list, hybrid_pipeline_model = _extract_with_pipeline_layout(
predictor,
images_pil_list,
@@ -936,7 +1409,7 @@ def doc_analyze(
batch_ratio,
)
elif _vlm_ocr_enable:
- with predictor_execution_guard(predictor):
+ with vlm_runtime["predictor_execution_guard"](predictor):
window_model_list = predictor.batch_two_step_extract(
images=images_pil_list,
image_analysis=image_analysis,
@@ -948,7 +1421,7 @@ def doc_analyze(
batch_ratio,
)
else:
- with predictor_execution_guard(predictor):
+ with vlm_runtime["predictor_execution_guard"](predictor):
window_model_list = predictor.batch_two_step_extract(
images=images_pil_list,
not_extract_list=list(NOT_EXTRACT_TYPES),
@@ -1024,7 +1497,7 @@ def doc_analyze(
async def aio_doc_analyze(
pdf_bytes: bytes,
- predictor: MinerUClient | None = None,
+ predictor: Any | None = None,
backend: Literal[
"http-client",
"transformers",
@@ -1038,7 +1511,7 @@ async def aio_doc_analyze(
inline_formula_enable: bool = True,
model_path: str | None = None,
server_url: str | None = None,
- effort: Literal["medium", "high"] = "medium",
+ effort: Literal["low", "medium", "high"] = "medium",
image_analysis: bool = True,
page_index_map: list[int] | None = None,
image_cache: ImagePayloadCache | None = None,
@@ -1047,9 +1520,13 @@ async def aio_doc_analyze(
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
effort = validate_effort(effort)
image_analysis = image_analysis if effort == "high" else False
- if predictor is None:
- predictor = await _get_model_async(backend, model_path, server_url, **kwargs)
- predictor = _maybe_enable_serial_execution(predictor, backend)
+ if effort == "low":
+ predictor = None
+ else:
+ vlm_runtime = _load_vlm_runtime()
+ if predictor is None:
+ predictor = await vlm_runtime["_get_model_async"](backend, model_path, server_url, **kwargs)
+ predictor = vlm_runtime["_maybe_enable_serial_execution"](predictor, backend)
device = get_device()
@@ -1092,8 +1569,17 @@ async def aio_doc_analyze(
f"pages {window_start + 1}-{window_end + 1}/{page_count} "
f"({len(images_pil_list)} pages)"
)
- if effort == "medium":
- async with aio_predictor_execution_guard(predictor):
+ if effort == "low":
+ window_model_list, hybrid_pipeline_model = await asyncio.to_thread(
+ _extract_with_local_layout,
+ images_pil_list,
+ language,
+ inline_formula_enable,
+ _ocr_enable,
+ batch_ratio,
+ )
+ elif effort == "medium":
+ async with vlm_runtime["aio_predictor_execution_guard"](predictor):
window_model_list, hybrid_pipeline_model = await _aio_extract_with_pipeline_layout(
predictor,
images_pil_list,
@@ -1103,7 +1589,7 @@ async def aio_doc_analyze(
batch_ratio,
)
elif _vlm_ocr_enable:
- async with aio_predictor_execution_guard(predictor):
+ async with vlm_runtime["aio_predictor_execution_guard"](predictor):
window_model_list = await predictor.aio_batch_two_step_extract(
images=images_pil_list,
image_analysis=image_analysis,
@@ -1116,7 +1602,7 @@ async def aio_doc_analyze(
batch_ratio,
)
else:
- async with aio_predictor_execution_guard(predictor):
+ async with vlm_runtime["aio_predictor_execution_guard"](predictor):
window_model_list = await predictor.aio_batch_two_step_extract(
images=images_pil_list,
not_extract_list=list(NOT_EXTRACT_TYPES),
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index aa4af06e..d3f0e50e 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -11,6 +11,7 @@ from ...utils.hash_utils import bytes_md5
from ...utils.image_payload import ImagePayloadCache
from ...utils.pdf_document import PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
+from ...utils.backend_options import validate_effort
from ..pipeline.model_init import MineruHybridModel
from ..utils.formula_number import optimize_hybrid_formula_number_blocks
from ..utils.middle_json_utils import apply_post_ocr
@@ -154,11 +155,12 @@ def apply_server_side_postprocess(
def finalize_middle_json_from_preproc(pages: list[PageInfo], effort: str = "medium") -> 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 == "medium",
+ auto_merge_vertical_by_det=effort in {"low", "medium"},
)
table_enable = get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
diff --git a/mineru/cli_old/api_request.py b/mineru/cli_old/api_request.py
index f9df94b5..7c91e393 100644
--- a/mineru/cli_old/api_request.py
+++ b/mineru/cli_old/api_request.py
@@ -119,8 +119,8 @@ async def parse_request_form(
Form(
description="""The backend for parsing:
- pipeline: More general, supports multiple languages, hallucination-free.
-- hybrid-engine: Hybrid parsing via local computing power, supports multiple languages. Use effort to switch medium/high behavior.
-- hybrid-http-client: Hybrid parsing via remote computing power but requires a little local computing power(client suitable for openai-compatible servers), supports multiple languages. Use effort to switch medium/high behavior.""",
+- hybrid-engine: Hybrid parsing via local computing power, supports multiple languages. Use effort to switch low/medium/high behavior.
+- hybrid-http-client: Hybrid parsing via remote computing power but requires a little local computing power(client suitable for openai-compatible servers), supports multiple languages. Use effort to switch low/medium/high behavior.""",
json_schema_extra=BACKEND_SCHEMA_EXTRA,
),
] = DEFAULT_BACKEND,
@@ -129,6 +129,7 @@ async def parse_request_form(
Form(
description="""(Adapted only for hybrid backend) Hybrid parsing effort:
- medium: Faster parsing for most documents, balancing accuracy and efficiency. Image/chart analysis is disabled.
+- low: Local Hybrid processing without VLM calls. Image/chart analysis is disabled.
- high: Higher-accuracy parsing with image/chart analysis support, which may take longer.""",
json_schema_extra=HYBRID_EFFORT_SCHEMA_EXTRA,
),
@@ -156,7 +157,7 @@ async def parse_request_form(
Form(
description=(
"Enable image/chart analysis for hybrid backends. "
- "Hybrid medium effort automatically disables image/chart analysis."
+ "Hybrid low and medium efforts automatically disable image/chart analysis."
),
),
] = True,
diff --git a/mineru/cli_old/client.py b/mineru/cli_old/client.py
index 0d0c5d62..ddeb395a 100644
--- a/mineru/cli_old/client.py
+++ b/mineru/cli_old/client.py
@@ -1073,6 +1073,7 @@ async def run_orchestrated_cli(
metavar="[" + "|".join(HYBRID_EFFORT_CHOICES) + "]",
help="""\b
Hybrid parsing effort:
+ low: Local Hybrid processing without VLM calls. Image/chart analysis is disabled.
medium: Faster parsing for most documents, balancing accuracy and efficiency. Image/chart analysis is disabled.
high: Higher-accuracy parsing with image/chart analysis support, which may take longer.
Without effort specified, medium will be used by default.
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 93a1b046..652566c9 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -730,7 +730,7 @@ def do_parse(
ensure_backend_dependencies(backend)
backend = backend[7:]
- if backend == "engine":
+ if backend == "engine" and effort != "low":
backend = get_vlm_engine(inference_engine="auto", is_async=False)
os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
@@ -844,7 +844,7 @@ async def aio_do_parse(
ensure_backend_dependencies(backend)
backend = backend[7:]
- if backend == "engine":
+ if backend == "engine" and effort != "low":
backend = get_vlm_engine(inference_engine="auto", is_async=True)
os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
diff --git a/mineru/cli_old/gradio_app.py b/mineru/cli_old/gradio_app.py
index 89166674..7ece4517 100644
--- a/mineru/cli_old/gradio_app.py
+++ b/mineru/cli_old/gradio_app.py
@@ -856,7 +856,7 @@ def resolve_parse_method(file_path, is_ocr, backend):
def is_image_analysis_option_visible(backend, effort=DEFAULT_HYBRID_EFFORT):
- """判断 Gradio 图片分析开关是否应展示;Hybrid medium 会强制关闭图片分析。"""
+ """判断 Gradio 图片分析开关是否应展示;只有 Hybrid high 支持图片分析。"""
if not isinstance(backend, str):
return False
try:
@@ -1675,7 +1675,7 @@ def main(ctx,
"image_analysis_enable": "启用图片分析",
"image_analysis_info": "禁用后,图片/图表块仍保留版面位置,但跳过 VLM 图片/图表分析。",
"effort": "解析强度",
- "effort_info": "Medium 速度更快;High 精度更高,耗时可能更长。",
+ "effort_info": "Low 使用本地 Hybrid 处理;Medium 速度更快;High 精度更高,耗时可能更长。",
"formula_label_vlm": "启用行间公式识别",
"formula_label_pipeline": "启用公式识别",
"formula_label_hybrid": "启用行内公式识别",
diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.py
index f0a8bc81..787fccdd 100644
--- a/mineru/kit/commands/api_server.py
+++ b/mineru/kit/commands/api_server.py
@@ -25,7 +25,7 @@ def api_server_cmd(
max_wait: int = 600,
language: str = "ch",
ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
- effort: Literal["medium", "high"] = "medium",
+ effort: Literal["low", "medium", "high"] = "medium",
disable_table: bool = False,
disable_formula: bool = False,
disable_image_analysis: bool = False,
diff --git a/mineru/kit/commands/parse.py b/mineru/kit/commands/parse.py
index 2e37a652..2dafc28a 100644
--- a/mineru/kit/commands/parse.py
+++ b/mineru/kit/commands/parse.py
@@ -34,7 +34,7 @@ def parse_cmd(
api_key: str | None = None,
language: str = "ch",
ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
- effort: Literal["medium", "high"] = "medium",
+ effort: Literal["low", "medium", "high"] = "medium",
disable_table: bool = False,
disable_formula: bool = False,
disable_image_analysis: bool = False,
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index b14cb85c..9ed6fa26 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -48,7 +48,7 @@ def parse_command(
api_key: str | None = typer.Option(None, "--api-key", help="API key for remote parse service"),
language: str = typer.Option("ch", "--language", help="Parser language hint"),
ocr_mode: str = typer.Option("auto", "--ocr-mode", help="OCR mode: auto, txt, ocr"),
- effort: str = typer.Option("medium", "--effort", help="Hybrid effort: medium, high"),
+ effort: str = typer.Option("medium", "--effort", help="Hybrid effort: low, medium, high"),
disable_table: bool = typer.Option(False, "--disable-table", help="Disable table recognition"),
disable_formula: bool = typer.Option(False, "--disable-formula", help="Disable formula recognition"),
disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help="Disable image analysis"),
@@ -86,7 +86,7 @@ def api_server_command(
max_wait: int = typer.Option(600, "--max-wait", help="Maximum seconds for wait parameter"),
language: str = typer.Option("ch", "--language", help="Parser language hint"),
ocr_mode: str = typer.Option("auto", "--ocr-mode", help="OCR mode: auto, txt, ocr"),
- effort: str = typer.Option("medium", "--effort", help="Hybrid effort: medium, high"),
+ effort: str = typer.Option("medium", "--effort", help="Hybrid effort: low, medium, high"),
disable_table: bool = typer.Option(False, "--disable-table", help="Disable table recognition"),
disable_formula: bool = typer.Option(False, "--disable-formula", help="Disable formula recognition"),
disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help="Disable image analysis"),
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index c6de3c17..d02d1f86 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -2047,8 +2047,8 @@ def create_app(
ocr_mode:
PDF OCR/text extraction mode for pipeline and hybrid backends.
effort:
- Hybrid backend effort level. Medium is faster. High is more accurate
- and may take longer.
+ Hybrid backend effort level. Low uses local Hybrid processing. Medium is
+ faster. High is more accurate and may take longer.
table_enable:
Whether table recognition is enabled.
formula_enable:
@@ -2060,7 +2060,8 @@ def create_app(
raw_backend = backend
tier, backend = _resolve_server_tier_and_backend(tier=tier, backend=backend)
backend, effort = resolve_backend_and_effort(raw_backend or backend, effort)
- _preflight_tier_dependencies(tier)
+ dependency_tier = "standard" if backend.startswith("hybrid-") and effort == "low" else tier
+ _preflight_tier_dependencies(dependency_tier)
_api_key: str | None = api_key or None
_upload_dir = pathlib.Path(upload_dir) if upload_dir else pathlib.Path(tempfile.mkdtemp(prefix="mineru_"))
_upload_dir.mkdir(parents=True, exist_ok=True)
@@ -2209,7 +2210,7 @@ def create_app(
@click.option(
"--effort",
default="medium",
- type=click.Choice(("medium", "high")),
+ type=click.Choice(("low", "medium", "high")),
help=HYBRID_EFFORT_HELP,
)
@click.option("--disable-table", is_flag=True, help="Disable table recognition.")
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index ce6a3c36..1c21ffeb 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -344,7 +344,7 @@ class PdfHybridParser(PdfBaseParser):
) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
- backend = _resolve_hybrid_backend(self.backend, is_async=False)
+ backend = self.backend if self.effort == "low" else _resolve_hybrid_backend(self.backend, is_async=False)
server_url = self.server_url if backend.endswith("client") else None
os.environ["MINERU_VLM_FORMULA_ENABLE"] = "true"
os.environ["MINERU_VLM_TABLE_ENABLE"] = str(self.table_enable).lower()
@@ -372,7 +372,7 @@ class PdfHybridParser(PdfBaseParser):
) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import aio_doc_analyze as hybrid_aio_doc_analyze
- backend = _resolve_hybrid_backend(self.backend, is_async=True)
+ backend = self.backend if self.effort == "low" else _resolve_hybrid_backend(self.backend, is_async=True)
server_url = self.server_url if backend.endswith("client") else None
os.environ["MINERU_VLM_FORMULA_ENABLE"] = "true"
os.environ["MINERU_VLM_TABLE_ENABLE"] = str(self.table_enable).lower()
diff --git a/mineru/utils/backend_options.py b/mineru/utils/backend_options.py
index dbcdcfda..d8247705 100644
--- a/mineru/utils/backend_options.py
+++ b/mineru/utils/backend_options.py
@@ -7,7 +7,7 @@ CANONICAL_HYBRID_ENGINE: Final = "hybrid-engine"
DEFAULT_BACKEND: Final = CANONICAL_HYBRID_ENGINE
DEFAULT_HYBRID_EFFORT: Final = "medium"
DEFAULT_EFFORT: Final = DEFAULT_HYBRID_EFFORT
-HYBRID_EFFORT_HELP: Final = "Medium is faster. High is more accurate and may take longer."
+HYBRID_EFFORT_HELP: Final = "Low uses local Hybrid processing. Medium is faster. High is more accurate and may take longer."
LOCAL_BACKEND_CHOICES: Final[tuple[str, ...]] = (
"pipeline",
@@ -17,7 +17,7 @@ HTTP_CLIENT_BACKEND_CHOICES: Final[tuple[str, ...]] = (
"hybrid-http-client",
)
PUBLIC_BACKEND_CHOICES: Final[tuple[str, ...]] = LOCAL_BACKEND_CHOICES + HTTP_CLIENT_BACKEND_CHOICES
-HYBRID_EFFORT_CHOICES: Final[tuple[str, ...]] = ("medium", "high")
+HYBRID_EFFORT_CHOICES: Final[tuple[str, ...]] = ("low", "medium", "high")
BACKEND_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(PUBLIC_BACKEND_CHOICES)}
HYBRID_EFFORT_SCHEMA_EXTRA: Final[dict[str, list[str]]] = {"enum": list(HYBRID_EFFORT_CHOICES)}
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index ff78acf0..a4fcf20c 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -13,6 +13,7 @@ from typer.testing import CliRunner
from mineru.kit.commands import api_server, models, parse, router, vlm_server
from mineru.kit.main import app
+from mineru.types import PageInfo
runner = CliRunner()
@@ -638,6 +639,97 @@ def test_cli_old_hybrid_branch_keeps_effort(monkeypatch: Any, tmp_path: Path) ->
assert seen["kwargs"]["effort"] == "high"
+def test_cli_old_hybrid_low_skips_vlm_engine_resolution(monkeypatch: Any, tmp_path: Path) -> None:
+ from mineru.cli_old import common
+
+ seen: dict[str, Any] = {}
+
+ monkeypatch.setattr(common, "_process_office_doc", lambda *args, **kwargs: [])
+ monkeypatch.setattr(
+ common,
+ "_prepare_pdf_inputs",
+ lambda pdfs, start, end: [
+ SimpleNamespace(pdf_bytes=pdf, retained_page_indices=None, broken_page_indices=None) for pdf in pdfs
+ ],
+ )
+ monkeypatch.setattr(common, "ensure_backend_dependencies", lambda backend: None)
+
+ def fail_get_vlm_engine(*_args: Any, **_kwargs: Any) -> str:
+ """Hybrid low 不应触发 VLM engine 解析。"""
+ raise AssertionError("low effort should not resolve VLM engine")
+
+ def _fake_process_hybrid(*args: Any, **kwargs: Any) -> None:
+ """记录 Hybrid low 仍进入 Hybrid 处理分支。"""
+ seen["backend"] = args[6]
+ seen["pdf_count"] = len(args[2])
+ seen["kwargs"] = kwargs
+
+ monkeypatch.setattr(common, "get_vlm_engine", fail_get_vlm_engine)
+ monkeypatch.setattr(common, "_process_hybrid", _fake_process_hybrid)
+
+ common.do_parse(
+ output_dir=str(tmp_path),
+ pdf_file_names=["a.pdf", "b.pdf"],
+ pdf_bytes_list=[b"%PDF-1.7\n", b"%PDF-1.7\n"],
+ p_lang_list=["ch", "ch"],
+ backend="hybrid-engine",
+ effort="low",
+ )
+
+ assert seen["backend"] == "engine"
+ assert seen["pdf_count"] == 2
+ assert seen["kwargs"]["effort"] == "low"
+
+
+def test_process_hybrid_low_calls_analyzer_per_file(monkeypatch: Any, tmp_path: Path) -> None:
+ from mineru.cli_old import common
+
+ calls: list[bytes] = []
+ outputs: list[tuple[str, str, str]] = []
+
+ def fake_doc_analyze(pdf_bytes: bytes, **_kwargs: Any) -> tuple[list[PageInfo], list[object], bool]:
+ """记录每个文件独立进入 Hybrid low analyzer。"""
+ calls.append(pdf_bytes)
+ return [PageInfo(page_idx=0, _backend="hybrid")], [], False
+
+ monkeypatch.setattr(common, "_load_hybrid_analyze_entrypoint", lambda *_args, **_kwargs: fake_doc_analyze)
+ monkeypatch.setattr(
+ common,
+ "prepare_env",
+ lambda output_dir, pdf_file_name, method: (str(tmp_path / pdf_file_name / "images"), str(tmp_path / pdf_file_name)),
+ )
+ monkeypatch.setattr(common, "FileBasedDataWriter", lambda _path: object())
+ monkeypatch.setattr(
+ common,
+ "_process_output",
+ lambda middle_json, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir, *_args, **_kwargs: outputs.append(
+ (pdf_file_name, local_md_dir, local_image_dir)
+ ),
+ )
+
+ common._process_hybrid(
+ output_dir=str(tmp_path),
+ pdf_file_names=["a.pdf", "b.pdf"],
+ pdf_bytes_list=[b"a", b"b"],
+ h_lang_list=["ch", "ch"],
+ parse_method="auto",
+ inline_formula_enable=True,
+ backend="engine",
+ f_draw_layout_bbox=False,
+ f_draw_span_bbox=False,
+ f_dump_md=True,
+ f_dump_middle_json=True,
+ f_dump_model_output=True,
+ f_dump_orig_pdf=True,
+ f_dump_content_list=True,
+ f_make_md_mode="mm_markdown",
+ effort="low",
+ )
+
+ assert calls == [b"a", b"b"]
+ assert [item[0] for item in outputs] == ["a.pdf", "b.pdf"]
+
+
def test_cli_old_async_legacy_vlm_branch_maps_to_hybrid_high(monkeypatch: Any, tmp_path: Path) -> None:
from mineru.cli_old import common
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 5601cf59..2c83ed7b 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -4,6 +4,7 @@ import inspect
import io
import json
import logging
+import subprocess
import sys
import types
from pathlib import Path
@@ -45,6 +46,48 @@ def _stub_api_server_dependency_preflight(monkeypatch: pytest.MonkeyPatch) -> No
monkeypatch.setattr(importlib, "import_module", lambda _module_name: object())
+def test_hybrid_analyze_import_does_not_require_vlm_utils() -> None:
+ """校验 Hybrid low 所需模块导入阶段不再强依赖 VLM 工具包。"""
+ repo_root = Path(__file__).resolve().parents[2]
+ code = """
+import importlib.abc
+import sys
+
+
+class BlockVlmUtilsFinder(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ # 阻断 mineru_vl_utils 导入,用来验证 Hybrid low 的 lazy import 边界。
+ if fullname == "mineru_vl_utils" or fullname.startswith("mineru_vl_utils."):
+ raise ModuleNotFoundError(f"blocked VLM utility import: {fullname}")
+ return None
+
+
+sys.meta_path.insert(0, BlockVlmUtilsFinder())
+import mineru.backend.hybrid.hybrid_analyze
+print("ok")
+"""
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ cwd=repo_root,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == "ok"
+
+
+def test_validate_effort_accepts_low_and_keeps_legacy_vlm_high() -> None:
+ """校验 low 成为公开 Hybrid effort,旧 VLM backend 仍强制 high。"""
+ from mineru.utils.backend_options import HYBRID_EFFORT_CHOICES, resolve_backend_and_effort, validate_effort
+
+ assert validate_effort("low") == "low"
+ assert "low" in HYBRID_EFFORT_CHOICES
+ assert resolve_backend_and_effort("vlm-engine", "low") == ("hybrid-engine", "high")
+
+
def test_api_client_builds_file_page_range_without_options(tmp_path: Path) -> None:
pdf = tmp_path / "demo.pdf"
pdf.write_bytes(b"%PDF-1.7\n")
@@ -954,6 +997,33 @@ def test_build_parser_maps_legacy_vlm_backend_to_hybrid_high(tmp_path: Path) ->
assert parser.effort == "high"
+def test_pdf_hybrid_low_parser_skips_vlm_backend_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
+ """校验 Hybrid low 直接进入本地分支,不解析 VLM engine。"""
+ seen: dict[str, object] = {}
+ fake_module = types.ModuleType("mineru.backend.hybrid.hybrid_analyze")
+
+ def fake_doc_analyze(_pdf_bytes: bytes, **kwargs: object) -> tuple[list[PageInfo], list[object], bool]:
+ """记录 low 分支收到的参数,并返回 Hybrid middle-json 形态。"""
+ seen.update(kwargs)
+ return [PageInfo(page_idx=0, _backend="hybrid")], [], False
+
+ fake_module.doc_analyze = fake_doc_analyze
+ monkeypatch.setitem(sys.modules, "mineru.backend.hybrid.hybrid_analyze", fake_module)
+
+ def fail_resolve_backend(*_args: object, **_kwargs: object) -> str:
+ """low 不应触发 VLM backend resolver。"""
+ raise AssertionError("low effort should not resolve VLM backend")
+
+ monkeypatch.setattr(parser_pdf, "_resolve_hybrid_backend", fail_resolve_backend)
+
+ parser = parser_pdf.PdfHybridParser(backend="hybrid-engine", effort="low")
+ pages = parser._run_analysis(b"%PDF-1.7\n")
+
+ assert pages[0]._backend == "hybrid"
+ assert seen["backend"] == "hybrid-engine"
+ assert seen["effort"] == "low"
+
+
@pytest.mark.parametrize(
("resolver", "backend"),
[
@@ -1127,13 +1197,13 @@ def test_api_server_cli_exposes_parser_runtime_options() -> None:
def test_api_server_cli_accepts_backend_alias(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, str] = {}
- def _fake_run(app, *, host: str, port: int) -> None:
+ def _fake_run(server) -> None:
"""记录 Click CLI 创建出的应用配置,避免测试启动真实 uvicorn 服务。"""
- seen["backend"] = app.state.backend
- seen["host"] = host
- seen["port"] = str(port)
+ seen["backend"] = server.config.app.state.backend
+ seen["host"] = server.config.host
+ seen["port"] = str(server.config.port)
- monkeypatch.setattr("uvicorn.run", _fake_run)
+ monkeypatch.setattr("uvicorn.Server.run", _fake_run)
result = runner.invoke(main, ["--backend", "hybrid-auto-engine", "--host", "0.0.0.0", "--port", "15981"])
@@ -1144,12 +1214,12 @@ def test_api_server_cli_accepts_backend_alias(monkeypatch: pytest.MonkeyPatch) -
def test_api_server_cli_maps_legacy_vlm_backend_to_hybrid_high(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, str] = {}
- def _fake_run(app, *, host: str, port: int) -> None:
+ def _fake_run(server) -> None:
"""记录 legacy VLM backend 进入 CLI 后的实际 parser 配置。"""
- seen["backend"] = app.state.backend
- seen["effort"] = app.state.effort
+ seen["backend"] = server.config.app.state.backend
+ seen["effort"] = server.config.app.state.effort
- monkeypatch.setattr("uvicorn.run", _fake_run)
+ monkeypatch.setattr("uvicorn.Server.run", _fake_run)
result = runner.invoke(main, ["--backend", "vlm-http-client", "--host", "0.0.0.0", "--port", "15983"])
@@ -1160,11 +1230,11 @@ def test_api_server_cli_maps_legacy_vlm_backend_to_hybrid_high(monkeypatch: pyte
def test_api_server_cli_normalizes_hidden_language_alias(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, str] = {}
- def _fake_run(app, *, host: str, port: int) -> None:
+ def _fake_run(server) -> None:
"""记录 Click CLI 创建出的应用语言配置,避免测试启动真实服务。"""
- seen["language"] = app.state.language
+ seen["language"] = server.config.app.state.language
- monkeypatch.setattr("uvicorn.run", _fake_run)
+ monkeypatch.setattr("uvicorn.Server.run", _fake_run)
result = runner.invoke(main, ["--language", "latin", "--host", "0.0.0.0", "--port", "15982"])
@@ -1202,7 +1272,9 @@ def test_api_server_cli_effort_help_matches_gradio_copy() -> None:
"""校验 api server 的 effort 帮助文案与 Gradio 英文提示保持一致。"""
effort_option = next(param for param in main.params if "--effort" in param.opts)
- assert effort_option.help == "Medium is faster. High is more accurate and may take longer."
+ assert effort_option.help == (
+ "Low uses local Hybrid processing. Medium is faster. High is more accurate and may take longer."
+ )
def test_api_server_public_exports_are_runtime_entrypoints_only() -> None:
diff --git a/tests/unittest/test_title_level_postprocess.py b/tests/unittest/test_title_level_postprocess.py
index 5c4528b1..e262473a 100644
--- a/tests/unittest/test_title_level_postprocess.py
+++ b/tests/unittest/test_title_level_postprocess.py
@@ -19,6 +19,20 @@ def test_finalize_client_side_pages_passes_hybrid_effort(monkeypatch) -> None:
assert calls == ["high"]
+def test_finalize_client_side_pages_accepts_hybrid_low(monkeypatch) -> None:
+ """校验客户端 Hybrid finalize 支持 low effort,并仍走 Hybrid 分支。"""
+ calls: list[str] = []
+ pages = [PageInfo(page_idx=0, _backend="hybrid")]
+ monkeypatch.setattr(
+ "mineru.backend.hybrid.model_output_to_middle_json.finalize_middle_json_from_preproc",
+ lambda parsed_pages, effort="medium": calls.append(effort),
+ )
+
+ title_level_postprocess.finalize_client_side_pages(pages, "hybrid", effort="low")
+
+ assert calls == ["low"]
+
+
def test_regenerate_client_side_outputs_forwards_hybrid_effort(monkeypatch, tmp_path) -> None:
"""校验客户端重建输出时继续把 Hybrid effort 传到 finalize 阶段。"""
from mineru.cli_old import client_side_output