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(gradio): require 6.21 and simplify event chains
myhloli412d2c9b866d
diff --git a/docs/next/cli/mineru-kit-vlm-server.md b/docs/next/cli/mineru-kit-vlm-server.mdindex 0344accf..d3d69935 100644--- a/docs/next/cli/mineru-kit-vlm-server.md+++ b/docs/next/cli/mineru-kit-vlm-server.md@@ -124,7 +124,7 @@ Qwen 模型通过 mineru-vl-utils 的公开路径准备接口生成独立兼容原始配置和权重不变,临时目录在服务退出后清理。MLX server 不修改上游函数。Gradio 已包含在 MinerU 基础包;手动添加 MLX 时请同时解析 `mineru` 与 `mlx-vlm>=0.7.0,<0.8.0`。-mlx-vlm 0.7.0 要求 Starlette 1.x,Gradio 6.8.0 与其不兼容;本次验收使用 Gradio 6.26.0。+mlx-vlm 0.7.0 要求 Starlette 1.x,与当前 `gradio>=6.21,<7` 的依赖范围兼容;此前验收使用 Gradio 6.26.0。## 8. 推理服务与 Parse API 的接口区别diff --git a/docs/next/cli/mineru-kit-webui.md b/docs/next/cli/mineru-kit-webui.mdindex 1a3acbd6..c1c38261 100644--- a/docs/next/cli/mineru-kit-webui.md+++ b/docs/next/cli/mineru-kit-webui.md@@ -6,7 +6,7 @@## PDF 预览与版本要求-Gradio 界面要求 `gradio>=6.8,<7`,不再支持 Gradio 5,也不再需要安装 `gradio-pdf`。+Gradio 界面要求 `gradio>=6.21,<7`,使用 6.21 修复后的纯前端事件链式触发,不再需要安装 `gradio-pdf`。PDF 预览使用独立 iframe 和随 MinerU 分发的 PDF.js 6.3.289,支持连续阅读、翻页、页码跳转、缩放和适应宽度。核心模块、worker、CMap、标准字体及解码资源均从当前 Gradio 站点加载,预览无需外部 CDN 或 npm。@@ -15,9 +15,9 @@ PDF 预览使用独立 iframe 和随 MinerU 分发的 PDF.js 6.3.289,支持连需要密码或损坏的 PDF 会显示预览错误。文字搜索、编辑、打印和缩略图不在当前预览功能范围内。静态资源和文件沿用 Gradio 的认证与文件路由,支持反向代理子路径;自定义挂载仍需传入自己的结果目录 `allowed_paths`。-Gradio 6.26 的 `huggingface-hub>=1.16` 与当前 Transformers 4 的依赖范围不兼容。-使用最新 Gradio 时,将 UI 安装在独立环境,通过 `--api-url` 连接推理服务;与本地模型同环境安装时,-让依赖解析器选择兼容的 Gradio 6.x,当前相关约束可解析到 6.17.3,无需升级 Transformers。+Gradio 6.21 要求 `starlette>=1.0.1,<2` 和 `huggingface-hub>=1.16,<2`,与当前 MinerU 的 Transformers 5 依赖范围兼容。+安装时让依赖解析器同时处理 MinerU 和推理后端,无需为 WebUI 单独提高 Transformers、vLLM 或 LMDeploy 的下限。+UI 也可安装在独立环境,通过 `--api-url` 连接推理服务。维护预览资源时执行 `python scripts/vendor_pdfjs.py`,脚本会校验固定上游压缩包并生成逐文件 SHA-256 清单。构建后使用 `python scripts/verify_pdfjs_distribution.py dist/*.whl dist/*.tar.gz` 检查资源和许可证是否完整。diff --git a/mineru/kit/commands/webui.py b/mineru/kit/commands/webui.pyindex 31466e80..45847430 100644--- a/mineru/kit/commands/webui.py+++ b/mineru/kit/commands/webui.py@@ -23,10 +23,10 @@ def _require_gradio_dependencies() -> None:"dependency_missing",t("Gradio is a base dependency; repair the installation with `pip install 'mineru'`."),)- if version("gradio") not in SpecifierSet(">=6.8,<7"):+ if version("gradio") not in SpecifierSet(">=6.21,<7"):exit_with_message("dependency_incompatible",- t("Gradio >=6.8,<7 is required; upgrade with `pip install --upgrade 'mineru'`."),+ t("Gradio >=6.21,<7 is required; upgrade with `pip install --upgrade 'mineru'`."),)diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 511d7077..1a21d7a1 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -168,7 +168,7 @@ _KIT_MENU_CSS = """}#mineru-kit-download-options :is(button, a):hover { background: var(--background-fill-secondary, #f3f4f6); }.mineru-kit-empty-preview { min-height: 160px; display: grid; place-items: center; opacity: .65; }-/* Gradio 6.8 会按逗号拆分并重写选择器,PDF/源文档预览使用独立选择器避免破坏 :has。 */+/* Gradio 6.x 仍按逗号拆分并重写选择器,PDF/源文档预览使用独立选择器避免破坏 :has。 *//* PDF/源文档预览直接贴合面板边框,独立预览不再沿用旧组件的标签留白与额外高度。 */.mineru-kit-preview:has(.mineru-pdf-frame),.mineru-kit-preview:has(.mineru-source-frame),@@ -663,15 +663,15 @@ def build_gradio_app(clear_button.click(fn=None, inputs=[], outputs=pdf_viewer, js=pdf_preview_js("clear"), **private_event_kwargs)source_script = _resource_text("gradio_source_preview.js")- input_file.change(+ begin_source_preview = input_file.change(fn=None,inputs=input_file,outputs=[source_ticket, source_preview],js=f"(...args) => ({source_script})('begin', ...args)",**private_event_kwargs,)- # Gradio 6.8 的纯前端事件不可靠地触发 then;通过请求值变化启动后台转换。- render_source_preview = source_ticket.change(+ # 前端先失效旧预览并生成票据,再串联后端;票据仍用于丢弃迟到回执。+ render_source_preview = begin_source_preview.then(fn=prepare_source_preview,inputs=[input_file, source_ticket],outputs=source_receipt,@@ -789,7 +789,7 @@ def build_gradio_app()def read_page_metadata(file_path: str | None) -> str:- """把页数元数据编码为稳定的 JSON 文本,供两个 Gradio 主版本共用。"""+ """把页数元数据编码为 JSON 文本,保持前端状态输入契约稳定。"""return json.dumps(pdf_page_metadata(file_path), ensure_ascii=False)input_file.change(@@ -1052,8 +1052,8 @@ def build_gradio_app(for callback in (read_conversion_status, cancel_ui_conversion, unload_session, convert_ui):callback.__annotations__["request"] = gr.Request- # 纯前端开始事件通过票据 change 发起转换,兼容旧版 Gradio 的 then 限制。- convert_button.click(+ # 前端先建立任务身份并重置界面,再串联后端提交。+ begin_conversion = convert_button.click(fn=None,inputs=[],outputs=[*begin_conversion_outputs, conversion_ticket, status_poll, html_output, json_output],@@ -1065,7 +1065,7 @@ def build_gradio_app(),**private_event_kwargs,)- ui_convert_event = conversion_ticket.change(+ ui_convert_event = begin_conversion.then(fn=convert_ui,inputs=[input_file, tier, page_range, force_ocr, conversion_ticket],outputs=conversion_receipt,@@ -1192,18 +1192,10 @@ def build_gradio_app(for format_name, label in _DOWNLOAD_FORMATS:begin_download = download_buttons[format_name].click(- fn=_download_request_handler,- inputs=active_run_id,- outputs=download_requests[format_name],- js=f"(...args) => [({download_js('begin', format_name, label)})(...args)[0]]",- **private_event_kwargs,- )- # 开始回执也必须经过前端令牌校验,避免慢请求在清除后重新显示旧的“准备中”。- begin_download.success(fn=None,- inputs=[download_requests[format_name], active_run_id],- outputs=[download_buttons[format_name], download_notice],- js=download_js("busy", format_name, label),+ inputs=active_run_id,+ outputs=[download_requests[format_name], download_buttons[format_name], download_notice],+ js=download_js("begin", format_name, label),**private_event_kwargs,)download_handler = session_download_handler(format_name)@@ -1357,11 +1349,6 @@ def _build_office_preview_html(file_path: str | Path, request: object | None = N)-def _download_request_handler(request_token: str) -> str:- """传回前端下载令牌以可靠触发后续事件,不直接修改可能已属于新文档的按钮。"""- return request_token if isinstance(request_token, str) else ""--def _download_handler(format_name: str, output_root: Path) -> Callable[..., tuple[str | None, str]]:"""创建一个绑定格式和 output root 的 Gradio 下载回调。"""diff --git a/mineru/resources/gradio_download.js b/mineru/resources/gradio_download.jsindex a639cc95..6558baf6 100644--- a/mineru/resources/gradio_download.js+++ b/mineru/resources/gradio_download.js@@ -25,17 +25,12 @@}if (action === "begin") {const [runId] = args;- if (!runId || state.runId !== runId || state.pending.has(format)) return [skip(), skip(), skip()];+ // 串联事件仍会继续执行,拒绝开始时清空令牌,避免复用旧请求再次导出。+ if (!runId || state.runId !== runId || state.pending.has(format)) return ["", skip(), skip()];const token = JSON.stringify({ run_id: runId, sequence: ++state.sequence });state.pending.set(format, token);return [token, button(`${label} · ${text("preparing_download")}`, false), ""];}- if (action === "busy") {- const [token, runId] = args;- // 即使开始回执晚于换文件或清除,也只能修改当前仍在等待的同一个请求。- if (!token || state.pending.get(format) !== token || !runId || state.runId !== runId) return [skip(), skip()];- return [button(`${label} · ${text("preparing_download")}`, false), ""];- }if (action === "complete") {const [file, receiptText, runId] = args;const receipt = JSON.parse(receiptText || "{}");diff --git a/mineru/utils/translations.py b/mineru/utils/translations.pyindex fc37fb68..71afd10a 100644--- a/mineru/utils/translations.py+++ b/mineru/utils/translations.py@@ -464,8 +464,8 @@ ZH_MESSAGES: dict[str, str] = {"Gradio is a base dependency; repair the installation with `pip install 'mineru'`.": ("Gradio 是基础依赖;请用 `pip install 'mineru'` 修复安装。"),- "Gradio >=6.8,<7 is required; upgrade with `pip install --upgrade 'mineru'`.": (- "需要 Gradio >=6.8,<7;请用 `pip install --upgrade 'mineru'` 升级。"+ "Gradio >=6.21,<7 is required; upgrade with `pip install --upgrade 'mineru'`.": (+ "需要 Gradio >=6.21,<7;请用 `pip install --upgrade 'mineru'` 升级。"),"Unsupported API server tier '{tier}'. Supported tiers: {tiers}": "不支持的 API server 档位 '{tier}'。支持的档位: {tiers}","{name} must be greater than zero": "{name} 必须大于零",diff --git a/pyproject.toml b/pyproject.tomlindex aaf99f03..b3b9714e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,7 +39,7 @@ classifiers = []dependencies = ["docvortex>=0.6.0,<0.7",- "gradio>=6.8,<7",+ "gradio>=6.21,<7","mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'","mineru-vl-utils>=2.0.7,<3","mineru-llama-cpp>=0.1.3,<1",diff --git a/tests/unittest/test_kit_gradio_conversion.py b/tests/unittest/test_kit_gradio_conversion.pyindex f1b52af1..cb492961 100644--- a/tests/unittest/test_kit_gradio_conversion.py+++ b/tests/unittest/test_kit_gradio_conversion.py@@ -201,6 +201,21 @@ def test_frontend_conversion_receipts() -> None:assert result.returncode == 0, result.stdout + result.stderr+def test_source_preview_and_conversion_follow_frontend_preparation(tmp_path: Path) -> None:+ """两个后端入口都在前端准备后串联,票据更新自身不能额外触发任务。"""+ app = _application(tmp_path, SimpleNamespace())+ dependencies = {item["id"]: item for item in app.config["dependencies"]}+ for name in ("prepare_source_preview", "convert_ui"):+ callback = next(fn for fn in app.fns.values() if fn.name == name)+ event = dependencies[callback._id]+ begin = dependencies[event["trigger_after"]]+ ticket = callback.inputs[-1]+ assert begin["backend_fn"] is False and begin["queue"] is False and begin["js"]+ assert ticket._id in begin["outputs"]+ assert event["api_visibility"] == "private"+ assert not any((ticket._id, "change") in item["targets"] for item in dependencies.values())++def test_conversion_and_poll_are_full_non_generator_responses(tmp_path: Path) -> None:"""通过 Gradio process_api 反复序列化,确认结果不会创建生成器差分缓存。"""from gradio import Requestdiff --git a/tests/unittest/test_kit_gradio_download.cjs b/tests/unittest/test_kit_gradio_download.cjsindex 7f3e07ec..9cf7c231 100644--- a/tests/unittest/test_kit_gradio_download.cjs+++ b/tests/unittest/test_kit_gradio_download.cjs@@ -28,8 +28,14 @@ for (const [format, label] of formats) {const [token, busy] = step("begin", format, "run-a");assert.equal(busy.interactive, false);assert.match(busy.value, /准备中/);- assert.deepEqual(step("begin", format, "run-a"), [{ __type__: "update" }, { __type__: "update" }, { __type__: "update" }]);+ assert.deepEqual(step("begin", format, "run-a"), ["", { __type__: "update" }, { __type__: "update" }]);const count = downloads.length;+ // 重复开始的空令牌回执不能消费尚未完成的有效请求。+ assert.deepEqual(+ step("complete", format, null, receipt("", "ignored duplicate"), "run-a"),+ [{ __type__: "update" }, { __type__: "update" }],+ );+ assert.equal(downloads.length, count);const [ready, notice] = step("complete", format, file, receipt(token), "run-a");assert.equal(downloads.length, count + 1);assert.deepEqual(downloads.at(-1), [file.url, file.orig_name]);@@ -53,8 +59,8 @@ assert.deepEqual(reset.slice(1, 8), Array(7).fill(null));assert.ok(reset.slice(-8, -1).every(update => update.interactive === false));step("activate", "", "run-b");const [current] = step("begin", "pdf", "run-b");-assert.deepEqual(step("busy", "pdf", retry, "run-b"), [{ __type__: "update" }, { __type__: "update" }]);-assert.equal(step("busy", "pdf", current, "run-b")[0].interactive, false);+assert.deepEqual(step("begin", "pdf", "run-a"), ["", { __type__: "update" }, { __type__: "update" }]);+assert.deepEqual(step("begin", "pdf", ""), ["", { __type__: "update" }, { __type__: "update" }]);assert.deepEqual(step("complete", "pdf", file, receipt(retry), "run-b"), [{ __type__: "update" }, { __type__: "update" }]);assert.equal(downloads.length, count);step("complete", "pdf", file, receipt(current), "run-b");diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.pyindex c19bf973..c8789383 100644--- a/tests/unittest/test_kit_gradio_download.py+++ b/tests/unittest/test_kit_gradio_download.py@@ -88,6 +88,10 @@ def test_download_receipt_keeps_request_on_success_and_failure(tmp_path: Path, mpath, receipt = handler(artifacts.as_state(), json.dumps({"run_id": "old-run", "sequence": 3}))assert path is None and "已变更" in json.loads(receipt)["error"]render.assert_not_called()+ # 被前端拒绝的重复点击只携带空令牌,不能进入导出逻辑。+ path, receipt = handler(artifacts.as_state(), "")+ assert path is None and json.loads(receipt)["request"] == ""+ render.assert_not_called()def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:@@ -111,7 +115,7 @@ def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:assert reset()[2]["visible"] is Falseassert reset()[7] == ""conversion = next(fn for fn in app.fns.values() if fn.name == "convert_handler")- # 浏览器通过票据变化启动普通请求;公开 API 仍保留四个输入与原生文件输出。+ # 浏览器先生成票据再串联普通请求;公开 API 仍保留四个输入与原生文件输出。assert len(conversion.inputs) == 4ui_conversion = next(fn for fn in app.fns.values() if fn.name == "convert_ui")ticket = ui_conversion.inputs[-1]@@ -130,11 +134,17 @@ def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:assert reset_on_upload["js"] and reset_on_upload["backend_fn"] is Falsehandlers = [fn for fn in app.fns.values() if fn.name == "handler"]assert len(handlers) == 7+ dependencies = {dep["id"]: dep for dep in app.config["dependencies"]}files = []for handler in handlers:file, receipt = handler.outputsassert file.__class__.__name__ == "File" and file.visible is Falsefiles.append(file._id)+ begin = dependencies[dependencies[handler._id]["trigger_after"]]+ assert begin["backend_fn"] is False and begin["queue"] is False+ assert len(begin["outputs"]) == 3 and begin["outputs"][0] == handler.inputs[1]._id+ assert '"begin"' in begin["js"]+ assert [dep["id"] for dep in dependencies.values() if dep.get("trigger_after") == begin["id"]] == [handler._id]success = next(dep for dep in app.config["dependencies"] if dep.get("trigger_after") == handler._id)assert success["trigger_only_on_success"] is Trueassert success["backend_fn"] is False and success["queue"] is Falsediff --git a/tests/unittest/test_kit_gradio_pdf_preview.py b/tests/unittest/test_kit_gradio_pdf_preview.pyindex bcd326f2..987f11e7 100644--- a/tests/unittest/test_kit_gradio_pdf_preview.py+++ b/tests/unittest/test_kit_gradio_pdf_preview.py@@ -6,6 +6,7 @@ import hashlibimport jsonimport shutilimport subprocess+import tomllibfrom pathlib import Pathfrom unittest.mock import Mockfrom urllib.parse import quote@@ -16,6 +17,7 @@ import typerfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom gradio.data_classes import FileData+from packaging.requirements import Requirementfrom mineru.kit.commands import webui as webui_commandfrom mineru.kit.gradio.app import build_gradio_app@@ -108,7 +110,7 @@ def test_pdfjs_manifest_matches_bundled_files() -> None:assert "Apache License" in (root / "LICENSE").read_text(encoding="utf-8")[email protected]("version", ["5.49.1", "5.50.0", "6.7.0", "7.0.0"])[email protected]("version", ["5.49.1", "5.50.0", "6.7.0", "6.8.0", "6.20.0", "7.0.0"])def test_webui_command_rejects_unsupported_version(monkeypatch: pytest.MonkeyPatch, version: str) -> None:"""即使用户跳过安装器检查,启动时仍明确拒绝旧版或未支持的主版本。"""monkeypatch.setattr(webui_command, "version", Mock(return_value=version))@@ -117,6 +119,21 @@ def test_webui_command_rejects_unsupported_version(monkeypatch: pytest.MonkeyPatassert getattr(error.value, "exit_code", None) == 1[email protected]("version", ["6.20.0", "6.21.0", "6.27.0", "6.30.0", "7.0.0"])+def test_webui_version_check_matches_package_requirement(monkeypatch: pytest.MonkeyPatch, version: str) -> None:+ """发行依赖与启动校验接受相同的版本区间,覆盖最低支持版本及两个边界。"""+ project = tomllib.loads((Path(__file__).parents[2] / "pyproject.toml").read_text(encoding="utf-8"))["project"]+ requirement = next(Requirement(item) for item in project["dependencies"] if item.startswith("gradio"))+ supported = version in requirement.specifier+ assert supported == (version in {"6.21.0", "6.27.0", "6.30.0"})+ monkeypatch.setattr(webui_command, "version", Mock(return_value=version))+ if supported:+ webui_command._require_gradio_dependencies()+ else:+ with pytest.raises(typer.Exit):+ webui_command._require_gradio_dependencies()++def test_pdf_preview_frontend_lifecycle() -> None:"""用 Node 执行实际适配器,验证乱序、编码和重复上传行为。"""node = shutil.which("node")