Skip to content

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

Enhance image handling in API client: support HTML image references and externalize assets during save

myhloli53a8bc20c8ff
diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.md
index b8aea60b..78ea4d7c 100644
--- a/docs/en/reference/output_files.md
+++ b/docs/en/reference/output_files.md
@@ -76,7 +76,7 @@ and report `pdf_title_geometry_conflict`; unavailable expansion clearance report
`pdf_title_clearance_unavailable`. Only rendering context changes, with no input,
asset, protocol or public-option changes.
-Requires `docvortex>=0.4.2,<1`. DocVortex clears native TXT PDF display equation
+Requires `docvortex>=0.4.3,<1`. DocVortex clears native TXT PDF display equation
`content` once when producing model output; MinerU Flash TXT uses that output.
Flash OCR already leaves display equation content empty. MinerU does not clear
equation content again. Both Flash paths retain the bbox, orientation, image and
@@ -186,7 +186,7 @@ Round-trip current results with `ParseResult.from_json(result.to_json())`. Legac
## Saved files, ZIP, and assets
-`ParseResult.save(writer)` writes `markdown.md`, `middle_json.json`, and `structured_content.json`, plus `model_output.json` when raw model output exists. `mineru-kit parse --format zip` packages these results.
+`ParseResult.save(writer)` materializes images on a document copy and writes `markdown.md`, `middle_json.json`, `structured_content.json`, and `images/`, plus `model_output.json` when raw model output exists. Self-hosted V1 API ZIP output and `mineru-kit parse --format zip` share this save path. All three consumer formats reference the same assets; image bytes, source page indices, block indices, and rotation metadata are preserved.
```python
from mineru.parser.writer import FileBasedDataWriter
@@ -194,6 +194,6 @@ from mineru.parser.writer import FileBasedDataWriter
result.save(FileBasedDataWriter("output"))
```
-Assets may be embedded or referenced by image paths, depending on the source and output entrypoint. PDF `ParseResult.to_dict()` omits block `image_base64`; saving intermediate JSON alone does not preserve every external asset. Download and retain matching assets when consuming API output references. Do not rely on a closed PDF object or the original file for later rendering.
+PDF `ParseResult.to_dict()` / `to_json()` still omit block `image_base64`, so standalone structural JSON is not a complete result package. `save(writer)` neither recrops nor rotates images and rejects unresolved asset references before writing, without reading the working directory or fetching network resources. With `include_images=True`, the API client restores direct images and images embedded in visual HTML from the ZIP. Gradio reuses those assets; PDF export needs only MiddleJson and the images, without the source PDF or ModelJson. `include_images=False` retains structural-only reading. Regenerate historical incomplete or incorrectly materialized results.
The WebUI layout PDF is a debugging artifact used to preview detections when available; otherwise the UI previews the original/cropped PDF. It serves a different purpose from `RenderFormat.PDF` above.
diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.md
index bc0aa00b..d87fd84a 100644
--- a/docs/zh/reference/output_files.md
+++ b/docs/zh/reference/output_files.md
@@ -47,7 +47,7 @@ pdf_bytes = render(result.middle_json, RenderFormat.PDF,
`pdf_title_layout_expanded` 记录扩展;`pdf_layout_font_exception` 记录局部正文较大或空间不足的调整原因、参考/目标/最终字号、原框和绘制框。原始几何重叠时不扩大占用并报告 `pdf_title_geometry_conflict`;原始间距过紧、没有安全扩展区域时报告 `pdf_title_clearance_unavailable`。字号和绘制区域仅存在于渲染上下文,不修改 MiddleJson 或素材,不新增接口参数。
-使用 `docvortex>=0.4.2,<1`。DocVortex 在生产原生 TXT PDF 模型输出时将行间公式的 `content` 清空一次,MinerU Flash TXT 直接使用该输出;Flash OCR 原本不填充行间公式内容,MinerU 不再重复清空。两条 Flash 路径保留 bbox、方向、图片及检测到的编号区域,PDF、Markdown、HTML、DOCX、EPUB、LaTeX 沿用图片回退。行内公式、非 Flash tier 的公式文本不变。旧缓存不会自动改写,重新解析才获得新几何和空内容公式。
+使用 `docvortex>=0.4.3,<1`。DocVortex 在生产原生 TXT PDF 模型输出时将行间公式的 `content` 清空一次,MinerU Flash TXT 直接使用该输出;Flash OCR 原本不填充行间公式内容,MinerU 不再重复清空。两条 Flash 路径保留 bbox、方向、图片及检测到的编号区域,PDF、Markdown、HTML、DOCX、EPUB、LaTeX 沿用图片回退。行内公式、非 Flash tier 的公式文本不变。旧缓存不会自动改写,重新解析才获得新几何和空内容公式。
```python
from pathlib import Path
@@ -145,7 +145,7 @@ Path("report.html").write_text(html, encoding="utf-8")
## 文件保存、ZIP 与素材
-`ParseResult.save(writer)` 写出 `markdown.md`、`middle_json.json`、`structured_content.json`;有原始模型结果时还写出 `model_output.json`。`mineru-kit parse --format zip` 打包这一组结果。
+`ParseResult.save(writer)` 先在文档副本上物化图片,再写出 `markdown.md`、`middle_json.json`、`structured_content.json` 和 `images/` 素材;有原始模型结果时还写出 `model_output.json`。自部署 V1 API ZIP 与 `mineru-kit parse --format zip` 共用这一保存入口。包内三种消费格式引用同一组素材,图片字节、源页号、块索引及旋转元数据保持不变。
```python
from mineru.parser.writer import FileBasedDataWriter
@@ -153,6 +153,6 @@ from mineru.parser.writer import FileBasedDataWriter
result.save(FileBasedDataWriter("output"))
```
-素材可能以内嵌数据或图片路径表示,取决于来源与输出入口。PDF 的 `ParseResult.to_dict()` 会省略块中的 `image_base64`;只保存中间 JSON 不等于保存了所有外部素材。消费 API 结果时按产物引用下载并保留对应素材,不能依赖已关闭的 PDF 对象或原文件继续渲染。
+PDF 的 `ParseResult.to_dict()` / `to_json()` 仍省略块中的 `image_base64`,因此独立结构 JSON 不等于携带素材的结果包。`save(writer)` 不重新裁图或旋转图片;已有路径却缺少字节时在写出前失败,不隐式读取当前目录或网络。API 客户端设置 `include_images=True` 后,从 ZIP 恢复直接图片和视觉 HTML 内嵌图片;Gradio 复用这些素材,PDF 导出只需 MiddleJson 与图片文件,无需源 PDF 或 ModelJson。`include_images=False` 保持结构读取行为。历史错误结果包需要重新生成。
WebUI 显示的布局 PDF 是调试产物,可用时用于预览检测结果;不可用时使用原始/裁页 PDF 预览。它与上述 `RenderFormat.PDF` 是不同用途。
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.py
index 9da616e5..e6caf487 100644
--- a/mineru/parser/api_client.py
+++ b/mineru/parser/api_client.py
@@ -11,18 +11,20 @@ from __future__ import annotations
import asyncio
import base64
import hashlib
+import html
import io
import ipaddress
import json
import logging
import os
import random
+import re
import time
import zipfile
from collections.abc import Callable
from pathlib import Path
from typing import Any, Literal, cast
-from urllib.parse import urlparse
+from urllib.parse import unquote, urlparse
import httpx
from docvortex.assets import validate_image_sidecar_path
@@ -39,6 +41,13 @@ _TRANSPORT_MAX_ATTEMPTS = 3
_TRANSPORT_RETRY_BASE_DELAY_SECONDS = 0.25
_TRANSPORT_RETRY_MAX_DELAY_SECONDS = 2.0
+_VISUAL_HTML_BLOCK_TYPES = frozenset({"image_body", "table_body", "chart_body"})
+_HTML_IMAGE_SOURCE_RE = re.compile(
+ r"(?P<prefix><img\b(?:[^>\"']|\"[^\"]*\"|'[^']*')*?\s+src\s*=\s*)"
+ r"(?:(?P<quote>[\"'])(?P<quoted>.*?)(?P=quote)|(?P<unquoted>[^\s>]+))",
+ re.IGNORECASE | re.DOTALL,
+)
+
logger = logging.getLogger("mineru.api_client")
_RequestMethod = Literal["GET", "POST", "PUT"]
@@ -914,9 +923,14 @@ def _read_middle_json_from_zip(archive: zipfile.ZipFile) -> dict[str, Any]:
def _collect_image_paths_from_middle_json(value: Any) -> set[str]:
- """递归收集 middle_json 中引用的图片 sidecar 路径。"""
+ """收集直接图片与视觉 HTML 图片引用,保留代码正文中的图片字面量。"""
paths: set[str] = set()
if isinstance(value, dict):
+ content = value.get("content")
+ if value.get("type") in _VISUAL_HTML_BLOCK_TYPES and isinstance(content, str):
+ for match in _HTML_IMAGE_SOURCE_RE.finditer(content):
+ if (path := _markup_image_path(match)) is not None:
+ paths.add(path)
for key, item in value.items():
if key in {"image_path", "img_path"} and isinstance(item, str) and item:
paths.add(item)
@@ -928,6 +942,14 @@ def _collect_image_paths_from_middle_json(value: Any) -> set[str]:
return paths
+def _markup_image_path(match: re.Match[str]) -> str | None:
+ """解释 HTML 图片的相对素材路径,已有 data URI 和网络图片不读取。"""
+ source = html.unescape(match.group("quoted") if match.group("quote") else match.group("unquoted")).strip()
+ if not source or source.startswith("#") or urlparse(source).scheme.lower() in {"data", "http", "https"}:
+ return None
+ return validate_image_sidecar_path(unquote(source))
+
+
def _read_image_sidecars_from_zip(archive: zipfile.ZipFile, mid_json: dict[str, Any]) -> dict[str, bytes]:
"""从 zip 读取 middle_json 实际引用的图片 sidecar,并复用统一路径安全校验。"""
archive_names = set(archive.namelist())
@@ -941,6 +963,8 @@ def _read_image_sidecars_from_zip(archive: zipfile.ZipFile, mid_json: dict[str,
if candidate in archive_names:
images[safe_image_path] = archive.read(candidate)
break
+ else:
+ raise _V1APIError("invalid_image_sidecar", f"Missing image sidecar in ZIP: {safe_image_path}")
return images
@@ -970,13 +994,29 @@ def _inline_image_sidecars(mid_json: Any, images: dict[str, bytes]) -> None:
if isinstance(mid_json, dict):
image_path = mid_json.get("image_path") or mid_json.get("img_path")
if isinstance(image_path, str) and image_path:
- image_bytes = images.get(image_path)
- if image_bytes is None and not image_path.startswith("images/"):
- image_bytes = images.get(f"images/{image_path}")
+ safe_path = validate_image_sidecar_path(image_path)
+ image_bytes = images.get(safe_path)
+ if image_bytes is None and not safe_path.startswith("images/"):
+ image_bytes = images.get(f"images/{safe_path}")
if image_bytes is not None:
- mid_json["image_base64"] = _encode_image_data_uri(image_bytes, image_path)
+ mid_json["image_base64"] = _encode_image_data_uri(image_bytes, safe_path)
mid_json.pop("image_path", None)
mid_json.pop("img_path", None)
+ content = mid_json.get("content")
+ if mid_json.get("type") in _VISUAL_HTML_BLOCK_TYPES and isinstance(content, str):
+
+ def replace_source(match: re.Match[str]) -> str:
+ """只替换 src 的值,保留 HTML 属性、空白与引号。"""
+ path = _markup_image_path(match)
+ if path is None:
+ return match.group(0)
+ data_uri = _encode_image_data_uri(images[path], path)
+ group = "quoted" if match.group("quote") else "unquoted"
+ start, end = match.span(group)
+ original = match.group(0)
+ return original[: start - match.start()] + data_uri + original[end - match.start() :]
+
+ mid_json["content"] = _HTML_IMAGE_SOURCE_RE.sub(replace_source, content)
for value in mid_json.values():
_inline_image_sidecars(value, images)
elif isinstance(mid_json, list):
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 265ad72e..7cdd4e56 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -86,21 +86,28 @@ class ParseResult:
return render_structured_content(self.middle_json, asset_base_url=asset_base_url)
def save(self, writer: DataWriter) -> None:
- writer.write_string("markdown.md", self.markdown())
- writer.write_string("middle_json.json", self.to_json())
-
- writer.write_string(
- "structured_content.json",
- json.dumps(self.structured_content(), ensure_ascii=False, indent=2),
- )
+ """在副本上外置并校验素材,再保存可离线重渲染的协议及原始图片字节。"""
+ from docvortex.export import materialize_middle, validate_materialized_assets
+
+ middle_json, assets = materialize_middle(self.middle_json)
+ validate_materialized_assets(middle_json, assets)
+ exported = ParseResult(middle_json=middle_json)
+ text_files = {
+ "markdown.md": exported.markdown(),
+ "middle_json.json": exported.to_json(),
+ "structured_content.json": json.dumps(exported.structured_content(), ensure_ascii=False, indent=2),
+ }
if self._model_output is not None:
validate_mineru_metadata(self._model_output)
model_output = self._model_output.to_dict(skip_defaults=False)
- writer.write_string(
- "model_output.json",
- json.dumps(model_output, ensure_ascii=False, indent=2),
- )
+ text_files["model_output.json"] = json.dumps(model_output, ensure_ascii=False, indent=2)
+
+ # 所有引用和序列化均先完成,避免缺失素材时写出貌似完整的结果包。
+ for path, content in text_files.items():
+ writer.write_string(path, content)
+ for path, payload in sorted(assets.items()):
+ writer.write(path, payload)
def export_pages(self) -> list[PageInfo]:
"""返回页面树副本,避免调用方修改污染 ParseResult.pages。"""
diff --git a/pyproject.toml b/pyproject.toml
index 6b8d5f11..fc236fb2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,7 +39,7 @@ classifiers = [
"Programming Language :: Python :: 3.14",
]
dependencies = [
- "docvortex>=0.4.2,<1",
+ "docvortex>=0.4.3,<1",
"gradio>=6.8,<7",
"mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'",
"mineru-vl-utils>=2.0.4,<3",
diff --git a/tests/unittest/test_parse_result_assets.py b/tests/unittest/test_parse_result_assets.py
new file mode 100644
index 00000000..31ff47cd
--- /dev/null
+++ b/tests/unittest/test_parse_result_assets.py
@@ -0,0 +1,282 @@
+"""从真实保存入口覆盖 API 素材往返及无需重裁的 PDF 导出。"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+from io import BytesIO
+import json
+from pathlib import Path
+from unittest.mock import AsyncMock
+import zipfile
+
+from bs4 import BeautifulSoup
+from docvortex.document.pdf import PDFDocument
+from PIL import Image
+import pytest
+from reportlab.pdfgen.canvas import Canvas
+
+from mineru.kit.common import save_parse_result
+from mineru.kit.gradio import artifacts as gradio_artifacts
+from mineru.parser import api_client, api_server
+from mineru.parser.base import ParseResult
+from mineru.parser.writer import DataWriter
+from mineru.render import PdfLayout, render_pdf
+from mineru.types import CodeBlock, MiddleJson
+
+
+def _result(angle: int = 270) -> tuple[ParseResult, bytes, str]:
+ """构造非连续源页及带非对称图片、HTML 表内图、代码字面量的真实结果。"""
+ image = Image.new("RGB", (200, 100), "red")
+ image.paste("blue", (100, 0, 200, 100))
+ image.paste("green", (0, 0, 25, 25))
+ output = BytesIO()
+ image.save(output, "PNG")
+ payload = output.getvalue()
+ uri = "data:image/png;base64," + base64.b64encode(payload).decode()
+ width, height = (100, 200) if angle in (90, 270) else (200, 100)
+ bbox = [0.1, 0.1, 0.1 + width / 400, 0.1 + height / 600]
+ markup = f"<table><tr><td><IMG alt='a &amp; b' width='20' SRC = '{uri}' /></td></tr></table>"
+ middle = MiddleJson.from_dict(
+ {
+ "schema": "docvortex.middle",
+ "schema_version": "2.0",
+ "is_full_document": False,
+ "metadata": {"file_suffix": "pdf", "producer": {"name": "mineru", "version": "test"}},
+ "extensions": {
+ "mineru": {"tier": "basic", "parse_mode": "txt"},
+ "docvortex_layout": {
+ "version": 1,
+ "pages": [
+ {"page_idx": 4, "width_pt": 400, "height_pt": 600, "image_rotations": {"2": angle}},
+ {"page_idx": 8, "width_pt": 400, "height_pt": 600},
+ ],
+ },
+ },
+ "pages": [
+ {
+ "page_idx": 4,
+ "blocks": [
+ {
+ "type": "table",
+ "index": 2,
+ "bbox": bbox,
+ "content": [
+ {"type": "table_body", "index": 2, "bbox": bbox, "image_base64": uri, "content": markup}
+ ],
+ },
+ ],
+ },
+ {"page_idx": 8, "blocks": []},
+ ],
+ }
+ )
+ return ParseResult(middle_json=middle), payload, markup
+
+
+def _entries(payload: bytes) -> dict[str, bytes]:
+ """读取完整 ZIP 文件集合以比较多次保存的实际内容。"""
+ with zipfile.ZipFile(BytesIO(payload)) as archive:
+ assert len(archive.namelist()) == len(set(archive.namelist()))
+ return {name: archive.read(name) for name in archive.namelist()}
+
+
+def test_save_externalizes_assets_without_changing_json_only_contract(tmp_path: Path) -> None:
+ """API 与 CLI 使用相同保存入口,协议与所有消费格式均引用同一份素材。"""
+ result, image, _ = _result()
+ before = result.middle_json.to_json()
+ entries = _entries(api_server._build_self_contained_zip_output(result))
+ assert entries == _entries(api_server._build_self_contained_zip_output(result))
+ assert set(entries) == {
+ "middle_json.json",
+ "markdown.md",
+ "structured_content.json",
+ "images/page_4_table_body_2.png",
+ "images/page_4_table_body_2_1.png",
+ }
+ for name, payload in entries.items():
+ if name.startswith("images/"):
+ assert payload == image
+ saved = json.loads(entries["middle_json.json"])
+ assert saved["extensions"] == result.middle_json.extensions
+ for name in ("middle_json.json", "markdown.md", "structured_content.json"):
+ assert b"data:image/" not in entries[name]
+ assert b"images/page_4_table_body_2_1.png" in entries[name]
+ assert result.middle_json.to_json() == before
+ assert "image_base64" not in result.to_json()
+ dest = tmp_path / "result.zip"
+ save_parse_result(result, dest, "zip")
+ assert _entries(dest.read_bytes()) == entries
+
+
[email protected]("asynchronous", [False, True])
[email protected]("include_images", [False, True])
+def test_server_zip_roundtrip_restores_direct_and_markup_images(
+ monkeypatch: pytest.MonkeyPatch,
+ asynchronous: bool,
+ include_images: bool,
+) -> None:
+ """同步异步均消费真实服务端 ZIP,恢复 HTML 时保持属性、引号和字节。"""
+ result, image, markup = _result()
+ payload = api_server._build_self_contained_zip_output(result)
+ monkeypatch.setattr(api_client, "_download_bytes", lambda *args: payload)
+ monkeypatch.setattr(api_client, "_async_download_bytes", AsyncMock(return_value=payload))
+ parser = api_client.MinerUApiParser(
+ api_url="http://localhost:8000",
+ tier="basic",
+ include_images=include_images,
+ include_model_output=True,
+ )
+ job = {"status": "completed", "files": [{"output_files": {"zip": {"file_id": "file-test"}}}]}
+ restored = (
+ asyncio.run(api_client._async_parse_result_from_job(job, "sample.pdf", parser))
+ if asynchronous
+ else api_client._parse_result_from_job(job, "sample.pdf", parser)
+ )
+ assert restored._model_output is None
+ assert restored.middle_json.extensions == result.middle_json.extensions
+ body = restored.pages[0].blocks[0].content[0]
+ if include_images:
+ assert body.image_path is None
+ assert base64.b64decode(body.image_base64.split(",", 1)[1]) == image
+ assert body.content == markup
+ assert _entries(api_server._build_self_contained_zip_output(restored)) == _entries(payload)
+ else:
+ assert body.image_base64 is None and body.image_path == "images/page_4_table_body_2.png"
+ assert "images/page_4_table_body_2_1.png" in body.content
+
+
[email protected]("angle", [0, 90, 180, 270])
+def test_gradio_pdf_uses_packaged_images_without_cropping(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ angle: int,
+) -> None:
+ """API 往返及 Gradio 物化后,在源 PDF 不可用时仍保持原布局像素。"""
+ result, image, _ = _result(angle)
+ restored = api_client._parse_result_from_zip_bytes(
+ api_server._build_self_contained_zip_output(result),
+ include_images=True,
+ include_model_output=False,
+ )
+ source = tmp_path / "source.pdf"
+ buffer = BytesIO()
+ canvas = Canvas(buffer, pagesize=(400, 600))
+ for _ in range(9):
+ canvas.showPage()
+ canvas.save()
+ source.write_bytes(buffer.getvalue())
+
+ def reject_crop(*args: object, **kwargs: object) -> bytes:
+ """完整素材不允许调用任何源 PDF 裁图兜底。"""
+ raise AssertionError("Packaged images must not be recropped")
+
+ monkeypatch.setattr(gradio_artifacts._ImageContext, "crop_for_block", reject_crop)
+ artifacts = gradio_artifacts.persist_parse_result(
+ restored,
+ source,
+ output_root=tmp_path / "output",
+ page_range="5,9",
+ )
+ saved = ParseResult.from_json(artifacts.middle_json_path.read_text())
+ body = saved.pages[0].blocks[0].content[0]
+ assert (artifacts.root / body.image_path).read_bytes() == image
+ inline_path = BeautifulSoup(body.content, "html.parser").img["src"]
+ assert (artifacts.root / inline_path).read_bytes() == image
+ source.unlink()
+ artifacts.source_path.unlink()
+ artifacts.origin_pdf_path.unlink()
+ 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:
+ assert actual.page_count == 2
+ assert actual.get_page_image_infos(0)[0].bbox == pytest.approx(expected.get_page_image_infos(0)[0].bbox)
+ for page_index in range(2):
+ left = expected.render_page(page_index, scale=1).pil_image
+ right = actual.render_page(page_index, scale=1).pil_image
+ try:
+ assert left.size == right.size and left.tobytes() == right.tobytes()
+ finally:
+ left.close()
+ right.close()
+
+
[email protected]("location", ["direct", "html"])
+def test_save_rejects_missing_assets_before_writing(location: str) -> None:
+ """未提供素材字节的引用必须在任何写出之前失败。"""
+ result, _, _ = _result()
+ body = result.pages[0].blocks[0].content[0]
+ if location == "direct":
+ body.image_base64 = None
+ body.image_path = "images/missing.png"
+ else:
+ body.content = '<table><tr><td><img src="images/missing.png"></td></tr></table>'
+
+ class RejectWriter(DataWriter):
+ """禁止缺失素材的结果写入任何文件。"""
+
+ def write(self, path: str, data: bytes) -> None:
+ """若验证未提前发生则立即暴露部分结果写出。"""
+ raise AssertionError(f"Unexpected write: {path}")
+
+ with pytest.raises(ValueError, match="Missing materialized"):
+ result.save(RejectWriter())
+
+
[email protected]("source", ["images/missing.png", "../escape.png"])
+def test_client_rejects_missing_or_unsafe_markup_asset(source: str) -> None:
+ """请求图片时,表内引用与直接引用遵守同样的完整性和路径检查。"""
+ result, _, _ = _result()
+ body = result.pages[0].blocks[0].content[0]
+ body.content = f'<table><tr><td><img src="{source}"></td></tr></table>'
+ buffer = BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ archive.writestr("middle_json.json", result.to_json())
+ with pytest.raises(api_client._V1APIError, match="image sidecar"):
+ api_client._parse_result_from_zip_bytes(buffer.getvalue(), include_images=True, include_model_output=False)
+
+
+def test_client_preserves_markup_attributes_and_code_literals() -> None:
+ """带空格、实体、不同引号的 src 可恢复,代码中相同 HTML 字面量不变。"""
+ data = b"image-bytes"
+ path = "images/a b&c.png"
+ source = "images/a%20b&amp;c.png"
+ value = {
+ "type": "table_body",
+ "content": (
+ f'<img alt="a > b" data-src="unchanged" src="{source}" width="2">'
+ "<IMG src=images/second.png height=3>"
+ '<img src="https://example.test/remote.png">'
+ ),
+ }
+ code = {"type": "code_body", "content": value["content"]}
+ old_code = code["content"]
+ document = [value, code]
+ assert api_client._collect_image_paths_from_middle_json(document) == {path, "images/second.png"}
+ api_client._inline_image_sidecars(document, {path: data, "images/second.png": data})
+ uri = api_client._encode_image_data_uri(data, path)
+ assert value["content"] == old_code.replace(source, uri).replace("src=images/second.png", f"src={uri}")
+ assert code["content"] == old_code
+
+
+def test_save_and_restore_leave_code_image_literals_unchanged() -> None:
+ """完整保存与恢复也不外置代码示例中的 data URI 或读取其虚构路径。"""
+ result, _, markup = _result()
+ literal = markup + '<img src="images/not-an-asset.png">'
+ result.pages[1].blocks.append(
+ CodeBlock.model_validate(
+ {
+ "type": "code",
+ "sub_type": "code",
+ "guess_lang": "html",
+ "index": 3,
+ "bbox": [0.1, 0.1, 0.9, 0.8],
+ "content": [{"type": "code_body", "index": 3, "content": literal}],
+ }
+ )
+ )
+ packed = api_server._build_self_contained_zip_output(result)
+ assert len([name for name in _entries(packed) if name.startswith("images/")]) == 2
+ restored = api_client._parse_result_from_zip_bytes(packed, include_images=True, include_model_output=False)
+ assert restored.pages[1].blocks[0].content[0].content == literal
+ assert result.pages[1].blocks[0].content[0].content == literal
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 8e702c0a..3c106c6c 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -77,7 +77,8 @@ _REMOVED_FORMULA_ENABLE_ENV = "MINERU_" + "FORMULA" + "_ENABLE"
def _stub_api_server_dependency_preflight(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(importlib, "import_module", lambda _module_name: object())
+ """只跳过服务依赖预检,避免覆盖全局导入而破坏运行时的惰性加载。"""
+ monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", lambda *_args, **_kwargs: None)
def _full_middle_json(*pages: PageInfo) -> MiddleJson: