Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
refactor: more dot-access replacements in para_split, model_output, magic_model
jinzhenj2a35d1563da3
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex 8d236144..417abe6e 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -372,8 +372,8 @@ def _has_doc_title_overlap(title_bbox: list[float], doc_title_bboxes: list[list[def _apply_layout_title_split(- model_list: list[list[dict[str, object]]],- images_layout_res: list[list[dict[str, object]]],+ model_list: list[list[dict[str, Any]]],+ images_layout_res: list[list[dict[str, Any]]],page_sizes: list[list[int]],overlap_threshold: float = LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,) -> None:@@ -396,7 +396,7 @@ def _predict_layout_for_title_split(hybrid_pipeline_model: MineruHybridModel,images: list[Image.Image],batch_ratio: int,-) -> list[dict[str, object]]:+) -> list[dict[str, Any]]:"""执行layout小模型检测,专门为Hybrid标题拆分提供页面layout结果。"""return run_layout_inference(hybrid_pipeline_model.layout_model.batch_predict,@@ -412,7 +412,7 @@ def _process_ocr_and_formulas(inline_formula_enable: bool,_ocr_enable: bool,batch_ratio: int = 1,-) -> tuple[list[list[dict[str, object]]], MineruHybridModel]:+) -> tuple[list[list[dict[str, Any]]], MineruHybridModel]:"""处理OCR和公式识别"""# 遍历model_list,对文本块截图交由OCR识别@@ -573,7 +573,7 @@ def _apply_layout_title_split_for_window(model_list: list[ExtractResult],language: str | None,batch_ratio: int,-) -> None:+) -> MineruHybridModel:"""为VLM-OCR路径补跑layout小模型,先基于VLM原始title做OCR det,再拆分标题。"""hybrid_model_singleton = HybridModelSingleton()hybrid_pipeline_model = hybrid_model_singleton.get_model(@@ -611,8 +611,8 @@ def _apply_layout_title_split_for_window(def _normalize_bbox(- inline_formula_list: list[list[dict[str, object]]],- ocr_res_list: list[list[dict[str, object]]],+ inline_formula_list: list[list[dict[str, Any]]],+ ocr_res_list: list[list[dict[str, Any]]],images_pil_list: list[Image.Image],) -> None:"""归一化坐标并生成最终结果"""@@ -647,11 +647,11 @@ def _build_ocr_text_model_item(ocr_res: dict[str, Any], keep_text: bool = True)def _merge_page_sidecar_items(- model_list: list[list[dict[str, object]]],- inline_formula_list: list[list[dict[str, object]]],- ocr_res_list: list[list[dict[str, object]]],+ model_list: list[list[dict[str, Any]]],+ inline_formula_list: list[list[dict[str, Any]]],+ ocr_res_list: list[list[dict[str, Any]]],keep_ocr_text: bool = True,-) -> list[list[dict[str, object]]]:+) -> list[list[dict[str, Any]]]:merged_model_list = []for page_model_list, page_inline_formula_list, page_ocr_res_list in zip(model_list, inline_formula_list, ocr_res_list):merged_page_model_list = list(page_model_list)@@ -745,7 +745,7 @@ def doc_analyze(server_url: str | None = None,image_analysis: bool = True,**kwargs: object,-) -> tuple[dict[str, object], list[list[dict[str, object]]], bool]:+) -> tuple[dict[str, Any], list[list[dict[str, Any]]], bool]:client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))if predictor is None:predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)@@ -889,7 +889,7 @@ async def aio_doc_analyze(server_url: str | None = None,image_analysis: bool = True,**kwargs: object,-) -> tuple[dict[str, object], list[list[dict[str, object]]], bool]:+) -> tuple[dict[str, Any], list[list[dict[str, Any]]], bool]:client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))if predictor is None:predictor = await _get_model_async(backend, model_path, server_url, **kwargs)diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 3ed4a095..0db22d2b 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport copyimport re+from typing import Anyfrom loguru import loggerfrom PIL import Image@@ -43,7 +44,7 @@ OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {}-def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict[str, object], block: Block) -> None:+def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict[str, Any], block: Block) -> None:if raw_block_type != BlockType.TEXT:returnif "merge_prev" in block_info:@@ -53,7 +54,7 @@ def _copy_raw_text_block_metadata(raw_block_type: str, block_info: dict[str, objclass MagicModel:def __init__(self,- page_model_list: list[dict[str, object]],+ page_model_list: list[dict[str, Any]],page: object,scale: float,page_pil_img: Image.Image,@@ -377,8 +378,8 @@ class MagicModel:@staticmethoddef _split_page_model_list(- page_model_list: list[dict[str, object]],- ) -> tuple[list[dict[str, object]], list[dict[str, object]], list[dict[str, object]]]:+ page_model_list: list[dict[str, Any]],+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:page_blocks = []page_inline_formula = []page_ocr_res = []diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex e8ffb811..cbe97b47 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -132,7 +132,7 @@ def _link_index_entries_by_anchor(middle_json: dict[str, Any]) -> None:text_block["anchor"] = anchor-def result_to_middle_json(model_output_blocks_list: list[list[dict[str, object]]], image_writer: object) -> dict[str, object]:+def result_to_middle_json(model_output_blocks_list: list[list[dict[str, Any]]], image_writer: object) -> dict[str, Any]:middle_json = {"pdf_info": [], "_backend": "office", "_version_name": __version__}for index, page_blocks in enumerate(model_output_blocks_list):page_info = blocks_to_page_info(page_blocks, image_writer, index)diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.pyindex d0c1ad27..51c139dc 100644--- a/mineru/backend/office/office_magic_model.py+++ b/mineru/backend/office/office_magic_model.py@@ -351,7 +351,7 @@ def parse_text_block_spans(content: str) -> list[Span]:return spans-def parse_list_block(list_block: dict[str, object]) -> Block:+def parse_list_block(list_block: dict[str, Any]) -> Block:"""递归解析嵌套列表结构,生成与VLM一致的blocks结构。@@ -393,7 +393,7 @@ def parse_list_block(list_block: dict[str, object]) -> Block:return result-def parse_index_block(index_block: dict[str, object]) -> Block:+def parse_index_block(index_block: dict[str, Any]) -> Block:"""递归解析嵌套索引结构(目录),生成与list一致的blocks结构。@@ -571,11 +571,11 @@ def code_content_clean(content: str) -> str:return ""-def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, object_block_type: str) -> list[dict[str, object]]:+def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, object_block_type: str) -> list[dict[str, Any]]:"""基于index的主客体关联包装函数"""# 定义获取主体和客体对象的函数- def get_subjects() -> list[dict[str, object]]:+ def get_subjects() -> list[dict[str, Any]]:return [{"lines": block.lines, "index": block.index}for block in filter(@@ -584,7 +584,7 @@ def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, obj)]- def get_objects() -> list[dict[str, object]]:+ def get_objects() -> list[dict[str, Any]]:return [{"lines": block.lines, "index": block.index}for block in filter(@@ -601,7 +601,7 @@ def __tie_up_category_by_index(blocks: list[Block], subject_block_type: str, obj)-def get_type_blocks(blocks: list[Block], block_type: Literal["image", "table", "chart"]) -> list[dict[str, object]]:+def get_type_blocks(blocks: list[Block], block_type: Literal["image", "table", "chart"]) -> list[dict[str, Any]]:with_captions = __tie_up_category_by_index(blocks, f"{block_type}_body", f"{block_type}_caption")ret = []for v in with_captions:diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.pyindex 11d8a7c6..4cb87c2d 100644--- a/mineru/backend/pipeline/pipeline_analyze.py+++ b/mineru/backend/pipeline/pipeline_analyze.py@@ -107,7 +107,7 @@ def _format_doc_slices(batch_slices: list[dict[str, int]]) -> str:def _finalize_processing_window_context(- context: dict[str, object],+ context: dict[str, Any],on_doc_ready: Callable[..., object],client_side_output_generation: bool = False,) -> None:@@ -135,7 +135,7 @@ def _finalize_processing_window_context(def _emit_zero_page_contexts(- doc_contexts: list[dict[str, object]],+ doc_contexts: list[dict[str, Any]],on_doc_ready: Callable[..., object],client_side_output_generation: bool = False,) -> None:@@ -324,7 +324,6 @@ def batch_image_analyze(formula_enable: bool = True,table_enable: bool = True,) -> object:-from .batch_analyze import BatchAnalyzemodel_manager = ModelSingleton()diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.pyindex bc4a2afa..f143774b 100644--- a/mineru/backend/vlm/vlm_analyze.py+++ b/mineru/backend/vlm/vlm_analyze.py@@ -434,7 +434,7 @@ def doc_analyze(server_url: str | None = None,image_analysis: bool = True,**kwargs: Any,-) -> tuple[dict[str, object], list[list[dict[str, object]]]]:+) -> tuple[dict[str, Any], list[list[dict[str, Any]]]]:client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))if predictor is None:predictor = ModelSingleton().get_model(backend, model_path, server_url, **kwargs)@@ -528,7 +528,7 @@ async def aio_doc_analyze(server_url: str | None = None,image_analysis: bool = True,**kwargs: Any,-) -> tuple[dict[str, object], list[list[dict[str, object]]]]:+) -> tuple[dict[str, Any], list[list[dict[str, Any]]]]:client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))if predictor is None:predictor = await _get_model_async(backend, model_path, server_url, **kwargs)diff --git a/mineru/cli/api_client.py b/mineru/cli/api_client.pyindex 9beada1f..92d03f8b 100644--- a/mineru/cli/api_client.py+++ b/mineru/cli/api_client.py@@ -27,10 +27,10 @@ from mineru.cli.api_protocol import (API_PROTOCOL_VERSION,DEFAULT_MAX_CONCURRENT_REQUESTS,)+from mineru.utils.check_sys_env import is_linux_environmentfrom mineru.utils.config_reader import (get_max_concurrent_requests as read_max_concurrent_requests,)-from mineru.utils.check_sys_env import is_linux_environmentHEALTH_ENDPOINT = "/health"TASKS_ENDPOINT = "/tasks"@@ -144,7 +144,7 @@ def get_effective_local_api_launch_mode(return default-def build_managed_process_popen_kwargs() -> dict[str, object]:+def build_managed_process_popen_kwargs() -> dict[str, Any]:if os.name == "nt":creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)if creationflags:@@ -373,10 +373,7 @@ def _validate_local_api_launch_mode_cli_args(launch_mode: str,cli_args: Sequence[str],) -> None:- if (- launch_mode == LOCAL_API_LAUNCH_MODE_SPAWN- and _cli_args_include_flag(cli_args, "--reload")- ):+ if launch_mode == LOCAL_API_LAUNCH_MODE_SPAWN and _cli_args_include_flag(cli_args, "--reload"):raise click.ClickException("Local mineru-api spawn launch mode does not support --reload. ""Remove --reload or set MINERU_LOCAL_API_LAUNCH_MODE=subprocess."@@ -390,9 +387,7 @@ def _build_local_api_server_env() -> tuple[dict[str, str], tuple[str, ...]]:env = os.environ.copy()env["MINERU_API_OUTPUT_ROOT"] = str(output_root)- env["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(- read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS)- )+ env["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS))env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"unset_env_names: list[str] = []@@ -488,9 +483,7 @@ class LocalAPIServer:# parsing startup when launched with stdin=PIPE and an EOF-based# shutdown watcher, so we only enable that path on non-Windows# subprocess launches.- self._use_stdin_shutdown_watcher = (- self._launch_mode == LOCAL_API_LAUNCH_MODE_SUBPROCESS and os.name != "nt"- )+ self._use_stdin_shutdown_watcher = self._launch_mode == LOCAL_API_LAUNCH_MODE_SUBPROCESS and os.name != "nt"env, unset_env_names = _build_local_api_server_env(self.output_root,use_stdin_shutdown_watcher=self._use_stdin_shutdown_watcher,@@ -699,9 +692,7 @@ def resolve_effective_max_concurrent_requests(server_max: int,) -> int:if local_max <= 0 or server_max <= 0:- raise ValueError(- "local_max and server_max must both be positive integers"- )+ raise ValueError("local_max and server_max must both be positive integers")return min(local_max, server_max)@@ -728,27 +719,20 @@ def response_detail(response: httpx.Response) -> str:def validate_server_health_payload(payload: dict, base_url: str) -> ServerHealth:status = payload.get("status")if status != "healthy":- raise click.ClickException(- f"MinerU API at {base_url} is not healthy: {json.dumps(payload, ensure_ascii=False)}"- )+ raise click.ClickException(f"MinerU API at {base_url} is not healthy: {json.dumps(payload, ensure_ascii=False)}")protocol_version = payload.get("protocol_version")if protocol_version != API_PROTOCOL_VERSION:raise click.ClickException(- f"MinerU API at {base_url} returned protocol_version={protocol_version}, "- f"expected {API_PROTOCOL_VERSION}"+ f"MinerU API at {base_url} returned protocol_version={protocol_version}, expected {API_PROTOCOL_VERSION}")max_concurrent_requests = payload.get("max_concurrent_requests")processing_window_size = payload.get("processing_window_size")if not isinstance(max_concurrent_requests, int) or max_concurrent_requests <= 0:- raise click.ClickException(- f"MinerU API at {base_url} did not return a valid positive max_concurrent_requests"- )+ raise click.ClickException(f"MinerU API at {base_url} did not return a valid positive max_concurrent_requests")if not isinstance(processing_window_size, int):- raise click.ClickException(- f"MinerU API at {base_url} did not return a valid processing_window_size"- )+ raise click.ClickException(f"MinerU API at {base_url} did not return a valid processing_window_size")return ServerHealth(base_url=base_url,@@ -764,8 +748,7 @@ async def fetch_server_health(response = await client.get(f"{base_url}{HEALTH_ENDPOINT}")if response.status_code != 200:raise click.ClickException(- f"Failed to query MinerU API health from {base_url}: "- f"{response.status_code} {response_detail(response)}"+ f"Failed to query MinerU API health from {base_url}: {response.status_code} {response_detail(response)}")return validate_server_health_payload(response.json(), base_url)@@ -784,9 +767,7 @@ async def wait_for_local_api_ready(if process is not None and _managed_process_exit_code(process) is not None:if local_server._launch_mode == LOCAL_API_LAUNCH_MODE_SPAWN:local_server.stop()- raise click.ClickException(- "Local mineru-api exited before becoming healthy."- )+ raise click.ClickException("Local mineru-api exited before becoming healthy.")try:return await fetch_server_health(client, local_server.base_url)except click.ClickException as exc:@@ -869,10 +850,7 @@ def submit_parse_task_sync(with ExitStack() as stack:files = []for upload_asset in upload_assets:- mime_type = (- mimetypes.guess_type(upload_asset.upload_name)[0]- or "application/octet-stream"- )+ mime_type = mimetypes.guess_type(upload_asset.upload_name)[0] or "application/octet-stream"file_handle = stack.enter_context(open(upload_asset.path, "rb"))files.append((@@ -892,15 +870,11 @@ def submit_parse_task_sync()except httpx.TimeoutException as exc:raise click.ClickException(- f"Timed out submitting parsing task to {task_url}. "- "The server may still be starting up or initializing the model."+ f"Timed out submitting parsing task to {task_url}. The server may still be starting up or initializing the model.") from excif response.status_code != 202:- raise click.ClickException(- f"Failed to submit parsing task: "- f"{response.status_code} {response_detail(response)}"- )+ raise click.ClickException(f"Failed to submit parsing task: {response.status_code} {response_detail(response)}")payload = response.json()task_id = payload.get("task_id")@@ -908,11 +882,7 @@ def submit_parse_task_sync(result_url = payload.get("result_url")file_names = payload.get("file_names")queued_ahead = payload.get("queued_ahead")- if (- not isinstance(task_id, str)- or not isinstance(status_url, str)- or not isinstance(result_url, str)- ):+ if not isinstance(task_id, str) or not isinstance(status_url, str) or not isinstance(result_url, str):raise click.ClickException("MinerU API returned an invalid task payload")normalized_file_names: tuple[str, ...] = ()@@ -954,8 +924,7 @@ async def wait_for_task_result(continueif response.status_code != 200:raise click.ClickException(- f"Failed to query task status for {task_label}: "- f"{response.status_code} {response_detail(response)}"+ f"Failed to query task status for {task_label}: {response.status_code} {response_detail(response)}")payload = response.json()@@ -978,14 +947,10 @@ async def wait_for_task_result(if status == "completed":returnraise click.ClickException(- f"Task {submit_response.task_id} failed for {task_label}: "- f"{json.dumps(payload, ensure_ascii=False)}"+ f"Task {submit_response.task_id} failed for {task_label}: {json.dumps(payload, ensure_ascii=False)}")- raise click.ClickException(- f"Timed out waiting for result of task {submit_response.task_id} "- f"for {task_label}"- )+ raise click.ClickException(f"Timed out waiting for result of task {submit_response.task_id} for {task_label}")async def download_result_zip(@@ -1011,8 +976,7 @@ async def download_result_zip(content_type = response.headers.get("content-type", "")if "application/zip" not in content_type:raise click.ClickException(- f"Expected a ZIP result for {task_label}, "- f"got content-type={content_type or 'unknown'}"+ f"Expected a ZIP result for {task_label}, got content-type={content_type or 'unknown'}")with open(zip_file_path, "wb") as handle:@@ -1024,8 +988,7 @@ async def download_result_zip(except httpx.TimeoutException as exc:zip_file_path.unlink(missing_ok=True)raise click.ClickException(- f"Timed out downloading result ZIP for task {submit_response.task_id} "- f"for {task_label}"+ f"Timed out downloading result ZIP for task {submit_response.task_id} for {task_label}") from excexcept asyncio.CancelledError:zip_file_path.unlink(missing_ok=True)@@ -1044,14 +1007,10 @@ def safe_extract_zip(zip_path: Path, output_dir: Path) -> None:for member in zip_file.infolist():member_path = PurePosixPath(member.filename)if member_path.is_absolute() or ".." in member_path.parts:- raise click.ClickException(- f"Refusing to extract unsafe ZIP entry: {member.filename}"- )+ raise click.ClickException(f"Refusing to extract unsafe ZIP entry: {member.filename}")target_path = (output_root / Path(*member_path.parts)).resolve()if target_path != output_root and output_root not in target_path.parents:- raise click.ClickException(- f"Refusing to extract unsafe ZIP entry: {member.filename}"- )+ raise click.ClickException(f"Refusing to extract unsafe ZIP entry: {member.filename}")if member.is_dir():target_path.mkdir(parents=True, exist_ok=True)