Skip to content

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

feat: add support for zip-only output in API client and server

myhloli2e95adeb1ffe
diff --git a/mineru/cli_old/gradio_app.py b/mineru/cli_old/gradio_app.py
index 5365026a..04b77687 100644
--- a/mineru/cli_old/gradio_app.py
+++ b/mineru/cli_old/gradio_app.py
@@ -1303,6 +1303,7 @@ async def _run_to_markdown_job(
api_url=server_health.base_url,
tier=runtime.tier,
include_model_output=True,
+ zip_output_only=True,
)
parse_result = await parser.parse_async(
file_path,
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.py
index ebc37f07..223c731b 100644
--- a/mineru/parser/api_client.py
+++ b/mineru/parser/api_client.py
@@ -61,6 +61,7 @@ class MinerUApiParser(DocumentParser):
api_key: str | None = None,
tier: Tier | None = None,
include_model_output: bool = False,
+ zip_output_only: bool = False,
) -> None:
api_url = api_url or os.environ.get("MINERU_API_URL", "https://mineru.net/api")
self._base = api_url.rstrip("/")
@@ -69,6 +70,7 @@ class MinerUApiParser(DocumentParser):
self._trust_env = should_trust_env_for_url(self._base)
self.tier = validate_tier(tier) if tier is not None else None
self.include_model_output = include_model_output
+ self.zip_output_only = zip_output_only
# ── DocumentParser interface ─────────────────────────────────────
@@ -116,6 +118,8 @@ class MinerUApiParser(DocumentParser):
def _output_formats(self) -> list[str]:
if "staging" in self._base:
return ["json"]
+ if self.zip_output_only:
+ return ["zip"]
formats = ["middle_json", "images"]
if self.include_model_output:
formats.append("zip")
@@ -307,6 +311,9 @@ def _parse_result_from_job(job: dict[str, Any], file_name: str, parser: MinerUAp
if files and files[0].get("output_files"):
outputs = files[0]["output_files"]
+ if parser.zip_output_only and "staging" not in parser._base:
+ return _parse_result_from_zip_output(parser, outputs, file_name)
+
mid_json = _download_json(parser, outputs)
result = _parse_result_from_middle_json(mid_json)
images = _download_image_sidecars(parser, outputs)
@@ -325,6 +332,13 @@ async def _async_parse_result_from_job(job: dict[str, Any], file_name: str, pars
if files and files[0].get("output_files"):
outputs = files[0]["output_files"]
+ if parser.zip_output_only and "staging" not in parser._base:
+ return _parse_result_from_zip_bytes(
+ await _async_download_zip_output(parser, outputs),
+ file_name,
+ include_model_output=parser.include_model_output,
+ )
+
mid_json = await _async_download_json(parser, outputs)
result = _parse_result_from_middle_json(mid_json)
images = await _async_download_image_sidecars(parser, outputs)
@@ -362,20 +376,128 @@ async def _async_download_model_output_from_zip(
def _extract_model_output_from_zip(zip_bytes: bytes, file_name: str) -> Any | None:
"""从 API server zip 中读取 `{stem}_model_output.json`,没有该文件则不影响普通解析。"""
- model_output_name = f"{Path(file_name).stem}_model_output.json"
try:
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as archive:
- if model_output_name not in archive.namelist():
- return None
- raw = archive.read(model_output_name)
+ return _extract_model_output_from_archive(archive, file_name)
except zipfile.BadZipFile as exc:
raise _V1APIError("invalid_model_output", "model output zip is not a valid ZIP archive") from exc
+
+
+def _extract_model_output_from_archive(archive: zipfile.ZipFile, file_name: str) -> Any | None:
+ """从已打开的 zip 读取原始模型输出,供普通 zip 和 zip-only 解析路径复用。"""
+ model_output_name = f"{Path(file_name).stem}_model_output.json"
+ if model_output_name not in archive.namelist():
+ return None
+ raw = archive.read(model_output_name)
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
raise _V1APIError("invalid_model_output", f"model output JSON is not valid JSON: {exc}") from exc
+def _download_zip_output(parser: MinerUApiParser, outputs: dict[str, Any]) -> bytes:
+ """下载 zip-only 模式的唯一结果包;缺失 zip 时给出明确错误。"""
+ zip_ref = outputs.get("zip")
+ if not isinstance(zip_ref, dict):
+ available = ", ".join(sorted(outputs)) or "none"
+ raise _V1APIError("missing_zip_output", f"Parse job did not return zip output; available outputs: {available}")
+ return _download_bytes(parser, zip_ref)
+
+
+async def _async_download_zip_output(parser: MinerUApiParser, outputs: dict[str, Any]) -> bytes:
+ """异步下载 zip-only 模式的唯一结果包;缺失 zip 时给出明确错误。"""
+ zip_ref = outputs.get("zip")
+ if not isinstance(zip_ref, dict):
+ available = ", ".join(sorted(outputs)) or "none"
+ raise _V1APIError("missing_zip_output", f"Parse job did not return zip output; available outputs: {available}")
+ return await _async_download_bytes(parser, zip_ref)
+
+
+def _parse_result_from_zip_output(parser: MinerUApiParser, outputs: dict[str, Any], file_name: str) -> ParseResult:
+ """从 v1 API 自包含 zip 输出恢复 ParseResult,避免逐个下载 middle_json 和图片。"""
+ return _parse_result_from_zip_bytes(
+ _download_zip_output(parser, outputs),
+ file_name,
+ include_model_output=parser.include_model_output,
+ )
+
+
+def _parse_result_from_zip_bytes(zip_bytes: bytes, file_name: str, *, include_model_output: bool) -> ParseResult:
+ """解析自包含 zip 包:读取 middle_json、图片 sidecar 和可选 model_output。"""
+ try:
+ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as archive:
+ mid_json = _read_middle_json_from_zip(archive, file_name)
+ result = _parse_result_from_middle_json(mid_json)
+ images = _read_image_sidecars_from_zip(archive, mid_json)
+ if images:
+ result.attach_export_images(images)
+ if include_model_output:
+ model_output = _extract_model_output_from_archive(archive, file_name)
+ if model_output is not None:
+ result._model_output = model_output
+ return result
+ except zipfile.BadZipFile as exc:
+ raise _V1APIError("invalid_zip_output", "zip output is not a valid ZIP archive") from exc
+
+
+def _middle_json_zip_candidates(file_name: str) -> list[str]:
+ """列出 API zip 和本地 Gradio zip 中可能出现的 middle_json 文件名。"""
+ stem = Path(file_name).stem
+ return [
+ f"{stem}.middle_json",
+ f"{stem}_middle.json",
+ f"{stem}.middle_json.json",
+ "middle_json.json",
+ ]
+
+
+def _read_middle_json_from_zip(archive: zipfile.ZipFile, file_name: str) -> dict[str, Any]:
+ """从 zip 中读取 middle_json,兼容 API server 和本地保存包的命名。"""
+ names = set(archive.namelist())
+ for candidate in _middle_json_zip_candidates(file_name):
+ if candidate not in names:
+ continue
+ raw = archive.read(candidate)
+ try:
+ loaded = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise _V1APIError("invalid_middle_json_output", f"middle_json output is not valid JSON: {exc}") from exc
+ if not isinstance(loaded, dict):
+ raise _V1APIError(
+ "invalid_middle_json_output",
+ "middle_json output must be a JSON object with pages or pdf_info",
+ )
+ return loaded
+ available = ", ".join(sorted(names)) or "none"
+ raise _V1APIError("missing_middle_json_output", f"ZIP output did not contain middle_json; available entries: {available}")
+
+
+def _collect_image_paths_from_middle_json(value: Any) -> set[str]:
+ """递归收集 middle_json 中引用的图片 sidecar 路径。"""
+ paths: set[str] = set()
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if key in {"image_path", "img_path"} and isinstance(item, str) and item:
+ paths.add(item)
+ else:
+ paths.update(_collect_image_paths_from_middle_json(item))
+ elif isinstance(value, list):
+ for item in value:
+ paths.update(_collect_image_paths_from_middle_json(item))
+ return paths
+
+
+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())
+ images: dict[str, bytes] = {}
+ for image_path in sorted(_collect_image_paths_from_middle_json(mid_json)):
+ safe_image_path = validate_image_sidecar_path(image_path)
+ if safe_image_path in archive_names:
+ images[safe_image_path] = archive.read(safe_image_path)
+ return images
+
+
def _download_image_sidecars(parser: MinerUApiParser, outputs: dict[str, Any]) -> dict[str, bytes]:
"""下载 API 返回的图片 sidecar,并按 middle_json 中的 image_path 建立字节映射。"""
images: dict[str, bytes] = {}
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index e718f19e..980d01e2 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -39,6 +39,7 @@ from pydantic import BaseModel, ConfigDict, Field
from ..types import Tier, validate_tier
from ..utils.backend_options import DEFAULT_HYBRID_EFFORT
+from ..utils.image_payload import validate_image_sidecar_path
from ..utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
from ..version import __version__
from . import parse_async
@@ -926,6 +927,34 @@ def _store_image_outputs(file_store: FileStore, images: dict[str, bytes]) -> lis
return img_refs
+def _build_self_contained_zip_output(result: Any, output_stem: str) -> bytes:
+ """构建自包含解析 zip,确保只请求 zip 时也能恢复 middle_json、图片和 model_output。"""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr(f"{output_stem}.markdown", _text_utf8_bytes(result.markdown() or ""))
+ zf.writestr(f"{output_stem}.middle_json", _json_utf8_bytes(result.to_dict(skip_defaults=True)))
+ zf.writestr(f"{output_stem}.content_list", _json_utf8_bytes(result.content_list()))
+ zf.writestr(f"{output_stem}.structured_content", _json_utf8_bytes(result.structured_content()))
+
+ for img_path, img_bytes in sorted(result.images().items()):
+ safe_img_path = validate_image_sidecar_path(img_path)
+ zf.writestr(safe_img_path, img_bytes)
+
+ model_output = getattr(result, "_model_output", None)
+ if model_output is not None:
+ zf.writestr(
+ f"{output_stem}_model_output.json",
+ _text_utf8_bytes(
+ json.dumps(
+ _sanitize_json_for_utf8(model_output),
+ ensure_ascii=False,
+ indent=4,
+ )
+ ),
+ )
+ return buf.getvalue()
+
+
# ═══════════════════════════════════════════════════════════════════════
# DEPENDENCIES
# ═══════════════════════════════════════════════════════════════════════
@@ -1346,42 +1375,7 @@ async def _run_job(
# zip
if "zip" in out_formats:
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
- for fmt_name, attr in [
- ("markdown", "markdown"),
- ("middle_json", "middle_json"),
- ("content_list", "content_list"),
- ("structured_content", "structured_content"),
- ]:
- ref = getattr(output_files, attr)
- if ref and ref.file_id:
- try:
- zf.writestr(
- f"{pathlib.Path(fr.name).stem}.{fmt_name}",
- file_store.read_file_data(ref.file_id),
- )
- except Exception:
- pass
- if output_files.images:
- for ir in output_files.images:
- try:
- zf.writestr(ir.path, file_store.read_file_data(ir.file_id))
- except Exception:
- pass
- model_output = getattr(result, "_model_output", None)
- if model_output is not None:
- zf.writestr(
- f"{pathlib.Path(fr.name).stem}_model_output.json",
- _text_utf8_bytes(
- json.dumps(
- _sanitize_json_for_utf8(model_output),
- ensure_ascii=False,
- indent=4,
- )
- ),
- )
- zip_bytes = buf.getvalue()
+ zip_bytes = _build_self_contained_zip_output(result, pathlib.Path(fr.name).stem)
zip_sha = hashlib.sha256(zip_bytes).hexdigest()
file_store.store_blob(zip_bytes, sha256hex=zip_sha)
zip_fid = file_store.create_file_for_output(f"{fr.name}.zip", zip_bytes, sha256hex=zip_sha)
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index 19b554e0..1beacd72 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -822,10 +822,11 @@ def test_gradio_v1_job_reuses_page_range_for_api_and_origin_pdf(
calls: dict[str, Any] = {}
class _FakeParser:
- def __init__(self, *, api_url: str, tier: str, include_model_output: bool) -> None:
+ def __init__(self, *, api_url: str, tier: str, include_model_output: bool, zip_output_only: bool) -> None:
calls["parser_api_url"] = api_url
calls["parser_tier"] = tier
calls["include_model_output"] = include_model_output
+ calls["zip_output_only"] = zip_output_only
async def parse_async(self, file_path: str, *, page_range: str) -> ParseResult:
calls["api_page_range"] = page_range
@@ -859,6 +860,7 @@ def test_gradio_v1_job_reuses_page_range_for_api_and_origin_pdf(
assert calls["api_page_range"] == "1~2"
assert calls["include_model_output"] is True
+ assert calls["zip_output_only"] is True
assert calls["persist_page_range"] == "1~2"
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index ac1f11d1..928e3ce7 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -196,6 +196,21 @@ def test_api_client_can_request_zip_for_model_output(tmp_path: Path) -> None:
assert payload["output_formats"] == ["middle_json", "images", "zip"]
+def test_api_client_can_request_zip_output_only(tmp_path: Path) -> None:
+ pdf = tmp_path / "demo.pdf"
+ pdf.write_bytes(b"%PDF-1.7\n")
+
+ parser = MinerUApiParser(
+ api_url="http://localhost:8000",
+ tier="high",
+ include_model_output=True,
+ zip_output_only=True,
+ )
+ payload = parser._build_payload(pdf, "")
+
+ assert payload["output_formats"] == ["zip"]
+
+
def test_api_client_keeps_staging_json_format_when_model_output_requested() -> None:
parser = MinerUApiParser(
api_url="https://staging.mineru.org.cn/api",
@@ -206,6 +221,17 @@ def test_api_client_keeps_staging_json_format_when_model_output_requested() -> N
assert parser._output_formats() == ["json"]
+def test_api_client_keeps_staging_json_format_when_zip_output_only_requested() -> None:
+ parser = MinerUApiParser(
+ api_url="https://staging.mineru.org.cn/api",
+ tier="extra_high",
+ include_model_output=True,
+ zip_output_only=True,
+ )
+
+ assert parser._output_formats() == ["json"]
+
+
def test_api_client_uses_tier_without_backend_semantics(tmp_path: Path) -> None:
pdf = tmp_path / "demo.pdf"
pdf.write_bytes(b"%PDF-1.7\n")
@@ -329,6 +355,138 @@ def test_api_client_async_downloads_model_output_from_zip(monkeypatch: pytest.Mo
assert result._model_output == [[{"raw": "model"}]]
+def test_api_client_zip_output_only_downloads_single_zip(monkeypatch: pytest.MonkeyPatch) -> None:
+ parser = MinerUApiParser(
+ api_url="http://localhost:8000",
+ tier="high",
+ include_model_output=True,
+ zip_output_only=True,
+ )
+ zip_ref = {"file_id": "file-zip", "bytes": 10}
+ image_cache = ImagePayloadCache()
+ image_path = image_cache.register_bytes(b"chart-bytes", "png", image_path="images/chart.png")
+ span = Span(type="image", bbox=(0, 0, 10, 10), image_path=image_path)
+ page = PageInfo(
+ page_idx=0,
+ page_size=(100, 200),
+ para_blocks=[Block(index=0, type="image", bbox=(0, 0, 10, 10), lines=[Line(bbox=(0, 0, 10, 10), spans=[span])])],
+ _backend="hybrid",
+ )
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("demo.middle_json", json.dumps(ParseResult(pages=[page]).to_dict(), ensure_ascii=False))
+ archive.writestr("images/chart.png", b"chart-bytes")
+ archive.writestr("demo_model_output.json", json.dumps([[{"raw": "model"}]], ensure_ascii=False, indent=4))
+ download_calls: list[dict[str, object]] = []
+
+ def fake_download_bytes(_parser: object, ref: dict[str, object]) -> bytes:
+ download_calls.append(ref)
+ return zip_buffer.getvalue() if ref is zip_ref else b""
+
+ monkeypatch.setattr(api_client, "_download_bytes", fake_download_bytes)
+ monkeypatch.setattr(
+ api_client,
+ "_download_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("zip-only must not download middle_json separately")),
+ )
+
+ result = _parse_result_from_job(
+ {
+ "job_id": "job_1",
+ "status": "completed",
+ "files": [{"output_files": {"zip": zip_ref}}],
+ },
+ "demo.pdf",
+ parser,
+ )
+
+ assert download_calls == [zip_ref]
+ assert result.pages[0].page_idx == 0
+ assert result.images() == {"images/chart.png": b"chart-bytes"}
+ assert result._model_output == [[{"raw": "model"}]]
+
+
+def test_api_client_async_zip_output_only_downloads_single_zip(monkeypatch: pytest.MonkeyPatch) -> None:
+ parser = MinerUApiParser(
+ api_url="http://localhost:8000",
+ tier="high",
+ include_model_output=True,
+ zip_output_only=True,
+ )
+ zip_ref = {"file_id": "file-zip", "bytes": 10}
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr(
+ "demo.middle_json",
+ json.dumps({"schema_version": "1.0.0", "pages": [{"page_idx": 2, "page_size": [100, 200]}]}),
+ )
+ archive.writestr("demo_model_output.json", json.dumps([[{"raw": "model"}]], ensure_ascii=False, indent=4))
+ download_calls: list[dict[str, object]] = []
+
+ async def fake_download_bytes(_parser: object, ref: dict[str, object]) -> bytes:
+ download_calls.append(ref)
+ return zip_buffer.getvalue() if ref is zip_ref else b""
+
+ async def fail_download_json(*_args: object, **_kwargs: object) -> dict[str, object]:
+ raise AssertionError("zip-only must not download middle_json separately")
+
+ monkeypatch.setattr(api_client, "_async_download_bytes", fake_download_bytes)
+ monkeypatch.setattr(api_client, "_async_download_json", fail_download_json)
+
+ result = asyncio.run(
+ api_client._async_parse_result_from_job(
+ {
+ "job_id": "job_1",
+ "status": "completed",
+ "files": [{"output_files": {"zip": zip_ref}}],
+ },
+ "demo.pdf",
+ parser,
+ )
+ )
+
+ assert download_calls == [zip_ref]
+ assert result.pages[0].page_idx == 2
+ assert result._model_output == [[{"raw": "model"}]]
+
+
+def test_api_client_zip_output_only_rejects_unsafe_image_entries(monkeypatch: pytest.MonkeyPatch) -> None:
+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="high", zip_output_only=True)
+ zip_ref = {"file_id": "file-zip", "bytes": 10}
+ middle_json = {
+ "schema_version": "1.0.0",
+ "pages": [
+ {
+ "page_idx": 0,
+ "para_blocks": [
+ {
+ "index": 0,
+ "type": "image",
+ "bbox": [0, 0, 10, 10],
+ "lines": [{"bbox": [0, 0, 10, 10], "spans": [{"type": "image", "bbox": [0, 0, 10, 10], "image_path": "../escape.png"}]}],
+ }
+ ],
+ }
+ ],
+ }
+ zip_buffer = io.BytesIO()
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("demo.middle_json", json.dumps(middle_json, ensure_ascii=False))
+
+ monkeypatch.setattr(api_client, "_download_bytes", lambda _parser, ref: zip_buffer.getvalue() if ref is zip_ref else b"")
+
+ with pytest.raises(ValueError, match="Unsafe image sidecar path"):
+ _parse_result_from_job(
+ {
+ "job_id": "job_1",
+ "status": "completed",
+ "files": [{"output_files": {"zip": zip_ref}}],
+ },
+ "demo.pdf",
+ parser,
+ )
+
+
def test_api_client_accepts_remote_pdf_info_json(monkeypatch: pytest.MonkeyPatch) -> None:
parser = MinerUApiParser(api_url="https://staging.mineru.org.cn/api", tier="high")
middle_json = {
@@ -999,6 +1157,119 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(
assert "\n " in model_output_text
+def test_api_server_zip_is_self_contained_when_only_zip_requested(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ img_bytes = b"chart-bytes"
+ image_cache = ImagePayloadCache()
+ image_path = image_cache.register_bytes(img_bytes, "png", image_path="images/chart.png")
+ span = Span(type="image", bbox=(0, 0, 10, 10), image_path=image_path)
+ block = Block(index=0, type="image", bbox=(0, 0, 10, 10), lines=[Line(bbox=(0, 0, 10, 10), spans=[span])])
+ parse_result = ParseResult(
+ pages=[
+ PageInfo(
+ page_idx=0,
+ page_size=(100, 100),
+ para_blocks=[block],
+ _backend="hybrid",
+ )
+ ],
+ _image_cache=image_cache,
+ _model_output=[[{"raw": "model"}]],
+ )
+
+ async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
+ return parse_result
+
+ monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
+ file_store = FileStore(tmp_path / "api-files")
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+ request = CreateJobRequest.model_validate(
+ {
+ "files": [{"source": {"type": "local", "path": str(source)}}],
+ "tier": "high",
+ "output_formats": ["zip"],
+ }
+ )
+ rec = api_server.JobStore().create(request, file_store)
+
+ asyncio.run(
+ api_server._run_job(
+ rec,
+ request,
+ file_store,
+ server_backend="hybrid-engine",
+ language="ch",
+ ocr_mode="auto",
+ image_analysis=True,
+ effort="medium",
+ )
+ )
+
+ output_files = rec.files[0].output_files
+ assert output_files.middle_json is None
+ assert output_files.images is None
+ assert output_files.zip is not None
+ with zipfile.ZipFile(io.BytesIO(file_store.read_file_data(output_files.zip.file_id))) as archive:
+ names = set(archive.namelist())
+ assert {
+ "demo.markdown",
+ "demo.middle_json",
+ "demo.content_list",
+ "demo.structured_content",
+ "demo_model_output.json",
+ "images/chart.png",
+ }.issubset(names)
+ assert json.loads(archive.read("demo.middle_json").decode("utf-8"))["_backend"] == "hybrid"
+ assert json.loads(archive.read("demo_model_output.json").decode("utf-8")) == [[{"raw": "model"}]]
+ assert archive.read("images/chart.png") == img_bytes
+
+
+def test_api_server_zip_rejects_unsafe_image_sidecar_path(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ parse_result = ParseResult(
+ pages=[PageInfo(page_idx=0, page_size=(100, 100), _backend="hybrid")],
+ _image_cache={"../escape.png": b"bad-image"},
+ )
+
+ async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
+ return parse_result
+
+ monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)
+ file_store = FileStore(tmp_path / "api-files")
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+ request = CreateJobRequest.model_validate(
+ {
+ "files": [{"source": {"type": "local", "path": str(source)}}],
+ "tier": "high",
+ "output_formats": ["zip"],
+ }
+ )
+ rec = api_server.JobStore().create(request, file_store)
+
+ asyncio.run(
+ api_server._run_job(
+ rec,
+ request,
+ file_store,
+ server_backend="hybrid-engine",
+ language="ch",
+ ocr_mode="auto",
+ image_analysis=True,
+ effort="medium",
+ )
+ )
+
+ assert rec.files[0].status == "failed"
+ assert rec.files[0].error is not None
+ assert "Unsafe image sidecar path" in rec.files[0].error.message
+
+
def test_api_server_zip_skips_model_output_when_parse_result_has_none(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,