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
fix(webui): synchronize source selection and download resets
myhloliff08d6b40888
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 26c8fb3f..bc94f674 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -869,9 +869,16 @@ def build_gradio_app(# 文件切换只重置下载控件;转换点击另加状态卡片,避免重置结果错位清空卡片。begin_conversion_outputs = [status_panel, *download_reset_outputs]- # 先在前端失效旧请求,再等待上传/清除/转换的 Python 回调,防止迟到的下载被触发。- gr.on(- triggers=[input_file.change, clear_button.click],+ # 匹配选择票据后才重置下载,重复文件事件与迟到票据保留当前结果。+ prepare_input.then(+ fn=None,+ inputs=source_preparation_ticket,+ outputs=download_reset_outputs,+ js=download_js("source"),+ **private_event_kwargs,+ )+ # 显式清除立即失效下载,不等待上传或转换的 Python 回调。+ clear_button.click(fn=None,inputs=[],outputs=download_reset_outputs,diff --git a/mineru/resources/gradio_download.js b/mineru/resources/gradio_download.jsindex 6558baf6..b2c93f28 100644--- a/mineru/resources/gradio_download.js+++ b/mineru/resources/gradio_download.js@@ -10,7 +10,18 @@"&": "&", "<": "<", ">": ">", '"': """, "'": "'",})[char]);+ if (action === "source") {+ // 只接受当前选择的票据,重复文件事件保留已完成结果及其在途下载。+ let source;+ try { source = JSON.parse(args[0] || "null"); } catch {}+ const preview = window.__mineruPdfPreview;+ if (!source?.id || source.id !== preview?.sourceId || source.path !== preview.source || source.id === state.sourceId) {+ return Array.from({ length: formats.length * 4 + 2 }, skip);+ }+ action = "reset";+ }if (action === "reset") {+ state.sourceId = window.__mineruPdfPreview?.sourceId || "";state.runId = "";state.pending.clear();return [diff --git a/mineru/resources/gradio_pdf_preview.js b/mineru/resources/gradio_pdf_preview.jsindex 472c9987..fce18216 100644--- a/mineru/resources/gradio_pdf_preview.js+++ b/mineru/resources/gradio_pdf_preview.js@@ -121,7 +121,7 @@if (operation === "clear") { state.clear(); return skip(); }if (operation === "reset") { reset(values[0]); return skip(); }if (operation === "prepare") {- if (!values[0] && state.localSelected) return skip();+ // 本地选择尚无服务器路径,也要生成匹配空路径的票据以清除旧结果。reset(values[0]);return JSON.stringify({ id: state.sourceId, revision: state.revision, path: key(values[0]) });}@@ -129,6 +129,8 @@let receipt;try { receipt = JSON.parse(values[0]); } catch { return skip(); }if (!receipt || receipt.id !== state.sourceId || receipt.path !== state.source) return skip();+ // 空路径只表示旧源已失效,不能把这类回执当作上传或准备成功。+ if (!receipt.path) return "";window.__mineruUpload?.prepared(receipt.error);if (receipt.error) { if (!state.frame) notice(receipt.error, true); return ""; }if (receipt.pdf) mount(receipt.pdf);diff --git a/tests/unittest/test_kit_gradio_conversion.py b/tests/unittest/test_kit_gradio_conversion.pyindex 92fa35e0..87884455 100644--- a/tests/unittest/test_kit_gradio_conversion.py+++ b/tests/unittest/test_kit_gradio_conversion.py@@ -260,6 +260,22 @@ def test_source_preview_and_conversion_follow_frontend_preparation(tmp_path: Patassert not any((ticket._id, "change") in item["targets"] for item in dependencies.values())+def test_local_selection_resets_results_before_upload_finishes(tmp_path: Path) -> None:+ """本地替换尚无服务端路径时就清空旧正文、JSON 和下载,上传失败也不残留旧结果。"""+ app = _application(tmp_path, SimpleNamespace())+ preview = _callback(app, "update_file_preview")+ request = SimpleNamespace(session_hash="local-replacement")+ old = json.dumps({"id": "a" * 32, "revision": 1, "path": "/cache/old.pdf"})+ preview("/cache/old.pdf", request, old)+ selected = json.dumps({"id": "b" * 32, "revision": 2, "path": ""})+ updates = preview(None, request, selected)+ assert updates[0]["value"] is None+ assert updates[5] == updates[-1] == ""+ assert updates[6] is None and updates[7] == ""+ assert all(update["interactive"] is False for update in updates[8:15])+ assert all(update == {"__type__": "update"} for update in preview(None, request, selected))++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 9cf7c231..8036a0c0 100644--- a/tests/unittest/test_kit_gradio_download.cjs+++ b/tests/unittest/test_kit_gradio_download.cjs@@ -65,4 +65,31 @@ assert.deepEqual(step("complete", "pdf", file, receipt(retry), "run-b"), [{ __tyassert.equal(downloads.length, count);step("complete", "pdf", file, receipt(current), "run-b");assert.equal(downloads.length, count + 1);++// 重复文件事件保留完整下载状态,包括已经生成的结果和尚未返回的下载令牌。+const source = {id: "a".repeat(32), revision: 1, path: "/cache/source.pdf"};+window.__mineruPdfPreview = {sourceId: source.id, source: source.path};+step("source", "", JSON.stringify(source));+step("activate", "", "run-c");+const [duplicateToken] = step("begin", "html", "run-c");+const duplicate = step("source", "", JSON.stringify(source));+assert.equal(duplicate.length, formats.length * 4 + 2);+assert.ok(duplicate.every(value => value.__type__ === "update" && Object.keys(value).length === 1));+const beforeDuplicate = downloads.length;+step("complete", "html", file, receipt(duplicateToken), "run-c");+assert.equal(downloads.length, beforeDuplicate + 1);++// 新的本地选择立即撤销旧下载,迟到的旧选择票据不能撤销新结果。+const replacement = {id: "b".repeat(32), revision: 2, path: ""};+window.__mineruPdfPreview = {sourceId: replacement.id, source: ""};+const changed = step("source", "", JSON.stringify(replacement));+assert.equal(changed[0], "");+assert.ok(changed.slice(-8, -1).every(update => update.interactive === false));+step("activate", "", "run-d");+const [replacementToken] = step("begin", "pdf", "run-d");+const stale = step("source", "", JSON.stringify(source));+assert.equal(stale.length, formats.length * 4 + 2);+assert.ok(stale.every(value => value.__type__ === "update" && Object.keys(value).length === 1));+step("complete", "pdf", file, receipt(replacementToken), "run-d");+assert.equal(downloads.length, beforeDuplicate + 2);console.log("download lifecycle passed");diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.pyindex bd7763fa..4996964b 100644--- a/tests/unittest/test_kit_gradio_download.py+++ b/tests/unittest/test_kit_gradio_download.py@@ -125,11 +125,17 @@ def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:assert reset_dependency["backend_fn"] is Falseassert "Preparing request..." in reset_dependency["js"]upload = next(fn for fn in app.fns.values() if fn.name == "convert_handler").inputs[0]+ preview = next(fn for fn in app.fns.values() if fn.name == "update_file_preview")+ preview_event = next(dep for dep in app.config["dependencies"] if dep["id"] == preview._id)reset_on_upload = next(depfor dep in app.config["dependencies"]- if (upload._id, "change") in dep["targets"] and dep["outputs"] == reset_dependency["outputs"][1:-4]+ if dep["trigger_after"] == preview_event["trigger_after"] and dep["outputs"] == reset_dependency["outputs"][1:-4])+ preparation = next(dep for dep in app.config["dependencies"] if dep["id"] == reset_on_upload["trigger_after"])+ assert (upload._id, "change") in preparation["targets"]+ assert reset_on_upload["inputs"] == [preparation["outputs"][0]]+ assert '"source"' in reset_on_upload["js"]assert reset_dependency["outputs"][0] not in reset_on_upload["outputs"]assert reset_on_upload["js"] and reset_on_upload["backend_fn"] is Falsehandlers = [fn for fn in app.fns.values() if fn.name == "handler"]diff --git a/tests/unittest/test_kit_gradio_pdf_preview.cjs b/tests/unittest/test_kit_gradio_pdf_preview.cjsindex 527251d9..ffadd066 100644--- a/tests/unittest/test_kit_gradio_pdf_preview.cjs+++ b/tests/unittest/test_kit_gradio_pdf_preview.cjs@@ -30,7 +30,7 @@ const window = {addEventListener: (name, fn) => events[name] = fn,__mineruI18n: { text: key => key },__mineruTrace: { reset() {}, activate(...values) { activations.push(values); } },- __mineruUpload: { isImage: name => name.endsWith(".png"), invalidate() {}, sync() {}, prepared() {} },+ __mineruUpload: { isImage: name => name.endsWith(".png"), invalidate() {}, sync() {}, prepared(error) { this.error = error; } },};const invoke = vm.runInNewContext(`(${script})`, { window, document, location, crypto, URL: LocalURL, URLSearchParams });// 使用真实文件路径而非编码后的 URL 判断文件身份。@@ -45,6 +45,16 @@ assert.ok(originalFrame && state.uploading);assert.equal(new URLSearchParams(new URL(originalFrame.src).hash.slice(1)).get("file"), `blob:${location.origin}/1`);invoke("reset", null);assert.equal(state.frame, originalFrame);+// 上传开始的空 FileData 仍须产生本次选择票据,让后端立即清除旧结果。+const selectedTicket = JSON.parse(invoke("prepare", null));+assert.equal(selectedTicket.id, "local-one");+assert.equal(selectedTicket.path, "");+assert.equal(selectedTicket.revision, state.revision);+assert.equal(state.frame, originalFrame);+// 失效旧源的空路径回执不能清空已经显示的上传失败信息。+window.__mineruUpload.error = "upload failed";+assert.equal(invoke("prepared", JSON.stringify({ ...selectedTicket, error: "" })), "");+assert.equal(window.__mineruUpload.error, "upload failed");const uploadingRevision = state.revision;assert.equal(state.bind(first, "local-one"), true);assert.ok(state.revision > uploadingRevision);