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(gradio): recover source preview from pre-load redirects
myhlolibbdaf52bac90
diff --git a/mineru/kit/gradio/source_preview.py b/mineru/kit/gradio/source_preview.pyindex ca83b29f..fb18f9d0 100644--- a/mineru/kit/gradio/source_preview.py+++ b/mineru/kit/gradio/source_preview.py@@ -46,6 +46,13 @@ _NAVIGATION_HANDLER_PATTERN = re.compile(# 离屏 slide 计入文档宽度,导致虚拟视口被错误放大到数千像素。_SOURCE_PREVIEW_BRIDGE = """<script id="mineru-source-preview-bridge">(function () {+ // 父页面只能通过消息确认 opaque-origin iframe 仍停留在原文,不能直接读取其 location。+ addEventListener("message", function (event) {+ var data = event.data;+ if (event.source !== parent || !data || data.type !== "mineru-source-preview-probe") return;+ parent.postMessage({type: "mineru-source-preview-probe-ack", probe: data.probe}, "*");+ });+if (window.navigation && typeof window.navigation.addEventListener === "function") {window.navigation.addEventListener("navigate", function (event) {// 保留页内锚点和 History API;可取消的整页导航不离开原文预览。diff --git a/mineru/resources/gradio_source_preview.js b/mineru/resources/gradio_source_preview.jsindex 4e93cfd3..b079cabd 100644--- a/mineru/resources/gradio_source_preview.js+++ b/mineru/resources/gradio_source_preview.js@@ -23,11 +23,13 @@"&": "&", "<": "<", ">": ">", '"': """, "'": "'",})[character]);- // 源 HTML 可以执行自身脚本;导航事件可取消时直接阻止整页跳转,旧浏览器回退到静态预览。+ // 源 HTML 可以执行自身脚本;可取消的整页导航直接阻止,其余导航探测后静态恢复。// HTML 的桌面视口缩放只作用于 iframe 外层舞台:WebKit 直接 transform iframe 时会出现// 内部页面布局正确、但绘制层只更新局部区域的现象,典型表现就是大块空白和正文被截断。const navigationGuardKey = `${key}NavigationGuard`;const sizeGuardKey = `${key}SizeGuard`;+ const navigationStates = new WeakMap();+ let probeSequence = 0;const fitSourceFrame = (frame, reportedWidth = null) => {if (!frame?.classList?.contains("mineru-source-frame")) return;const stage = frame.parentElement?.classList?.contains("mineru-source-stage") ? frame.parentElement : null;@@ -67,9 +69,18 @@new ResizeObserver(() => fitSourceFrame(frame)).observe(viewport);}};+ // 跳转后只恢复一次原文,并禁用源脚本,避免恢复本身再次触发跳转。+ const restoreSourceFrame = (frame, state) => {+ if (state.restored) return;+ const source = frame.getAttribute?.("srcdoc");+ if (!source) return;+ state.restored = true;+ state.probe = null;+ frame.setAttribute("sandbox", "allow-popups");+ frame.srcdoc = source;+ };const installNavigationGuard = () => {if (window[navigationGuardKey] || typeof document === "undefined") return;- const states = new WeakMap();document.addEventListener("load", (event) => {const frame = event.target;if (!frame || frame.tagName !== "IFRAME" || !frame.classList?.contains("mineru-source-frame")) return;@@ -77,29 +88,46 @@if (!frameId || frameId !== String(window[key])) return;observeSourceFrame(frame);fitSourceFrame(frame);- const state = states.get(frame);+ let state = navigationStates.get(frame);if (!state) {- states.set(frame, {restored: false});+ state = {restored: false, verified: false, probe: null};+ navigationStates.set(frame, state);+ // OFD 等无脚本预览不需要探测;HTML/MHTML 首次 load 可能已是重定向目标。+ if (!frame.getAttribute?.("sandbox")?.split(/\s+/).includes("allow-scripts")) {+ state.verified = true;+ return;+ }+ const probe = String(++probeSequence);+ state.probe = probe;+ frame.contentWindow?.postMessage({type: "mineru-source-preview-probe", probe}, "*");+ setTimeout(() => {+ if (!state.verified && state.probe === probe && frame.dataset?.mineruSourcePreviewId === String(window[key])) {+ restoreSourceFrame(frame, state);+ }+ }, 250);return;}- if (state.restored) return;- const source = frame.getAttribute?.("srcdoc");- if (!source) return;- // 更改 sandbox 只作用于下一次加载:恢复原文时禁用源脚本,避免定时导航再次运行。- state.restored = true;- frame.setAttribute("sandbox", "allow-popups");- frame.srcdoc = source;+ restoreSourceFrame(frame, state);}, true);window[navigationGuardKey] = true;};const installSizeGuard = () => {if (window[sizeGuardKey] || typeof window.addEventListener !== "function") return;window.addEventListener("message", (event) => {- if (event.data?.type !== "mineru-source-preview-size") return;+ const type = event.data?.type;+ if (type !== "mineru-source-preview-size" && type !== "mineru-source-preview-probe-ack") return;for (const frame of document.querySelectorAll?.("iframe.mineru-source-frame") || []) {if (frame.contentWindow !== event.source) continue;const frameId = frame.dataset?.mineruSourcePreviewId;if (!frameId || frameId !== String(window[key])) return;+ if (type === "mineru-source-preview-probe-ack") {+ const state = navigationStates.get(frame);+ if (state && !state.restored && state.probe === event.data.probe) {+ state.verified = true;+ state.probe = null;+ }+ return;+ }observeSourceFrame(frame);fitSourceFrame(frame, event.data.width);return;diff --git a/tests/unittest/test_kit_gradio_source_preview.cjs b/tests/unittest/test_kit_gradio_source_preview.cjsindex 6e283e87..823d5a18 100644--- a/tests/unittest/test_kit_gradio_source_preview.cjs+++ b/tests/unittest/test_kit_gradio_source_preview.cjs@@ -6,6 +6,7 @@ let sequence = 0;const listeners = {};const windowListeners = {};const sourceFrames = [];+const timers = [];const browserWindow = {location: {href: 'https://demo.example.test/mineru/', origin: 'https://demo.example.test'},addEventListener(type, listener) {@@ -28,6 +29,7 @@ const preview = vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../../mURL,URLSearchParams,crypto: {randomUUID: () => String(++sequence)},+ setTimeout: (callback) => timers.push(callback),});const first = JSON.parse(preview('begin', {path: '/first.html'})[0]);const second = JSON.parse(preview('begin', {path: '/second.ofd'})[0]);@@ -48,6 +50,7 @@ assert.equal(typeof listeners.load, 'function');let restores = 0;let sandbox = 'allow-scripts allow-popups';+let probe = null;const sourceViewport = {classList: {contains: (name) => name === 'mineru-source-viewport'},clientWidth: 600,@@ -64,8 +67,14 @@ const sourceFrame = {dataset: {mineruSourcePreviewId: String(htmlTicket.id), mineruSourceContentWidth: "1200"},parentElement: sourceStage,style: {},- contentWindow: {},- getAttribute: (name) => name === 'srcdoc' ? '<p>source</p>' : null,+ contentWindow: {+ postMessage(message, target) {+ assert.equal(target, '*');+ assert.equal(message.type, 'mineru-source-preview-probe');+ probe = message.probe;+ },+ },+ getAttribute: (name) => name === 'srcdoc' ? '<p>source</p>' : name === 'sandbox' ? sandbox : null,setAttribute(name, value) {assert.equal(name, 'sandbox');sandbox = value;@@ -79,6 +88,13 @@ const sourceFrame = {sourceFrames.push(sourceFrame);listeners.load({target: sourceFrame});assert.equal(restores, 0);+assert.ok(probe);+windowListeners.message({+ source: sourceFrame.contentWindow,+ data: {type: 'mineru-source-preview-probe-ack', probe},+});+timers.shift()();+assert.equal(restores, 0);assert.equal(sourceFrame.style.width, '100%');assert.equal(sourceFrame.style.height, '100%');assert.equal(sourceFrame.style.transform, '');@@ -100,11 +116,59 @@ assert.equal(sourceStage.style.transformOrigin, '0 0');assert.equal(sourceStage.style.transform, 'scale(0.5)');listeners.load({target: sourceFrame});assert.equal(restores, 1);++// 首次 load 已经来自重定向目标时,探测超时后恢复一次静态原文。+const immediateTicket = JSON.parse(preview('begin', {path: '/immediate.html'})[0]);+let immediateRestores = 0;+let immediateSandbox = 'allow-scripts allow-popups';+const immediateFrame = {+ tagName: 'IFRAME',+ classList: {contains: (name) => name === 'mineru-source-frame'},+ dataset: {mineruSourcePreviewId: String(immediateTicket.id)},+ parentElement: sourceStage,+ style: {},+ contentWindow: {postMessage: (message) => assert.equal(message.type, 'mineru-source-preview-probe')},+ getAttribute: (name) => name === 'srcdoc' ? '<p>immediate</p>' : name === 'sandbox' ? immediateSandbox : null,+ setAttribute(name, value) {+ assert.equal(name, 'sandbox');+ immediateSandbox = value;+ },+ set srcdoc(value) {+ immediateRestores += 1;+ assert.equal(value, '<p>immediate</p>');+ assert.equal(immediateSandbox, 'allow-popups');+ },+};+sourceFrames.push(immediateFrame);+listeners.load({target: immediateFrame});+assert.equal(immediateRestores, 0);+timers.shift()();+assert.equal(immediateRestores, 1);+listeners.load({target: immediateFrame});+assert.equal(immediateRestores, 1);listeners.load({target: sourceFrame});assert.equal(restores, 1);listeners.load({target: sourceFrame});assert.equal(restores, 1);+// 无源脚本的 OFD 首次加载无需探测,也不能额外重载。+const ofdTicket = JSON.parse(preview('begin', {path: '/static.ofd'})[0]);+const ofdFrame = {+ tagName: 'IFRAME',+ classList: {contains: (name) => name === 'mineru-source-frame'},+ dataset: {mineruSourcePreviewId: String(ofdTicket.id)},+ parentElement: sourceStage,+ style: {},+ contentWindow: {postMessage: () => assert.fail('OFD must not be probed')},+ getAttribute: (name) => name === 'sandbox' ? '' : name === 'srcdoc' ? '<p>ofd</p>' : null,+ set srcdoc(_value) {+ assert.fail('OFD must not reload on its first load');+ },+};+sourceFrames.push(ofdFrame);+listeners.load({target: ofdFrame});+assert.equal(timers.length, 0);+const epub = {path: '/tmp/中文 book.epub', url: '/gradio_api/file=/tmp/中文 book.epub'};const viewer = {path: '/tmp/reader.html', url: '/gradio_api/file=/tmp/reader.html'};const epubTicket = JSON.parse(preview('begin', epub)[0]);