Skip to content

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

feat: update hybrid effort terminology and adjust related logic for medium and extra_high levels

myhloli01aa3ba839c9
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 35ade568..3d4a96fe 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -16,7 +16,13 @@ from tqdm import tqdm
from ...types import NOT_EXTRACT_TYPES, BBox, PageInfo
from ...types import BlockType as MineruBlockType
-from ...utils.backend_options import validate_effort
+from ...utils.backend_options import (
+ DEFAULT_HYBRID_EFFORT,
+ LAYOUT_HYBRID_EFFORT,
+ LOCAL_HYBRID_EFFORT,
+ MAX_HYBRID_EFFORT,
+ 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
@@ -58,7 +64,7 @@ LAYOUT_BASE_BATCH_SIZE = 1
MFR_BASE_BATCH_SIZE = 16
OCR_DET_BASE_BATCH_SIZE = 8
LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8
-HYBRID_MEDIUM_LAYOUT_LABEL_MAP = {
+HYBRID_VLM_LAYOUT_LABEL_MAP = {
"abstract": MineruBlockType.TEXT,
"algorithm": MineruBlockType.ALGORITHM,
"aside_text": MineruBlockType.ASIDE_TEXT,
@@ -83,8 +89,8 @@ HYBRID_MEDIUM_LAYOUT_LABEL_MAP = {
"vertical_text": MineruBlockType.TEXT,
}
-HYBRID_LOW_LAYOUT_LABEL_MAP = {
- **HYBRID_MEDIUM_LAYOUT_LABEL_MAP,
+HYBRID_MEDIUM_LAYOUT_LABEL_MAP = {
+ **HYBRID_VLM_LAYOUT_LABEL_MAP,
"doc_title": MineruBlockType.DOC_TITLE,
"paragraph_title": MineruBlockType.PARAGRAPH_TITLE,
"figure_title": MineruBlockType.IMAGE_CAPTION,
@@ -93,14 +99,14 @@ HYBRID_LOW_LAYOUT_LABEL_MAP = {
def _load_vlm_content_block() -> Any:
- """按需加载 VLM ContentBlock,避免 Hybrid low 导入阶段依赖 mineru_vl_utils。"""
+ """按需加载 VLM ContentBlock,避免 Hybrid medium 导入阶段依赖 mineru_vl_utils。"""
from mineru_vl_utils.structs import ContentBlock
return ContentBlock
def _load_vlm_runtime() -> dict[str, Any]:
- """按需加载 VLM runtime 组件,确保只有 medium/high 路径触发 VLM 依赖。"""
+ """按需加载 VLM runtime 组件,确保只有 high/extra_high 路径触发 VLM 依赖。"""
from ...model.vlm.runtime import (
ModelSingleton,
_get_model_async,
@@ -123,8 +129,8 @@ def _is_hybrid_ocr_det_candidate(block: dict[str, Any]) -> bool:
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 标签。"""
+def _is_hybrid_medium_ocr_det_candidate(block: dict[str, Any]) -> bool:
+ """判断 Hybrid medium 本地 layout 块是否需要 OCR det,覆盖 doc/index/list 等 layout 标签。"""
item_type = block.get("type") or block.get("label")
return item_type in {
*NOT_EXTRACT_TYPES,
@@ -477,7 +483,7 @@ def _normalize_layout_bbox_to_unit(bbox: BBox | None, page_size: tuple[int, int]
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))
+ block_type = HYBRID_VLM_LAYOUT_LABEL_MAP.get(str(label))
if block_type is None:
return None
@@ -489,15 +495,15 @@ def _layout_item_to_content_block(layout_item: dict[str, Any], page_size: tuple[
try:
return ContentBlock(type=block_type, bbox=bbox, angle=layout_item.get("angle", 0) or 0)
except AssertionError:
- logger.debug(f"Skip invalid Hybrid medium layout block: {layout_item}")
+ logger.debug(f"Skip invalid Hybrid high layout block: {layout_item}")
return None
-def _build_medium_layout_blocks(
+def _build_high_layout_blocks(
images_layout_res: list[list[dict[str, Any]]],
images_pil_list: list[Image.Image],
) -> list[list[Any]]:
- """按页构造 Hybrid medium 模式传给 VLM 的外部 layout blocks。"""
+ """按页构造 Hybrid high 模式传给 VLM 的外部 layout blocks。"""
blocks_list: list[list[Any]] = []
for layout_res, image in zip(images_layout_res, images_pil_list):
page_size = _normalize_page_size(image)
@@ -510,13 +516,13 @@ def _build_medium_layout_blocks(
return blocks_list
-def _is_low_table_enabled() -> bool:
- """读取 Hybrid low 的表格开关,复用 Hybrid 当前通过环境变量传入的表格配置。"""
+def _is_medium_table_enabled() -> bool:
+ """读取 Hybrid medium 的表格开关,复用 Hybrid 当前通过环境变量传入的表格配置。"""
return get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
-def _normalize_low_content(value: Any) -> str:
- """将 low 本地模型输出的文本字段规范成 Hybrid block 可消费的字符串。"""
+def _normalize_medium_content(value: Any) -> str:
+ """将 medium 本地模型输出的文本字段规范成 Hybrid block 可消费的字符串。"""
if isinstance(value, list):
return "\n".join(str(item) for item in value if str(item).strip())
if isinstance(value, str):
@@ -524,7 +530,7 @@ def _normalize_low_content(value: Any) -> str:
return ""
-def _low_layout_item_to_hybrid_item(
+def _medium_layout_item_to_hybrid_item(
layout_item: dict[str, Any],
page_size: tuple[int, int],
) -> dict[str, Any] | None:
@@ -536,7 +542,7 @@ def _low_layout_item_to_hybrid_item(
score = float(layout_item.get("score", 0.0) or 0.0)
if label == "inline_formula":
- latex = _normalize_low_content(layout_item.get("latex", ""))
+ latex = _normalize_medium_content(layout_item.get("latex", ""))
if not latex:
return None
return {"type": "inline_formula", "bbox": bbox, "latex": latex, "score": score}
@@ -544,11 +550,11 @@ def _low_layout_item_to_hybrid_item(
return {
"type": "ocr_text",
"bbox": bbox,
- "text": _normalize_low_content(layout_item.get("text", "")),
+ "text": _normalize_medium_content(layout_item.get("text", "")),
"score": score,
}
- block_type = HYBRID_LOW_LAYOUT_LABEL_MAP.get(label)
+ block_type = HYBRID_MEDIUM_LAYOUT_LABEL_MAP.get(label)
if block_type is None:
return None
@@ -561,42 +567,42 @@ def _low_layout_item_to_hybrid_item(
hybrid_item["sub_type"] = "seal"
if block_type == MineruBlockType.TABLE:
- hybrid_item["content"] = _normalize_low_content(layout_item.get("html", ""))
+ hybrid_item["content"] = _normalize_medium_content(layout_item.get("html", ""))
elif block_type == MineruBlockType.EQUATION:
- hybrid_item["content"] = _normalize_low_content(layout_item.get("latex", ""))
+ hybrid_item["content"] = _normalize_medium_content(layout_item.get("latex", ""))
else:
- content = _normalize_low_content(layout_item.get("text", ""))
+ content = _normalize_medium_content(layout_item.get("text", ""))
if content:
hybrid_item["content"] = content
return hybrid_item
-def _build_low_hybrid_model_list(
+def _build_medium_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 形态。"""
+ """按页构造 Hybrid medium 的模型输出,保持最终 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)
+ hybrid_item = _medium_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(
+def _run_medium_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 遮罩使用的公式框。"""
+ """执行 Hybrid medium 的本地公式识别,并返回供 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"]
@@ -635,7 +641,7 @@ def _run_low_formula_recognition(
return mfd_res
-def _apply_low_table_rotate_label(table_res_dict: dict[str, Any], rotate_label: str) -> None:
+def _apply_medium_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
@@ -649,12 +655,12 @@ def _apply_low_table_rotate_label(table_res_dict: dict[str, Any], rotate_label:
table_res_dict["wired_table_img"] = cv2.rotate(np.asarray(table_res_dict["wired_table_img"]), rotate_code)
-def _collect_low_table_items(
+def _collect_medium_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 单文件窗口中的表格裁剪项,不跨文件聚合。"""
+ """收集 Hybrid medium 单文件窗口中的表格裁剪项,不跨文件聚合。"""
table_items = []
for layout_res, np_img, lang in zip(images_layout_res, np_images, lang_list):
for table_res in layout_res:
@@ -662,7 +668,7 @@ def _collect_low_table_items(
continue
def get_crop_table_img(scale: float) -> np.ndarray:
- """按指定缩放裁剪表格图,保持 low 表格处理只使用当前文件窗口图像。"""
+ """按指定缩放裁剪表格图,保持 medium 表格处理只使用当前文件窗口图像。"""
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]
@@ -683,7 +689,7 @@ def _collect_low_table_items(
return table_items
-def _collect_low_table_ocr_rec_inputs(
+def _collect_medium_table_ocr_rec_inputs(
atom_model_manager: Any,
table_items: list[dict[str, Any]],
batch_ratio: int,
@@ -706,10 +712,10 @@ def _collect_low_table_ocr_rec_inputs(
det_images,
det_batch_size,
tqdm_enable=True,
- tqdm_desc="Hybrid-low table OCR-det",
+ tqdm_desc="Hybrid-medium table OCR-det",
)
if len(batch_results) != len(table_items):
- raise ValueError("Hybrid low table OCR det batch result count mismatch")
+ raise ValueError("Hybrid medium 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:
@@ -726,18 +732,18 @@ def _collect_low_table_ocr_rec_inputs(
return rec_img_lang_group
-def _apply_low_table_recognition(
+def _apply_medium_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():
+ """执行 Hybrid medium 的本地表格识别,结果写回 layout table 项的 html 字段。"""
+ if not _is_medium_table_enabled():
return
- table_items = _collect_low_table_items(images_layout_res, np_images, lang_list)
+ table_items = _collect_medium_table_items(images_layout_res, np_images, lang_list)
if not table_items:
return
@@ -749,19 +755,19 @@ def _apply_low_table_recognition(
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")
+ raise ValueError("Hybrid medium 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)
+ _apply_medium_table_rotate_label(table_item, rotate_label)
except Exception as exc:
- logger.warning(f"Hybrid low table orientation classification failed: {exc}, using original image")
+ logger.warning(f"Hybrid medium 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")
+ logger.warning(f"Hybrid medium table classification failed: {exc}, using default model")
- rec_img_lang_group = _collect_low_table_ocr_rec_inputs(atom_model_manager, table_items, batch_ratio)
+ rec_img_lang_group = _collect_medium_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
@@ -777,7 +783,7 @@ def _apply_low_table_recognition(
[item["cropped_img"] for item in rec_img_list],
det=False,
tqdm_enable=True,
- tqdm_desc=f"Hybrid-low table OCR-rec {lang}",
+ tqdm_desc=f"Hybrid-medium 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"]]
@@ -796,7 +802,7 @@ def _apply_low_table_recognition(
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"):
+ for table_item in tqdm(wired_table_items, desc="Hybrid-medium table-wired predict"):
if not table_item.get("ocr_result"):
continue
wired_table_model = atom_model_manager.get_atom_model(
@@ -817,12 +823,12 @@ def _apply_low_table_recognition(
table_item["table_res"]["html"] = html_code[start_index:end_index]
-def _apply_low_seal_ocr(
+def _apply_medium_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 项。"""
+ """执行 Hybrid medium 的印章 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:
@@ -853,7 +859,7 @@ def _apply_low_seal_ocr(
layout_item["text"] = seal_texts
-def _prune_low_empty_ocr_text_blocks(images_layout_res: list[list[dict[str, Any]]], ocr_enable: bool) -> None:
+def _prune_medium_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
@@ -861,7 +867,7 @@ def _prune_low_empty_ocr_text_blocks(images_layout_res: list[list[dict[str, Any]
layout_res[:] = [
item
for item in layout_res
- if item.get("label") != "ocr_text" or bool(_normalize_low_content(item.get("text", "")))
+ if item.get("label") != "ocr_text" or bool(_normalize_medium_content(item.get("text", "")))
]
@@ -872,7 +878,7 @@ def _extract_with_local_layout(
_ocr_enable: bool,
batch_ratio: int,
) -> tuple[list[list[dict[str, Any]]], MineruHybridModel]:
- """Hybrid low 路径:单文件窗口内执行本地 layout/OCR/table/formula,不跨文件 batch。"""
+ """Hybrid medium 路径:单文件窗口内执行本地 layout/OCR/table/formula,不跨文件 batch。"""
hybrid_model_singleton = HybridModelSingleton()
hybrid_pipeline_model = hybrid_model_singleton.get_model(
lang=language,
@@ -884,35 +890,35 @@ def _extract_with_local_layout(
images_pil_list,
batch_size=min(8, batch_ratio * LAYOUT_BASE_BATCH_SIZE),
)
- mfd_res = _run_low_formula_recognition(
+ mfd_res = _run_medium_formula_recognition(
hybrid_pipeline_model,
images_layout_res,
np_images,
inline_formula_enable,
batch_ratio,
)
- _apply_low_table_recognition(
+ _apply_medium_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)
+ _apply_medium_seal_ocr(hybrid_pipeline_model, images_layout_res, np_images)
+ _prune_medium_empty_ocr_text_blocks(images_layout_res, _ocr_enable)
+ medium_model_list = _build_medium_hybrid_model_list(images_layout_res, images_pil_list)
ocr_res_list = _ocr_det(
hybrid_pipeline_model,
np_images,
- low_model_list,
+ medium_model_list,
mfd_res,
_ocr_enable,
batch_ratio=batch_ratio,
- candidate_fn=_is_hybrid_low_ocr_det_candidate,
+ candidate_fn=_is_hybrid_medium_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,
+ medium_model_list,
[[] for _ in images_pil_list],
ocr_res_list,
)
@@ -1086,7 +1092,7 @@ def _extract_with_pipeline_layout(
_ocr_enable: bool,
batch_ratio: int,
) -> tuple[list[list[dict[str, Any]]], MineruHybridModel]:
- """Hybrid medium 路径:用 Pipeline layout 约束 VLM 抽取,再补 OCR/formula sidecar。"""
+ """Hybrid high 路径:用 Pipeline layout 约束 VLM 抽取,再补 OCR/formula sidecar。"""
hybrid_model_singleton = HybridModelSingleton()
hybrid_pipeline_model = hybrid_model_singleton.get_model(
lang=language,
@@ -1094,7 +1100,7 @@ def _extract_with_pipeline_layout(
)
np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
images_layout_res = _predict_layout_for_title_split(hybrid_pipeline_model, np_images, batch_ratio)
- layout_blocks = _build_medium_layout_blocks(images_layout_res, images_pil_list)
+ layout_blocks = _build_high_layout_blocks(images_layout_res, images_pil_list)
window_model_list = predictor.batch_extract_with_layout(
images=images_pil_list,
blocks_list=layout_blocks,
@@ -1120,7 +1126,7 @@ async def _aio_extract_with_pipeline_layout(
_ocr_enable: bool,
batch_ratio: int,
) -> tuple[list[list[dict[str, Any]]], MineruHybridModel]:
- """Hybrid medium 异步路径:异步调用 VLM layout-aware extract,其余本地步骤放线程执行。"""
+ """Hybrid high 异步路径:异步调用 VLM layout-aware extract,其余本地步骤放线程执行。"""
hybrid_model_singleton = HybridModelSingleton()
hybrid_pipeline_model = hybrid_model_singleton.get_model(
lang=language,
@@ -1133,7 +1139,7 @@ async def _aio_extract_with_pipeline_layout(
np_images,
batch_ratio,
)
- layout_blocks = _build_medium_layout_blocks(images_layout_res, images_pil_list)
+ layout_blocks = _build_high_layout_blocks(images_layout_res, images_pil_list)
window_model_list = await predictor.aio_batch_extract_with_layout(
images=images_pil_list,
blocks_list=layout_blocks,
@@ -1298,7 +1304,7 @@ def get_batch_ratio(device: str) -> int:
def _should_enable_vlm_ocr(ocr_enable: bool, language: str, inline_formula_enable: bool) -> bool:
- """判断 high effort 是否启用 VLM OCR 两阶段抽取。"""
+ """判断 extra_high effort 是否启用 VLM OCR 两阶段抽取。"""
force_enable = os.getenv("MINERU_FORCE_VLM_OCR_ENABLE", "0").lower() in ("1", "true", "yes")
if force_enable:
return True
@@ -1332,7 +1338,7 @@ def doc_analyze(
inline_formula_enable: bool = True,
model_path: str | None = None,
server_url: str | None = None,
- effort: Literal["low", "medium", "high"] = "medium",
+ effort: Literal["medium", "high", "extra_high"] = DEFAULT_HYBRID_EFFORT,
image_analysis: bool = True,
page_index_map: list[int] | None = None,
image_cache: ImagePayloadCache | None = None,
@@ -1340,8 +1346,8 @@ def doc_analyze(
) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
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 effort == "low":
+ image_analysis = image_analysis if effort == MAX_HYBRID_EFFORT else False
+ if effort == LOCAL_HYBRID_EFFORT:
predictor = None
else:
vlm_runtime = _load_vlm_runtime()
@@ -1353,7 +1359,11 @@ def doc_analyze(
pdf_doc = PDFDocument(pdf_bytes)
_ocr_enable = ocr_classify(pdf_doc, parse_method=parse_method)
- _vlm_ocr_enable = effort == "high" and _should_enable_vlm_ocr(_ocr_enable, language, inline_formula_enable)
+ _vlm_ocr_enable = effort == MAX_HYBRID_EFFORT and _should_enable_vlm_ocr(
+ _ocr_enable,
+ language,
+ inline_formula_enable,
+ )
middle_json: list[PageInfo] = []
model_list: list[list[dict[str, Any]]] = []
@@ -1390,7 +1400,7 @@ def doc_analyze(
f"pages {window_start + 1}-{window_end + 1}/{page_count} "
f"({len(images_pil_list)} pages)"
)
- if effort == "low":
+ if effort == LOCAL_HYBRID_EFFORT:
window_model_list, hybrid_pipeline_model = _extract_with_local_layout(
images_pil_list,
language,
@@ -1398,7 +1408,7 @@ def doc_analyze(
_ocr_enable,
batch_ratio,
)
- elif effort == "medium":
+ elif effort == LAYOUT_HYBRID_EFFORT:
with vlm_runtime["predictor_execution_guard"](predictor):
window_model_list, hybrid_pipeline_model = _extract_with_pipeline_layout(
predictor,
@@ -1511,7 +1521,7 @@ async def aio_doc_analyze(
inline_formula_enable: bool = True,
model_path: str | None = None,
server_url: str | None = None,
- effort: Literal["low", "medium", "high"] = "medium",
+ effort: Literal["medium", "high", "extra_high"] = DEFAULT_HYBRID_EFFORT,
image_analysis: bool = True,
page_index_map: list[int] | None = None,
image_cache: ImagePayloadCache | None = None,
@@ -1519,8 +1529,8 @@ async def aio_doc_analyze(
) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
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 effort == "low":
+ image_analysis = image_analysis if effort == MAX_HYBRID_EFFORT else False
+ if effort == LOCAL_HYBRID_EFFORT:
predictor = None
else:
vlm_runtime = _load_vlm_runtime()
@@ -1532,7 +1542,11 @@ async def aio_doc_analyze(
pdf_doc = PDFDocument(pdf_bytes)
_ocr_enable = ocr_classify(pdf_doc, parse_method=parse_method)
- _vlm_ocr_enable = effort == "high" and _should_enable_vlm_ocr(_ocr_enable, language, inline_formula_enable)
+ _vlm_ocr_enable = effort == MAX_HYBRID_EFFORT and _should_enable_vlm_ocr(
+ _ocr_enable,
+ language,
+ inline_formula_enable,
+ )
middle_json: list[PageInfo] = []
model_list = []
@@ -1569,7 +1583,7 @@ async def aio_doc_analyze(
f"pages {window_start + 1}-{window_end + 1}/{page_count} "
f"({len(images_pil_list)} pages)"
)
- if effort == "low":
+ if effort == LOCAL_HYBRID_EFFORT:
window_model_list, hybrid_pipeline_model = await asyncio.to_thread(
_extract_with_local_layout,
images_pil_list,
@@ -1578,7 +1592,7 @@ async def aio_doc_analyze(
_ocr_enable,
batch_ratio,
)
- elif effort == "medium":
+ elif effort == LAYOUT_HYBRID_EFFORT:
async with vlm_runtime["aio_predictor_execution_guard"](predictor):
window_model_list, hybrid_pipeline_model = await _aio_extract_with_pipeline_layout(
predictor,
diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.py
index 88a3d4cc..5b14d388 100644
--- a/mineru/backend/hybrid/hybrid_magic_model.py
+++ b/mineru/backend/hybrid/hybrid_magic_model.py
@@ -298,7 +298,7 @@ class MagicModel:
_copy_raw_text_block_metadata(draft, block)
if block.type == BlockType.INDEX:
- # Hybrid medium 使用 INDEX 作为 VLM content 内部哨兵;内容构造完成后再对齐 3.4 输出为 text。
+ # Hybrid VLM 路径使用 INDEX 作为 content 内部哨兵;内容构造完成后再对齐 3.4 输出为 text。
block.type = BlockType.TEXT
blocks.append(block)
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index 5e97b926..762c48e1 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -11,7 +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 ...utils.backend_options import DEFAULT_HYBRID_EFFORT, LAYOUT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, validate_effort
from ..local_model_runtime import MineruHybridModel
from ..utils.formula_number import optimize_hybrid_formula_number_blocks
from ..utils.middle_json_utils import apply_post_ocr
@@ -153,14 +153,14 @@ def apply_server_side_postprocess(
_apply_post_ocr(pages, hybrid_pipeline_model)
-def finalize_middle_json_from_preproc(pages: list[PageInfo], effort: str = "medium") -> None:
+def finalize_middle_json_from_preproc(pages: list[PageInfo], effort: str = DEFAULT_HYBRID_EFFORT) -> None:
"""从 Hybrid preproc_blocks 执行完整 finalize,供服务端完整路径和客户端复用。"""
effort = validate_effort(effort)
build_para_blocks_from_preproc(pages)
merge_para_text_blocks(
pages,
auto_merge_by_det=True,
- auto_merge_vertical_by_det=effort in {"low", "medium"},
+ auto_merge_vertical_by_det=effort in {LOCAL_HYBRID_EFFORT, LAYOUT_HYBRID_EFFORT},
)
table_enable = get_table_enable(os.getenv("MINERU_VLM_TABLE_ENABLE", "True").lower() == "true")
@@ -177,7 +177,7 @@ def finalize_middle_json(
hybrid_pipeline_model: MineruHybridModel,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
) -> None:
"""保持旧入口语义:服务端先做必要 post-OCR,再执行完整 finalize。"""
apply_server_side_postprocess(pages, hybrid_pipeline_model, _ocr_enable, _vlm_ocr_enable)
diff --git a/mineru/backend/local_model_runtime.py b/mineru/backend/local_model_runtime.py
index 15e41ff6..80d8b2ef 100644
--- a/mineru/backend/local_model_runtime.py
+++ b/mineru/backend/local_model_runtime.py
@@ -26,7 +26,7 @@ from ..utils.ocr_language import normalize_ocr_model_lang
class AtomicModel:
- """本地原子模型名称集合,供 Hybrid low 和共享模型单例统一索引。"""
+ """本地原子模型名称集合,供 Hybrid medium 和共享模型单例统一索引。"""
Layout = "layout"
MFD = "mfd"
@@ -38,7 +38,7 @@ class AtomicModel:
TableOrientationCls = "table_ori_cls"
LOCAL_MODEL_INIT_LOCK = threading.RLock()
-# 这些锁保护 Hybrid low/medium/high 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
+# 这些锁保护 Hybrid medium/high/extra_high 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。
LOCAL_MODEL_LAYOUT_INFERENCE_LOCK = threading.RLock()
LOCAL_MODEL_MFR_INFERENCE_LOCK = threading.RLock()
LOCAL_MODEL_OCR_INFERENCE_LOCK = threading.RLock()
diff --git a/mineru/cli_old/api_client.py b/mineru/cli_old/api_client.py
index 595a49e8..c0ec35e8 100644
--- a/mineru/cli_old/api_client.py
+++ b/mineru/cli_old/api_client.py
@@ -23,6 +23,8 @@ import click
import httpx
from loguru import logger
+from mineru.utils.backend_options import DEFAULT_HYBRID_EFFORT
+
from mineru.cli_old.api_protocol import (
API_PROTOCOL_VERSION,
DEFAULT_MAX_CONCURRENT_REQUESTS,
@@ -793,7 +795,7 @@ def build_parse_request_form_data(
end_page_id: Optional[int],
*,
image_analysis: bool = True,
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
return_md: bool,
return_middle_json: bool,
return_model_output: bool,
diff --git a/mineru/cli_old/api_request.py b/mineru/cli_old/api_request.py
index 41777302..544c2dd4 100644
--- a/mineru/cli_old/api_request.py
+++ b/mineru/cli_old/api_request.py
@@ -124,8 +124,8 @@ async def parse_request_form(
str,
Form(
description="""The backend for parsing:
-- hybrid-engine: Hybrid parsing via local computing power. Hybrid low supports language-aware local OCR; 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). Hybrid low supports language-aware local OCR; use effort to switch low/medium/high behavior.""",
+- hybrid-engine: Hybrid parsing via local computing power. Hybrid medium supports language-aware local OCR; use effort to switch medium/high/extra_high behavior.
+- hybrid-http-client: Hybrid parsing via remote computing power but requires a little local computing power(client suitable for openai-compatible servers). Hybrid medium supports language-aware local OCR; use effort to switch medium/high/extra_high behavior.""",
json_schema_extra=BACKEND_SCHEMA_EXTRA,
),
] = DEFAULT_BACKEND,
@@ -133,9 +133,9 @@ async def parse_request_form(
str,
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. Supports language-aware local OCR and table OCR. Image/chart analysis is disabled.
-- high: Higher-accuracy parsing with image/chart analysis support, which may take longer.""",
+- medium: Local Hybrid processing without VLM calls. Supports language-aware local OCR and table OCR. Image/chart analysis is disabled.
+- high: Faster VLM parsing for most documents, balancing accuracy and efficiency. Image/chart analysis is disabled.
+- extra_high: Higher-accuracy parsing with image/chart analysis support, which may take longer.""",
json_schema_extra=HYBRID_EFFORT_SCHEMA_EXTRA,
),
] = DEFAULT_HYBRID_EFFORT,
@@ -162,7 +162,7 @@ async def parse_request_form(
Form(
description=(
"Enable image/chart analysis for hybrid backends. "
- "Hybrid low and medium efforts automatically disable image/chart analysis."
+ "Hybrid medium and high efforts automatically disable image/chart analysis."
),
),
] = True,
diff --git a/mineru/cli_old/client.py b/mineru/cli_old/client.py
index 04b38eab..202e9525 100644
--- a/mineru/cli_old/client.py
+++ b/mineru/cli_old/client.py
@@ -1027,10 +1027,10 @@ 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.
+ medium: Local Hybrid processing without VLM calls. Image/chart analysis is disabled.
+ high: Faster VLM parsing for most documents, balancing accuracy and efficiency. Image/chart analysis is disabled.
+ extra_high: Higher-accuracy parsing with image/chart analysis support, which may take longer.
+ Without effort specified, high will be used by default.
Adapted only for the case where the backend is set to 'hybrid-*'.""",
)
@click.option(
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 8cc45e68..90f2736c 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -19,7 +19,12 @@ from mineru.cli_old.visualization import select_pages_for_pdf_visualization
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
from mineru.render import render_content_list, render_markdown, render_structured_content
-from mineru.utils.backend_options import DEFAULT_BACKEND, DEFAULT_HYBRID_EFFORT, resolve_backend_and_effort
+from mineru.utils.backend_options import (
+ DEFAULT_BACKEND,
+ DEFAULT_HYBRID_EFFORT,
+ LOCAL_HYBRID_EFFORT,
+ resolve_backend_and_effort,
+)
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes
@@ -613,7 +618,7 @@ def do_parse(
ensure_backend_dependencies(backend)
backend = backend[7:]
- if backend == "engine" and effort != "low":
+ if backend == "engine" and effort != LOCAL_HYBRID_EFFORT:
backend = get_vlm_engine(inference_engine="auto", is_async=False)
os.environ["MINERU_VLM_TABLE_ENABLE"] = str(table_enable)
@@ -704,7 +709,7 @@ async def aio_do_parse(
ensure_backend_dependencies(backend)
backend = backend[7:]
- if backend == "engine" and effort != "low":
+ if backend == "engine" and effort != LOCAL_HYBRID_EFFORT:
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 7cbaab59..04acab0e 100644
--- a/mineru/cli_old/gradio_app.py
+++ b/mineru/cli_old/gradio_app.py
@@ -49,6 +49,8 @@ from mineru.utils.backend_options import (
HYBRID_EFFORT_CHOICES,
HYBRID_EFFORT_HELP,
LOCAL_BACKEND_CHOICES,
+ LOCAL_HYBRID_EFFORT,
+ MAX_HYBRID_EFFORT,
normalize_backend,
)
from mineru.utils.ocr_language import PUBLIC_OCR_LANGUAGE_CHOICES, validate_public_ocr_lang
@@ -854,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 high 支持图片分析。"""
+ """判断 Gradio 图片分析开关是否应展示;只有 Hybrid extra_high 支持图片分析。"""
if not isinstance(backend, str):
return False
try:
@@ -862,7 +864,7 @@ def is_image_analysis_option_visible(backend, effort=DEFAULT_HYBRID_EFFORT):
except ValueError:
pass
if backend.startswith("hybrid"):
- return effort == "high"
+ return effort == MAX_HYBRID_EFFORT
return False
@@ -872,14 +874,14 @@ def is_effort_option_visible(backend):
def is_ocr_language_option_visible(backend: object, effort: object = DEFAULT_HYBRID_EFFORT) -> bool:
- """判断 OCR 语言选项是否展示;只有 Hybrid low 对用户暴露语言输入。"""
+ """判断 OCR 语言选项是否展示;只有 Hybrid medium 对用户暴露语言输入。"""
if not isinstance(backend, str):
return False
try:
backend = normalize_backend(backend)
except ValueError:
pass
- return backend.startswith("hybrid") and effort == "low"
+ return backend.startswith("hybrid") and effort == LOCAL_HYBRID_EFFORT
def is_force_ocr_option_visible(backend: object) -> bool:
@@ -1613,9 +1615,9 @@ def main(ctx,
"formula_info_vlm": "If disabled, display formulas will be shown as images.",
"formula_info_hybrid": "If disabled, inline formulas will not be detected or parsed.",
"ocr_language": "OCR Language",
- "ocr_language_info": "Select the OCR language for Hybrid low local OCR and table OCR.",
+ "ocr_language_info": "Select the OCR language for Hybrid medium local OCR and table OCR.",
"force_ocr": "Force enable OCR",
- "force_ocr_info": "Enable only if the result is extremely poor. Hybrid low requires correct OCR language.",
+ "force_ocr_info": "Enable only if the result is extremely poor. Hybrid medium requires correct OCR language.",
"force_ocr_info_hybrid": "Enable only if the result is extremely poor.",
"convert": "Convert",
"clear": "Clear",
@@ -1674,15 +1676,15 @@ def main(ctx,
"image_analysis_enable": "启用图片分析",
"image_analysis_info": "禁用后,图片/图表块仍保留版面位置,但跳过 VLM 图片/图表分析。",
"effort": "解析强度",
- "effort_info": "解析强度越高,解析质量越好但速度越慢;解析强度越低,速度更快但质量可能下降。",
+ "effort_info": "解析强度越高,解析质量越好但速度越慢;medium 为最快的本地 Hybrid 模式。",
"formula_label_vlm": "启用行间公式识别",
"formula_label_hybrid": "启用行内公式识别",
"formula_info_vlm": "禁用后,行间公式将显示为图片。",
"formula_info_hybrid": "禁用后,行内公式将不会被检测或解析。",
"ocr_language": "OCR 语言",
- "ocr_language_info": "为 Hybrid low 的本地 OCR 和表格 OCR 选择语言。",
+ "ocr_language_info": "为 Hybrid medium 的本地 OCR 和表格 OCR 选择语言。",
"force_ocr": "强制启用 OCR",
- "force_ocr_info": "仅在识别效果极差时启用;Hybrid low 需选择正确的 OCR 语言。",
+ "force_ocr_info": "仅在识别效果极差时启用;Hybrid medium 需选择正确的 OCR 语言。",
"force_ocr_info_hybrid": "仅在识别效果极差时启用。",
"convert": "转换",
"clear": "清除",
diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.py
index 787fccdd..9b59fa4f 100644
--- a/mineru/kit/commands/api_server.py
+++ b/mineru/kit/commands/api_server.py
@@ -6,7 +6,7 @@ import typer
from ...parser import api_server as parser_api_server
from ...parser.tier import PARSER_BACKENDS
-from ...utils.backend_options import resolve_backend_and_effort
+from ...utils.backend_options import DEFAULT_HYBRID_EFFORT, resolve_backend_and_effort
from ...utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
from ..errors import exit_with_message
@@ -25,7 +25,7 @@ def api_server_cmd(
max_wait: int = 600,
language: str = "ch",
ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
- effort: Literal["low", "medium", "high"] = "medium",
+ effort: Literal["medium", "high", "extra_high"] = DEFAULT_HYBRID_EFFORT,
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 be5425b0..46cd4255 100644
--- a/mineru/kit/commands/parse.py
+++ b/mineru/kit/commands/parse.py
@@ -6,7 +6,7 @@ from typing import Literal
from ...parser import MinerUApiParser
from ...parser import parse as local_parse
-from ...utils.backend_options import resolve_backend_and_effort
+from ...utils.backend_options import DEFAULT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, resolve_backend_and_effort
from ...utils.ocr_language import validate_public_ocr_lang
from ..common import (
build_remote_api_url,
@@ -34,7 +34,7 @@ def parse_cmd(
api_key: str | None = None,
language: str = "ch",
ocr_mode: Literal["auto", "txt", "ocr"] = "auto",
- effort: Literal["low", "medium", "high"] = "medium",
+ effort: Literal["medium", "high", "extra_high"] = DEFAULT_HYBRID_EFFORT,
disable_table: bool = False,
disable_formula: bool = False,
disable_image_analysis: bool = False,
@@ -77,7 +77,7 @@ def parse_cmd(
exit_with_message("invalid_request", str(exc), "backend")
resolved_tier, resolved_backend = effective_local_tier_and_backend(tier, normalized_backend)
if resolved_tier == "standard":
- normalized_effort = "low"
+ normalized_effort = LOCAL_HYBRID_EFFORT
parse_one = partial(
local_parse,
tier=resolved_tier,
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index 1e885825..48d4cc76 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -6,6 +6,7 @@ import typer
from click.core import Context
from typer.core import TyperGroup
+from ..utils.backend_options import DEFAULT_HYBRID_EFFORT, HYBRID_EFFORT_HELP
from .commands import api_server, models, parse, router, vlm_server
TOP_LEVEL_COMMAND_ORDER = [
@@ -46,9 +47,9 @@ def parse_command(
remote: bool = typer.Option(False, "--remote", help="Use mineru.net official remote parse service"),
remote_url: str | None = typer.Option(None, "--remote-url", help="Use a custom remote parse service URL"),
api_key: str | None = typer.Option(None, "--api-key", help="API key for remote parse service"),
- language: str = typer.Option("ch", "--language", help="Hybrid low OCR language hint; accepted by other efforts for compatibility"),
+ language: str = typer.Option("ch", "--language", help="Hybrid medium OCR language hint; accepted by other efforts for compatibility"),
ocr_mode: str = typer.Option("auto", "--ocr-mode", help="OCR mode: auto, txt, ocr"),
- effort: str = typer.Option("medium", "--effort", help="Hybrid effort: low, medium, high"),
+ effort: str = typer.Option(DEFAULT_HYBRID_EFFORT, "--effort", help=HYBRID_EFFORT_HELP),
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"),
@@ -84,9 +85,9 @@ def api_server_command(
concurrency: int = typer.Option(1, "--concurrency", help="Maximum concurrent parse jobs"),
url_timeout: int = typer.Option(60, "--url-timeout", help="Timeout for URL source downloads"),
max_wait: int = typer.Option(600, "--max-wait", help="Maximum seconds for wait parameter"),
- language: str = typer.Option("ch", "--language", help="Hybrid low OCR language hint; accepted by other efforts for compatibility"),
+ language: str = typer.Option("ch", "--language", help="Hybrid medium OCR language hint; accepted by other efforts for compatibility"),
ocr_mode: str = typer.Option("auto", "--ocr-mode", help="OCR mode: auto, txt, ocr"),
- effort: str = typer.Option("medium", "--effort", help="Hybrid effort: low, medium, high"),
+ effort: str = typer.Option(DEFAULT_HYBRID_EFFORT, "--effort", help=HYBRID_EFFORT_HELP),
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/__init__.py b/mineru/parser/__init__.py
index 79fb6932..8909fd5e 100644
--- a/mineru/parser/__init__.py
+++ b/mineru/parser/__init__.py
@@ -10,7 +10,7 @@ from .html import HtmlParser
from .office import DocxParser, PptxParser, XlsxParser
from .pdf import PdfFlashParser, PdfHybridParser, PdfPipelineParser, PdfVlmParser
from .tier import PARSER_BACKENDS, backend_for_tier, resolve_tier_and_backend
-from ..utils.backend_options import resolve_backend_and_effort
+from ..utils.backend_options import DEFAULT_HYBRID_EFFORT, LOCAL_HYBRID_EFFORT, resolve_backend_and_effort
__all__ = [
"backend_for_tier",
@@ -54,7 +54,7 @@ def _build_parser(
backend: str | None = None,
language: str = "ch",
ocr_mode: str = "auto",
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
disable_table: bool = False,
disable_formula: bool = False,
disable_image_analysis: bool = False,
@@ -70,7 +70,7 @@ def _build_parser(
resolved_tier, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)
resolved_backend, resolved_effort = resolve_backend_and_effort(backend or resolved_backend, effort)
if resolved_tier == "standard":
- resolved_effort = "low"
+ resolved_effort = LOCAL_HYBRID_EFFORT
resolved_ocr_mode = method or ocr_mode
resolved_language = lang or language
resolved_table_enable = (not disable_table) if table_enable is None else table_enable
@@ -114,7 +114,7 @@ def parse(
backend: str | None = None,
language: str = "ch",
ocr_mode: str = "auto",
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
disable_table: bool = False,
disable_formula: bool = False,
disable_image_analysis: bool = False,
@@ -153,7 +153,7 @@ async def parse_async(
backend: str | None = None,
language: str = "ch",
ocr_mode: str = "auto",
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
disable_table: bool = False,
disable_formula: bool = False,
disable_image_analysis: bool = False,
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index a591c260..7905cfd4 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -38,7 +38,13 @@ from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from ..types import Tier
-from ..utils.backend_options import HYBRID_EFFORT_HELP, resolve_backend_and_effort
+from ..utils.backend_options import (
+ DEFAULT_HYBRID_EFFORT,
+ HYBRID_EFFORT_CHOICES,
+ HYBRID_EFFORT_HELP,
+ LOCAL_HYBRID_EFFORT,
+ resolve_backend_and_effort,
+)
from ..utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
from ..version import __version__
from . import parse_async
@@ -1258,7 +1264,7 @@ async def _run_job(
table_enable: bool,
formula_enable: bool,
image_analysis: bool,
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
url_timeout: int = 60,
) -> None:
rec.status = "running"
@@ -1991,8 +1997,8 @@ def _model_ids_and_tiers_for_server_tier(tier: Tier) -> tuple[list[str], list[di
return ["Hybrid-Low", "MinerU-HTML"], [
{
"id": "standard",
- "description": "Hybrid low parsing with local lightweight models.",
- "current_model": "hybrid-low",
+ "description": "Hybrid medium parsing with local lightweight models.",
+ "current_model": "hybrid-medium",
},
]
@@ -2015,7 +2021,7 @@ def create_app(
api_key: str | None = None,
language: str = "ch",
ocr_mode: str = "auto",
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
table_enable: bool = True,
formula_enable: bool = True,
image_analysis: bool = True,
@@ -2027,7 +2033,7 @@ def create_app(
upload_dir:
Directory for uploaded files and parse artifacts.
tier:
- Server parsing tier. ``"standard"`` selects Hybrid low;
+ Server parsing tier. ``"standard"`` selects Hybrid medium;
``"pro"`` selects the default Hybrid backend. If ``backend`` is also provided,
both values must be compatible.
backend:
@@ -2042,12 +2048,12 @@ def create_app(
Optional API key. When set, clients must pass ``Authorization: Bearer <key>``
to access list endpoints and advanced output formats.
language:
- Hybrid low OCR language hint; accepted by other efforts for compatibility.
+ Hybrid medium OCR language hint; accepted by other efforts for compatibility.
ocr_mode:
PDF OCR/text extraction mode for Hybrid backends.
effort:
- Hybrid backend effort level. Low uses local Hybrid processing. Medium is
- faster. High is more accurate and may take longer.
+ Hybrid backend effort level. Medium uses local Hybrid processing. High and
+ extra_high use progressively stronger VLM-assisted parsing.
table_enable:
Whether table recognition is enabled.
formula_enable:
@@ -2060,8 +2066,8 @@ def create_app(
tier, backend = _resolve_server_tier_and_backend(tier=tier, backend=backend)
backend, effort = resolve_backend_and_effort(raw_backend or backend, effort)
if tier == "standard":
- effort = "low"
- dependency_tier = "standard" if backend.startswith("hybrid-") and effort == "low" else tier
+ effort = LOCAL_HYBRID_EFFORT
+ dependency_tier = "standard" if backend.startswith("hybrid-") and effort == LOCAL_HYBRID_EFFORT 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_"))
@@ -2168,7 +2174,7 @@ def create_app(
help=(
"Advanced parser backend "
f"({', '.join(_API_SERVER_BACKENDS)}). "
- "Defaults from --tier: standard -> hybrid-engine --effort low, pro -> hybrid-engine."
+ f"Defaults from --tier: standard -> hybrid-engine --effort {LOCAL_HYBRID_EFFORT}, pro -> hybrid-engine."
),
)
@click.option(
@@ -2200,7 +2206,7 @@ def create_app(
default="ch",
type=str,
metavar="[" + "|".join(_API_SERVER_LANGUAGES) + "]",
- help="Hybrid low OCR language hint; accepted by other efforts for compatibility.",
+ help="Hybrid medium OCR language hint; accepted by other efforts for compatibility.",
)
@click.option(
"--ocr-mode",
@@ -2210,8 +2216,9 @@ def create_app(
)
@click.option(
"--effort",
- default="medium",
- type=click.Choice(("low", "medium", "high")),
+ default=DEFAULT_HYBRID_EFFORT,
+ type=str,
+ metavar="[" + "|".join(HYBRID_EFFORT_CHOICES) + "]",
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 eb5f57a1..7cabde20 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -10,7 +10,14 @@ from typing import Any
from ..errors import InvalidRequestError
from ..types import PageInfo
-from ..utils.backend_options import CANONICAL_HYBRID_ENGINE, resolve_backend_and_effort, validate_effort
+from ..utils.backend_options import (
+ CANONICAL_HYBRID_ENGINE,
+ DEFAULT_HYBRID_EFFORT,
+ LOCAL_HYBRID_EFFORT,
+ MAX_HYBRID_EFFORT,
+ resolve_backend_and_effort,
+ validate_effort,
+)
from ..utils.image_payload import ImagePayloadCache
from .base import DocumentParser, ParseResult
@@ -47,7 +54,7 @@ class PdfBaseParser(DocumentParser):
backend: str = "hybrid-engine",
method: str = "auto",
lang: str = "ch",
- effort: str = "medium",
+ effort: str = DEFAULT_HYBRID_EFFORT,
formula_enable: bool = True,
table_enable: bool = True,
image_analysis: bool = True,
@@ -247,7 +254,11 @@ class PdfHybridParser(PdfBaseParser):
) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
- backend = self.backend if self.effort == "low" else _resolve_hybrid_backend(self.backend, is_async=False)
+ backend = (
+ self.backend
+ if self.effort == LOCAL_HYBRID_EFFORT
+ 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()
@@ -275,7 +286,9 @@ class PdfHybridParser(PdfBaseParser):
) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import aio_doc_analyze as hybrid_aio_doc_analyze
- backend = self.backend if self.effort == "low" else _resolve_hybrid_backend(self.backend, is_async=True)
+ backend = (
+ self.backend if self.effort == LOCAL_HYBRID_EFFORT 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()
@@ -297,23 +310,23 @@ class PdfHybridParser(PdfBaseParser):
class PdfPipelineParser(PdfHybridParser):
- """保留旧 SDK 类名,内部统一委托 Hybrid low 解析。"""
+ """保留旧 SDK 类名,内部统一委托 Hybrid medium 解析。"""
def __init__(self, **kwargs: Any) -> None:
- """将旧 PdfPipelineParser 构造参数归一到 Hybrid low,避免继续加载旧 backend。"""
+ """将旧 PdfPipelineParser 构造参数归一到 Hybrid medium,避免继续加载旧 backend。"""
kwargs.pop("backend", None)
kwargs.pop("effort", None)
- super().__init__(backend=CANONICAL_HYBRID_ENGINE, effort="low", **kwargs)
+ super().__init__(backend=CANONICAL_HYBRID_ENGINE, effort=LOCAL_HYBRID_EFFORT, **kwargs)
class PdfVlmParser(PdfHybridParser):
- """保留旧 SDK 类名,内部统一委托 Hybrid high 解析。"""
+ """保留旧 SDK 类名,内部统一委托 Hybrid extra_high 解析。"""
def __init__(self, **kwargs: Any) -> None:
- """将旧 PdfVlmParser 构造参数归一到 Hybrid high,避免继续暴露独立 VLM backend。"""
+ """将旧 PdfVlmParser 构造参数归一到 Hybrid extra_high,避免继续暴露独立 VLM backend。"""
backend = kwargs.pop("backend", "vlm-engine")
kwargs.pop("effort", None)
- resolved_backend, resolved_effort = resolve_backend_and_effort(backend, "high")
+ resolved_backend, resolved_effort = resolve_backend_and_effort(backend, MAX_HYBRID_EFFORT)
super().__init__(backend=resolved_backend, effort=resolved_effort, **kwargs)
diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.js
index 9fb8e523..4a9d2205 100644
--- a/mineru/resources/gradio_app.js
+++ b/mineru/resources/gradio_app.js
@@ -131,8 +131,8 @@
const effort = getEffortValue();
const showClientOptions = backend.endsWith("http-client");
const showImageAnalysis = backend.startsWith("vlm")
- || (backend.startsWith("hybrid") && effort === "high");
- const showOcrLanguage = backend.startsWith("hybrid") && effort === "low";
+ || (backend.startsWith("hybrid") && effort === "extra_high");
+ const showOcrLanguage = backend.startsWith("hybrid") && effort === "medium";
const hideForceOcr = !backend.startsWith("hybrid");
const hideHybridEffort = !backend.startsWith("hybrid");
diff --git a/mineru/utils/backend_options.py b/mineru/utils/backend_options.py
index e73ae164..25cb9abf 100644
--- a/mineru/utils/backend_options.py
+++ b/mineru/utils/backend_options.py
@@ -4,11 +4,14 @@ from __future__ import annotations
from typing import Final
CANONICAL_HYBRID_ENGINE: Final = "hybrid-engine"
+LOCAL_HYBRID_EFFORT: Final = "medium"
+LAYOUT_HYBRID_EFFORT: Final = "high"
+MAX_HYBRID_EFFORT: Final = "extra_high"
DEFAULT_BACKEND: Final = CANONICAL_HYBRID_ENGINE
-DEFAULT_HYBRID_EFFORT: Final = "medium"
+DEFAULT_HYBRID_EFFORT: Final = LAYOUT_HYBRID_EFFORT
DEFAULT_EFFORT: Final = DEFAULT_HYBRID_EFFORT
HYBRID_EFFORT_HELP: Final = (
- "Higher effort improves parsing quality but may be slower; lower effort is faster but may reduce quality."
+ "Higher effort improves parsing quality but may be slower; medium is the fastest local Hybrid mode."
)
LOCAL_BACKEND_CHOICES: Final[tuple[str, ...]] = (
@@ -18,7 +21,11 @@ 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, ...]] = ("low", "medium", "high")
+HYBRID_EFFORT_CHOICES: Final[tuple[str, ...]] = (
+ LOCAL_HYBRID_EFFORT,
+ LAYOUT_HYBRID_EFFORT,
+ MAX_HYBRID_EFFORT,
+)
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)}
@@ -64,22 +71,22 @@ def normalize_public_backend(backend: str | None) -> str:
def validate_effort(effort: str | None) -> str:
- """校验 Hybrid effort 级别,入口层统一使用 medium 作为默认值。"""
+ """校验 Hybrid effort 级别,只允许 medium/high/extra_high 三档。"""
normalized = (effort or DEFAULT_EFFORT).strip().lower()
- if normalized in SUPPORTED_EFFORTS:
+ if normalized in HYBRID_EFFORT_CHOICES:
return normalized
- raise ValueError(f"Unsupported effort '{effort}'. Supported efforts: {', '.join(SUPPORTED_EFFORTS)}")
+ raise ValueError(f"Unsupported effort '{effort}'. Supported efforts: {', '.join(HYBRID_EFFORT_CHOICES)}")
def resolve_backend_and_effort(backend: str | None, effort: str | None = None) -> tuple[str, str]:
- """同时解析 backend 与 effort,旧 pipeline/VLM backend 分别统一转为 Hybrid low/high。"""
+ """同时解析 backend 与 effort,旧 pipeline/VLM backend 分别统一转为 Hybrid medium/extra_high。"""
raw_backend = (backend or "").strip()
resolved_backend = normalize_backend(raw_backend)
resolved_effort = validate_effort(effort)
if raw_backend in LEGACY_PIPELINE_BACKEND_ALIASES:
- resolved_effort = "low"
+ resolved_effort = LOCAL_HYBRID_EFFORT
elif raw_backend in LEGACY_VLM_BACKEND_ALIASES:
- resolved_effort = "high"
+ resolved_effort = MAX_HYBRID_EFFORT
return resolved_backend, resolved_effort
diff --git a/mineru/utils/ocr_language.py b/mineru/utils/ocr_language.py
index 6232b341..866fe1da 100644
--- a/mineru/utils/ocr_language.py
+++ b/mineru/utils/ocr_language.py
@@ -107,7 +107,7 @@ def format_public_ocr_lang_description() -> str:
for lang in PUBLIC_OCR_LANGUAGES
]
return (
- "(Mainly for Hybrid low local OCR and table OCR; accepted by other "
+ "(Mainly for Hybrid medium local OCR and table OCR; accepted by other "
"Hybrid efforts for compatibility.) Input the languages in the pdf "
"to improve OCR accuracy when language-aware OCR is used. Options:\n"
+ "\n".join(option_lines)
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index b715ea22..f372c0e9 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -525,21 +525,23 @@ def test_parse_rejects_removed_ch_lite_language(tmp_path: Path) -> None:
assert "Language ch_lite not supported" in result.output
-def test_gradio_language_option_only_visible_for_hybrid_low() -> None:
+def test_gradio_language_option_only_visible_for_hybrid_medium() -> None:
from mineru.cli_old import gradio_app
- assert gradio_app.is_ocr_language_option_visible("hybrid-engine", "low") is True
- assert gradio_app.is_ocr_language_option_visible("hybrid-engine", "medium") is False
+ assert gradio_app.is_ocr_language_option_visible("hybrid-engine", "medium") is True
assert gradio_app.is_ocr_language_option_visible("hybrid-engine", "high") is False
- assert gradio_app.is_ocr_language_option_visible("flash", "low") is False
+ assert gradio_app.is_ocr_language_option_visible("hybrid-engine", "extra_high") is False
+ assert gradio_app.is_ocr_language_option_visible("flash", "medium") is False
-def test_gradio_frontend_shows_ocr_language_for_hybrid_low() -> None:
+def test_gradio_frontend_shows_ocr_language_for_hybrid_medium() -> None:
js_text = Path("mineru/resources/gradio_app.js").read_text(encoding="utf-8")
assert 'const effortControl = effortRoot?.querySelector(\'[role="listbox"]\');' in js_text
assert 'input[type="radio"]' not in js_text
- assert 'const showOcrLanguage = backend.startsWith("hybrid") && effort === "low";' in js_text
+ assert 'const showImageAnalysis = backend.startsWith("vlm")' in js_text
+ assert '|| (backend.startsWith("hybrid") && effort === "extra_high");' in js_text
+ assert 'const showOcrLanguage = backend.startsWith("hybrid") && effort === "medium";' in js_text
def test_gradio_effort_option_is_below_backend_selector() -> None:
@@ -554,7 +556,7 @@ def test_gradio_effort_option_is_below_backend_selector() -> None:
advanced_popover_idx = gradio_text.index('elem_classes=["mineru-advanced-popover"]')
assert "effort = gr.Radio(" not in gradio_text
- assert "解析强度越高,解析质量越好但速度越慢;解析强度越低,速度更快但质量可能下降。" in gradio_text
+ assert "解析强度越高,解析质量越好但速度越慢;medium 为最快的本地 Hybrid 模式。" in gradio_text
assert "Low 使用本地 Hybrid 处理;Medium 速度更快;High 精度更高,耗时可能更长。" not in gradio_text
assert backend_block_idx < backend_idx < client_options_idx < effort_idx < max_pages_idx < advanced_popover_idx
@@ -598,7 +600,7 @@ def test_parse_forwards_flash_backend(monkeypatch: Any, tmp_path: Path) -> None:
assert output.read_text(encoding="utf-8") == "# demo\n"
-def test_cli_old_legacy_vlm_branch_maps_to_hybrid_high(monkeypatch: Any, tmp_path: Path) -> None:
+def test_cli_old_legacy_vlm_branch_maps_to_hybrid_extra_high(monkeypatch: Any, tmp_path: Path) -> None:
from mineru.cli_old import common
seen: dict[str, Any] = {}
@@ -615,7 +617,7 @@ def test_cli_old_legacy_vlm_branch_maps_to_hybrid_high(monkeypatch: Any, tmp_pat
monkeypatch.setattr(common, "get_vlm_engine", lambda inference_engine="auto", is_async=False: "vllm-engine")
def _fake_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录 legacy VLM 输入最终进入 Hybrid high 分支。"""
+ """记录 legacy VLM 输入最终进入 Hybrid extra_high 分支。"""
seen["backend"] = args[3]
seen["hybrid_backend"] = args[6]
seen["kwargs"] = kwargs
@@ -632,7 +634,7 @@ def test_cli_old_legacy_vlm_branch_maps_to_hybrid_high(monkeypatch: Any, tmp_pat
)
assert seen["hybrid_backend"] == "vllm-engine"
- assert seen["kwargs"]["effort"] == "high"
+ assert seen["kwargs"]["effort"] == "extra_high"
assert seen["kwargs"]["image_analysis"] is True
assert not hasattr(common, "_process_vlm")
@@ -673,7 +675,7 @@ 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:
+def test_cli_old_hybrid_medium_skips_vlm_engine_resolution(monkeypatch: Any, tmp_path: Path) -> None:
from mineru.cli_old import common
seen: dict[str, Any] = {}
@@ -689,11 +691,11 @@ def test_cli_old_hybrid_low_skips_vlm_engine_resolution(monkeypatch: Any, tmp_pa
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")
+ """Hybrid medium 不应触发 VLM engine 解析。"""
+ raise AssertionError("medium effort should not resolve VLM engine")
def _fake_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录 Hybrid low 仍进入 Hybrid 处理分支。"""
+ """记录 Hybrid medium 仍进入 Hybrid 处理分支。"""
seen["backend"] = args[6]
seen["langs"] = list(args[3])
seen["pdf_count"] = len(args[2])
@@ -708,16 +710,16 @@ def test_cli_old_hybrid_low_skips_vlm_engine_resolution(monkeypatch: Any, tmp_pa
pdf_bytes_list=[b"%PDF-1.7\n", b"%PDF-1.7\n"],
p_lang_list=["en", "en"],
backend="hybrid-engine",
- effort="low",
+ effort="medium",
)
assert seen["backend"] == "engine"
assert seen["langs"] == ["en", "en"]
assert seen["pdf_count"] == 2
- assert seen["kwargs"]["effort"] == "low"
+ assert seen["kwargs"]["effort"] == "medium"
-def test_process_hybrid_low_calls_analyzer_per_file(monkeypatch: Any, tmp_path: Path) -> None:
+def test_process_hybrid_medium_calls_analyzer_per_file(monkeypatch: Any, tmp_path: Path) -> None:
from mineru.cli_old import common
calls: list[bytes] = []
@@ -725,7 +727,7 @@ def test_process_hybrid_low_calls_analyzer_per_file(monkeypatch: Any, tmp_path:
outputs: list[tuple[str, str, str]] = []
def fake_doc_analyze(pdf_bytes: bytes, **kwargs: Any) -> tuple[list[PageInfo], list[object], bool]:
- """记录每个文件独立进入 Hybrid low analyzer。"""
+ """记录每个文件独立进入 Hybrid medium analyzer。"""
calls.append(pdf_bytes)
languages.append(kwargs["language"])
return [PageInfo(page_idx=0, _backend="hybrid")], [], False
@@ -761,7 +763,7 @@ def test_process_hybrid_low_calls_analyzer_per_file(monkeypatch: Any, tmp_path:
f_dump_orig_pdf=True,
f_dump_content_list=True,
f_make_md_mode="mm_markdown",
- effort="low",
+ effort="medium",
)
assert calls == [b"a", b"b"]
@@ -769,7 +771,7 @@ def test_process_hybrid_low_calls_analyzer_per_file(monkeypatch: Any, tmp_path:
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:
+def test_cli_old_async_legacy_vlm_branch_maps_to_hybrid_extra_high(monkeypatch: Any, tmp_path: Path) -> None:
from mineru.cli_old import common
seen: dict[str, Any] = {}
@@ -786,7 +788,7 @@ def test_cli_old_async_legacy_vlm_branch_maps_to_hybrid_high(monkeypatch: Any, t
monkeypatch.setattr(common, "get_vlm_engine", lambda inference_engine="auto", is_async=True: "vllm-async-engine")
async def _fake_async_process_hybrid(*args: Any, **kwargs: Any) -> None:
- """记录异步 legacy VLM 输入最终进入 Hybrid high 分支。"""
+ """记录异步 legacy VLM 输入最终进入 Hybrid extra_high 分支。"""
seen["backend"] = args[3]
seen["hybrid_backend"] = args[6]
seen["kwargs"] = kwargs
@@ -805,7 +807,7 @@ def test_cli_old_async_legacy_vlm_branch_maps_to_hybrid_high(monkeypatch: Any, t
)
assert seen["hybrid_backend"] == "vllm-async-engine"
- assert seen["kwargs"]["effort"] == "high"
+ assert seen["kwargs"]["effort"] == "extra_high"
assert seen["kwargs"]["image_analysis"] is True
assert not hasattr(common, "_async_process_vlm")
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 6082752d..42d8be6e 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -47,7 +47,7 @@ def _stub_api_server_dependency_preflight(monkeypatch: pytest.MonkeyPatch) -> No
def test_hybrid_analyze_import_does_not_require_vlm_utils() -> None:
- """校验 Hybrid low 所需模块导入阶段不再强依赖 VLM 工具包。"""
+ """校验 Hybrid medium 所需模块导入阶段不再强依赖 VLM 工具包。"""
repo_root = Path(__file__).resolve().parents[2]
code = """
import importlib.abc
@@ -56,7 +56,7 @@ import sys
class BlockVlmUtilsFinder(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path=None, target=None):
- # 阻断 mineru_vl_utils 导入,用来验证 Hybrid low 的 lazy import 边界。
+ # 阻断 mineru_vl_utils 导入,用来验证 Hybrid medium 的 lazy import 边界。
if fullname == "mineru_vl_utils" or fullname.startswith("mineru_vl_utils."):
raise ModuleNotFoundError(f"blocked VLM utility import: {fullname}")
return None
@@ -79,14 +79,15 @@ print("ok")
assert result.stdout.strip() == "ok"
-def test_validate_effort_accepts_low_and_maps_legacy_backends() -> None:
- """校验 legacy backend 输入统一映射到当前 Hybrid effort 合约。"""
+def test_validate_effort_rejects_low_and_maps_legacy_backends() -> None:
+ """校验 Hybrid effort 只接受 medium/high/extra_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")
- assert resolve_backend_and_effort("pipeline", "high") == ("hybrid-engine", "low")
+ assert HYBRID_EFFORT_CHOICES == ("medium", "high", "extra_high")
+ with pytest.raises(ValueError, match="Unsupported effort 'low'"):
+ validate_effort("low")
+ assert resolve_backend_and_effort("vlm-engine", "medium") == ("hybrid-engine", "extra_high")
+ assert resolve_backend_and_effort("pipeline", "extra_high") == ("hybrid-engine", "medium")
def test_api_client_builds_file_page_range_without_options(tmp_path: Path) -> None:
@@ -498,7 +499,7 @@ def test_create_app_does_not_read_runtime_settings_from_env(tmp_path: Path, monk
assert app.state.max_wait == 600
assert app.state.language == "ch"
assert app.state.ocr_mode == "auto"
- assert app.state.effort == "low"
+ assert app.state.effort == "medium"
assert app.state.table_enable is True
assert app.state.formula_enable is True
assert app.state.image_analysis is True
@@ -617,7 +618,7 @@ def test_api_server_rendered_outputs_store_image_sidecars(
table_enable=True,
formula_enable=True,
image_analysis=True,
- effort="low",
+ effort="medium",
)
)
@@ -682,7 +683,7 @@ def test_api_server_middle_json_preserves_backend_for_client_rendering(
table_enable=True,
formula_enable=True,
image_analysis=True,
- effort="low",
+ effort="medium",
)
)
@@ -749,7 +750,7 @@ def test_api_server_sanitizes_surrogates_in_text_outputs(
table_enable=True,
formula_enable=True,
image_analysis=True,
- effort="low",
+ effort="medium",
)
)
@@ -804,7 +805,7 @@ def test_api_server_logs_traceback_when_job_file_fails(
table_enable=True,
formula_enable=True,
image_analysis=True,
- effort="low",
+ effort="medium",
)
)
@@ -860,7 +861,7 @@ def test_api_server_tier_selects_compatible_backend(tmp_path: Path, monkeypatch:
assert [tier["id"] for tier in pro_app.state.tiers] == ["pro"]
assert standard_app.state.tier == "standard"
assert standard_app.state.backend == "hybrid-engine"
- assert standard_app.state.effort == "low"
+ assert standard_app.state.effort == "medium"
assert [tier["id"] for tier in standard_app.state.tiers] == ["standard"]
@@ -870,7 +871,7 @@ def test_api_server_defaults_to_standard_tier(tmp_path: Path, monkeypatch: pytes
assert app.state.tier == "standard"
assert app.state.backend == "hybrid-engine"
- assert app.state.effort == "low"
+ assert app.state.effort == "medium"
assert [tier["id"] for tier in app.state.tiers] == ["standard"]
@@ -954,7 +955,7 @@ def test_api_server_cli_reports_dependency_preflight_without_traceback(monkeypat
assert "Traceback" not in result.output
-def test_api_server_maps_legacy_pipeline_backend_to_standard_hybrid_low(
+def test_api_server_maps_legacy_pipeline_backend_to_standard_hybrid_medium(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_stub_api_server_dependency_preflight(monkeypatch)
@@ -962,7 +963,7 @@ def test_api_server_maps_legacy_pipeline_backend_to_standard_hybrid_low(
assert app.state.tier == "standard"
assert app.state.backend == "hybrid-engine"
- assert app.state.effort == "low"
+ assert app.state.effort == "medium"
def test_api_server_allows_compatible_tier_and_explicit_backend(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -971,7 +972,7 @@ def test_api_server_allows_compatible_tier_and_explicit_backend(tmp_path: Path,
assert app.state.tier == "pro"
assert app.state.backend == "hybrid-engine"
- assert app.state.effort == "high"
+ assert app.state.effort == "extra_high"
assert [tier["id"] for tier in app.state.tiers] == ["pro"]
@@ -999,7 +1000,7 @@ def test_build_parser_forwards_effort_to_hybrid_parser(tmp_path: Path) -> None:
assert parser.effort == "high"
-def test_build_parser_maps_legacy_vlm_backend_to_hybrid_high(tmp_path: Path) -> None:
+def test_build_parser_maps_legacy_vlm_backend_to_hybrid_extra_high(tmp_path: Path) -> None:
pdf = tmp_path / "demo.pdf"
pdf.write_bytes(b"%PDF-1.7\n")
@@ -1007,10 +1008,10 @@ def test_build_parser_maps_legacy_vlm_backend_to_hybrid_high(tmp_path: Path) ->
assert parser.__class__.__name__ == "PdfHybridParser"
assert parser.backend == "hybrid-engine"
- assert parser.effort == "high"
+ assert parser.effort == "extra_high"
-def test_build_parser_maps_legacy_pipeline_backend_to_hybrid_low(tmp_path: Path) -> None:
+def test_build_parser_maps_legacy_pipeline_backend_to_hybrid_medium(tmp_path: Path) -> None:
pdf = tmp_path / "demo.pdf"
pdf.write_bytes(b"%PDF-1.7\n")
@@ -1018,26 +1019,26 @@ def test_build_parser_maps_legacy_pipeline_backend_to_hybrid_low(tmp_path: Path)
assert parser.__class__.__name__ == "PdfHybridParser"
assert parser.backend == "hybrid-engine"
- assert parser.effort == "low"
+ assert parser.effort == "medium"
-def test_pdf_pipeline_parser_compat_delegates_to_hybrid_low() -> None:
+def test_pdf_pipeline_parser_compat_delegates_to_hybrid_medium() -> None:
parser = parser_pdf.PdfPipelineParser(method="ocr", lang="en", effort="high")
assert isinstance(parser, parser_pdf.PdfHybridParser)
assert parser.backend == "hybrid-engine"
assert parser.method == "ocr"
assert parser.lang == "en"
- assert parser.effort == "low"
+ assert parser.effort == "medium"
-def test_pdf_hybrid_low_parser_skips_vlm_backend_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
- """校验 Hybrid low 直接进入本地分支,不解析 VLM engine。"""
+def test_pdf_hybrid_medium_parser_skips_vlm_backend_resolution(monkeypatch: pytest.MonkeyPatch) -> None:
+ """校验 Hybrid medium 直接进入本地分支,不解析 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 形态。"""
+ """记录 medium 分支收到的参数,并返回 Hybrid middle-json 形态。"""
seen.update(kwargs)
return [PageInfo(page_idx=0, _backend="hybrid")], [], False
@@ -1045,17 +1046,17 @@ def test_pdf_hybrid_low_parser_skips_vlm_backend_resolution(monkeypatch: pytest.
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")
+ """medium 不应触发 VLM backend resolver。"""
+ raise AssertionError("medium 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", lang="en")
+ parser = parser_pdf.PdfHybridParser(backend="hybrid-engine", effort="medium", lang="en")
pages = parser._run_analysis(b"%PDF-1.7\n")
assert pages[0]._backend == "hybrid"
assert seen["backend"] == "hybrid-engine"
- assert seen["effort"] == "low"
+ assert seen["effort"] == "medium"
assert seen["language"] == "en"
@@ -1089,7 +1090,7 @@ def test_pdf_engine_resolvers_keep_http_client_backend() -> None:
assert parser_pdf._resolve_hybrid_backend("hybrid-http-client", is_async=True) == "http-client"
-def test_pdf_vlm_parser_compat_delegates_to_hybrid_high(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_pdf_vlm_parser_compat_delegates_to_hybrid_extra_high(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[tuple[str, bool]] = []
backends: list[str] = []
efforts: list[str] = []
@@ -1123,7 +1124,7 @@ def test_pdf_vlm_parser_compat_delegates_to_hybrid_high(monkeypatch: pytest.Monk
assert asyncio.run(parser._arun_analysis(b"%PDF")) == []
assert calls == [("hybrid-engine", False), ("hybrid-engine", True)]
assert backends == ["sync-backend", "async-backend"]
- assert efforts == ["high", "high"]
+ assert efforts == ["extra_high", "extra_high"]
def test_pdf_hybrid_parser_passes_call_mode_to_backend_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1193,7 +1194,7 @@ def test_api_server_stores_parser_runtime_options(tmp_path: Path, monkeypatch: p
assert app.state.language == "ch"
assert app.state.ocr_mode == "ocr"
- assert app.state.effort == "low"
+ assert app.state.effort == "medium"
assert app.state.table_enable is False
assert app.state.formula_enable is False
assert app.state.image_analysis is False
@@ -1246,7 +1247,7 @@ def test_api_server_cli_accepts_backend_alias(monkeypatch: pytest.MonkeyPatch) -
assert seen == {"backend": "hybrid-engine", "host": "0.0.0.0", "port": "15981"}
-def test_api_server_cli_maps_legacy_vlm_backend_to_hybrid_high(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_api_server_cli_maps_legacy_vlm_backend_to_hybrid_extra_high(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, str] = {}
def _fake_run(server) -> None:
@@ -1259,7 +1260,7 @@ def test_api_server_cli_maps_legacy_vlm_backend_to_hybrid_high(monkeypatch: pyte
result = runner.invoke(main, ["--backend", "vlm-http-client", "--host", "0.0.0.0", "--port", "15983"])
assert result.exit_code == 0
- assert seen == {"backend": "hybrid-http-client", "effort": "high"}
+ assert seen == {"backend": "hybrid-http-client", "effort": "extra_high"}
def test_api_server_cli_normalizes_hidden_language_alias(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1309,7 +1310,7 @@ def test_api_server_cli_effort_help_matches_gradio_copy() -> None:
effort_option = next(param for param in main.params if "--effort" in param.opts)
assert effort_option.help == (
- "Higher effort improves parsing quality but may be slower; lower effort is faster but may reduce quality."
+ "Higher effort improves parsing quality but may be slower; medium is the fastest local Hybrid mode."
)
diff --git a/tests/unittest/test_title_level_postprocess.py b/tests/unittest/test_title_level_postprocess.py
index a85d58b3..e4354c9b 100644
--- a/tests/unittest/test_title_level_postprocess.py
+++ b/tests/unittest/test_title_level_postprocess.py
@@ -21,8 +21,8 @@ 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 分支。"""
+def test_finalize_client_side_pages_rejects_low_effort(monkeypatch) -> None:
+ """校验客户端 Hybrid finalize 不再接受 low effort。"""
calls: list[str] = []
pages = [PageInfo(page_idx=0, _backend="hybrid")]
monkeypatch.setattr(
@@ -30,9 +30,10 @@ def test_finalize_client_side_pages_accepts_hybrid_low(monkeypatch) -> None:
lambda parsed_pages, effort="medium": calls.append(effort),
)
- title_level_postprocess.finalize_client_side_pages(pages, "hybrid", effort="low")
+ with pytest.raises(ValueError, match="Unsupported effort 'low'"):
+ title_level_postprocess.finalize_client_side_pages(pages, "hybrid", effort="low")
- assert calls == ["low"]
+ assert calls == []
def test_regenerate_client_side_outputs_forwards_hybrid_effort(monkeypatch, tmp_path) -> None: