Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: remove global OCR mode configuration and update API to use request-level OCR mode
myhloli95015271b79b
diff --git a/docs/next/api/parse-jobs.md b/docs/next/api/parse-jobs.mdindex 3ac7ef5b..2f9eb765 100644--- a/docs/next/api/parse-jobs.md+++ b/docs/next/api/parse-jobs.md@@ -40,6 +40,7 @@ Job 状态:}],"tier": null,+ "ocr_mode": "auto","output_formats": ["markdown", "middle_json", "structured_content", "zip"],"callback": {"url": "https://your.app/mineru-webhook",@@ -54,9 +55,12 @@ Job 状态:|------|------|:--:|------|------|| `files` | array | 是 | 无 | 至少 1 个,最多由 access level 决定。 || `tier` | string 或 null | 否 | `null` | 当前服务支持的 tier 或 `null`。省略或传 `null` 表示使用默认选择策略;完整 tier 语义见 [解析 Tier](../tiers.md) 与 [ADR-0024](../decisions/0024-file-type-tier-normalization.md)。HTML 输入自动路由到 HTML 解析器。 |+| `ocr_mode` | string | 否 | `"auto"` | 本次任务的解析模式:`auto` 自动判断、`txt` 使用文本层、`ocr` 强制 OCR。覆盖所有 tier,沿用底层 PDF/图片解析语义;其他格式使用各自的固定解析路径。非法值或 `null` 返回 HTTP 400。 || `output_formats` | array | 否 | `["markdown"]` | 请求产物格式。 || `callback` | object | 否 | `null` | Webhook 回调配置,官方 API registered 用户可用。 |+`ocr_mode` 在同一任务的文件间共用,任务之间独立。省略时固定使用 `auto`;Local Parse Server 不再通过启动参数设置全局 OCR 模式。+HTML job 固定使用静态 `auto` 正文选择,不执行 JavaScript,也不下载页面引用的远程图片。URL source 的来源 URL会用于解析相对链接;本地 source 的相对图片仅允许位于源 HTML 的安全根目录内。diff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.mdindex f5c95264..36898291 100644--- a/docs/next/cli/mineru-kit-api-server.md+++ b/docs/next/cli/mineru-kit-api-server.md@@ -75,11 +75,13 @@ mineru-kit api-server --tier basic --port 16580mineru-kit api-server --tier standard --port 15982mineru-kit api-server --tier standard --no-flash --port 8000mineru-kit api-server --tier standard --preload-models-mineru-kit api-server --tier standard --language en --ocr-mode ocr --disable-image-analysis+mineru-kit api-server --tier standard --language en --disable-image-analysis```未传 `--tier` 时暴露 `flash`、`basic`、`standard`、`advanced`;PDF/image 请求未指定 tier 时默认 `standard`。+OCR 模式通过每次 `POST /v1/parse/jobs` 请求的 `ocr_mode` 设置,可选 `auto`、`txt`、`ocr`,省略时为 `auto`。启动参数 `--ocr-mode` 已移除,传入会报错;Python `create_app()` 同样不再接受该参数。+模型默认在首次解析时懒加载。`--preload-models` 会在 Basic 或 Standard 服务启动时提前加载所需模型,并在加载失败时让能力接口返回明确错误;Flash 没有本地模型,该参数对 Flash 无操作。Doclib managed parse-server 会自动启用模型预加载。启动完成后,HTTP API 不暴露 backend。`GET /v1/tiers` 也不新增 backend 字段;调用方如需推断实现,只能从 `current_model` 做弱推断。@@ -99,7 +101,6 @@ mineru-kit api-server --tier standard --language en --ocr-mode ocr --disable-ima### 稳定解析参数- language-- ocr-mode- disable-image-analysis- concurrency- upload-dirdiff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.mdindex ccc2b7fc..cd2e3984 100644--- a/docs/next/cli/mineru-kit-gradio.md+++ b/docs/next/cli/mineru-kit-gradio.md@@ -44,7 +44,6 @@ mineru-kit gradio \| `--api-server-tier` | 自动启动 server 的能力档位:`flash`、`basic`、`standard`。 || `--api-server-concurrency` | 自动启动 server 的最大并发任务数。 || `--api-server-language` | 自动启动 server 的 OCR 语言提示。 |-| `--api-server-ocr-mode` | 自动启动 server 的 OCR 模式:`auto`、`txt`、`ocr`。 || `--api-server-preload-models` | 在自动启动阶段预加载模型。 || `--api-server-no-flash` | 自动启动 server 时关闭 Flash。 || `--api-server-disable-image-analysis` | 自动启动 server 时关闭图片分析。 |@@ -58,6 +57,12 @@ mineru-kit gradio \解析 tier 使用原生离散滑块选择,上方即时显示当前档位。滑块按 `flash → basic → standard → advanced` 排列,仅包含服务实际支持的档位。默认优先选择 `standard`,否则选择最高可用档位;仅有一个档位时禁用滑块。上传新文件或清除结果会保留当前选择。+上传原始 PDF 时,tier 下方显示“强制 OCR”开关,所有档位(包括 Flash)均可使用。默认关闭,提交 `ocr_mode:"auto"` 自动判断;开启时提交 `ocr_mode:"ocr"`,忽略 PDF 文本层并进行 OCR。更换或清除文件会重置开关,同一文件切换 tier 保留选择。图片与其他格式隐藏开关,提交时固定使用 `auto`。++Gradio 转换事件新增 `force_ocr` 布尔参数,默认 `false`,位于 `raw_page_range` 之后。服务端处理转换事件时仍会检查原始文件类型,非 PDF 即使传入 `true` 也不会强制 OCR。++OCR 模式由每次 V1 解析任务决定;API Server 不再提供启动时的 OCR 配置,Gradio 的 `--api-server-ocr-mode` 及其 `--ocr-mode` 别名已移除,传入会报错。连接外部 V1 服务时,需要该服务支持任务级 `ocr_mode` 字段。+启用 Gradio 事件 API 时,转换事件的 `tier_position` 参数为从 `0` 开始的整数位置,替代原来的 tier 字符串。例如四档齐全时 `3` 对应 `advanced`;仅支持 `basic/standard/advanced` 时 `2` 对应 `advanced`。位置始终按照上述顺序对实际可用档位编号,越界位置会报错。V1 API 的 `tier` 参数仍使用字符串,启动参数不变。仅在已上传原始 PDF 且 tier 不是 `flash` 时显示页码双滑块。轨道范围由 `pypdfium2` 读取的实际页数确定,为 `1~n`,两端对应包含首尾页的连续选区。Flash 和其他文件格式隐藏控件,并始终全部解析。@@ -72,6 +77,12 @@ Gradio 转换事件保留 `raw_page_range` 字符串接口,仍接受 V1 `page_Gradio 首先发现 `/v1/health` 和 `/v1/tiers`,然后通过 `MinerUApiParser` 上传文件、创建 `/v1/parse/jobs`、轮询任务并下载 ZIP 结果。解析结果保存为严格 Middle JSON 2.0。+左下角使用与 3.4.5 一致的两列步骤卡片,展示准备请求、检查服务、提交任务、排队、解析中、下载结果、整理输出和完成。排队状态来自本地任务槽或 V1 的 `queued` 响应,圆点每秒循环更新;不显示前方任务数。每个界面服务仍一次执行一个转换,等待中的会话也会立即显示排队动画。++收到 V1 的 `running` 后开始解析计时,每 0.1 秒刷新一次;收到任务终态时冻结,下载和整理输出不计入该耗时。最终完成文案保留观察到的解析耗时;直接完成且没有观察到 `running` 的快速任务不显示耗时。界面动画不增加 API 请求,任务轮询仍为每秒一次。清除或更换文件会停止当前会话的状态流并释放本地等待位置,不向 V1 发送远端取消请求。++`MinerUApiParser.parse()` 和 `parse_async()` 提供可选的 `status_callback` 参数,接收公开的 `ApiJobStatus`(`queued`、`running`、`completed`、`partial`、`failed`、`canceled`)。回调在任务提交响应及每次轮询响应后同步调用;回调异常只记录日志。这里的 `completed` 表示服务端任务完成,解析方法仍需下载并构造 `ParseResult` 后才返回。+## 结果与下载页面只展示:diff --git a/docs/next/decisions/0017-mineru-kit-api-server-command.md b/docs/next/decisions/0017-mineru-kit-api-server-command.mdindex 839529e4..f022adc7 100644--- a/docs/next/decisions/0017-mineru-kit-api-server-command.md+++ b/docs/next/decisions/0017-mineru-kit-api-server-command.md@@ -89,7 +89,6 @@ backend 不是普通 API 协议层字段。#### 稳定解析参数- `--language`-- `--ocr-mode`- `--disable-image-analysis`- `--concurrency`- `--upload-dir`@@ -97,6 +96,8 @@ backend 不是普通 API 协议层字段。### 6. 不进入正式契约的参数+OCR 模式使用 V1 任务级 `ocr_mode` 参数,省略时默认 `auto`。服务启动参数 `--ocr-mode` 已移除,不保留全局默认值或兼容透传。+`--reload` 不进入正式命令设计。原因:diff --git a/docs/next/sdk/api-parser.md b/docs/next/sdk/api-parser.mdindex 6ac1d3e6..84869c11 100644--- a/docs/next/sdk/api-parser.md+++ b/docs/next/sdk/api-parser.md@@ -48,6 +48,7 @@ class MinerUApiParser(DocumentParser):api_url: str | None = None,api_key: str | None = None,tier: str | None = None,+ ocr_mode: Literal["auto", "txt", "ocr"] | None = None,include_images: bool = False,include_model_output: bool = False,) -> None: ...@@ -61,6 +62,7 @@ class MinerUApiParser(DocumentParser):| `api_key` | Bearer token。省略时读取 `MINERU_API_KEY`;Local Parse Server 未启用鉴权时可为空。 || `tier` | `flash`、`basic`、`standard`、`advanced` 或 `None`。`None` 表示 SDK 在 HTTP 请求中省略 `tier`,让 v1 API 使用默认选择策略;非 PDF/image 文件按 API Server 批量规则归一,见 [ADR-0024](../decisions/0024-file-type-tier-normalization.md)。 || `include_images` | 是否从 zip 产物读取图片 sidecar,并挂载到 `ParseResult` 图片缓存。 |+| `ocr_mode` | 请求级 OCR 模式:`auto` 自动判断、`txt` 使用文本层、`ocr` 强制 OCR。默认 `None`,在 HTTP 请求中省略字段,由服务端按 `auto` 处理;显式设置时同步与异步解析均传入任务顶层。 || `include_model_output` | 是否请求并保留模型原始输出;开启时通过 zip 产物读取。 |## 行为流程diff --git a/mineru/kit/commands/api_server.py b/mineru/kit/commands/api_server.pyindex 1ab39237..a68798b1 100644--- a/mineru/kit/commands/api_server.py+++ b/mineru/kit/commands/api_server.py@@ -47,7 +47,6 @@ def api_server_cmd("--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"),disable_image_analysis: bool = typer.Option(False, "--disable-image-analysis", help="Disable image analysis"),preload_models: bool = typer.Option(False, "--preload-models", help="Load local models during server startup"),api_key: str | None = typer.Option(None, "--api-key", help="Optional fixed API key"),@@ -74,8 +73,6 @@ def api_server_cmd(str(max_inline_bytes),"--language",normalized_language,- "--ocr-mode",- ocr_mode,*tier_args,*(["--no-flash"] if no_flash else []),*(["--allow-local-source"] if allow_local_source else []),diff --git a/mineru/kit/commands/gradio.py b/mineru/kit/commands/gradio.pyindex ae8cb1a0..088640c5 100644--- a/mineru/kit/commands/gradio.py+++ b/mineru/kit/commands/gradio.py@@ -73,9 +73,6 @@ def gradio_cmd(1, "--api-server-concurrency", "--concurrency", help="Managed server job concurrency"),api_server_language: str = typer.Option("ch", "--api-server-language", "--language", help="Managed server OCR language"),- api_server_ocr_mode: Literal["auto", "txt", "ocr"] = typer.Option(- "auto", "--api-server-ocr-mode", "--ocr-mode", help="Managed server OCR mode"- ),api_server_disable_image_analysis: bool = typer.Option(False,"--api-server-disable-image-analysis/--disable-image-analysis",@@ -116,7 +113,6 @@ def gradio_cmd(api_server_no_flash=api_server_no_flash,api_server_concurrency=api_server_concurrency,api_server_language=normalized_language,- api_server_ocr_mode=api_server_ocr_mode,api_server_disable_image_analysis=api_server_disable_image_analysis,api_server_preload_models=api_server_preload_models,)diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex dcfa6b19..4c34b588 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -6,6 +6,8 @@ import asyncioimport htmlimport jsonimport os+import time+from contextlib import aclosingfrom pathlib import Pathfrom collections.abc import Callablefrom typing import Any, Literal@@ -18,14 +20,21 @@ from ...utils.stdio import configure_standard_streamsfrom .artifacts import RunArtifacts, markdown_for_gradio, persist_parse_result, render_downloadfrom .client import (ManagedLocalApiServer,- STATUS_COMPLETED,- STATUS_PREPARING_REQUEST,- STATUS_PROCESSING_OUTPUT,V1ArtifactClient,V1ServerCapabilities,)from .page_range import effective_page_range as _effective_page_rangefrom .page_range import pdf_page_metadata, validate_max_pages+from .status import (+ DEFAULT_STATUS as _DEFAULT_STATUS,+ STATUS_COMPLETED,+ STATUS_PREPARING_REQUEST,+ STATUS_PROCESSING_OUTPUT,+ STATUS_QUEUED_LOCALLY,+ StatusPanelState,+ status_html as _status_html,+ stream_status_updates,+)_DOWNLOAD_FORMATS: tuple[tuple[str, str], ...] = (("zip", "ZIP"),@@ -36,16 +45,6 @@ _DOWNLOAD_FORMATS: tuple[tuple[str, str], ...] = (("pdf", "PDF"),)_DEFAULT_TIER = "standard"-_DEFAULT_STATUS = "Upload a file and start conversion."-_STATUS_STEPS = (- ("prepare", "准备"),- ("check", "检查服务"),- ("submit", "提交任务"),- ("process", "服务端解析"),- ("download", "下载结果"),- ("output", "整理输出"),- ("done", "完成"),-)_LATEX_DELIMITERS_A = [{"left": "$$", "right": "$$", "display": True},{"left": "$", "right": "$", "display": False},@@ -110,16 +109,6 @@ _KIT_MENU_CSS = """border: 0; border-radius: 6px; background: transparent; box-shadow: none; text-align: left;}.mineru-kit-download-options :is(button, a):hover { background: var(--background-fill-secondary, #f3f4f6); }-.mineru-kit-status { min-height: 84px; }-.mineru-kit-status-steps { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }-.mineru-kit-status-steps .status-step {- display: inline-flex; align-items: center; gap: 4px;- color: var(--body-text-color-subdued, #6b7280); font-size: 12px;-}-.mineru-kit-status-steps .status-step i { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .35; }-.mineru-kit-status-steps .status-step.is-active { color: var(--mineru-accent, #f97316); font-weight: 600; }-.mineru-kit-status-steps .status-step.is-active i, .mineru-kit-status-steps .status-step.is-done i { opacity: 1; }-.mineru-kit-status-steps .status-step.is-error { color: #dc2626; font-weight: 600; }.mineru-kit-empty-preview { min-height: 160px; display: grid; place-items: center; opacity: .65; }.mineru-kit-image-preview img { max-height: var(--mineru-pdf-page-height, 720px); object-fit: contain; }@media (max-width: 900px) {@@ -183,52 +172,8 @@ def _tier_for_position(position: int | float, tier_choices: list[Tier]) -> Tier:return tier_choices[int(position)]-def _status_html(message: str) -> str:- """生成不解释协议细节、只显示当前阶段的安全状态片段。"""- raw_message = str(message or _DEFAULT_STATUS)- safe_message = html.escape(raw_message)- lowered = raw_message.lower()- if raw_message.startswith("Failed:"):- current_index = len(_STATUS_STEPS) - 1- state_for_index = "error"- elif "downloading" in lowered or "downloaded" in lowered:- current_index, state_for_index = 4, "active"- elif "completed" in lowered:- current_index = len(_STATUS_STEPS) - 1- state_for_index = "done"- elif "preparing outputs" in lowered:- current_index, state_for_index = 5, "active"- elif "preparing" in lowered:- current_index, state_for_index = 0, "active"- elif "checking" in lowered:- current_index, state_for_index = 1, "active"- elif "submitting" in lowered:- current_index, state_for_index = 2, "active"- elif "processing" in lowered:- current_index, state_for_index = 3, "active"- else:- current_index, state_for_index = -1, "pending"- items: list[str] = []- for index, (_key, label) in enumerate(_STATUS_STEPS):- if state_for_index == "error" and index == current_index:- state = "is-error"- elif state_for_index == "done" or index < current_index:- state = "is-done"- elif index == current_index:- state = "is-active"- else:- state = "is-pending"- items.append(f'<span class="status-step {state}"><i></i>{label}</span>')- return (- '<div class="mineru-kit-status">'- f'<div class="mineru-kit-status-steps">{"".join(items)}</div>'- f"<strong>{safe_message}</strong>"- "</div>"- )--def _file_suffix(path_value: str | Path | None) -> str:- """读取上传文件的小写后缀,供 UI 预览和页码控件判断。"""+ """读取上传文件的小写后缀,供预览、选页与 OCR 控件判断。"""if not path_value:return ""return Path(path_value).suffix.lower().lstrip(".")@@ -289,6 +234,9 @@ def build_gradio_app(app_js = _resource_text("gradio_app.js")# Gradio 5 在 Blocks 构造时接收静态资源,6 则在 launch 时接收。blocks_kwargs = {"css": app_css, "js": app_js} if _gradio_major_version(gr) < 6 else {}+ # 等待限制放在生成器内部,使其他会话也能立即显示本地排队状态。+ conversion_slot = asyncio.Semaphore(1)+ session_tasks: dict[str, set[asyncio.Task[tuple[Any, ...]]]] = {}with gr.Blocks(**blocks_kwargs) as demo:gr.HTML(@@ -322,6 +270,14 @@ def build_gradio_app(show_label=False,elem_classes=["mineru-tier-slider"],)+ force_ocr = gr.Checkbox(+ value=False,+ label="强制 OCR",+ info="忽略 PDF 文本层并进行 OCR;关闭时自动判断。",+ visible=False,+ interactive=True,+ elem_classes=["mineru-force-ocr"],+ )page_range = gr.Textbox(value="",label="页码范围",@@ -360,7 +316,7 @@ def build_gradio_app(with gr.Row(elem_classes=["mineru-actions"]):convert_button = gr.Button("转换", variant="primary", scale=1, min_width=0, interactive=False)clear_button = gr.ClearButton(value="清除", scale=1, min_width=1)- status_panel = gr.HTML(_status_html(_DEFAULT_STATUS), elem_classes=["mineru-kit-status"])+ status_panel = gr.HTML(_status_html(), elem_classes=["mineru-status-panel"])with gr.Column(scale=4, min_width=340, elem_classes=["mineru-kit-preview", "mineru-preview-pane"]):pdf_preview = PDF(@@ -444,6 +400,7 @@ def build_gradio_app([input_file,page_range,+ force_ocr,markdown_output,markdown_source,structured_source,@@ -504,6 +461,29 @@ def build_gradio_app()private_event_kwargs = _private_event_kwargs(gr)++ def update_ocr_control(file_path: str | None) -> Any:+ """仅为原始 PDF 显示开关,并在更换或清除文件时重置为自动判断。"""+ return gr.update(value=False, visible=_file_suffix(file_path) in PDF_EXTENSIONS)++ input_file.change(+ fn=update_ocr_control,+ inputs=input_file,+ outputs=force_ocr,+ trigger_mode="always_last",+ **private_event_kwargs,+ )++ async def cancel_session_conversion(request: object | None = None) -> None:+ """主动回收当前会话的任务,不依赖 Gradio 5/6 对异步生成器的关闭实现。"""+ session_hash = getattr(request, "session_hash", None)+ tasks = session_tasks.pop(session_hash, set())+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)++ cancel_session_conversion.__annotations__["request"] = gr.Request# 显式注册加载事件,确保两个主版本都会执行前端初始化函数而不只加载其文本。demo.load(fn=None, js=app_js, **private_event_kwargs)tier.input(@@ -518,23 +498,18 @@ def build_gradio_app(% json.dumps(tier_choices),**private_event_kwargs,)- input_file.change(- fn=update_file_preview,- inputs=input_file,- outputs=[- pdf_preview,- image_preview,- office_preview,- generic_preview,- status_panel,- markdown_output,- markdown_source,- structured_source,- artifact_state,- *download_buttons.values(),- ],- **private_event_kwargs,- )+ preview_outputs = [+ pdf_preview,+ image_preview,+ office_preview,+ generic_preview,+ status_panel,+ markdown_output,+ markdown_source,+ structured_source,+ artifact_state,+ *download_buttons.values(),+ ]# 文件页数只在上传后读取;前端缓存元数据,tier 切换和拖动不发起 Python 请求。range_inputs = [input_file, tier, page_metadata, page_selection, page_handle_a, page_handle_b]@@ -576,6 +551,7 @@ def build_gradio_app(file_path: str | None,tier_position: int | float,raw_page_range: str,+ force_ocr: bool = False,request: object | None = None,) -> Any:"""执行单文件 V1 解析并流式更新状态与三个结果标签。"""@@ -614,64 +590,90 @@ def build_gradio_app(except MineruError as exc:yield (_status_html(f"Failed: {exc.code}: {exc}"), "", "", "", *empty_result[4:])return- yield (_status_html(STATUS_PREPARING_REQUEST), "", "", "", *empty_result[4:])- status_queue: asyncio.Queue[str] = asyncio.Queue()+ state = StatusPanelState()+ state.append(STATUS_PREPARING_REQUEST)+ yield (state.render(), *empty_result[1:])+ status_queue: asyncio.Queue[tuple[str, float]] = asyncio.Queue()loop = asyncio.get_running_loop()def emit(message: str) -> None:- """把同步 client 状态安全投递到当前 Gradio 事件循环。"""- loop.call_soon_threadsafe(status_queue.put_nowait, message)-- task = asyncio.create_task(- client.parse_file(- source_path,- tier=selected_tier,- page_range=page_text,- status_callback=emit,- )- )+ """记录通知时刻,避免队列消费延迟被误算为服务端解析耗时。"""+ loop.call_soon_threadsafe(status_queue.put_nowait, (message, time.monotonic()))++ async def run_conversion() -> tuple[Any, ...]:+ """在单任务槽内解析和整理结果;取消或失败均自动释放等待位置。"""+ if conversion_slot.locked():+ emit(STATUS_QUEUED_LOCALLY)+ async with conversion_slot:+ result = await client.parse_file(+ source_path,+ tier=selected_tier,+ page_range=page_text,+ # 再次检查源文件类型,避免事件 API 或隐藏控件残留值强制处理非 PDF。+ ocr_mode="ocr" if suffix in PDF_EXTENSIONS and force_ocr else "auto",+ status_callback=emit,+ )+ emit(STATUS_PROCESSING_OUTPUT)+ artifacts = await asyncio.to_thread(+ persist_parse_result,+ result,+ source_path,+ output_root=output_root,+ page_range=page_text,+ )+ markdown_text = artifacts.markdown_path.read_text(encoding="utf-8")+ structured_text = artifacts.structured_content_path.read_text(encoding="utf-8")+ preview_path = artifacts.layout_pdf_path or artifacts.origin_pdf_path+ office_html = _build_office_result_html(artifacts, request) if _is_office(source_path) else ""+ generic_html = (+ "" if preview_path or office_html else '<div class="mineru-kit-empty-preview">结果已生成</div>'+ )+ show_image_preview = suffix in IMAGE_EXTENSIONS and preview_path is None+ return (+ markdown_for_gradio(markdown_text, artifacts),+ markdown_text,+ structured_text,+ gr.update(value=str(preview_path) if preview_path else None, visible=preview_path is not None),+ gr.update(value=str(source_path) if show_image_preview else None, visible=show_image_preview),+ gr.update(value=office_html, visible=bool(office_html)),+ gr.update(value=generic_html, visible=bool(generic_html)),+ artifacts.as_state(),+ *_download_updates(gr, interactive=True),+ )++ task = asyncio.create_task(run_conversion())+ session_hash = getattr(request, "session_hash", None)+ if session_hash:+ session_tasks.setdefault(session_hash, set()).add(task)++ def forget_task(done_task: asyncio.Task[tuple[Any, ...]]) -> None:+ """任务结束即释放会话索引,即使前端已丢弃生成器也不保留任务引用。"""+ tasks = session_tasks.get(session_hash)+ if tasks is not None:+ tasks.discard(done_task)+ if not tasks:+ session_tasks.pop(session_hash, None)++ task.add_done_callback(forget_task)try:- while not task.done():- try:- message = await asyncio.wait_for(status_queue.get(), timeout=0.25)- except asyncio.TimeoutError:- continue- yield (_status_html(message), "", "", "", *empty_result[4:])- while not status_queue.empty():- yield (_status_html(status_queue.get_nowait()), "", "", "", *empty_result[4:])- result = await task- emit(STATUS_PROCESSING_OUTPUT)- yield (_status_html(STATUS_PROCESSING_OUTPUT), "", "", "", *empty_result[4:])- artifacts = await asyncio.to_thread(- persist_parse_result,- result,- source_path,- output_root=output_root,- page_range=page_text,- )- markdown_text = artifacts.markdown_path.read_text(encoding="utf-8")- structured_text = artifacts.structured_content_path.read_text(encoding="utf-8")- preview_path = artifacts.layout_pdf_path or artifacts.origin_pdf_path- office_html = _build_office_result_html(artifacts, request) if _is_office(source_path) else ""- generic_html = "" if preview_path or office_html else '<div class="mineru-kit-empty-preview">结果已生成</div>'- show_image_preview = suffix in IMAGE_EXTENSIONS and preview_path is None- yield (- _status_html(STATUS_COMPLETED),- markdown_for_gradio(markdown_text, artifacts),- markdown_text,- structured_text,- gr.update(value=str(preview_path) if preview_path else None, visible=preview_path is not None),- gr.update(value=str(source_path) if show_image_preview else None, visible=show_image_preview),- gr.update(value=office_html, visible=bool(office_html)),- gr.update(value=generic_html, visible=bool(generic_html)),- artifacts.as_state(),- *_download_updates(gr, interactive=True),- )+ async with aclosing(stream_status_updates(task, status_queue, state)) as updates:+ async for status in updates:+ # 动画只更新状态卡片,避免反复重建预览和清空结果组件。+ yield (status, *(gr.skip() for _ in empty_result[1:]))+ result_outputs = await task+ state.append(STATUS_COMPLETED)+ yield (state.render(), *result_outputs)+ except asyncio.CancelledError:+ # 会话重置后静默结束旧流,避免把取消异常或旧状态写回新界面。+ returnexcept Exception as exc:+ state.append(f"Failed: {exc}")+ yield (state.render(), *empty_result[1:])+ finally:+ # 清除、换文件或断开流时仅取消本地等待,不发送远端取消请求。if not task.done():task.cancel()- await asyncio.gather(task, return_exceptions=True)- yield (_status_html(f"Failed: {exc}"), "", "", "", *empty_result[4:])+ await asyncio.gather(task, return_exceptions=True)convert_outputs = [status_panel,@@ -687,17 +689,25 @@ def build_gradio_app(]# Gradio 在读取函数签名时需要真实的 Request 类型对象;注解在运行时补回以保持延迟导入。convert_handler.__annotations__["request"] = gr.Request- event_kwargs: dict[str, Any] = {"queue": True, "show_progress": "hidden"}+ event_kwargs: dict[str, Any] = {"queue": True, "show_progress": "hidden", "concurrency_limit": None}if _gradio_major_version(gr) >= 6:event_kwargs["api_visibility"] = "public" if enable_api else "private"else:event_kwargs["api_name"] = "to_markdown" if enable_api else False- convert_button.click(+ convert_event = convert_button.click(fn=convert_handler,- inputs=[input_file, tier, page_range],+ inputs=[input_file, tier, page_range, force_ocr],outputs=convert_outputs,**event_kwargs,)+ input_file.change(+ fn=update_file_preview,+ inputs=input_file,+ outputs=preview_outputs,+ cancels=[convert_event],+ **private_event_kwargs,+ )+ input_file.change(fn=cancel_session_conversion, inputs=[], outputs=[], **private_event_kwargs)reset_outputs = [status_panel,@@ -727,7 +737,8 @@ def build_gradio_app(*_download_updates(gr, interactive=False),)- clear_button.click(fn=reset_ui, inputs=[], outputs=reset_outputs, queue=False)+ clear_button.click(fn=reset_ui, inputs=[], outputs=reset_outputs, cancels=[convert_event], queue=False)+ clear_button.click(fn=cancel_session_conversion, inputs=[], outputs=[], **private_event_kwargs)for format_name, _label in _DOWNLOAD_FORMATS:download_buttons[format_name].click(@@ -759,7 +770,6 @@ def launch_gradio(api_server_no_flash: bool,api_server_concurrency: int,api_server_language: str,- api_server_ocr_mode: Literal["auto", "txt", "ocr"],api_server_disable_image_analysis: bool,api_server_preload_models: bool,max_pages: int | None = None,@@ -779,7 +789,6 @@ def launch_gradio(no_flash=api_server_no_flash,concurrency=api_server_concurrency,language=api_server_language,- ocr_mode=api_server_ocr_mode,disable_image_analysis=api_server_disable_image_analysis,preload_models=api_server_preload_models,api_key=resolved_api_key,diff --git a/mineru/kit/gradio/client.py b/mineru/kit/gradio/client.pyindex 49796383..12ce142f 100644--- a/mineru/kit/gradio/client.py+++ b/mineru/kit/gradio/client.py@@ -12,24 +12,26 @@ import timefrom collections.abc import Callablefrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, cast+from typing import Any, Literal, castimport httpx-from ...parser.api_client import MinerUApiParser, should_trust_env_for_url+from ...parser.api_client import ApiJobStatus, MinerUApiParser, should_trust_env_for_urlfrom ...parser.base import ParseResultfrom ...parser.page_range import normalize_page_range_inputfrom ...parser.process_control import ManagedProcessControlfrom ...types import SERVER_TIERS, TIERS, ServerTier, Tierfrom ...utils.stdio import utf8_subprocess_env--STATUS_PREPARING_REQUEST = "Preparing request..."-STATUS_CHECKING_SERVER = "Checking server status..."-STATUS_SUBMITTING_TASK = "Submitting task..."-STATUS_PROCESSING_ON_SERVER = "Processing on server..."-STATUS_DOWNLOADING_RESULT = "Result archive downloaded."-STATUS_PROCESSING_OUTPUT = "Preparing outputs..."-STATUS_COMPLETED = "Completed"+from .status import (+ STATUS_CHECKING_SERVER,+ STATUS_COMPLETED,+ STATUS_DOWNLOADING_RESULT,+ STATUS_PREPARING_REQUEST,+ STATUS_PROCESSING_ON_SERVER,+ STATUS_PROCESSING_OUTPUT,+ STATUS_QUEUED_ON_SERVER,+ STATUS_SUBMITTING_TASK,+)class V1ArtifactError(RuntimeError):@@ -181,6 +183,7 @@ class V1ArtifactClient:*,tier: str,page_range: str,+ ocr_mode: Literal["auto", "txt", "ocr"] = "auto",status_callback: Callable[[str], None] | None = None,) -> ParseResult:"""通过 V1 API 解析单个文件,并返回带图片/模型输出的 `ParseResult`。"""@@ -203,18 +206,30 @@ class V1ArtifactClient:api_url=self.base_url,api_key=self.api_key,tier=cast(Tier, tier),+ ocr_mode=ocr_mode,include_images=True,include_model_output=True,)- emit(STATUS_PROCESSING_ON_SERVER)++ def on_job_status(status: ApiJobStatus) -> None:+ """将真实 V1 状态映射到卡片阶段,服务端完成仅代表开始下载。"""+ messages: dict[ApiJobStatus, str] = {+ "queued": STATUS_QUEUED_ON_SERVER,+ "running": STATUS_PROCESSING_ON_SERVER,+ "completed": STATUS_DOWNLOADING_RESULT,+ "partial": STATUS_DOWNLOADING_RESULT,+ "failed": "Failed: server task failed",+ "canceled": "Failed: server task canceled",+ }+ emit(messages[status])+try:- result = await parser.parse_async(path, page_range=page_range)+ result = await parser.parse_async(path, page_range=page_range, status_callback=on_job_status)except Exception as exc:emit(f"Failed: {exc}")if isinstance(exc, (FileNotFoundError, V1ArtifactError)):raiseraise V1ArtifactError(str(exc), code=getattr(exc, "code", "parse_failed")) from exc- emit(STATUS_DOWNLOADING_RESULT)return resultdef _headers(self) -> dict[str, str]:@@ -248,7 +263,6 @@ class ManagedLocalApiServer:no_flash: bool = False,concurrency: int = 1,language: str = "ch",- ocr_mode: str = "auto",disable_image_analysis: bool = False,preload_models: bool = False,api_key: str | None = None,@@ -262,7 +276,6 @@ class ManagedLocalApiServer:self.no_flash = no_flashself.concurrency = concurrencyself.language = language- self.ocr_mode = ocr_modeself.disable_image_analysis = disable_image_analysisself.preload_models = preload_modelsself.api_key = api_key@@ -373,8 +386,6 @@ class ManagedLocalApiServer:str(self.concurrency),"--language",self.language,- "--ocr-mode",- self.ocr_mode,*(["--no-flash"] if self.no_flash else []),*(["--disable-image-analysis"] if self.disable_image_analysis else []),*(["--preload-models"] if self.preload_models else []),diff --git a/mineru/kit/gradio/status.py b/mineru/kit/gradio/status.pynew file mode 100644index 00000000..ed80d5de--- /dev/null+++ b/mineru/kit/gradio/status.py@@ -0,0 +1,193 @@+"""Gradio 步骤卡片、单次任务计时与流式状态等待。"""++from __future__ import annotations++import asyncio+import html+import time+from collections.abc import AsyncIterator, Callable+from dataclasses import dataclass, field+from typing import Any++DEFAULT_STATUS = "Upload a file and start conversion."+STATUS_PREPARING_REQUEST = "Preparing request..."+STATUS_CHECKING_SERVER = "Checking server status..."+STATUS_SUBMITTING_TASK = "Submitting task..."+STATUS_QUEUED_LOCALLY = "Queued locally"+STATUS_QUEUED_ON_SERVER = "Queued on server"+STATUS_PROCESSING_ON_SERVER = "Processing on server..."+STATUS_DOWNLOADING_RESULT = "Task completed, downloading result..."+STATUS_PROCESSING_OUTPUT = "Preparing outputs..."+STATUS_COMPLETED = "Completed"++_STEPS = (+ ("prepare", "Prepare", "准备请求"),+ ("check", "Check service", "检查服务"),+ ("submit", "Submit", "提交任务"),+ ("queue", "Queue", "排队"),+ ("process", "Parse", "解析中"),+ ("download", "Download", "下载结果"),+ ("outputs", "Build outputs", "整理输出"),+ ("done", "Done", "完成"),+)+_MESSAGE_STEPS = {+ STATUS_PREPARING_REQUEST: 0,+ STATUS_CHECKING_SERVER: 1,+ STATUS_SUBMITTING_TASK: 2,+ STATUS_QUEUED_LOCALLY: 3,+ STATUS_QUEUED_ON_SERVER: 3,+ STATUS_PROCESSING_ON_SERVER: 4,+ STATUS_DOWNLOADING_RESULT: 5,+ STATUS_PROCESSING_OUTPUT: 6,+ STATUS_COMPLETED: 7,+}+++def _localized_text(key: str, english: str, chinese: str) -> str:+ """输出中英文属性,复用页面现有的浏览器语言本地化逻辑。"""+ return (+ f'<span data-mineru-i18n-key="{html.escape(key, quote=True)}"'+ f' data-mineru-i18n-en="{html.escape(english, quote=True)}"'+ f' data-mineru-i18n-zh="{html.escape(chinese, quote=True)}">{html.escape(chinese)}</span>'+ )+++@dataclass+class StatusPanelState:+ """保存一次转换的阶段和单调时钟,不在会话之间共享状态。"""++ clock: Callable[[], float] = field(default=time.monotonic, repr=False)+ message: str = DEFAULT_STATUS+ step_index: int = -1+ processing_elapsed: float | None = None+ _processing_started: float | None = None+ _queue_started: float | None = None++ def append(self, message: str, *, at: float | None = None) -> bool:+ """接收真实阶段变化;重复通知不会重置解析计时或排队动画。"""+ if not message or message == self.message:+ return False+ now = self.clock() if at is None else at+ if self._processing_started is not None:+ self.processing_elapsed = max(0.0, now - self._processing_started)+ self._processing_started = None+ if message == STATUS_PROCESSING_ON_SERVER:+ self._processing_started = now+ self.processing_elapsed = 0.0+ if message in (STATUS_QUEUED_LOCALLY, STATUS_QUEUED_ON_SERVER):+ if self._queue_started is None:+ self._queue_started = now+ else:+ self._queue_started = None+ self.message = message+ # 本地等待可能发生在上传之前;已展示的步骤不因后续准备通知倒退。+ self.step_index = max(self.step_index, _MESSAGE_STEPS.get(message, -1))+ if message.startswith("Failed:"):+ self.step_index = len(_STEPS) - 1+ return True++ @property+ def refresh_interval(self) -> float | None:+ """只在解析或排队期间启用旧版刷新频率。"""+ if self._processing_started is not None:+ return 0.1+ if self._queue_started is not None:+ return 1.0+ return None++ def render(self) -> str:+ """按 3.4.5 的两列卡片结构渲染当前状态,并转义外部错误文本。"""+ now = self.clock()+ failed = self.message.startswith("Failed:")+ completed = self.message == STATUS_COMPLETED+ items: list[str] = []+ for index, (key, english, chinese) in enumerate(_STEPS):+ if failed and index == self.step_index:+ state = "is-active is-error"+ key, english, chinese = "failed", "Failed", "失败"+ elif completed or index < self.step_index:+ state = "is-done"+ elif index == self.step_index:+ state = "is-active"+ else:+ state = "is-pending"+ items.append(+ f'<div class="status-step {state}"><span class="status-dot"></span>'+ f'<span class="status-label">{_localized_text("status_step_" + key, english, chinese)}</span></div>'+ )+ latest = self.message+ if self._processing_started is not None:+ elapsed = max(0.0, now - self._processing_started)+ latest = f"Processing on server ({elapsed:.1f}s)"+ elif self._queue_started is not None:+ latest += "." * (int(max(0.0, now - self._queue_started)) % 10 + 1)+ elif completed and self.processing_elapsed is not None:+ latest = f"{STATUS_COMPLETED} ({self.processing_elapsed:.1f}s)"+ if self.message == DEFAULT_STATUS:+ title = _localized_text("status_idle_title", "Waiting", "等待任务")+ latest_html = _localized_text("status_idle_hint", DEFAULT_STATUS, "上传文件后开始转换。")+ else:+ title = _localized_text("status_latest", "Latest status", "最新状态")+ latest_html = html.escape(latest)+ return (+ '<div class="status-steps-panel">'+ f'<div class="status-panel-title">{title}</div>'+ f'<div class="status-steps-list">{"".join(items)}</div>'+ f'<div class="status-latest">{latest_html}</div></div>'+ )+++def status_html(message: str = DEFAULT_STATUS) -> str:+ """为初始化、输入校验和重置生成没有历史计时的状态卡片。"""+ state = StatusPanelState()+ state.append(message)+ return state.render()+++async def stream_status_updates(+ task: asyncio.Task[Any],+ events: asyncio.Queue[tuple[str, float]],+ state: StatusPanelState,+) -> AsyncIterator[str]:+ """同时等待任务、状态通知和本地动画时钟,并及时回收临时等待任务。"""+ while True:+ while not events.empty():+ message, at = events.get_nowait()+ if state.append(message, at=at):+ yield state.render()+ if task.done():+ return+ waiter = asyncio.create_task(events.get())+ updated_html: str | None = None+ try:+ done, _ = await asyncio.wait({task, waiter}, timeout=state.refresh_interval, return_when=asyncio.FIRST_COMPLETED)+ if waiter in done:+ message, at = waiter.result()+ if state.append(message, at=at):+ updated_html = state.render()+ elif not done:+ updated_html = state.render()+ finally:+ if not waiter.done():+ waiter.cancel()+ await asyncio.gather(waiter, return_exceptions=True)+ # 向 Gradio 交回控制权前已回收临时 waiter,避免暂停在 yield 时残留后台等待。+ if updated_html is not None:+ yield updated_html+++__all__ = [+ "DEFAULT_STATUS",+ "STATUS_CHECKING_SERVER",+ "STATUS_COMPLETED",+ "STATUS_DOWNLOADING_RESULT",+ "STATUS_PREPARING_REQUEST",+ "STATUS_PROCESSING_ON_SERVER",+ "STATUS_PROCESSING_OUTPUT",+ "STATUS_QUEUED_LOCALLY",+ "STATUS_QUEUED_ON_SERVER",+ "STATUS_SUBMITTING_TASK",+ "StatusPanelState",+ "status_html",+ "stream_status_updates",+]diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.pyindex 2f08eb76..fd722b71 100644--- a/mineru/parser/__init__.py+++ b/mineru/parser/__init__.py@@ -6,12 +6,13 @@ from typing import Literalfrom ..model.flash.html import HtmlSourceContextfrom ..types import Tier-from .api_client import MinerUApiParser+from .api_client import ApiJobStatus, MinerUApiParserfrom .base import MIDDLE_JSON_SCHEMA_VERSION, DocumentParser, ParseResultfrom .mineru_parser import MinerUParserfrom .tier import PARSER_BACKENDS, backend_for_tier__all__ = [+ "ApiJobStatus","backend_for_tier","PARSER_BACKENDS","DocumentParser",diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex cceef8ae..8c534162 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -19,8 +19,9 @@ import osimport randomimport timeimport zipfile+from collections.abc import Callablefrom pathlib import Path-from typing import Any, Literal+from typing import Any, Literal, castfrom urllib.parse import urlparseimport httpx@@ -41,6 +42,19 @@ _TRANSPORT_RETRY_MAX_DELAY_SECONDS = 2.0logger = logging.getLogger("mineru.api_client")_RequestMethod = Literal["GET", "POST", "PUT"]+ApiJobStatus = Literal["queued", "running", "completed", "partial", "failed", "canceled"]+_JOB_STATUSES = {"queued", "running", *_TERMINAL_JOB_STATUSES}+++def _notify_job_status(job: dict[str, Any], callback: Callable[[ApiJobStatus], None] | None) -> None:+ """通知观察者真实任务状态,隔离回调错误并忽略未知的扩展状态。"""+ status = job.get("status")+ if callback is None or not isinstance(status, str) or status not in _JOB_STATUSES:+ return+ try:+ callback(cast(ApiJobStatus, status))+ except Exception:+ logger.exception("Parse job status callback failed")class _APITransportError(Exception):@@ -74,6 +88,7 @@ class MinerUApiParser(DocumentParser):Constructor parameters:- ``tier`` → v1 ``tier`` (``"flash"`` / ``"basic"`` / ``"standard"`` / ``"advanced"``); ``None`` omits the field+ - ``ocr_mode`` → v1 request OCR mode; ``None`` omits the field (server default: ``"auto"``)- ``page_range`` → per-file v1 ``page_range``"""@@ -85,38 +100,57 @@ class MinerUApiParser(DocumentParser):api_url: str | None = None,api_key: str | None = None,tier: Tier | None = None,+ ocr_mode: Literal["auto", "txt", "ocr"] | None = None,include_images: bool = False,include_model_output: bool = False,) -> None:+ """保存请求配置;未指定 OCR 模式时省略字段,保留既有客户端的请求结构。"""+ if ocr_mode is not None and ocr_mode not in ("auto", "txt", "ocr"):+ raise ValueError(f"Unsupported OCR mode '{ocr_mode}'")self._base_url = (api_url or os.environ.get("MINERU_API_URL") or self.DEFAULT_API_URL).rstrip("/")self._api_key = (api_key if api_key is not None else os.environ.get("MINERU_API_KEY")) or Noneself._local = _is_local_network_url(self._base_url)self._trust_env = should_trust_env_for_url(self._base_url)self._source_features: set[str] | None = Noneself.tier = validate_tier(tier) if tier is not None else None+ self.ocr_mode = ocr_modeself.include_images = include_imagesself.include_model_output = include_model_output# ── DocumentParser interface ─────────────────────────────────────- def parse(self, path: str | Path, *, page_range: str = "") -> ParseResult:+ def parse(+ self,+ path: str | Path,+ *,+ page_range: str = "",+ status_callback: Callable[[ApiJobStatus], None] | None = None,+ ) -> ParseResult:+ """同步解析文件;可选回调观察任务状态,服务端完成后仍需下载并构造结果。"""page_range = normalize_page_range_input(page_range)file_path = Path(path)if not file_path.exists():raise FileNotFoundError(file_path)payload = self._build_payload(self._build_source(file_path), page_range)- job = self._do_parse(payload)+ job = self._do_parse(payload, status_callback=status_callback)return self._build_result(job, file_path.name)- async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:+ async def parse_async(+ self,+ path: str | Path,+ *,+ page_range: str = "",+ status_callback: Callable[[ApiJobStatus], None] | None = None,+ ) -> ParseResult:+ """异步解析文件;回调属于本次调用,不在复用的 parser 实例上保存。"""page_range = normalize_page_range_input(page_range)file_path = Path(path)if not file_path.exists():raise FileNotFoundError(file_path)payload = self._build_payload(await self._async_build_source(file_path), page_range)- job = await self._async_do_parse(payload)+ job = await self._async_do_parse(payload, status_callback=status_callback)return await self._async_build_result(job, file_path.name)def get_usage(self) -> dict[str, Any]:@@ -174,6 +208,8 @@ class MinerUApiParser(DocumentParser):}if self.tier is not None:payload["tier"] = self.tier+ if self.ocr_mode is not None:+ payload["ocr_mode"] = self.ocr_modereturn payloaddef _supports_local_source(self) -> bool:@@ -433,7 +469,10 @@ class MinerUApiParser(DocumentParser):# ── parse execution ──────────────────────────────────────────────- def _do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:+ def _do_parse(+ self, payload: dict[str, Any], *, status_callback: Callable[[ApiJobStatus], None] | None = None+ ) -> dict[str, Any]:+ """提交同步任务,并从提交响应开始通知实际状态。"""with httpx.Client(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = _request_once(cli,@@ -444,11 +483,15 @@ class MinerUApiParser(DocumentParser):json_body=payload,)job = self._check(r)+ _notify_job_status(job, status_callback)if job.get("status") not in _TERMINAL_JOB_STATUSES:- job = self._poll(cli, job["job_id"])+ job = self._poll(cli, job["job_id"], status_callback=status_callback)return job- async def _async_do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:+ async def _async_do_parse(+ self, payload: dict[str, Any], *, status_callback: Callable[[ApiJobStatus], None] | None = None+ ) -> dict[str, Any]:+ """提交异步任务,并从提交响应开始通知实际状态。"""async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:r = await _async_request_once(cli,@@ -459,11 +502,13 @@ class MinerUApiParser(DocumentParser):json_body=payload,)job = self._check(r)+ _notify_job_status(job, status_callback)if job.get("status") not in _TERMINAL_JOB_STATUSES:- job = await self._async_poll(cli, job["job_id"])+ job = await self._async_poll(cli, job["job_id"], status_callback=status_callback)return job- def _poll(self, cli: Any, job_id: str) -> dict[str, Any]:+ def _poll(self, cli: Any, job_id: str, *, status_callback: Callable[[ApiJobStatus], None] | None = None) -> dict[str, Any]:+ """保持每秒一次的同步轮询,并通知每次响应中的任务状态。"""for _ in range(_POLL_MAX_ATTEMPTS): # max 1 hourtime.sleep(_POLL_INTERVAL_SECONDS)r = _request_with_retry(@@ -474,11 +519,15 @@ class MinerUApiParser(DocumentParser):headers=self._headers(),)job = self._check(r)+ _notify_job_status(job, status_callback)if job.get("status") in _TERMINAL_JOB_STATUSES:return jobraise _V1APIError("timeout", f"Job {job_id} did not complete within timeout")- async def _async_poll(self, cli: Any, job_id: str) -> dict[str, Any]:+ async def _async_poll(+ self, cli: Any, job_id: str, *, status_callback: Callable[[ApiJobStatus], None] | None = None+ ) -> dict[str, Any]:+ """保持每秒一次的异步轮询,状态刷新不额外增加网络请求。"""for _ in range(_POLL_MAX_ATTEMPTS):await asyncio.sleep(_POLL_INTERVAL_SECONDS)r = await _async_request_with_retry(@@ -489,6 +538,7 @@ class MinerUApiParser(DocumentParser):headers=self._headers(),)job = self._check(r)+ _notify_job_status(job, status_callback)if job.get("status") in _TERMINAL_JOB_STATUSES:return jobraise _V1APIError("timeout", f"Job {job_id} did not complete within timeout")diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 78c5f2b0..593497bb 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -464,6 +464,9 @@ class CreateJobRequest(BaseModel):model_config = _PYDANTIC_CONFIGfiles: list[JobFileEntry] = Field(min_length=1)tier: Tier | None = None+ ocr_mode: Literal["auto", "txt", "ocr"] = Field(+ default="auto", description="OCR mode for this parse job: auto-detect, native text, or forced OCR."+ )output_formats: list[str] = ["markdown"]callback: CallbackConfig | None = None@@ -1323,7 +1326,6 @@ async def _run_job(req: CreateJobRequest,file_store: FileStore,*,- ocr_mode: str,image_analysis: bool,url_timeout: int = 60,allow_local_source: bool = False,@@ -1380,7 +1382,7 @@ async def _run_job(result = await parse_async(str(tmp_path),tier=effective_tier,- ocr_mode=ocr_mode,+ ocr_mode=req.ocr_mode,image_analysis=image_analysis,page_range=page_range,source_context=source_context,@@ -1843,7 +1845,6 @@ async def create_job(max_inline_bytes_val: int = request.app.state.max_inline_bytesallow_http_source_val: bool = request.app.state.allow_http_sourceflash_enabled_val: bool = request.app.state.flash_enabled- ocr_mode_val: str = request.app.state.ocr_modeimage_analysis_val: bool = request.app.state.image_analysis# async — fire and forget@@ -1853,7 +1854,6 @@ async def create_job(rec,body,file_store,- ocr_mode=ocr_mode_val,image_analysis=image_analysis_val,url_timeout=url_timeout_val,allow_local_source=allow_local_source_val,@@ -1949,9 +1949,6 @@ def _build_v1_router() -> APIRouter:return _router-_OCR_MODES = ("auto", "txt", "ocr")--def _normalize_server_tier(tier: str | None) -> ServerTier:"""规范化 API server 的单个启动能力档位。"""if tier is not None and not isinstance(tier, str):@@ -2129,7 +2126,6 @@ def create_app(allow_http_source: bool = False,api_key: str | None = None,language: str = "ch",- ocr_mode: str = "auto",image_analysis: bool = True,preload_models: bool = False,) -> FastAPI:@@ -2159,8 +2155,6 @@ def create_app(to access list endpoints and advanced output formats.language:Hybrid medium OCR language hint; accepted by other efforts for compatibility.- ocr_mode:- PDF OCR/text extraction mode for Hybrid backends.image_analysis:Whether image analysis is enabled for Hybrid backends.preload_models:@@ -2204,7 +2198,6 @@ def create_app(application.state.allow_http_source = allow_http_sourceapplication.state.api_key = _api_keyapplication.state.language = language- application.state.ocr_mode = ocr_modeapplication.state.effort = effortapplication.state.image_analysis = image_analysisapplication.state.preload_models = preload_models@@ -2259,7 +2252,6 @@ def create_app(application.state.allow_http_source = allow_http_sourceapplication.state.api_key = _api_keyapplication.state.language = language- application.state.ocr_mode = ocr_modeapplication.state.effort = effortapplication.state.image_analysis = image_analysisapplication.state.preload_models = preload_models@@ -2388,12 +2380,6 @@ def create_app(metavar="[" + "|".join(_API_SERVER_LANGUAGES) + "]",help="Hybrid medium OCR language hint; accepted by other efforts for compatibility.",)- "--ocr-mode",- default="auto",- type=click.Choice(_OCR_MODES),- help="PDF OCR/text extraction mode. Applies to hybrid-* backends.",-)@click.option("--disable-image-analysis",is_flag=True,@@ -2422,7 +2408,6 @@ def main(max_inline_bytes: int,allow_http_source: bool,language: str,- ocr_mode: str,disable_image_analysis: bool,preload_models: bool,api_key: str | None,@@ -2459,7 +2444,6 @@ def main(allow_http_source=allow_http_source,api_key=api_key,language=language,- ocr_mode=ocr_mode,image_analysis=not disable_image_analysis,preload_models=preload_models,)diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 0b38e94d..91a128c9 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -560,6 +560,21 @@ def test_api_server_rejects_backend_and_effort_options() -> None:assert "--effort" in effort_result.output+ ("command", "option"),+ [("api-server", "--ocr-mode"), ("gradio", "--ocr-mode"), ("gradio", "--api-server-ocr-mode")],+)+def test_server_commands_reject_startup_ocr_configuration(command: str, option: str) -> None:+ """服务启动命令不再接受或展示 OCR 配置,单次解析命令继续提供该参数。"""+ result = runner.invoke(app, [command, option, "ocr"])+ assert result.exit_code != 0+ assert "No such option" in result.output+ help_result = runner.invoke(app, [command, "--help"])+ assert help_result.exit_code == 0+ assert option not in help_result.output+ assert "--ocr-mode" in runner.invoke(app, ["parse", "--help"]).output++def test_kit_commands_do_not_expose_formula_table_switches() -> None:"""校验 mineru-kit 公开命令不再暴露公式/表格识别开关。"""parse_help = runner.invoke(app, ["parse", "--help"])@@ -591,6 +606,7 @@ def test_api_server_forwards_single_tier_and_no_flash(monkeypatch: Any) -> None:assert [seen["args"][index + 1] for index, item in enumerate(seen["args"]) if item == "--tier"] == ["standard"]assert "--no-flash" in seen["args"]assert "--preload-models" in seen["args"]+ assert "--ocr-mode" not in seen["args"]def test_api_server_without_tier_lets_parser_api_apply_standard_default(monkeypatch: Any) -> None:diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex 74461083..023456a4 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport io+import jsonimport subprocessimport sysimport zipfile@@ -35,7 +36,7 @@ from mineru.kit.main import appfrom mineru.parser import api_client as parser_api_clientfrom mineru.parser import api_server as parser_api_serverfrom mineru.parser.base import ParseResult-from mineru.types import BlockType, ImageBlock, ImageBodyBlock, MiddleJson, PageInfo, TextBlock, TextSpan+from mineru.types import BlockType, ImageBlock, ImageBodyBlock, MiddleJson, ModelJson, PageInfo, TextBlock, TextSpanfrom mineru.version import __version__from typer.testing import CliRunner@@ -410,6 +411,60 @@ def test_api_client_upload_auth_is_limited_to_same_origin() -> None:assert "Authorization" not in external+def test_gradio_ocr_reaches_analysis_through_real_v1_jobs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """贯通 UI、上传、V1 任务与统一解析器,仅替换分析推理并检查连续请求之间的模式隔离。"""+ from mineru.parser import mineru_parser++ source = tmp_path / "report.PDF"+ source.write_bytes(_pdf_bytes())+ received_modes: list[str] = []++ async def fake_analyze(file_bytes: bytes, **kwargs: Any) -> tuple[MiddleJson, ModelJson]:+ """记录真正传入分析层的模式,并生成与模式一致的严格结果和模型输出。"""+ assert file_bytes.startswith(b"%PDF")+ received_modes.append(kwargs["parse_mode"])+ middle = _middle_json(with_image=False)+ middle.parse_mode = "ocr" if kwargs["parse_mode"] == "ocr" else "txt"+ model = ModelJson(+ pages=[[]],+ page_index_map=[],+ file_suffix="pdf",+ effort="flash",+ parse_mode=middle.parse_mode,+ mineru_version=__version__,+ )+ return middle, model++ monkeypatch.setattr(mineru_parser, "aio_doc_analyze", fake_analyze)+ api = parser_api_server.create_app(upload_dir=str(tmp_path / "api"), tier="flash")+ with TestClient(api, base_url="http://testserver") as test_client:+ request_log: list[tuple[str, str, str | None]] = []+ proxy = _httpx_proxy_for_test_client(test_client, request_log)+ monkeypatch.setattr(gradio_client, "httpx", proxy)+ monkeypatch.setattr(parser_api_client, "httpx", proxy)+ client = V1ArtifactClient(api_url="http://testserver")++ async def convert_requests() -> None:+ """同一 Gradio 实例依次强制、自动、强制解析,再通过缺省 SDK 请求验证默认模式。"""+ capabilities = await client.discover()+ demo = build_gradio_app(client, capabilities, output_root=tmp_path / "output", enable_example=False)+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")+ for enabled in (True, False, True):+ updates = [update async for update in handler(str(source), 0, "", enabled)]+ state = updates[-1][8]+ assert state is not None, updates[-1][0]+ payload = json.loads(Path(state["middle_json_path"]).read_text())+ assert payload["parse_mode"] == ("ocr" if enabled else "txt")+ default_parser = parser_api_client.MinerUApiParser(api_url="http://testserver", tier="flash")+ result = await default_parser.parse_async(source)+ assert result.middle_json.parse_mode == "txt"++ asyncio.run(convert_requests())+ assert not hasattr(api.state, "ocr_mode")+ assert received_modes == ["ocr", "auto", "ocr", "auto"]+ assert sum(method == "POST" and path == "/v1/parse/jobs" for method, path, _ in request_log) == 4++def test_v1_client_preserves_v1_error_code(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:"""验证 V1 error envelope 会保留错误码并清晰传给 UI。"""source = tmp_path / "demo.pdf"@@ -421,7 +476,7 @@ def test_v1_client_preserves_v1_error_code(monkeypatch: pytest.MonkeyPatch, tmp_def __init__(self, **_kwargs: Any) -> None:"""忽略构造参数。"""- async def parse_async(self, _path: Path, *, page_range: str) -> ParseResult:+ async def parse_async(self, _path: Path, *, page_range: str, status_callback: Any = None) -> ParseResult:"""抛出与正式 API client 一致的错误形态。"""error = RuntimeError(f"bad range: {page_range}")error.code = "page_range_invalid" # type: ignore[attr-defined]@@ -435,7 +490,8 @@ def test_v1_client_preserves_v1_error_code(monkeypatch: pytest.MonkeyPatch, tmp_assert error.value.code == "page_range_invalid"-def test_v1_client_parse_uses_api_parser_zip_contract(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:[email protected]("ocr_mode", ["auto", "txt", "ocr"])+def test_v1_client_parse_uses_api_parser_zip_contract(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ocr_mode: str) -> None:"""验证 Gradio client 固定请求带图片和模型输出的 V1 ZIP 结果。"""source = tmp_path / "demo.pdf"source.write_bytes(_pdf_bytes())@@ -448,10 +504,16 @@ def test_v1_client_parse_uses_api_parser_zip_contract(monkeypatch: pytest.Monkey"""保存构造参数,供断言 V1 ZIP 契约。"""calls.update(kwargs)- async def parse_async(self, path: Path, *, page_range: str) -> ParseResult:+ async def parse_async(self, path: Path, *, page_range: str, status_callback: Any = None) -> ParseResult:"""返回最小解析结果。"""calls["path"] = pathcalls["page_range"] = page_range+ assert statuses == ["Preparing request...", "Submitting task..."]+ assert status_callback is not None+ status_callback("queued")+ status_callback("running")+ status_callback("completed")+ assert statuses[-1] == STATUS_DOWNLOADING_RESULTreturn ParseResult(middle_json=_middle_json(with_image=False))monkeypatch.setattr("mineru.kit.gradio.client.MinerUApiParser", FakeParser)@@ -463,14 +525,18 @@ def test_v1_client_parse_uses_api_parser_zip_contract(monkeypatch: pytest.Monkey("file_id",),)statuses: list[str] = []- result = asyncio.run(client.parse_file(source, tier="standard", page_range="1-2", status_callback=statuses.append))+ result = asyncio.run(+ client.parse_file(source, tier="standard", page_range="1-2", ocr_mode=ocr_mode, status_callback=statuses.append)+ )assert isinstance(result, ParseResult)assert calls["include_images"] is Trueassert calls["include_model_output"] is Trueassert calls["tier"] == "standard"+ assert calls["ocr_mode"] == ocr_modeassert calls["page_range"] == "1-2"assert statuses[0] == "Preparing request..."assert statuses[-1] == STATUS_DOWNLOADING_RESULT+ assert statuses[2:4] == ["Queued on server", "Processing on server..."]def test_managed_local_api_command_uses_kit_entrypoint() -> None:@@ -480,7 +546,6 @@ def test_managed_local_api_command_uses_kit_entrypoint() -> None:no_flash=True,concurrency=3,language="en",- ocr_mode="ocr",disable_image_analysis=True,preload_models=True,api_key="secret",@@ -490,7 +555,12 @@ def test_managed_local_api_command_uses_kit_entrypoint() -> None:assert "--tier" in command and command[command.index("--tier") + 1] == "standard"assert "--no-flash" in commandassert "--preload-models" in command+ assert "--ocr-mode" not in commandassert command[command.index("--api-key") + 1] == "secret"+ with pytest.raises(TypeError, match="ocr_mode"):+ ManagedLocalApiServer(ocr_mode="ocr") # type: ignore[call-arg]+ with pytest.raises(TypeError, match="api_server_ocr_mode"):+ gradio_app.launch_gradio(api_server_ocr_mode="ocr") # type: ignore[call-arg]def test_managed_local_api_server_cleans_process_control_and_temp_dir(@@ -739,6 +809,48 @@ def test_gradio_file_types_page_range_and_header_follow_new_contract(tmp_path: Passert "{{HEADER_" not in header+def test_gradio_ocr_control_visibility_reset_and_event_binding(tmp_path: Path) -> None:+ """验证 PDF 专属开关的缺省值、文件重置、清除绑定和独立于 tier 的可见性。"""+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash", "standard"), ("zip",), ("file_id",))+ demo = build_gradio_app(Mock(), capabilities, output_root=tmp_path, enable_example=False)+ checkbox = next(block for block in demo.blocks.values() if block.__class__.__name__ == "Checkbox")+ assert checkbox.label == "强制 OCR" and checkbox.value is False and checkbox.visible is False+ update = next(fn for fn in demo.fns.values() if fn.name == "update_ocr_control")+ assert len(update.inputs) == 1 and update.inputs[0].__class__.__name__ == "File"+ for path, visible in (("first.pdf", True), ("second.PDF", True), ("photo.png", False), ("book.docx", False), (None, False)):+ assert update.fn(path) == {"__type__": "update", "value": False, "visible": visible}+ convert = next(fn for fn in demo.fns.values() if fn.name == "convert_handler")+ assert convert.inputs[-1] is checkbox+ slider = next(block for block in demo.blocks.values() if "mineru-tier-slider" in (block.elem_classes or []))+ clear = next(block for block in demo.blocks.values() if block.__class__.__name__ == "ClearButton")+ events = demo.config["dependencies"]+ assert all(checkbox._id not in event["outputs"] for event in events if (slider._id, "input") in event["targets"])+ assert any(checkbox._id in event["outputs"] for event in events if (clear._id, "click") in event["targets"])+ change = next(event for event in events if event["id"] == update._id)+ assert change["queue"] is False and change["trigger_mode"] == "always_last"++[email protected]("suffix", [".png", ".docx", ".csv"])+def test_gradio_non_pdf_ignores_hidden_force_ocr(tmp_path: Path, suffix: str) -> None:+ """直接调用事件并传入残留 True,非 PDF 请求仍使用 auto。"""+ source = tmp_path / f"source{suffix}"+ source.write_bytes(b"placeholder")+ client = SimpleNamespace(parse_file=AsyncMock(side_effect=V1ArtifactError("stop after request")))+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",))+ demo = build_gradio_app(client, capabilities, output_root=tmp_path / "output", enable_example=False)+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")++ async def convert() -> None:+ """消费完整转换事件,以等待参数进入 client。"""+ updates = [update async for update in handler(str(source), 0, "1-3", True)]+ assert "stop after request" in updates[-1][0]++ asyncio.run(convert())+ client.parse_file.assert_awaited_once()+ assert client.parse_file.call_args.kwargs["ocr_mode"] == "auto"+ assert client.parse_file.call_args.kwargs["page_range"] == ""++def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -> None:"""验证新 UI 不引入旧 backend 控件,并注册三个标签和下载事件。"""capabilities = V1ServerCapabilities(@@ -822,8 +934,9 @@ def test_gradio_tier_slider_uses_available_tiers_and_preserves_selection((("flash",), 0, "flash"),],)[email protected]("force_ocr", [False, True])def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(- tmp_path: Path, tiers: tuple[str, ...], position: int, expected_tier: str+ tmp_path: Path, tiers: tuple[str, ...], position: int, expected_tier: str, force_ocr: bool) -> None:"""验证滑块位置映射与 PDF page_range 透传,并只在新结果完成后启用下载。"""source = tmp_path / "demo.pdf"@@ -842,17 +955,19 @@ def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(*,tier: str,page_range: str,+ ocr_mode: str = "auto",status_callback: Any = None,) -> ParseResult:"""返回最小解析结果并记录页码。"""self.calls.append((path, tier, page_range))+ assert ocr_mode == ("ocr" if force_ocr else "auto")if status_callback is not None:status_callback("Processing on server...")return ParseResult(middle_json=_middle_json(with_image=False))async def collect_updates(handler: Any) -> list[tuple[Any, ...]]:"""收集 Gradio 异步生成器的全部增量输出。"""- return [update async for update in handler(str(source), position, " 1 ")]+ return [update async for update in handler(str(source), position, " 1 ", force_ocr)]capabilities = V1ServerCapabilities("http://127.0.0.1:1", tiers, ("zip",), ("file_id",))client = FakeClient()@@ -933,3 +1048,119 @@ def test_gradio_conversion_failure_clears_previous_downloads(tmp_path: Path) ->assert "Failed: boom" in update[0]assert update[8] is Noneassert all(item["interactive"] is False and item["value"] is None for item in update[-6:])++[email protected]("explicit_session_cancel", [False, True])+def test_gradio_local_queue_cancellation_releases_slot_and_keeps_sessions_isolated(+ tmp_path: Path, explicit_session_cancel: bool+) -> None:+ """验证等待和运行中的生成器被关闭后释放任务槽,其他会话仍能完成自己的结果。"""+ sources = [tmp_path / f"session-{index}.csv" for index in range(3)]+ for source in sources:+ source.write_text("name,value\na,1\n", encoding="utf-8")++ async def scenario() -> None:+ """模拟两个会话取消后由第三个会话接续执行,不依赖真实服务等待。"""+ finish = asyncio.Event()+ calls: list[Path] = []+ canceled: list[Path] = []++ class WaitingClient:+ """按测试事件控制解析完成时机。"""++ async def parse_file(self, path: Path, *, status_callback: Any, **_kwargs: Any) -> ParseResult:+ """记录实际进入任务槽的会话,并传播本地取消。"""+ calls.append(path)+ status_callback("Processing on server...")+ try:+ await finish.wait()+ except asyncio.CancelledError:+ canceled.append(path)+ raise+ status_callback(STATUS_DOWNLOADING_RESULT)+ return ParseResult(middle_json=_middle_json(with_image=False))++ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",))+ demo = build_gradio_app(WaitingClient(), capabilities, output_root=tmp_path / "output", enable_example=False)+ handler_fn = next(fn for fn in demo.fns.values() if fn.name == "convert_handler")+ assert handler_fn.concurrency_limit is None+ # 清除和文件切换都使用 Gradio 的会话级取消事件。+ cancellation_events = [dependency for dependency in demo.config["dependencies"] if dependency["cancels"]]+ assert len(cancellation_events) >= 2+ assert all(handler_fn._id in dependency["cancels"] for dependency in cancellation_events)++ async def advance_until(stream: Any, marker: str) -> tuple[Any, ...]:+ """推进生成器直到目标阶段,并给测试死锁设置明确超时。"""+ while True:+ update = await asyncio.wait_for(anext(stream), timeout=2)+ if marker in update[0]:+ return update++ requests = [SimpleNamespace(session_hash=f"session-{index}") for index in range(3)]+ first, second, third = [+ handler_fn.fn(str(source), 0, "", request=request) for source, request in zip(sources, requests)+ ]+ cancel_session = next(fn.fn for fn in demo.fns.values() if fn.name == "cancel_session_conversion")+ await advance_until(first, "Processing on server")+ queued = await advance_until(second, "Queued locally.")+ assert all(value == {"__type__": "update"} for value in queued[1:])+ assert calls == [sources[0]]+ if explicit_session_cancel:+ await cancel_session(requests[1])+ with pytest.raises(StopAsyncIteration):+ await anext(second)+ else:+ await second.aclose()+ await advance_until(third, "Queued locally.")+ if explicit_session_cancel:+ await cancel_session(requests[0])+ with pytest.raises(StopAsyncIteration):+ await anext(first)+ else:+ await first.aclose()+ await advance_until(third, "Processing on server")+ assert canceled == [sources[0]]+ assert calls == [sources[0], sources[2]]+ finish.set()+ updates = [update async for update in third]+ final = updates[-1]+ assert "Completed (" in final[0]+ assert final[8]["stem"] == sources[2].stem+ assert all(item["interactive"] is True for item in final[-6:])++ asyncio.run(scenario())+++def test_gradio_output_failure_stops_timer_and_allows_next_conversion(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """验证解析完成后的输出整理错误仍显示失败,并释放槽位供下一次转换使用。"""+ source = tmp_path / "source.csv"+ source.write_text("name,value\na,1\n", encoding="utf-8")++ class CompletedClient:+ """模拟已完成远端解析和下载的任务。"""++ async def parse_file(self, _path: Path, *, status_callback: Any, **_kwargs: Any) -> ParseResult:+ """按真实阶段通知后返回解析结果。"""+ status_callback("Processing on server...")+ status_callback(STATUS_DOWNLOADING_RESULT)+ return ParseResult(middle_json=_middle_json(with_image=False))++ def fail_persistence(*_args: Any, **_kwargs: Any) -> Any:+ """模拟产物磁盘写入失败。"""+ raise OSError("output disk unavailable")++ monkeypatch.setattr(gradio_app, "persist_parse_result", fail_persistence)+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",))+ demo = build_gradio_app(CompletedClient(), capabilities, output_root=tmp_path, enable_example=False)+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")++ async def scenario() -> None:+ """连续运行两次,验证异常分支没有泄漏执行槽。"""+ for _ in range(2):+ updates = [update async for update in handler(str(source), 0, "")]+ assert "Failed: output disk unavailable" in updates[-1][0]+ assert "is-error" in updates[-1][0]+ assert updates[-1][8] is None+ assert all(item["interactive"] is False for item in updates[-1][-6:])++ asyncio.run(scenario())diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.pyindex c7bc563f..e139c0ab 100644--- a/tests/unittest/test_kit_gradio_page_range.py+++ b/tests/unittest/test_kit_gradio_page_range.py@@ -83,7 +83,6 @@ def test_launch_forwards_limit_and_versioned_assets(monkeypatch: pytest.MonkeyPaapi_server_no_flash=False,api_server_concurrency=1,api_server_language="ch",- api_server_ocr_mode="auto",api_server_disable_image_analysis=False,api_server_preload_models=False,max_pages=20,@@ -201,7 +200,7 @@ def test_metadata_does_not_read_non_pdf(monkeypatch: pytest.MonkeyPatch) -> Nonedef test_native_range_components_and_frontend_only_events(tmp_path: Path) -> None:- """双滑块使用原生组件,联动与档位切换不请求 Python,公开转换输入仍为三项。"""+ """双滑块联动与档位切换不请求 Python,公开转换输入在页码之后增加 OCR 开关。"""capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash", "standard"), ("zip",), ("file_id",))demo = gradio_app.build_gradio_app(Mock(), capabilities, output_root=tmp_path, max_pages=20, enable_example=False)sliders = [block for block in demo.blocks.values() if block.__class__.__name__ == "Slider"]@@ -216,8 +215,9 @@ def test_native_range_components_and_frontend_only_events(tmp_path: Path) -> Nonassert len(events[0]["targets"]) == 5assert events[0]["outputs"][:2] == [sliders[1]._id, sliders[2]._id]handler = next(fn for fn in demo.fns.values() if fn.name == "convert_handler")- assert len(handler.inputs) == 3+ assert len(handler.inputs) == 4assert handler.inputs[2].__class__.__name__ == "Textbox" and handler.inputs[2].visible is False+ assert handler.inputs[3].__class__.__name__ == "Checkbox" and handler.inputs[3].value is Falsemetadata_handler = next(fn for fn in demo.fns.values() if fn.name == "read_page_metadata")assert metadata_handler.outputs[0].__class__.__name__ == "Textbox"metadata = json.loads(metadata_handler.fn(str(_pdf(tmp_path, 12))))diff --git a/tests/unittest/test_kit_gradio_status.py b/tests/unittest/test_kit_gradio_status.pynew file mode 100644index 00000000..4ac9a0ab--- /dev/null+++ b/tests/unittest/test_kit_gradio_status.py@@ -0,0 +1,106 @@+"""步骤卡片的计时、状态生命周期与安全文本回归。"""++import asyncio+from contextlib import aclosing++import pytest++from mineru.kit.gradio.status import (+ STATUS_COMPLETED,+ STATUS_DOWNLOADING_RESULT,+ STATUS_PROCESSING_ON_SERVER,+ STATUS_PROCESSING_OUTPUT,+ STATUS_QUEUED_LOCALLY,+ STATUS_QUEUED_ON_SERVER,+ StatusPanelState,+ status_html,+ stream_status_updates,+)+++def test_processing_clock_excludes_queue_and_download_and_keeps_completed_duration() -> None:+ """模拟长时间排队和下载,确保完成耗时仅保留两次真实运行通知之间的时间。"""+ now = [0.0]+ state = StatusPanelState(clock=lambda: now[0])+ state.append(STATUS_QUEUED_ON_SERVER)+ now[0] = 100.0+ state.append(STATUS_PROCESSING_ON_SERVER)+ assert state.refresh_interval == 0.1+ now[0] = 101.2+ assert "Processing on server (1.2s)" in state.render()+ assert not state.append(STATUS_PROCESSING_ON_SERVER)+ now[0] = 104.6+ state.append(STATUS_DOWNLOADING_RESULT, at=104.5)+ assert state.refresh_interval is None+ assert state.processing_elapsed == pytest.approx(4.5)+ assert "status-step is-active" in state.render()+ assert state.render().count("status-step is-done") == 5+ now[0] = 200.0+ state.append(STATUS_PROCESSING_OUTPUT)+ state.append(STATUS_COMPLETED)+ assert "Completed (4.5s)" in state.render()+ assert state.render().count("status-step is-done") == 8++[email protected]("message", [STATUS_QUEUED_LOCALLY, STATUS_QUEUED_ON_SERVER])+def test_queue_animation_cycles_without_restarting_on_repeated_status(message: str) -> None:+ """验证本地和远端队列都按每秒一个圆点循环,重复轮询不重置动画。"""+ now = [5.0]+ state = StatusPanelState(clock=lambda: now[0])+ state.append(message)+ assert state.refresh_interval == 1.0+ for seconds, dots in [(0, 1), (3, 4), (9, 10), (10, 1)]:+ now[0] = 5.0 + seconds+ assert not state.append(message)+ assert f'<div class="status-latest">{message}{"." * dots}</div>' in state.render()+++def test_fast_completion_has_no_invented_elapsed_time_and_reset_has_eight_pending_steps() -> None:+ """验证没有观察到运行的任务不显示零秒耗时,重置后保留完整双语步骤。"""+ state = StatusPanelState()+ state.append(STATUS_QUEUED_ON_SERVER)+ state.append(STATUS_DOWNLOADING_RESULT)+ state.append(STATUS_COMPLETED)+ assert '<div class="status-latest">Completed</div>' in state.render()+ idle = status_html()+ assert idle.count("status-step is-pending") == 8+ assert 'data-mineru-i18n-en="Waiting"' in idle+ assert 'data-mineru-i18n-zh="排队"' in idle+ assert "status-steps-panel" in idle++[email protected]("error", ["server task failed", "server task canceled", '<script>alert("x")</script>'])+def test_failure_stops_timer_and_renders_escaped_error(error: str) -> None:+ """验证失败或取消停止计时,并使用红色失败节点展示转义后的消息。"""+ state = StatusPanelState(clock=lambda: 10.0)+ state.append(STATUS_PROCESSING_ON_SERVER, at=1.0)+ state.append(f"Failed: {error}", at=3.0)+ rendered = state.render()+ assert state.processing_elapsed == 2.0+ assert state.refresh_interval is None+ assert "status-step is-active is-error" in rendered+ assert 'data-mineru-i18n-en="Failed"' in rendered+ assert "<script>" not in rendered+++def test_status_stream_ticks_while_job_waits_and_cleans_up_waiter() -> None:+ """验证无网络通知时仍刷新本地时钟,关闭流后不残留队列等待任务。"""++ async def scenario() -> None:+ """运行可手动推进时钟的解析等待场景。"""+ now = [1.0]+ state = StatusPanelState(clock=lambda: now[0])+ events: asyncio.Queue[tuple[str, float]] = asyncio.Queue()+ events.put_nowait((STATUS_PROCESSING_ON_SERVER, 1.0))+ task = asyncio.create_task(asyncio.Event().wait())+ baseline = set(asyncio.all_tasks())+ async with aclosing(stream_status_updates(task, events, state)) as stream:+ assert "(0.0s)" in await anext(stream)+ now[0] = 2.3+ assert "(1.3s)" in await asyncio.wait_for(anext(stream), timeout=1)+ assert set(asyncio.all_tasks()) == baseline+ assert set(asyncio.all_tasks()) == baseline+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ asyncio.run(scenario())diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 2c8d0227..7a6727cf 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -1442,9 +1442,11 @@ def test_api_client_omits_tier_when_unspecified(tmp_path: Path) -> None:assert "tier" not in payload-def test_api_client_constructor_does_not_expose_ocr_or_image_options() -> None:+def test_api_client_constructor_exposes_request_ocr_without_legacy_options() -> None:+ """验证 OCR 使用显式请求参数,且不恢复旧 method 或图片分析选项。"""parameters = inspect.signature(MinerUApiParser).parameters+ assert parameters["ocr_mode"].default is Noneassert "method" not in parametersassert "image_analysis" not in parameters@@ -1796,7 +1798,7 @@ def test_create_app_does_not_read_runtime_settings_from_env(tmp_path: Path, monkassert app.state.max_inline_bytes == 1024 * 1024assert app.state.allow_http_source is Falseassert app.state.language == "ch"- assert app.state.ocr_mode == "auto"+ assert not hasattr(app.state, "ocr_mode")assert app.state.effort == "high"assert app.state.image_analysis is Trueassert not hasattr(app.state, _REMOVED_TABLE_ENABLE_PARAM)@@ -1900,7 +1902,6 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(rec,request,file_store,- ocr_mode="auto",image_analysis=True,allow_local_source=True,)@@ -1939,7 +1940,6 @@ def test_api_server_run_job_normalizes_lightweight_file_tier_to_flash(rec,request,file_store,- ocr_mode="auto",image_analysis=True,allow_local_source=True,)@@ -2072,7 +2072,6 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(rec,request,file_store,- ocr_mode="auto",image_analysis=True,allow_local_source=True,)@@ -2121,7 +2120,6 @@ def test_api_server_zip_rejects_unsafe_image_sidecar_path(rec,request,file_store,- ocr_mode="auto",image_analysis=True,allow_local_source=True,)@@ -2163,7 +2161,6 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(rec,request,file_store,- ocr_mode="auto",image_analysis=True,allow_local_source=True,)@@ -2209,7 +2206,6 @@ def test_api_server_logs_traceback_when_job_file_fails(rec,request,file_store,- ocr_mode="auto",image_analysis=True,allow_local_source=True,)@@ -2427,7 +2423,6 @@ def test_api_server_standard_jobs_use_requested_tier(tmp_path: Path, monkeypatchrec,request,file_store,- ocr_mode=app.state.ocr_mode,image_analysis=app.state.image_analysis,allow_local_source=app.state.allow_local_source,max_inline_bytes=app.state.max_inline_bytes,@@ -2629,12 +2624,11 @@ def test_api_server_stores_parser_runtime_options(tmp_path: Path, monkeypatch: pupload_dir=str(tmp_path),tier="basic",language="en",- ocr_mode="ocr",image_analysis=False,)assert app.state.language == "ch"- assert app.state.ocr_mode == "ocr"+ assert not hasattr(app.state, "ocr_mode")assert app.state.effort == "medium"assert app.state.image_analysis is Falseassert not hasattr(app.state, _REMOVED_TABLE_ENABLE_PARAM)@@ -2652,7 +2646,7 @@ def test_api_server_cli_exposes_parser_runtime_options() -> None:assert "--tier" in option_namesassert "--backend" not in option_namesassert "--language" in option_names- assert "--ocr-mode" in option_names+ assert "--ocr-mode" not in option_namesassert "--allow-local-source" in option_namesassert "--max-inline-bytes" in option_namesassert "--allow-http-source" in option_namesdiff --git a/tests/unittest/test_parser_api_ocr.py b/tests/unittest/test_parser_api_ocr.pynew file mode 100644index 00000000..153d2e5c--- /dev/null+++ b/tests/unittest/test_parser_api_ocr.py@@ -0,0 +1,108 @@+"""V1 请求级 OCR 参数、输入校验与服务启动配置退役回归。"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from typing import Any, Literal+from unittest.mock import AsyncMock, Mock++import httpx+import pytest+from click.testing import CliRunner+from fastapi.testclient import TestClient++from mineru.parser import api_client, api_server+from mineru.parser.api_client import MinerUApiParser++[email protected]("use_async", [False, True])[email protected]("ocr_mode", [None, "auto", "txt", "ocr"])+def test_api_parser_serializes_request_ocr_mode(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ use_async: bool,+ ocr_mode: Literal["auto", "txt", "ocr"] | None,+) -> None:+ """通过正式 HTTP 提交流程检查两个入口的显式模式与缺省字段。"""+ source = tmp_path / "demo.pdf"+ source.write_bytes(b"%PDF-1.7\n")+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="flash", ocr_mode=ocr_mode)+ parser._source_features = {"local"}+ payloads: list[dict[str, Any]] = []++ def respond(request: httpx.Request) -> httpx.Response:+ """记录完整任务请求,在产物下载前返回已完成任务。"""+ assert request.method == "POST" and request.url.path == "/v1/parse/jobs"+ payloads.append(json.loads(request.content))+ return httpx.Response(202, json={"job_id": "job_test", "status": "completed"})++ transport = httpx.MockTransport(respond)+ sync_client, async_client = httpx.Client, httpx.AsyncClient++ def create_sync_client(**kwargs: Any) -> httpx.Client:+ """向同步传输注入请求记录器,避免访问真实网络。"""+ return sync_client(transport=transport, **kwargs)++ def create_async_client(**kwargs: Any) -> httpx.AsyncClient:+ """向异步传输注入同一个请求记录器。"""+ return async_client(transport=transport, **kwargs)++ monkeypatch.setattr(api_client.httpx, "Client", create_sync_client)+ monkeypatch.setattr(api_client.httpx, "AsyncClient", create_async_client)+ monkeypatch.setattr(parser, "_build_result", Mock())+ monkeypatch.setattr(parser, "_async_build_result", AsyncMock())+ if use_async:+ asyncio.run(parser.parse_async(source, page_range="1"))+ else:+ parser.parse(source, page_range="1")++ expected: dict[str, Any] = {+ "files": [{"source": {"type": "local", "path": str(source)}, "page_range": "1"}],+ "tier": "flash",+ "output_formats": ["middle_json"],+ }+ if ocr_mode is not None:+ expected["ocr_mode"] = ocr_mode+ assert payloads == [expected]++[email protected]("value", ["", "forced", True, 1, {}])+def test_api_parser_rejects_invalid_ocr_mode(value: object) -> None:+ """在上传之前拒绝不属于公开模式集合的配置。"""+ with pytest.raises(ValueError, match="Unsupported OCR mode"):+ MinerUApiParser(ocr_mode=value) # type: ignore[arg-type]++[email protected]("value", [None, "", "forced", True, 1, {}])+def test_api_server_rejects_invalid_request_ocr_mode(tmp_path: Path, value: object) -> None:+ """非法模式统一返回带参数定位的 HTTP 400,且不会创建任务。"""+ app = api_server.create_app(upload_dir=str(tmp_path), tier="flash")+ with TestClient(app) as client:+ response = client.post(+ "/v1/parse/jobs",+ json={+ "files": [{"source": {"type": "inline", "name": "demo.pdf", "data": "JVBERi0xLjcK"}}],+ "ocr_mode": value,+ },+ )+ assert response.status_code == 400+ assert response.json()["error"]["code"] == "invalid_request"+ assert response.json()["error"]["param"] == "ocr_mode"+ assert app.state.job_store._jobs == {}+++def test_api_server_ocr_defaults_to_request_auto_without_startup_configuration(tmp_path: Path) -> None:+ """请求缺省值固定为 auto,应用生命周期不保存全局 OCR 模式。"""+ request = api_server.CreateJobRequest.model_validate({"files": [{"source": {"type": "local", "path": "/tmp/demo.pdf"}}]})+ assert request.ocr_mode == "auto"+ app = api_server.create_app(upload_dir=str(tmp_path), tier="flash")+ assert not hasattr(app.state, "ocr_mode")+ with TestClient(app):+ assert not hasattr(app.state, "ocr_mode")+ with pytest.raises(TypeError, match="ocr_mode"):+ api_server.create_app(ocr_mode="ocr") # type: ignore[call-arg]+ result = CliRunner().invoke(api_server.main, ["--ocr-mode", "ocr"])+ assert result.exit_code != 0+ assert "No such option: --ocr-mode" in result.outputdiff --git a/tests/unittest/test_parser_api_status.py b/tests/unittest/test_parser_api_status.pynew file mode 100644index 00000000..fad99a9a--- /dev/null+++ b/tests/unittest/test_parser_api_status.py@@ -0,0 +1,108 @@+"""同步和异步 V1 parser 的状态观察回调合同。"""++import asyncio+from pathlib import Path+from typing import Any++import httpx+import pytest++from mineru.parser import ApiJobStatus, MinerUApiParser, ParseResult+from mineru.parser import api_client+from mineru.types import MiddleJson++[email protected]("use_async", [False, True])[email protected]("callback_raises", [False, True])+ "statuses",+ [+ ("queued", "running", "running", "completed"),+ ("completed",),+ ("queued", "partial"),+ ("queued", "running", "failed"),+ ("queued", "canceled"),+ ],+)+def test_parse_notifies_submission_and_polls_before_result_building(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ use_async: bool,+ callback_raises: bool,+ statuses: tuple[ApiJobStatus, ...],+) -> None:+ """验证六种真实状态、固定轮询、直接完成和回调异常隔离,通知不延迟到结果下载之后。"""+ source = tmp_path / "source.pdf"+ source.write_bytes(b"%PDF-1.7\n")+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="flash")+ parser._source_features = {"local"}+ notifications: list[ApiJobStatus] = []+ delays: list[float] = []+ replies = iter(statuses)+ methods: list[str] = []+ result = ParseResult(+ middle_json=MiddleJson(+ pages=[], is_full_document=True, file_suffix="pdf", effort="flash", parse_mode="txt", mineru_version="4.0.0"+ )+ )++ def respond(request: httpx.Request) -> httpx.Response:+ """只模拟创建和轮询任务,保留正式 HTTP 调用及状态传播路径。"""+ methods.append(request.method)+ return httpx.Response(200, json={"job_id": "job_test", "status": next(replies)})++ transport = httpx.MockTransport(respond)+ sync_client, async_client = httpx.Client, httpx.AsyncClient++ def create_sync_client(**kwargs: Any) -> httpx.Client:+ """注入同步 HTTP transport,禁止测试访问真实服务。"""+ return sync_client(transport=transport, **kwargs)++ def create_async_client(**kwargs: Any) -> httpx.AsyncClient:+ """注入异步 HTTP transport,禁止测试访问真实服务。"""+ return async_client(transport=transport, **kwargs)++ async def sleep_async(delay: float) -> None:+ """记录轮询间隔而不真实等待。"""+ delays.append(delay)++ def on_status(status: ApiJobStatus) -> None:+ """记录本次调用的状态,按参数模拟不可靠的观察者。"""+ notifications.append(status)+ if callback_raises:+ raise RuntimeError("observer failed")++ def build_result(job: dict[str, Any], file_name: str) -> ParseResult:+ """确认所有状态在开始下载/构建结果之前已经通知。"""+ assert notifications == list(statuses)+ assert file_name == source.name+ api_client._raise_for_terminal_job_error(job)+ return result++ async def build_result_async(job: dict[str, Any], file_name: str) -> ParseResult:+ """为异步解析复用相同的终态和通知时序断言。"""+ return build_result(job, file_name)++ monkeypatch.setattr(httpx, "Client", create_sync_client)+ monkeypatch.setattr(httpx, "AsyncClient", create_async_client)+ monkeypatch.setattr(api_client.time, "sleep", delays.append)+ monkeypatch.setattr(api_client.asyncio, "sleep", sleep_async)+ monkeypatch.setattr(parser, "_build_result", build_result)+ monkeypatch.setattr(parser, "_async_build_result", build_result_async)++ def parse() -> ParseResult:+ """统一执行两个公共入口,确保回调参数一路透传。"""+ if use_async:+ return asyncio.run(parser.parse_async(source, status_callback=on_status))+ return parser.parse(source, status_callback=on_status)++ if statuses[-1] in ("failed", "canceled"):+ with pytest.raises(Exception, match=f"ended with status {statuses[-1]}"):+ parse()+ else:+ assert parse() is result+ assert notifications == list(statuses)+ assert methods == ["POST", *(["GET"] * (len(statuses) - 1))]+ assert delays == [1] * (len(statuses) - 1)+ assert ("Parse job status callback failed" in caplog.text) is callback_raisesdiff --git a/tests/unittest/test_pdf_page_id.py b/tests/unittest/test_pdf_page_id.pyindex 70611a5e..7130dc1e 100644--- a/tests/unittest/test_pdf_page_id.py+++ b/tests/unittest/test_pdf_page_id.py@@ -259,7 +259,7 @@ def test_async_job_resolves_relative_ranges_and_reports_file_errors(tmp_path: Pa})record = api_server.JobStore().create(request, store)- asyncio.run(api_server._run_job(record, request, store, ocr_mode="auto", image_analysis=True, allow_local_source=True))+ asyncio.run(api_server._run_job(record, request, store, image_analysis=True, allow_local_source=True))assert record.status == "partial"assert record.files[0].page_range == "1,4-5"assert record.files[0].status == "completed"