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(status): enhance status updates with unique identifiers and improve snapshot rendering
myhloli4740a867eee5
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 2efd7a6d..a44dbc65 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -849,11 +849,6 @@ def build_gradio_app(yield (_status_html(message), *reset_result[1:])returnselected_tier = "flash"- try:- page_text = await asyncio.to_thread(_effective_page_range, source_path, raw_page_range, max_pages=max_pages)- except MineruError as exc:- yield (_status_html(f"Failed: {exc.code}: {exc}"), *reset_result[1:])- returnstatus_queue: asyncio.Queue[tuple[str, float]] = asyncio.Queue()loop = asyncio.get_running_loop()@@ -866,6 +861,8 @@ def build_gradio_app(if conversion_slot.locked():emit(STATUS_QUEUED_LOCALLY)async with conversion_slot:+ emit(STATUS_PREPARING_REQUEST)+ page_text = await asyncio.to_thread(_effective_page_range, source_path, raw_page_range, max_pages=max_pages)result = await client.parse_file(source_path,tier=selected_tier,@@ -935,7 +932,8 @@ def build_gradio_app(# 会话重置后静默结束旧流,避免把取消异常或旧状态写回新界面。returnexcept Exception as exc:- state.append(f"Failed: {exc}")+ message = f"{exc.code}: {exc}" if isinstance(exc, MineruError) else str(exc)+ state.append(f"Failed: {message}")yield (state.render(), *reset_result[1:])finally:# 清除、换文件或断开流时仅取消本地等待,不发送远端取消请求。diff --git a/mineru/kit/gradio/status.py b/mineru/kit/gradio/status.pyindex 33b6e036..3c10f01e 100644--- a/mineru/kit/gradio/status.py+++ b/mineru/kit/gradio/status.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport time+import uuidfrom collections.abc import AsyncIterator, Callablefrom dataclasses import dataclass, fieldfrom decimal import ROUND_HALF_UP, Decimal@@ -45,6 +46,9 @@ class StatusPanelState:step_index: int = -1processing_elapsed: float | None = None_processing_started: float | None = None+ run_id: str = field(default_factory=lambda: uuid.uuid4().hex)+ phase_id: int = 0+ sequence: int = 0def append(self, message: str, *, at: float | None = None) -> bool:"""接收真实阶段变化;重复通知不会重置解析计时。"""@@ -58,12 +62,18 @@ class StatusPanelState:self._processing_started = nowself.processing_elapsed = 0.0self.message = message- # 本地等待可能发生在上传之前;已展示的步骤不因后续准备通知倒退。- self.step_index = max(self.step_index, _MESSAGE_STEPS.get(message, -1))+ self.phase_id += 1+ # 本地排队结束后可以重新准备请求,高亮必须与实际阶段一致。+ self.step_index = _MESSAGE_STEPS.get(message, self.step_index)if message.startswith("Failed:"):self.step_index = len(_STEPS) - 1return True+ def snapshot(self) -> str:+ """为周期同步生成新序号,确保静态阶段也能重新应用到浏览器。"""+ self.sequence += 1+ return self.render()+def render(self) -> str:"""按 3.4.5 的两列卡片结构渲染当前状态,并转义外部错误文本。"""now = self.clock()@@ -108,7 +118,9 @@ class StatusPanelState:'<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"{timer_attributes}>{latest_html}</div></div>'+ f'<div class="status-latest" data-mineru-run-id="{self.run_id}" '+ f'data-mineru-phase-id="{self.phase_id}" data-mineru-status-seq="{self.sequence}"'+ f"{timer_attributes}>{latest_html}</div></div>")@@ -124,28 +136,36 @@ async def stream_status_updates(events: asyncio.Queue[tuple[str, float]],state: StatusPanelState,) -> AsyncIterator[str]:- """只等待真实阶段通知或任务结束,并及时回收临时等待任务。"""+ """阶段变化立即发送,长任务每秒同步快照;浏览器独立绘制动画。"""+ loop = asyncio.get_running_loop()+ next_refresh = loop.time() + 1.0while True:while not events.empty():message, at = events.get_nowait()if state.append(message, at=at):- yield state.render()+ next_refresh = loop.time() + 1.0+ yield state.snapshot()if task.done():returnwaiter = asyncio.create_task(events.get())updated_html: str | None = Nonetry:- done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED)+ done, _ = await asyncio.wait(+ {task, waiter}, timeout=max(0.0, next_refresh - loop.time()), return_when=asyncio.FIRST_COMPLETED+ )if waiter in done:message, at = waiter.result()if state.append(message, at=at):- updated_html = state.render()+ updated_html = state.snapshot()+ if updated_html is None and not task.done() and loop.time() >= next_refresh:+ updated_html = state.snapshot()finally:if not waiter.done():waiter.cancel()await asyncio.gather(waiter, return_exceptions=True)# 向 Gradio 交回控制权前已回收临时 waiter,避免暂停在 yield 时残留后台等待。if updated_html is not None:+ next_refresh = loop.time() + 1.0yield updated_htmldiff --git a/mineru/resources/gradio_app.css b/mineru/resources/gradio_app.cssindex 1b2c8920..e01e90d9 100644--- a/mineru/resources/gradio_app.css+++ b/mineru/resources/gradio_app.css@@ -64,9 +64,9 @@ body.dark .gradio-container {}/* 两个原生 range 共用同一条轨道;仅滑块接收指针,保留原生键盘交互。 */.mineru-kit-page-range {- display: none !important; position: relative; padding: 8px 12px 22px !important; overflow: visible !important;+ display: none !important; position: relative; padding: 4px 12px 15px !important; overflow: visible !important;border: 1px solid var(--mineru-panel-border); border-radius: 8px;- gap: 8px !important; flex: 0 0 auto !important;+ gap: 0 !important; flex: 0 0 auto !important;}/* 用明确的选页状态控制可见性,保留原生滑块的交互状态。 */.mineru-kit-page-range:has([data-range-visible="true"]) { display: flex !important; }@@ -76,7 +76,7 @@ body.dark .gradio-container {.mineru-page-selection { font-weight: 600; color: var(--mineru-accent); }.mineru-page-axis { position: absolute; bottom: 0; left: 0; right: 0; font-size: 12px; opacity: .7; }.mineru-page-summary { position: static !important; }-.mineru-kit-page-range .mineru-page-axis { bottom: 5px; left: 12px; right: 12px; }+.mineru-kit-page-range .mineru-page-axis { bottom: 4px; left: 12px; right: 12px; }.mineru-page-sliders { position: relative !important; height: 32px; min-height: 32px !important; gap: 0 !important; }.mineru-page-sliders::before {content: ""; position: absolute; left: 8px; right: 8px; top: 14px; height: 4px; border-radius: 4px;diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.jsindex 5036129d..2f64b3d7 100644--- a/mineru/resources/gradio_app.js+++ b/mineru/resources/gradio_app.js@@ -1,5 +1,5 @@() => {- const APP_SCRIPT_VERSION = "v4-local-queue-animation";+ const APP_SCRIPT_VERSION = "v6-local-status-clock";if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {return;}@@ -213,6 +213,11 @@refreshMineruCustomHtml();});if (typeof MutationObserver !== "undefined") {+ let refreshPending = false;+ const observationOptions = {+ childList: true, subtree: true, characterData: true, attributes: true,+ attributeFilter: ["title", "aria-label", "data-mineru-i18n-en", "data-mineru-i18n-zh"],+ };const uiObserver = new MutationObserver((mutations) => {// 本地计时与排队动画的文字变化无需重新扫描整页,避免递归本地化。if (mutations.every(({ target }) => {@@ -221,12 +226,20 @@})) {return;}- refreshMineruCustomHtml();- });- uiObserver.observe(document.body, {- childList: true, subtree: true, characterData: true, attributes: true,- attributeFilter: ["title", "aria-label", "data-mineru-i18n-en", "data-mineru-i18n-zh"],+ if (refreshPending) return;+ refreshPending = true;+ // 合并同帧重绘,并隔离自身写入,避免本地化与计时更新形成微任务循环。+ requestAnimationFrame(() => {+ refreshPending = false;+ uiObserver.disconnect();+ try {+ refreshMineruCustomHtml();+ } finally {+ uiObserver.observe(document.body, observationOptions);+ }+ });});+ uiObserver.observe(document.body, observationOptions);}document.addEventListener("click", (event) => {diff --git a/mineru/resources/gradio_status_timer.js b/mineru/resources/gradio_status_timer.jsindex a00cfd67..2139b044 100644--- a/mineru/resources/gradio_status_timer.js+++ b/mineru/resources/gradio_status_timer.js@@ -1,9 +1,9 @@(i18n) => {let interval = null;let activeSpan = null;- let activeStart = null;let startedAt = 0;let activeMode = null;+ let activeIdentity = null;let activeQueueKey = null;let queueStartedAt = 0;@@ -16,8 +16,8 @@activeSpan?.removeAttribute("data-mineru-local-timer");activeSpan?.removeAttribute("data-mineru-local-animation");activeSpan = null;- activeStart = null;activeMode = null;+ activeIdentity = null;activeQueueKey = null;};@@ -46,16 +46,17 @@const span = status?.querySelector('[data-mineru-i18n-key="status_message"]');const start = status?.getAttribute("data-mineru-processing-start");if (span && start !== null) {- if (activeMode === "processing" && span === activeSpan && start === activeStart) return;- if (activeMode !== "processing") stop();- else activeSpan?.removeAttribute("data-mineru-local-timer");- const serverElapsed = Number(status.getAttribute("data-mineru-processing-elapsed"));- const serverElapsedMs = Number.isFinite(serverElapsed) ? Math.max(0, serverElapsed * 1000) : 0;- const observedStart = performance.now() - serverElapsedMs;- startedAt = activeMode === "processing" && start === activeStart- ? Math.min(startedAt, observedStart) : observedStart;+ const identity = `${status.getAttribute("data-mineru-run-id")}:${status.getAttribute("data-mineru-phase-id")}`;+ // 快照可能复用节点却清除本地标记,必须重新认领节点,不能提前返回。+ if (activeMode !== "processing" || identity !== activeIdentity) {+ stop();+ // 解析计时只从浏览器首次观察到该阶段开始,不读取服务端耗时或起点。+ startedAt = performance.now();+ } else if (span !== activeSpan) {+ activeSpan?.removeAttribute("data-mineru-local-timer");+ }+ activeIdentity = identity;activeSpan = span;- activeStart = start;activeMode = "processing";activeSpan.setAttribute("data-mineru-local-timer", "");if (interval === null) interval = setInterval(render, 10);@@ -66,13 +67,11 @@const queueSpan = queueStatus?.querySelector('[data-mineru-i18n-key="status_message"]');const queueKey = queueStatus?.getAttribute("data-mineru-queue-key");if (queueSpan && (queueKey === "queued_locally" || queueKey === "queued_on_server")) {- if (activeMode === "queue" && queueSpan === activeSpan && queueKey === activeQueueKey) {- render();- return;- }- if (activeMode !== "queue" || queueKey !== activeQueueKey) stop();- else activeSpan?.removeAttribute("data-mineru-local-animation");+ const identity = `${queueStatus.getAttribute("data-mineru-run-id")}:${queueStatus.getAttribute("data-mineru-phase-id")}`;+ if (activeMode !== "queue" || queueKey !== activeQueueKey || identity !== activeIdentity) stop();+ else if (queueSpan !== activeSpan) activeSpan?.removeAttribute("data-mineru-local-animation");if (activeMode !== "queue") queueStartedAt = performance.now();+ activeIdentity = identity;activeSpan = queueSpan;activeQueueKey = queueKey;activeMode = "queue";diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex 575919f0..6b5228f9 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -1614,3 +1614,51 @@ def test_shared_layout_failure_keeps_other_gradio_artifacts(tmp_path: Path, monkwith zipfile.ZipFile(render_download(artifacts.as_state(), "markdown")) as archive:assert f"{artifacts.stem}.md" in archive.namelist()assert "layout.pdf" not in archive.namelist()+++def test_gradio_slow_precheck_streams_heartbeats_and_queues_other_sessions(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """页码预检阻塞时仍同步状态,其他会话先显示排队而不是堵在预检前。"""+ import threading++ source = tmp_path / "source.pdf"+ source.write_bytes(_pdf_bytes())+ release = threading.Event()+ started = threading.Event()++ def precheck(*_args: Any, **_kwargs: Any) -> str:+ """用事件阻塞预检,避免测试依赖真实 PDF 耗时。"""+ started.set()+ assert release.wait(10)+ return "1"++ monkeypatch.setattr(gradio_app, "_effective_page_range", precheck)+ client = SimpleNamespace(parse_file=AsyncMock(side_effect=V1ArtifactError("test finished")))+ 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 scenario() -> None:+ """同时推进两个会话,验证预检时的心跳和执行槽等待。"""+ first = handler(str(source), 0, "")+ second = handler(str(source), 0, "")+ try:+ await anext(first)+ heartbeat = await asyncio.wait_for(anext(first), 2)+ assert started.is_set()+ assert "Preparing request" in heartbeat[0]+ assert 'data-mineru-status-seq="1"' in heartbeat[0]+ assert all(value == {"__type__": "update"} for value in heartbeat[1:])+ await anext(second)+ queued = await asyncio.wait_for(anext(second), 0.5)+ assert "Queued locally" in queued[0]+ release.set()+ assert "test finished" in [item async for item in first][-1][0]+ assert "test finished" in [item async for item in second][-1][0]+ finally:+ release.set()+ await first.aclose()+ await second.aclose()++ asyncio.run(scenario())diff --git a/tests/unittest/test_kit_gradio_status.py b/tests/unittest/test_kit_gradio_status.pyindex 54f9072b..50bbc70a 100644--- a/tests/unittest/test_kit_gradio_status.py+++ b/tests/unittest/test_kit_gradio_status.py@@ -131,3 +131,57 @@ def test_status_stream_waits_for_stage_changes_and_cleans_up_waiter() -> None:await asyncio.gather(task, return_exceptions=True)asyncio.run(scenario())++[email protected]("message", ["Preparing request...", STATUS_QUEUED_ON_SERVER, STATUS_PROCESSING_ON_SERVER])+def test_status_heartbeat_survives_duplicate_notifications(message: str) -> None:+ """重复阶段通知不能饿死每秒快照,心跳也不能改变任务或阶段身份。"""++ async def scenario() -> None:+ """持续发送同阶段通知并检查周期快照及即时阶段切换。"""+ state = StatusPanelState()+ state.append(message)+ identity = (state.run_id, state.phase_id, state._processing_started)+ events: asyncio.Queue[tuple[str, float]] = asyncio.Queue()+ finish = asyncio.Event()+ task = asyncio.create_task(finish.wait())++ async def repeat() -> None:+ """模拟每次查询都返回相同阶段。"""+ while not finish.is_set():+ events.put_nowait((message, state.clock()))+ await asyncio.sleep(0.05)++ sender = asyncio.create_task(repeat())+ try:+ async with aclosing(stream_status_updates(task, events, state)) as stream:+ started = asyncio.get_running_loop().time()+ first = await asyncio.wait_for(anext(stream), 2)+ assert 0.9 <= asyncio.get_running_loop().time() - started < 2+ assert 'data-mineru-status-seq="1"' in first+ assert identity == (state.run_id, state.phase_id, state._processing_started)+ sender.cancel()+ await asyncio.gather(sender, return_exceptions=True)+ events.put_nowait((STATUS_PROCESSING_OUTPUT, state.clock()))+ update = await asyncio.wait_for(anext(stream), 0.5)+ assert "Preparing outputs" in update+ assert 'data-mineru-status-seq="2"' in update+ finish.set()+ assert [item async for item in stream] == []+ finally:+ finish.set()+ sender.cancel()+ await asyncio.gather(task, sender, return_exceptions=True)++ asyncio.run(scenario())+++def test_local_queue_can_return_to_preparation() -> None:+ """拿到本地槽位后高亮准备步骤,避免底部阶段与高亮不一致。"""+ state = StatusPanelState()+ state.append(STATUS_QUEUED_LOCALLY)+ phase = state.phase_id+ state.append("Preparing request...")+ assert state.step_index == 0+ assert state.phase_id == phase + 1+ assert "data-mineru-queue-key" not in state.render()diff --git a/tests/unittest/test_kit_gradio_status_timer.cjs b/tests/unittest/test_kit_gradio_status_timer.cjsindex a9f96a54..42a2a1f3 100644--- a/tests/unittest/test_kit_gradio_status_timer.cjs+++ b/tests/unittest/test_kit_gradio_status_timer.cjs@@ -91,10 +91,10 @@ assert.equal(remounted.hasAttribute("data-mineru-local-timer"), false);const second = makeSpan();currentStatus = makeStatus("200.000000000", 0.01, second);timer.sync();-assert.equal(second.textContent, "服务端解析中(0.01 秒)");+assert.equal(second.textContent, "服务端解析中(0.00 秒)");now = 1050;tick();-assert.equal(second.textContent, "服务端解析中(0.94 秒)");+assert.equal(second.textContent, "服务端解析中(0.93 秒)");currentStatus = null;timer.sync();assert.equal(stopped, 2);@@ -117,6 +117,13 @@ tick();assert.equal(queued.textContent, "服务端排队中.");i18n.localize({ querySelectorAll(selector) { return selector === "[data-mineru-i18n-key]" ? [queued] : []; } });assert.equal(queued.textContent, "服务端排队中.");+// 排队节点复用时同样需要恢复标记,否则本地化会吞掉圆点。+queued.removeAttribute("data-mineru-local-animation");+queued.setAttribute("data-mineru-i18n-zh", "服务端排队中");+timer.sync();+i18n.localize({ querySelectorAll: (selector) => selector === "[data-mineru-i18n-key]" ? [queued] : [] });+assert.equal(queued.hasAttribute("data-mineru-local-animation"), true);+assert.equal(queued.textContent, "服务端排队中.");const remountedQueue = makeSpan();queued.isConnected = false;currentStatus = makeStatus(null, null, remountedQueue, "queued_on_server");@@ -139,7 +146,7 @@ currentStatus = makeStatus("400.000000000", 0.04, afterQueue);now = 12400;timer.sync();assert.equal(intervalMs, 10);-assert.equal(afterQueue.textContent, "服务端解析中(0.04 秒)");+assert.equal(afterQueue.textContent, "服务端解析中(0.00 秒)");assert.equal(localQueue.hasAttribute("data-mineru-local-animation"), false);currentStatus = null;timer.sync();@@ -187,3 +194,84 @@ assert.equal(preparingSpan.getAttribute("data-mineru-i18n-key"), "preparing_requassert.equal(latestAttributes.size, 0);assert.ok(steps[0].values.has("is-active"));assert.ok(steps.slice(1).every((step) => step.values.has("is-pending")));++// 每秒快照不校准正在运行的本地时钟,即使服务端耗时明显不同。+currentStatus = null;+timer.sync();+now = 20000;+const stableClock = makeSpan();+currentStatus = makeStatus("stable", 0, stableClock);+timer.sync();+now = 21000;+currentStatus = makeStatus("stable", 99, makeSpan());+timer.sync();+assert.equal(currentStatus.querySelector().textContent, "服务端解析中(1.00 秒)");++// Gradio 复用节点并清除自定义属性后,心跳必须恢复本地所有权,防止本地化覆盖小数。+const patchedSpan = currentStatus.querySelector();+for (let heartbeat = 2; heartbeat <= 5; heartbeat += 1) {+ now = 20000 + heartbeat * 1000;+ patchedSpan.removeAttribute("data-mineru-local-timer");+ patchedSpan.setAttribute("data-mineru-i18n-en", `Processing on server (${heartbeat}.00s)`);+ patchedSpan.setAttribute("data-mineru-i18n-zh", `服务端解析中(${heartbeat}.00 秒)`);+ // 服务端起点或耗时变动也不应重新校准同一任务、同一阶段的本地起点。+ currentStatus = makeStatus(`changed-${heartbeat}`, 99, patchedSpan);+ timer.sync();+ assert.equal(patchedSpan.hasAttribute("data-mineru-local-timer"), true);+ for (let fraction = 1; fraction < 100; fraction += 1) {+ now = 20000 + heartbeat * 1000 + fraction * 10;+ tick();+ i18n.localize({ querySelectorAll: (selector) => selector === "[data-mineru-i18n-key]" ? [patchedSpan] : [] });+ assert.equal(patchedSpan.textContent, `服务端解析中(${heartbeat}.${String(fraction).padStart(2, "0")} 秒)`);+ }+}++// 新任务即使阶段与起点相同,也必须重置本地计时。+const freshStatus = makeStatus("stable", 0, makeSpan());+const oldGet = freshStatus.getAttribute;+freshStatus.getAttribute = (name) => name === "data-mineru-run-id" ? "new-run" : oldGet(name);+currentStatus = freshStatus;+timer.sync();+assert.equal(currentStatus.querySelector().textContent, "服务端解析中(0.00 秒)");++// 页面本地化会产生 DOM 写入;同帧外部重绘只刷新一次,自身写入不得反馈成无限循环。+let observer = null;+let observing = false;+let localizations = 0;+const frames = [];+const externalMutation = { target: { nodeType: 1, closest: () => null } };+const appContext = vm.createContext({+ window: {},+ document: { body: {}, querySelector: () => null, querySelectorAll: () => [], addEventListener() {} },+ localStorage: { getItem: () => null },+ requestAnimationFrame: (callback) => frames.push(callback),+ MutationObserver: class {+ // 保存观察回调,测试中模拟浏览器的 DOM 变化通知。+ constructor(callback) { observer = callback; }+ // 恢复外部变化监听。+ observe() { observing = true; }+ // 隔离本地化自身的 DOM 写入。+ disconnect() { observing = false; }+ },+ stubI18n: {+ localize() {+ localizations += 1;+ if (observing) observer([externalMutation]);+ },+ },+ stubTimer: () => ({ sync() {}, showPreparing() {} }),+});+vm.runInContext(resource("gradio_app.js")+ .replace("__MINERU_I18N__", "stubI18n")+ .replace("__MINERU_STATUS_TIMER__", "stubTimer"), appContext)();+while (frames.length) frames.shift()();+const beforeRefresh = localizations;+observer([externalMutation]);+observer([externalMutation]);+assert.equal(frames.length, 1);+frames.shift()();+assert.equal(localizations, beforeRefresh + 1);+assert.equal(frames.length, 0);+assert.equal(observing, true);+observer([{ target: { nodeType: 1, closest: () => ({}) } }]);+assert.equal(frames.length, 0);