Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Enhance Office file preview functionality and update related UI messages

myhloli391cb5f19a9e
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.md
index daad5c26..da83d7bb 100644
--- a/docs/next/cli/mineru-kit-gradio.md
+++ b/docs/next/cli/mineru-kit-gradio.md
@@ -114,7 +114,11 @@ MinerU 自定义文案跟随浏览器首选语言:中文(包括 `zh-CN`、`z
## 预览与兼容边界
-转换开始、排队、解析和整理输出期间保留当前预览及浏览位置,成功生成结果后再刷新。转换失败也保留当前预览;点击清除会恢复空预览,更换文件会显示新文件的源预览或对应格式提示。
+Office 类文件(DOC/DOCX、PPT/PPTX、XLS/XLSX、RTF、ODT/ODS/ODP)上传后立即显示“Office 在线预览”提示卡和在线预览框。提示文案和布局沿用 3.4.5,文件链接以站点加文件名尾部的短地址显示;实际预览使用完整文件 URL。该文件需要能被 Microsoft 在线预览服务访问,解析不依赖在线预览是否成功。
+
+Office 转换开始、失败及成功后都保留已挂载的源预览。“忽略”仅隐藏当前提示卡,“不再提示”保存浏览器偏好;转换完成不会重新加载预览框或恢复已忽略的提示。更换文件更新源预览,清除恢复空预览。
+
+转换开始、排队、解析和整理输出期间保留当前预览及浏览位置;PDF 和图片成功生成结果后刷新预览。转换失败也保留当前预览;点击清除会恢复空预览,更换文件会显示新文件的源预览或对应格式提示。
PDF 和图片会生成与解析范围一致的 `origin.pdf`;布局预览使用 schema 2.0 顶层 block/bbox 生成语义 overlay。无法生成 overlay 时仍保留 origin PDF 预览。
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
index 2f6b031f..5ad20514 100644
--- a/mineru/kit/gradio/app.py
+++ b/mineru/kit/gradio/app.py
@@ -446,7 +446,7 @@ def build_gradio_app(
]
)
- def update_file_preview(file_path: str | None) -> tuple[Any, ...]:
+ 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))
if not file_path:
@@ -480,7 +480,7 @@ def build_gradio_app(
_preview_update(gr, None, visible=False),
_preview_update(
gr,
- preview_placeholder("office_pending"),
+ _build_office_preview_html(file_path, request),
visible=True,
),
_preview_update(gr, "", visible=False),
@@ -494,6 +494,8 @@ def build_gradio_app(
*reset_result,
)
+ # 保持公开输入只有文件,访问地址由 Gradio 的请求上下文注入。
+ update_file_preview.__annotations__["request"] = gr.Request
private_event_kwargs = _private_event_kwargs(gr)
download_script = _resource_text("gradio_download.js")
@@ -690,17 +692,22 @@ def build_gradio_app(
markdown_text = artifacts.markdown_path.read_text(encoding="utf-8")
structured_text = artifacts.structured_content_path.read_text(encoding="utf-8")
preview_path = artifacts.layout_pdf_path or artifacts.origin_pdf_path
- office_html = _build_office_result_html(artifacts, request) if _is_office(source_path) else ""
- generic_html = "" if preview_path or office_html else preview_placeholder("result_ready")
+ generic_html = "" if preview_path else preview_placeholder("result_ready")
show_image_preview = suffix in IMAGE_EXTENSIONS and preview_path is None
+ result_preview_updates = (
+ _pdf_preview_update(gr, str(preview_path) if preview_path else None),
+ gr.update(value=str(source_path) if show_image_preview else None, visible=show_image_preview),
+ gr.update(value="", visible=False),
+ gr.update(value=generic_html, visible=bool(generic_html)),
+ )
+ if _is_office(source_path):
+ # Office 源预览已在上传时挂载,成功后不重载 iframe,也不恢复已忽略的提示。
+ result_preview_updates = tuple(gr.skip() for _ in range(4))
return (
markdown_for_gradio(markdown_text, artifacts),
markdown_text,
structured_text,
- _pdf_preview_update(gr, str(preview_path) if preview_path else None),
- gr.update(value=str(source_path) if show_image_preview else None, visible=show_image_preview),
- gr.update(value=office_html, visible=bool(office_html)),
- gr.update(value=generic_html, visible=bool(generic_html)),
+ *result_preview_updates,
artifacts.as_state(),
*_download_updates(gr, interactive=True, run_id=artifacts.root.name),
)
@@ -935,21 +942,24 @@ 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 _build_office_result_html(artifacts: RunArtifacts, request: Any = None) -> str:
- """为 Office 结果生成带可选在线预览的安全提示,转换不依赖该 iframe。"""
- source_name = artifacts.source_path.name
+def _build_office_preview_html(file_path: str | Path, request: object | None = None) -> str:
+ """复用 3.4.5 的上传即预览结构;短地址只供展示,iframe 始终使用完整地址。"""
+ source_path = Path(file_path)
headers = getattr(request, "headers", None) or {}
host = headers.get("x-forwarded-host") or headers.get("host") or "localhost:7860"
protocol = headers.get("x-forwarded-proto") or "http"
- public_url = f"{protocol}://{host}/gradio_api/file={quote(str(artifacts.source_path), safe='/:')}"
+ public_url = f"{protocol}://{host}/gradio_api/file={quote(str(source_path), safe='/:')}"
+ short_name = f"{source_path.stem[-12:]}{source_path.suffix}" if source_path.stem else source_path.name
+ short_public_url = f"{protocol}://{host}/....{short_name}"
viewer_url = "https://view.officeapps.live.com/op/embed.aspx?src=" + quote(public_url, safe="")
return (
'<div class="office-preview-shell">'
'<div class="office-preview-notice">'
'<div class="office-preview-copy">'
- f"<strong>{localized_text('office_completed', name=source_name)}</strong>"
- f"{localized_text('office_notice')}"
- f'<div class="office-preview-source-link">{html.escape(public_url, quote=True)}</div>'
+ f"<strong>{localized_text('office_preview_title')}</strong>"
+ f"<span>{localized_text('office_notice')}</span>"
+ '<div class="office-preview-source-link">'
+ f"{localized_text('office_preview_source_link')}: {html.escape(short_public_url, quote=True)}</div>"
"</div>"
'<div class="office-preview-actions">'
f'<button type="button" class="office-preview-ignore-once">{localized_text("ignore_once")}</button>'
diff --git a/mineru/kit/gradio/i18n.py b/mineru/kit/gradio/i18n.py
index ac41fdc6..2eff3c7c 100644
--- a/mineru/kit/gradio/i18n.py
+++ b/mineru/kit/gradio/i18n.py
@@ -49,7 +49,6 @@ MESSAGES: dict[str, tuple[str, str]] = {
"empty_preview": ("No source document preview", "暂无源文档预览"),
"source_preview": ("Source document preview", "源文档预览"),
"unsupported_preview": ("No source preview for this format", "该格式暂无源文档预览"),
- "office_pending": ("Office results will be available after conversion", "Office 文件将在转换后提供结果"),
"result_ready": ("Results are ready", "结果已生成"),
"markdown_rendered": ("Markdown preview", "Markdown 渲染"),
"markdown_source": ("Markdown source", "Markdown 源码"),
@@ -61,13 +60,15 @@ MESSAGES: dict[str, tuple[str, str]] = {
"download_failed": ("{format} download failed: {error}", "{format} 下载失败:{error}"),
"missing_download": ("No download file was received. Please try again.", "未获得下载文件,请重试。"),
"stale_download": ("The parsing result has changed. Please download again.", "解析结果已变更,请重新下载。"),
- "office_completed": ("{name} has been parsed", "{name} 已完成解析"),
+ "office_preview_title": ("Office online preview", "Office 在线预览"),
+ "office_preview_source_link": ("File url", "文件链接"),
"office_notice": (
- "Office preview uses an external service. Conversion results do not depend on this preview.",
- "Office 在线预览依赖外部服务,转换结果不依赖该预览。",
+ "This preview requires the current file to be reachable by Microsoft Office Online. "
+ "Conversion does not depend on this preview.",
+ "该预览需要当前文件可被 Microsoft 在线预览服务访问,转换不依赖该预览。",
),
"ignore_once": ("Dismiss", "忽略"),
- "ignore_forever": ("Don't show again", "不再提示"),
+ "ignore_forever": ("Always dismiss", "不再提示"),
"status_idle_title": ("Waiting", "等待任务"),
"status_idle_hint": ("Upload a file and start conversion.", "上传文件后开始转换。"),
"status_latest": ("Latest status", "最新状态"),
diff --git a/tests/unittest/test_kit_gradio_i18n.cjs b/tests/unittest/test_kit_gradio_i18n.cjs
index 42d51d8d..4f81438b 100644
--- a/tests/unittest/test_kit_gradio_i18n.cjs
+++ b/tests/unittest/test_kit_gradio_i18n.cjs
@@ -14,7 +14,7 @@ for (const [languages, language, expected] of [
context.window.__mineruI18n = i18n;
assert.equal(i18n.resolveLocale(), expected);
assert.equal(i18n.text("force_ocr_info"), messages.force_ocr_info[expected === "zh" ? 1 : 0]);
- assert.ok(i18n.text("office_completed", { name: "$& 文件.pdf" }).includes("$& 文件.pdf"));
+ assert.ok(i18n.text("failed", { error: "$& 文件.pdf" }).includes("$& 文件.pdf"));
const range = vm.runInContext(resource("gradio_page_range.js"), context);
const out = range(["flash", "standard"], ["csv"], 20, "/test.pdf", 1,
JSON.stringify({ path: "/test.pdf", page_count: 10 }), "{}", 1, 1,
diff --git a/tests/unittest/test_kit_gradio_i18n.py b/tests/unittest/test_kit_gradio_i18n.py
index 910b4111..81d08187 100644
--- a/tests/unittest/test_kit_gradio_i18n.py
+++ b/tests/unittest/test_kit_gradio_i18n.py
@@ -41,7 +41,7 @@ def test_i18n_launch_and_component_contract(tmp_path: Path) -> None:
def test_bilingual_errors_and_html_keep_untrusted_details_as_text() -> None:
"""本地错误附带英文翻译,未知服务端消息和恶意文件名仍是转义后的原文。"""
- value = localized_text("office_completed", name='<img src=x onerror="alert(1)"> $& 中文.pdf')
+ value = localized_text("failed", error='<img src=x onerror="alert(1)"> $& 中文.pdf')
assert "<img" not in value and "&lt;img" in value and "$&amp; 中文.pdf" in value
for message, expected in [
("Failed: input file does not exist", "输入文件不存在"),
diff --git a/tests/unittest/test_kit_gradio_office_preview.py b/tests/unittest/test_kit_gradio_office_preview.py
new file mode 100644
index 00000000..ce69eea8
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_office_preview.py
@@ -0,0 +1,133 @@
+"""Office 上传即预览、旧版提示文案和转换期间保留 iframe 的回归。"""
+
+from __future__ import annotations
+
+import asyncio
+import html
+import re
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+from urllib.parse import parse_qs, quote, urlsplit
+
+import pytest
+
+from mineru.filetypes import OFFICE_EXTENSIONS
+from mineru.kit.gradio import app as app_module
+from mineru.kit.gradio.client import V1ServerCapabilities
+from mineru.kit.gradio.i18n import MESSAGES
+from mineru.parser.base import ParseResult
+from test_kit_gradio import _middle_json
+
+
[email protected]("suffix", sorted(OFFICE_EXTENSIONS | {ext.upper() for ext in OFFICE_EXTENSIONS}))
+def test_office_upload_builds_preview_without_parsing(tmp_path: Path, suffix: str) -> None:
+ """所有现有 Office 格式上传后即可预览,请求上下文不增加事件公开输入。"""
+ client = SimpleNamespace(parse_file=AsyncMock())
+ demo = app_module.build_gradio_app(
+ client,
+ V1ServerCapabilities("http://localhost:1", ("flash",), ("zip",), ("file_id",)),
+ output_root=tmp_path,
+ enable_example=False,
+ )
+ callback = next(fn for fn in demo.fns.values() if fn.name == "update_file_preview")
+ assert len(callback.inputs) == 1
+ request = SimpleNamespace(headers={"host": "example.test:7860"})
+ updates = callback.fn(str(tmp_path / f"document.{suffix}"), request)
+ assert updates[0]["visible"] == "hidden" and updates[1]["visible"] is False
+ assert updates[2]["visible"] is True and updates[3]["visible"] is False
+ assert 'class="office-preview-notice"' in updates[2]["value"]
+ assert 'class="office-preview-frame"' in updates[2]["value"]
+ assert "Office 在线预览" in updates[2]["value"]
+ assert "Office 文件将在转换后提供结果" not in updates[2]["value"]
+ client.parse_file.assert_not_called()
+
+
+ ("headers", "base"),
+ [
+ ({}, "http://localhost:7860"),
+ ({"host": "example.test:8080"}, "http://example.test:8080"),
+ (
+ {"host": "internal:7860", "x-forwarded-host": "documents.example.test", "x-forwarded-proto": "https"},
+ "https://documents.example.test",
+ ),
+ ],
+)
[email protected]("name", ["short.docx", "abcdefghijklmnopqrst中文 空格.xlsx", "a<>&\"'.pptx"])
+def test_office_short_address_keeps_full_encoded_iframe_url(headers: dict[str, str], base: str, name: str) -> None:
+ """短地址只截取主名末尾十二字符,完整预览 URL 仍正确编码并防止 HTML 注入。"""
+ source = Path("/uploaded/private") / name
+ markup = app_module._build_office_preview_html(source, SimpleNamespace(headers=headers))
+ iframe_url = html.unescape(re.search(r'<iframe[^>]+src="([^"]+)"', markup)[1])
+ public_url = parse_qs(urlsplit(iframe_url).query)["src"][0]
+ assert public_url == f"{base}/gradio_api/file={quote(str(source), safe='/:')}"
+ displayed = html.unescape(re.search(r'<div class="office-preview-source-link">(.*?)</div>', markup)[1])
+ assert f"{base}/....{source.stem[-12:]}{source.suffix}" in displayed
+ assert "/uploaded/private" not in displayed
+ assert "文件链接" in displayed and "File url" in displayed
+ assert "<a " not in markup and "<>&" not in markup
+ assert markup.count("<iframe") == 1
+ if not headers:
+ assert markup == app_module._build_office_preview_html(source)
+
+
+def test_office_copy_matches_345_release() -> None:
+ """固定中英文文案属于本次恢复的用户可见契约。"""
+ assert MESSAGES["office_preview_title"] == ("Office online preview", "Office 在线预览")
+ assert MESSAGES["office_notice"] == (
+ "This preview requires the current file to be reachable by Microsoft Office Online. "
+ "Conversion does not depend on this preview.",
+ "该预览需要当前文件可被 Microsoft 在线预览服务访问,转换不依赖该预览。",
+ )
+ assert MESSAGES["office_preview_source_link"] == ("File url", "文件链接")
+ assert MESSAGES["ignore_once"] == ("Dismiss", "忽略")
+ assert MESSAGES["ignore_forever"] == ("Always dismiss", "不再提示")
+
+
[email protected]("outcome", ["success", "parse_failure", "output_failure"])
+def test_office_conversion_never_replaces_uploaded_preview(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ outcome: str,
+) -> None:
+ """成功、解析失败及整理失败都不替换 iframe,避免浏览位置或已忽略状态丢失。"""
+ source = tmp_path / "document.docx"
+ source.write_bytes(b"Office source fixture")
+ result = ParseResult(middle_json=_middle_json(with_image=False, file_suffix="docx"))
+ parse = AsyncMock(return_value=result)
+ if outcome == "parse_failure":
+ parse.side_effect = RuntimeError("office parse failed")
+
+ def fail_output(*_args: object, **_kwargs: object) -> None:
+ """模拟解析完成后的产物整理失败。"""
+ raise OSError("output unavailable")
+
+ if outcome == "output_failure":
+ monkeypatch.setattr(app_module, "persist_parse_result", fail_output)
+ demo = app_module.build_gradio_app(
+ SimpleNamespace(parse_file=parse),
+ V1ServerCapabilities("http://localhost:1", ("flash",), ("zip",), ("file_id",)),
+ output_root=tmp_path / "output",
+ enable_example=False,
+ )
+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")
+
+ async def collect() -> list[tuple[object, ...]]:
+ """消费完整生成器并检查每一次前端预览更新。"""
+ 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:])
+ if outcome == "success":
+ assert "hello-0" in updates[-1][2]
+ else:
+ assert "Failed:" in updates[-1][0]
+ preview = next(fn.fn for fn in demo.fns.values() if fn.name == "update_file_preview")
+ assert "next.pptx" in preview("next.pptx")[2]["value"]
+ assert preview("next.pdf")[2]["visible"] is False
+ assert preview("next.png")[1]["value"] == "next.png"
+ assert preview("next.epub")[2]["visible"] is False
+ assert preview(None)[2]["value"] == ""