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): preserve MHTML base and stop preview redirect loops
myhlolid59cf02e1ec5
diff --git a/mineru/kit/gradio/source_preview.py b/mineru/kit/gradio/source_preview.pyindex b62bd0c6..45b23c0d 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 () {+ if (window.navigation && typeof window.navigation.addEventListener === "function") {+ window.navigation.addEventListener("navigate", function (event) {+ // 保留页内锚点和 History API;可取消的整页导航不离开原文预览。+ if (event.cancelable && !event.destination.sameDocument) event.preventDefault();+ });+ }+function explicitViewportWidth() {var injected = document.querySelector('meta[name="mineru-source-preview-width"]');var injectedWidth = injected ? Number(injected.getAttribute("content")) : 0;@@ -196,13 +203,13 @@ def _source_viewport_width_hint(soup: BeautifulSoup) -> int:return 0-def _source_base_url(soup: BeautifulSoup) -> str | None:- """从已有 base、canonical 或 og:url 中恢复网页资源的原始解析基址。"""+def _source_base_url(soup: BeautifulSoup) -> tuple[str | None, bool]:+ """从已有 base、canonical 或 og:url 恢复基址,并标记应保留的绝对 base。"""existing = soup.find("base", href=True)if existing is not None:try:if urlsplit(str(existing["href"])).scheme.lower() in {"http", "https"}:- return None+ return None, Trueexcept ValueError:passexisting.decompose()@@ -222,10 +229,10 @@ def _source_base_url(soup: BeautifulSoup) -> str | None:continuetry:if urlsplit(str(candidate)).scheme.lower() in {"http", "https"}:- return str(candidate)+ return str(candidate), Falseexcept ValueError:continue- return None+ return None, Falsedef _prepare_source_html_preview(@@ -256,8 +263,8 @@ def _prepare_source_html_preview(width_hint = _source_viewport_width_hint(soup)hint = f'<meta name="mineru-source-preview-width" content="{width_hint}">' if width_hint else ""- base_url = _source_base_url(soup)- if base_url is None and source_base_url:+ base_url, has_absolute_base = _source_base_url(soup)+ if base_url is None and not has_absolute_base and source_base_url:try:if urlsplit(source_base_url).scheme.lower() in {"http", "https"}:base_url = source_base_urldiff --git a/mineru/resources/gradio_source_preview.js b/mineru/resources/gradio_source_preview.jsindex 7efd5d52..cc9e9b1b 100644--- a/mineru/resources/gradio_source_preview.js+++ b/mineru/resources/gradio_source_preview.js@@ -23,7 +23,7 @@"&": "&", "<": "<", ">": ">", '"': """, "'": "'",})[character]);- // 源 HTML 可以执行自身脚本,但初始化完成后若 iframe 又发生整页导航,则恢复原始 srcdoc。+ // 源 HTML 可以执行自身脚本;导航事件可取消时直接阻止整页跳转,旧浏览器回退到静态预览。// HTML 的桌面视口缩放只作用于 iframe 外层舞台:WebKit 直接 transform iframe 时会出现// 内部页面布局正确、但绘制层只更新局部区域的现象,典型表现就是大块空白和正文被截断。const navigationGuardKey = `${key}NavigationGuard`;@@ -79,16 +79,15 @@fitSourceFrame(frame);const state = states.get(frame);if (!state) {- states.set(frame, {restoring: false});- return;- }- if (state.restoring) {- state.restoring = false;+ states.set(frame, {restored: false});return;}+ if (state.restored) return;const source = frame.getAttribute?.("srcdoc");if (!source) return;- state.restoring = true;+ // 更改 sandbox 只作用于下一次加载:恢复原文时禁用源脚本,避免定时导航再次运行。+ state.restored = true;+ frame.setAttribute("sandbox", "");frame.srcdoc = source;}, true);window[navigationGuardKey] = true;diff --git a/tests/unittest/test_kit_gradio_mhtml_preview.py b/tests/unittest/test_kit_gradio_mhtml_preview.pyindex c97ad198..e13fdf94 100644--- a/tests/unittest/test_kit_gradio_mhtml_preview.py+++ b/tests/unittest/test_kit_gradio_mhtml_preview.py@@ -29,14 +29,17 @@ def _part(payload: str | bytes, media_type: str, location: str) -> EmailMessage:return part-def _archive(*, cycle: bool = False) -> bytes:+def _archive(*, cycle: bool = False, root_html: str | None = None) -> bytes:"""生成含 CSS 导入、相对资源、CID 和缺失资源的网页归档。"""root = _part(- '<html><head><title>中文预览</title><link rel="stylesheet" href="style.css" media="screen">'- '<style>.inline{background:url("pic.png")}</style></head>'- '<body><iframe src="cid:ad-page"></iframe><img src="pic.png" srcset="pic.png 1x, missing.png 2x">'- '<picture><source srcset="data:image/png;base64,eA== 1x, pic.png 2x"></picture>'- '<p style="background:url(pic.png)">正文</p></body></html>',+ root_html+ or (+ '<html><head><title>中文预览</title><link rel="stylesheet" href="style.css" media="screen">'+ '<style>.inline{background:url("pic.png")}</style></head>'+ '<body><iframe src="cid:ad-page"></iframe><img src="pic.png" srcset="pic.png 1x, missing.png 2x">'+ '<picture><source srcset="data:image/png;base64,eA== 1x, pic.png 2x"></picture>'+ '<p style="background:url(pic.png)">正文</p></body></html>'+ ),"text/html","https://site.test/article",)@@ -79,6 +82,18 @@ def test_mhtml_preview_reuses_archived_assets_and_preserves_media(cycle: bool) -assert "@import" not in nested+def test_mhtml_preview_preserves_declared_absolute_base() -> None:+ """归档源地址不能插到已有绝对 base 前,以免未重写的相对脚本指向错误目录。"""+ document = _document(+ _archive(+ root_html='<html><head><base href="https://cdn.site.test/assets/">'+ '<script src="runtime.js"></script></head><body><p>正文</p></body></html>'+ )+ )+ assert [base["href"] for base in document.find_all("base")] == ["https://cdn.site.test/assets/"]+ assert document.find("script", src=True)["src"] == "runtime.js"++@pytest.mark.parametrize("name", ["page.mhtml", "page.MHT"])def test_mhtml_preview_receipt_and_flash_parse(tmp_path: Path, name: str) -> None:"""两个后缀共用预览和 Flash 解析,回执仍带请求标识。"""diff --git a/tests/unittest/test_kit_gradio_source_preview.cjs b/tests/unittest/test_kit_gradio_source_preview.cjsindex e74c1e7b..5791ffbc 100644--- a/tests/unittest/test_kit_gradio_source_preview.cjs+++ b/tests/unittest/test_kit_gradio_source_preview.cjs@@ -47,6 +47,7 @@ assert.match(guardedMarkup, new RegExp(`data-mineru-source-preview-id="${htmlTicassert.equal(typeof listeners.load, 'function');let restores = 0;+let sandbox = 'allow-scripts';const sourceViewport = {classList: {contains: (name) => name === 'mineru-source-viewport'},clientWidth: 600,@@ -65,8 +66,13 @@ const sourceFrame = {style: {},contentWindow: {},getAttribute: (name) => name === 'srcdoc' ? '<p>source</p>' : null,+ setAttribute(name, value) {+ assert.equal(name, 'sandbox');+ sandbox = value;+ },set srcdoc(value) {restores += 1;+ assert.equal(sandbox, '');assert.equal(value, '<p>source</p>');},};@@ -97,7 +103,7 @@ assert.equal(restores, 1);listeners.load({target: sourceFrame});assert.equal(restores, 1);listeners.load({target: sourceFrame});-assert.equal(restores, 2);+assert.equal(restores, 1);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'};