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 archived stylesheet state and enable preview links
myhlolid15d3c1b70eb
diff --git a/mineru/kit/gradio/mhtml_preview.py b/mineru/kit/gradio/mhtml_preview.pyindex fa54fc98..d0218d55 100644--- a/mineru/kit/gradio/mhtml_preview.py+++ b/mineru/kit/gradio/mhtml_preview.py@@ -220,8 +220,6 @@ def build_mhtml_preview(payload: bytes) -> str:source_uri = archive.source_context.source_uri or ""base = document.find("base", href=True)base_uri = urljoin(source_uri, str(base["href"])) if base is not None else source_uri- rewritten_styles: set[int] = set()-# 归档中的子页面常指向 CID 广告资源;预览只展示主文档,避免浏览器尝试装载子框架。for tag in document.find_all(["iframe", "frame", "frameset"]):if tag.parent is not None:@@ -236,15 +234,12 @@ def build_mhtml_preview(payload: bytes) -> str:link["href"] = resources._fallback(str(link["href"]), base_uri)continuestylesheet = resources.stylesheet(part, active=frozenset())- replacement = document.new_tag("style")- if link.get("media"):- replacement["media"] = link["media"]- replacement.string = stylesheet.replace("</style", "<\\/style")- link.replace_with(replacement)- rewritten_styles.add(id(replacement))+ # 保留 link 的 title、alternate、disabled 与 media 语义,只替换归档样式的地址。+ encoded = base64.b64encode(stylesheet.encode("utf-8")).decode("ascii")+ link["href"] = resources._charge(f"data:text/css;charset=utf-8;base64,{encoded}")for style in document.find_all("style"):- if style.string and id(style) not in rewritten_styles:+ if style.string:style.string = resources.rewrite_css(str(style.string), base_uri).replace("</style", "<\\/style")for tag in document.find_all(style=True):tag["style"] = resources._tokens(tinycss2.parse_component_value_list(str(tag["style"])), base_uri, frozenset())@@ -260,7 +255,7 @@ def build_mhtml_preview(payload: bytes) -> str:width_attribute = f' data-mineru-source-content-width="{width_hint}"' if width_hint else ""frame = (f'<iframe class="mineru-source-frame"{width_attribute} title="MHTML preview" '- 'sandbox="allow-scripts" referrerpolicy="no-referrer" '+ 'sandbox="allow-scripts allow-popups" referrerpolicy="no-referrer" 'f'srcdoc="{html.escape(prepared, quote=True)}"></iframe>')if len(frame.encode("utf-8")) > MAX_PREVIEW_BYTES:diff --git a/mineru/kit/gradio/source_preview.py b/mineru/kit/gradio/source_preview.pyindex 45b23c0d..ca83b29f 100644--- a/mineru/kit/gradio/source_preview.py+++ b/mineru/kit/gradio/source_preview.py@@ -281,7 +281,7 @@ def build_html_preview(payload: bytes) -> str:width_attribute = f' data-mineru-source-content-width="{width_hint}"' if width_hint else ""frame = (f'<iframe class="mineru-source-frame"{width_attribute} title="HTML preview" '- 'sandbox="allow-scripts" referrerpolicy="no-referrer" '+ 'sandbox="allow-scripts allow-popups" referrerpolicy="no-referrer" 'f'srcdoc="{html.escape(document, quote=True)}"></iframe>')# 外层舞台负责缩放,iframe 保留桌面布局视口,避免窄预览面板改变源页面排版。diff --git a/mineru/resources/gradio_source_preview.js b/mineru/resources/gradio_source_preview.jsindex cc9e9b1b..4e93cfd3 100644--- a/mineru/resources/gradio_source_preview.js+++ b/mineru/resources/gradio_source_preview.js@@ -87,7 +87,7 @@if (!source) return;// 更改 sandbox 只作用于下一次加载:恢复原文时禁用源脚本,避免定时导航再次运行。state.restored = true;- frame.setAttribute("sandbox", "");+ frame.setAttribute("sandbox", "allow-popups");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 e13fdf94..ec141924 100644--- a/tests/unittest/test_kit_gradio_mhtml_preview.py+++ b/tests/unittest/test_kit_gradio_mhtml_preview.py@@ -29,7 +29,7 @@ def _part(payload: str | bytes, media_type: str, location: str) -> EmailMessage:return part-def _archive(*, cycle: bool = False, root_html: str | None = None) -> bytes:+def _archive(*, cycle: bool = False, root_html: str | None = None, extra_parts: tuple[EmailMessage, ...] = ()) -> bytes:"""生成含 CSS 导入、相对资源、CID 和缺失资源的网页归档。"""root = _part(root_html@@ -50,7 +50,7 @@ def _archive(*, cycle: bool = False, root_html: str | None = None) -> bytes:font = _part(b"saved-font", "font/woff2", "https://site.test/font.woff2")message = EmailMessage(policy=policy.SMTP)message.make_related()- for part in (root, css, nested, picture, font):+ for part in (root, css, nested, picture, font, *extra_parts):message.attach(part)return message.as_bytes()@@ -58,7 +58,7 @@ def _archive(*, cycle: bool = False, root_html: str | None = None) -> bytes:def _document(payload: bytes) -> BeautifulSoup:"""读取 iframe 的 srcdoc,确认归档资源实际交给浏览器的内容。"""frame = BeautifulSoup(build_mhtml_preview(payload), "html.parser").iframe- assert frame is not None and frame.get("sandbox") == ["allow-scripts"]+ assert frame is not None and set(frame.get("sandbox")) == {"allow-scripts", "allow-popups"}return BeautifulSoup(frame["srcdoc"], "html.parser")@@ -72,8 +72,9 @@ def test_mhtml_preview_reuses_archived_assets_and_preserves_media(cycle: bool) -assert "https://site.test/missing.png 2x" in document.img["srcset"]assert document.source["srcset"].startswith("data:image/png;base64,eA== 1x, data:image/png;base64,")assert document.p["style"].count("data:image/png;base64,") == 1- assert document.find("style", media="screen") is not None- css = document.find("style", media="screen").get_text()+ stylesheet = document.find("link", media="screen")+ assert stylesheet is not None and stylesheet["href"].startswith("data:text/css;charset=utf-8;base64,")+ css = base64.b64decode(stylesheet["href"].split(",", 1)[1]).decode("utf-8")encoded = re.search(r"data:text/css;charset=utf-8;base64,([A-Za-z0-9+/=]+)", css)assert encoded is not Nonenested = base64.b64decode(encoded.group(1)).decode("utf-8")@@ -82,6 +83,28 @@ def test_mhtml_preview_reuses_archived_assets_and_preserves_media(cycle: bool) -assert "@import" not in nested+def test_mhtml_preview_preserves_inactive_stylesheet_state() -> None:+ """归档样式内嵌后仍保留备用和禁用标记,不让它们覆盖当前页面样式。"""+ document = _document(+ _archive(+ root_html="<html><head><style>p{color:red}</style>"+ '<link rel="alternate stylesheet" title="Blue" href="alt.css">'+ '<link rel="stylesheet" disabled href="disabled.css"></head>'+ "<body><p>正文</p></body></html>",+ extra_parts=(+ _part("p{color:blue}", "text/css", "https://site.test/alt.css"),+ _part("p{color:green}", "text/css", "https://site.test/disabled.css"),+ ),+ )+ )+ links = document.find_all("link", rel=lambda rel: rel and "stylesheet" in rel)+ assert len(links) == 2+ assert links[0]["rel"] == ["alternate", "stylesheet"] and links[0]["title"] == "Blue"+ assert "disabled" in links[1].attrs+ assert all(link["href"].startswith("data:text/css;charset=utf-8;base64,") for link in links)+ assert document.style.get_text() == "p{color:red}"++def test_mhtml_preview_preserves_declared_absolute_base() -> None:"""归档源地址不能插到已有绝对 base 前,以免未重写的相对脚本指向错误目录。"""document = _document(diff --git a/tests/unittest/test_kit_gradio_source_preview.cjs b/tests/unittest/test_kit_gradio_source_preview.cjsindex 5791ffbc..6e283e87 100644--- a/tests/unittest/test_kit_gradio_source_preview.cjs+++ b/tests/unittest/test_kit_gradio_source_preview.cjs@@ -47,7 +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';+let sandbox = 'allow-scripts allow-popups';const sourceViewport = {classList: {contains: (name) => name === 'mineru-source-viewport'},clientWidth: 600,@@ -72,7 +72,7 @@ const sourceFrame = {},set srcdoc(value) {restores += 1;- assert.equal(sandbox, '');+ assert.equal(sandbox, 'allow-popups');assert.equal(value, '<p>source</p>');},};diff --git a/tests/unittest/test_kit_gradio_source_preview.py b/tests/unittest/test_kit_gradio_source_preview.pyindex 41d1a256..aba43eb4 100644--- a/tests/unittest/test_kit_gradio_source_preview.py+++ b/tests/unittest/test_kit_gradio_source_preview.py@@ -117,7 +117,7 @@ def test_html_preview_injects_csp_into_head_and_keeps_content() -> None:assert root.get("class") == "mineru-source-viewport"assert root.xpath("./div[@class='mineru-source-stage']/iframe[@class='mineru-source-frame']")frame = _frame_element(markup)- assert frame.get("sandbox") == "allow-scripts"+ assert frame.get("sandbox") == "allow-scripts allow-popups"assert frame.get("referrerpolicy") == "no-referrer"assert frame.get("class") == "mineru-source-frame"document = html.fromstring(frame.get("srcdoc"))@@ -278,7 +278,7 @@ def test_html_preview_keeps_formula_scripts_for_typesetting() -> None:"</head><body><p>质能方程 \\(E=mc^2\\)</p></body></html>").encode("utf-8")frame = _frame_element(build_html_preview(payload))- assert frame.get("sandbox") == "allow-scripts"+ assert frame.get("sandbox") == "allow-scripts allow-popups"document = html.fromstring(frame.get("srcdoc"))scripts = [script for script in document.xpath("//script") if script.get("id") != "mineru-source-preview-bridge"]assert len(scripts) == 2@@ -307,7 +307,7 @@ def test_html_preview_removes_auto_navigation_but_keeps_normal_scripts_and_event'<p id="section">正文仍需展示</p></body></html>').encode("utf-8")frame = _frame_element(build_html_preview(payload))- assert frame.get("sandbox") == "allow-scripts"+ assert frame.get("sandbox") == "allow-scripts allow-popups"document = html.fromstring(frame.get("srcdoc"))assert not document.xpath("//meta[translate(@http-equiv, 'REFSH', 'refsh')='refresh']")assert document.xpath("//img")[0].get("onerror") is None