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
Correct source preview base URLs and stylesheet budgeting
myhloli35422863f82c
diff --git a/mineru/kit/gradio/mhtml_preview.py b/mineru/kit/gradio/mhtml_preview.pyindex d0218d55..f2738432 100644--- a/mineru/kit/gradio/mhtml_preview.py+++ b/mineru/kit/gradio/mhtml_preview.py@@ -62,14 +62,14 @@ class _PreviewResources:"""使用 DocVortex 公开索引解析 CID、绝对或相对资源地址。"""return self.archive.find(reference, base_href=base_uri)- def _data_uri(self, part: ArchivePart) -> str:- """按 MIME 类型缓存资源字节;每次插入仍独立计入输出预算。"""+ def _data_uri(self, part: ArchivePart, *, charge: bool) -> str:+ """按 MIME 类型缓存资源字节;只对直接写入预览文档的地址计费。"""if part not in self.embedded:payload = self.archive.decode(part)self.embedded[part] = f"data:{part.media_type};base64,{base64.b64encode(payload).decode('ascii')}"- return self._charge(self.embedded[part])+ return self._charge(self.embedded[part]) if charge else self.embedded[part]- def resource_url(self, reference: str, base_uri: str) -> str:+ def resource_url(self, reference: str, base_uri: str, *, charge: bool = True) -> str:"""有归档资源时嵌入,缺失时交由浏览器请求正确的远端地址。"""part = self._part(reference, base_uri)if part is not None:@@ -80,7 +80,7 @@ class _PreviewResources:"application/vnd.ms-fontobject","application/octet-stream",}:- return self._data_uri(part)+ return self._data_uri(part, charge=charge)except MhtmlParseError:passreturn self._fallback(reference, base_uri)@@ -122,7 +122,7 @@ class _PreviewResources:if part in active or len(active) >= MAX_CSS_IMPORT_DEPTH:return ""if part in self.stylesheets:- return self._charge(self.stylesheets[part])+ return self.stylesheets[part]if part.media_type != "text/css":return ""try:@@ -136,7 +136,8 @@ class _PreviewResources:css = payload.decode("utf-8-sig", errors="replace")rewritten = self.rewrite_css(css, part.source_uri, active | {part})self.stylesheets[part] = rewritten- return self._charge(rewritten)+ # CSS 原文不会直接输出,调用方只对最终写入文档的数据地址计费。+ return rewrittendef _css_reference(self, token: object) -> str | None:"""从 CSS 词法 token 中读取 URL 或引号字符串。"""@@ -159,7 +160,7 @@ class _PreviewResources:for token in tokens:reference = self._css_reference(token)if reference is not None and getattr(token, "type", "") != "string":- pieces.append(self._css_url(self.resource_url(reference, base_uri)))+ pieces.append(self._css_url(self.resource_url(reference, base_uri, charge=False)))elif getattr(token, "type", "") == "function":pieces.append(f"{token.name}({self._tokens(token.arguments, base_uri, active)})")elif getattr(token, "type", "") in {"() block", "[] block", "{} block"}:@@ -188,7 +189,7 @@ class _PreviewResources:if not nested:continueencoded = base64.b64encode(nested.encode()).decode("ascii")- target = self._charge(f"data:text/css;charset=utf-8;base64,{encoded}")+ target = f"data:text/css;charset=utf-8;base64,{encoded}"else:target = self._fallback(reference, base_uri)if not target:@@ -240,16 +241,18 @@ def build_mhtml_preview(payload: bytes) -> str:for style in document.find_all("style"):if style.string:- style.string = resources.rewrite_css(str(style.string), base_uri).replace("</style", "<\\/style")+ rewritten = resources.rewrite_css(str(style.string), base_uri).replace("</style", "<\\/style")+ style.string = resources._charge(rewritten)for tag in document.find_all(style=True):- tag["style"] = resources._tokens(tinycss2.parse_component_value_list(str(tag["style"])), base_uri, frozenset())+ rewritten = resources._tokens(tinycss2.parse_component_value_list(str(tag["style"])), base_uri, frozenset())+ tag["style"] = resources._charge(rewritten)for tag in document.find_all(["img", "source"]):if tag.get("src"):tag["src"] = resources.resource_url(str(tag["src"]), base_uri)if tag.get("srcset"):tag["srcset"] = resources.rewrite_srcset(str(tag["srcset"]), base_uri)- prepared, width_hint = _prepare_source_html_preview(str(document), source_base_url=source_uri, csp_meta=_MHTML_CSP_META)+ prepared, width_hint = _prepare_source_html_preview(str(document), source_base_url=base_uri, csp_meta=_MHTML_CSP_META)if len(prepared.encode("utf-8")) > MAX_PREVIEW_BYTES:raise ValueError("MHTML preview exceeds 64 MiB")width_attribute = f' data-mineru-source-content-width="{width_hint}"' if width_hint else ""diff --git a/mineru/kit/gradio/source_preview.py b/mineru/kit/gradio/source_preview.pyindex fb18f9d0..6a09a600 100644--- a/mineru/kit/gradio/source_preview.py+++ b/mineru/kit/gradio/source_preview.py@@ -9,7 +9,7 @@ import jsonimport refrom collections.abc import Callablefrom pathlib import Path-from urllib.parse import urlsplit+from urllib.parse import urljoin, urlsplitfrom bs4 import BeautifulSoupfrom loguru import logger@@ -216,7 +216,7 @@ def _source_base_url(soup: BeautifulSoup) -> tuple[str | None, bool]:if existing is not None:try:if urlsplit(str(existing["href"])).scheme.lower() in {"http", "https"}:- return None, True+ return str(existing["href"]), Trueexcept ValueError:passexisting.decompose()@@ -258,26 +258,39 @@ def _prepare_source_html_preview(for tag in soup.find_all(attrs={"referrerpolicy": True}):tag["referrerpolicy"] = "no-referrer"- for link in soup.find_all("a", href=True):- try:- scheme = urlsplit(str(link["href"])).scheme.lower()- except ValueError:- continue- if scheme not in {"http", "https"}:- continue- link["target"] = "_blank"- link["rel"] = list(dict.fromkeys([*link.get("rel", []), "noopener", "noreferrer"]))-width_hint = _source_viewport_width_hint(soup)hint = f'<meta name="mineru-source-preview-width" content="{width_hint}">' if width_hint else ""+ original_base = soup.find("base", href=True)+ try:+ had_relative_base = original_base is not None and urlsplit(str(original_base["href"])).scheme.lower() not in {+ "http",+ "https",+ }+ except ValueError:+ had_relative_base = original_base is not Nonebase_url, has_absolute_base = _source_base_url(soup)- if base_url is None and not has_absolute_base and source_base_url:+ if (base_url is None or had_relative_base) and not has_absolute_base and source_base_url:try:if urlsplit(source_base_url).scheme.lower() in {"http", "https"}:base_url = source_base_urlexcept ValueError:pass- base = f'<base href="{html.escape(base_url, quote=True)}">' if base_url is not None else ""+ for link in soup.find_all("a", href=True):+ href = str(link["href"])+ if not href or href.startswith("#"):+ continue+ try:+ scheme = urlsplit(href).scheme.lower()+ resolved = urljoin(base_url, href) if not scheme and base_url else href+ if urlsplit(resolved).scheme.lower() not in {"http", "https"}:+ continue+ except ValueError:+ continue+ link["href"] = resolved+ link["target"] = "_blank"+ link["rel"] = list(dict.fromkeys([*link.get("rel", []), "noopener", "noreferrer"]))++ base = f'<base href="{html.escape(base_url, quote=True)}">' if base_url is not None and not has_absolute_base else ""prepared = _inject_head(str(soup), f"{_REFERRER_META}{hint}{base}{csp_meta}{_SOURCE_PREVIEW_BRIDGE}")return prepared, width_hintdiff --git a/tests/unittest/test_kit_gradio_mhtml_preview.py b/tests/unittest/test_kit_gradio_mhtml_preview.pyindex ec141924..dc2b9a80 100644--- a/tests/unittest/test_kit_gradio_mhtml_preview.py+++ b/tests/unittest/test_kit_gradio_mhtml_preview.py@@ -117,6 +117,42 @@ def test_mhtml_preview_preserves_declared_absolute_base() -> None:assert document.find("script", src=True)["src"] == "runtime.js"+def test_mhtml_preview_resolves_declared_relative_base() -> None:+ """相对 base 与归档资源使用同一目录,未归档脚本和链接也能按该目录加载。"""+ document = _document(+ _archive(+ root_html='<html><head><base href="assets/">'+ '<link rel="canonical" href="https://site.test/other/page">'+ '<script src="runtime.js"></script>'+ '<link rel="stylesheet" href="missing.css"></head>'+ '<body><a href="next.html">next</a></body></html>'+ )+ )+ assert [base["href"] for base in document.find_all("base")] == ["https://site.test/assets/"]+ assert document.find("script", src=True)["src"] == "runtime.js"+ assert document.find("link", rel="stylesheet")["href"] == "https://site.test/assets/missing.css"+ assert document.a["href"] == "https://site.test/assets/next.html"+ assert document.a["target"] == "_blank"++[email protected]("nested", [False, True])+def test_mhtml_preview_counts_emitted_stylesheet_once(monkeypatch: pytest.MonkeyPatch, nested: bool) -> None:+ """较大的归档 CSS 及嵌套导入只按最终数据地址计入预览预算。"""+ from mineru.kit.gradio import mhtml_preview++ stylesheet = "parent.css" if nested else "large.css"+ extra_parts = (_part("a{color:red}" * 2000, "text/css", "https://site.test/large.css"),)+ if nested:+ extra_parts += (_part('@import "large.css";', "text/css", "https://site.test/parent.css"),)+ payload = _archive(+ root_html=f'<html><head><link rel="stylesheet" href="{stylesheet}"></head><body>ok</body></html>',+ extra_parts=extra_parts,+ )+ preview = build_mhtml_preview(payload)+ monkeypatch.setattr(mhtml_preview, "MAX_PREVIEW_BYTES", len(preview.encode("utf-8")))+ assert build_mhtml_preview(payload) == preview++@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.py b/tests/unittest/test_kit_gradio_source_preview.pyindex aba43eb4..9221fdc3 100644--- a/tests/unittest/test_kit_gradio_source_preview.py+++ b/tests/unittest/test_kit_gradio_source_preview.py@@ -359,6 +359,44 @@ def test_html_preview_restores_source_base_from_canonical_or_existing_base() ->assert [base.get("href") for base in existing.xpath("//head/base")] == ["https://cdn.example.test/root/"]+ ("head", "expected_root", "expected_next"),+ [+ (+ '<link rel="canonical" href="https://example.test/articles/one">',+ "https://example.test/docs",+ "https://example.test/articles/next.html",+ ),+ (+ '<base href="https://cdn.example.test/root/">',+ "https://cdn.example.test/docs",+ "https://cdn.example.test/root/next.html",+ ),+ ],+)+def test_html_preview_opens_relative_links_with_resolved_base(head: str, expected_root: str, expected_next: str) -> None:+ """有远端基址时,相对及协议相对链接在新窗口打开,页内锚点仍留在原文。"""+ payload = (+ f"<html><head>{head}</head><body>"+ '<a id="root" href="/docs">root</a><a id="next" href="next.html">next</a>'+ '<a id="protocol" href="//other.test/page">protocol</a>'+ '<a id="fragment" href="#section">fragment</a>'+ '<a id="mail" href="mailto:[email protected]">mail</a>'+ '<p id="section">section</p></body></html>'+ ).encode()+ document = html.fromstring(_frame_document(build_html_preview(payload)))+ assert document.get_element_by_id("root").get("href") == expected_root+ assert document.get_element_by_id("next").get("href") == expected_next+ assert document.get_element_by_id("protocol").get("href") == "https://other.test/page"+ for anchor_id in ("root", "next", "protocol"):+ link = document.get_element_by_id(anchor_id)+ assert link.get("target") == "_blank"+ assert {"noopener", "noreferrer"} <= set(link.get("rel").split())+ assert document.get_element_by_id("fragment").get("href") == "#section"+ assert document.get_element_by_id("fragment").get("target") is None+ assert document.get_element_by_id("mail").get("target") is None++def test_html_preview_decodes_declared_charset() -> None:"""按头部 charset 声明解码 GBK 等存量文档,未知编码回退 UTF-8 替换。"""payload = '<html><head><meta charset="gbk"></head><body><p>中文内容</p></body></html>'.encode("gbk")