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
Refactor download formats and enhance HTML preview functionality
myhlolif58b7d4e72c2
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.mdindex da83d7bb..4f3d28bb 100644--- a/docs/next/cli/mineru-kit-gradio.md+++ b/docs/next/cli/mineru-kit-gradio.md@@ -96,13 +96,11 @@ Gradio 首先发现 `/v1/health` 和 `/v1/tiers`,然后通过 `MinerUApiParser页面只展示:-- Markdown 渲染;-- Markdown 源码;-- Structured Content 源码。+- Markdown 渲染:实际展示 HTML renderer 的完整输出,保留表格、公式和代码高亮。-下载图标位于右侧结果栏的标签行最右端,鼠标悬停或键盘聚焦即可展开菜单。菜单包含 ZIP、HTML、DOCX、LaTeX bundle、EPUB 和 PDF。HTML、DOCX、EPUB、PDF 和 LaTeX 不作为 API job 输出请求,而是在用户点击菜单后从本次保存的 Middle JSON 按需渲染。LaTeX 下载包包含 `.tex` 与 `images/`,可交给 XeLaTeX 使用;Gradio 不自动执行 TeX 编译。+下载图标位于右侧结果栏的标签行最右端,鼠标悬停或键盘聚焦即可展开菜单。菜单包含 Markdown、JSON、HTML、DOCX、LaTeX、EPUB 和 PDF。下载文件由 Gradio 从本次保存的结果按需生成,不新增 API job 输出格式。Markdown 和 JSON 分别下载独立 ZIP,根目录放置同名 `.md` 或 `.json`,图片放在 `images/`,正文及 JSON 图片字段使用相对路径。JSON 内容使用 Structured Content,不包含 Middle JSON。LaTeX 下载包包含 `.tex` 与 `images/`,可交给 XeLaTeX 使用;Gradio 不自动执行 TeX 编译。预览和下载的单个 HTML 均使用当前 Gradio 服务的图片 HTTP 链接,不嵌入 base64;链接可用性取决于当前服务和任务文件。-每次选择格式后,按钮会显示“准备中”,文件就绪后自动开始下载,无需再次点击。再次下载同一格式复用已有文件;生成失败时显示错误并允许重试。清除、更换文件或重新解析会使旧下载请求失效。+每次选择格式后,按钮会显示“准备中”,文件就绪后自动开始下载,无需再次点击。再次下载时,HTML 根据当前访问地址重新生成,其他格式复用已有文件;生成失败时显示错误并允许重试。清除、更换文件或重新解析会使旧下载请求失效。每次解析的文件保存在独立的 `output-dir/gradio/<run-id>/` 目录,包含源文件、Middle JSON、基础文本产物以及可选的 `origin.pdf`、`layout.pdf` 和图片资源。路径只向 Gradio 暴露在配置的 output root 内。diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 5ad20514..519a1872 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -17,7 +17,7 @@ from ...errors import MineruErrorfrom ...filetypes import FLASH_ONLY_PARSE_EXTENSIONS, IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PARSEABLE_EXTENSIONS, PDF_EXTENSIONSfrom ...types import TIERS, Tierfrom ...utils.stdio import configure_standard_streams-from .artifacts import RunArtifacts, markdown_for_gradio, persist_parse_result, render_download+from .artifacts import RunArtifacts, persist_parse_result, render_download, render_html_previewfrom .client import (GradioArtifactClient,ManagedLocalApiServer,@@ -39,10 +39,11 @@ from .status import ()_DOWNLOAD_FORMATS: tuple[tuple[str, str], ...] = (- ("zip", "ZIP"),+ ("markdown", "Markdown"),+ ("json", "JSON"),("html", "HTML"),("docx", "DOCX"),- ("latex", "LaTeX bundle"),+ ("latex", "LaTeX"),("epub", "EPUB"),("pdf", "PDF"),)@@ -247,7 +248,6 @@ def build_gradio_app(raise ValueError("V1 API server did not advertise any parsing tier")preferred_tier = _default_tier(capabilities)file_types = _supported_file_types()- markdown_copy_kwargs = {"buttons": ["copy"]} if _gradio_major_version(gr) >= 6 else {"show_copy_button": True}app_css = _resource_text("gradio_app.css") + _KIT_MENU_CSSi18n = gr.I18n(**translations())app_js = _resource_text("gradio_app.js").replace(@@ -376,32 +376,10 @@ def build_gradio_app(with gr.Column(scale=4, min_width=340, elem_classes=["mineru-kit-results", "mineru-markdown-pane"]):with gr.Tabs(elem_classes=["mineru-markdown-tabs"]):with gr.Tab(i18n("mineru.markdown_rendered")):- markdown_output = gr.Markdown(+ html_output = gr.HTML(value="",- height=775,- line_breaks=True,- latex_delimiters=_latex_delimiters(latex_delimiters_type),- **markdown_copy_kwargs,elem_classes=["mineru-markdown-output"],)- with gr.Tab(i18n("mineru.markdown_source")):- markdown_source = gr.Code(- value="",- label=i18n("mineru.markdown_source"),- language="markdown",- lines=28,- interactive=False,- elem_classes=["mineru-markdown-text"],- )- with gr.Tab(i18n("mineru.structured_source")):- structured_source = gr.Code(- value="",- label=i18n("mineru.structured_source"),- language="json",- lines=28,- interactive=False,- elem_classes=["mineru-structured-content"],- )with gr.Column(scale=0, min_width=0, elem_classes=["mineru-kit-download-menu"]):gr.HTML(_DOWNLOAD_ICON_HTML, elem_classes=["mineru-kit-download-trigger"])with gr.Column(@@ -435,9 +413,7 @@ def build_gradio_app(input_file,page_range,force_ocr,- markdown_output,- markdown_source,- structured_source,+ html_output,pdf_preview,image_preview,office_preview,@@ -448,7 +424,7 @@ def build_gradio_app(def update_file_preview(file_path: str | None, request: object | None = None) -> tuple[Any, ...]:"""切换源文件预览,并清除上一份文档的结果与下载状态。"""- reset_result = (_status_html(_DEFAULT_STATUS), "", "", "", None, *_download_updates(gr, interactive=False))+ reset_result = (_status_html(_DEFAULT_STATUS), "", None, *_download_updates(gr, interactive=False))if not file_path:return (_pdf_preview_update(gr, None),@@ -560,9 +536,7 @@ def build_gradio_app(office_preview,generic_preview,status_panel,- markdown_output,- markdown_source,- structured_source,+ html_output,artifact_state,active_run_id,*download_buttons.values(),@@ -617,13 +591,11 @@ def build_gradio_app(force_ocr: bool = False,request: object | None = None,) -> Any:- """执行单文件 V1 解析并流式更新状态与三个结果标签。"""+ """执行单文件 V1 解析并流式更新状态与 HTML 结果。"""# 开始或失败只重置结果与下载;预览内容、显隐和浏览位置保持不变。reset_result = (_status_html(_DEFAULT_STATUS),"",- "",- "",*(gr.skip() for _ in range(4)),None,*_download_updates(gr, interactive=False),@@ -633,22 +605,22 @@ def build_gradio_app(returnsource_path = Path(file_path).resolve()if not source_path.is_file():- yield (_status_html("Failed: input file does not exist"), "", "", "", *reset_result[4:])+ yield (_status_html("Failed: input file does not exist"), *reset_result[1:])returnsuffix = _file_suffix(source_path)if suffix not in PARSEABLE_EXTENSIONS:- yield (_status_html(f"Failed: unsupported file type '.{suffix}'"), "", "", "", *reset_result[4:])+ yield (_status_html(f"Failed: unsupported file type '.{suffix}'"), *reset_result[1:])returntry:selected_tier = _tier_for_position(tier_position, tier_choices)except ValueError as exc:- yield (_status_html(f"Failed: {exc}"), "", "", "", *reset_result[4:])+ yield (_status_html(f"Failed: {exc}"), *reset_result[1:])returnif suffix in FLASH_ONLY_PARSE_EXTENSIONS:# 提交端独立约束有效档位,避免事件 API 或前端残留值绕过 Flash 锁定。if "flash" not in tier_choices:message = "Failed: tier_unavailable: 该格式仅支持 Flash,当前服务不可用"- yield (_status_html(message), "", "", "", *reset_result[4:])+ yield (_status_html(message), *reset_result[1:])returnselected_tier = "flash"try:@@ -656,7 +628,7 @@ def build_gradio_app(_effective_page_range, source_path, raw_page_range, tier=selected_tier, max_pages=max_pages)except MineruError as exc:- yield (_status_html(f"Failed: {exc.code}: {exc}"), "", "", "", *reset_result[4:])+ yield (_status_html(f"Failed: {exc.code}: {exc}"), *reset_result[1:])returnstate = StatusPanelState()state.append(STATUS_PREPARING_REQUEST)@@ -689,8 +661,11 @@ def build_gradio_app(output_root=output_root,page_range=page_text,)- markdown_text = artifacts.markdown_path.read_text(encoding="utf-8")- structured_text = artifacts.structured_content_path.read_text(encoding="utf-8")+ rendered_html = await asyncio.to_thread(+ render_html_preview,+ artifacts,+ public_base_url=_gradio_public_base_url(request),+ )preview_path = artifacts.layout_pdf_path or artifacts.origin_pdf_pathgeneric_html = "" if preview_path else preview_placeholder("result_ready")show_image_preview = suffix in IMAGE_EXTENSIONS and preview_path is None@@ -704,9 +679,7 @@ def build_gradio_app(# Office 源预览已在上传时挂载,成功后不重载 iframe,也不恢复已忽略的提示。result_preview_updates = tuple(gr.skip() for _ in range(4))return (- markdown_for_gradio(markdown_text, artifacts),- markdown_text,- structured_text,+ rendered_html,*result_preview_updates,artifacts.as_state(),*_download_updates(gr, interactive=True, run_id=artifacts.root.name),@@ -748,9 +721,7 @@ def build_gradio_app(convert_outputs = [status_panel,- markdown_output,- markdown_source,- structured_source,+ html_output,pdf_preview,image_preview,office_preview,@@ -791,9 +762,7 @@ def build_gradio_app(reset_outputs = [status_panel,- markdown_output,- markdown_source,- structured_source,+ html_output,pdf_preview,image_preview,office_preview,@@ -808,8 +777,6 @@ def build_gradio_app(return (_status_html(_DEFAULT_STATUS),"",- "",- "",_pdf_preview_update(gr, None),gr.update(value=None, visible=False),gr.update(value="", visible=False),@@ -837,8 +804,10 @@ def build_gradio_app(js=download_js("busy", format_name, label),**private_event_kwargs,)+ download_handler = _download_handler(format_name, output_root)+ download_handler.__annotations__["request"] = gr.Requestprepare_download = begin_download.then(- fn=_download_handler(format_name, output_root),+ fn=download_handler,inputs=[artifact_state, download_requests[format_name]],outputs=[download_files[format_name], download_receipts[format_name]],queue=True,@@ -942,6 +911,23 @@ def _example_files(file_types: list[str]) -> list[str]:return [str(path) for path in sorted(example_root.iterdir()) if path.is_file() and path.suffix.lower() in suffixes]+def _gradio_public_base_url(request: object | None = None) -> str:+ """从 Gradio 请求获取当前外部站点根地址,保留反向代理协议、域名和挂载路径。"""+ headers = getattr(request, "headers", None) or {}+ raw_request = getattr(request, "request", None)+ request_url = getattr(raw_request, "url", None)+ host = headers.get("x-forwarded-host") or headers.get("host") or getattr(request_url, "netloc", "localhost:7860")+ protocol = headers.get("x-forwarded-proto") or getattr(request_url, "scheme", "http")+ host = host.split(",", 1)[0].strip()+ protocol = protocol.split(",", 1)[0].strip()+ scope = getattr(raw_request, "scope", None) or {}+ root_path = scope.get("root_path", "")+ if root_path.startswith(("http://", "https://")):+ return root_path.rstrip("/")+ root_path = "/" + root_path.strip("/") if root_path else ""+ return f"{protocol}://{host}{root_path}"++def _build_office_preview_html(file_path: str | Path, request: object | None = None) -> str:"""复用 3.4.5 的上传即预览结构;短地址只供展示,iframe 始终使用完整地址。"""source_path = Path(file_path)@@ -992,18 +978,23 @@ def _download_request_handler(request_token: str) -> str:return request_token if isinstance(request_token, str) else ""-def _download_handler(format_name: str, output_root: Path) -> Callable[[object, str], tuple[str | None, str]]:+def _download_handler(format_name: str, output_root: Path) -> Callable[..., tuple[str | None, str]]:"""创建一个绑定格式和 output root 的 Gradio 下载回调。"""- def handler(state: object, request_token: str) -> tuple[str | None, str]:+ def handler(state: object, request_token: str, request: object | None = None) -> tuple[str | None, str]:"""校验请求所属结果,返回文件与回执;生成失败也交给前端按请求标识恢复按钮。"""receipt = {"request": request_token, "error": ""}try:- request = json.loads(request_token)+ token = json.loads(request_token)artifacts = RunArtifacts.from_state(state)- if request["run_id"] != artifacts.root.name:+ if token["run_id"] != artifacts.root.name:raise ValueError("解析结果已变更,请重新下载。")- path = render_download(state, format_name, allowed_root=output_root)+ path = render_download(+ state,+ format_name,+ allowed_root=output_root,+ public_base_url=_gradio_public_base_url(request),+ )return path, json.dumps(receipt, ensure_ascii=False)except Exception as exc:receipt["error"] = str(exc)diff --git a/mineru/kit/gradio/artifacts.py b/mineru/kit/gradio/artifacts.pyindex e7386060..aed8c5d8 100644--- a/mineru/kit/gradio/artifacts.py+++ b/mineru/kit/gradio/artifacts.py@@ -2,7 +2,8 @@from __future__ import annotations-import base64+import hashlib+import htmlimport jsonimport reimport shutil@@ -10,8 +11,9 @@ import uuidimport zipfilefrom dataclasses import dataclass, fieldfrom pathlib import Path+from tempfile import TemporaryDirectoryfrom typing import Any, Callable, Literal, cast-from urllib.parse import quote+from urllib.parse import quote, unquote, urlsplitfrom loguru import logger@@ -28,7 +30,6 @@ from ...render import (MarkdownRenderOptions,PdfRenderOptions,RenderFormat,- RenderMode,StructuredContentRenderOptions,render,)@@ -36,10 +37,8 @@ from ...types import BlockBase, ImagePayloadBlock, MiddleJsonfrom docvortex.foundation.image_payload import parse_image_data_uri_strictfrom docvortex.foundation.image_payload import validate_image_sidecar_path-DownloadFormat = Literal["zip", "html", "docx", "latex", "epub", "pdf"]+DownloadFormat = Literal["markdown", "json", "html", "docx", "latex", "epub", "pdf"]-_IMAGE_DATA_URI_RE = re.compile(r"data:image/[A-Za-z0-9.+-]+;base64,[A-Za-z0-9+/=]+")-_MARKDOWN_IMAGE_RE = re.compile(r"!\[(?P<alt>[^\]]*)\]\((?P<src>[^)]+)\)")_HTML_IMAGE_RE = re.compile(r"(?P<prefix><img\b[^>]*?\bsrc\s*=\s*)(?P<quote>[\"'])(?P<src>[^\"']+)(?P=quote)",re.IGNORECASE,@@ -57,7 +56,6 @@ class RunArtifacts:middle_json_path: Pathmarkdown_path: Pathstructured_content_path: Path- bundle_zip_path: Pathdownloads_dir: Pathfile_suffix: strorigin_pdf_path: Path | None = None@@ -74,7 +72,6 @@ class RunArtifacts:"middle_json_path": str(self.middle_json_path),"markdown_path": str(self.markdown_path),"structured_content_path": str(self.structured_content_path),- "bundle_zip_path": str(self.bundle_zip_path),"downloads_dir": str(self.downloads_dir),"file_suffix": self.file_suffix,"origin_pdf_path": str(self.origin_pdf_path) if self.origin_pdf_path else "",@@ -95,7 +92,6 @@ class RunArtifacts:"middle_json_path","markdown_path","structured_content_path",- "bundle_zip_path","downloads_dir","file_suffix",)@@ -124,7 +120,6 @@ class RunArtifacts:"middle_json_path","markdown_path","structured_content_path",- "bundle_zip_path","downloads_dir",)]@@ -141,7 +136,6 @@ class RunArtifacts:middle_json_path=Path(cast(str, state["middle_json_path"])).resolve(),markdown_path=Path(cast(str, state["markdown_path"])).resolve(),structured_content_path=Path(cast(str, state["structured_content_path"])).resolve(),- bundle_zip_path=Path(cast(str, state["bundle_zip_path"])).resolve(),downloads_dir=Path(cast(str, state["downloads_dir"])).resolve(),file_suffix=cast(str, state["file_suffix"]),origin_pdf_path=optional_paths[0],@@ -179,11 +173,7 @@ class _ImageContext:except Exception as exc:logger.warning("Failed to crop Gradio PDF image page={} bbox={}: {}", source_page_idx, bbox, exc)return None- relative = f"images/page_{source_page_idx}_{_safe_type_name(str(block.type))}_{block.index or 0}.jpg"- relative = _unique_relative_image_name(relative, self.image_paths.values())- target = self.output_dir / relative- target.parent.mkdir(parents=True, exist_ok=True)- target.write_bytes(data)+ relative = _write_materialized_asset(self.output_dir, data, "jpg")self.image_paths[key] = relativereturn relative, data@@ -207,7 +197,6 @@ def create_run_artifacts(source_path: Path, output_root: Path) -> RunArtifacts:middle_json_path=root / "middle_json.json",markdown_path=root / "markdown.md",structured_content_path=root / "structured_content.json",- bundle_zip_path=root / f"{stem}.zip",downloads_dir=downloads_dir,file_suffix=source_suffix.removeprefix("."),)@@ -220,10 +209,9 @@ def persist_parse_result(output_root: Path,page_range: str,) -> RunArtifacts:- """保存 V1 ParseResult,并生成旧 UI 所需的 Markdown、JSON 和预览文件。"""+ """保存图片已物化的语义副本,并生成 Markdown、Structured Content 和预览文件。"""artifacts = create_run_artifacts(source_path, output_root)shutil.copyfile(source_path, artifacts.source_path)- artifacts.middle_json_path.write_text(result.to_json(), encoding="utf-8")if result._model_output is not None:model_output = result._model_output.to_dict(skip_defaults=False)(artifacts.root / "model_output.json").write_text(@@ -244,26 +232,24 @@ def persist_parse_result(origin_pdf,artifacts.root,page_indices=artifacts.page_indices,+ asset_root=source_path.parent,)try:+ materialized = _materialize_middle_json(result.middle_json, image_context)+ artifacts.middle_json_path.write_text(ParseResult(middle_json=materialized).to_json(), encoding="utf-8")markdown = cast(str,render(- result.middle_json,+ materialized,RenderFormat.MARKDOWN,- options=MarkdownRenderOptions(- mode=RenderMode.DEFAULT,- image_renderer=(lambda block: _markdown_image_for_block(image_context, block, result.middle_json))- if image_context.source_pdf is not None- else None,- ),+ options=MarkdownRenderOptions(),),)artifacts.markdown_path.write_text(markdown, encoding="utf-8")structured = cast(dict[str, Any],render(- result.middle_json,+ materialized,RenderFormat.STRUCTURED_CONTENT,options=StructuredContentRenderOptions(),),@@ -291,66 +277,65 @@ def persist_parse_result(else:artifacts.layout_pdf_path = layout_path- build_bundle_zip(artifacts)return artifacts-def build_bundle_zip(artifacts: RunArtifacts) -> Path:- """把当前任务的源文件和基础产物压缩为用户可下载的 ZIP。"""- _ensure_path_inside(artifacts.root, artifacts.bundle_zip_path)- with zipfile.ZipFile(artifacts.bundle_zip_path, "w", zipfile.ZIP_DEFLATED) as archive:- for path in sorted(artifacts.root.rglob("*")):- if path.is_symlink():- raise ValueError(f"Artifact tree must not contain symlinks: {path}")- if not path.is_file() or path == artifacts.bundle_zip_path or artifacts.downloads_dir in path.parents:- continue- relative = path.relative_to(artifacts.root).as_posix()- validate_image_sidecar_path(relative)- archive.write(path, arcname=relative)- return artifacts.bundle_zip_path---def markdown_for_gradio(markdown: str, artifacts: RunArtifacts) -> str:- """把任务目录中的相对图片路径转换为 Gradio 可访问的绝对文件 URL。"""- if not isinstance(markdown, str):- return ""-- def _resolve(src: str) -> str | None:- """解析并校验任务目录内的图片引用。"""- normalized = src.strip()- if not normalized or _is_external_source(normalized):- return None- try:- safe = validate_image_sidecar_path(normalized)- except ValueError:- return None- candidate = (artifacts.root / safe).resolve()- try:- candidate.relative_to(artifacts.root.resolve())- except ValueError:- return None- if not candidate.is_file() or candidate.suffix.lower() not in _IMAGE_SUFFIXES:- return None- return f"/gradio_api/file={quote(str(candidate), safe='/:')}"-- def replace_markdown(match: re.Match[str]) -> str:- """替换 Markdown 图片链接,保留无法安全解析的原文。"""- public = _resolve(match.group("src"))- return f"" if public else match.group(0)-- result = _MARKDOWN_IMAGE_RE.sub(replace_markdown, markdown)+def render_html_preview(artifacts: RunArtifacts, *, public_base_url: str) -> str:+ """用独立 iframe 展示公共 HTML renderer 的完整输出,保留样式及公式脚本。"""+ value = _render_html(artifacts, public_base_url=public_base_url)+ return (+ '<iframe class="mineru-rendered-html-frame" title="Markdown preview" '+ 'sandbox="allow-scripts allow-popups" '+ f'srcdoc="{html.escape(value, quote=True)}"></iframe>'+ )- def replace_html(match: re.Match[str]) -> str:- """替换 HTML img 的本地图片链接。"""- public = _resolve(match.group("src"))- if public is None:- return match.group(0)- return f"{match.group('prefix')}{match.group('quote')}{public}{match.group('quote')}"- return _HTML_IMAGE_RE.sub(replace_html, result)+def _render_html(artifacts: RunArtifacts, *, public_base_url: str) -> str:+ """把已物化语义树渲染为使用当前 Gradio 静态图片地址的独立 HTML。"""+ if urlsplit(public_base_url).scheme not in {"http", "https"} or not urlsplit(public_base_url).netloc:+ raise ValueError("HTML rendering requires the current Gradio HTTP base URL")+ result = ParseResult.from_json(artifacts.middle_json_path.read_text(encoding="utf-8"))+ asset_base_url = f"{public_base_url.rstrip('/')}/gradio_api/file={quote(str(artifacts.root), safe='/:')}"+ return cast(+ str,+ render(+ result.middle_json,+ RenderFormat.HTML,+ options=HtmlRenderOptions(+ standalone=True,+ document_title=artifacts.stem,+ asset_base_url=asset_base_url,+ ),+ ),+ )-def render_download(artifacts_state: object, format_name: str, *, allowed_root: Path | None = None) -> str:+def _build_text_download(artifacts: RunArtifacts, format_name: Literal["markdown", "json"]) -> Path:+ """仅打包所选正文文件和物化图片,所有 ZIP 成员使用相对路径。"""+ source = artifacts.markdown_path if format_name == "markdown" else artifacts.structured_content_path+ extension = "md" if format_name == "markdown" else "json"+ target = artifacts.downloads_dir / f"{artifacts.stem}_{format_name}.zip"+ _ensure_path_inside(artifacts.root, target)+ images = artifacts.root / "images"+ _ensure_path_inside(artifacts.root, images)+ files = [(source, f"{artifacts.stem}.{extension}")]+ for path in sorted(images.rglob("*")):+ _ensure_path_inside(images, path)+ if path.is_symlink():+ raise ValueError(f"Image assets must not contain symlinks: {path}")+ if path.is_file():+ files.append((path, path.relative_to(artifacts.root).as_posix()))+ _write_archive(files, target)+ return target+++def render_download(+ artifacts_state: object,+ format_name: str,+ *,+ allowed_root: Path | None = None,+ public_base_url: str = "",+) -> str:"""从已保存 Middle JSON 按需生成指定下载文件,并返回绝对路径。"""artifacts = RunArtifacts.from_state(artifacts_state)if allowed_root is not None:@@ -360,58 +345,35 @@ def render_download(artifacts_state: object, format_name: str, *, allowed_root:artifacts.middle_json_path,artifacts.markdown_path,artifacts.structured_content_path,- artifacts.bundle_zip_path,artifacts.downloads_dir,):_ensure_path_inside(artifacts.root, path)- if format_name not in {"zip", "html", "docx", "latex", "epub", "pdf"}:+ if format_name not in {"markdown", "json", "html", "docx", "latex", "epub", "pdf"}:raise ValueError(f"Unsupported download format: {format_name}")download_format = cast(DownloadFormat, format_name)+ # HTML 总是使用本次请求的站点地址,不能复用其他域名下生成的文件。+ if download_format == "html":+ target = artifacts.downloads_dir / f"{artifacts.stem}.html"+ _ensure_path_inside(artifacts.root, target)+ target.write_text(_render_html(artifacts, public_base_url=public_base_url), encoding="utf-8")+ return str(target)cached = artifacts.generated_downloads.get(download_format)if cached is not None and cached.is_file():return str(cached)inferred_cache = _inferred_download_path(artifacts, download_format)if inferred_cache is not None and inferred_cache.is_file():return str(inferred_cache)- if download_format == "zip":- return str(build_bundle_zip(artifacts))+ if download_format in {"markdown", "json"}:+ return str(_build_text_download(artifacts, cast(Literal["markdown", "json"], download_format)))result = ParseResult.from_json(artifacts.middle_json_path.read_text(encoding="utf-8"))middle_json = result.middle_json- source_pdf = artifacts.origin_pdf_path if artifacts.origin_pdf_path and artifacts.origin_pdf_path.is_file() else None- page_indices = artifacts.page_indices- if source_pdf is None:- source_pdf, resolved_page_indices = _prepare_origin_pdf(- artifacts.source_path,- page_range="",- output_path=artifacts.downloads_dir / f".{artifacts.stem}_render_source.pdf",- keep_existing=True,- )- page_indices = tuple(resolved_page_indices)- image_context = _build_image_context(- middle_json,- source_pdf,- artifacts.root,- page_indices=page_indices,- )+ image_context = _build_image_context(middle_json, None, artifacts.root)try:- if download_format == "html":- target = artifacts.downloads_dir / f"{artifacts.stem}.html"- _ensure_path_inside(artifacts.root, target)- html_middle = _materialize_middle_json(middle_json, image_context, mode="inline")- value = cast(- str,- render(- html_middle,- RenderFormat.HTML,- options=HtmlRenderOptions(standalone=True, document_title=artifacts.stem),- ),- )- target.write_text(value, encoding="utf-8")- elif download_format == "docx":+ if download_format == "docx":target = artifacts.downloads_dir / f"{artifacts.stem}.docx"_ensure_path_inside(artifacts.root, target)- docx_middle = _materialize_middle_json(middle_json, image_context, mode="path")+ docx_middle = _materialize_middle_json(middle_json, image_context)value = cast(bytes,render(@@ -424,7 +386,7 @@ def render_download(artifacts_state: object, format_name: str, *, allowed_root:elif download_format == "epub":target = artifacts.downloads_dir / f"{artifacts.stem}.epub"_ensure_path_inside(artifacts.root, target)- epub_middle = _materialize_middle_json(middle_json, image_context, mode="path")+ epub_middle = _materialize_middle_json(middle_json, image_context)value = cast(bytes,render(@@ -437,7 +399,7 @@ def render_download(artifacts_state: object, format_name: str, *, allowed_root:elif download_format == "pdf":target = artifacts.downloads_dir / f"{artifacts.stem}_rendered.pdf"_ensure_path_inside(artifacts.root, target)- pdf_middle = _materialize_middle_json(middle_json, image_context, mode="path")+ pdf_middle = _materialize_middle_json(middle_json, image_context)value = cast(bytes,render(@@ -458,13 +420,12 @@ def render_download(artifacts_state: object, format_name: str, *, allowed_root:latex_root.mkdir(parents=True, exist_ok=True)latex_context = _build_image_context(middle_json,- source_pdf,+ None,latex_root,- page_indices=page_indices,asset_root=artifacts.root,)try:- latex_middle = _materialize_middle_json(middle_json, latex_context, mode="path")+ latex_middle = _materialize_middle_json(middle_json, latex_context)latex_text = cast(str,render(@@ -479,7 +440,6 @@ def render_download(artifacts_state: object, format_name: str, *, allowed_root:finally:_close_image_context(latex_context)_ensure_path_inside(artifacts.root, target)- build_bundle_zip(artifacts)artifacts.generated_downloads[download_format] = targetreturn str(target)finally:@@ -571,23 +531,11 @@ def _close_image_context(context: _ImageContext) -> None:context.source_pdf.close()-def _markdown_image_for_block(context: _ImageContext, block: BlockBase, middle_json: MiddleJson) -> str:- """为 Markdown renderer 提供当前视觉 block 的相对图片引用。"""- page_idx = _find_block_page_idx(middle_json, block)- if page_idx is None:- return ""- cropped = context.crop_for_block(block, middle_page_idx=page_idx)- if cropped is None:- return ""- relative, _data = cropped- return f""---def _materialize_middle_json(middle_json: MiddleJson, context: _ImageContext, *, mode: Literal["path", "inline"]) -> MiddleJson:+def _materialize_middle_json(middle_json: MiddleJson, context: _ImageContext) -> MiddleJson:"""复制 Middle JSON,并为 PDF bbox 或 inline image 准备目标 renderer 所需的图片载荷。"""copied = middle_json.model_copy(deep=True)for page in copied.pages:- page.blocks = [_materialize_block(block, context, middle_page_idx=page.page_idx, mode=mode) for block in page.blocks]+ page.blocks = [_materialize_block(block, context, middle_page_idx=page.page_idx) for block in page.blocks]return copied@@ -596,7 +544,6 @@ def _materialize_block(context: _ImageContext,*,middle_page_idx: int,- mode: Literal["path", "inline"],) -> BlockBase:"""递归复制 block 树,并统一处理图片 data URI、sidecar 和 PDF bbox。"""updates: dict[str, Any] = {}@@ -621,87 +568,51 @@ def _materialize_block(relative, data = croppedextension = Path(relative).suffix.lstrip(".") or extensionif data:- if mode == "inline":- updates["image_base64"] = _data_uri(data, extension)- updates["image_path"] = None- else:- relative = _write_materialized_asset(context.output_dir, data, extension, block, middle_page_idx)- updates["image_path"] = relative- updates["image_base64"] = None+ updates["image_path"] = _write_materialized_asset(context.output_dir, data, extension)+ updates["image_base64"] = None+ updates["image_url"] = Nonecontent = getattr(block, "content", None)if isinstance(content, list):- updates["content"] = [- _materialize_block(child, context, middle_page_idx=middle_page_idx, mode=mode) for child in content- ]+ updates["content"] = [_materialize_block(child, context, middle_page_idx=middle_page_idx) for child in content]elif isinstance(content, str) and "<img" in content.lower():- if mode == "path":- updates["content"] = _replace_inline_images_in_markup(content, context.output_dir, block, middle_page_idx)- else:- updates["content"] = _inline_relative_images_in_markup(content, context.asset_root)+ updates["content"] = _materialize_markup_images(content, context)+return block.model_copy(update=updates, deep=True) if updates else block-def _write_materialized_asset(- output_dir: Path,- data: bytes,- extension: str,- block: BlockBase,- page_idx: int,- *,- ordinal: int = 0,-) -> str:- """把图片写入受控目录并返回安全相对路径。"""+def _write_materialized_asset(output_dir: Path, data: bytes, extension: str) -> str:+ """按图片内容生成稳定文件名,避免无 index 的嵌套图片互相覆盖。"""safe_extension = extension.lower().lstrip(".") or "jpg"- suffix = f"_{ordinal}" if ordinal > 0 else ""- relative = f"images/page_{page_idx}_{_safe_type_name(str(block.type))}_{block.index or 0}{suffix}.{safe_extension}"- relative = validate_image_sidecar_path(relative)+ if f".{safe_extension}" not in _IMAGE_SUFFIXES:+ raise ValueError(f"Unsupported image extension: {extension}")+ relative = f"images/{hashlib.sha256(data).hexdigest()}.{safe_extension}"target = output_dir / relative+ _ensure_path_inside(output_dir, target)target.parent.mkdir(parents=True, exist_ok=True)if not target.exists():target.write_bytes(data)return relative-def _replace_inline_images_in_markup(content: str, output_dir: Path, block: BlockBase, page_idx: int) -> str:- """将 HTML 字符串中的 data URI 图片外置为安全相对路径。"""- ordinal = 0-- def replace(match: re.Match[str]) -> str:- """写出匹配到的内嵌图片并返回相对 sidecar 路径。"""- nonlocal ordinal- ordinal += 1- try:- data, extension = parse_image_data_uri_strict(match.group(0))- except ValueError:- return match.group(0)- relative = _write_materialized_asset(output_dir, data, extension, block, page_idx, ordinal=ordinal)- return relative-- return _IMAGE_DATA_URI_RE.sub(replace, content)---def _inline_relative_images_in_markup(content: str, root: Path) -> str:- """将已有 HTML sidecar 引用读取为 data URI,保证 HTML 下载单文件可用。"""+def _materialize_markup_images(content: str, context: _ImageContext) -> str:+ """将内嵌 HTML 的 data URI 和已有相对图片统一复制到目标 images 目录。"""def replace(match: re.Match[str]) -> str:- """读取一个安全相对图片并替换 src 属性。"""- source = match.group("src").strip()- if _is_external_source(source):- return match.group(0)- try:- safe_path = validate_image_sidecar_path(source)- except ValueError:+ """解析一个 img 的图片载荷并保留原有 HTML 属性及引号。"""+ source = html.unescape(match.group("src")).strip()+ if source.startswith("data:"):+ data, extension = parse_image_data_uri_strict(source)+ elif _is_external_source(source):return match.group(0)- candidate = (root / safe_path).resolve()- try:- candidate.relative_to(root.resolve())- except ValueError:- return match.group(0)- if not candidate.is_file():- return match.group(0)- uri = _data_uri(candidate.read_bytes(), candidate.suffix.lstrip(".") or "png")- return f"{match.group('prefix')}{match.group('quote')}{uri}{match.group('quote')}"+ else:+ safe_path = validate_image_sidecar_path(unquote(source))+ candidate = context.asset_root / safe_path+ _ensure_path_inside(context.asset_root, candidate)+ data = candidate.read_bytes()+ extension = candidate.suffix.lstrip(".")+ relative = _write_materialized_asset(context.output_dir, data, extension)+ return f"{match.group('prefix')}{match.group('quote')}{relative}{match.group('quote')}"return _HTML_IMAGE_RE.sub(replace, content)@@ -722,45 +633,34 @@ def _asset_resolver(root: Path) -> Callable[[str], bytes]:return resolve-def _find_block_page_idx(middle_json: MiddleJson, target: BlockBase) -> int | None:- """按 block 类型、index 和 bbox 查找视觉 block 所属页面。"""- target_key = _block_lookup_key(target)- for page in middle_json.pages:- pending: list[BlockBase] = list(page.blocks)- while pending:- block = pending.pop()- if block is target or _block_lookup_key(block) == target_key:- return page.page_idx- content = getattr(block, "content", None)- if isinstance(content, list):- pending.extend(child for child in content if isinstance(child, BlockBase))- return None---def _block_lookup_key(block: BlockBase) -> tuple[str, int | None, tuple[float, ...] | None]:- """生成跨 renderer 深拷贝仍稳定的 block 查找键。"""- block_type = getattr(block.type, "value", block.type)- bbox = tuple(float(item) for item in block.bbox) if block.bbox is not None else None- return str(block_type), block.index, bbox--def _zip_directory(directory: Path, target: Path) -> None:"""将目录内容压缩为稳定的相对路径 ZIP。"""- with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:- for path in sorted(directory.rglob("*")):- if path.is_symlink():- raise ValueError(f"LaTeX artifact tree must not contain symlinks: {path}")- if path.is_file() and path != target:- relative = path.relative_to(directory).as_posix()+ files: list[tuple[Path, str]] = []+ for path in sorted(directory.rglob("*")):+ _ensure_path_inside(directory, path)+ if path.is_symlink():+ raise ValueError(f"Artifact tree must not contain symlinks: {path}")+ if path.is_file() and path != target:+ files.append((path, path.relative_to(directory).as_posix()))+ _write_archive(files, target)+++def _write_archive(files: list[tuple[Path, str]], target: Path) -> None:+ """完整写出后再发布 ZIP,失败时不留下会被下次请求误用的半成品缓存。"""+ with TemporaryDirectory(prefix=".bundle-", dir=target.parent) as directory:+ pending = Path(directory) / target.name+ with zipfile.ZipFile(pending, "w", zipfile.ZIP_DEFLATED) as archive:+ for path, relative in files:validate_image_sidecar_path(relative)archive.write(path, arcname=relative)+ pending.replace(target)def _inferred_download_path(artifacts: RunArtifacts, format_name: DownloadFormat) -> Path | None:"""根据稳定命名规则定位已生成的下载文件,避免 State 未更新时重复渲染。"""- if format_name == "zip":- return artifacts.bundle_zip_pathnames = {+ "markdown": f"{artifacts.stem}_markdown.zip",+ "json": f"{artifacts.stem}_json.zip","html": f"{artifacts.stem}.html","docx": f"{artifacts.stem}.docx","latex": f"{artifacts.stem}_latex.zip",@@ -795,30 +695,6 @@ def _safe_stem(value: str) -> str:return encoded[:120].decode("utf-8", errors="ignore") or "document"-def _safe_type_name(value: str) -> str:- """把 block 类型转换为稳定的文件名片段。"""- return re.sub(r"[^A-Za-z0-9_-]+", "_", value).strip("_") or "image"---def _unique_relative_image_name(relative: str, existing: Any) -> str:- """在同一任务中为重复图片路径追加稳定序号。"""- existing_set = set(existing)- if relative not in existing_set:- return relative- path = Path(relative)- for index in range(2, 10000):- candidate = path.with_name(f"{path.stem}_{index}{path.suffix}").as_posix()- if candidate not in existing_set:- return candidate- raise ValueError("Too many duplicate image assets")---def _data_uri(data: bytes, extension: str) -> str:- """按图片扩展名生成严格的 image data URI。"""- subtype = {"jpg": "jpeg", "jpeg": "jpeg", "svg": "svg+xml"}.get(extension.lower(), extension.lower())- return f"data:image/{subtype};base64,{base64.b64encode(data).decode('ascii')}"--def _is_external_source(value: str) -> bool:"""判断图片引用是否已经是 scheme URL 或 data URI。"""return bool(re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", value))@@ -827,9 +703,8 @@ def _is_external_source(value: str) -> bool:__all__ = ["DownloadFormat","RunArtifacts",- "build_bundle_zip","create_run_artifacts",- "markdown_for_gradio",+ "render_html_preview","persist_parse_result","render_download",]diff --git a/mineru/kit/gradio/i18n.py b/mineru/kit/gradio/i18n.pyindex 2eff3c7c..9f48e32d 100644--- a/mineru/kit/gradio/i18n.py+++ b/mineru/kit/gradio/i18n.py@@ -51,10 +51,7 @@ MESSAGES: dict[str, tuple[str, str]] = {"unsupported_preview": ("No source preview for this format", "该格式暂无源文档预览"),"result_ready": ("Results are ready", "结果已生成"),"markdown_rendered": ("Markdown preview", "Markdown 渲染"),- "markdown_source": ("Markdown source", "Markdown 源码"),- "structured_source": ("Structured Content source", "Structured Content 源码"),"download_results": ("Download results", "下载结果"),- "latex_bundle": ("LaTeX bundle", "LaTeX 压缩包"),"examples": ("Examples", "示例"),"preparing_download": ("Preparing…", "准备中…"),"download_failed": ("{format} download failed: {error}", "{format} 下载失败:{error}"),diff --git a/mineru/resources/gradio_app.css b/mineru/resources/gradio_app.cssindex 010b38d5..08586017 100644--- a/mineru/resources/gradio_app.css+++ b/mineru/resources/gradio_app.css@@ -209,30 +209,17 @@ body.dark .gradio-container {.mineru-markdown-tabs .tab-nav {border-bottom-color: var(--mineru-panel-border);}-.mineru-markdown-tabs textarea {- height: var(--mineru-markdown-text-content-height) !important;- min-height: var(--mineru-markdown-text-content-height) !important;-}-.mineru-markdown-text,-.mineru-content-list-json,-.mineru-markdown-text .wrap,-.mineru-content-list-json .wrap,-.mineru-markdown-text .codemirror-wrapper,-.mineru-content-list-json .codemirror-wrapper {- height: var(--mineru-markdown-text-content-height) !important;- min-height: var(--mineru-markdown-text-content-height) !important;-}-.mineru-markdown-text .cm-editor,-.mineru-content-list-json .cm-editor,-.mineru-markdown-text .cm-scroller,-.mineru-content-list-json .cm-scroller {- height: 100% !important;- max-height: 100% !important;- min-height: 0 !important;+.mineru-markdown-output .html-container,+.mineru-markdown-output .prose {+ padding: 0 !important;+ max-width: none !important;}-.mineru-markdown-text .cm-scroller,-.mineru-content-list-json .cm-scroller {- overflow: auto !important;+.mineru-rendered-html-frame {+ display: block;+ width: 100%;+ height: var(--mineru-preview-content-height);+ border: 0;+ background: white;}.status-steps-panel {border: 1px solid var(--mineru-panel-border);diff --git a/mineru/resources/gradio_download.js b/mineru/resources/gradio_download.jsindex bcb07c96..11975633 100644--- a/mineru/resources/gradio_download.js+++ b/mineru/resources/gradio_download.js@@ -1,7 +1,6 @@// 按结果标识协调下载请求、按钮状态和浏览器下载,丢弃旧文档的回执。(action, formats, format, label, ...args) => {const { text, message } = window.__mineruI18n;- label = label === "LaTeX bundle" ? text("latex_bundle") : label;const state = window.__mineruGradioDownloads ??= { runId: "", sequence: 0, pending: new Map() };// 用标准组件更新对象兼容 Gradio 5/6;空更新不会覆盖新文档的按钮状态。const skip = () => ({ __type__: "update" });@@ -16,7 +15,7 @@state.pending.clear();return ["", ...formats.map(() => null), ...formats.map(() => ""), ...formats.map(() => ""),- ...formats.map(([, name]) => button(name === "LaTeX bundle" ? text("latex_bundle") : name, false)), "",+ ...formats.map(([, name]) => button(name, false)), "",];}if (action === "activate") {diff --git a/mineru/resources/gradio_i18n.js b/mineru/resources/gradio_i18n.jsindex 3a482e00..6348c1c3 100644--- a/mineru/resources/gradio_i18n.js+++ b/mineru/resources/gradio_i18n.js@@ -20,7 +20,6 @@".mineru-upload-file > label", ".mineru-force-ocr", ".mineru-actions button",".mineru-tier-label", ".mineru-page-handle-a label", ".mineru-page-handle-b label",".mineru-kit-pdf-preview > label", ".mineru-kit-image-preview > label",- ".mineru-markdown-text > label", ".mineru-structured-content > label",".mineru-markdown-tabs [role=tab]", ".mineru-markdown-tabs .tab-wrapper [aria-hidden] button",".mineru-kit-download-options button", "#mineru-kit-examples > .label",];diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex c4b4ac03..80934949 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -637,7 +637,7 @@ def test_gradio_ocr_reaches_analysis_through_real_v1_jobs(monkeypatch: pytest.Mohandler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")for enabled in (True, False, True):updates = [update async for update in handler(str(source), 0, "", enabled)]- state = updates[-1][8]+ state = updates[-1][6]assert state is not None, updates[-1][0]payload = json.loads(Path(state["middle_json_path"]).read_text())assert payload["extensions"]["mineru"]["parse_mode"] == ("ocr" if enabled else "txt")@@ -842,7 +842,7 @@ def test_managed_local_api_server_cleans_process_control_and_temp_dir(def test_persist_and_render_all_gradio_download_formats(tmp_path: Path) -> None:- """验证严格 Middle JSON、布局 PDF 和六种下载产物。"""+ """验证严格 Middle JSON、布局 PDF 和七种下载产物。"""source = tmp_path / "报告.pdf"source.write_bytes(_pdf_bytes())result = ParseResult(middle_json=_middle_json(), _model_output=_model_json())@@ -853,26 +853,24 @@ def test_persist_and_render_all_gradio_download_formats(tmp_path: Path) -> None:assert artifacts.layout_pdf_path == artifacts.root / "layout.pdf"assert artifacts.origin_pdf_path is not None and artifacts.origin_pdf_path.is_file()assert artifacts.layout_pdf_path is not None and artifacts.layout_pdf_path.is_file()- assert artifacts.bundle_zip_path.is_file()+ assert not list(artifacts.root.glob("*.zip"))assert list((artifacts.root / "images").glob("*.jpg"))- with zipfile.ZipFile(artifacts.bundle_zip_path) as archive:- assert {- "source.pdf",- "middle_json.json",- "markdown.md",- "structured_content.json",- "model_output.json",- "origin.pdf",- "layout.pdf",- }.issubset(archive.namelist())-- html_path = Path(render_download(artifacts.as_state(), "html", allowed_root=tmp_path / "output"))+ for format_name, extension in (("markdown", "md"), ("json", "json")):+ path = render_download(artifacts.as_state(), format_name, allowed_root=tmp_path / "output")+ with zipfile.ZipFile(path) as archive:+ assert f"{artifacts.stem}.{extension}" in archive.namelist()+ assert all(name.startswith("images/") or name == f"{artifacts.stem}.{extension}" for name in archive.namelist())++ html_path = Path(+ render_download(artifacts.as_state(), "html", allowed_root=tmp_path / "output", public_base_url="http://localhost:7860")+ )docx_path = Path(render_download(artifacts.as_state(), "docx", allowed_root=tmp_path / "output"))latex_path = Path(render_download(artifacts.as_state(), "latex", allowed_root=tmp_path / "output"))epub_path = Path(render_download(artifacts.as_state(), "epub", allowed_root=tmp_path / "output"))pdf_path = Path(render_download(artifacts.as_state(), "pdf", allowed_root=tmp_path / "output"))assert "<!doctype html>" in html_path.read_text(encoding="utf-8").lower()- assert "data:image/jpeg;base64," in html_path.read_text(encoding="utf-8")+ assert "data:image/" not in html_path.read_text(encoding="utf-8")+ assert "http://localhost:7860/gradio_api/file=" in html_path.read_text(encoding="utf-8")assert docx_path.read_bytes().startswith(b"PK")assert epub_path.read_bytes().startswith(b"PK")assert pdf_path.read_bytes().startswith(b"%PDF")@@ -915,7 +913,8 @@ def test_page_range_image_crops_follow_original_page_indices(tmp_path: Path) ->output_root=tmp_path / "output",page_range="2-3",)- images = sorted((artifacts.root / "images").glob("*.jpg"))+ saved = ParseResult.from_json(artifacts.middle_json_path.read_text())+ images = [artifacts.root / page.blocks[1].content[0].image_path for page in saved.pages]assert len(images) == 2with Image.open(images[0]) as first_image, Image.open(images[1]) as second_image:first_mean = ImageStat.Stat(first_image.convert("RGB")).mean@@ -957,7 +956,6 @@ def test_run_artifact_paths_are_absolute_and_inside_output_root(tmp_path: Path)first.middle_json_path,first.markdown_path,first.structured_content_path,- first.bundle_zip_path,first.downloads_dir,):assert path.is_absolute()@@ -1043,8 +1041,8 @@ def test_gradio_non_pdf_ignores_hidden_force_ocr(tmp_path: Path, suffix: str) ->assert client.parse_file.call_args.kwargs["page_range"] == ""-def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -> None:- """验证新 UI 不引入旧 backend 控件,并注册三个标签和下载事件。"""+def test_build_gradio_app_exposes_html_tab_and_download_menu(tmp_path: Path) -> None:+ """验证新 UI 不引入旧 backend 控件,并注册 HTML 标签和下载事件。"""capabilities = V1ServerCapabilities("http://127.0.0.1:1",("flash", "basic", "standard", "advanced"),@@ -1060,8 +1058,6 @@ def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -tab_labels = [component.label for component in app.blocks.values() if component.__class__.__name__ == "Tab"]assert [label.key for label in tab_labels] == ["mineru.markdown_rendered",- "mineru.markdown_source",- "mineru.structured_source",]download_buttons = [component@@ -1069,7 +1065,7 @@ def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -if component.__class__.__name__ == "Button"and any(name.startswith("mineru-kit-download-") for name in (component.elem_classes or []))]- assert [component.value for component in download_buttons] == ["ZIP", "HTML", "DOCX", "LaTeX bundle", "EPUB", "PDF"]+ assert [component.value for component in download_buttons] == ["Markdown", "JSON", "HTML", "DOCX", "LaTeX", "EPUB", "PDF"]assert not any(component.__class__.__name__ == "DownloadButton" for component in app.blocks.values())assert all(component.interactive is False for component in download_buttons)file_inputs = [@@ -1179,8 +1175,8 @@ def test_gradio_flash_only_input_requires_available_flash(tmp_path: Path, tiers:updates = asyncio.run(convert())assert "tier_unavailable" in updates[-1][0]assert "该格式仅支持 Flash,当前服务不可用" in updates[-1][0]- assert updates[-1][8] is None- assert all(item["interactive"] is False for item in updates[-1][-6:])+ assert updates[-1][6] is None+ assert all(item["interactive"] is False for item in updates[-1][-7:])client.parse_file.assert_not_called()@@ -1243,11 +1239,11 @@ def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(updates = asyncio.run(collect_updates(convert_handler))assert client.calls == [(source.resolve(), expected_tier, "" if expected_tier == "flash" else "1")]- assert len(updates[-1]) == 16- assert updates[-1][9] == Path(updates[-1][8]["root"]).name- assert updates[-1][8] is not None- assert all(update["interactive"] is True for update in updates[-1][-6:])- assert all(update["interactive"] is False for update in updates[0][-6:])+ assert len(updates[-1]) == 15+ assert updates[-1][7] == Path(updates[-1][6]["root"]).name+ assert updates[-1][6] is not None+ assert all(update["interactive"] is True for update in updates[-1][-7:])+ assert all(update["interactive"] is False for update in updates[0][-7:])@pytest.mark.parametrize(@@ -1276,8 +1272,8 @@ def test_gradio_conversion_rejects_invalid_tier_position(tmp_path: Path, tiers:updates = asyncio.run(collect_updates())assert "Failed: Invalid tier slider position" in updates[-1][0]- assert updates[-1][8] is None- assert all(item["interactive"] is False for item in updates[-1][-6:])+ assert updates[-1][6] is None+ assert all(item["interactive"] is False for item in updates[-1][-7:])client.parse_file.assert_not_called()@@ -1309,8 +1305,8 @@ def test_gradio_conversion_failure_clears_previous_downloads(tmp_path: Path) ->update = asyncio.run(final_update(convert_handler))assert "Failed: boom" in update[0]- assert update[8] is None- assert all(item["interactive"] is False for item in update[-6:])+ assert update[6] is None+ assert all(item["interactive"] is False for item in update[-7:])@pytest.mark.parametrize("explicit_session_cancel", [False, True])@@ -1388,8 +1384,8 @@ def test_gradio_local_queue_cancellation_releases_slot_and_keeps_sessions_isolatupdates = [update async for update in third]final = updates[-1]assert "Completed (" in final[0]- assert final[8]["stem"] == sources[2].stem- assert all(item["interactive"] is True for item in final[-6:])+ assert final[6]["stem"] == sources[2].stem+ assert all(item["interactive"] is True for item in final[-7:])asyncio.run(scenario())@@ -1423,8 +1419,8 @@ def test_gradio_output_failure_stops_timer_and_allows_next_conversion(tmp_path:updates = [update async for update in handler(str(source), 0, "")]assert "Failed: output disk unavailable" in updates[-1][0]assert "is-error" in updates[-1][0]- assert updates[-1][8] is None- assert all(item["interactive"] is False for item in updates[-1][-6:])+ assert updates[-1][6] is None+ assert all(item["interactive"] is False for item in updates[-1][-7:])asyncio.run(scenario())@@ -1503,7 +1499,6 @@ def test_shared_layout_failure_keeps_other_gradio_artifacts(tmp_path: Path, monkassert artifacts.markdown_path.is_file()assert not (artifacts.root / "layout.pdf").exists()assert any("Skipping Gradio layout overlay" in call.args[0] for call in warnings.call_args_list)- with zipfile.ZipFile(artifacts.bundle_zip_path) as archive:- assert "origin.pdf" in archive.namelist()- assert "middle_json.json" in archive.namelist()+ with 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()diff --git a/tests/unittest/test_kit_gradio_download.cjs b/tests/unittest/test_kit_gradio_download.cjsindex e277e6d5..7f3e07ec 100644--- a/tests/unittest/test_kit_gradio_download.cjs+++ b/tests/unittest/test_kit_gradio_download.cjs@@ -17,7 +17,7 @@ global.window = { __mineruI18n: vm.runInThisContext(fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_i18n.js"), "utf8"))(JSON.parse(fs.readFileSync(0, "utf8"))) };const reduce = vm.runInThisContext(fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_download.js"), "utf8"));-const formats = [["zip", "ZIP"], ["html", "HTML"], ["docx", "DOCX"], ["latex", "LaTeX bundle"], ["epub", "EPUB"], ["pdf", "PDF"]];+const formats = [["markdown", "Markdown"], ["json", "JSON"], ["html", "HTML"], ["docx", "DOCX"], ["latex", "LaTeX"], ["epub", "EPUB"], ["pdf", "PDF"]];// 调用实际产品脚本,保持 DOM 替身只负责记录下载行为。const step = (action, format = "", ...args) => reduce(action, formats, format, formats.find(([name]) => name === format)?.[1], ...args);const receipt = (request, error = "") => JSON.stringify({ request, error });@@ -33,7 +33,7 @@ for (const [format, label] of formats) {const [ready, notice] = step("complete", format, file, receipt(token), "run-a");assert.equal(downloads.length, count + 1);assert.deepEqual(downloads.at(-1), [file.url, file.orig_name]);- assert.equal(ready.value, label === "LaTeX bundle" ? "LaTeX 压缩包" : label);+ assert.equal(ready.value, label);assert.equal(ready.interactive, true);assert.equal(notice, "");step("complete", format, file, receipt(token), "run-a");@@ -49,8 +49,8 @@ const [retry] = step("begin", "pdf", "run-a");const count = downloads.length;const reset = step("reset");assert.equal(reset[0], "");-assert.deepEqual(reset.slice(1, 7), Array(6).fill(null));-assert.ok(reset.slice(-7, -1).every(update => update.interactive === false));+assert.deepEqual(reset.slice(1, 8), Array(7).fill(null));+assert.ok(reset.slice(-8, -1).every(update => update.interactive === false));step("activate", "", "run-b");const [current] = step("begin", "pdf", "run-b");assert.deepEqual(step("busy", "pdf", retry, "run-b"), [{ __type__: "update" }, { __type__: "update" }]);diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.pyindex dd6df36b..43bef235 100644--- a/tests/unittest/test_kit_gradio_download.py+++ b/tests/unittest/test_kit_gradio_download.py@@ -53,8 +53,8 @@ def test_download_event_chain_and_pdf_mount(tmp_path: Path) -> None:assert preview(source)[0]["visible"] == "hidden"assert "mineru-kit-pdf-empty" in preview(source)[0]["elem_classes"]reset = next(fn.fn for fn in app.fns.values() if fn.name == "reset_ui")- assert reset()[4]["visible"] == "hidden"- assert reset()[9] == ""+ assert reset()[2]["visible"] == "hidden"+ assert reset()[7] == ""conversion = next(fn for fn in app.fns.values() if fn.name == "convert_handler")dependency = next(dep for dep in app.config["dependencies"] if dep["id"] == conversion._id)# 转换必须等待真正的重置完成事件,纯 JS 事件的 then 在支持版本中不会可靠触发。@@ -62,7 +62,7 @@ def test_download_event_chain_and_pdf_mount(tmp_path: Path) -> None:assert reset_event.name == "reset_download_ui"assert len(reset_event.fn()) == len(reset_event.outputs)handlers = [fn for fn in app.fns.values() if fn.name == "handler"]- assert len(handlers) == 6+ assert len(handlers) == 7files = []for handler in handlers:file, receipt = handler.outputs@@ -72,7 +72,7 @@ def test_download_event_chain_and_pdf_mount(tmp_path: Path) -> None:assert success["trigger_only_on_success"] is Trueassert success["backend_fn"] is False and success["queue"] is Falseassert success["inputs"][:2] == [file._id, receipt._id]- assert len(set(files)) == 6+ assert len(set(files)) == 7def test_frontend_download_lifecycle() -> None:diff --git a/tests/unittest/test_kit_gradio_html.py b/tests/unittest/test_kit_gradio_html.pynew file mode 100644index 00000000..63489c4d--- /dev/null+++ b/tests/unittest/test_kit_gradio_html.py@@ -0,0 +1,226 @@+"""HTML 预览的 HTTP 图片、独立文本下载包及物化语义树回归。"""++from __future__ import annotations++import base64+import io+import json+import re+import zipfile+from pathlib import Path+from types import SimpleNamespace+from urllib.parse import quote, unquote++import gradio as gr+import pytest+from bs4 import BeautifulSoup+from fastapi.testclient import TestClient+from PIL import Image+from starlette.requests import Request++from mineru.kit.gradio.app import _download_handler, _gradio_public_base_url, build_gradio_app+from mineru.kit.gradio.artifacts import persist_parse_result, render_download, render_html_preview+from mineru.kit.gradio.client import V1ServerCapabilities+from mineru.parser.base import ParseResult+from mineru.types import BlockType, EquationBlock, TableBlock, TableBodyBlock+from test_kit_gradio import _middle_json+++def _image_bytes(color: str) -> bytes:+ """生成可真实加载的彩色 PNG,以区分同页不同图片。"""+ output = io.BytesIO()+ Image.new("RGB", (24, 16), color).save(output, "PNG")+ return output.getvalue()++[email protected]("image_source", ["inline", "sidecar"])+def test_materialized_html_and_independent_archives(tmp_path: Path, image_source: str) -> None:+ """正文、表格图片和公式保持语义,HTTP 与 ZIP 各自使用正确的图片地址。"""+ source = tmp_path / "中文 报告.docx"+ source.write_bytes(b"source")+ middle = _middle_json(file_suffix="docx")+ image_body = middle.pages[0].blocks[1].content[0]+ image_body.image_url = "https://example.test/fallback.png"+ red = _image_bytes("red")+ blue = _image_bytes("blue")+ if image_source == "inline":+ image_body.image_base64 = "data:image/png;base64," + base64.b64encode(red).decode()+ table_image = "data:image/png;base64," + base64.b64encode(blue).decode()+ else:+ (tmp_path / "图 1.png").write_bytes(red)+ (tmp_path / "图 2.png").write_bytes(blue)+ image_body.image_path = "图 1.png"+ table_image = quote("图 2.png")+ middle.pages[0].blocks.extend(+ [+ TableBlock(+ type=BlockType.TABLE,+ index=2,+ content=[+ TableBodyBlock(+ type=BlockType.TABLE_BODY,+ index=2,+ content=f'<table><tr><td><img src="{table_image}"></td></tr></table>',+ ),+ ],+ ),+ EquationBlock(type=BlockType.EQUATION, index=3, content="x^2 + y^2 = z^2"),+ ]+ )+ original = middle.model_dump_json()+ artifacts = persist_parse_result(ParseResult(middle_json=middle), source, output_root=tmp_path / "输出 空格", page_range="")+ assert middle.model_dump_json() == original+ assert len(list((artifacts.root / "images").iterdir())) == 2+ assert "base64," not in artifacts.middle_json_path.read_text()+ # 后续导出只能读取物化素材,不再需要源文件或源目录中的图片。+ source.unlink()+ artifacts.source_path.unlink()+ if image_source == "sidecar":+ (tmp_path / "图 1.png").unlink()+ (tmp_path / "图 2.png").unlink()++ base = "https://demo.example.test/mineru"+ preview = render_html_preview(artifacts, public_base_url=base)+ frame = BeautifulSoup(preview, "html.parser").iframe+ html_document = frame["srcdoc"]+ assert html_document.lower().startswith("<!doctype html>")+ assert "<style>" in html_document and "MathJax-script" in html_document+ assert "allow-scripts" in frame["sandbox"] and "allow-same-origin" not in frame["sandbox"]+ assert "data:image/" not in html_document+ urls = [image["src"] for image in BeautifulSoup(html_document, "html.parser").find_all("img")]+ assert len(urls) == 2+ for url in urls:+ assert url.startswith(f"{base}/gradio_api/file=") and " " not in url+ path = Path(unquote(url.split("/gradio_api/file=", 1)[1]))+ assert path.read_bytes() in {red, blue}++ for format_name, extension in (("markdown", "md"), ("json", "json"), ("latex", "tex")):+ path = Path(render_download(artifacts.as_state(), format_name, allowed_root=tmp_path))+ assert path.name == f"{artifacts.stem}_{format_name}.zip"+ with zipfile.ZipFile(path) as archive:+ names = archive.namelist()+ document = archive.read(f"{artifacts.stem}.{extension}").decode()+ assert "base64," not in document and "gradio_api/file=" not in document+ assert all(name.startswith("images/") or name == f"{artifacts.stem}.{extension}" for name in names)+ references = set(re.findall(r"images/[a-f0-9]+\.png", document))+ assert references and references.issubset(names)+ assert {archive.read(name) for name in references} == {red, blue}+ if format_name == "json":+ structured = json.loads(document)+ assert "pages" in structured and "schema_version" not in structured+ assert structured["pages"][0]["blocks"][1]["image_source"] in names+ modified = path.stat().st_mtime_ns+ assert render_download(artifacts.as_state(), format_name) == str(path)+ assert path.stat().st_mtime_ns == modified++ # HTML 是一个文件,每次按当前请求站点重建链接。+ for public_base in (base, "http://localhost:17866"):+ path = Path(render_download(artifacts.as_state(), "html", public_base_url=public_base))+ assert path.suffix == ".html"+ content = path.read_text()+ assert "data:image/" not in content+ assert all(+ img["src"].startswith(public_base + "/gradio_api/file=")+ for img in BeautifulSoup(content, "html.parser").find_all("img")+ )+ with pytest.raises(ValueError, match="Unsupported download format"):+ render_download(artifacts.as_state(), "zip")++[email protected]("format_name,extension", [("markdown", "md"), ("json", "json")])+def test_text_download_without_images(tmp_path: Path, format_name: str, extension: str) -> None:+ """无图文档仍下载独立 ZIP,不添加其他格式或内部产物。"""+ source = tmp_path / "text.docx"+ source.write_bytes(b"source")+ result = ParseResult(middle_json=_middle_json(with_image=False, file_suffix="docx"))+ artifacts = persist_parse_result(result, source, output_root=tmp_path / "output", page_range="")+ with zipfile.ZipFile(render_download(artifacts.as_state(), format_name)) as archive:+ assert archive.namelist() == [f"text.{extension}"]+++ "headers,root_path,expected",+ [+ ({"host": "localhost:17866"}, "", "http://localhost:17866"),+ ({"host": "localhost:17866"}, "/mineru", "http://localhost:17866/mineru"),+ (+ {"host": "internal", "x-forwarded-host": "demo.test, proxy", "x-forwarded-proto": "https, http"},+ "/mineru",+ "https://demo.test/mineru",+ ),+ ({"host": "internal"}, "https://shared.test/app/", "https://shared.test/app"),+ ],+)+def test_html_public_url_uses_request_context(headers: dict[str, str], root_path: str, expected: str) -> None:+ """验证当前端口、反向代理和子路径都进入 HTML 图片公开地址。"""+ request = Request(+ {+ "type": "http",+ "scheme": "http",+ "server": ("internal", 80),+ "path": "/queue/join",+ "root_path": root_path,+ "headers": [(key.encode(), value.encode()) for key, value in headers.items()],+ }+ )+ assert _gradio_public_base_url(gr.Request(request=request)) == expected+++def test_html_images_are_served_by_gradio(tmp_path: Path) -> None:+ """通过真实 Gradio 文件路由读取预览中的 PNG,同时检查下载请求没有新增用户输入。"""+ source = tmp_path / "report.docx"+ source.write_bytes(b"source")+ middle = _middle_json(file_suffix="docx")+ data = _image_bytes("green")+ middle.pages[0].blocks[1].content[0].image_base64 = "data:image/png;base64," + base64.b64encode(data).decode()+ artifacts = persist_parse_result(ParseResult(middle_json=middle), source, output_root=tmp_path / "output", page_range="")+ cap = V1ServerCapabilities("http://unused.test", ("flash",), ("zip",), ("file_id",))+ demo = build_gradio_app(SimpleNamespace(), cap, output_root=tmp_path / "output", enable_example=False)+ demo.allowed_paths = [str(tmp_path / "output")]+ app = gr.routes.App.create_app(demo)+ preview = render_html_preview(artifacts, public_base_url="http://testserver")+ content = BeautifulSoup(preview, "html.parser").iframe["srcdoc"]+ url = BeautifulSoup(content, "html.parser").img["src"]+ with TestClient(app) as client:+ response = client.get(url)+ assert response.status_code == 200+ assert response.headers["content-type"] == "image/png"+ assert response.content == data+ output = next(component for component in demo.blocks.values() if "mineru-markdown-output" in (component.elem_classes or []))+ assert isinstance(output, gr.HTML)+ handlers = [fn for fn in demo.fns.values() if fn.name == "handler"]+ assert len(handlers) == 7 and all(len(fn.inputs) == 2 for fn in handlers)+ handler = _download_handler("html", tmp_path / "output")+ path, receipt = handler(+ artifacts.as_state(),+ json.dumps({"run_id": artifacts.root.name}),+ SimpleNamespace(headers={"host": "current.test:9999"}),+ )+ assert not json.loads(receipt)["error"]+ assert "http://current.test:9999/gradio_api/file=" in Path(path).read_text()+++def test_archive_failure_does_not_poison_retry(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """图片读取中途失败不能生成有效缓存,恢复后再次下载应得到完整压缩包。"""+ source = tmp_path / "report.docx"+ source.write_bytes(b"source")+ middle = _middle_json(file_suffix="docx")+ middle.pages[0].blocks[1].content[0].image_base64 = (+ "data:image/png;base64," + base64.b64encode(_image_bytes("red")).decode()+ )+ artifacts = persist_parse_result(ParseResult(middle_json=middle), source, output_root=tmp_path / "output", page_range="")+ write = zipfile.ZipFile.write++ def fail_image(archive: zipfile.ZipFile, filename: str | Path, arcname: str | None = None) -> None:+ """模拟正文已写入、图片开始写入时发生磁盘读取错误。"""+ if arcname and arcname.startswith("images/"):+ raise OSError("image read failed")+ write(archive, filename, arcname)++ with monkeypatch.context() as patch:+ patch.setattr(zipfile.ZipFile, "write", fail_image)+ with pytest.raises(OSError, match="image read failed"):+ render_download(artifacts.as_state(), "markdown")+ assert not list(artifacts.downloads_dir.iterdir())+ with zipfile.ZipFile(render_download(artifacts.as_state(), "markdown")) as archive:+ assert len(archive.namelist()) == 2diff --git a/tests/unittest/test_kit_gradio_i18n.py b/tests/unittest/test_kit_gradio_i18n.pyindex 81d08187..f46d834a 100644--- a/tests/unittest/test_kit_gradio_i18n.py+++ b/tests/unittest/test_kit_gradio_i18n.py@@ -118,26 +118,26 @@ def test_conversion_preserves_all_preview_components_until_success(try:await asyncio.wait_for(started.wait(), timeout=3)assert updates- assert all(update[4:8] == ({"__type__": "update"},) * 4 for update in updates)+ assert all(update[2:6] == ({"__type__": "update"},) * 4 for update in updates)finish.set()await asyncio.wait_for(consumer, timeout=10)finally:if not consumer.done():consumer.cancel()await asyncio.gather(consumer, return_exceptions=True)- assert all(update[4:8] == ({"__type__": "update"},) * 4 for update in updates[:-1])+ assert all(update[2:6] == ({"__type__": "update"},) * 4 for update in updates[:-1])if outcome == "success":- assert updates[-1][7]["visible"] is True- assert "结果已生成" in updates[-1][7]["value"]- assert updates[-1][8] is not None+ assert updates[-1][5]["visible"] is True+ assert "结果已生成" in updates[-1][5]["value"]+ assert updates[-1][6] is not Noneelse:- assert updates[-1][4:8] == ({"__type__": "update"},) * 4- assert updates[-1][8] is None+ assert updates[-1][2:6] == ({"__type__": "update"},) * 4+ assert updates[-1][6] is Noneassert "Failed:" in updates[-1][0]# 真正的清除仍会重置预览,文件切换仍按新文件类型展示。reset = next(fn.fn for fn in demo.fns.values() if fn.name == "reset_ui")preview = next(fn.fn for fn in demo.fns.values() if fn.name == "update_file_preview")- assert reset()[4]["value"] is None and reset()[7]["visible"] is True+ assert reset()[2]["value"] is None and reset()[5]["visible"] is Trueassert preview("new.pdf")[0]["value"] == "new.pdf"asyncio.run(scenario())diff --git a/tests/unittest/test_kit_gradio_office_preview.py b/tests/unittest/test_kit_gradio_office_preview.pyindex ce69eea8..5d215208 100644--- a/tests/unittest/test_kit_gradio_office_preview.py+++ b/tests/unittest/test_kit_gradio_office_preview.py@@ -118,11 +118,11 @@ def test_office_conversion_never_replaces_uploaded_preview(return [update async for update in handler(str(source), 0, "")]updates = asyncio.run(collect())- assert updates and all(update[4:8] == ({"__type__": "update"},) * 4 for update in updates)- assert bool(updates[-1][8]) is (outcome == "success")- assert all(item["interactive"] is (outcome == "success") for item in updates[-1][-6:])+ assert updates and all(update[2:6] == ({"__type__": "update"},) * 4 for update in updates)+ assert bool(updates[-1][6]) is (outcome == "success")+ assert all(item["interactive"] is (outcome == "success") for item in updates[-1][-7:])if outcome == "success":- assert "hello-0" in updates[-1][2]+ assert "hello-0" in updates[-1][1]else:assert "Failed:" in updates[-1][0]preview = next(fn.fn for fn in demo.fns.values() if fn.name == "update_file_preview")diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.pyindex 7cc7492f..9fbf2c77 100644--- a/tests/unittest/test_kit_gradio_page_range.py+++ b/tests/unittest/test_kit_gradio_page_range.py@@ -278,7 +278,7 @@ def test_invalid_or_oversized_range_is_rejected_before_submission(tmp_path: Pathupdates = asyncio.run(collect())assert "page_range_invalid" in str(updates[-1][0])- assert updates[-1][8] is None+ assert updates[-1][6] is Noneclient.parse_file.assert_not_called()