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(webui): reuse prepared inputs and persistent PDF previews
myhloli82a66de5c9a9
diff --git a/docs/next/cli/mineru-kit-webui.md b/docs/next/cli/mineru-kit-webui.mdindex 64b79c52..4632b365 100644--- a/docs/next/cli/mineru-kit-webui.md+++ b/docs/next/cli/mineru-kit-webui.md@@ -10,8 +10,9 @@ Gradio 界面要求 `gradio>=6.21,<7`,使用 6.21 修复后的纯前端事件PDF 预览使用独立 iframe 和随 MinerU 分发的 PDF.js 6.3.289,支持连续阅读、翻页、页码跳转、缩放和适应宽度。核心模块、worker、CMap、标准字体及解码资源均从当前 Gradio 站点加载,预览无需外部 CDN 或 npm。-上传时显示原始 PDF,解析完成后显示所选范围的原文 PDF,并叠加可点击的布局区域。-图片解析完成后通过单页 PDF 提供相同的双向溯源交互。+本地 PDF 选择后使用浏览器文件立即预览完整文档,与上传并行,不从服务端回下载 PDF。+图片上传完成后立即在服务端准备单页 PDF,预览和解析共用该文件,不显示独立图片预览。+两类输入在解析完成后都保留原有查看器,只更新布局区域并跳到本次解析范围的第一页,保留缩放。每次切换文档回到第一页并适应宽度;浏览页码不改变解析页范围,翻页和缩放不调用 Python 解析接口。需要密码或损坏的 PDF 会显示预览错误。文字搜索、编辑、打印和缩略图不在当前预览功能范围内。静态资源和文件沿用 Gradio 的认证与文件路由,支持反向代理子路径;自定义挂载仍需传入自己的结果目录 `allowed_paths`。@@ -32,7 +33,7 @@ UI 也可安装在独立环境,通过 `--api-url` 连接推理服务。“显示区域框”默认开启。关闭后,区域在悬停或选中时显示。选中文字、点击正文链接及操作折叠控件分别执行对应的正文操作。跨页合并的段落、列表和表格会记录多个原文区域。点击右侧内容先定位首个来源,选中内容旁的“来源页”按钮可以切换关联原文页。-来源页使用原文页号,左侧查看器的页码输入使用当前预览 PDF 的页序。键盘 Tab、Enter 和空格可用于激活区域。+来源页和左侧查看器的页码输入均使用原文页号,部分页解析不改变完整预览 PDF 的页序。键盘 Tab、Enter 和空格可用于激活区域。溯源映射由 DocVortex HTML renderer 提供,WebUI 通过浏览器消息完成定位。文件切换、清除及重新转换会重置来源与选中状态。@@ -140,7 +141,7 @@ Gradio 转换事件在原有输出末尾追加 Structured Content JSON 文本,每次选择格式后,按钮会显示“准备中”,文件就绪后自动开始下载,无需再次点击。再次下载时,HTML 根据当前访问地址重新生成,其他格式复用已有文件;生成失败时显示错误并允许重试。清除、更换文件或重新解析会使旧下载请求失效。-每次解析的文件保存在独立的 `output-dir/gradio/<run-id>/` 目录,包含源文件、Middle JSON、基础文本产物以及可选的 `origin.pdf` 和图片资源。路径只向 Gradio 暴露在配置的 output root 内。+每次上传的稳定输入保存在 `output-dir/gradio/sources/<source-id>/`,图片只在此转换一次 PDF。每次解析的 Middle JSON、基础文本产物和图片资源保存在独立的 `output-dir/gradio/<run-id>/`。PDF 输入不生成 `origin.pdf`,结果持久化也不重新生成预览文件。清除或关闭会话会释放无使用者且无成功结果引用的准备文件;成功结果引用的输入沿用输出目录的保留周期。所有路径都限定在各自的源目录或结果目录中。## 界面语言@@ -154,9 +155,9 @@ Office 类文件(DOC/DOCX、PPT/PPTX、XLS/XLSX、RTF、ODT/ODS/ODP)上传Office 转换开始、失败及成功后都保留已挂载的源预览。“忽略”仅隐藏当前提示卡,“不再提示”保存浏览器偏好;转换完成不会重新加载预览框或恢复已忽略的提示。更换文件更新源预览,清除恢复空预览。-转换开始、排队、解析和整理输出期间保留当前预览及浏览位置;PDF 和图片成功生成结果后刷新预览。转换失败也保留当前预览;点击清除会恢复空预览,更换文件会显示新文件的源预览或对应格式提示。+转换开始、排队、解析和整理输出期间保留当前预览及浏览位置;PDF 和图片成功生成结果后只添加浮层,并跳到解析首个原始页面。转换失败也保留当前预览;点击清除会恢复空预览,更换文件会显示新文件的源预览或对应格式提示。-PDF 和图片会生成与解析范围一致的 `origin.pdf`,由 PDF.js 展示。浏览器根据布局区域和来源映射,用 JavaScript 绘制标框、标签与双向溯源交互浮层。+PDF.js 始终展示完整输入 PDF,图片使用上传阶段准备的 PDF。浏览器根据原始页索引绘制标框、标签和双向溯源浮层。WebUI 不因 bbox 重新打开 PDF 补裁素材;解析端负责生成所需图片,打包和恢复边界检查引用完整性。合法的无截图块不要求补图。结果导出只使用已保存语义树与素材,不依赖源文件。`mineru-webui` 提供为 `mineru-kit webui` 的独立命令名,参数与行为完全相同;旧 HTTP 协议和旧 Gradio 专属参数不再提供。@@ -165,11 +166,11 @@ Gradio 使用 Tasks 能力发现和逐文件 `upload` 描述,固定使用 PUT## 嵌入宿主的文档操作`mineru.kit.gradio` 公开导出 `GradioDocumentIO` 协议。调用 `build_gradio_app()` 时可通过关键字参数-`document_io` 注入宿主实现,统一接管 `pdf_page_metadata()`、`effective_page_range()` 和-`persist_parse_result()`。不传时沿用进程内的页数读取、选页校验和产物保存。+`document_io` 注入宿主实现,统一接管 `prepare_source()`、`pdf_page_metadata()`、`effective_page_range()` 和+`persist_parse_result()`。`prepare_source(path, *, source_id, output_root)` 返回公开的 `PreparedSource` 路径记录,图片转换和 PDFium 生命周期由此边界隔离。默认实现使用进程内工作线程;上传准备独立于模型解析槽,同一选择的并发准备会合并。界面页数回调与转换服务共享同一实例,各应用之间互不影响。选页与持久化仍在工作线程中执行,取消必须等待同步工作结束后再释放转换槽。实现的构造过程应只定义行为,不启动进程、打开 PDF 或加载模型。-HF Demo 使用该接口将三类操作委托 CPU sidecar,生产与预检共用界面构建入口,不再替换 Gradio 模块函数。+HF Demo 使用该接口将输入准备、页数、选页与持久化委托 CPU sidecar,生产与预检共用界面构建入口,不再替换 Gradio 模块函数。HF 适配代码要求支持此协议与 `document_io` 参数的 MinerU;跨越该接口升级边界时,应成对更新或回滚宿主与 MinerU。diff --git a/mineru/kit/gradio/__init__.py b/mineru/kit/gradio/__init__.pyindex eddbdcce..a9e895cd 100644--- a/mineru/kit/gradio/__init__.py+++ b/mineru/kit/gradio/__init__.py@@ -3,11 +3,13 @@from .app import build_gradio_app, launch_gradiofrom .client import GradioArtifactClient, ManagedLocalApiServer, V1ArtifactClient, V1ArtifactError, V1ServerCapabilitiesfrom .document_io import GradioDocumentIO+from .sources import PreparedSource__all__ = ["GradioArtifactClient","GradioDocumentIO","ManagedLocalApiServer",+ "PreparedSource","V1ArtifactClient","V1ArtifactError","V1ServerCapabilities",diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 35ca6df7..ab8f34b2 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -186,7 +186,7 @@ _KIT_MENU_CSS = """}.mineru-kit-pdf-preview .html-container, .mineru-kit-pdf-preview .prose,.mineru-kit-source-preview .html-container, .mineru-kit-source-preview .prose { height: 100%; padding: 0 !important; }-.mineru-kit-pdf-preview:not(:has(.mineru-pdf-frame, [role="alert"])) { display: none !important; }+.mineru-kit-pdf-preview:not(:has(.mineru-pdf-frame, [role="alert"], [role="status"])) { display: none !important; }/* HTML 源预览用固定 viewport 裁剪逻辑舞台。缩放舞台而不是 iframe 本体,避免 Safari/WebKit 在 transform iframe 时把子文档绘制层裁成局部区域。 */.mineru-source-viewport {@@ -381,6 +381,7 @@ def build_gradio_app())app_js = app_js.replace("__MINERU_TRACE__", _resource_text("gradio_trace.js"))+ app_js = app_js.replace("__MINERU_PDF_PREVIEW__", _resource_text("gradio_pdf_preview.js"))# 等待限制放在生成器内部,使其他会话也能立即显示本地排队状态。conversions = SessionConversions()conversion_service = ConversionService(@@ -404,6 +405,22 @@ def build_gradio_app(file_types=file_types,file_count="single",type="filepath",+ visible=False,+ )+ upload_control = gr.HTML(+ value="",+ html_template='<label class="mineru-upload-target"><input type="file" accept="'+ + ",".join(file_types)+ + '" />'+ '<span class="mineru-upload-label"></span></label><div class="mineru-upload-status" role="status"></div>'+ '<button type="button" class="mineru-upload-retry" hidden></button>',+ js_on_load="("+ + _resource_text("gradio_upload.js")+ + ")({element, props, upload, accepted: "+ + json.dumps(file_types)+ + ", imageExtensions: "+ + json.dumps(sorted(IMAGE_EXTENSIONS))+ + "})",elem_classes=["mineru-upload-file"],)with gr.Group():@@ -497,7 +514,7 @@ def build_gradio_app(pdf_viewer_entry = gr.File(value=str(viewer_entry), visible=False, interactive=False)epub_viewer_entry_component = gr.File(value=str(epub_viewer_entry), visible=False, interactive=False)pdf_viewer = gr.HTML(- value="",+ value='<div class="mineru-pdf-host"></div>',apply_default_css=False,# 保持原生 HTML 挂载,避免较早的 Gradio 6 忽略纯前端的 visible 更新。visible=True,@@ -594,8 +611,22 @@ def build_gradio_app(])- def update_file_preview(file_path: str | None, request: object | None = None) -> tuple[Any, ...]:- """切换源文件预览,并清除上一份文档的结果与下载状态。"""+ preview_identities: dict[str, tuple[str | None, str]] = {}++ def update_file_preview(file_path: str | None, request: object | None = None, ticket: str = "") -> tuple[Any, ...]:+ """真实选择变更才清除结果;重复 FileData 事件及迟到源回执保持当前结果。"""+ session = getattr(request, "session_hash", "") or ""+ identity = json.loads(ticket or "{}")+ if session:+ revision = identity.get("revision", 0)+ selected = (file_path, identity.get("id", ""))+ if (+ ticket and identity.get("path") != (file_path or "")+ ) or revision < conversion_service.sources.revisions.get(session, 0):+ return tuple(gr.skip() for _ in preview_outputs)+ if preview_identities.get(session) == selected:+ return tuple(gr.skip() for _ in preview_outputs)+ preview_identities[session] = selectedreset_result = (_status_html(_DEFAULT_STATUS),"",@@ -623,7 +654,7 @@ def build_gradio_app(if suffix in IMAGE_EXTENSIONS:return (_pdf_preview_update(gr, None),- _preview_update(gr, file_path, visible=True),+ _preview_update(gr, None, visible=False),_preview_update(gr, "", visible=False),_preview_update(gr, preview_placeholder("source_preview"), visible=False),*reset_result,@@ -665,6 +696,86 @@ def build_gradio_app(input_file.change(fn=None, inputs=input_file, outputs=pdf_viewer, js=pdf_preview_js("reset"), **private_event_kwargs)clear_button.click(fn=None, inputs=[], outputs=pdf_viewer, js=pdf_preview_js("clear"), **private_event_kwargs)+ source_preparation_ticket = gr.Textbox(value="", visible=False)+ source_preparation_receipt = gr.Textbox(value="", visible=False)+ source_ready = gr.Textbox(value="", visible=False)++ upload_control.change(+ fn=None,+ inputs=upload_control,+ outputs=input_file,+ js="value => window.__mineruUpload.bridge(value)",+ **private_event_kwargs,+ )++ async def prepare_uploaded_source(file_path: str | None, ticket: str, request: object | None = None) -> str:+ """上传后立即准备稳定输入,迟到回执由前端选择身份拦截。"""+ if not ticket:+ return ""+ identity = json.loads(ticket)+ source_id = uuid.UUID(identity["id"]).hex+ revision = identity["revision"]+ if type(revision) is not int or revision <= 0 or identity["path"] != (file_path or ""):+ return ""+ session = getattr(request, "session_hash", "") or ""+ receipt = {"id": source_id, "path": file_path or "", "pdf": None, "error": ""}+ try:+ if not file_path or _file_suffix(file_path) not in PDF_EXTENSIONS | IMAGE_EXTENSIONS:+ await conversion_service.sources.retire(session, revision=revision)+ else:+ prepared = await conversion_service.sources.prepare(session, Path(file_path), source_id, revision)+ if prepared.preview_pdf_path:+ path = str(prepared.preview_pdf_path)+ receipt["pdf"] = {+ "path": path,+ "url": f"{_gradio_public_base_url(request)}/gradio_api/file={quote(path, safe='/')}",+ "orig_name": prepared.preview_pdf_path.name,+ }+ except Exception as exc:+ receipt["error"] = str(exc)+ return json.dumps(receipt, ensure_ascii=False)++ prepare_uploaded_source.__annotations__["request"] = gr.Request+ prepare_input = input_file.change(+ fn=None,+ inputs=input_file,+ outputs=[source_preparation_ticket, source_ready],+ js=f"file => [({pdf_preview_js('prepare')})(file), window.__mineruPdfPreview.readyPath]",+ **private_event_kwargs,+ )+ prepare_input.then(+ fn=prepare_uploaded_source,+ inputs=[input_file, source_preparation_ticket],+ outputs=source_preparation_receipt,+ trigger_mode="multiple",+ show_progress="hidden",+ **private_event_kwargs,+ )+ source_preparation_receipt.change(+ fn=None,+ inputs=source_preparation_receipt,+ outputs=source_ready,+ js=pdf_preview_js("prepared"),+ **private_event_kwargs,+ )++ async def retire_uploaded_source(ticket: str, request: object | None = None) -> None:+ """显式清除独立释放输入租期,不依赖隐藏 File 的重复或空值变更事件。"""+ identity = json.loads(ticket)+ revision = identity.get("revision")+ if identity.get("path") == "" and type(revision) is int and revision > 0:+ await conversion_service.sources.retire(getattr(request, "session_hash", "") or "", revision=revision)++ retire_uploaded_source.__annotations__["request"] = gr.Request+ clear_source = clear_button.click(+ fn=None,+ inputs=[],+ outputs=[source_preparation_ticket, source_ready],+ js=f"() => {{ ({pdf_preview_js('clear')})(); return [({pdf_preview_js('prepare')})(null), '']; }}",+ **private_event_kwargs,+ )+ clear_source.then(fn=retire_uploaded_source, inputs=source_preparation_ticket, outputs=[], **private_event_kwargs)+source_script = _resource_text("gradio_source_preview.js")begin_source_preview = input_file.change(fn=None,@@ -748,7 +859,7 @@ def build_gradio_app(cancel_session_conversion.__annotations__["request"] = gr.Request# 显式注册幂等加载事件,初始化前端状态和自定义文案。- demo.load(fn=None, js=app_js, **private_event_kwargs)+ demo.load(fn=None, inputs=pdf_viewer_entry, js=app_js, **private_event_kwargs)preview_outputs = [pdf_preview,image_preview,@@ -763,7 +874,16 @@ def build_gradio_app(]# 文件页数只在上传后读取;前端缓存元数据,tier 切换和拖动不发起 Python 请求。- range_inputs = [input_file, tier, page_metadata, page_selection, page_handle_a, page_handle_b, tier_selection]+ range_inputs = [+ input_file,+ tier,+ page_metadata,+ page_selection,+ page_handle_a,+ page_handle_b,+ tier_selection,+ source_ready,+ ]range_outputs = [page_handle_a,page_handle_b,@@ -779,7 +899,14 @@ def build_gradio_app(range_script = _resource_text("gradio_page_range.js")# 共用一个 always_last 事件流,避免文件、元数据、清除与拖动的并行回调互相覆盖。gr.on(- triggers=[input_file.change, tier.input, page_metadata.change, page_handle_a.input, page_handle_b.input],+ triggers=[+ input_file.change,+ tier.input,+ page_metadata.change,+ page_handle_a.input,+ page_handle_b.input,+ source_ready.change,+ ],fn=None,inputs=range_inputs,outputs=range_outputs,@@ -818,7 +945,7 @@ def build_gradio_app(try:outcome = await conversion_service.execute(run,- ConversionInput(file_path, tier_position, raw_page_range, force_ocr),+ ConversionInput(file_path, tier_position, raw_page_range, force_ocr, session),public_base_url=_gradio_public_base_url(request),)return conversion_updates(outcome, status_html=run.state.render(), download_formats=_DOWNLOAD_FORMATS)@@ -888,6 +1015,8 @@ def build_gradio_app(async def unload_session(request: object | None = None) -> None:"""标签页关闭后释放会话快照,并等待剩余同步任务退出。"""await cancel_session_conversion(request)+ await conversion_service.sources.retire(getattr(request, "session_hash", "") or "")+ preview_identities.pop(getattr(request, "session_hash", "") or "", None)conversions.revisions.pop(getattr(request, "session_hash", "") or "", None)async def convert_ui(@@ -914,7 +1043,7 @@ def build_gradio_app(public_base_url = _gradio_public_base_url(request)outcome = await conversion_service.execute(run,- ConversionInput(file_path, tier_position, raw_page_range, force_ocr),+ ConversionInput(file_path, tier_position, raw_page_range, force_ocr, session, identity.get("source_id", "")),public_base_url=public_base_url,)if conversions.current(session, run_id) is not run:@@ -987,9 +1116,9 @@ def build_gradio_app(gr.on(triggers=[input_file.change, clear_button.click],fn=None,- inputs=[],+ inputs=input_file,outputs=[conversion_ticket, conversion_cancel, status_poll],- js=conversion_js("cancel"),+ js=conversion_js("cancel_source"),**private_event_kwargs,)conversion_cancel.change(@@ -1002,9 +1131,8 @@ def build_gradio_app(demo.unload(unload_session)source_preview_event = input_file.change(fn=update_file_preview,- inputs=input_file,+ inputs=[input_file, source_preparation_ticket],outputs=preview_outputs,- cancels=[convert_event, ui_convert_event],# 示例切换也会触发文件变更,预览准备期间保持状态卡片可见。show_progress="hidden",**private_event_kwargs,diff --git a/mineru/kit/gradio/artifacts.py b/mineru/kit/gradio/artifacts.pyindex 6adfb82c..5f55eba2 100644--- a/mineru/kit/gradio/artifacts.py+++ b/mineru/kit/gradio/artifacts.py@@ -20,14 +20,11 @@ from urllib.parse import quote, urlsplitfrom bs4 import BeautifulSoupfrom docvortex.assets import AssetStore, parse_image_data_uri_strict, validate_image_sidecar_path-from docvortex.document.pdf import PDFDocument-from docvortex.document.pdf.pdfium import safe_rewrite_pdf_bytes_with_pdfium_result-from docvortex.export import materialize_middle+from docvortex.export import materialize_middle, validate_materialized_assetsfrom loguru import loggerfrom ...filetypes import IMAGE_EXTENSIONS, PDF_EXTENSIONSfrom ...parser.base import ParseResult-from ...parser.page_range import parse_page_rangefrom ...render import (DocxRenderOptions,EpubRenderOptions,@@ -39,7 +36,8 @@ from ...render import (StructuredContentRenderOptions,render,)-from ...types import BlockBase, ImagePayloadBlock, MiddleJson+from ...types import ImagePayloadBlock, MiddleJson+from .sources import PreparedSourceDownloadFormat = Literal["markdown", "json", "html", "docx", "latex", "epub", "pdf"]@@ -62,14 +60,13 @@ class RunArtifacts:root: Pathstem: str- source_path: Pathmiddle_json_path: Pathmarkdown_path: Pathstructured_content_path: Pathdownloads_dir: Pathfile_suffix: str- origin_pdf_path: Path | None = None- page_indices: tuple[int, ...] = ()+ prepared_source: PreparedSource | None = None+ initial_page_idx: int | None = Nonegenerated_downloads: dict[str, Path] = field(default_factory=dict)def as_state(self) -> dict[str, Any]:@@ -77,14 +74,13 @@ class RunArtifacts:return {"root": str(self.root),"stem": self.stem,- "source_path": str(self.source_path),"middle_json_path": str(self.middle_json_path),"markdown_path": str(self.markdown_path),"structured_content_path": str(self.structured_content_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 "",- "page_indices": list(self.page_indices),+ "prepared_source": self.prepared_source.as_state() if self.prepared_source else None,+ "initial_page_idx": self.initial_page_idx,"generated_downloads": {key: str(value) for key, value in self.generated_downloads.items()},}@@ -96,7 +92,6 @@ class RunArtifacts:required = ("root","stem",- "source_path","middle_json_path","markdown_path","structured_content_path",@@ -118,13 +113,10 @@ class RunArtifacts:candidate = Path(value).resolve()_ensure_path_inside(root, candidate)generated_downloads[str(key)] = candidate- raw_indices = state.get("page_indices", [])- page_indices = tuple(int(value) for value in raw_indices) if isinstance(raw_indices, list) else ()root = Path(cast(str, state["root"])).resolve()core_paths = [Path(cast(str, state[key])).resolve()for key in (- "source_path","middle_json_path","markdown_path","structured_content_path",@@ -133,55 +125,25 @@ class RunArtifacts:]for path in core_paths:_ensure_path_inside(root, path)- origin_pdf_path = _optional_path(state.get("origin_pdf_path"))- if origin_pdf_path is not None:- _ensure_path_inside(root, origin_pdf_path)+ prepared = state.get("prepared_source")+ prepared_source = PreparedSource.from_state(prepared, source_root=root.parent / "sources") if prepared else None+ initial_page_idx = state.get("initial_page_idx")+ if initial_page_idx is not None and (type(initial_page_idx) is not int or initial_page_idx < 0):+ raise ValueError("Invalid initial preview page")return cls(root=root,stem=stem,- source_path=Path(cast(str, state["source_path"])).resolve(),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(),downloads_dir=Path(cast(str, state["downloads_dir"])).resolve(),file_suffix=cast(str, state["file_suffix"]),- origin_pdf_path=origin_pdf_path,- page_indices=page_indices,+ prepared_source=prepared_source,+ initial_page_idx=initial_page_idx,generated_downloads=generated_downloads,)-@dataclass-class _ImageContext:- """为一次渲染保存源 PDF、页面映射和已写出的图片资源。"""-- source_pdf: PDFDocument | None- source_page_by_middle_page: dict[int, int]- output_dir: Path- asset_root: Path- crop_cache: dict[tuple[int, tuple[float, ...]], bytes] = field(default_factory=dict)-- def crop_for_block(self, block: BlockBase, *, middle_page_idx: int) -> bytes | None:- """按 bbox 读取裁后 PDF 页面,仅缓存图片字节,不写出临时图片文件。"""- if self.source_pdf is None or block.bbox is None:- return None- source_page_idx = self.source_page_by_middle_page.get(middle_page_idx, middle_page_idx)- if source_page_idx < 0 or source_page_idx >= self.source_pdf.page_count:- return None- bbox = tuple(float(item) for item in block.bbox)- key = (middle_page_idx, bbox)- existing = self.crop_cache.get(key)- if existing is not None:- return existing- try:- data = self.source_pdf.crop_image(block.bbox, source_page_idx)- except Exception as exc:- logger.warning("Failed to crop Gradio PDF image page={} bbox={}: {}", source_page_idx, bbox, exc)- return None- self.crop_cache[key] = data- return data--def create_run_artifacts(source_path: Path, output_root: Path) -> RunArtifacts:"""创建一次解析专属目录,并返回全部基础产物路径。"""output_root = output_root.expanduser().resolve()@@ -193,11 +155,9 @@ def create_run_artifacts(source_path: Path, output_root: Path) -> RunArtifacts:downloads_dir = root / "downloads"downloads_dir.mkdir()source_suffix = source_path.suffix.lower() or ".bin"- source_copy = root / f"source{source_suffix}"return RunArtifacts(root=root,stem=stem,- source_path=source_copy,middle_json_path=root / "middle_json.json",markdown_path=root / "markdown.md",structured_content_path=root / "structured_content.json",@@ -215,53 +175,33 @@ def persist_parse_result() -> RunArtifacts:"""保存图片已物化的语义副本,并生成 Markdown、Structured Content 和预览文件。"""artifacts = create_run_artifacts(source_path, output_root)- shutil.copyfile(source_path, artifacts.source_path)-- with _output_stage("origin_pdf", artifacts):- origin_pdf, page_indices = _prepare_origin_pdf(- artifacts.source_path,- page_range=page_range,- output_path=artifacts.root / "origin.pdf",+ artifacts.initial_page_idx = result.pages[0].page_idx if result.pages else None+ with _output_stage("materialize", artifacts):+ materialized = _materialize_middle_json(result.middle_json, artifacts.root, asset_root=source_path.parent)+ artifacts.middle_json_path.write_text(ParseResult(middle_json=materialized).to_json(), encoding="utf-8")+ with _output_stage("markdown", artifacts):+ markdown = cast(+ str,+ render(+ materialized,+ RenderFormat.MARKDOWN,+ options=MarkdownRenderOptions(),+ ),+ )+ artifacts.markdown_path.write_text(markdown, encoding="utf-8")+ with _output_stage("structured_json", artifacts):+ structured = cast(+ dict[str, Any],+ render(+ materialized,+ RenderFormat.STRUCTURED_CONTENT,+ options=StructuredContentRenderOptions(),+ ),+ )+ artifacts.structured_content_path.write_text(+ json.dumps(structured, ensure_ascii=False, indent=2),+ encoding="utf-8",)- artifacts.origin_pdf_path = origin_pdf- artifacts.page_indices = tuple(page_indices)-- image_context = _build_image_context(- result.middle_json,- origin_pdf,- artifacts.root,- page_indices=artifacts.page_indices,- asset_root=source_path.parent,- )- try:- with _output_stage("materialize", artifacts):- materialized = _materialize_middle_json(result.middle_json, image_context)- artifacts.middle_json_path.write_text(ParseResult(middle_json=materialized).to_json(), encoding="utf-8")- with _output_stage("markdown", artifacts):- markdown = cast(- str,- render(- materialized,- RenderFormat.MARKDOWN,- options=MarkdownRenderOptions(),- ),- )- artifacts.markdown_path.write_text(markdown, encoding="utf-8")- with _output_stage("structured_json", artifacts):- structured = cast(- dict[str, Any],- render(- materialized,- RenderFormat.STRUCTURED_CONTENT,- options=StructuredContentRenderOptions(),- ),- )- artifacts.structured_content_path.write_text(- json.dumps(structured, ensure_ascii=False, indent=2),- encoding="utf-8",- )- finally:- _close_image_context(image_context)return artifacts@@ -269,7 +209,7 @@ def persist_parse_result(def render_html_preview(artifacts: RunArtifacts, *, public_base_url: str) -> str:"""用独立 iframe 展示公共 HTML renderer 的完整输出,保留样式及公式脚本。"""with _output_stage("html_preview", artifacts):- if artifacts.origin_pdf_path is not None:+ if artifacts.file_suffix in PDF_EXTENSIONS | IMAGE_EXTENSIONS:value = _render_html(artifacts, public_base_url=public_base_url, include_source_map=True)else:value = _render_html(artifacts, public_base_url=public_base_url)@@ -294,7 +234,7 @@ def _add_trace_preview(document: str, artifacts: RunArtifacts, *, middle_json: Mjson.dumps({"documentId": artifacts.root.name,- "pageIndices": list(artifacts.page_indices),+ "initialPageIdx": artifacts.initial_page_idx,"parentOrigin": f"{base.scheme}://{base.netloc}","pageLabels": MESSAGES["trace_source"],"layoutRegions": [asdict(region) for region in collect_layout_regions(middle_json.pages)],@@ -442,7 +382,6 @@ def render_download(if allowed_root is not None:_ensure_path_inside(allowed_root.resolve(), artifacts.root)for path in (- artifacts.source_path,artifacts.middle_json_path,artifacts.markdown_path,artifacts.structured_content_path,@@ -527,132 +466,43 @@ def render_download(return str(target)-def _prepare_origin_pdf(- source_path: Path,- *,- page_range: str,- output_path: Path,- keep_existing: bool = False,-) -> tuple[Path | None, list[int]]:- """将 PDF/image 输入转换为与解析范围一致的 origin PDF。"""- if keep_existing and output_path.is_file():- try:- with PDFDocument(output_path.read_bytes()) as doc:- return output_path, list(range(doc.page_count))- except Exception:- output_path.unlink(missing_ok=True)- suffix = source_path.suffix.lower().lstrip(".")- source_bytes = source_path.read_bytes()- if suffix in IMAGE_EXTENSIONS:- pdf_bytes = PDFDocument.from_image(source_bytes).bytes- output_path.write_bytes(pdf_bytes)- return output_path, [0]- if suffix not in PDF_EXTENSIONS:- return None, []- with PDFDocument(source_bytes) as doc:- page_count = doc.page_count- page_indices = parse_page_range(page_range, page_count)- if page_indices == list(range(page_count)):- output_path.write_bytes(source_bytes)- return output_path, page_indices- rewrite = safe_rewrite_pdf_bytes_with_pdfium_result(source_bytes, page_indices=page_indices)- output_path.write_bytes(rewrite.pdf_bytes or source_bytes)- return output_path, rewrite.retained_page_indices or page_indices---def _build_image_context(- middle_json: MiddleJson,- origin_pdf: Path | None,- output_dir: Path,- *,- page_indices: tuple[int, ...] = (),- asset_root: Path | None = None,-) -> _ImageContext:- """创建页面映射和源 PDF 上下文,供 Markdown 与多格式渲染共享。"""- resolved_asset_root = (asset_root or output_dir).resolve()- if origin_pdf is None:- return _ImageContext(- source_pdf=None,- source_page_by_middle_page={},- output_dir=output_dir,- asset_root=resolved_asset_root,- )- source_pdf = PDFDocument(origin_pdf.read_bytes())- page_map = _source_page_map(middle_json, source_pdf.page_count, page_indices)- return _ImageContext(- source_pdf=source_pdf,- source_page_by_middle_page=page_map,- output_dir=output_dir,- asset_root=resolved_asset_root,- )---def _source_page_map(middle_json: MiddleJson, source_page_count: int, page_indices: tuple[int, ...]) -> dict[int, int]:- """将 Middle JSON 原始页号映射到当前 origin PDF 的顺序页号。"""- original_to_output = {- original_page_idx: output_page_idx- for output_page_idx, original_page_idx in enumerate(page_indices)- if output_page_idx < source_page_count- }- page_map: dict[int, int] = {}- for position, page in enumerate(middle_json.pages):- mapped = original_to_output.get(page.page_idx)- if mapped is not None:- page_map[page.page_idx] = mapped- elif position < source_page_count:- page_map[page.page_idx] = position- elif page.page_idx < source_page_count:- page_map[page.page_idx] = page.page_idx- return page_map---def _close_image_context(context: _ImageContext) -> None:- """释放上下文持有的 PDFium 文档。"""- if context.source_pdf is not None:- context.source_pdf.close()---def _materialize_middle_json(middle_json: MiddleJson, context: _ImageContext) -> MiddleJson:+def _materialize_middle_json(middle_json: MiddleJson, output_dir: Path, *, asset_root: Path | None = None) -> MiddleJson:"""由宿主提供素材字节,统一交给 DocVortex 命名、消解冲突并改写引用。"""- images = context.output_dir / "images"- _ensure_path_inside(context.output_dir, images)+ asset_root = (asset_root or output_dir).resolve()+ images = output_dir / "images"+ _ensure_path_inside(output_dir, images)existing = AssetStore()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():- existing.add(path.relative_to(context.output_dir).as_posix(), path.read_bytes())+ existing.add(path.relative_to(output_dir).as_posix(), path.read_bytes())def resolve_image(block: ImagePayloadBlock, page_idx: int) -> tuple[bytes, str] | None:- """保持内嵌载荷、本地路径及 PDF 补裁的现有分支顺序和错误处理。"""+ """仅消费已有素材;缺失或非法图片明确失败,bbox 不触发源文件补裁。"""data: bytes | None = Noneextension = "jpg"- if block.image_base64:- try:- data, extension = parse_image_data_uri_strict(block.image_base64)- except ValueError:- return None+ if block.image_base64 is not None:+ data, extension = parse_image_data_uri_strict(block.image_base64)elif block.image_path:safe_path = validate_image_sidecar_path(block.image_path)- candidate = (context.asset_root / safe_path).resolve()- _ensure_path_inside(context.asset_root, candidate)- if candidate.is_file():- data = candidate.read_bytes()- extension = candidate.suffix.lstrip(".") or extension- elif block.bbox is not None:- data = context.crop_for_block(block, middle_page_idx=page_idx)+ candidate = (asset_root / safe_path).resolve()+ _ensure_path_inside(asset_root, candidate)+ data = candidate.read_bytes()+ extension = candidate.suffix.lstrip(".") or extensionreturn (data, extension) if data else Nonedocument, assets = materialize_middle(middle_json,existing,image_resolver=resolve_image,- asset_resolver=_asset_resolver(context.asset_root),+ asset_resolver=_asset_resolver(asset_root),)+ validate_materialized_assets(document, assets)for relative_path, payload in assets.items():- target = context.output_dir / relative_path- _ensure_path_inside(context.output_dir, target)+ target = output_dir / relative_path+ _ensure_path_inside(output_dir, target)if target.is_symlink():raise ValueError(f"Image assets must not contain symlinks: {target}")target.parent.mkdir(parents=True, exist_ok=True)@@ -738,13 +588,6 @@ def _ensure_path_inside(root: Path, target: Path) -> None:raise ValueError(f"Artifact path escapes output root: {target}") from exc-def _optional_path(value: object) -> Path | None:- """把 State 中的可选路径字段转换为绝对 Path。"""- if not isinstance(value, str) or not value:- return None- return Path(value).resolve()--def _safe_stem(value: str) -> str:"""生成文件系统安全且长度受限的任务名称。"""normalized = re.sub(r"[^\w.-]+", "_", str(value), flags=re.UNICODE).strip("._")diff --git a/mineru/kit/gradio/conversion.py b/mineru/kit/gradio/conversion.pyindex 371e1880..96749068 100644--- a/mineru/kit/gradio/conversion.py+++ b/mineru/kit/gradio/conversion.py@@ -26,6 +26,8 @@ class ConversionInput:tier_position: int | floatpage_range: strforce_ocr: bool = False+ session_id: str = ""+ source_id: str = ""@dataclass(frozen=True)diff --git a/mineru/kit/gradio/conversion_service.py b/mineru/kit/gradio/conversion_service.pyindex 3e4b2ecb..42669512 100644--- a/mineru/kit/gradio/conversion_service.py+++ b/mineru/kit/gradio/conversion_service.py@@ -39,6 +39,7 @@ from .conversion import ()from .document_io import GradioDocumentIO, LocalGradioDocumentIOfrom .page_range import validate_max_pages+from .sources import PreparedSource, SessionSourcesfrom .status import (STATUS_COMPLETED,STATUS_PREPARING_REQUEST,@@ -94,6 +95,7 @@ class ConversionService:self.max_pages = max_pagesself.slot = slotself.document_io = document_io if document_io is not None else LocalGradioDocumentIO()+ self.sources = SessionSources(self.document_io, output_root)async def execute(self,@@ -162,6 +164,30 @@ class ConversionService:emit: Callable[[str | ParseStatusUpdate], None],*,public_base_url: str,+ ) -> ConversionOutput:+ """PDF 和图片在解析排队前获取输入租期,重复解析复用上传阶段的 PDF。"""+ if validated.suffix not in PDF_EXTENSIONS | IMAGE_EXTENSIONS:+ return await self._convert_ready(run, inputs, validated, emit, public_base_url=public_base_url)+ prepared, lease = await self.sources.acquire(+ inputs.session_id or run.run_id, validated.source_path, source_id=inputs.source_id+ )+ retained = False+ try:+ output = await self._convert_ready(run, inputs, validated, emit, public_base_url=public_base_url, prepared=prepared)+ retained = not run.cancelled+ return output+ finally:+ await self.sources.release(lease, retain=retained)++ async def _convert_ready(+ self,+ run: ConversionRun,+ inputs: ConversionInput,+ validated: _ValidatedInput,+ emit: Callable[[str | ParseStatusUpdate], None],+ *,+ public_base_url: str,+ prepared: PreparedSource | None = None,) -> ConversionOutput:"""同步工作退出前始终持有执行槽,输出完成后只缓存素材路径。"""if self.slot.locked():@@ -169,10 +195,13 @@ class ConversionService:async with self.slot:run.publish(STATUS_PREPARING_REQUEST)page_text = await run_sync_output(- self.document_io.effective_page_range, validated.source_path, inputs.page_range, max_pages=self.max_pages+ self.document_io.effective_page_range,+ prepared.source_path if prepared else validated.source_path,+ inputs.page_range,+ max_pages=self.max_pages,)result = await self.client.parse_file(- validated.source_path,+ prepared.parse_path if prepared else validated.source_path,tier=validated.tier,page_range=page_text,ocr_mode="ocr" if validated.suffix in PDF_EXTENSIONS and inputs.force_ocr else "auto",@@ -189,6 +218,7 @@ class ConversionService:output_root=self.output_root,page_range=page_text,)+ artifacts.prepared_source = preparedrendered_html = await run_sync_output(render_html_preview, artifacts, public_base_url=public_base_url)structured_json = await run_sync_output(artifacts.structured_content_path.read_text, encoding="utf-8")run.artifacts = artifacts.as_state()@@ -219,11 +249,11 @@ def _prepare_preview(suffix: str, artifacts: RunArtifacts) -> PreviewPlan:"""仅描述结果预览数据,保留已有 Office、OFD、EPUB 和网页源预览。"""if suffix in OFFICE_EXTENSIONS | HTML_EXTENSIONS | MHTML_EXTENSIONS | {"ofd", "epub"}:return PreviewPlan(preserve_source=True)- preview_path = artifacts.origin_pdf_path+ preview_path = artifacts.prepared_source.preview_pdf_path if artifacts.prepared_source else Nonereturn PreviewPlan(preserve_source=False,pdf_path=preview_path,- image_path=artifacts.source_path if suffix in IMAGE_EXTENSIONS and preview_path is None else None,+ image_path=None,show_ready_placeholder=preview_path is None,)diff --git a/mineru/kit/gradio/document_io.py b/mineru/kit/gradio/document_io.pyindex 4b7d96c9..7a11bafb 100644--- a/mineru/kit/gradio/document_io.py+++ b/mineru/kit/gradio/document_io.py@@ -9,11 +9,16 @@ from ...parser.base import ParseResultfrom . import artifacts, page_rangefrom .artifacts import RunArtifactsfrom .page_range import PdfPageMetadata+from .sources import PreparedSource, prepare_sourceclass GradioDocumentIO(Protocol):"""定义界面和转换服务共享的同步文档操作,不约束宿主的进程实现。"""+ def prepare_source(self, path: Path, *, source_id: str, output_root: Path) -> PreparedSource:+ """准备一次上传的稳定输入,图片生成的 PDF 由预览与解析共用。"""+ ...+def pdf_page_metadata(self, file_path: str | None) -> PdfPageMetadata:"""读取上传文件页数,返回可序列化的文件身份、页数和错误。"""...@@ -36,13 +41,17 @@ class GradioDocumentIO(Protocol):output_root: Path,page_range: str,) -> RunArtifacts:- """物化解析结果及原文预览,只返回路径和可序列化的产物描述。"""+ """物化完整解析素材,只返回路径和可序列化的产物描述。"""...class LocalGradioDocumentIO:"""普通 WebUI 的进程内实现,实例化时不打开文档或创建目录。"""+ def prepare_source(self, path: Path, *, source_id: str, output_root: Path) -> PreparedSource:+ """通过公共图片转换能力准备输入,保持 PDFium 操作可被宿主隔离。"""+ return prepare_source(path, source_id=source_id, output_root=output_root)+def pdf_page_metadata(self, file_path: str | None) -> PdfPageMetadata:"""委托现有页数读取实现,沿用共享 PDFium 锁和错误格式。"""return page_range.pdf_page_metadata(file_path)diff --git a/mineru/kit/gradio/i18n.py b/mineru/kit/gradio/i18n.pyindex ce8f89d9..80f5561b 100644--- a/mineru/kit/gradio/i18n.py+++ b/mineru/kit/gradio/i18n.py@@ -25,6 +25,11 @@ MESSAGES: dict[str, tuple[str, str]] = {"homepage": ("Homepage", "主页"),"download": ("Download", "下载"),"upload": ("Select a document to parse", "请选择要解析的文件"),+ "upload_drop": ("Choose, drop or paste a document or image", "选择、拖放或粘贴文件或图片"),+ "upload_retry": ("Retry", "重试"),+ "uploading": ("Uploading…", "正在上传…"),+ "upload_unsupported": ("Unsupported file type", "不支持此文件类型"),+ "preparing_pdf": ("Preparing PDF preview…", "正在准备 PDF 预览…"),"tier": ("Parsing tier", "解析等级"),"tier_value": ("Parsing tier: {tier}{notice}", "解析等级:{tier}{notice}"),"tier_flash": ("flash", "flash(极速)"),diff --git a/mineru/kit/gradio/page_range.py b/mineru/kit/gradio/page_range.pyindex 75f4b783..265ccf47 100644--- a/mineru/kit/gradio/page_range.py+++ b/mineru/kit/gradio/page_range.py@@ -25,12 +25,13 @@ def validate_max_pages(max_pages: int | None) -> None:def read_pdf_page_count(path: str | Path) -> int:"""在共享 PDFium 锁内读取页数,并在成功或异常时及时释放文档。"""- import pypdfium2 as pdfium+ # 先取得公共 PDF 包,再读取其运行时;与图片准备的首次导入保持同一锁顺序。+ from docvortex.document.pdf import pdfium as pdfium_runtime- from docvortex.document.pdf.pdfium import pdfium_guard+ import pypdfium2 as pdfiumtry:- with pdfium_guard():+ with pdfium_runtime.pdfium_guard():document = pdfium.PdfDocument(str(path))try:page_count = len(document)diff --git a/mineru/kit/gradio/pdf_preview.py b/mineru/kit/gradio/pdf_preview.pyindex 09fe446b..780fc04a 100644--- a/mineru/kit/gradio/pdf_preview.py+++ b/mineru/kit/gradio/pdf_preview.py@@ -7,7 +7,7 @@ import mimetypesfrom pathlib import Pathfrom typing import Literal-PreviewAction = Literal["reset", "clear", "begin", "source", "result"]+PreviewAction = Literal["setup", "reset", "clear", "begin", "source", "result", "prepare", "prepared"]def register_pdf_preview_resources() -> Path:diff --git a/mineru/kit/gradio/sources.py b/mineru/kit/gradio/sources.pynew file mode 100644index 00000000..9d1bdeff--- /dev/null+++ b/mineru/kit/gradio/sources.py@@ -0,0 +1,181 @@+"""上传级输入准备及文件租期;解析结果不拥有第二份预览文档。"""++from __future__ import annotations++import asyncio+import shutil+import uuid+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import TYPE_CHECKING, Any++from ...filetypes import IMAGE_EXTENSIONS, PDF_EXTENSIONS+from .conversion import await_task_completion, run_sync_output++if TYPE_CHECKING:+ from .document_io import GradioDocumentIO+++@dataclass(frozen=True)+class PreparedSource:+ """只保存不可变路径和原始身份,允许宿主通过 CPU sidecar 序列化传递。"""++ source_id: str+ root: Path+ original_path: Path+ source_path: Path+ parse_path: Path+ preview_pdf_path: Path | None+ file_suffix: str++ def as_state(self) -> dict[str, str]:+ """转成纯字符串记录,不传递 PDFium 句柄或文件内容。"""+ return {key: str(value) if value is not None else "" for key, value in asdict(self).items()}++ @classmethod+ def from_state(cls, value: dict[str, Any], *, source_root: Path) -> PreparedSource:+ """限定准备目录身份及其所有派生文件,原始上传路径只作为身份使用。"""+ source_id = value["source_id"]+ if not isinstance(source_id, str) or uuid.UUID(source_id).hex != source_id:+ raise ValueError("Invalid prepared source identity")+ root = Path(value["root"]).resolve()+ if root != source_root.resolve() / source_id:+ raise ValueError("Prepared source escapes source root")+ paths = {key: Path(value[key]).resolve() for key in ("source_path", "parse_path")}+ preview = Path(value["preview_pdf_path"]).resolve() if value["preview_pdf_path"] else None+ for path in (*paths.values(), *([preview] if preview else [])):+ if not path.is_relative_to(root):+ raise ValueError("Prepared file escapes source directory")+ return cls(+ source_id, root, Path(value["original_path"]), **paths, preview_pdf_path=preview, file_suffix=value["file_suffix"]+ )+++def prepare_source(path: Path, *, source_id: str, output_root: Path) -> PreparedSource:+ """保存稳定输入;图片仅在此转换一次,预览和解析共用同一 PDF 字节。"""+ if uuid.UUID(source_id).hex != source_id:+ raise ValueError("Invalid prepared source identity")+ path = path.resolve()+ root = output_root.resolve() / "gradio" / "sources" / source_id+ root.mkdir(parents=True, exist_ok=False)+ try:+ source = root / path.name+ shutil.copyfile(path, source)+ suffix = path.suffix.lower().lstrip(".")+ preview = source if suffix in PDF_EXTENSIONS else None+ if suffix in IMAGE_EXTENSIONS:+ from docvortex.document.pdf import PDFDocument++ preview = root / f"{path.stem}.pdf"+ with PDFDocument.from_image(source.read_bytes()) as document:+ preview.write_bytes(document.bytes)+ return PreparedSource(source_id, root, path, source, preview or source, preview, suffix)+ except BaseException:+ shutil.rmtree(root, ignore_errors=True)+ raise+++@dataclass+class _SourceLease:+ """准备任务和解析共享租期,失效后只清理无成功结果引用的文件。"""++ original_path: Path+ task: asyncio.Task[PreparedSource]+ users: int = 0+ retained: bool = False+ retired: bool = False+++class SessionSources:+ """按应用、会话和选择身份隔离准备任务,合并同一输入的并发准备。"""++ def __init__(self, document_io: GradioDocumentIO, output_root: Path) -> None:+ """只初始化注册表,实际文件操作均在显式准备和释放时执行。"""+ self.document_io = document_io+ self.output_root = output_root+ self.current: dict[str, tuple[str, _SourceLease]] = {}+ self.revisions: dict[str, int] = {}+ self.cleanups: set[asyncio.Task[None]] = set()++ async def prepare(self, session: str, path: Path, source_id: str, revision: int) -> PreparedSource:+ """接收单调选择修订号,拒绝晚到准备请求并复用本轮已创建的任务。"""+ path = path.resolve()+ previous = self.current.get(session)+ if previous and previous[0] == source_id:+ if previous[1].original_path != path:+ raise ValueError("Source identity does not match uploaded file")+ return await asyncio.shield(previous[1].task)+ if revision <= self.revisions.get(session, 0):+ raise ValueError("Source preparation has expired")+ self.revisions[session] = revision+ if previous:+ previous[1].retired = True+ task = asyncio.create_task(+ run_sync_output(self.document_io.prepare_source, path, source_id=source_id, output_root=self.output_root)+ )+ lease = _SourceLease(path, task)+ self.current[session] = (source_id, lease)+ try:+ source = await asyncio.shield(task)+ if lease.retired:+ raise ValueError("Source preparation has expired")+ return source+ finally:+ if previous:+ self._schedule_cleanup(previous[1])+ await self._cleanup(lease)++ def _schedule_cleanup(self, lease: _SourceLease) -> None:+ """旧同步准备在后台安全退出,不阻塞已经就绪的新文件回执。"""+ task = asyncio.create_task(self._cleanup(lease))+ self.cleanups.add(task)+ task.add_done_callback(self.cleanups.discard)++ async def acquire(self, session: str, path: Path, *, source_id: str = "") -> tuple[PreparedSource, _SourceLease]:+ """浏览器使用预检记录;公开 API 在转换前走同一准备流程。"""+ current = self.current.get(session)+ if source_id and (not current or current[0] != source_id or current[1].original_path != path.resolve()):+ raise ValueError("Source preparation has expired")+ if not current or current[1].original_path != path.resolve():+ await self.prepare(session, path, uuid.uuid4().hex, self.revisions.get(session, 0) + 1)+ lease = self.current[session][1]+ lease.users += 1+ try:+ prepared = await asyncio.shield(lease.task)+ if lease.retired:+ raise ValueError("Source preparation has expired")+ return prepared, lease+ except BaseException:+ await self.release(lease)+ raise++ async def release(self, lease: _SourceLease, *, retain: bool = False) -> None:+ """成功结果保留其文件引用;最后一个使用者退出后才清理过期输入。"""+ lease.retained |= retain+ lease.users -= 1+ await self._cleanup(lease)++ async def retire(self, session: str, *, revision: int | None = None) -> None:+ """清除和关闭时使准备失效,不强制终止正在运行的同步转换。"""+ if revision is not None:+ if revision <= self.revisions.get(session, 0):+ return+ self.revisions[session] = revision+ previous = self.current.pop(session, None)+ if previous:+ previous[1].retired = True+ await self._cleanup(previous[1])++ async def _cleanup(self, lease: _SourceLease) -> None:+ """等待同步准备真正结束后回收未引用目录,失败任务已自行清理。"""+ if not lease.retired or lease.retained or lease.users:+ return+ try:+ source = await await_task_completion(lease.task)+ except (Exception, asyncio.CancelledError):+ return+ if not lease.users and not lease.retained:+ await asyncio.to_thread(shutil.rmtree, source.root, True)+++__all__ = ["PreparedSource", "SessionSources", "prepare_source"]diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex 0d68f9f3..008cc9d9 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -31,7 +31,7 @@ from typing import Any, Literal, castfrom urllib.parse import unquote, urlparse, urljoinimport httpx-from docvortex.assets import validate_image_sidecar_path+from docvortex.assets import validate_image_payload, validate_image_sidecar_pathfrom pydantic import ValidationErrorfrom ..task_types import TaskStatus, task_status_url@@ -1007,6 +1007,10 @@ def _encode_image_data_uri(image_bytes: bytes, image_path: str) -> str:subtype = _IMAGE_DATA_URI_SUBTYPES.get(ext)if subtype is None:raise _V1APIError("invalid_image_sidecar", f"Unsupported image sidecar extension: {image_path}")+ try:+ validate_image_payload(image_bytes, ext)+ except ValueError as exc:+ raise _V1APIError("invalid_image_sidecar", f"Invalid image sidecar {image_path}: {exc}") from excreturn f"data:image/{subtype};base64,{base64.b64encode(image_bytes).decode('ascii')}"diff --git a/mineru/resources/gradio_app.css b/mineru/resources/gradio_app.cssindex e01e90d9..8f872a0b 100644--- a/mineru/resources/gradio_app.css+++ b/mineru/resources/gradio_app.css@@ -403,3 +403,14 @@ body.dark .gradio-container {max-height: 240px;}}++/* 上传外观和原生文件桥接解耦,状态变化不会重建预览。 */+.mineru-upload-target { display: flex; align-items: center; justify-content: center; min-height: 110px; padding: 16px; border: 1px dashed var(--border-color-primary); border-radius: 8px; cursor: pointer; overflow-wrap: anywhere; }+.mineru-upload-target input { position: absolute; width: 1px; height: 1px; opacity: 0; }+.mineru-upload-target:focus-within { outline: 2px solid var(--color-accent); }+.mineru-upload-status { font-size: 13px; margin-top: 6px; overflow-wrap: anywhere; }+.mineru-pdf-host [role="status"], .mineru-pdf-host [role="alert"] { padding: 24px; }++.mineru-kit-preview:has(.mineru-pdf-host iframe, .mineru-pdf-host [role]) .mineru-kit-generic-preview { display: none !important; }++.mineru-pdf-host { height: 100%; min-height: 0; }diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.jsindex d1508afd..1b0d8ed3 100644--- a/mineru/resources/gradio_app.js+++ b/mineru/resources/gradio_app.js@@ -1,24 +1,16 @@-() => {- const APP_SCRIPT_VERSION = "v7-bidirectional-trace";+(viewerEntry) => {+ const preview = __MINERU_PDF_PREVIEW__;+ const APP_SCRIPT_VERSION = "v8-persistent-source";if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {+ preview("setup", viewerEntry);return;}window.__mineruGradioAppInstalled = APP_SCRIPT_VERSION;const OFFICE_PREVIEW_NOTICE_STORAGE_KEY = "mineru.officePreviewNoticeIgnored";- const CLIPBOARD_MIME_EXTENSIONS = {- "image/png": "png",- "image/jpeg": "jpg",- "image/webp": "webp",- "image/gif": "gif",- "image/bmp": "bmp",- "image/tiff": "tiff",- "application/pdf": "pdf",- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",- "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",- };const i18n = window.__mineruI18n = __MINERU_I18N__;+ preview("setup", viewerEntry);+ window.__mineruUpload?.localize();(__MINERU_TRACE__)();const statusTimer = (__MINERU_STATUS_TIMER__)(i18n);window.__mineruStatusPanel = statusTimer;@@ -80,135 +72,6 @@refreshPageRangeTrack();};- const findUploadFileInput = () => {- const uploadRoot = document.querySelector(".mineru-upload-file");- if (!uploadRoot) {- return null;- }- return uploadRoot.querySelector('input[type="file"]');- };-- // 读取上传控件 accept 规则,后续粘贴文件仍复用 gr.File 的支持格式边界。- const getUploadAcceptedTypes = (uploadInput) => {- const accept = uploadInput?.getAttribute("accept") || "";- return accept.split(",").map((item) => item.trim().toLowerCase()).filter(Boolean);- };-- // 判断剪贴板文件是否匹配 gr.File 当前支持的扩展名或 MIME 类型。- const fileMatchesAcceptedType = (file, acceptedTypes) => {- if (!acceptedTypes.length) {- return true;- }- const name = (file.name || "").toLowerCase();- const type = (file.type || "").toLowerCase();- return acceptedTypes.some((accepted) => {- if (accepted.startsWith(".")) {- return name.endsWith(accepted);- }- if (accepted.endsWith("/*")) {- return type.startsWith(accepted.slice(0, -1));- }- return type === accepted;- });- };-- // 为截图等无文件名剪贴板图片补一个扩展名,确保后端按普通图片文件解析。- const buildClipboardFileName = (file) => {- const type = (file.type || "").toLowerCase();- const extension = CLIPBOARD_MIME_EXTENSIONS[type];- if (!extension) {- return "";- }- const timestamp = new Date().toISOString()- .replace(/[-:]/g, "")- .replace(/[.].+/, "")- .replace("T", "-");- const prefix = type.startsWith("image/") ? "clipboard-image" : "clipboard-file";- return `${prefix}-${timestamp}.${extension}`;- };-- // 保留浏览器暴露的原始文件;仅在文件名缺少扩展名时复制一份并补齐名称。- const normalizeClipboardFile = (file) => {- if (/[.][^.]+$/.test(file.name || "")) {- return file;- }- const fileName = buildClipboardFileName(file);- if (!fileName || typeof File === "undefined") {- return file;- }- return new File([file], fileName, {- type: file.type,- lastModified: file.lastModified || Date.now(),- });- };-- // 同时兼容剪贴板 files 与 items,两种入口在不同浏览器里暴露情况不一致。- const collectClipboardFiles = (clipboardData) => {- const files = Array.from(clipboardData.files || []);- if (files.length) {- return files;- }- return Array.from(clipboardData.items || [])- .filter((item) => item.kind === "file")- .map((item) => item.getAsFile())- .filter(Boolean);- };-- // 构造只包含目标文件的 FileList;部分浏览器不允许构造 DataTransfer,需要降级处理。- const createUploadFileList = (file) => {- try {- const transfer = new DataTransfer();- transfer.items.add(file);- return transfer.files;- } catch (error) {- return null;- }- };-- // 把文件列表赋值给 gr.File 的原生 input,并触发 Gradio 监听的变更事件。- const assignClipboardFileToUpload = (uploadInput, uploadFiles) => {- if (!uploadFiles) {- return false;- }- try {- uploadInput.files = uploadFiles;- } catch (error) {- return false;- }- uploadInput.dispatchEvent(new Event("input", { bubbles: true }));- uploadInput.dispatchEvent(new Event("change", { bubbles: true }));- return true;- };-- // 将剪贴板文件注入现有 gr.File input,避免为图片、PDF、Office 维护第二套上传链路。- const uploadClipboardFile = (event) => {- const clipboardData = event.clipboardData;- const uploadInput = findUploadFileInput();- if (!clipboardData || !uploadInput) {- return false;- }-- const acceptedTypes = getUploadAcceptedTypes(uploadInput);- const rawClipboardFiles = clipboardData.files || null;- const clipboardFiles = collectClipboardFiles(clipboardData)- .map((rawFile) => ({ rawFile, uploadFile: normalizeClipboardFile(rawFile) }))- .filter(({ uploadFile }) => fileMatchesAcceptedType(uploadFile, acceptedTypes));- if (!clipboardFiles.length) {- return false;- }-- const { rawFile, uploadFile } = clipboardFiles[0];- const uploadFiles = createUploadFileList(uploadFile)- || (- rawClipboardFiles?.length === 1- && rawClipboardFiles[0] === rawFile- && rawFile === uploadFile- ? rawClipboardFiles- : null- );- return assignClipboardFileToUpload(uploadInput, uploadFiles);- };-refreshMineruCustomHtml();requestAnimationFrame(() => {refreshMineruCustomHtml();@@ -269,11 +132,6 @@}});- document.addEventListener("paste", (event) => {- if (uploadClipboardFile(event)) {- event.preventDefault();- }- });// 拖动时下一帧读取 Gradio 已同步的值;键盘输入也走同一条路径。document.addEventListener("input", (event) => {diff --git a/mineru/resources/gradio_conversion.js b/mineru/resources/gradio_conversion.jsindex 6bb4157e..6f0066d8 100644--- a/mineru/resources/gradio_conversion.js+++ b/mineru/resources/gradio_conversion.js@@ -24,6 +24,8 @@};if (action === "begin") {+ state.sourceId = window.__mineruPdfPreview?.sourceId;+ state.sourcePath = window.__mineruPdfPreview?.source;stopPreviewLog();state.runId = uuid4().replaceAll("-", "");state.revision += 1;@@ -31,7 +33,14 @@state.terminal = false;state.applied = false;window.__mineruStatusPanel?.showPreparing();- return [JSON.stringify({ run_id: state.runId, revision: state.revision }), timer(true)];+ return [JSON.stringify({ run_id: state.runId, revision: state.revision, source_id: state.sourceId }), timer(true)];+ }+ if (action === "cancel_source") {+ const path = args[0]?.path || "";+ if (path && path === state.sourcePath && state.sourceId === window.__mineruPdfPreview?.sourceId) {+ return [skip(), skip(), skip()];+ }+ action = "cancel";}if (action === "cancel") {stopPreviewLog();diff --git a/mineru/resources/gradio_page_range.js b/mineru/resources/gradio_page_range.jsindex 5623bbe0..add9fe70 100644--- a/mineru/resources/gradio_page_range.js+++ b/mineru/resources/gradio_page_range.js@@ -1,4 +1,4 @@-(tiers, flashOnlyExtensions, maxPages, file, position, metadata, previous, handleAValue, handleBValue, tierSelection) => {+(tiers, flashOnlyExtensions, maxPages, file, position, metadata, previous, handleAValue, handleBValue, tierSelection, sourceReady) => {// 纯前端状态转换:经原生组件事件读写值,不逐次向 Python 发送拖动请求。// 内部元数据使用 JSON 文本,避免不同 Gradio 版本的 JSON 组件封装差异。const { text, message } = window.__mineruI18n;@@ -80,7 +80,7 @@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) && (!needsRange || count > 0) }),+ update({ interactive: Boolean(path) && sourceReady === path && (!needsRange || count > 0) }),update({ value: escapeHtml(notice), visible: Boolean(notice) }),// 同一事件同时更新值、标签和页码,程序赋值无需再触发 tier.input。update({ value: effectivePosition, interactive: !flashOnly && tiers.length > 1, visible: !flashOnly && tiers.length > 1 }),diff --git a/mineru/resources/gradio_pdf_preview.js b/mineru/resources/gradio_pdf_preview.jsindex 6e08f9d8..472c9987 100644--- a/mineru/resources/gradio_pdf_preview.js+++ b/mineru/resources/gradio_pdf_preview.js@@ -1,91 +1,162 @@-// 用原生 FileData 判定文件身份;只访问自有 iframe 执行取消,不读取 Gradio 内部组件状态。+// 稳定容器由本控制器独占;Gradio 只传文件回执,不再替换 iframe HTML。(action, ...args) => {- const state = window.__mineruPdfPreview ??= { source: "", conversion: "", revision: 0, result: "" };- // 路径用于比较文档身份;仅 Windows 路径转换分隔符,保留 POSIX 文件名中的反斜杠。- const path = (value) => /^[a-z]:[\\/]|^\\\\/i.test(value) ? value.replace(/\\/g, "/") : value;- const key = (file) => path(String(file?.path || file?.url || ""));- // 输出只更新自有 HTML 组件;迟到回调通过空更新保持当前预览。- const skip = () => ({ __type__: "update" });- const empty = () => ({ __type__: "update", value: "", visible: true });- // 在 Gradio 卸载 iframe 前同步停止旧 PDF 的下载与渲染,避免移动端同时运行两份查看器。- const disposeCurrentViewer = () => {- try {- document.querySelector("iframe.mineru-pdf-frame")?.contentWindow?.__mineruPdfDisposePreview?.();- } catch (error) {- // iframe 尚未就绪时由其 pagehide 回调完成清理。- }- };- // 使用 FileData 的路由前缀与原始路径,避免空格、#、?、% 等文件名字符被误解释为 URL 语法。- const fileUrl = (file, routeBase = null) => {- if (!file?.url || !file?.path || /^https?:/i.test(file.path)) throw new Error("Invalid preview file");- const marker = "/gradio_api/file=";- const supplied = new URL(file.url, window.location.href);- if (supplied.origin !== window.location.origin) throw new Error("Invalid preview origin");- if (!supplied.pathname.includes(marker)) throw new Error("Invalid preview route");- // 事件结果的相对 URL 可能省略挂载前缀,使用初始静态文件的完整路由作为统一基址。- const route = routeBase || supplied.href;- const index = route.indexOf(marker);- const encoded = path(file.path).split("/").map(encodeURIComponent).join("/");- const url = new URL(route.slice(0, index + marker.length) + encoded, window.location.href);- if (url.origin !== window.location.origin) throw new Error("Invalid preview origin");- return url.href;- };- // 文件名和本地化文本都必须作为属性文本编码,不允许注入活动 HTML。- const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (character) => ({- "&": "&", "<": "<", ">": ">", '"': """, "'": "'",- })[character]);-- if (action === "reset" || action === "clear") {- window.__mineruTrace?.reset();- disposeCurrentViewer();- state.source = action === "clear" ? "" : key(args[0]);- state.conversion = "";- state.result = "";- state.revision += 1;- return empty();- }- if (action === "begin") {- window.__mineruTrace?.reset();- state.conversion = state.source;- return [];- }- const [file, source, viewer, runId] = args;- if (!state.source || key(source) !== state.source) return skip();- if (action === "source") {- // 原文的 File 缓存路径与上传文件一致;不能让晚到的原文事件覆盖布局结果。- if (state.result || (file && key(file) !== key(source))) return skip();- } else if (action === "result") {- if (!runId || state.conversion !== state.source) return skip();- state.result = runId;- window.__mineruTrace?.activate(runId);- } else {- return skip();- }- if (!file) {- disposeCurrentViewer();- return empty();- }- const { text } = window.__mineruI18n;- disposeCurrentViewer();- try {- const messages = Object.fromEntries([- "preview", "pdf_loading", "pdf_previous", "pdf_next", "pdf_page", "pdf_zoom_out", "pdf_zoom_in",- "trace_regions", "trace_source", "trace_merged", "trace_merged_description",- "pdf_fit_width", "pdf_invalid", "pdf_password", "pdf_load_failed",- ].map((name) => [name, text(name)]));- const viewerUrl = fileUrl(viewer);- const params = new URLSearchParams({ file: fileUrl(file, viewerUrl), messages: JSON.stringify(messages) });- if (action === "result") params.set("documentId", runId);- const url = new URL(viewerUrl);- // Gradio 6 会复用 iframe 节点;只改 hash 不会重新加载文档,必须改变查询参数。- url.searchParams.set("document", String(++state.revision));- url.hash = params.toString();- return {- __type__: "update", visible: true,- value: `<iframe class="mineru-pdf-frame" title="${escapeHtml(text("preview"))}" ` +- `src="${escapeHtml(url.href)}" sandbox="allow-scripts allow-same-origin"></iframe>`,+ if (!window.__mineruPdfPreview) {+ const state = { source: "", sourceId: "", revision: 0, conversion: "", result: "", blob: "", frame: null, viewer: null, uploading: false, localSelected: false, readyPath: "", file: null };+ // 使用全上下文可用的随机数,兼容局域网 HTTP。+ const identity = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), value => value.toString(16).padStart(2, "0")).join("");+ // 文件路径只作为已完成上传的身份,不依据文件名猜测对应关系。+ const key = file => String(file?.path || file?.url || "");+ const skip = () => ({ __type__: "update" });+ const host = () => document.querySelector(".mineru-pdf-host");+ // 继续使用 Gradio 的同源文件路由,正确编码路径中的特殊字符和代理前缀。+ const fileUrl = (file, routeBase = null) => {+ if (!file?.url || !file?.path || /^https?:/i.test(file.path)) throw new Error("Invalid preview file");+ const supplied = new URL(file.url, location.href);+ const marker = "/gradio_api/file=";+ if (supplied.origin !== location.origin || !supplied.pathname.includes(marker)) throw new Error("Invalid preview route");+ const route = routeBase || supplied.href;+ const path = /^[a-z]:[\\/]|^\\\\/i.test(file.path) ? file.path.replace(/\\/g, "/") : file.path;+ return route.slice(0, route.indexOf(marker) + marker.length) + path.split("/").map(encodeURIComponent).join("/");+ };+ // 切换输入才销毁旧 PDF;先停止使用再撤销 Blob URL。+ const dispose = () => {+ try { state.frame?.contentWindow?.__mineruPdfDisposePreview?.(); } catch {}+ state.frame?.remove();+ state.frame = null;+ state.file = null;+ if (state.blob) URL.revokeObjectURL(state.blob);+ state.blob = "";+ host()?.replaceChildren();+ };+ // 状态只写文本节点,错误和文件名均不进入活动 HTML。+ const notice = (message, error = false) => {+ if (!host()) return;+ const node = document.createElement("div");+ node.setAttribute("role", error ? "alert" : "status");+ node.textContent = message;+ host().replaceChildren(node);+ };+ // 只为当前源文件挂载一次,上传回执和转换结果不会改变文档 URL。+ const mount = file => {+ if (file) state.file = file;+ file = state.file;+ if (state.frame || !state.viewer || !host() || !window.__mineruI18n || (!state.blob && !file)) return;+ const { text } = window.__mineruI18n;+ try {+ const viewerUrl = fileUrl(state.viewer);+ const source = state.blob || (file ? fileUrl(file, viewerUrl) : "");+ if (!source) return;+ const messages = Object.fromEntries([+ "preview", "pdf_loading", "pdf_previous", "pdf_next", "pdf_page", "pdf_zoom_out", "pdf_zoom_in",+ "trace_regions", "trace_source", "trace_merged", "trace_merged_description", "pdf_fit_width",+ "pdf_invalid", "pdf_password", "pdf_load_failed",+ ].map(name => [name, text(name)]));+ const url = new URL(viewerUrl);+ url.searchParams.set("source", state.sourceId);+ url.hash = new URLSearchParams({ file: source, sourceId: state.sourceId, messages: JSON.stringify(messages) }).toString();+ const frame = document.createElement("iframe");+ frame.className = "mineru-pdf-frame";+ frame.title = text("preview");+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin");+ frame.src = url.href;+ state.frame = frame;+ host().replaceChildren(frame);+ } catch (error) { notice(text("pdf_load_failed"), true); }+ };+ // 原生文件组件清空可能是上传开始时的桥接事件,不能撤销刚建立的本地预览。+ const reset = file => {+ const path = key(file);+ if ((!path && state.localSelected) || (path && path === state.source)) return;+ window.__mineruTrace?.reset();+ dispose();+ state.source = path;+ state.sourceId = identity();+ state.revision += 1;+ state.conversion = "";+ state.result = "";+ state.readyPath = "";+ state.uploading = false;+ state.localSelected = false;+ window.__mineruUpload?.sync(file);+ };+ state.local = (file, id) => {+ // 选文件时立即建立身份,PDF 本地读取与上传并行。+ reset(null);+ window.__mineruTrace?.reset();+ dispose();+ state.source = "";+ state.sourceId = id;+ state.revision += 1;+ state.conversion = "";+ state.result = "";+ state.readyPath = "";+ state.uploading = true;+ state.localSelected = true;+ if (/\.pdf$/i.test(file.name)) {+ state.blob = URL.createObjectURL(file);+ mount(null);+ } else if (window.__mineruUpload?.isImage(file.name)) {+ notice(window.__mineruI18n.text("preparing_pdf"));+ }+ };+ state.bind = (file, id) => {+ // 仅当前上传闭包可以绑定远端路径,迟到上传不能进入 Gradio 文件组件。+ if (id !== state.sourceId) return false;+ state.source = key(file);+ state.revision += 1;+ state.uploading = false;+ return true;+ };+ state.clear = () => {+ // 清除同时使本地上传失效,但不重复触发控件事件。+ state.uploading = false;+ state.localSelected = false;+ state.source = "";+ reset(null);+ window.__mineruUpload?.invalidate();+ };+ state.invoke = (operation, ...values) => {+ // 统一接收框架事件,所有返回值均保持稳定 HTML 容器。+ if (operation === "setup") { state.viewer = values[0] || state.viewer; mount(null); return []; }+ if (operation === "clear") { state.clear(); return skip(); }+ if (operation === "reset") { reset(values[0]); return skip(); }+ if (operation === "prepare") {+ if (!values[0] && state.localSelected) return skip();+ reset(values[0]);+ return JSON.stringify({ id: state.sourceId, revision: state.revision, path: key(values[0]) });+ }+ if (operation === "prepared") {+ let receipt;+ try { receipt = JSON.parse(values[0]); } catch { return skip(); }+ if (!receipt || receipt.id !== state.sourceId || receipt.path !== state.source) return skip();+ window.__mineruUpload?.prepared(receipt.error);+ if (receipt.error) { if (!state.frame) notice(receipt.error, true); return ""; }+ if (receipt.pdf) mount(receipt.pdf);+ state.readyPath = receipt.path;+ return receipt.path;+ }+ if (operation === "begin") {+ window.__mineruTrace?.reset();+ state.conversion = state.sourceId;+ state.result = "";+ return [];+ }+ const [file, source, viewer, runId] = values;+ if (viewer) state.viewer = viewer;+ if (!state.source || key(source) !== state.source) return skip();+ if (operation === "source") {+ if (!state.result && file && key(file) === key(source)) mount(file);+ } else if (operation === "result" && runId && state.conversion === state.sourceId) {+ state.result = runId;+ if (file) {+ mount(file);+ window.__mineruTrace?.activate(runId, state.sourceId);+ }+ }+ return skip();};- } catch (error) {- return { __type__: "update", visible: true, value: `<div role="alert">${escapeHtml(text("pdf_load_failed"))}</div>` };+ window.addEventListener("pagehide", dispose, { once: true });+ window.__mineruPdfPreview = state;}+ return window.__mineruPdfPreview.invoke(action, ...args);}diff --git a/mineru/resources/gradio_trace.js b/mineru/resources/gradio_trace.jsindex 83d2d6d7..7ee65bfe 100644--- a/mineru/resources/gradio_trace.js+++ b/mineru/resources/gradio_trace.js@@ -3,7 +3,9 @@if (window.__mineruTrace) return;let documentId = "";let entries = [];- let pageIndices = [];+ let initialPageIdx = null;+ let sourceId = "";+ let htmlReady = false;let layoutRegions = [];// 合并正文中的多个同页来源仍用完整物理身份区分。const sourceKey = (source) => JSON.stringify([source.page_idx, source.block_index, source.child_path]);@@ -11,13 +13,14 @@const send = (selector, message) => {const frame = document.querySelector(selector);frame?.contentWindow?.postMessage(- { ...message, channel: "mineru-trace", documentId },+ { ...message, channel: "mineru-trace", documentId, sourceId },selector.includes("rendered") ? "*" : location.origin);};// 初始化可重复执行,覆盖两侧加载次序和 iframe 重挂载。const initialize = () => {- send("iframe.mineru-pdf-frame", { type: "init", entries, pageIndices, layoutRegions });+ send("iframe.mineru-pdf-frame", { type: "bind" });+ if (htmlReady) send("iframe.mineru-pdf-frame", { type: "init", entries, initialPageIdx, layoutRegions });};window.__mineruTrace = {// 切换或重提立即使旧来源和待定位请求失效。@@ -25,29 +28,37 @@send("iframe.mineru-pdf-frame", { type: "clear" });documentId = "";entries = [];- pageIndices = [];+ initialPageIdx = null;+ htmlReady = false;layoutRegions = [];},// 只在已接受的结果回执进入预览时绑定产物标识。- activate(id) {- if (documentId === id) return;+ activate(id, currentSourceId) {+ if (documentId === id && sourceId === currentSourceId) return;this.reset();documentId = id;+ sourceId = currentSourceId;+ initialize();+ // 正文可能先于结果回执完成加载,主动握手补回已错过的 ready。+ send("iframe.mineru-rendered-html-frame", { type: "request-ready" });}};window.addEventListener("message", (event) => {const data = event.data;- if (!documentId || data?.channel !== "mineru-trace" || data.documentId !== documentId) return;+ if (!documentId || data?.channel !== "mineru-trace") return;const htmlFrame = document.querySelector("iframe.mineru-rendered-html-frame");const pdfFrame = document.querySelector("iframe.mineru-pdf-frame");const fromHtml = event.source === htmlFrame?.contentWindow;const fromPdf = event.source === pdfFrame?.contentWindow && event.origin === location.origin;if (!fromHtml && !fromPdf) return;+ if (fromPdf && (data.sourceId !== sourceId || (data.type !== "ready" && data.documentId !== documentId))) return;+ if (fromHtml && data.documentId !== documentId) return;if (data.type === "ready") {if (fromHtml) {- if (!Array.isArray(data.entries) || !Array.isArray(data.pageIndices)) return;+ if (!Array.isArray(data.entries)) return;entries = data.entries;- pageIndices = data.pageIndices;+ initialPageIdx = data.initialPageIdx;+ htmlReady = true;layoutRegions = Array.isArray(data.layoutRegions) ? data.layoutRegions : [];send("iframe.mineru-rendered-html-frame", {type: "labels",diff --git a/mineru/resources/gradio_trace_html.js b/mineru/resources/gradio_trace_html.jsindex f45b5e42..97203cfd 100644--- a/mineru/resources/gradio_trace_html.js+++ b/mineru/resources/gradio_trace_html.js@@ -44,6 +44,8 @@// 所有事件带产物身份,父窗口仍需核对实际发送窗口。const send = (message) =>parent.postMessage({ ...message, channel: "mineru-trace", documentId: config.documentId }, parentOrigin);+ // 初次加载和父窗口主动握手共用结果快照,覆盖两侧就绪先后顺序。+ const announceReady = () => send({ type: "ready", entries, initialPageIdx: config.initialPageIdx, layoutRegions: config.layoutRegions });// 页码条贴近选中内容并限制在当前 iframe 的可见范围内。const positionNavigation = () => {if (!selected) return;@@ -113,6 +115,10 @@data.documentId !== config.documentId)return;+ if (data.type === "request-ready") {+ announceReady();+ return;+ }if (data.type === "labels") {pageLabel = data.pageLabel;navigation.setAttribute("aria-label", pageLabel);@@ -147,5 +153,5 @@},{ once: true });- send({ type: "ready", entries, pageIndices: config.pageIndices, layoutRegions: config.layoutRegions });+ announceReady();}diff --git a/mineru/resources/gradio_upload.js b/mineru/resources/gradio_upload.jsnew file mode 100644index 00000000..2ae86151--- /dev/null+++ b/mineru/resources/gradio_upload.js@@ -0,0 +1,120 @@+// 上传控件只通过 Gradio 的公开 upload/props 接口写入文件,不读取框架内部状态。+({ element, props, upload, accepted, imageExtensions }) => {+ let id = "";+ let localFile = null;+ let uploadedFile = null;+ let pending = false;+ let bridged = "";+ // DOM 引用按需取得,兼容组件对属性更新的模板协调。+ const input = () => element.querySelector('input[type="file"]');+ const label = () => element.querySelector(".mineru-upload-label");+ const status = () => element.querySelector(".mineru-upload-status");+ const retry = () => element.querySelector(".mineru-upload-retry");+ const text = key => window.__mineruI18n?.text(key) || key;+ const identity = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), value => value.toString(16).padStart(2, "0")).join("");+ const isImage = name => imageExtensions.some(extension => name.toLowerCase().endsWith(`.${extension}`));+ // 文件名和服务器错误只显示为文本;错误状态允许使用同一文件重试。+ const display = (name, message = "", failed = false) => {+ label().textContent = name || text("upload_drop");+ status().textContent = message;+ status().setAttribute("role", failed ? "alert" : "status");+ retry().hidden = !failed;+ retry().textContent = text("upload_retry");+ };+ // 每次文件选择有独立闭包身份,旧上传即使成功也不会写入原生文件桥接组件。+ const submit = async file => {+ if (!file || !accepted.some(extension => file.name.toLowerCase().endsWith(extension))) {+ display(file?.name, text("upload_unsupported"), false);+ return;+ }+ const previous = localFile === file ? uploadedFile : null;+ id = identity();+ const current = id;+ localFile = file;+ uploadedFile = null;+ pending = true;+ window.__mineruPdfPreview.local(file, current);+ display(file.name, text("uploading"));+ props.value = JSON.stringify({ id: current, stage: "selected" });+ try {+ // 已上传但 PDF 准备失败时只重试准备,不重复上传图片。+ const result = previous || await upload(file);+ if (id !== current) return;+ const data = { ...result, orig_name: file.name, size: file.size, mime_type: file.type, meta: { _type: "gradio.FileData" } };+ if (!window.__mineruPdfPreview.bind(data, current)) return;+ uploadedFile = data;+ pending = false;+ display(file.name, isImage(file.name) ? text("preparing_pdf") : "");+ // 让清空事件先提交,重复准备同一服务器路径仍能触发文件变更。+ await new Promise(resolve => setTimeout(resolve, 0));+ if (id === current) props.value = JSON.stringify({ id: current, stage: "uploaded", file: data });+ } catch (error) {+ if (id !== current) return;+ pending = false;+ display(file.name, String(error?.message || error), true);+ }+ };+ // 清除只撤销本控件身份,真正文件取消和租期回收由原生组件事件协调。+ const invalidate = () => {+ id = "";+ localFile = null;+ uploadedFile = null;+ pending = false;+ input().value = "";+ display("");+ };+ window.__mineruUpload = {+ isImage, invalidate,+ // 同一次控件 change 的重复派发不再写回相同 FileData,避免触发重复源事件。+ bridge(value) {+ let receipt;+ try { receipt = JSON.parse(value); } catch { return { __type__: "update" }; }+ const key = `${receipt.id}:${receipt.stage}`;+ if (receipt.id !== window.__mineruPdfPreview.sourceId || key === bridged) return { __type__: "update" };+ bridged = key;+ return receipt.stage === "uploaded" ? receipt.file : null;+ },+ // 启动脚本晚于上传组件挂载时补齐初始语言。+ localize() { if (!localFile && !uploadedFile) display(""); },+ // 示例写入隐藏文件组件时同步文件名,不能把它关联到旧本地 File。+ sync(file) {+ if (pending || (file?.path && uploadedFile?.path === file.path)) return;+ invalidate();+ if (file) display(file.orig_name || file.path.split(/[\\/]/).pop());+ },+ // 输入准备成功或失败均在上传控件中显示,原图不会作为降级预览出现。+ prepared(error) { display(localFile?.name || label().textContent, error || "", Boolean(error && localFile)); },+ };+ element.addEventListener("change", event => {+ if (event.target === input()) submit(input().files?.[0]);+ });+ element.addEventListener("dragover", event => { event.preventDefault(); });+ element.addEventListener("drop", event => {+ event.preventDefault();+ submit(event.dataTransfer?.files?.[0]);+ });+ retry().addEventListener("click", () => submit(localFile));+ // 剪贴板与文件选择共用唯一上传流程,不再向隐藏 gr.File 注入合成 FileList。+ const paste = event => {+ const mimeExtensions = {+ "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif",+ "image/bmp": "bmp", "image/tiff": "tiff", "application/pdf": "pdf",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",+ };+ const data = event.clipboardData;+ const files = data?.files?.length ? Array.from(data.files) : Array.from(data?.items || []).map(item => item.getAsFile()).filter(Boolean);+ const normalized = files.map(file => {+ // 无扩展名截图沿用 MIME 命名;文件不经过 FileList 注入或二次上传。+ const extension = mimeExtensions[file.type];+ return !/\.[^.]+$/.test(file.name) && extension+ ? new File([file], `clipboard-${Date.now()}.${extension}`, { type: file.type }) : file;+ });+ const file = normalized.find(item => accepted.some(extension => item.name.toLowerCase().endsWith(extension)));+ if (file) { event.preventDefault(); submit(file); }+ };+ document.addEventListener("paste", paste);+ window.addEventListener("pagehide", () => document.removeEventListener("paste", paste), { once: true });+ display("");+}diff --git a/mineru/resources/pdf_preview/trace.mjs b/mineru/resources/pdf_preview/trace.mjsindex 5715584f..c5f1297c 100644--- a/mineru/resources/pdf_preview/trace.mjs+++ b/mineru/resources/pdf_preview/trace.mjs@@ -1,5 +1,7 @@// PDF.js 的溯源层只依赖宿主查看器及公开页视图,状态按文档隔离。-export function installTrace({ viewer, eventBus, container, documentId, messages }) {+export function installTrace({ viewer, eventBus, container, sourceId, messages }) {+ let documentId = "";+ let initialized = false;const layers = new Map();let entries = [];let sourcesByPage = new Map();@@ -8,8 +10,6 @@ export function installTrace({ viewer, eventBus, container, documentId, messageslet layoutByBox = new Map();let traceableSources = new Set();let mergedEntries = new Map();- let pageIndices = [];- let pageNumbers = new Map();let selectedId = "";let selectedSourceKey = "";let hoveredBox = null;@@ -36,7 +36,7 @@ export function installTrace({ viewer, eventBus, container, documentId, messagesdocument.getElementById("toolbar").append(toggle);// 普通调用语句保留当前调用帧,避免 WebKit 在严格模式尾调用中把消息来源归到父窗口。const send = (message) => {- parent.postMessage({ ...message, channel: "mineru-trace", documentId }, location.origin);+ parent.postMessage({ ...message, channel: "mineru-trace", documentId, sourceId }, location.origin);};// 物理身份包含原始页、顶层块号和完整子路径,跨页合并后仍能精确关联。const sourceKey = (source) => JSON.stringify([source.page_idx, source.block_index, source.child_path]);@@ -57,8 +57,8 @@ export function installTrace({ viewer, eventBus, container, documentId, messages};// 读取真实页框而非缓存的命中元素,页面画布被回收后仍能使用已加载的页面尺寸。const sourceRect = (source, host) => {- const pageNumber = pageNumbers.get(source.page_idx);- const page = pageNumber === undefined ? null : viewer.getPageView(pageNumber - 1);+ const pageNumber = source.page_idx + 1;+ const page = viewer.getPageView(pageNumber - 1);const bbox = source.bbox;if (!page?.pdfPage || !page.div.isConnected || bbox[2] <= bbox[0] || bbox[3] <= bbox[1]) return null;const rect = page.div.getBoundingClientRect();@@ -149,7 +149,6 @@ export function installTrace({ viewer, eventBus, container, documentId, messageslayoutByBox = new Map();traceableSources = new Set();mergedEntries = new Map();- pageNumbers = new Map(pageIndices.map((pageIdx, index) => [pageIdx, index + 1]));for (const entry of entries) {const seen = new Set();// 按首次出现的位置保留物理区域,父子共框及重复来源只参与一次连接。@@ -269,7 +268,7 @@ export function installTrace({ viewer, eventBus, container, documentId, messages// 跳页后的页面可能尚未获得真实尺寸,等待对应页完成渲染再定位。const finishNavigation = () => {if (!pending) return;- const pageNumber = pageIndices.indexOf(pending.pageIdx) + 1;+ const pageNumber = pending.pageIdx + 1;const page = viewer.getPageView(pageNumber - 1);const layer = page?.div.querySelector(".mineru-trace-layer");const boxes = [...(layer?.children || [])].filter(item => item.traceIds.includes(pending.id));@@ -304,7 +303,7 @@ export function installTrace({ viewer, eventBus, container, documentId, messagesold.hit.remove();old.layout.remove();}- const pageIdx = pageIndices[pageNumber - 1];+ const pageIdx = pageNumber - 1;const candidates = [...(sourcesByPage.get(pageIdx) || [])];candidates.sort((a, b) => b.entry.depth - a.entry.depth);const unique = new Map();@@ -395,10 +394,15 @@ export function installTrace({ viewer, eventBus, container, documentId, messagesevent.source !== parent ||event.origin !== location.origin ||data?.channel !== "mineru-trace" ||- data.documentId !== documentId+ data.sourceId !== sourceId)return;- if (data.type === "clear") {+ if (data.type === "bind") {+ if (documentId === data.documentId) return;+ documentId = data.documentId;+ initialized = false;+ } else if (data.documentId !== documentId) return;+ if (data.type === "clear" || data.type === "bind") {entries = [];selectedId = "";selectedSourceKey = "";@@ -409,7 +413,7 @@ export function installTrace({ viewer, eventBus, container, documentId, messagesclearLayers();toggle.hidden = true;} else if (data.type === "init") {- if (!Array.isArray(data.entries) || !Array.isArray(data.pageIndices)) return;+ if (!documentId || !Array.isArray(data.entries)) return;entries = data.entries.filter((entry) =>typeof entry.id === "string" &&@@ -422,7 +426,6 @@ export function installTrace({ viewer, eventBus, container, documentId, messagessource.bbox.every((value) => Number.isFinite(value) && value >= 0 && value <= 1)));- pageIndices = data.pageIndices;const layoutRegions = Array.isArray(data.layoutRegions) ? data.layoutRegions.filter((region) =>Number.isInteger(region.page_idx) && Number.isInteger(region.block_index) &&Array.isArray(region.child_path) && region.child_path.every((value) => Number.isInteger(value) && value >= 0) &&@@ -439,6 +442,13 @@ export function installTrace({ viewer, eventBus, container, documentId, messagestoggle.hidden = !layoutRegions.length && !entries.length;for (const page of viewer.getCachedPageViews()) mount(page.id);scheduleConnections();+ if (!initialized) {+ initialized = true;+ const pageNumber = data.initialPageIdx + 1;+ if (Number.isInteger(data.initialPageIdx) && pageNumber >= 1 && pageNumber <= viewer.pagesCount) {+ viewer.scrollPageIntoView({ pageNumber });+ }+ }} else if (data.type === "select" && entries.some((entry) => entry.id === data.id)) {pending = null;selectedId = data.id;@@ -450,8 +460,8 @@ export function installTrace({ viewer, eventBus, container, documentId, messagesfocusedBox = null;updateSelection();if (data.scroll) {- const pageNumber = pageIndices.indexOf(data.pageIdx) + 1;- if (pageNumber < 1) return;+ const pageNumber = data.pageIdx + 1;+ if (pageNumber < 1 || pageNumber > viewer.pagesCount) return;pending = data;viewer.scrollPageIntoView({ pageNumber });finishNavigation();diff --git a/mineru/resources/pdf_preview/viewer.mjs b/mineru/resources/pdf_preview/viewer.mjsindex 7daad87d..67dd8b73 100644--- a/mineru/resources/pdf_preview/viewer.mjs+++ b/mineru/resources/pdf_preview/viewer.mjs@@ -88,7 +88,7 @@ const zoom = (delta) => {// 模块和 worker 使用同一份固定发行包,不启用 PDF 内嵌脚本、编辑或交互表单。try {const source = new URL(params.get("file") || "", window.location.href);- if (!params.get("file") || source.origin !== window.location.origin || !source.pathname.includes("/gradio_api/file=")) {+ if (!params.get("file") || source.origin !== window.location.origin || !(source.protocol === "blob:" || source.pathname.includes("/gradio_api/file="))) {throw new Error("Invalid PDF source");}const pdfjs = await import("./vendor/pdfjs/legacy/build/pdf.min.mjs");@@ -105,9 +105,7 @@ try {ready = true;document.getElementById("toolbar").setAttribute("aria-busy", "false");resize();- if (params.get("documentId")) {- disposeTrace = installTrace({ viewer, eventBus, container, documentId: params.get("documentId"), messages });- }+ disposeTrace = installTrace({ viewer, eventBus, container, sourceId: params.get("sourceId"), messages });});eventBus.on("pagechanging", updateControls);eventBus.on("scalechanging", updateControls);diff --git a/pyproject.toml b/pyproject.tomlindex 6fce84f0..ed657668 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -38,7 +38,7 @@ classifiers = ["Programming Language :: Python :: 3.14",]dependencies = [- "docvortex>=0.6.20,<0.7",+ "docvortex>=0.6.21,<0.7","gradio>=6.21,<7","mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'","mineru-vl-utils>=2.0.8,<3",diff --git a/scripts/verify_pdfjs_distribution.py b/scripts/verify_pdfjs_distribution.pyindex 622ba267..dbb82a33 100644--- a/scripts/verify_pdfjs_distribution.py+++ b/scripts/verify_pdfjs_distribution.py@@ -13,7 +13,7 @@ def verify_distribution(path: Path) -> None:"""逐文件比较发布包与源码资源,防止递归目录或许可证在打包时遗漏。"""root = Path(__file__).resolve().parents[1]resources = root / "mineru/resources/pdf_preview"- expected = [*resources.rglob("*"), root / "mineru/resources/gradio_pdf_preview.js"]+ expected = [*resources.rglob("*"), *(root / "mineru/resources").glob("gradio_*.js")]if path.suffix == ".whl":with zipfile.ZipFile(path) as archive:contents = {name: archive.read(name) for name in archive.namelist() if "mineru/resources/" in name}diff --git a/tests/browser/gradio_layout_checks.js b/tests/browser/gradio_layout_checks.jsindex bb09a6e6..44c81e9c 100644--- a/tests/browser/gradio_layout_checks.js+++ b/tests/browser/gradio_layout_checks.js@@ -2,12 +2,14 @@async (page) => {const pdf = await (await page.locator("iframe.mineru-pdf-frame").elementHandle()).contentFrame();const html = await (await page.locator("iframe.mineru-rendered-html-frame").elementHandle()).contentFrame();- const viewport = page.viewportSize();+ const viewport = page.viewportSize() || await page.evaluate(() => ({ width: innerWidth, height: innerHeight }));// 从生产预览配置读取期望布局,逐项核对实际 DOM 和页面几何。const config = await html.evaluate(() => {const script = [...document.scripts].find(node => node.textContent.includes('"layoutRegions":'));return JSON.parse(script.textContent.slice(script.textContent.lastIndexOf(")(") + 2, -2));});+ const firstPage = Math.min(...config.layoutRegions.map(region => region.page_idx)) + 1;+ const pageCount = Number(await pdf.locator("#pages").textContent());const toggle = pdf.locator("#trace-toggle");if (await toggle.getAttribute("aria-pressed") !== "true") await toggle.click();// 翻页必须等待当前页浮层完成挂载,覆盖 PDF.js 缓存重建。@@ -20,7 +22,7 @@ async (page) => {// 坐标以实际页框为基准,标签允许收缩但类型、编号和身份必须完整。const checkPage = async (number) => {await goToPage(number);- const expected = config.layoutRegions.filter(region => region.page_idx === config.pageIndices[number - 1]);+ const expected = config.layoutRegions.filter(region => region.page_idx === number - 1);await pdf.waitForFunction(({ number, expected }) => {const host = document.querySelector(`.page[data-page-number="${number}"]`);const layer = host?.querySelector(".mineru-layout-layer");@@ -61,11 +63,11 @@ async (page) => {return expected.length;};const checkedPages = [];- for (const number of [...new Set([1, Math.min(2, config.pageIndices.length), config.pageIndices.length])]) {+ for (const number of [...new Set([firstPage, Math.min(firstPage + 1, pageCount), pageCount])]) {checkedPages.push({ number, regions: await checkPage(number) });}- await goToPage(1);- const sourceButton = pdf.locator('.page[data-page-number="1"] button[data-trace-id]').last();+ await goToPage(firstPage);+ const sourceButton = pdf.locator(` .page[data-page-number="${firstPage}"] button[data-trace-id]`.trim()).last();const sourceId = await sourceButton.getAttribute("data-trace-id");await sourceButton.click();await html.waitForFunction(id => document.querySelector("[data-mineru-selected]")?.dataset.docvortexTraceId === id, sourceId);@@ -100,7 +102,7 @@ async (page) => {await pdf.waitForFunction(key => document.querySelector(".mineru-layout-region.expanded")?.dataset.sourceKey === key, hoveredKey);await toggle.hover();await pdf.waitForFunction(key => document.querySelector(".mineru-layout-region.expanded")?.dataset.sourceKey === key, selectedKey);- const inspector = pdf.locator('.page[data-page-number="1"] .mineru-layout-inspector').first();+ const inspector = pdf.locator(`.page[data-page-number="${firstPage}"] .mineru-layout-inspector`).first();if (await inspector.count()) {const key = await inspector.getAttribute("data-source-key");await inspector.focus();@@ -117,7 +119,7 @@ async (page) => {await html.locator(`[data-docvortex-trace-id="${merged.id}"]`).press("Enter");for (const source of merged.sources) {await html.getByRole("button", { name: new RegExp(` ${source.page_idx + 1}$`) }).click();- const number = config.pageIndices.indexOf(source.page_idx) + 1;+ const number = source.page_idx + 1;await pdf.waitForFunction(number => Number(document.querySelector("#page").value) === number, number);await checkPage(number);const key = JSON.stringify([source.page_idx, source.block_index, source.child_path]);@@ -135,7 +137,7 @@ async (page) => {.find(sources => sources.length > new Set(sources.map(source => source.page_idx)).size));if (samePage) {for (const source of samePage) {- await goToPage(config.pageIndices.indexOf(source.page_idx) + 1);+ await goToPage(source.page_idx + 1);const key = JSON.stringify([source.page_idx, source.block_index, source.child_path]);const buttons = pdf.locator("button[data-trace-id]");const index = await buttons.evaluateAll((nodes, key) => nodes.findIndex(node => node.dataset.sourceKey === key), key);@@ -149,11 +151,11 @@ async (page) => {await pdf.waitForFunction(() => [...document.querySelectorAll(".mineru-layout-region:not(.selected):not(.hovered)")].every(node => getComputedStyle(node).visibility === "hidden"));await toggle.click();- await goToPage(1);+ await goToPage(firstPage);const oldScale = await pdf.locator("#scale").innerText();await pdf.locator("#zoom-in").click();await pdf.waitForFunction(value => document.querySelector("#scale").textContent !== value, oldScale);- await checkPage(1);+ await checkPage(firstPage);const selectedSources = await html.evaluate(() => {const selected = document.querySelector("[data-mineru-selected]");return selected ? JSON.parse(selected.dataset.docvortexSources) : [];@@ -166,7 +168,7 @@ async (page) => {await pdf.locator("#fit").click();await page.setViewportSize({ width: 375, height: 900 });await page.locator("iframe.mineru-pdf-frame").scrollIntoViewIfNeeded();- await checkPage(1);+ await checkPage(firstPage);// 辅助块的压缩标签也能通过键盘查看完整类型,且使用独立的只读检查元素。const compactInspector = await pdf.locator(".mineru-layout-inspector").evaluateAll(nodes => nodes.findIndex(node => {const region = [...node.closest(".page").querySelectorAll(".mineru-layout-region")]@@ -185,7 +187,7 @@ async (page) => {const overflow = await pdf.evaluate(() => document.getElementById("toolbar").scrollWidth > innerWidth);if (overflow) throw new Error("Narrow toolbar overflows");await page.setViewportSize(viewport);- await checkPage(1);+ await checkPage(firstPage);return {checkedPages, sourceId, targetId, colors, mergedSources: merged?.sources, samePageSources: samePage,layoutRegions: config.layoutRegions.length, narrow: true, zoom: true, inspectedAuxiliary: compactInspector >= 0diff --git a/tests/browser/gradio_merge_checks.js b/tests/browser/gradio_merge_checks.jsindex d42c1187..49aeeaf0 100644--- a/tests/browser/gradio_merge_checks.js+++ b/tests/browser/gradio_merge_checks.js@@ -3,7 +3,7 @@ async (page) => {const pdfElement = page.locator("iframe.mineru-pdf-frame");const pdf = await (await pdfElement.elementHandle()).contentFrame();const html = await (await page.locator("iframe.mineru-rendered-html-frame").elementHandle()).contentFrame();- const viewport = page.viewportSize();+ const viewport = page.viewportSize() || await page.evaluate(() => ({ width: innerWidth, height: innerHeight }));const data = await html.evaluate(() => {const script = [...document.scripts].find(node => node.textContent.includes('"layoutRegions":'));const config = JSON.parse(script.textContent.slice(script.textContent.lastIndexOf(")(") + 2, -2));@@ -11,7 +11,7 @@ async (page) => {id: node.dataset.docvortexTraceId, type: node.dataset.blockType,sources: JSON.parse(node.dataset.docvortexSources)}));- return { documentId: config.documentId, pageIndices: config.pageIndices, entries };+ return { documentId: config.documentId, entries };});const merged = data.entries.filter(entry => entry.sources.length > 1);if (!merged.length) throw new Error("The real parse result has no merged sources to check");@@ -24,26 +24,26 @@ async (page) => {// 通过页码控件取得端点页面的实际尺寸,再把线段中点滚入视口。const showEdge = async (entry, index) => {for (const source of entry.sources.slice(index, index + 2)) {- const number = data.pageIndices.indexOf(source.page_idx) + 1;+ const number = source.page_idx + 1;await pdf.locator("#page").fill(String(number));await pdf.locator("#page").press("Enter");await pdf.locator(`.page[data-page-number="${number}"] .mineru-trace-layer`).waitFor({ state: "attached" });}- await pdf.evaluate(({ entry, index, pageIndices }) => {+ await pdf.evaluate(({ entry, index }) => {const host = document.getElementById("viewer-container");const sources = entry.sources.slice(index, index + 2);const bounds = sources.map(source => document.querySelector(- `.page[data-page-number="${pageIndices.indexOf(source.page_idx) + 1}"]`+ `.page[data-page-number="${source.page_idx + 1}"]`).getBoundingClientRect());const middle = (bounds[0].top + sources[0].bbox[3] * bounds[0].height +bounds[1].top + sources[1].bbox[1] * bounds[1].height) / 2;host.scrollTop += middle - host.getBoundingClientRect().top - host.clientHeight / 2;- }, { entry, index, pageIndices: data.pageIndices });+ }, { entry, index });await pdf.locator("#toolbar").hover();};// 直接比较 SVG 端点和实际命中框的角点,允许最多 2 CSS px 的亚像素排版误差。const checkEdges = async (entry) => {- await pdf.waitForFunction(({ entry, pageIndices }) => {+ await pdf.waitForFunction(({ entry }) => {const svg = document.querySelector(".mineru-merge-layer");if (svg?.dataset.traceId !== entry.id || !svg.children.length) return false;const origin = svg.getBoundingClientRect();@@ -54,7 +54,7 @@ async (page) => {const index = keys.indexOf(JSON.stringify(from));if (index < 0 || keys[index + 1] !== JSON.stringify(to)) throw new Error("Merge source order changed");const rects = entry.sources.slice(index, index + 2).map(source => {- const pageNode = document.querySelector(`.page[data-page-number="${pageIndices.indexOf(source.page_idx) + 1}"]`);+ const pageNode = document.querySelector(`.page[data-page-number="${source.page_idx + 1}"]`);const node = [...pageNode.querySelectorAll("button[data-trace-id]")].find(node =>node.traceIds.includes(entry.id) && node.source.bbox.every((value, i) => value === source.bbox[i]));if (!node) throw new Error("Missing rendered source hit box");@@ -71,7 +71,7 @@ async (page) => {}if (getComputedStyle(svg).pointerEvents !== "none") throw new Error("Merge layer intercepts clicks");return true;- }, { entry, pageIndices: data.pageIndices });+ }, { entry });};for (const entry of merged) {await selectEntry(entry);diff --git a/tests/browser/gradio_trace_checks.js b/tests/browser/gradio_trace_checks.jsindex 3e31fa86..661bf8d0 100644--- a/tests/browser/gradio_trace_checks.js+++ b/tests/browser/gradio_trace_checks.js@@ -22,7 +22,7 @@ async (page) => {await page.frameLocator("iframe.mineru-pdf-frame").locator("button[data-trace-id]").first().waitFor();const pdf = await (await page.locator("iframe.mineru-pdf-frame").elementHandle()).contentFrame();const html = await (await page.locator("iframe.mineru-rendered-html-frame").elementHandle()).contentFrame();- const documentId = new URLSearchParams(new URL(pdf.url()).hash.slice(1)).get("documentId");+ const documentId = await page.evaluate(() => window.__mineruPdfPreview.result);if (!documentId) throw new Error("Convert the PDF before checking source navigation");const pageInput = pdf.locator("#page");if (Number(await pageInput.getAttribute("max")) < 2) throw new Error("Use a PDF with at least two pages");diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex 6a1366fd..78676669 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import base64import ioimport jsonimport subprocess@@ -105,11 +106,14 @@ def _middle_json(]if with_image:image_index = page_idx * 10 + 1+ payload = io.BytesIO()+ Image.new("RGB", (30, 40), (0, 255, 0) if page_idx == 1 else (0, 0, 255)).save(payload, format="JPEG")image_body = ImageBodyBlock(type=BlockType.IMAGE_BODY,index=image_index,bbox=(0.1, 0.3, 0.8, 0.8) if file_suffix == "pdf" else None,content="",+ image_base64="data:image/jpeg;base64," + base64.b64encode(payload.getvalue()).decode(),)blocks.append(ImageBlock(@@ -369,7 +373,6 @@ def test_v1_client_discovers_api_server_without_advanced(api = parser_api_server.create_app(upload_dir=str(tmp_path / "api"),tiers=("flash", "basic", "standard"),-)request_log: list[tuple[str, str, str | None]] = []@@ -524,12 +527,11 @@ def test_gradio_routes_native_and_pdf_to_standard_only_server(monkeypatch: pytesmonkeypatch.setenv("MINERU_API_KEY", "remote-secret")monkeypatch.setattr(parser_api_server, "_preflight_tier_dependencies", Mock())_stub_inference(monkeypatch)- remote_api = parser_api_server.create_app(- upload_dir=str(tmp_path / "remote"), tiers=("standard",), api_key="remote-secret"- )+ remote_api = parser_api_server.create_app(upload_dir=str(tmp_path / "remote"), tiers=("standard",), api_key="remote-secret")requests: list[tuple[str, str, str, str | None]] = []submissions: list[dict[str, Any]] = []with TestClient(remote_api, base_url="http://remote.test") as remote_http:+async def handle(request: httpx.Request) -> httpx.Response:"""将能力发现、上传和下载都交给唯一远端服务,保留完整请求供断言。"""requests.append((request.url.host, request.method, request.url.path, request.headers.get("authorization")))@@ -910,9 +912,8 @@ def test_persist_and_render_all_gradio_download_formats(tmp_path: Path) -> None:artifacts = persist_parse_result(result, source, output_root=tmp_path / "output", page_range="")assert artifacts.middle_json_path.read_text(encoding="utf-8").find('"schema_version": "2.0"') >= 0- assert artifacts.origin_pdf_path == artifacts.root / "origin.pdf"- assert artifacts.origin_pdf_path is not None and artifacts.origin_pdf_path.is_file()- assert artifacts.origin_pdf_path.read_bytes() == source.read_bytes()+ assert not (artifacts.root / "origin.pdf").exists()+ assert artifacts.prepared_source is Noneassert not (artifacts.root / "layout.pdf").exists()assert not (artifacts.root / "model_output.json").exists()assert not list(artifacts.root.glob("*.zip"))@@ -941,7 +942,7 @@ def test_persist_and_render_all_gradio_download_formats(tmp_path: Path) -> None:assert any(name.startswith("images/") for name in archive.namelist())-def test_persist_image_input_creates_real_origin_pdf(tmp_path: Path) -> None:+def test_image_pdf_is_prepared_outside_result_persistence(tmp_path: Path) -> None:"""验证图片输入生成可读取的原文预览 PDF。"""source = tmp_path / "scan.png"Image.new("RGB", (64, 48), "white").save(source)@@ -951,13 +952,17 @@ def test_persist_image_input_creates_real_origin_pdf(tmp_path: Path) -> None:output_root=tmp_path / "output",page_range="",)- assert artifacts.origin_pdf_path is not None- assert artifacts.origin_pdf_path.read_bytes().startswith(b"%PDF")- assert len(PdfReader(str(artifacts.origin_pdf_path)).pages) == 1+ from mineru.kit.gradio.sources import prepare_source++ prepared = prepare_source(source, source_id="1" * 32, output_root=tmp_path / "output")+ assert prepared.preview_pdf_path is not None+ assert prepared.preview_pdf_path.read_bytes().startswith(b"%PDF")+ assert len(PdfReader(str(prepared.preview_pdf_path)).pages) == 1+ assert not (artifacts.root / "origin.pdf").exists()assert not (artifacts.root / "layout.pdf").exists()-def test_page_range_image_crops_follow_original_page_indices(tmp_path: Path) -> None:+def test_page_range_materialized_images_keep_original_page_indices(tmp_path: Path) -> None:"""验证抽页后视觉块仍从对应原始页裁图,而不是错位到相邻页。"""source = tmp_path / "colors.pdf"source.write_bytes(_colored_pdf_bytes([(1, 0, 0), (0, 1, 0), (0, 0, 1)]))@@ -977,7 +982,7 @@ def test_page_range_image_crops_follow_original_page_indices(tmp_path: Path) ->assert second_mean[2] > second_mean[0] + 100 and second_mean[2] > second_mean[1] + 100-def test_persist_page_range_keeps_cropped_origin_page_order(tmp_path: Path) -> None:+def test_persist_page_range_keeps_original_initial_page_without_pdf(tmp_path: Path) -> None:"""验证 V1 page_range 会应用到原文预览 PDF 并保留原始页号映射。"""source = tmp_path / "three-pages.pdf"source.write_bytes(_pdf_bytes(page_count=3))@@ -987,9 +992,8 @@ def test_persist_page_range_keeps_cropped_origin_page_order(tmp_path: Path) -> Noutput_root=tmp_path / "output",page_range="2-3",)- assert artifacts.page_indices == (1, 2)- assert artifacts.origin_pdf_path is not None- assert len(PdfReader(str(artifacts.origin_pdf_path)).pages) == 2+ assert artifacts.initial_page_idx == 1+ assert not list(artifacts.root.glob("*.pdf"))assert not (artifacts.root / "layout.pdf").exists()@@ -1000,12 +1004,10 @@ def test_run_artifact_paths_are_absolute_and_inside_output_root(tmp_path: Path)second = create_run_artifacts(source, tmp_path / "output")assert first.root != second.rootassert first.root.is_absolute()- assert first.source_path.name == "source.pdf"assert first.middle_json_path.name == "middle_json.json"assert first.markdown_path.name == "markdown.md"assert first.structured_content_path.name == "structured_content.json"for path in (- first.source_path,first.middle_json_path,first.markdown_path,first.structured_content_path,@@ -1107,7 +1109,7 @@ def test_gradio_examples_render_only_with_local_files(monkeypatch: pytest.Monkey(dataset,) = find_examples(demo)assert [sample[0] for sample in dataset.samples] == ["demo.pdf"]assert dataset.samples_per_page == gradio_app._EXAMPLES_PER_PAGE- upload = next(block for block in demo.blocks.values() if "mineru-upload-file" in (block.elem_classes or []))+ upload = next(fn for fn in demo.fns.values() if fn.name == "convert_handler").inputs[0]click = next(event for event in demo.config["dependencies"] if (dataset._id, "click") in event["targets"])assert upload._id in click["outputs"]status = next(block for block in demo.blocks.values() if "mineru-status-panel" in (block.elem_classes or []))@@ -1128,7 +1130,10 @@ def test_gradio_examples_render_only_with_local_files(monkeypatch: pytest.Monkeydef test_gradio_non_pdf_ignores_hidden_force_ocr(tmp_path: Path, suffix: str) -> None:"""直接调用事件并传入残留 True,非 PDF 请求仍使用 auto。"""source = tmp_path / f"source{suffix}"- source.write_bytes(b"placeholder")+ if source.suffix.lower().lstrip(".") in IMAGE_EXTENSIONS:+ Image.new("RGB", (20, 30), "white").save(source, format="PNG")+ else:+ source.write_bytes(b"placeholder")client = SimpleNamespace(parse_file=AsyncMock(side_effect=V1ArtifactError("stop after request")))capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("default",), ("upload",))demo = build_gradio_app(client, capabilities, output_root=tmp_path / "output", enable_example=False)@@ -1174,7 +1179,7 @@ def test_build_gradio_app_exposes_html_tab_and_download_menu(tmp_path: Path) ->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 = [- component for component in app.blocks.values() if component.__class__.__name__ == "File" and component.visible+ component for component in app.blocks.values() if component.__class__.__name__ == "File" and component.file_types]assert len(file_inputs) == 1assert file_inputs[0].file_count == "single"@@ -1258,7 +1263,10 @@ def test_gradio_tier_slider_uses_available_tiers_and_preserves_selection(def test_gradio_conversion_enforces_file_type_tier(tmp_path: Path, extension: str, uppercase: bool) -> None:"""高档位残留值对所有轻量格式固定为 Flash,图片则保留用户选择,后缀不区分大小写。"""source = tmp_path / f"source.{extension.upper() if uppercase else extension}"- source.write_bytes(b"placeholder")+ if source.suffix.lower().lstrip(".") in IMAGE_EXTENSIONS:+ Image.new("RGB", (20, 30), "white").save(source, format="PNG")+ else:+ source.write_bytes(b"placeholder")client = SimpleNamespace(parse_file=AsyncMock(side_effect=V1ArtifactError("stop after request")))capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("standard", "flash"), ("default",), ("upload",))demo = build_gradio_app(client, capabilities, output_root=tmp_path / "output", enable_example=False)@@ -1354,7 +1362,9 @@ def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(convert_handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")updates = asyncio.run(collect_updates(convert_handler))- assert client.calls == [(source.resolve(), expected_tier, "1")]+ assert len(client.calls) == 1+ assert client.calls[0][0].read_bytes() == source.read_bytes()+ assert client.calls[0][1:] == (expected_tier, "1")assert len(updates[-1]) == 16assert updates[-1][7] == Path(updates[-1][6]["root"]).nameassert updates[-1][6] is not None@@ -1488,7 +1498,7 @@ def test_gradio_local_queue_cancellation_releases_slot_and_keeps_sessions_isolatassert handler_fn.concurrency_limit is None# 清除和文件切换都使用 Gradio 的会话级取消事件。cancellation_events = [dependency for dependency in demo.config["dependencies"] if dependency["cancels"]]- assert len(cancellation_events) >= 2+ assert len(cancellation_events) == 1assert all(handler_fn._id in dependency["cancels"] for dependency in cancellation_events)ui = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_ui")@@ -1595,7 +1605,7 @@ def test_persist_skips_layout_pdf_rendering(tmp_path: Path, monkeypatch: pytest.ParseResult(middle_json=_middle_json()), source, output_root=tmp_path / "output", page_range="")render_layout.assert_not_called()- assert artifacts.origin_pdf_path.is_file()+ assert not list(artifacts.root.glob("*.pdf"))assert artifacts.middle_json_path.is_file()assert artifacts.markdown_path.is_file()assert not (artifacts.root / "layout.pdf").exists()@@ -1604,7 +1614,7 @@ def test_persist_skips_layout_pdf_rendering(tmp_path: Path, monkeypatch: pytest.legacy_state = {**state, "layout_pdf_path": str(artifacts.root / "layout.pdf")}restored = artifact_module.RunArtifacts.from_state(legacy_state)assert restored.as_state() == state- assert _prepare_preview(suffix, restored).pdf_path == artifacts.origin_pdf_path+ assert _prepare_preview(suffix, restored).pdf_path is Nonewith zipfile.ZipFile(render_download(legacy_state, "markdown")) as archive:assert f"{artifacts.stem}.md" in archive.namelist()assert "layout.pdf" not in archive.namelist()@@ -1638,10 +1648,12 @@ def test_gradio_slow_precheck_keeps_polling_available_and_queues_other_sessions("""预检线程阻塞时仍可独立查询准备和排队状态。"""requests = [SimpleNamespace(session_hash=f"s{i}") for i in range(2)]tickets = [json.dumps({"run_id": f"{i + 1:032x}", "revision": 1}) for i in range(2)]- first, second = [- asyncio.create_task(handler(str(source), 0, "", False, ticket, request))- for ticket, request in zip(tickets, requests)- ]+ first = asyncio.create_task(handler(str(source), 0, "", False, tickets[0], requests[0]))+ for _ in range(600):+ if started.is_set():+ break+ await asyncio.sleep(0.005)+ second = asyncio.create_task(handler(str(source), 0, "", False, tickets[1], requests[1]))try:for _ in range(600):if started.is_set() and "Queued locally" in poll(tickets[1], requests[1]):diff --git a/tests/unittest/test_kit_gradio_conversion.cjs b/tests/unittest/test_kit_gradio_conversion.cjsindex bd771a63..be76d455 100644--- a/tests/unittest/test_kit_gradio_conversion.cjs+++ b/tests/unittest/test_kit_gradio_conversion.cjs@@ -77,3 +77,11 @@ assert.equal(insecureRun.run_id[12], '4');assert.match(insecureRun.run_id[16], /^[89ab]$/);assert.equal(warns.length, 1);console.log('insecure-context fallback passed');++// 同一文件的重复 change 不应取消任务;换选择身份必须立即失效。+window.__mineruPdfPreview = { sourceId: "source-one", source: "/source.pdf" };+const activeSourceTicket = JSON.parse(invoke("begin")[0]);+assert.equal(activeSourceTicket.source_id, "source-one");+assert.ok(invoke("cancel_source", {path:"/source.pdf"}).every(value => value.__type__ === "update"));+window.__mineruPdfPreview.sourceId = "source-two";+assert.equal(invoke("cancel_source", {path:"/source.pdf"})[0], "");diff --git a/tests/unittest/test_kit_gradio_document_io.py b/tests/unittest/test_kit_gradio_document_io.pyindex 6aaaa815..20805475 100644--- a/tests/unittest/test_kit_gradio_document_io.py+++ b/tests/unittest/test_kit_gradio_document_io.py@@ -102,14 +102,14 @@ def test_callbacks_share_injected_io_without_crossing_app_instances(tmp_path: Parequest = SimpleNamespace(session_hash="same-session")receipt = json.loads(await callbacks[callback_name](str(source), 0, raw_range, True, ticket, request))outputs = receipt["outputs"]- state = {"root": str(Path(outputs[2]["value"]["path"]).parent)}+ state = {"root": str(tmp_path / f"output-{index}" / "gradio" / outputs[6])}assert Path(state["root"]).name == outputs[6]assert receipt["run_id"] == f"{index + 1:032x}"assert "Completed" in outputs[0] and outputs[1] and outputs[-1]assert Path(state["root"]).parent == tmp_path / f"output-{index}" / "gradio"assert host.calls == [("metadata", str(source)),- ("range", source.resolve(), raw_range, index + 1),+ ("range", client.parse_file.call_args.args[0], raw_range, index + 1),("persist", source.resolve(), tmp_path / f"output-{index}", str(index + 1)),]client.parse_file.assert_awaited_once()diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.pyindex c8789383..bd7763fa 100644--- a/tests/unittest/test_kit_gradio_download.py+++ b/tests/unittest/test_kit_gradio_download.py@@ -124,7 +124,7 @@ def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:)assert reset_dependency["backend_fn"] is Falseassert "Preparing request..." in reset_dependency["js"]- upload = next(block for block in app.blocks.values() if "mineru-upload-file" in (block.elem_classes or []))+ upload = next(fn for fn in app.fns.values() if fn.name == "convert_handler").inputs[0]reset_on_upload = next(depfor dep in app.config["dependencies"]diff --git a/tests/unittest/test_kit_gradio_html.py b/tests/unittest/test_kit_gradio_html.pyindex 06f6ff76..5943cd8b 100644--- a/tests/unittest/test_kit_gradio_html.py+++ b/tests/unittest/test_kit_gradio_html.py@@ -125,6 +125,7 @@ def test_materialized_html_and_independent_archives(tmp_path: Path, image_sourceelse:(tmp_path / "图 1.png").write_bytes(red)(tmp_path / "图 2.png").write_bytes(blue)+ image_body.image_base64 = Noneimage_body.image_path = "图 1.png"table_image = quote("图 2.png")middle.pages[0].blocks.extend(@@ -150,7 +151,6 @@ def test_materialized_html_and_independent_archives(tmp_path: Path, image_sourceassert "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()@@ -262,10 +262,10 @@ def test_epub_preview_anchors_stay_in_srcdoc_without_changing_download(tmp_path:def test_preview_link_targets_preserve_document_links(href: str, external: bool) -> None:"""按链接协议区分网页与文内跳转,覆盖表格链接并保留已有 rel 和其他标签内容。"""document = (- '<html><head><style>a { color: blue; }</style></head><body>'+ "<html><head><style>a { color: blue; }</style></head><body>"f'<table><tr><td><a href="{html.escape(href, quote=True)}" target="_self" rel="nofollow noopener">''<em>Reference</em></a></td></tr></table><a id="chapter-one">Chapter One</a>'- '<script>const example = "<a href=\'https://example.test\'>";</script></body></html>'+ "<script>const example = \"<a href='https://example.test'>\";</script></body></html>")original = BeautifulSoup(document, "html.parser")prepared = BeautifulSoup(_prepare_preview_links(document), "html.parser")diff --git a/tests/unittest/test_kit_gradio_image_names.py b/tests/unittest/test_kit_gradio_image_names.pyindex 92d8db2d..3cd6f18c 100644--- a/tests/unittest/test_kit_gradio_image_names.py+++ b/tests/unittest/test_kit_gradio_image_names.py@@ -16,8 +16,6 @@ from test_kit_gradio_html import _image_bytesfrom mineru.kit.common import save_parse_resultfrom mineru.kit.gradio.artifacts import (- _build_image_context,- _close_image_context,_materialize_middle_json,persist_parse_result,render_download,@@ -68,16 +66,9 @@ def test_crops_use_original_pages_and_parent_type(tmp_path: Path, page_indices:mean = ImageStat.Stat(image.convert("RGB")).meanassert mean[channel] > 240 and sum(value for index, value in enumerate(mean) if index != channel) < 20- # 单独读取裁图缓存也不应产生任何临时图片文件。- crop_root = tmp_path / "crop-only"- context = _build_image_context(saved.middle_json, artifacts.origin_pdf_path, crop_root, page_indices=page_indices)- try:- block = saved.pages[0].blocks[1].content[0]- first = context.crop_for_block(block, middle_page_idx=page_indices[0])- assert first and context.crop_for_block(block, middle_page_idx=page_indices[0]) is first- assert not crop_root.exists()- finally:- _close_image_context(context)+ # 保存后的素材重复物化不需要 PDF 对象,也不会重新编码图片。+ repeated = _materialize_middle_json(saved.middle_json, artifacts.root)+ assert repeated == saved.middle_jsondef test_parent_names_table_images_and_repeated_materialization(tmp_path: Path) -> None:@@ -134,8 +125,7 @@ def test_parent_names_table_images_and_repeated_materialization(tmp_path: Path)"images/page_0_table_image_2_2.png",]assert before["page_0_image_1.png"] == before["page_0_table_2.png"]- context = _build_image_context(saved.middle_json, None, artifacts.root)- repeated = _materialize_middle_json(saved.middle_json, context)+ repeated = _materialize_middle_json(saved.middle_json, artifacts.root)assert repeated == saved.middle_jsonassert {path.name: path.read_bytes() for path in (artifacts.root / "images").iterdir()} == beforefor format_name in ("markdown", "json", "latex"):@@ -168,8 +158,7 @@ def test_identical_images_on_different_pages_keep_their_names(tmp_path: Path) ->middle = _middle_json(file_suffix="docx", page_indices=(2, 5))for page in middle.pages:page.blocks[1].content[0].image_base64 = _image_uri("red")- context = _build_image_context(middle, None, tmp_path)- result = _materialize_middle_json(middle, context)+ result = _materialize_middle_json(middle, tmp_path)assert [page.blocks[1].content[0].image_path for page in result.pages] == ["images/page_2_image_21.png","images/page_5_image_51.png",@@ -183,15 +172,14 @@ def test_conflicting_contents_never_overwrite_or_take_inline_ordinals(tmp_path:middle.pages[0].page_idx = 1body = middle.pages[0].blocks[1].content[0]body.image_base64 = _image_uri("red")- context = _build_image_context(middle, None, tmp_path)- first = _materialize_middle_json(middle, context).pages[0].blocks[1].content[0].image_path+ first = _materialize_middle_json(middle, tmp_path).pages[0].blocks[1].content[0].image_pathbody.image_base64 = _image_uri("blue")body.content = f'<img src="{_image_uri("blue")}">'- saved = _materialize_middle_json(middle, context)+ saved = _materialize_middle_json(middle, tmp_path)second = saved.pages[0].blocks[1].content[0].image_pathassert first == "images/page_1_image_1.png"assert second == "images/page_1_image_1_duplicate_1.png"- assert _materialize_middle_json(saved, context) == saved+ assert _materialize_middle_json(saved, tmp_path) == savedassert saved.pages[0].blocks[1].content[0].content == '<img src="images/page_1_image_1_1.png">'assert (tmp_path / first).read_bytes() == _image_bytes("red")assert (tmp_path / second).read_bytes() == _image_bytes("blue")diff --git a/tests/unittest/test_kit_gradio_office_preview.py b/tests/unittest/test_kit_gradio_office_preview.pyindex 8b4f9263..f6ab400b 100644--- a/tests/unittest/test_kit_gradio_office_preview.py+++ b/tests/unittest/test_kit_gradio_office_preview.py@@ -32,7 +32,7 @@ def test_office_upload_builds_preview_without_parsing(tmp_path: Path, suffix: stenable_example=False,)callback = next(fn for fn in demo.fns.values() if fn.name == "update_file_preview")- assert len(callback.inputs) == 1+ assert len(callback.inputs) == 2request = SimpleNamespace(headers={"host": "example.test:7860"})updates = callback.fn(str(tmp_path / f"document.{suffix}"), request)assert updates[0]["visible"] is False and updates[1]["visible"] is False@@ -140,6 +140,6 @@ def test_office_conversion_never_replaces_uploaded_preview(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.png")[1]["value"] is Noneassert preview("next.epub")[2]["visible"] is Falseassert preview(None)[2]["value"] == ""diff --git a/tests/unittest/test_kit_gradio_page_range.cjs b/tests/unittest/test_kit_gradio_page_range.cjsindex 6ab863df..34cb2a74 100644--- a/tests/unittest/test_kit_gradio_page_range.cjs+++ b/tests/unittest/test_kit_gradio_page_range.cjs@@ -29,7 +29,7 @@ function createUi(limit = 20, availableTiers = tiers) {const result = reduce(availableTiers, flashOnlyExtensions, limit, state.file, state.position,JSON.stringify(state.metadata), JSON.stringify(state.previous), state.a, state.b,- JSON.stringify(state.tierSelection)+ JSON.stringify(state.tierSelection), (typeof state.file === "string" ? state.file : state.file?.path) || "");if ("value" in result[0]) state.a = result[0].value;if ("value" in result[1]) state.b = result[1].value;diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.pyindex 35f43912..23a4ba98 100644--- a/tests/unittest/test_kit_gradio_page_range.py+++ b/tests/unittest/test_kit_gradio_page_range.py@@ -158,6 +158,7 @@ def test_launch_remote_preserves_capabilities_without_local_fallback(events: list[str] = []failure = V1ArtifactError("startup failure", code="server_start_failed")remote_cap = V1ServerCapabilities("http://remote.test", remote_tiers, ("default",), ("upload",))+async def discover_remote() -> V1ServerCapabilities:"""记录主服务完成能力发现的时间点。"""events.append("remote")@@ -323,7 +324,7 @@ def test_native_range_components_and_frontend_only_events(tmp_path: Path) -> Nonevents = [event for event in demo.config["dependencies"] if (slider._id, "input") in event["targets"]]assert len(events) == 1 and events[0]["backend_fn"] is False and events[0]["queue"] is Falseassert events[0]["trigger_mode"] == "always_last"- assert len(events[0]["targets"]) == 5+ assert len(events[0]["targets"]) == 6assert events[0]["outputs"][:2] == [sliders[1]._id, sliders[2]._id]handler = next(fn for fn in demo.fns.values() if fn.name == "convert_handler")assert len(handler.inputs) == 4diff --git a/tests/unittest/test_kit_gradio_pdf_preview.cjs b/tests/unittest/test_kit_gradio_pdf_preview.cjsindex 088af66f..527251d9 100644--- a/tests/unittest/test_kit_gradio_pdf_preview.cjs+++ b/tests/unittest/test_kit_gradio_pdf_preview.cjs@@ -1,73 +1,105 @@-// 运行真实预览适配脚本,验证文件编码、事件乱序和清除失效,不模拟 Gradio 内部组件。+// 执行生产预览控制器,验证本地文件、服务器准备及结果更新共享唯一 iframe。const assert = require("node:assert/strict");const fs = require("node:fs");const vm = require("node:vm");-const path = require("node:path");-const script = fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_pdf_preview.js"), "utf8");-const window = { location: new URL("https://mineru.test/prefix/"), __mineruI18n: { text: (key) => `中文 ${key}` } };-let currentFrame = null;+const crypto = require("node:crypto").webcrypto;+const script = fs.readFileSync(require("node:path").join(__dirname, "../../mineru/resources/gradio_pdf_preview.js"), "utf8");+const location = new URL("https://mineru.test/prefix/");let disposed = 0;-const document = { querySelector: () => currentFrame };-const invoke = vm.runInNewContext(`(${script})`, { window, document, URL, URLSearchParams });-// 使用原始文件路径构造典型 FileData,模拟框架回传的未编码 URL。-const file = (name) => ({ path: `/cache/${name}`, url: `/prefix/gradio_api/file=/cache/${name}`, orig_name: name });-// 提取真正传给 iframe 的地址,后续断言同时覆盖两层 URL 编码。-const iframe = (update) => new URL(update.value.match(/src="([^"]+)"/)[1].replaceAll("&", "&"));-const first = file('中文 空格#?%&".pdf');-const second = file("second.pdf");+let revoked = 0;+let blobs = 0;+const activations = [];+const events = {};+const host = { children: [], replaceChildren(...nodes) { this.children = nodes; } };+// 最小 DOM 替身只观察真实创建、释放和 URL,不模拟 Gradio 内部状态。+const document = {+ querySelector: selector => selector === ".mineru-pdf-host" ? host : null,+ createElement: tag => ({+ tag, attributes: {},+ setAttribute(name, value) { this.attributes[name] = value; },+ remove() { host.children = host.children.filter(node => node !== this); },+ contentWindow: { __mineruPdfDisposePreview() { disposed++; } },+ })+};+class LocalURL extends URL {+ // 使用浏览器同源 Blob URL,记录释放次数。+ static createObjectURL() { return `blob:${location.origin}/${++blobs}`; }+ static revokeObjectURL() { revoked++; }+}+const window = {+ addEventListener: (name, fn) => events[name] = fn,+ __mineruI18n: { text: key => key },+ __mineruTrace: { reset() {}, activate(...values) { activations.push(values); } },+ __mineruUpload: { isImage: name => name.endsWith(".png"), invalidate() {}, sync() {}, prepared() {} },+};+const invoke = vm.runInNewContext(`(${script})`, { window, document, location, crypto, URL: LocalURL, URLSearchParams });+// 使用真实文件路径而非编码后的 URL 判断文件身份。+const file = name => ({ path: `/cache/${name}`, url: `/prefix/gradio_api/file=/cache/${name}`, orig_name: name });+const first = file('中文 #?%&".pdf');const viewer = file("assets/viewer.html");-assert.equal(invoke("reset", first).value, "");-const initial = invoke("source", first, first, viewer);-assert.equal(initial.visible, true);-const initialUrl = iframe(initial);-currentFrame = { contentWindow: { __mineruPdfDisposePreview: () => { disposed += 1; } } };-assert.equal(initialUrl.pathname, "/prefix/gradio_api/file=/cache/assets/viewer.html");-assert.ok(initialUrl.searchParams.has("document"));-const parameters = new URLSearchParams(initialUrl.hash.slice(1));-const pdfUrl = new URL(parameters.get("file"));-assert.equal(decodeURIComponent(pdfUrl.pathname), `/prefix/gradio_api/file=${first.path}`);-assert.equal(pdfUrl.search, "");-assert.equal(pdfUrl.hash, "");-assert.ok(initial.value.includes('sandbox="allow-scripts allow-same-origin"'));-assert.equal(JSON.parse(parameters.get("messages")).pdf_page, "中文 pdf_page");-assert.equal(JSON.parse(parameters.get("messages")).trace_merged, "中文 trace_merged");-assert.equal(JSON.parse(parameters.get("messages")).trace_merged_description, "中文 trace_merged_description");-// Gradio 的事件 FileData 可能缺少挂载前缀,静态入口的基址必须用于结果 PDF。-const relative = { ...first, url: first.url.replace("/prefix", "") };-const relativeParams = new URLSearchParams(iframe(invoke("source", relative, first, viewer)).hash.slice(1));-assert.equal(new URL(relativeParams.get("file")).pathname, pdfUrl.pathname);--invoke("begin");-const origin = file("run/origin.pdf");-assert.equal(invoke("result", origin, first, viewer, "run-1").visible, true);-assert.equal(invoke("source", first, first, viewer).value, undefined);-const beforeReset = disposed;-invoke("reset", second);-assert.equal(disposed, beforeReset + 1);-assert.equal(invoke("result", origin, first, viewer, "run-1").value, undefined);-assert.equal(invoke("source", first, second, viewer).value, undefined);-assert.equal(disposed, beforeReset + 1);-assert.equal(invoke("source", second, second, viewer).visible, true);-assert.equal(disposed, beforeReset + 2);-invoke("begin");-assert.equal(invoke("result", origin, second, viewer, "").value, undefined);-assert.equal(invoke("clear").value, "");-assert.equal(disposed, beforeReset + 3);-assert.equal(invoke("result", origin, second, viewer, "run-2").value, undefined);-assert.equal(invoke("source", second, second, viewer).value, undefined);+invoke("setup", viewer);+const state = window.__mineruPdfPreview;+state.local({ name: first.orig_name }, "local-one");+const originalFrame = state.frame;+assert.ok(originalFrame && state.uploading);+assert.equal(new URLSearchParams(new URL(originalFrame.src).hash.slice(1)).get("file"), `blob:${location.origin}/1`);+invoke("reset", null);+assert.equal(state.frame, originalFrame);+const uploadingRevision = state.revision;+assert.equal(state.bind(first, "local-one"), true);+assert.ok(state.revision > uploadingRevision);invoke("reset", first);-assert.notEqual(iframe(invoke("source", first, first, viewer)).search, initialUrl.search);+const ticket = JSON.parse(invoke("prepare", first));+assert.equal(invoke("prepared", JSON.stringify({ ...ticket, pdf: first })), first.path);+invoke("source", first, first, viewer);+for (const id of ["run-one", "run-two"]) {+ invoke("begin");+ invoke("result", file(`${id}/preview.pdf`), first, viewer, id);+ assert.equal(state.frame, originalFrame);+}+assert.deepEqual(activations.map(values => [...values]), [["run-one", "local-one"], ["run-two", "local-one"]]);+assert.equal(disposed, 0);+invoke("prepared", JSON.stringify({ ...ticket, error: "copy failed" }));+assert.equal(host.children[0], originalFrame);+invoke("clear");+assert.equal(disposed, 1);+assert.equal(revoked, 1);+assert.equal(invoke("prepared", JSON.stringify({ ...ticket, pdf: first })).value, undefined);+assert.equal(state.frame, null);-const image = file("photo.png");-invoke("reset", image);-assert.equal(invoke("source", null, image, viewer).value, "");+// 图片上传后就加载准备好的 PDF,转换结果不得再次创建查看器。+const picture = file("photo.png");+state.local({ name: "photo.png" }, "image-one");+assert.equal(state.frame, null);+state.bind(picture, "image-one");+invoke("reset", picture);+const imageTicket = JSON.parse(invoke("prepare", picture));+invoke("prepared", JSON.stringify({ ...imageTicket, pdf: file("sources/photo.pdf") }));+const imageFrame = state.frame;+assert.ok(imageFrame);invoke("begin");-assert.equal(invoke("result", origin, image, viewer, "image-run").visible, true);+invoke("result", file("sources/photo.pdf"), picture, viewer, "image-run");+assert.equal(state.frame, imageFrame);+state.local({ name: "photo.png" }, "image-two");+assert.equal(state.bind(picture, "image-one"), false);+invoke("prepared", JSON.stringify({ ...imageTicket, pdf: file("old.pdf") }));+assert.equal(state.frame, null);++// 示例及 Windows 路径继续正确编码,并拒绝跨源文件。+invoke("clear");+invoke("reset", first);+invoke("source", first, first, viewer);+let params = new URLSearchParams(new URL(state.frame.src).hash.slice(1));+assert.equal(decodeURIComponent(new URL(params.get("file")).pathname), `/prefix/gradio_api/file=${first.path}`);const win = { path: "C:\\cache\\中文 #1.pdf", url: "/prefix/gradio_api/file=C:/cache/中文 #1.pdf" };invoke("reset", win);-const windowsUrl = new URL(new URLSearchParams(iframe(invoke("source", win, win, viewer)).hash.slice(1)).get("file"));-assert.equal(decodeURIComponent(windowsUrl.pathname), "/prefix/gradio_api/file=C:/cache/中文 #1.pdf");-const external = { path: first.path, url: `https://other.test/gradio_api/file=${first.path}` };+invoke("source", win, win, viewer);+params = new URLSearchParams(new URL(state.frame.src).hash.slice(1));+assert.equal(decodeURIComponent(new URL(params.get("file")).pathname), "/prefix/gradio_api/file=C:/cache/中文 #1.pdf");+const external = { path: "/cache/external.pdf", url: "https://other.test/gradio_api/file=/cache/external.pdf" };invoke("reset", external);-assert.ok(invoke("source", external, external, viewer).value.includes('role="alert"'));-console.log("PDF preview lifecycle and URL checks passed");+invoke("source", external, external, viewer);+assert.equal(state.frame, null);+assert.equal(host.children[0].attributes.role, "alert");+events.pagehide();+console.log("Persistent PDF, local upload identity, image preparation and URL checks passed");diff --git a/tests/unittest/test_kit_gradio_pdf_preview.py b/tests/unittest/test_kit_gradio_pdf_preview.pyindex 987f11e7..f9d3760e 100644--- a/tests/unittest/test_kit_gradio_pdf_preview.py+++ b/tests/unittest/test_kit_gradio_pdf_preview.py@@ -40,7 +40,7 @@ def test_pdf_preview_transport_and_success_events(tmp_path: Path) -> None:assert not any(type(block).__module__.startswith("gradio_pdf") for block in demo.blocks.values())viewer = next(block for block in demo.blocks.values() if "mineru-kit-pdf-preview" in (block.elem_classes or []))assert isinstance(viewer, gr.HTML) and viewer.visible is True- assert ':not(:has(.mineru-pdf-frame, [role="alert"]))' in demo._mineru_kit_css+ assert ':not(:has(.mineru-pdf-frame, [role="alert"], [role="status"]))' in demo._mineru_kit_cssfor event in (source, conversion):previews = [item for item in demo.config["dependencies"] if item.get("trigger_after") == event._id]assert len(previews) == 1diff --git a/tests/unittest/test_kit_gradio_sources.py b/tests/unittest/test_kit_gradio_sources.pynew file mode 100644index 00000000..d9b5fbd4--- /dev/null+++ b/tests/unittest/test_kit_gradio_sources.py@@ -0,0 +1,263 @@+"""上传级输入准备、复用、清理及无源 PDF 素材消费的回归。"""++from __future__ import annotations++import asyncio+import subprocess+import sys+from pathlib import Path+from unittest.mock import Mock++import pytest+from PIL import Image+from docvortex.document.pdf import PDFDocument++from mineru.kit.gradio.document_io import LocalGradioDocumentIO+from mineru.kit.gradio.sources import PreparedSource, SessionSources, prepare_source+from mineru.kit.gradio.artifacts import persist_parse_result+from mineru.parser.base import ParseResult+from test_kit_gradio import _middle_json, _pdf_bytes+++def test_pdf_preparation_preserves_bytes_and_image_has_one_pdf(tmp_path: Path) -> None:+ """PDF 原字节保存,图片预览与解析使用同一文件并保留原始类型。"""+ pdf = tmp_path / "中文 #?.pdf"+ pdf.write_bytes(_pdf_bytes(3))+ prepared = prepare_source(pdf, source_id="a" * 32, output_root=tmp_path)+ assert prepared.source_path.read_bytes() == pdf.read_bytes()+ assert prepared.parse_path == prepared.preview_pdf_path == prepared.source_path+ assert not list(prepared.root.glob("origin.pdf"))+ image = tmp_path / "photo.png"+ Image.new("RGBA", (40, 60), (255, 0, 0, 128)).save(image)+ prepared = prepare_source(image, source_id="b" * 32, output_root=tmp_path)+ assert prepared.file_suffix == "png"+ assert prepared.preview_pdf_path == prepared.parse_path != prepared.source_path+ assert len(list(prepared.root.glob("*.pdf"))) == 1+ assert PreparedSource.from_state(prepared.as_state(), source_root=tmp_path / "gradio/sources") == prepared+++def test_shared_preparation_and_active_lease_cleanup(tmp_path: Path) -> None:+ """并发准备只执行一次,切换会话不能提前删除正在解析的文件。"""+ image = tmp_path / "one.png"+ Image.new("RGB", (20, 30), "red").save(image)+ io = LocalGradioDocumentIO()+ original = io.prepare_source+ io.prepare_source = Mock(wraps=original)++ async def scenario() -> None:+ """真实生成 PDF 并交错持有、失效和释放租期。"""+ sources = SessionSources(io, tmp_path)+ first, second = await asyncio.gather(*(sources.prepare("s", image, "a" * 32, 1) for _ in range(2)))+ assert first == second and io.prepare_source.call_count == 1+ acquired, lease = await sources.acquire("s", image)+ assert acquired == first and io.prepare_source.call_count == 1+ await sources.retire("s", revision=2)+ assert first.root.is_dir()+ await sources.release(lease)+ assert not first.root.exists()+ with pytest.raises(ValueError, match="expired"):+ await sources.prepare("s", image, "b" * 32, 1)++ asyncio.run(scenario())++[email protected]("mode,orientation", [("RGB", 6), ("CMYK", 1), ("L", 1)])+def test_image_preparation_keeps_public_conversion_rules(tmp_path: Path, mode: str, orientation: int) -> None:+ """EXIF 转正、CMYK 和灰度输入都由公共转换实现生成单页 PDF。"""+ source = tmp_path / "photo.jpg"+ exif = Image.Exif()+ exif[274] = orientation+ with Image.new(mode, (40, 60)) as image:+ image.save(source, exif=exif)+ prepared = prepare_source(source, source_id="c" * 32, output_root=tmp_path)+ with PDFDocument(prepared.parse_path.read_bytes()) as document:+ assert document.page_count == 1+ width, height = document.page_size(0)+ assert width / height == pytest.approx(1.5 if orientation == 6 else 2 / 3, rel=0.001)+++def test_repeated_image_conversion_reuses_prepared_pdf_bytes(tmp_path: Path) -> None:+ """上传准备、两次解析和预览共用一份 PDF,原图身份继续禁止图片选页。"""+ from types import SimpleNamespace+ from unittest.mock import AsyncMock++ from mineru.kit.gradio.conversion import ConversionInput, ConversionRun, ConversionSuccess+ from mineru.kit.gradio.conversion_service import ConversionService++ image = tmp_path / "photo.png"+ Image.new("RGB", (20, 30), "red").save(image)+ io = LocalGradioDocumentIO()+ io.prepare_source = Mock(wraps=io.prepare_source)+ client = SimpleNamespace(parse_file=AsyncMock(return_value=ParseResult(middle_json=_middle_json())))++ async def scenario() -> None:+ """完整执行服务回调,比较实际交给解析客户端的路径和字节。"""+ service = ConversionService(+ client,+ tier_choices=("basic",),+ output_root=tmp_path,+ max_pages=1,+ slot=asyncio.Semaphore(1),+ document_io=io,+ )+ prepared = await service.sources.prepare("session", image, "a" * 32, 1)+ before = prepared.parse_path.read_bytes()+ for identity in ("first", "second"):+ run = ConversionRun(identity)+ outcome = await service.execute(+ run,+ ConversionInput(str(image), 0, "5,2", True, "session", prepared.source_id),+ public_base_url="http://test.local",+ )+ assert isinstance(outcome, ConversionSuccess)+ assert outcome.output.preview.pdf_path == prepared.preview_pdf_path+ assert outcome.output.preview.image_path is None+ assert io.prepare_source.call_count == 1+ assert client.parse_file.await_count == 2+ for call in client.parse_file.await_args_list:+ assert call.args[0] == prepared.preview_pdf_path+ assert call.args[0].read_bytes() == before+ assert call.kwargs["page_range"] == ""+ assert call.kwargs["ocr_mode"] == "auto"++ asyncio.run(scenario())+++def test_successful_result_retains_source_but_failed_prepare_can_retry(tmp_path: Path) -> None:+ """成功结果引用的输入保留;失败准备清理目录且允许新修订重试。"""+ image = tmp_path / "bad.png"+ image.write_bytes(b"invalid")++ async def scenario() -> None:+ """生成失败不泄漏半成品目录,成功后的清除不破坏已有文件输出。"""+ sources = SessionSources(LocalGradioDocumentIO(), tmp_path)+ with pytest.raises(Exception):+ await sources.prepare("s", image, "a" * 32, 1)+ assert not (tmp_path / "gradio/sources" / ("a" * 32)).exists()+ Image.new("RGB", (20, 30), "blue").save(image)+ prepared = await sources.prepare("s", image, "b" * 32, 2)+ _, lease = await sources.acquire("s", image)+ await sources.release(lease, retain=True)+ await sources.retire("s")+ assert prepared.parse_path.is_file()++ asyncio.run(scenario())+++def test_prepared_source_rejects_path_escape(tmp_path: Path) -> None:+ """共享源目录只能包含本次输入文件,不能扩大为任意 output root 路径。"""+ pdf = tmp_path / "source.pdf"+ pdf.write_bytes(_pdf_bytes())+ prepared = prepare_source(pdf, source_id="a" * 32, output_root=tmp_path)+ state = prepared.as_state()+ state["parse_path"] = str(tmp_path / "another.pdf")+ with pytest.raises(ValueError, match="escapes"):+ PreparedSource.from_state(state, source_root=tmp_path / "gradio/sources")+++def test_materialization_never_opens_pdf_and_bbox_only_is_legal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """只有语义 bbox 的块合法,已有素材保存不允许打开或渲染任何源 PDF。"""+ forbidden = Mock(side_effect=AssertionError("WebUI materialization must not open PDF"))+ monkeypatch.setattr(PDFDocument, "__init__", forbidden)+ middle = _middle_json(page_indices=(4, 8))+ middle.pages[1].blocks[1].content[0].image_base64 = None+ result = persist_parse_result(+ ParseResult(middle_json=middle), tmp_path / "unavailable.pdf", output_root=tmp_path, page_range="5,9"+ )+ forbidden.assert_not_called()+ assert result.initial_page_idx == 4+ assert len(list((result.root / "images").iterdir())) == 1+ assert not list(result.root.glob("*.pdf"))+ assert middle.pages[0].blocks[1].content[0].image_base64 is not None+++def test_materialization_reports_invalid_payload_and_missing_file(tmp_path: Path) -> None:+ """实际声明的素材必须存在且有效,不借助 bbox 掩盖缺失或损坏。"""+ middle = _middle_json()+ body = middle.pages[0].blocks[1].content[0]+ body.image_base64 = "data:image/png;base64,aW52YWxpZA=="+ with pytest.raises(ValueError):+ persist_parse_result(ParseResult(middle_json=middle), tmp_path / "source.pdf", output_root=tmp_path, page_range="")+ body.image_base64 = None+ body.image_path = "images/missing.png"+ with pytest.raises(FileNotFoundError):+ persist_parse_result(ParseResult(middle_json=middle), tmp_path / "source.pdf", output_root=tmp_path, page_range="")+++def test_new_source_ready_does_not_wait_for_retired_preparation(tmp_path: Path) -> None:+ """旧图片准备未退出时,新 PDF 仍可就绪,旧目录在线程结束后清理。"""+ import threading++ started = threading.Event()+ finish = threading.Event()+ source = tmp_path / "source.pdf"+ source.write_bytes(_pdf_bytes())+ io = LocalGradioDocumentIO()+ original = io.prepare_source++ def delayed(path: Path, *, source_id: str, output_root: Path) -> PreparedSource:+ """只阻塞第一份准备,模拟快速替换大图片的场景。"""+ if source_id == "a" * 32:+ started.set()+ assert finish.wait(5)+ return original(path, source_id=source_id, output_root=output_root)++ io.prepare_source = delayed++ async def scenario() -> None:+ """新请求不依赖旧准备退出,失效回执也不能重新成为当前输入。"""+ registry = SessionSources(io, tmp_path)+ old = asyncio.create_task(registry.prepare("s", source, "a" * 32, 1))+ await asyncio.to_thread(started.wait, 2)+ try:+ current = await asyncio.wait_for(registry.prepare("s", source, "b" * 32, 2), timeout=1)+ assert current.source_id == "b" * 32 and not old.done()+ finally:+ finish.set()+ with pytest.raises(ValueError, match="expired"):+ await old+ await asyncio.gather(*registry.cleanups)+ assert not (tmp_path / "gradio/sources" / ("a" * 32)).exists()+ await registry.retire("s")++ asyncio.run(scenario())+++def test_expired_conversion_cannot_replace_current_prepared_source(tmp_path: Path) -> None:+ """旧转换请求即使晚于新上传到达,也不能重新准备旧文件并覆盖当前身份。"""+ source = tmp_path / "one.pdf"+ source.write_bytes(_pdf_bytes())++ async def scenario() -> None:+ """过期 source_id 在取得解析租期之前失败,当前记录保持不变。"""+ registry = SessionSources(LocalGradioDocumentIO(), tmp_path)+ await registry.prepare("s", source, "a" * 32, 1)+ current = await registry.prepare("s", source, "b" * 32, 2)+ with pytest.raises(ValueError, match="expired"):+ await registry.acquire("s", source, source_id="a" * 32)+ assert registry.current["s"][0] == current.source_id+ await registry.retire("s")+ await asyncio.gather(*registry.cleanups)++ asyncio.run(scenario())+++def test_cold_image_preparation_and_pdf_metadata_import_together(tmp_path: Path) -> None:+ """冷进程首次准备图片与读取 PDF 页数时保持导入锁顺序一致。"""+ Image.new("RGB", (20, 30), "red").save(tmp_path / "image.png")+ (tmp_path / "source.pdf").write_bytes(_pdf_bytes())+ code = """+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+import sys+from mineru.kit.gradio.sources import prepare_source+from mineru.kit.gradio.page_range import pdf_page_metadata+root = Path(sys.argv[1])+with ThreadPoolExecutor(2) as pool:+ image = pool.submit(prepare_source, root / 'image.png', source_id='a' * 32, output_root=root)+ metadata = pool.submit(pdf_page_metadata, str(root / 'source.pdf'))+ assert image.result().parse_path.is_file()+ assert metadata.result()['page_count'] == 1+"""+ completed = subprocess.run([sys.executable, "-c", code, str(tmp_path)], capture_output=True, text=True, timeout=20)+ assert completed.returncode == 0, completed.stderrdiff --git a/tests/unittest/test_kit_gradio_status_timer.cjs b/tests/unittest/test_kit_gradio_status_timer.cjsindex 27070095..018683b9 100644--- a/tests/unittest/test_kit_gradio_status_timer.cjs+++ b/tests/unittest/test_kit_gradio_status_timer.cjs@@ -264,7 +264,8 @@ const appContext = vm.createContext({vm.runInContext(resource("gradio_app.js").replace("__MINERU_I18N__", "stubI18n").replace("__MINERU_STATUS_TIMER__", "stubTimer")- .replace("__MINERU_TRACE__", "() => {}"), appContext)();+ .replace("__MINERU_TRACE__", "() => {}")+ .replace("__MINERU_PDF_PREVIEW__", "() => {}"), appContext)();while (frames.length) frames.shift()();const beforeRefresh = localizations;observer([externalMutation]);diff --git a/tests/unittest/test_kit_gradio_trace.cjs b/tests/unittest/test_kit_gradio_trace.cjsindex 100c173f..4cba0ae4 100644--- a/tests/unittest/test_kit_gradio_trace.cjs+++ b/tests/unittest/test_kit_gradio_trace.cjs@@ -21,7 +21,7 @@ const script = fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradvm.runInNewContext(`(${script})()`, { window, document, location });// 统一构造来源消息,允许测试替换发送者与文档身份。const emit = (source, data, origin = "null") =>- handlers.message({ source: source.contentWindow, origin, data: { channel: "mineru-trace", documentId: "one", ...data } });+ handlers.message({ source: source.contentWindow, origin, data: { channel: "mineru-trace", sourceId: "source-one", documentId: "one", ...data } });const entry = {id: "p2-b1",sources: [@@ -31,10 +31,14 @@ const entry = {],depth: 0};-window.__mineruTrace.activate("one");+// 正文先加载时首次 ready 会被丢弃,激活必须主动请求同一产物的快照。+emit(html, { type: "ready", entries: [entry], initialPageIdx: 2 });+window.__mineruTrace.activate("one", "source-one");+assert.equal(delivered.at(-1).name, "html");+assert.equal(delivered.at(-1).message.type, "request-ready");emit(pdf, { type: "ready" }, location.origin);const layoutRegions = [{ page_idx: 5, block_index: 2, child_path: [], type: "text", index: 2, bbox: [0.1, 0.1, 0.8, 0.2], color: [0.6, 0.05, 0.3] }];-emit(html, { type: "ready", entries: [entry], pageIndices: [2, 5], layoutRegions });+emit(html, { type: "ready", entries: [entry], initialPageIdx: 2, layoutRegions });assert.equal(delivered.at(-1).message.layoutRegions, layoutRegions);emit(html, { type: "select", id: entry.id });assert.equal(delivered.at(-1).message.pageIdx, 2);@@ -50,7 +54,7 @@ assert.equal(delivered.at(-2).message.sourceKey, samePageKey);assert.equal(delivered.at(-2).message.pageIdx, 5);assert.equal(delivered.at(-1).message.sourceKey, samePageKey);// 同一结果重复激活仍保留映射,可供重挂载的 PDF 查看器恢复。-window.__mineruTrace.activate("one");+window.__mineruTrace.activate("one", "source-one");emit(pdf, { type: "ready" }, location.origin);assert.equal(delivered.at(-1).message.entries.length, 1);assert.equal(delivered.at(-1).message.layoutRegions, layoutRegions);@@ -59,13 +63,13 @@ emit(frame("foreign"), { type: "select", id: entry.id });emit(pdf, { type: "select", id: entry.id }, "https://foreign.test");emit(html, { type: "select", id: "missing" });assert.equal(delivered.length, count);-window.__mineruTrace.activate("two");+window.__mineruTrace.activate("two", "source-one");const switched = delivered.length;-emit(html, { type: "ready", entries: [entry], pageIndices: [2, 5] });+emit(html, { type: "ready", entries: [entry], initialPageIdx: 2 });emit(pdf, { type: "select", id: entry.id }, location.origin);assert.equal(delivered.length, switched);emit(pdf, { type: "ready", documentId: "two" }, location.origin);-assert.equal(delivered.at(-1).message.layoutRegions.length, 0);+assert.equal(delivered.at(-1).message.type, "bind");window.__mineruTrace.reset();console.log("Trace identity, handshake and bidirectional routing passed");@@ -110,7 +114,7 @@ const checkHtmlNavigation = (};const source = fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_trace_html.js"), "utf8");vm.runInNewContext(`(${source})(${JSON.stringify({- pageLabels: ["Source page", "来源页"], documentId: "one", parentOrigin: configuredOrigin, pageIndices: [2, 5],+ pageLabels: ["Source page", "来源页"], documentId: "one", parentOrigin: configuredOrigin, initialPageIdx: 2,layoutRegions: [{ ...entry.sources[0], child_path: [0], color: [0.2, 0.4, 0.9] },{ ...entry.sources[1], color: [0.6, 0.05, 0.3] },@@ -118,13 +122,17 @@ const checkHtmlNavigation = (]})})`, context);assert.deepEqual(targetOrigins, [eventOrigin]);+ htmlHandlers.message({ source: htmlParent, origin: eventOrigin, data: {+ channel: "mineru-trace", documentId: "one", type: "request-ready"+ } });+ assert.deepEqual(targetOrigins, [eventOrigin, eventOrigin]);// 同一父窗口传来的不同来源消息仍须拒绝,避免规范化放宽来源边界。htmlHandlers.message({ source: htmlParent, origin: "https://foreign.test", data: {- channel: "mineru-trace", documentId: "one", type: "select", id: entry.id, pageIdx: 2, scroll: false+ channel: "mineru-trace", sourceId: "source-one", documentId: "one", type: "select", id: entry.id, pageIdx: 2, scroll: false} });assert.equal(navigation.hidden, true);htmlHandlers.message({ source: htmlParent, origin: eventOrigin, data: {- channel: "mineru-trace", documentId: "one", type: "select", id: entry.id, pageIdx: 2, scroll: false+ channel: "mineru-trace", sourceId: "source-one", documentId: "one", type: "select", id: entry.id, pageIdx: 2, scroll: false} });htmlHandlers.scroll();assert.equal(navigation.hidden, false);@@ -132,7 +140,7 @@ const checkHtmlNavigation = (assert.equal(selected.style["--trace-color"], "rgb(51 102 230)");assert.equal(navigation.style["--trace-color"], selected.style["--trace-color"]);htmlHandlers.message({ source: htmlParent, origin: eventOrigin, data: {- channel: "mineru-trace", documentId: "one", type: "select", id: entry.id,+ channel: "mineru-trace", sourceId: "source-one", documentId: "one", type: "select", id: entry.id,pageIdx: 5, sourceKey: samePageKey, scroll: false} });assert.equal(selected.style["--trace-color"], "rgb(0 153 26)");@@ -208,6 +216,7 @@ class TraceNode {const pdfHandlers = {};const pdfParent = { postMessage() {} };const scrolls = [];+const jumps = [];let boxRect = { left: 950, top: 800, width: 100, height: 80 };const pdfBox = { traceIds: [entry.id], getBoundingClientRect: () => boxRect };const container = {@@ -227,19 +236,28 @@ const pdfContext = {ResizeObserver: class { observe() {} },window: { addEventListener: (name, callback) => { pdfHandlers[name] = callback; } },viewer: {+ pagesCount: 6, currentScale: 1.75,getPageView: () => ({ div: { querySelector: () => ({ children: [pdfBox] }) } }),- getCachedPageViews: () => [], scrollPageIntoView() {}+ getCachedPageViews: () => [],+ // 记录实际页跳转,验证重复握手不移动用户位置或改变缩放。+ scrollPageIntoView({ pageNumber }) { jumps.push(pageNumber); }},eventBus: { on() {}, off() {} }};const pdfScript = fs.readFileSync(path.join(__dirname, "../../mineru/resources/pdf_preview/trace.mjs"), "utf8");vm.runInNewContext(`${pdfScript.replace("export function", "function")}-installTrace({ viewer, eventBus, container, documentId: "one", messages: {} });`, pdfContext);+installTrace({ viewer, eventBus, container, sourceId: "source-one", messages: {} });`, pdfContext);// 模拟已验证的父页面消息,复用生产 init/select 的完整分发路径。const emitPdf = data => pdfHandlers.message({ source: pdfParent, origin: location.origin, data: {- channel: "mineru-trace", documentId: "one", ...data+ channel: "mineru-trace", sourceId: "source-one", documentId: "one", ...data} });-emitPdf({ type: "init", entries: [entry], pageIndices: [2, 5] });+emitPdf({ type: "bind" });+emitPdf({ type: "init", entries: [entry], initialPageIdx: 2 });+assert.deepEqual(jumps, [3]);+emitPdf({ type: "bind" });+emitPdf({ type: "init", entries: [entry], initialPageIdx: 5 });+assert.deepEqual(jumps, [3]);+assert.equal(pdfContext.viewer.currentScale, 1.75);emitPdf({ type: "select", id: entry.id, pageIdx: 2, scroll: true });assert.equal(scrolls.at(-1).top, 800);assert.equal(scrolls.at(-1).left, 850);@@ -250,6 +268,15 @@ assert.ok(scrolls.at(-1).left <= 0);boxRect = { left: 950, top: 800, width: 700, height: 80 };emitPdf({ type: "select", id: entry.id, pageIdx: 2, scroll: true });assert.equal(scrolls.at(-1).left, 1034);+// 无版式框仍使用实际解析范围首跳;空页范围和 clear 不触发跳页。+emitPdf({ type: "bind", documentId: "two" });+emitPdf({ type: "init", documentId: "two", entries: [], initialPageIdx: 5 });+assert.equal(jumps.at(-1), 6);+const jumpCount = jumps.length;+emitPdf({ type: "clear", documentId: "two" });+emitPdf({ type: "bind", documentId: "three" });+emitPdf({ type: "init", documentId: "three", entries: [], initialPageIdx: null });+assert.equal(jumps.length, jumpCount);console.log("PDF source navigation handles horizontal zoom overflow");// 用同一入口挂载完整页面,覆盖跨栏后跨页的三段链及真实焦点优先级。@@ -265,7 +292,7 @@ Object.assign(mergeContainer, { clientLeft: 0, clientTop: 0, rect: { left: 100,const pageViews = [0, 1].map(index => {const div = new TraceNode();div.rect = { left: 100, top: 40 + index * 602, width: 500, height: 600 };- return { id: index + 1, div, pdfPage: {} };+ return { id: [3, 6][index], div, pdfPage: {} };});const mergeContext = {parent: pdfParent, location, AbortController,@@ -287,7 +314,8 @@ const mergeContext = {},container: mergeContainer,viewer: {- getPageView: index => pageViews[index], getCachedPageViews: () => pageViews,+ pagesCount: 6,+ getPageView: index => pageViews.find(page => page.id === index + 1), getCachedPageViews: () => pageViews,scrollPageIntoView() {}},eventBus: {@@ -297,10 +325,10 @@ const mergeContext = {messages: { trace_merged: "合并", trace_merged_description: "由 {count} 个原始内容块合并" }};vm.runInNewContext(`${pdfScript.replace("export function", "function")}-globalThis.disposeTrace = installTrace({ viewer, eventBus, container, documentId: "one", messages });`, mergeContext);+globalThis.disposeTrace = installTrace({ viewer, eventBus, container, sourceId: "source-one", messages });`, mergeContext);// 消息经过生产身份校验,避免测试绕过初始化和选择流程。const emitMerge = data => mergeHandlers.message({ source: pdfParent, origin: location.origin, data: {- channel: "mineru-trace", documentId: "one", ...data+ channel: "mineru-trace", sourceId: "source-one", documentId: "one", ...data} });// 一次刷新执行已排队的回调,并验证更新确实按帧合并。const flushConnections = () => {@@ -321,7 +349,8 @@ const single = { id: "single", depth: 0, sources: [{}] };const parentChain = { id: "parent", depth: 0, sources: chain.sources.map(source => ({ ...source, child_path: [] })) };const layoutRegionsForChain = chain.sources.map(source => ({ ...source, type: "text", index: 1, color: [0.6, 0.05, 0.3] }));-const mergeInit = { type: "init", entries: [parentChain, chain, single], pageIndices: [2, 5], layoutRegions: layoutRegionsForChain };+const mergeInit = { type: "init", entries: [parentChain, chain, single], initialPageIdx: 2, layoutRegions: layoutRegionsForChain };+emitMerge({ type: "bind" });emitMerge(mergeInit);flushConnections();const overlay = mergeBody.children[0];@@ -365,7 +394,7 @@ mergeEvents.updateviewarea();flushConnections();assert.equal(overlay.children.length, 1);pageViews[1].pdfPage = {};-mergeEvents.pagerendered({ pageNumber: 2 });+mergeEvents.pagerendered({ pageNumber: 6 });flushConnections();assert.equal(overlay.children.length, 2);// 重复来源不会多画线,几何无效的中间片段阻断两侧线段。diff --git a/tests/unittest/test_kit_gradio_trace.py b/tests/unittest/test_kit_gradio_trace.pyindex 3b6d13bf..f0147d68 100644--- a/tests/unittest/test_kit_gradio_trace.py+++ b/tests/unittest/test_kit_gradio_trace.py@@ -19,7 +19,7 @@ def test_pdf_trace_preview_and_public_render(tmp_path: Path) -> None:source.write_bytes(_pdf_bytes())middle = _middle_json(with_image=False)artifacts = persist_parse_result(ParseResult(middle_json=middle), source, output_root=tmp_path, page_range="")- assert _prepare_preview("pdf", artifacts).pdf_path == artifacts.origin_pdf_path+ assert _prepare_preview("pdf", artifacts).pdf_path is Noneassert not (artifacts.root / "layout.pdf").exists()preview = render_html_preview(artifacts, public_base_url="http://testserver")frame = BeautifulSoup(preview, "html.parser").iframe@@ -27,7 +27,8 @@ def test_pdf_trace_preview_and_public_render(tmp_path: Path) -> None:document = BeautifulSoup(frame["srcdoc"], "html.parser")assert document.select_one("[data-docvortex-trace-id]")assert artifacts.root.name in document.get_text() or artifacts.root.name in str(document)- assert "pageIndices" in str(document)+ assert "initialPageIdx" in str(document)+ assert "pageIndices" not in str(document)trace_style = next(style.string for style in document.select("style") if ".mineru-trace-pages {" in (style.string or ""))assert "max-height: calc(100vh - var(--mineru-preview-offset, 8px) - 8px)" in trace_styleassert "overflow-y: auto" in trace_stylediff --git a/tests/unittest/test_kit_gradio_upload.cjs b/tests/unittest/test_kit_gradio_upload.cjsnew file mode 100644index 00000000..234b9e09--- /dev/null+++ b/tests/unittest/test_kit_gradio_upload.cjs@@ -0,0 +1,65 @@+// 通过真实上传控件脚本重放选择、拖放、粘贴及迟到上传,不模拟框架内部组件状态。+const assert = require("node:assert/strict");+const fs = require("node:fs");+const vm = require("node:vm");+const crypto = require("node:crypto").webcrypto;+const script = fs.readFileSync(require("node:path").join(__dirname, "../../mineru/resources/gradio_upload.js"), "utf8");+const handlers = {};+const documentHandlers = {};+const input = { value: "", files: [] };+const label = { textContent: "" };+const status = { textContent: "", setAttribute() {} };+const retry = { hidden: true, addEventListener(name, handler) { this[name] = handler; } };+const nodes = { 'input[type="file"]': input, '.mineru-upload-label': label, '.mineru-upload-status': status, '.mineru-upload-retry': retry };+const element = { querySelector: selector => nodes[selector], addEventListener: (name, handler) => handlers[name] = handler };+const uploaded = [];+const pending = [];+const values = [];+const window = {+ addEventListener() {},+ __mineruI18n: { text: value => value },+ __mineruPdfPreview: {+ sourceId: "",+ local(file, id) { this.sourceId = id; },+ bind(file, id) { return id === this.sourceId; }+ }+};+const document = { addEventListener: (name, handler) => documentHandlers[name] = handler, removeEventListener() {} };+const props = { set value(value) { values.push(value); } };+// 只替换传输边界,调用方仍执行生产异步闭包和身份校验。+const upload = file => { uploaded.push(file); return new Promise(resolve => pending.push(resolve)); };+vm.runInNewContext(`(${script})`, { window, document, crypto, setTimeout, File })({element, props, upload, accepted:[".pdf", ".png"], imageExtensions:["png"]});+// 等待控件显式安排的下一次提交,不依赖模拟时钟或固定上传耗时。+const tick = () => new Promise(resolve => setTimeout(resolve, 10));+(async () => {+ const first = new File(["first"], "same.pdf");+ const second = new File(["second"], "same.pdf");+ input.files = [first]; handlers.change({target:input});+ const firstId = window.__mineruPdfPreview.sourceId;+ handlers.drop({preventDefault(){},dataTransfer:{files:[second]}});+ const secondId = window.__mineruPdfPreview.sourceId;+ assert.notEqual(firstId, secondId);+ pending[0]({path:"/old.pdf",url:"/old.pdf"});+ await tick();+ assert.equal(values.some(value=>value.includes("/old.pdf")), false);+ pending[1]({path:"/new.pdf",url:"/new.pdf"});+ await tick();+ const receipt = values.at(-1);+ assert.equal(window.__mineruUpload.bridge(receipt).path,"/new.pdf");+ assert.equal(window.__mineruUpload.bridge(receipt).__type__,"update");+ window.__mineruUpload.prepared("prepare failed");+ assert.equal(retry.hidden,false);+ retry.click();+ await tick();+ assert.equal(uploaded.length,2);+ assert.equal(JSON.parse(values.at(-1)).file.path,"/new.pdf");+ assert.equal(window.__mineruUpload.bridge(receipt).__type__,"update");+ documentHandlers.paste({preventDefault(){},clipboardData:{files:[],items:[{getAsFile:()=>new File(["png"],"clipboard",{type:"image/png"})}]}});+ assert.ok(uploaded.at(-1).name.endsWith(".png"));+ const before = values.length;+ window.__mineruUpload.invalidate();+ pending[2]({path:"/late.png",url:"/late.png"});+ await tick();+ assert.equal(values.length,before);+ console.log("Upload identity, duplicate events, preparation retry, paste and clear passed");+})().catch(error=>{console.error(error);process.exitCode=1;});diff --git a/tests/unittest/test_kit_gradio_upload.py b/tests/unittest/test_kit_gradio_upload.pynew file mode 100644index 00000000..1ab12ed0--- /dev/null+++ b/tests/unittest/test_kit_gradio_upload.py@@ -0,0 +1,12 @@+"""自有上传入口只通过公共传输接口工作,并隔离迟到回执。"""++from pathlib import Path+import shutil+import subprocess+++def test_upload_frontend_lifecycle() -> None:+ """运行真实脚本验证同名替换、准备重试、粘贴及清除。"""+ node = shutil.which("node")+ assert node is not None+ subprocess.run([node, str(Path(__file__).with_suffix(".cjs"))], check=True)diff --git a/tests/unittest/test_parse_result_assets.py b/tests/unittest/test_parse_result_assets.pyindex 68ad9e36..0d551827 100644--- a/tests/unittest/test_parse_result_assets.py+++ b/tests/unittest/test_parse_result_assets.py@@ -160,7 +160,8 @@ def test_gradio_pdf_uses_packaged_images_without_cropping("""完整素材不允许调用任何源 PDF 裁图兜底。"""raise AssertionError("Packaged images must not be recropped")- monkeypatch.setattr(gradio_artifacts._ImageContext, "crop_for_block", reject_crop)+ monkeypatch.setattr(PDFDocument, "crop_image", reject_crop)+ monkeypatch.setattr(PDFDocument, "render_page", reject_crop)artifacts = gradio_artifacts.persist_parse_result(restored,source,@@ -173,8 +174,7 @@ def test_gradio_pdf_uses_packaged_images_without_cropping(inline_path = BeautifulSoup(body.content, "html.parser").img["src"]assert (artifacts.root / inline_path).read_bytes() == imagesource.unlink()- artifacts.source_path.unlink()- artifacts.origin_pdf_path.unlink()+ monkeypatch.undo()downloaded = Path(gradio_artifacts.render_download(artifacts.as_state(), "pdf"))with PDFDocument(render_pdf(result.middle_json, layout=PdfLayout.ORIGINAL)) as expected:with PDFDocument(downloaded.read_bytes()) as actual:@@ -227,7 +227,7 @@ def test_client_rejects_missing_or_unsafe_markup_asset(source: str) -> None:def test_client_preserves_markup_attributes_and_code_literals() -> None:"""带空格、实体、不同引号的 src 可恢复,代码中相同 HTML 字面量不变。"""- data = b"image-bytes"+ _, data, _ = _result()path = "images/a b&c.png"source = "images/a%20b&c.png"value = {@@ -269,3 +269,17 @@ def test_save_and_restore_leave_code_image_literals_unchanged() -> None:restored = api_client._parse_result_from_zip_bytes(packed, include_images=True)assert restored.pages[1].blocks[0].content[0].content == literalassert result.pages[1].blocks[0].content[0].content == literal+++def test_client_reports_corrupt_image_at_restore_boundary() -> None:+ """缺失引用之外,损坏的实际 sidecar 也必须在恢复阶段明确失败。"""+ result, _, _ = _result()+ original = _entries(build_default_zip(result))+ name = next(name for name in original if name.startswith("images/"))+ original[name] = b"corrupt image bytes"+ output = BytesIO()+ with zipfile.ZipFile(output, "w") as archive:+ for name, data in original.items():+ archive.writestr(name, data)+ with pytest.raises(api_client._V1APIError, match="Invalid image sidecar"):+ api_client._parse_result_from_zip_bytes(output.getvalue(), include_images=True)diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex f981455e..d2f74de1 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -7,6 +7,7 @@ import jsonimport threadingfrom io import BytesIOfrom pathlib import Path+from types import SimpleNamespacefrom typing import get_args, get_type_hintsfrom unittest.mock import MagicMock@@ -199,8 +200,8 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:page_image.close()-def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:- """验证像素框会裁到页面范围,无效框会跳过载荷写入且不影响其他块。"""+def test_visual_block_crop_clips_page_boundary_and_reports_invalid_bbox() -> None:+ """有效任务正常裁图,已选素材的无效框必须在生产边界报告。"""page_image = Image.new("L", (100, 80), 128)clipped_block = {"type": BlockType.CHART,@@ -213,10 +214,8 @@ def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:"angle": 0,}- visuals._attach_visual_block_images(- [[clipped_block, invalid_block]],- [{"img_pil": page_image}],- )+ with pytest.raises(ValueError, match="PDF visual asset generation failed"):+ visuals._attach_visual_block_images([[clipped_block, invalid_block]], [{"img_pil": page_image}])crop_image = _decode_jpeg_data_uri(clipped_block["image_base64"])try:@@ -1215,7 +1214,7 @@ def test_doc_analyze_office_returns_model_json_without_pdf_processing(monkeypatch.setattr(window, "load_images_from_pdf_bytes_range", image_loader)monkeypatch.setattr(window, "_attach_visual_block_images", visual_image_attacher)monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", model_list_normalizer)- monkeypatch.setattr(office.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(office, "time", SimpleNamespace(perf_counter=fake_perf_counter))middle_json, model_json = analyze.doc_analyze(b"office-bytes",@@ -1479,7 +1478,7 @@ def test_pdf_infer_timer_excludes_hybrid_vlm_initialization_and_cleanup(monkeypatch.setattr(pipeline, "PDFDocument", MagicMock(return_value=fake_document))monkeypatch.setattr(hybrid_runtime, "HybridLocalModelContextSingleton", MagicMock(return_value=hybrid_singleton))monkeypatch.setattr(pipeline, "get_vlm_predictor", fake_vlm_get_model)- monkeypatch.setattr(pipeline.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(pipeline, "time", SimpleNamespace(perf_counter=fake_perf_counter))monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", fake_normalize_model_list)monkeypatch.setattr(pipeline, "clean_memory", fake_clean_memory)@@ -1751,12 +1750,23 @@ def test_doc_analyze_flash_returns_complete_model_json_and_typed_middle_json(monoriginal_attach_visual_block_images(*args, **kwargs) # type: ignore[arg-type]def fake_render_crops(- pdf_bytes, prepared_pages, start_page_id, end_page_id, timeout=None, threads=None, *, session=None- ):+ pdf_bytes: bytes,+ prepared_pages: list[list[tuple[int, dict[str, object]]]],+ start_page_id: int,+ end_page_id: int,+ timeout: float | None = None,+ threads: int | None = None,+ *,+ session: object | None = None,+ ) -> list[list[tuple[int, object]]]:"""在当前裁图进程边界提供固定页图,保留真实编码、窗口顺序与释放断言。"""page_images = fake_load_images_for_window(- pdf_bytes, start_page_id=start_page_id, end_page_id=end_page_id,- image_type="pil_img", timeout=timeout, threads=threads,+ pdf_bytes,+ start_page_id=start_page_id,+ end_page_id=end_page_id,+ image_type="pil_img",+ timeout=timeout,+ threads=threads,)try:tracked_attach_visual_block_images(prepared_pages, page_images, start_page_id)@@ -1786,7 +1796,7 @@ def test_doc_analyze_flash_returns_complete_model_json_and_typed_middle_json(monmonkeypatch.setattr("docvortex.document.pdf.images._load_visual_crops_from_pdf_bytes_range", fake_render_crops)monkeypatch.setattr(visuals, "_attach_prepared_visual_block_images", tracked_attach_visual_block_images)monkeypatch.setattr(pipeline, "_normalize_pdf_model_list", tracked_normalize_model_list)- monkeypatch.setattr(pipeline.time, "perf_counter", fake_perf_counter)+ monkeypatch.setattr(pipeline, "time", SimpleNamespace(perf_counter=fake_perf_counter))monkeypatch.setattr(flash_model, "PdfModel", MagicMock(return_value=fake_pdf_model))middle_json, model_json = analyze.doc_analyze(