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
Update DocVortex dependency version and enhance bilingual support in Gradio interface
myhlolicdc1d9ace02a
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.mdindex 335530ad..daad5c26 100644--- a/docs/next/cli/mineru-kit-gradio.md+++ b/docs/next/cli/mineru-kit-gradio.md@@ -106,8 +106,16 @@ Gradio 首先发现 `/v1/health` 和 `/v1/tiers`,然后通过 `MinerUApiParser每次解析的文件保存在独立的 `output-dir/gradio/<run-id>/` 目录,包含源文件、Middle JSON、基础文本产物以及可选的 `origin.pdf`、`layout.pdf` 和图片资源。路径只向 Gradio 暴露在配置的 output root 内。+## 界面语言++MinerU 自定义文案跟随浏览器首选语言:中文(包括 `zh-CN`、`zh-TW` 等)统一显示简体中文,其他语言或无法识别时显示英文。Header、控件说明、页码提示、任务状态及下载提示使用同一规则;文件名、文档正文和服务端原始错误详情保持原文。Gradio 原生控件保留框架自带的国际化能力,上传提示、复制工具栏、页脚等可以按浏览器语言显示日语、法语等其他受支持语言。++强制 OCR 的说明为“忽略 PDF 文本层并进行 OCR”;英文为“Ignore the PDF text layer and perform OCR”。+## 预览与兼容边界+转换开始、排队、解析和整理输出期间保留当前预览及浏览位置,成功生成结果后再刷新。转换失败也保留当前预览;点击清除会恢复空预览,更换文件会显示新文件的源预览或对应格式提示。+PDF 和图片会生成与解析范围一致的 `origin.pdf`;布局预览使用 schema 2.0 顶层 block/bbox 生成语义 overlay。无法生成 overlay 时仍保留 origin PDF 预览。`mineru-gradio` 保留为 `mineru-kit gradio` 的兼容命令名,参数与行为完全相同;旧 HTTP 协议和旧 Gradio 专属参数不再提供。diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 3d48aa1e..2f6b031f 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -24,6 +24,7 @@ from .client import (V1ArtifactClient,V1ServerCapabilities,)+from .i18n import MESSAGES, localized_text, preview_placeholder, translationsfrom .page_range import effective_page_range as _effective_page_rangefrom .page_range import pdf_page_metadata, validate_max_pagesfrom .status import (@@ -55,7 +56,8 @@ _LATEX_DELIMITERS_B = [{"left": "\\[", "right": "\\]", "display": True},]_DOWNLOAD_ICON_HTML = """-<button type="button" class="mineru-kit-download-icon" title="下载结果" aria-label="下载结果"+<button type="button" class="mineru-kit-download-icon" title="Download results" aria-label="Download results"+ data-mineru-i18n-key="download_results" data-mineru-i18n-attr="title aria-label"aria-controls="mineru-kit-download-options"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">@@ -131,22 +133,27 @@ def _render_header(*, gradio_major_version: int = 5) -> str:"""渲染复用旧版视觉风格的静态 Header。"""template = _resource_text("gradio_header.html")values = {- "{{HEADER_TITLE}}": "MinerU 4:文档提取",- "{{HEADER_SUBTITLE}}": "开源文档提取工具,支持 PDF、Office、EPUB、OFD、HTML、CSV 与图片。","{{HEADER_SUPPORT_TEXT}}": "",- "{{HEADER_STARS_ALT}}": "GitHub 星标",- "{{HEADER_CODE_LINK}}": "代码",- "{{HEADER_MODEL_LINK}}": "模型","{{HEADER_MODEL_HUGGINGFACE_LINK}}": "Hugging Face","{{HEADER_MODEL_MODELSCOPE_LINK}}": "ModelScope",- "{{HEADER_PAPER_LINK}}": "论文","{{HEADER_PAPER_MINERU_REPORT}}": "MinerU · arXiv","{{HEADER_PAPER_MINERU25_REPORT}}": "MinerU 2.5 · arXiv","{{HEADER_PAPER_MINERU25PRO_REPORT}}": "MinerU 2.5 Pro · arXiv",- "{{HEADER_HOMEPAGE_LINK}}": "主页",- "{{HEADER_DOWNLOAD_LINK}}": "下载","{{HEADER_GRADIO_VERSION_CLASS}}": " mineru-gradio6-header" if gradio_major_version >= 6 else "",}+ for placeholder, key in {+ "HEADER_TITLE": "header_title",+ "HEADER_SUBTITLE": "header_subtitle",+ "HEADER_CODE_LINK": "code",+ "HEADER_MODEL_LINK": "model",+ "HEADER_PAPER_LINK": "paper",+ "HEADER_HOMEPAGE_LINK": "homepage",+ "HEADER_DOWNLOAD_LINK": "download",+ }.items():+ template = template.replace("{{" + placeholder + "}}", localized_text(key))+ template = template.replace(+ 'alt="{{HEADER_STARS_ALT}}"', 'alt="GitHub stars" data-mineru-i18n-attr="alt" data-mineru-i18n-key="stars"'+ )rendered = templatefor placeholder, value in values.items():rendered = rendered.replace(placeholder, html.escape(value, quote=True))@@ -242,7 +249,11 @@ def build_gradio_app(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_CSS- app_js = _resource_text("gradio_app.js")+ i18n = gr.I18n(**translations())+ app_js = _resource_text("gradio_app.js").replace(+ "__MINERU_I18N__",+ f"({_resource_text('gradio_i18n.js')})({json.dumps(MESSAGES, ensure_ascii=False)})",+ )# Gradio 5 在 Blocks 构造时接收静态资源,6 则在 launch 时接收。blocks_kwargs = {"css": app_css, "js": app_js} if _gradio_major_version(gr) < 6 else {}# 等待限制放在生成器内部,使其他会话也能立即显示本地排队状态。@@ -257,7 +268,7 @@ def build_gradio_app(with gr.Row(elem_classes=["mineru-kit-workspace"]):with gr.Column(scale=2, min_width=280, elem_classes=["mineru-kit-control", "mineru-control-column"]):input_file = gr.File(- label="请选择要解析的文件",+ label=i18n("mineru.upload"),file_types=file_types,file_count="single",type="filepath",@@ -277,7 +288,7 @@ def build_gradio_app(step=1,precision=0,interactive=len(tier_choices) > 1,- label="解析 tier",+ label=i18n("mineru.tier"),show_label=False,elem_classes=["mineru-tier-slider"],)@@ -285,15 +296,15 @@ def build_gradio_app(tier_selection = gr.Textbox(value=json.dumps({"tier": preferred_tier, "locked": False}), visible=False)force_ocr = gr.Checkbox(value=False,- label="强制 OCR",- info="忽略 PDF 文本层并进行 OCR;关闭时自动判断。",+ label=i18n("mineru.force_ocr"),+ info=i18n("mineru.force_ocr_info"),visible=False,interactive=True,elem_classes=["mineru-force-ocr"],)page_range = gr.Textbox(value="",- label="页码范围",+ label=i18n("mineru.page_range"),visible=False,)# 用 JSON 文本承载内部状态,避开 Gradio 5/6 JSON 组件的序列化差异。@@ -309,7 +320,7 @@ def build_gradio_app(value=1,step=1,precision=0,- label="起始页",+ label=i18n("mineru.start_page"),interactive=False,container=False,elem_classes=["mineru-page-handle-a"],@@ -320,20 +331,22 @@ def build_gradio_app(value=1,step=1,precision=0,- label="结束页",+ label=i18n("mineru.end_page"),interactive=False,container=False,elem_classes=["mineru-page-handle-b"],)page_notice = gr.HTML(value="", visible=False, elem_classes=["mineru-page-notice"])with gr.Row(elem_classes=["mineru-actions"]):- convert_button = gr.Button("转换", variant="primary", scale=1, min_width=0, interactive=False)- clear_button = gr.ClearButton(value="清除", scale=1, min_width=1)+ convert_button = gr.Button(+ i18n("mineru.convert"), variant="primary", scale=1, min_width=0, interactive=False+ )+ clear_button = gr.ClearButton(value=i18n("mineru.clear"), scale=1, min_width=1)status_panel = gr.HTML(_status_html(), elem_classes=["mineru-status-panel"])with gr.Column(scale=4, min_width=340, elem_classes=["mineru-kit-preview", "mineru-preview-pane"]):pdf_preview = PDF(- label="文档预览",+ label=MESSAGES["preview"][0],interactive=False,# 预先挂载空组件,避免 gradio-pdf 首次带值挂载时漏掉文件加载。visible="hidden",@@ -341,7 +354,7 @@ def build_gradio_app(elem_classes=["mineru-kit-pdf-preview", "mineru-kit-pdf-empty"],)image_preview = gr.Image(- label="文档预览",+ label=i18n("mineru.preview"),type="filepath",interactive=False,visible=False,@@ -355,14 +368,14 @@ def build_gradio_app(elem_classes=["mineru-kit-office-preview", "mineru-office-preview-html"],)generic_preview = gr.HTML(- value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>',+ value=preview_placeholder("empty_preview"),visible=True,elem_classes=["mineru-kit-generic-preview"],)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("Markdown 渲染"):+ with gr.Tab(i18n("mineru.markdown_rendered")):markdown_output = gr.Markdown(value="",height=775,@@ -371,17 +384,19 @@ def build_gradio_app(**markdown_copy_kwargs,elem_classes=["mineru-markdown-output"],)- with gr.Tab("Markdown 源码"):+ 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("Structured Content 源码"):+ with gr.Tab(i18n("mineru.structured_source")):structured_source = gr.Code(value="",+ label=i18n("mineru.structured_source"),language="json",lines=28,interactive=False,@@ -408,7 +423,7 @@ def build_gradio_app(if enable_example:examples = _example_files(file_types)if examples:- gr.Examples(examples=examples, inputs=input_file, label="示例", elem_id="mineru-kit-examples")+ gr.Examples(examples=examples, inputs=input_file, label=i18n("mineru.examples"), elem_id="mineru-kit-examples")artifact_state = gr.State(value=None)active_run_id = gr.Textbox(value="", visible=False)@@ -439,7 +454,7 @@ def build_gradio_app(_pdf_preview_update(gr, None),_preview_update(gr, None, visible=False),_preview_update(gr, "", visible=False),- _preview_update(gr, '<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),+ _preview_update(gr, preview_placeholder("empty_preview"), visible=True),*reset_result,)suffix = _file_suffix(file_path)@@ -448,7 +463,7 @@ def build_gradio_app(_pdf_preview_update(gr, file_path),_preview_update(gr, None, visible=False),_preview_update(gr, "", visible=False),- _preview_update(gr, '<div class="mineru-kit-empty-preview">源文档预览</div>', visible=False),+ _preview_update(gr, preview_placeholder("source_preview"), visible=False),*reset_result,)if suffix in IMAGE_EXTENSIONS:@@ -456,7 +471,7 @@ def build_gradio_app(_pdf_preview_update(gr, None),_preview_update(gr, file_path, visible=True),_preview_update(gr, "", visible=False),- _preview_update(gr, '<div class="mineru-kit-empty-preview">源文档预览</div>', visible=False),+ _preview_update(gr, preview_placeholder("source_preview"), visible=False),*reset_result,)if _is_office(file_path):@@ -465,7 +480,7 @@ def build_gradio_app(_preview_update(gr, None, visible=False),_preview_update(gr,- '<div class="mineru-kit-empty-preview">Office 文件将在转换后提供结果</div>',+ preview_placeholder("office_pending"),visible=True,),_preview_update(gr, "", visible=False),@@ -475,7 +490,7 @@ def build_gradio_app(_pdf_preview_update(gr, None),_preview_update(gr, None, visible=False),_preview_update(gr, "", visible=False),- _preview_update(gr, '<div class="mineru-kit-empty-preview">该格式暂无源文档预览</div>', visible=True),+ _preview_update(gr, preview_placeholder("unsupported_preview"), visible=True),*reset_result,)@@ -601,39 +616,37 @@ def build_gradio_app(request: object | None = None,) -> Any:"""执行单文件 V1 解析并流式更新状态与三个结果标签。"""- empty_result = (+ # 开始或失败只重置结果与下载;预览内容、显隐和浏览位置保持不变。+ reset_result = (_status_html(_DEFAULT_STATUS),"","","",- _pdf_preview_update(gr, None),- gr.update(value=None, visible=False),- gr.update(value="", visible=False),- gr.update(value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),+ *(gr.skip() for _ in range(4)),None,*_download_updates(gr, interactive=False),)if not file_path:- yield empty_result+ yield reset_resultreturnsource_path = Path(file_path).resolve()if not source_path.is_file():- yield (_status_html("Failed: input file does not exist"), "", "", "", *empty_result[4:])+ yield (_status_html("Failed: input file does not exist"), "", "", "", *reset_result[4:])returnsuffix = _file_suffix(source_path)if suffix not in PARSEABLE_EXTENSIONS:- yield (_status_html(f"Failed: unsupported file type '.{suffix}'"), "", "", "", *empty_result[4:])+ yield (_status_html(f"Failed: unsupported file type '.{suffix}'"), "", "", "", *reset_result[4:])returntry:selected_tier = _tier_for_position(tier_position, tier_choices)except ValueError as exc:- yield (_status_html(f"Failed: {exc}"), "", "", "", *empty_result[4:])+ yield (_status_html(f"Failed: {exc}"), "", "", "", *reset_result[4:])returnif suffix in FLASH_ONLY_PARSE_EXTENSIONS:# 提交端独立约束有效档位,避免事件 API 或前端残留值绕过 Flash 锁定。if "flash" not in tier_choices:message = "Failed: tier_unavailable: 该格式仅支持 Flash,当前服务不可用"- yield (_status_html(message), "", "", "", *empty_result[4:])+ yield (_status_html(message), "", "", "", *reset_result[4:])returnselected_tier = "flash"try:@@ -641,11 +654,11 @@ 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}"), "", "", "", *empty_result[4:])+ yield (_status_html(f"Failed: {exc.code}: {exc}"), "", "", "", *reset_result[4:])returnstate = StatusPanelState()state.append(STATUS_PREPARING_REQUEST)- yield (state.render(), *empty_result[1:])+ yield (state.render(), *reset_result[1:])status_queue: asyncio.Queue[tuple[str, float]] = asyncio.Queue()loop = asyncio.get_running_loop()@@ -678,9 +691,7 @@ def build_gradio_app(structured_text = artifacts.structured_content_path.read_text(encoding="utf-8")preview_path = artifacts.layout_pdf_path or artifacts.origin_pdf_pathoffice_html = _build_office_result_html(artifacts, request) if _is_office(source_path) else ""- generic_html = (- "" if preview_path or office_html else '<div class="mineru-kit-empty-preview">结果已生成</div>'- )+ generic_html = "" if preview_path or office_html else preview_placeholder("result_ready")show_image_preview = suffix in IMAGE_EXTENSIONS and preview_path is Nonereturn (markdown_for_gradio(markdown_text, artifacts),@@ -712,7 +723,7 @@ def build_gradio_app(async with aclosing(stream_status_updates(task, status_queue, state)) as updates:async for status in updates:# 动画只更新状态卡片,避免反复重建预览和清空结果组件。- yield (status, *(gr.skip() for _ in empty_result[1:]))+ yield (status, *(gr.skip() for _ in reset_result[1:]))result_outputs = await taskstate.append(STATUS_COMPLETED)yield (state.render(), *result_outputs)@@ -721,7 +732,7 @@ def build_gradio_app(returnexcept Exception as exc:state.append(f"Failed: {exc}")- yield (state.render(), *empty_result[1:])+ yield (state.render(), *reset_result[1:])finally:# 清除、换文件或断开流时仅取消本地等待,不发送远端取消请求。if not task.done():@@ -795,7 +806,7 @@ def build_gradio_app(_pdf_preview_update(gr, None),gr.update(value=None, visible=False),gr.update(value="", visible=False),- gr.update(value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),+ gr.update(value=preview_placeholder("empty_preview"), visible=True),None,*_download_updates(gr, interactive=False),)@@ -837,7 +848,9 @@ def build_gradio_app(demo._mineru_kit_css = app_cssdemo._mineru_kit_js = app_js- demo._mineru_kit_launch_kwargs = {"css": app_css, "js": app_js} if _gradio_major_version(gr) >= 6 else {}+ demo._mineru_kit_launch_kwargs = {"i18n": i18n}+ if _gradio_major_version(gr) >= 6:+ demo._mineru_kit_launch_kwargs.update(css=app_css, js=app_js)demo.queue(default_concurrency_limit=1)return demo@@ -924,7 +937,7 @@ def _example_files(file_types: list[str]) -> list[str]:def _build_office_result_html(artifacts: RunArtifacts, request: Any = None) -> str:"""为 Office 结果生成带可选在线预览的安全提示,转换不依赖该 iframe。"""- source_name = html.escape(artifacts.source_path.name, quote=True)+ source_name = artifacts.source_path.nameheaders = 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"@@ -934,13 +947,13 @@ def _build_office_result_html(artifacts: RunArtifacts, request: Any = None) -> s'<div class="office-preview-shell">''<div class="office-preview-notice">''<div class="office-preview-copy">'- f"<strong>{source_name} 已完成解析</strong>"- "<span>Office 在线预览依赖外部服务,转换结果不依赖该预览。</span>"+ 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>'"</div>"'<div class="office-preview-actions">'- '<button type="button" class="office-preview-ignore-once">忽略</button>'- '<button type="button" class="office-preview-ignore-forever">不再提示</button>'+ f'<button type="button" class="office-preview-ignore-once">{localized_text("ignore_once")}</button>'+ f'<button type="button" class="office-preview-ignore-forever">{localized_text("ignore_forever")}</button>'"</div>""</div>"f'<iframe class="office-preview-frame" src="{html.escape(viewer_url, quote=True)}" frameborder="0"></iframe>'diff --git a/mineru/kit/gradio/i18n.py b/mineru/kit/gradio/i18n.pynew file mode 100644index 00000000..ac41fdc6--- /dev/null+++ b/mineru/kit/gradio/i18n.py@@ -0,0 +1,159 @@+"""Gradio 界面的唯一中英文词典,不翻译文档正文或外部错误详情。"""++from __future__ import annotations++import html+import re++# 每项依次为英文和简体中文;同时供 Gradio 属性、Python HTML 和前端事件使用。+MESSAGES: dict[str, tuple[str, str]] = {+ "header_title": ("MinerU 4: Document Extraction", "MinerU 4:文档提取"),+ "header_subtitle": (+ "Open-source document extraction for PDF, Office, EPUB, OFD, HTML, CSV and images.",+ "开源文档提取工具,支持 PDF、Office、EPUB、OFD、HTML、CSV 与图片。",+ ),+ "stars": ("GitHub stars", "GitHub 星标"),+ "code": ("Code", "代码"),+ "model": ("Models", "模型"),+ "paper": ("Papers", "论文"),+ "homepage": ("Homepage", "主页"),+ "download": ("Download", "下载"),+ "upload": ("Select a document to parse", "请选择要解析的文件"),+ "tier": ("Parsing tier", "解析 tier"),+ "tier_value": ("Parsing tier: {tier}{notice}", "解析 tier:{tier}{notice}"),+ "tier_unavailable_suffix": (" (unavailable on this server)", "(当前服务不可用)"),+ "force_ocr": ("Force OCR", "强制 OCR"),+ "force_ocr_info": ("Ignore the PDF text layer and perform OCR", "忽略 PDF 文本层并进行 OCR"),+ "page_range": ("Page range", "页码范围"),+ "start_page": ("Start page", "起始页"),+ "end_page": ("End page", "结束页"),+ "page_count": ("{count} pages", "{count} 页"),+ "page_limit": ("Up to {count} pages", "最多 {count} 页"),+ "page_unlimited": ("No page limit", "不限页数"),+ "reading_pages": ("Reading PDF page count…", "正在读取 PDF 页数…"),+ "page_read_failed": (+ "Cannot read the PDF page count. Check whether the file is damaged or password-protected.",+ "无法读取 PDF 页数,请检查文件是否损坏或需要密码。",+ ),+ "page_limit_exceeded": (+ "At most {limit} pages can be parsed per conversion; {count} pages are selected.",+ "单次最多解析 {limit} 页,当前选择了 {count} 页。",+ ),+ "flash_unavailable": (+ "This format requires Flash, which is unavailable on this server",+ "该格式仅支持 Flash,当前服务不可用",+ ),+ "convert": ("Convert", "转换"),+ "clear": ("Clear", "清除"),+ "preview": ("Document preview", "文档预览"),+ "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 源码"),+ "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}"),+ "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_notice": (+ "Office preview uses an external service. Conversion results do not depend on this preview.",+ "Office 在线预览依赖外部服务,转换结果不依赖该预览。",+ ),+ "ignore_once": ("Dismiss", "忽略"),+ "ignore_forever": ("Don't show again", "不再提示"),+ "status_idle_title": ("Waiting", "等待任务"),+ "status_idle_hint": ("Upload a file and start conversion.", "上传文件后开始转换。"),+ "status_latest": ("Latest status", "最新状态"),+ "status_step_prepare": ("Prepare", "准备请求"),+ "status_step_check": ("Check service", "检查服务"),+ "status_step_submit": ("Submit", "提交任务"),+ "status_step_queue": ("Queue", "排队"),+ "status_step_process": ("Parse", "解析中"),+ "status_step_download": ("Download", "下载结果"),+ "status_step_outputs": ("Build outputs", "整理输出"),+ "status_step_done": ("Done", "完成"),+ "status_step_failed": ("Failed", "失败"),+ "preparing_request": ("Preparing request...", "正在准备请求…"),+ "checking_server": ("Checking server status...", "正在检查服务状态…"),+ "submitting_task": ("Submitting task...", "正在提交任务…"),+ "queued_locally": ("Queued locally", "本地排队中"),+ "queued_on_server": ("Queued on server", "服务端排队中"),+ "processing_on_server": ("Processing on server...", "服务端解析中…"),+ "processing_elapsed": ("Processing on server ({elapsed}s)", "服务端解析中({elapsed} 秒)"),+ "downloading_result": ("Task completed, downloading result...", "任务已完成,正在下载结果…"),+ "processing_output": ("Preparing outputs...", "正在整理输出…"),+ "completed": ("Completed", "已完成"),+ "completed_elapsed": ("Completed ({elapsed}s)", "已完成({elapsed} 秒)"),+ "failed": ("Failed: {error}", "失败:{error}"),+ "missing_input": ("input file does not exist", "输入文件不存在"),+ "unsupported_input": ("unsupported file type '.{suffix}'", "不支持的文件类型 '.{suffix}'"),+ "invalid_tier": ("Invalid tier slider position", "解析档位无效"),+}+++def translations() -> dict[str, dict[str, str]]:+ """为原生组件提供命名空间词典,中文地区统一使用简体中文。"""+ english = {f"mineru.{key}": pair[0] for key, pair in MESSAGES.items()}+ chinese = {f"mineru.{key}": pair[1] for key, pair in MESSAGES.items()}+ return {"en": english, "zh": chinese, "zh-CN": chinese, "zh-TW": chinese}+++def localized_text(key: str, **values: object) -> str:+ """为文本叶节点生成双语标记;参数只作为转义后的普通文本插入。"""+ english, chinese = (template.format(**values) for template in MESSAGES[key])+ return _localized_span(key, english, chinese)+++def _localized_span(key: str, english: str, chinese: str) -> str:+ """统一转义标记属性与可见文字,避免错误详情成为活动 HTML。"""+ return (+ f'<span data-mineru-i18n-key="{html.escape(key, quote=True)}"'+ f' data-mineru-i18n-en="{html.escape(english, quote=True)}"'+ f' data-mineru-i18n-zh="{html.escape(chinese, quote=True)}">{html.escape(chinese)}</span>'+ )+++def _message_pair(message: str) -> tuple[str, str]:+ """按固定消息及已知参数模板翻译应用提示,未知详情保留原文。"""+ for pair in MESSAGES.values():+ if message in pair:+ return pair+ if message.startswith("Failed: "):+ return tuple(template.format(error=detail) for template, detail in zip(MESSAGES["failed"], _message_pair(message[8:])))+ for prefix in ("tier_unavailable: ", "page_range_invalid: "):+ if message.startswith(prefix):+ return tuple(prefix + detail for detail in _message_pair(message[len(prefix) :]))+ patterns = (+ (r"Processing on server \((?P<elapsed>[\d.]+)s\)", "processing_elapsed"),+ (r"Completed \((?P<elapsed>[\d.]+)s\)", "completed_elapsed"),+ (r"unsupported file type '\.(?P<suffix>[^']*)'", "unsupported_input"),+ (r"单次最多解析 (?P<limit>\d+) 页,当前选择了 (?P<count>\d+) 页。", "page_limit_exceeded"),+ )+ for pattern, key in patterns:+ if match := re.fullmatch(pattern, message):+ return tuple(template.format(**match.groupdict()) for template in MESSAGES[key])+ for key in ("queued_locally", "queued_on_server"):+ english, chinese = MESSAGES[key]+ if message.startswith(english) and set(message[len(english) :]) <= {"."}:+ return message, chinese + message[len(english) :]+ return message, message+++def localized_message(message: str) -> str:+ """保持后端状态协议不变,只在生成界面 HTML 时附加双语显示。"""+ return _localized_span("status_message", *_message_pair(message))+++def preview_placeholder(key: str) -> str:+ """保留预览占位容器,只对内部文字应用本地化。"""+ return f'<div class="mineru-kit-empty-preview">{localized_text(key)}</div>'+++__all__ = ["MESSAGES", "localized_message", "localized_text", "preview_placeholder", "translations"]diff --git a/mineru/kit/gradio/preview.py b/mineru/kit/gradio/preview.pyindex 94079817..05e67c5a 100644--- a/mineru/kit/gradio/preview.py+++ b/mineru/kit/gradio/preview.py@@ -1,45 +1,12 @@-"""基于 schema 2.0 Middle JSON 的 Gradio 文档预览和布局标注。"""+"""Gradio 布局预览的文件适配,绘制能力由 DocVortex 统一维护。"""from __future__ import annotations-from io import BytesIOfrom pathlib import Path-from typing import Any, Iterable-from pypdf import PageObject, PdfReader, PdfWriter-from reportlab.pdfgen import canvas+from docvortex.visualization import render_layout_pdf-from ...types import BlockBase, BlockType, MiddleJson, PageInfo--_VISUAL_PARENT_TYPES = {- BlockType.IMAGE,- BlockType.TABLE,- BlockType.CHART,- BlockType.CODE,-}--_BLOCK_COLORS: dict[str, tuple[float, float, float]] = {- "text": (0.60, 0.05, 0.30),- "ref_text": (0.45, 0.20, 0.65),- "doc_title": (0.20, 0.20, 0.80),- "paragraph_title": (0.20, 0.40, 0.90),- "equation": (0.00, 0.60, 0.10),- "list": (0.10, 0.60, 0.35),- "index": (0.10, 0.60, 0.35),- "image_body": (0.30, 0.85, 0.05),- "image_caption": (0.10, 0.55, 0.90),- "image_footnote": (0.95, 0.45, 0.10),- "table_body": (0.80, 0.80, 0.00),- "table_caption": (1.00, 0.85, 0.10),- "table_footnote": (0.55, 0.90, 0.25),- "chart_body": (0.30, 0.85, 0.05),- "chart_caption": (0.10, 0.55, 0.90),- "chart_footnote": (0.95, 0.45, 0.10),- "code_body": (0.40, 0.00, 0.80),- "algorithm_body": (0.40, 0.00, 0.80),- "code_caption": (0.70, 0.35, 0.95),- "code_footnote": (0.85, 0.70, 0.95),-}+from ...types import MiddleJsondef draw_layout_overlay(@@ -49,114 +16,15 @@ def draw_layout_overlay(*,page_indices: tuple[int, ...] = (),) -> None:- """将当前 Middle JSON 的语义 bbox 绘制到 origin PDF,生成布局预览。"""+ """读取原始 PDF 并写出共享绘制结果,保留 Gradio 的调用和文件契约。"""if not isinstance(middle_json, MiddleJson):raise TypeError("middle_json must be a MiddleJson instance")if not origin_pdf_path.is_file():raise FileNotFoundError(origin_pdf_path)- reader = PdfReader(str(origin_pdf_path))- writer = PdfWriter()- pages_by_original_idx = {page.page_idx: page for page in middle_json.pages}- for output_index, source_page in enumerate(reader.pages):- middle_page = _page_for_output_index(- output_index,- pages_by_original_idx,- middle_json.pages,- page_indices,- )- overlay = _build_page_overlay(source_page, middle_page)- if overlay is not None:- page_copy = PageObject.create_blank_page(- None,- width=float(source_page.cropbox.width),- height=float(source_page.cropbox.height),- )- page_copy.merge_page(source_page)- page_copy.merge_page(overlay)- writer.add_page(page_copy)- else:- writer.add_page(source_page)-+ pdf_bytes = render_layout_pdf(origin_pdf_path.read_bytes(), middle_json.pages, page_indices=page_indices or None)output_path.parent.mkdir(parents=True, exist_ok=True)- with output_path.open("wb") as output_file:- writer.write(output_file)---def _page_for_output_index(- output_index: int,- pages_by_original_idx: dict[int, PageInfo],- pages: list[PageInfo],- page_indices: tuple[int, ...],-) -> PageInfo | None:- """按裁页映射优先、页面顺序回退选择 overlay 对应的 Middle 页面。"""- if page_indices and output_index < len(page_indices):- mapped = pages_by_original_idx.get(page_indices[output_index])- if mapped is not None:- return mapped- if output_index < len(pages):- return pages[output_index]- return None---def _build_page_overlay(page: Any, middle_page: PageInfo | None) -> PageObject | None:- """为单个 PDF 页面生成透明 bbox overlay 页面。"""- if middle_page is None:- return None- width = float(page.cropbox.width)- height = float(page.cropbox.height)- if width <= 0 or height <= 0:- return None- boxes = list(_iter_overlay_boxes(middle_page.blocks))- if not boxes:- return None-- packet = BytesIO()- painter = canvas.Canvas(packet, pagesize=(width, height))- painter.setLineWidth(1.0)- for block_type, bbox in boxes:- x0, y0, x1, y1 = _normalized_bbox_to_pdf(bbox, width, height)- color = _BLOCK_COLORS.get(block_type, (0.90, 0.10, 0.10))- painter.setStrokeColorRGB(*color)- painter.rect(x0, y0, max(0.5, x1 - x0), max(0.5, y1 - y0), stroke=1, fill=0)- painter.save()- packet.seek(0)- return PdfReader(packet).pages[0]---def _iter_overlay_boxes(blocks: Iterable[BlockBase]) -> Iterable[tuple[str, tuple[float, float, float, float]]]:- """遍历当前 block 树并为视觉父块选择子块 bbox,避免重复绘制。"""- for block in blocks:- block_type = _block_type_value(block)- if block.bbox is not None and block.type not in _VISUAL_PARENT_TYPES:- yield block_type, tuple(float(item) for item in block.bbox)- content = getattr(block, "content", None)- children = [child for child in content if isinstance(child, BlockBase)] if isinstance(content, list) else []- if block.type in _VISUAL_PARENT_TYPES and children:- for child in children:- if child.bbox is not None:- yield _block_type_value(child), tuple(float(item) for item in child.bbox)- elif children:- yield from _iter_overlay_boxes(children)---def _normalized_bbox_to_pdf(- bbox: tuple[float, float, float, float],- width: float,- height: float,-) -> tuple[float, float, float, float]:- """把左上原点的归一化 bbox 转换为 PDF 左下原点坐标。"""- x0 = min(max(bbox[0], 0.0), 1.0) * width- x1 = min(max(bbox[2], 0.0), 1.0) * width- top = min(max(bbox[1], 0.0), 1.0) * height- bottom = min(max(bbox[3], 0.0), 1.0) * height- return x0, height - bottom, x1, height - top---def _block_type_value(block: BlockBase) -> str:- """统一读取 Enum 或字符串 block 类型值。"""- value = getattr(block.type, "value", block.type)- return str(value)+ output_path.write_bytes(pdf_bytes)__all__ = ["draw_layout_overlay"]diff --git a/mineru/kit/gradio/status.py b/mineru/kit/gradio/status.pyindex ed80d5de..a5bb144c 100644--- a/mineru/kit/gradio/status.py+++ b/mineru/kit/gradio/status.py@@ -3,12 +3,13 @@from __future__ import annotationsimport asyncio-import htmlimport timefrom collections.abc import AsyncIterator, Callablefrom dataclasses import dataclass, fieldfrom typing import Any+from .i18n import localized_message, localized_text as _localized_text+DEFAULT_STATUS = "Upload a file and start conversion."STATUS_PREPARING_REQUEST = "Preparing request..."STATUS_CHECKING_SERVER = "Checking server status..."@@ -20,16 +21,7 @@ STATUS_DOWNLOADING_RESULT = "Task completed, downloading result..."STATUS_PROCESSING_OUTPUT = "Preparing outputs..."STATUS_COMPLETED = "Completed"-_STEPS = (- ("prepare", "Prepare", "准备请求"),- ("check", "Check service", "检查服务"),- ("submit", "Submit", "提交任务"),- ("queue", "Queue", "排队"),- ("process", "Parse", "解析中"),- ("download", "Download", "下载结果"),- ("outputs", "Build outputs", "整理输出"),- ("done", "Done", "完成"),-)+_STEPS = ("prepare", "check", "submit", "queue", "process", "download", "outputs", "done")_MESSAGE_STEPS = {STATUS_PREPARING_REQUEST: 0,STATUS_CHECKING_SERVER: 1,@@ -43,15 +35,6 @@ _MESSAGE_STEPS = {}-def _localized_text(key: str, english: str, chinese: str) -> str:- """输出中英文属性,复用页面现有的浏览器语言本地化逻辑。"""- return (- f'<span data-mineru-i18n-key="{html.escape(key, quote=True)}"'- f' data-mineru-i18n-en="{html.escape(english, quote=True)}"'- f' data-mineru-i18n-zh="{html.escape(chinese, quote=True)}">{html.escape(chinese)}</span>'- )--@dataclassclass StatusPanelState:"""保存一次转换的阶段和单调时钟,不在会话之间共享状态。"""@@ -101,10 +84,10 @@ class StatusPanelState:failed = self.message.startswith("Failed:")completed = self.message == STATUS_COMPLETEDitems: list[str] = []- for index, (key, english, chinese) in enumerate(_STEPS):+ for index, key in enumerate(_STEPS):if failed and index == self.step_index:state = "is-active is-error"- key, english, chinese = "failed", "Failed", "失败"+ key = "failed"elif completed or index < self.step_index:state = "is-done"elif index == self.step_index:@@ -113,7 +96,7 @@ class StatusPanelState:state = "is-pending"items.append(f'<div class="status-step {state}"><span class="status-dot"></span>'- f'<span class="status-label">{_localized_text("status_step_" + key, english, chinese)}</span></div>'+ f'<span class="status-label">{_localized_text("status_step_" + key)}</span></div>')latest = self.messageif self._processing_started is not None:@@ -124,11 +107,11 @@ class StatusPanelState:elif completed and self.processing_elapsed is not None:latest = f"{STATUS_COMPLETED} ({self.processing_elapsed:.1f}s)"if self.message == DEFAULT_STATUS:- title = _localized_text("status_idle_title", "Waiting", "等待任务")- latest_html = _localized_text("status_idle_hint", DEFAULT_STATUS, "上传文件后开始转换。")+ title = _localized_text("status_idle_title")+ latest_html = _localized_text("status_idle_hint")else:- title = _localized_text("status_latest", "Latest status", "最新状态")- latest_html = html.escape(latest)+ title = _localized_text("status_latest")+ latest_html = localized_message(latest)return ('<div class="status-steps-panel">'f'<div class="status-panel-title">{title}</div>'diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.jsindex 1d6f22bb..37ba4a56 100644--- a/mineru/resources/gradio_app.js+++ b/mineru/resources/gradio_app.js@@ -1,5 +1,5 @@() => {- const APP_SCRIPT_VERSION = "v1-pdf-page-range-crossing";+ const APP_SCRIPT_VERSION = "v1-project-bilingual-preview";if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {return;}@@ -18,38 +18,9 @@"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",};- // 只把中文浏览器语言映射为中文;其他所有语言统一降级到英文。- const normalizeMineruLocale = (locale) => {- const normalized = String(locale || "").toLowerCase();- if (normalized.startsWith("zh")) {- return "zh";- }- return "en";- };-- // 以浏览器首选语言为准;非中文语言包括 en/ja/ko/fr 等都统一使用英文文案。- const resolveMineruLocale = () => {- if (typeof navigator !== "undefined") {- const languages = Array.from(navigator.languages || []);- const primaryLocale = languages[0] || navigator.language;- if (primaryLocale) {- return normalizeMineruLocale(primaryLocale);- }- }- return normalizeMineruLocale(document.documentElement.getAttribute("lang"));- };-- // Gradio 只会自动翻译组件属性;header/status 这类自定义 HTML 需要前端按浏览器语言补一次。- const localizeMineruCustomText = () => {- const locale = resolveMineruLocale();- document.querySelectorAll("[data-mineru-i18n-key]").forEach((item) => {- const localizedText = item.getAttribute(`data-mineru-i18n-${locale}`)- || item.getAttribute("data-mineru-i18n-en");- if (localizedText !== null && item.textContent !== localizedText) {- item.textContent = localizedText;- }- });- };+ const i18n = window.__mineruI18n = __MINERU_I18N__;+ // HTML 回调和前端事件使用同一份词典与首选语言规则。+ const localizeMineruCustomText = () => i18n.localize();// 读取浏览器本地偏好时做容错,避免隐私模式禁用 localStorage 影响页面初始化。const getOfficePreviewNoticeIgnored = () => {@@ -242,7 +213,10 @@const uiObserver = new MutationObserver(() => {refreshMineruCustomHtml();});- uiObserver.observe(document.body, { childList: true, subtree: true });+ uiObserver.observe(document.body, {+ childList: true, subtree: true, characterData: true, attributes: true,+ attributeFilter: ["title", "aria-label", "data-mineru-i18n-en", "data-mineru-i18n-zh"],+ });}document.addEventListener("click", (event) => {diff --git a/mineru/resources/gradio_download.js b/mineru/resources/gradio_download.jsindex 0c018fff..bcb07c96 100644--- a/mineru/resources/gradio_download.js+++ b/mineru/resources/gradio_download.js@@ -1,5 +1,7 @@// 按结果标识协调下载请求、按钮状态和浏览器下载,丢弃旧文档的回执。(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" });@@ -14,7 +16,7 @@state.pending.clear();return ["", ...formats.map(() => null), ...formats.map(() => ""), ...formats.map(() => ""),- ...formats.map(([, name]) => button(name, false)), "",+ ...formats.map(([, name]) => button(name === "LaTeX bundle" ? text("latex_bundle") : name, false)), "",];}if (action === "activate") {@@ -27,13 +29,13 @@if (!runId || state.runId !== runId || state.pending.has(format)) return [skip(), skip(), skip()];const token = JSON.stringify({ run_id: runId, sequence: ++state.sequence });state.pending.set(format, token);- return [token, button(`${label} · 准备中…`, false), ""];+ return [token, button(`${label} · ${text("preparing_download")}`, false), ""];}if (action === "busy") {const [token, runId] = args;// 即使开始回执晚于换文件或清除,也只能修改当前仍在等待的同一个请求。if (!token || state.pending.get(format) !== token || !runId || state.runId !== runId) return [skip(), skip()];- return [button(`${label} · 准备中…`, false), ""];+ return [button(`${label} · ${text("preparing_download")}`, false), ""];}if (action === "complete") {const [file, receiptText, runId] = args;@@ -45,8 +47,8 @@if (request.run_id !== runId) return [skip(), skip()];state.pending.delete(format);if (receipt.error || !file?.url) {- const message = receipt.error || "未获得下载文件,请重试。";- return [button(label, true), `<div role="alert">${escapeHtml(label)} 下载失败:${escapeHtml(message)}</div>`];+ const error = message(receipt.error) || text("missing_download");+ return [button(label, true), `<div role="alert">${escapeHtml(text("download_failed", { format: label, error }))}</div>`];}const anchor = document.createElement("a");anchor.href = file.url;diff --git a/mineru/resources/gradio_i18n.js b/mineru/resources/gradio_i18n.jsnew file mode 100644index 00000000..3a482e00--- /dev/null+++ b/mineru/resources/gradio_i18n.js@@ -0,0 +1,56 @@+(messages) => {+ // 首选语言独立于服务端和 Gradio 当前 locale,所有中文地区统一简体中文。+ const resolveLocale = () => {+ const primary = typeof navigator === "undefined" ? "" : navigator.languages?.[0] || navigator.language || "";+ return /^zh(?:-|$)/i.test(primary) ? "zh" : "en";+ };+ // 参数按字面替换,不能把用户文件名中的美元符号解释为替换表达式。+ const text = (key, values = {}, locale = resolveLocale()) => {+ const template = messages[key]?.[locale === "zh" ? 1 : 0] ?? key;+ return template.replace(/\{(\w+)\}/g, (match, name) => String(values[name] ?? match));+ };+ // 只识别应用词典中的完整固定消息,不改写外部错误详情。+ const message = (value) => {+ const entry = Object.entries(messages).find(([, pair]) => pair.includes(value));+ return entry ? text(entry[0]) : value;+ };+ // 仅校正 MinerU 自己定义的组件文案;框架的上传提示、工具栏和页脚保留原生语言。+ const localizeProjectLabels = (root) => {+ const selectors = [+ ".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",+ ];+ root.querySelectorAll(selectors.join(",")).forEach((element) => {+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);+ let node;+ while ((node = walker.nextNode())) {+ const original = node.textContent.trim();+ let translated = message(original);+ const tier = /^(?:解析 tier:|Parsing tier: )(\w+)$/.exec(original);+ if (tier) translated = text("tier_value", { tier: tier[1], notice: "" });+ if (translated !== original) node.textContent = node.textContent.replace(original, () => translated);+ }+ });+ };+ // 自定义 HTML 只处理明确标记的叶节点或属性,绝不遍历文档正文做替换。+ const localize = (root = document) => {+ const locale = resolveLocale();+ root.querySelectorAll("[data-mineru-i18n-key]").forEach((item) => {+ const key = item.getAttribute("data-mineru-i18n-key");+ const value = item.getAttribute(`data-mineru-i18n-${locale}`) ?? text(key);+ const attributes = item.getAttribute("data-mineru-i18n-attr");+ if (attributes) {+ attributes.split(" ").forEach((name) => {+ if (item.getAttribute(name) !== value) item.setAttribute(name, value);+ });+ } else if (item.textContent !== value) item.textContent = value;+ });+ localizeProjectLabels(root);+ if (document.title !== text("header_title")) document.title = text("header_title");+ };+ return { text, message, resolveLocale, localize };+}diff --git a/mineru/resources/gradio_page_range.js b/mineru/resources/gradio_page_range.jsindex 4d5de67a..b974d739 100644--- a/mineru/resources/gradio_page_range.js+++ b/mineru/resources/gradio_page_range.js@@ -1,6 +1,7 @@(tiers, flashOnlyExtensions, maxPages, file, position, metadata, previous, handleAValue, handleBValue, tierSelection) => {// 纯前端状态转换:经原生组件事件读写值,不逐次向 Python 发送拖动请求。// 内部元数据使用 JSON 文本,避免不同 Gradio 版本的 JSON 组件封装差异。+ const { text, message } = window.__mineruI18n;metadata = JSON.parse(metadata || "{}");previous = JSON.parse(previous || "{}");tierSelection = JSON.parse(tierSelection);@@ -65,26 +66,26 @@const start = Math.min(state.handle_a, state.handle_b);const end = Math.max(state.handle_a, state.handle_b);const selected = end - start + 1;- const limitText = maxPages === null ? "不限页数" : `最多 ${maxPages} 页`;+ const limitText = maxPages === null ? text("page_unlimited") : text("page_limit", { count: maxPages });const summary = `<div class="mineru-page-values" data-range-visible="${visible}" data-start-handle="${state.start_handle}">`- + `<span>起始页 <strong>${start}</strong></span>`- + `<span class="mineru-page-selection">[${start}-${end}] · ${selected} 页</span>`- + `<span>结束页 <strong>${end}</strong></span></div>`+ + `<span>${text("start_page")} <strong>${start}</strong></span>`+ + `<span class="mineru-page-selection">[${start}-${end}] · ${text("page_count", { count: selected })}</span>`+ + `<span>${text("end_page")} <strong>${end}</strong></span></div>`+ `<div class="mineru-page-axis"><span>1</span><span>${limitText}</span><span>${count}</span></div>`;- const notice = flashUnavailable ? "该格式仅支持 Flash,当前服务不可用"- : needsRange && !count ? (state.error || "正在读取 PDF 页数…") : "";+ const notice = flashUnavailable ? text("flash_unavailable")+ : needsRange && !count ? (message(state.error) || text("reading_pages")) : "";const range = visible ? (start === end ? String(start) : `${start}-${end}`) : "";// 两个端点始终保留完整文档跨度,不能把轨道范围截短为页数上限。const slider = (value, label) => update({ minimum: 1, maximum: Math.max(1, count), value, interactive, label });return [- slider(state.handle_a, state.start_handle === "a" ? "起始页" : "结束页"),- slider(state.handle_b, state.start_handle === "b" ? "起始页" : "结束页"),+ slider(state.handle_a, state.start_handle === "a" ? text("start_page") : text("end_page")),+ slider(state.handle_b, state.start_handle === "b" ? text("start_page") : text("end_page")),summary, range, JSON.stringify(state),update({ interactive: Boolean(path) && !flashUnavailable && (!needsRange || count > 0) }),update({ value: escapeHtml(notice), visible: Boolean(notice) }),// 同一事件同时更新值、标签和页码,程序赋值无需再触发 tier.input。update({ value: effectivePosition, interactive: !flashOnly && tiers.length > 1 }),- `解析 tier:${selectedTier}${flashUnavailable ? "(当前服务不可用)" : ""}`,+ text("tier_value", { tier: selectedTier, notice: flashUnavailable ? text("tier_unavailable_suffix") : "" }),JSON.stringify(tierSelection),];}diff --git a/pyproject.toml b/pyproject.tomlindex ea74963d..709ea7fb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -38,7 +38,7 @@ classifiers = ["Programming Language :: Python :: 3.13",]dependencies = [- "docvortex>=0.2.1,<1.0.0",+ "docvortex>=0.2.2,<1.0.0","mineru-vl-utils>=1.2.1,<2","metafile-render>=0.3.0,<1.0.0","mineru-llama-cpp>=0.1.0,<1",diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex 8dafbbc8..c4b4ac03 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -1006,7 +1006,7 @@ def test_gradio_ocr_control_visibility_reset_and_event_binding(tmp_path: Path) -capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash", "standard"), ("zip",), ("file_id",))demo = build_gradio_app(Mock(), capabilities, output_root=tmp_path, enable_example=False)checkbox = next(block for block in demo.blocks.values() if block.__class__.__name__ == "Checkbox")- assert checkbox.label == "强制 OCR" and checkbox.value is False and checkbox.visible is False+ assert checkbox.label.key == "mineru.force_ocr" and checkbox.value is False and checkbox.visible is Falseupdate = next(fn for fn in demo.fns.values() if fn.name == "update_ocr_control")assert len(update.inputs) == 1 and update.inputs[0].__class__.__name__ == "File"for path, visible in (("first.pdf", True), ("second.PDF", True), ("photo.png", False), ("book.docx", False), (None, False)):@@ -1058,7 +1058,11 @@ def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -enable_example=False,)tab_labels = [component.label for component in app.blocks.values() if component.__class__.__name__ == "Tab"]- assert tab_labels == ["Markdown 渲染", "Markdown 源码", "Structured Content 源码"]+ assert [label.key for label in tab_labels] == [+ "mineru.markdown_rendered",+ "mineru.markdown_source",+ "mineru.structured_source",+ ]download_buttons = [componentfor component in app.blocks.values()@@ -1423,3 +1427,83 @@ def test_gradio_output_failure_stops_timer_and_allows_next_conversion(tmp_path:assert all(item["interactive"] is False for item in updates[-1][-6:])asyncio.run(scenario())++[email protected]("page_indices", [(), (2, 0, 1)])+def test_layout_preview_matches_shared_renderer_and_pdf_document(tmp_path: Path, page_indices: tuple[int, ...]) -> None:+ """三个公开入口使用相同页映射、边框和页面属性,缺失页不回退到其他结果。"""+ from docvortex.document.pdf.document import PDFDocument+ from docvortex.visualization import render_layout_pdf+ from mineru.kit.gradio.preview import draw_layout_overlay++ source = tmp_path / "source.pdf"+ source.write_bytes(_pdf_bytes(page_count=3))+ middle = _middle_json(page_indices=(1, 2))+ before = middle.model_dump(mode="json")+ expected = render_layout_pdf(source.read_bytes(), middle.pages, page_indices=page_indices or None)+ preview = tmp_path / "preview" / "layout.pdf"+ draw_layout_overlay(middle, source, preview, page_indices=page_indices)+ document_output = tmp_path / "document.pdf"+ with PDFDocument(source.read_bytes()) as document:+ document.draw_layout_bbox(middle.pages, str(document_output), page_indices=page_indices or None)+ expected_pages = PdfReader(io.BytesIO(expected)).pages+ for output in (preview, document_output):+ actual_pages = PdfReader(output).pages+ assert len(actual_pages) == 3+ for actual, wanted in zip(actual_pages, expected_pages):+ assert actual.mediabox == wanted.mediabox+ assert actual.cropbox == wanted.cropbox+ assert actual.rotation == wanted.rotation+ wanted_content = wanted.get_contents()+ if wanted_content is None:+ assert actual.get_contents() is None+ else:+ assert actual.get_contents().get_data() == wanted_content.get_data()+ assert middle.model_dump(mode="json") == before+ missing_page = 1 if page_indices else 0+ assert expected_pages[missing_page].get_contents() is None+++def test_layout_preview_rejects_invalid_input_without_writing(tmp_path: Path) -> None:+ """薄封装保留输入校验,并在映射非法时不写入布局产物。"""+ from mineru.kit.gradio.preview import draw_layout_overlay++ source = tmp_path / "source.pdf"+ output = tmp_path / "layout.pdf"+ with pytest.raises(TypeError, match="MiddleJson"):+ draw_layout_overlay({}, source, output)+ with pytest.raises(FileNotFoundError):+ draw_layout_overlay(_middle_json(), source, output)+ source.write_bytes(_pdf_bytes())+ with pytest.raises(ValueError, match="page_indices length"):+ draw_layout_overlay(_middle_json(), source, output, page_indices=(0, 1))+ assert not output.exists()+++def test_shared_layout_failure_keeps_other_gradio_artifacts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """共享绘制失败仍由 Gradio 记录告警,其他解析文件和下载包继续生成。"""+ from mineru.kit.gradio import artifacts as artifact_module+ from mineru.kit.gradio import preview++ def fail_layout(*_args: Any, **_kwargs: Any) -> bytes:+ """模拟共享绘制引擎失败以验证产品层降级路径。"""+ raise ValueError("layout fixture failure")++ warnings = Mock()+ monkeypatch.setattr(preview, "render_layout_pdf", fail_layout)+ monkeypatch.setattr(artifact_module.logger, "warning", warnings)+ source = tmp_path / "source.pdf"+ source.write_bytes(_pdf_bytes())+ artifacts = persist_parse_result(+ ParseResult(middle_json=_middle_json()), source, output_root=tmp_path / "output", page_range=""+ )+ assert artifacts.layout_pdf_path is None+ assert artifacts.origin_pdf_path.is_file()+ assert artifacts.middle_json_path.is_file()+ assert 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()+ 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 3c6b6a14..e277e6d5 100644--- a/tests/unittest/test_kit_gradio_download.cjs+++ b/tests/unittest/test_kit_gradio_download.cjs@@ -3,7 +3,7 @@ const fs = require("node:fs");const path = require("node:path");const vm = require("node:vm");const downloads = [];-global.window = {};+global.document = {body: { appendChild() { /* 模拟临时下载链接挂载。 */ } },createElement() {@@ -11,6 +11,11 @@ global.document = {return { click() { downloads.push([this.href, this.download]); }, remove() {} };},};+// 使用产品词典和真实语言解析器;默认中文以保留既有行为断言。+Object.defineProperty(globalThis, "navigator", { value: { languages: ["zh-CN"] }, configurable: true });+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"]];// 调用实际产品脚本,保持 DOM 替身只负责记录下载行为。@@ -28,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);+ assert.equal(ready.value, label === "LaTeX bundle" ? "LaTeX 压缩包" : label);assert.equal(ready.interactive, true);assert.equal(notice, "");step("complete", format, file, receipt(token), "run-a");diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.pyindex c99d0335..dd6df36b 100644--- a/tests/unittest/test_kit_gradio_download.py+++ b/tests/unittest/test_kit_gradio_download.py@@ -11,6 +11,7 @@ from unittest.mock import Mockimport pytestfrom mineru.kit.gradio import app as gradio_app+from mineru.kit.gradio.i18n import MESSAGESfrom mineru.kit.gradio.artifacts import create_run_artifactsfrom mineru.kit.gradio.client import V1ServerCapabilities@@ -79,5 +80,7 @@ def test_frontend_download_lifecycle() -> None:node = shutil.which("node")if node is None:pytest.skip("Node.js is required for frontend state tests")- result = subprocess.run([node, str(Path(__file__).with_suffix(".cjs"))], capture_output=True, text=True, check=False)+ result = subprocess.run(+ [node, str(Path(__file__).with_suffix(".cjs"))], input=json.dumps(MESSAGES), capture_output=True, text=True, check=False+ )assert result.returncode == 0, result.stdout + result.stderrdiff --git a/tests/unittest/test_kit_gradio_i18n.cjs b/tests/unittest/test_kit_gradio_i18n.cjsnew file mode 100644index 00000000..42d51d8d--- /dev/null+++ b/tests/unittest/test_kit_gradio_i18n.cjs@@ -0,0 +1,37 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const vm = require("node:vm");+const messages = JSON.parse(fs.readFileSync(0, "utf8"));+// 加载实际产品脚本,语言用独立浏览器环境提供,不复制翻译或状态算法。+const resource = (name) => fs.readFileSync(path.join(__dirname, "../../mineru/resources/", name), "utf8");+for (const [languages, language, expected] of [+ [["zh-CN"], "zh-CN", "zh"], [["zh-TW"], "zh-TW", "zh"], [["zh-HK"], "zh-HK", "zh"],+ [["en-US"], "en-US", "en"], [["ja-JP", "zh-CN"], "ja-JP", "en"], [[], "", "en"], [[], "zh-CN", "zh"],+]) {+ const context = vm.createContext({ navigator: { languages, language }, window: {} });+ const i18n = vm.runInContext(resource("gradio_i18n.js"), context)(messages);+ 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"));+ 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,+ JSON.stringify({ tier: "standard", locked: false }));+ assert.equal(out[0].label, i18n.text("start_page"));+ assert.equal(out[3], "1-10");+ assert.ok(out[2].includes(i18n.text("page_limit", { count: 20 })));+ assert.equal(out[8], i18n.text("tier_value", { tier: "standard", notice: "" }));+ const download = vm.runInContext(resource("gradio_download.js"), context);+ const formats = [["html", "HTML"]];+ download("activate", formats, "", "", "run");+ const [token, busy] = download("begin", formats, "html", "HTML", "run");+ assert.ok(busy.value.includes(i18n.text("preparing_download")));+ const [, failure] = download("complete", formats, "html", "HTML", null,+ JSON.stringify({ request: token, error: '<script>external error</script>' }), "run");+ assert.ok(failure.includes("<script>external error</script>"));+ assert.ok(!failure.includes("<script>"));+ assert.ok(failure.includes(expected === "zh" ? "下载失败" : "download failed"));+ assert.equal(download("reset", formats)[4].value, "HTML");+}diff --git a/tests/unittest/test_kit_gradio_i18n.py b/tests/unittest/test_kit_gradio_i18n.pynew file mode 100644index 00000000..910b4111--- /dev/null+++ b/tests/unittest/test_kit_gradio_i18n.py@@ -0,0 +1,143 @@+"""双语初始化、动态文案与转换期间保留预览的行为回归。"""++from __future__ import annotations++import asyncio+import json+import shutil+import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest++from mineru.kit.gradio.app import build_gradio_app+from mineru.kit.gradio.client import V1ServerCapabilities+from mineru.kit.gradio.i18n import MESSAGES, localized_message, localized_text, translations+from mineru.parser.base import ParseResult+from test_kit_gradio import _middle_json+++def test_i18n_launch_and_component_contract(tmp_path: Path) -> None:+ """词典必须进入实际启动参数;OCR 说明在两个语言下都只有指定的一句话。"""+ demo = build_gradio_app(+ SimpleNamespace(),+ V1ServerCapabilities("http://localhost:1", ("flash",), ("zip",), ("file_id",)),+ output_root=tmp_path,+ enable_example=False,+ )+ dictionary = demo._mineru_kit_launch_kwargs["i18n"].translations_dict+ assert dictionary == translations()+ assert dictionary["zh-TW"] == dictionary["zh-CN"]+ # 只注册项目命名空间,原生组件的日语等词典继续由 Gradio 管理。+ assert set(dictionary) == {"en", "zh", "zh-CN", "zh-TW"}+ assert all(key.startswith("mineru.") for locale in dictionary.values() for key in locale)+ checkbox = next(block for block in demo.blocks.values() if block.__class__.__name__ == "Checkbox")+ assert checkbox.info.key == "mineru.force_ocr_info"+ assert dictionary["zh-CN"][checkbox.info.key] == "忽略 PDF 文本层并进行 OCR"+ assert dictionary["en"][checkbox.info.key] == "Ignore the PDF text layer and perform OCR"+ assert "__MINERU_I18N__" not in demo._mineru_kit_js+++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')+ assert "<img" not in value and "<img" in value and "$& 中文.pdf" in value+ for message, expected in [+ ("Failed: input file does not exist", "输入文件不存在"),+ ("Failed: unsupported file type '.exe'", "不支持的文件类型"),+ ("Failed: page_range_invalid: 单次最多解析 20 页,当前选择了 25 页。", "At most 20 pages"),+ ("Failed: <script>unknown detail</script>", "<script>unknown detail</script>"),+ ]:+ rendered = localized_message(message)+ assert expected in rendered and "<script>" not in rendered+++def test_frontend_language_policy_and_dynamic_events() -> None:+ """同一前端脚本在不同浏览器首选语言下覆盖页码、下载与错误提示。"""+ node = shutil.which("node")+ if node is None:+ pytest.skip("Node.js is required for frontend state tests")+ result = subprocess.run(+ [node, str(Path(__file__).with_suffix(".cjs"))],+ input=json.dumps(MESSAGES),+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr++[email protected]("outcome", ["success", "parse_failure", "output_failure"])+def test_conversion_preserves_all_preview_components_until_success(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ outcome: str,+) -> None:+ """暂停真实生成器,确认首帧、处理状态和失败都不改变已有四种预览。"""+ from mineru.kit.gradio import app as app_module++ source = tmp_path / "document.csv"+ source.write_text("a,b\n1,2\n", encoding="utf-8")++ async def scenario() -> None:+ """用事件控制解析完成,模拟前端按 Gradio skip 语义保留已有界面。"""+ started = asyncio.Event()+ finish = asyncio.Event()++ async def parse_file(*_args: object, **kwargs: object) -> ParseResult:+ """先通知处理阶段,待测试放行后返回结果或抛出解析异常。"""+ kwargs["status_callback"]("Processing on server...")+ started.set()+ await finish.wait()+ if outcome == "parse_failure":+ raise RuntimeError("test parse failure")+ return ParseResult(middle_json=_middle_json(with_image=False, file_suffix="csv"))++ def fail_output(*_args: object, **_kwargs: object) -> None:+ """模拟解析已成功但本地输出整理失败。"""+ raise OSError("test output failure")++ if outcome == "output_failure":+ monkeypatch.setattr(app_module, "persist_parse_result", fail_output)+ demo = build_gradio_app(+ SimpleNamespace(parse_file=parse_file),+ 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")+ updates: list[tuple[object, ...]] = []++ async def collect() -> None:+ """独立消费生成器,避免测试本身阻挡状态通知和任务启动。"""+ async for update in handler(str(source), 0, ""):+ updates.append(update)++ consumer = asyncio.create_task(collect())+ try:+ await asyncio.wait_for(started.wait(), timeout=3)+ assert updates+ assert all(update[4:8] == ({"__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])+ if outcome == "success":+ assert updates[-1][7]["visible"] is True+ assert "结果已生成" in updates[-1][7]["value"]+ assert updates[-1][8] is not None+ else:+ assert updates[-1][4:8] == ({"__type__": "update"},) * 4+ assert updates[-1][8] is None+ assert "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 preview("new.pdf")[0]["value"] == "new.pdf"++ asyncio.run(scenario())diff --git a/tests/unittest/test_kit_gradio_page_range.cjs b/tests/unittest/test_kit_gradio_page_range.cjsindex ebae3ba0..3c78aeee 100644--- a/tests/unittest/test_kit_gradio_page_range.cjs+++ b/tests/unittest/test_kit_gradio_page_range.cjs@@ -2,6 +2,11 @@ const assert = require("node:assert/strict");const fs = require("node:fs");const path = require("node:path");const vm = require("node:vm");+// 使用产品词典和真实语言解析器;默认中文以保留既有行为断言。+Object.defineProperty(globalThis, "navigator", { value: { languages: ["zh-CN"] }, configurable: true });+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_page_range.js"), "utf8"));const tiers = ["flash", "basic", "standard", "advanced"];// 使用 Python 测试传入的统一格式集合,测试和产品代码均不维护另一份后缀清单。diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.pyindex ca12086d..7cc7492f 100644--- a/tests/unittest/test_kit_gradio_page_range.py+++ b/tests/unittest/test_kit_gradio_page_range.py@@ -18,6 +18,7 @@ from typer.testing import CliRunnerfrom mineru.errors import InvalidRequestErrorfrom mineru.filetypes import FLASH_ONLY_PARSE_EXTENSIONS, TIERED_PARSE_EXTENSIONSfrom mineru.kit.gradio import app as gradio_app+from mineru.kit.gradio.i18n import MESSAGESfrom mineru.kit.gradio import page_range as rangesfrom mineru.kit.gradio.client import V1ArtifactError, V1ServerCapabilitiesfrom mineru.kit.main import app@@ -377,9 +378,9 @@ def test_native_range_components_and_frontend_only_events(tmp_path: Path) -> Nonimport gradio as grif gradio_app._gradio_major_version(gr) >= 6:- assert set(demo._mineru_kit_launch_kwargs) == {"css", "js"}+ assert set(demo._mineru_kit_launch_kwargs) == {"css", "js", "i18n"}else:- assert demo._mineru_kit_launch_kwargs == {}+ assert set(demo._mineru_kit_launch_kwargs) == {"i18n"}assert demo.css and demo.js@@ -395,6 +396,7 @@ def test_frontend_page_range_state_machine() -> None:json.dumps(sorted(FLASH_ONLY_PARSE_EXTENSIONS)),json.dumps(sorted(TIERED_PARSE_EXTENSIONS)),],+ input=json.dumps(MESSAGES),capture_output=True,text=True,check=False,diff --git a/tests/unittest/test_kit_gradio_status.py b/tests/unittest/test_kit_gradio_status.pyindex 4ac9a0ab..7fae3fe5 100644--- a/tests/unittest/test_kit_gradio_status.py+++ b/tests/unittest/test_kit_gradio_status.py@@ -52,7 +52,7 @@ def test_queue_animation_cycles_without_restarting_on_repeated_status(message: sfor seconds, dots in [(0, 1), (3, 4), (9, 10), (10, 1)]:now[0] = 5.0 + secondsassert not state.append(message)- assert f'<div class="status-latest">{message}{"." * dots}</div>' in state.render()+ assert f'data-mineru-i18n-en="{message}{"." * dots}"' in state.render()def test_fast_completion_has_no_invented_elapsed_time_and_reset_has_eight_pending_steps() -> None:@@ -61,7 +61,7 @@ def test_fast_completion_has_no_invented_elapsed_time_and_reset_has_eight_pendinstate.append(STATUS_QUEUED_ON_SERVER)state.append(STATUS_DOWNLOADING_RESULT)state.append(STATUS_COMPLETED)- assert '<div class="status-latest">Completed</div>' in state.render()+ assert 'data-mineru-i18n-en="Completed"' in state.render()idle = status_html()assert idle.count("status-step is-pending") == 8assert 'data-mineru-i18n-en="Waiting"' in idle