Skip to content

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

refactor: collapse image payloads to base64 and bbox above parser

jinzhenjd6244b08695d
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 855895b5..f60b8c1d 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -27,6 +27,7 @@ from ..filetypes import IMAGE_EXTENSIONS, TEXT_EXTENSIONS, TEXT_FILE_TYPES
from ..parser.tier import TierDependencyError, ensure_tier_runtime_dependencies
from ..render._internal.markdown.assets import build_markdown_image
from ..render._internal.markdown.blocks import render_single_block
+from ..utils.image_payload import parse_image_data_uri_strict
from ..types import (
DEPLOYMENT_TIERS,
TIERS,
@@ -71,9 +72,7 @@ from .services.parse_svc import (
accessible_file_for_sha256,
filter_pages_by_user_range,
load_pages_from_done_batches,
- parse_image_sidecar_dir,
parse_page_range_set,
- resolve_image_sidecar_path,
)
from .telemetry.buckets import pages_bucket, results_bucket
from .types import (
@@ -211,7 +210,7 @@ _VISUAL_BLOCK_LABELS = {
@dataclass(frozen=True)
class _BlockImageSource:
kind: str
- sidecar_path: Path | None = None
+ data_uri: str | None = None
@dataclass(frozen=True)
@@ -1227,8 +1226,6 @@ class DoclibServer(AsyncDoclibInterface):
text
for _, text in _page_markdown_blocks(
page,
- data_dir=data_dir,
- sha256=sha256,
short_id=doc["short_id"],
tier=tier,
)
@@ -1254,8 +1251,6 @@ class DoclibServer(AsyncDoclibInterface):
pages_for_render = _select_context_pages(loaded_pages, plan.target, plan.context)
rendered = _render_progressive_markdown(
pages_for_render,
- data_dir=data_dir,
- sha256=plan.sha256,
short_id=plan.short_id,
tier=plan.tier,
after=_parse_after_cursor(plan.after),
@@ -1318,15 +1313,14 @@ class DoclibServer(AsyncDoclibInterface):
block = _find_block_by_no(page, plan.target.block_no)
if block is None:
raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")
- image_dir = parse_image_sidecar_dir(_effective_data_dir(self.state), plan.sha256, plan.tier)
- source = _resolve_block_image_source(block, image_dir=image_dir)
+ source = _resolve_block_image_source(block)
if source is None:
raise NotFoundError("asset_not_available", "Block image asset is not available.", "locator")
if source.kind == "source_bbox":
asset = await self._render_source_image_asset(plan, page)
else:
- assert source.sidecar_path is not None
- asset = self._render_sidecar_image_asset(plan, source.sidecar_path)
+ assert source.data_uri is not None
+ asset = self._render_base64_image_asset(plan, source.data_uri)
target_ref = plan.locator or page_ref(plan.short_id, plan.tier, plan.target.page_no)
return DocContentResponse(
@@ -1458,8 +1452,8 @@ class DoclibServer(AsyncDoclibInterface):
height=height,
)
- def _render_sidecar_image_asset(self, plan: _ReadPlan, sidecar_path: Path) -> ContentAsset:
- image_bytes = sidecar_path.read_bytes()
+ def _render_base64_image_asset(self, plan: _ReadPlan, data_uri: str) -> ContentAsset:
+ image_bytes, _extension = parse_image_data_uri_strict(data_uri)
image_bytes = _transcode_image_bytes(image_bytes, plan.image_format)
width, height = _image_size_from_bytes(image_bytes)
return _write_temp_asset(
@@ -1801,31 +1795,24 @@ def _is_empty_bbox(bbox: object) -> bool:
return values[0] >= values[2] or values[1] >= values[3]
-def _resolve_block_image_source(block: BlockBase, *, image_dir: str) -> _BlockImageSource | None:
+def _resolve_block_image_source(block: BlockBase) -> _BlockImageSource | None:
if not _is_empty_bbox(block.bbox):
return _BlockImageSource(kind="source_bbox")
for payload in _iter_block_image_payloads(block):
- if not payload.image_path:
- continue
- candidate = resolve_image_sidecar_path(image_dir, payload.image_path)
- if candidate is not None and candidate.is_file():
- return _BlockImageSource(kind="sidecar", sidecar_path=candidate)
+ if payload.image_base64:
+ return _BlockImageSource(kind="base64", data_uri=payload.image_base64)
return None
def _make_doclib_image_renderer(
*,
- data_dir: str,
- sha256: str,
short_id: str,
tier: Tier,
page_no: int,
) -> Callable[[BlockBase], str]:
- image_dir = parse_image_sidecar_dir(data_dir, sha256, tier)
-
def _render(block: BlockBase) -> str:
label = _VISUAL_BLOCK_LABELS.get(block.type, "Image block")
- source = _resolve_block_image_source(block, image_dir=image_dir)
+ source = _resolve_block_image_source(block)
if source is not None:
block_no = block.index + 1 if block.index is not None else 0 # TODO: change after block.index's type changed.
return build_markdown_image(block_ref(short_id, tier, page_no, block_no), label)
@@ -1925,8 +1912,6 @@ def _render_progressive_markdown(
add_markers: bool,
target: ContentCursor | None = None,
context: int = 0,
- data_dir: str = "",
- sha256: str = "",
page_count: int | None = None,
) -> _RenderedContent:
output: list[str] = []
@@ -1942,8 +1927,6 @@ def _render_progressive_markdown(
continue
page_blocks = _page_markdown_blocks(
page,
- data_dir=data_dir,
- sha256=sha256,
short_id=short_id,
tier=tier,
)
@@ -2071,8 +2054,6 @@ def _page_marker(page_no: int, page_count: int | None) -> str:
def _page_markdown_blocks(
page: PageInfo,
*,
- data_dir: str = "",
- sha256: str = "",
short_id: str = "",
tier: Tier = "standard",
) -> list[tuple[int, str]]:
@@ -2080,8 +2061,6 @@ def _page_markdown_blocks(
result: list[tuple[int, str]] = []
image_renderer = _make_doclib_image_renderer(
- data_dir=data_dir,
- sha256=sha256,
short_id=short_id,
tier=tier,
page_no=page.page_idx + 1,
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 6906c045..b0f59bf1 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -9,7 +9,7 @@ import os
import time
from collections.abc import Sequence
from dataclasses import dataclass
-from pathlib import Path, PurePosixPath
+from pathlib import Path
from typing import Literal, cast
from urllib.parse import urlparse
@@ -1050,7 +1050,6 @@ class ParseService:
write_start_ms = _now_ms()
try:
os.makedirs(output_dir, exist_ok=True)
- _write_cached_image_sidecars(parse_image_sidecar_dir(self.data_dir, sha256, tier), result.images())
with open(json_path, "w", encoding="utf-8") as f:
json.dump(export_payload, f, ensure_ascii=False, indent=2)
except Exception as exc:
@@ -1565,31 +1564,6 @@ def parse_batch_json_path(data_dir: str, sha256: str, tier: Tier, page_range: st
return os.path.join(os.path.expanduser(data_dir), "parsed", sha256[:2], sha256, tier, filename)
-def parse_image_sidecar_dir(data_dir: str, sha256: str, tier: Tier) -> str:
- """返回 doclib 解析缓存图片 sidecar 目录,供同一文档同一 tier 的多个 batch 共用。"""
- return os.path.join(os.path.expanduser(data_dir), "parsed", sha256[:2], sha256, tier, "images")
-
-
-def resolve_image_sidecar_path(image_dir: str, image_path: str) -> Path | None:
- """把 public image_path 安全映射到 doclib 缓存图片目录,拒绝绝对路径和上跳路径。"""
- if not image_path:
- return None
- raw_path = PurePosixPath(image_path)
- if raw_path.is_absolute() or any(part in {"", ".", ".."} for part in raw_path.parts):
- return None
- return Path(image_dir).joinpath(*raw_path.parts)
-
-
-def _write_cached_image_sidecars(image_dir: str, images: dict[str, bytes]) -> None:
- """把 ParseResult.images() 的图片字节写入 doclib 缓存,保证后续 markdown 链接可访问。"""
- for image_path, image_bytes in images.items():
- sidecar_path = resolve_image_sidecar_path(image_dir, image_path)
- if sidecar_path is None:
- continue
- sidecar_path.parent.mkdir(parents=True, exist_ok=True)
- sidecar_path.write_bytes(image_bytes)
-
-
def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_rows: Sequence[ParseBatchRow]) -> list[PageInfo]:
"""Load valid done JSON batches and keep the newest page for duplicate page_idx values."""
pages_by_page_idx: dict[int, PageInfo] = {}
@@ -1658,7 +1632,6 @@ def _remap_api_result_pages_to_page_range(result: ParseResult, page_range: str)
)
for page, page_no in zip(result.pages, requested_page_numbers, strict=True):
page.page_idx = page_no - 1
- result.refresh_export_cache(preserve_images=True)
def _parse_coverage(request_page_range: str, rows: list[ParseRow]) -> dict:
diff --git a/mineru/kit/common.py b/mineru/kit/common.py
index 9b8ad7ee..19838993 100644
--- a/mineru/kit/common.py
+++ b/mineru/kit/common.py
@@ -10,7 +10,6 @@ from ..filetypes import PARSEABLE_EXTENSIONS
from ..parser.base import ParseResult
from ..parser.writer import FileBasedDataWriter
from ..types import Tier
-from ..utils.image_payload import validate_image_sidecar_path
KitFormat = Literal["markdown", "middle_json", "zip"]
LocalTier: TypeAlias = Tier
@@ -117,11 +116,9 @@ def save_parse_result(result: ParseResult, dest: Path, format: KitFormat) -> Non
dest.parent.mkdir(parents=True, exist_ok=True)
if format == "markdown":
_write_utf8_text(dest, result.markdown())
- _write_image_sidecars(dest.parent, result.images())
return
if format == "middle_json":
_write_utf8_text(dest, result.to_json())
- _write_image_sidecars(dest.parent, result.images())
return
if format == "zip":
tmp_dir = dest.parent / f".{dest.stem}"
@@ -146,28 +143,6 @@ def _write_utf8_text(path: Path, content: str) -> None:
path.write_bytes(content.encode("utf-8", errors="replace"))
-def _resolve_safe_sidecar_path(output_dir: Path, image_path: str) -> str:
- """校验图片 sidecar 路径必须落在输出目录内,并返回安全的相对路径。"""
- safe_image_path = validate_image_sidecar_path(image_path)
- output_root = output_dir.resolve()
- target_path = (output_root / safe_image_path).resolve()
- try:
- target_path.relative_to(output_root)
- except ValueError as exc:
- raise ValueError(f"Unsafe image sidecar path: {image_path}") from exc
- return target_path.relative_to(output_root).as_posix()
-
-
-def _write_image_sidecars(output_dir: Path, images: dict[str, bytes]) -> None:
- """将 public middle_json 引用的图片 sidecar 写到输出目录,避免 image_path 悬空。"""
- writer = FileBasedDataWriter(str(output_dir))
- safe_images = [
- (_resolve_safe_sidecar_path(output_dir, image_path), image_bytes) for image_path, image_bytes in images.items()
- ]
- for image_path, image_bytes in safe_images:
- writer.write(image_path, image_bytes)
-
-
def parse_result_payload(path: Path, dest: Path, format: KitFormat) -> dict[str, str]:
return {
"input": str(path),
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.py
index fa4d7c05..04d298af 100644
--- a/mineru/parser/api_client.py
+++ b/mineru/parser/api_client.py
@@ -9,6 +9,7 @@ does not expose parser backend selection.
from __future__ import annotations
import asyncio
+import base64
import hashlib
import io
import ipaddress
@@ -795,11 +796,11 @@ def _parse_result_from_zip_bytes(
try:
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as archive:
mid_json = _read_middle_json_from_zip(archive)
- result = _parse_result_from_middle_json(mid_json)
if include_images:
images = _read_image_sidecars_from_zip(archive, mid_json)
if images:
- result.attach_export_images(images)
+ _inline_image_sidecars(mid_json, images)
+ result = _parse_result_from_middle_json(mid_json)
if include_model_output:
model_output = _extract_model_output_from_archive(archive)
if model_output is not None:
@@ -807,6 +808,8 @@ def _parse_result_from_zip_bytes(
return result
except zipfile.BadZipFile as exc:
raise _V1APIError("invalid_zip_output", "zip output is not a valid ZIP archive") from exc
+ except ValueError as exc:
+ raise _V1APIError("invalid_image_sidecar", str(exc)) from exc
def _middle_json_zip_candidates() -> list[str]:
@@ -869,6 +872,46 @@ def _read_image_sidecars_from_zip(archive: zipfile.ZipFile, mid_json: dict[str,
return images
+_IMAGE_DATA_URI_SUBTYPES: dict[str, str] = {
+ "jpg": "jpeg",
+ "jpeg": "jpeg",
+ "png": "png",
+ "gif": "gif",
+ "webp": "webp",
+ "bmp": "bmp",
+ "tiff": "tiff",
+ "svg": "svg+xml",
+}
+
+
+def _encode_image_data_uri(image_bytes: bytes, image_path: str) -> str:
+ """把图片字节编码为 data URI,MIME subtype 从 sidecar 扩展名推断。"""
+ ext = Path(image_path).suffix.lstrip(".").lower()
+ subtype = _IMAGE_DATA_URI_SUBTYPES.get(ext)
+ if subtype is None:
+ raise _V1APIError("invalid_image_sidecar", f"Unsupported image sidecar extension: {image_path}")
+ return f"data:image/{subtype};base64,{base64.b64encode(image_bytes).decode('ascii')}"
+
+
+def _inline_image_sidecars(mid_json: Any, images: dict[str, bytes]) -> None:
+ """递归把 middle_json 中引用的图片 sidecar 路径替换为内联 data URI。"""
+ 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}")
+ if image_bytes is not None:
+ mid_json["image_base64"] = _encode_image_data_uri(image_bytes, image_path)
+ mid_json.pop("image_path", None)
+ mid_json.pop("img_path", None)
+ for value in mid_json.values():
+ _inline_image_sidecars(value, images)
+ elif isinstance(mid_json, list):
+ for item in mid_json:
+ _inline_image_sidecars(item, images)
+
+
def _download_json(parser: MinerUApiParser, outputs: dict[str, Any]) -> dict[str, Any]:
ref = outputs.get("middle_json")
if not ref:
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 905691c2..019b95f3 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -6,17 +6,13 @@ from abc import ABC, abstractmethod
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Literal, cast
+from typing import Any, Literal, cast
from ..render import render_markdown, render_structured_content
from ..render.contracts import ImageRenderer, RenderMode
from ..types import FILE_SUFFIXES, FileSuffix, MiddleJson, ModelJson, PageInfo
-from ..utils.image_payload import ImagePayloadCache
from .writer import DataWriter
-if TYPE_CHECKING:
- from ..model.flash.pdf.document import PDFDocument
-
MIDDLE_JSON_SCHEMA_VERSION: str = "2.0"
_LEGACY_SCHEMA_VERSION: str = "1.0"
_LEGACY_DEFAULT_FILE_SUFFIX: FileSuffix = "pdf"
@@ -90,22 +86,13 @@ class ParseResult:
"""
middle_json: MiddleJson
- _pdf_doc: PDFDocument | None = None
_model_output: Any = None
- _image_cache: ImagePayloadCache | dict[str, bytes] | None = None
@property
def pages(self) -> list[PageInfo]:
"""顶层页面列表,委托给 MiddleJson。"""
return self.middle_json.pages
- def __post_init__(self) -> None:
- """规范化顶层图片缓存,确保 public middle_json 不再从 span 携带图片字节。"""
- if self._image_cache is None:
- self._image_cache = ImagePayloadCache()
- elif isinstance(self._image_cache, dict):
- self._image_cache = ImagePayloadCache(self._image_cache)
-
@staticmethod
def from_dict(d: dict[str, Any]) -> ParseResult:
if not isinstance(d, dict):
@@ -218,23 +205,6 @@ class ParseResult:
json.dumps(model_output, ensure_ascii=False, indent=2),
)
- for img_path, img_bytes in self.images().items():
- writer.write(img_path, img_bytes)
-
- def images(self) -> dict[str, bytes]:
- assert isinstance(self._image_cache, ImagePayloadCache)
- return self._image_cache.images()
-
- def attach_export_images(self, images: dict[str, bytes]) -> None:
- """绑定 API sidecar 下载到的图片字节,供后续 images/save 统一写出。"""
- assert isinstance(self._image_cache, ImagePayloadCache)
- self._image_cache.update(images)
-
- def refresh_export_cache(self, *, preserve_images: bool = False) -> None:
- """保留历史方法名;当前仅按需清空顶层图片缓存。"""
- if not preserve_images:
- self._image_cache = ImagePayloadCache()
-
def export_pages(self) -> list[PageInfo]:
"""返回页面树副本,避免调用方修改污染 ParseResult.pages。"""
return deepcopy(self.pages)
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index f8fc4acd..6ad3c836 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import base64
import binascii
-import hashlib
from pathlib import Path, PureWindowsPath
import re
import xml.etree.ElementTree as ElementTree
@@ -229,48 +228,6 @@ def extract_mineru_generated_svg_fallback(payload: bytes) -> tuple[bytes, int, i
return fallback, width, height
-def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:
- """复用旧裁图路径哈希规则,根据逻辑路径生成稳定图片文件名。"""
- ext = normalize_image_extension(image_format)
- return f"{path_key}.{ext}"
-
-
-class ImagePayloadCache:
- """保存运行时图片载荷,public middle_json 只通过 image_path 引用图片。"""
-
- def __init__(self, images: dict[str, bytes] | None = None) -> None:
- self._images: dict[str, bytes] = dict(images or {})
-
- def register_bytes(
- self,
- img_bytes: bytes,
- image_format: str = "JPEG",
- *,
- path_key: str | None = None,
- image_path: str | None = None,
- ) -> str:
- """登记图片字节,优先使用显式路径,其次使用逻辑 path_key 生成稳定路径。"""
- if image_path:
- img_path = image_path
- elif path_key:
- img_path = image_path_from_key(path_key, image_format)
- else:
- ext = normalize_image_extension(image_format)
- payload_key = base64.b64encode(img_bytes).decode("ascii")
- img_path = f"{hashlib.sha256(payload_key.encode('utf-8')).hexdigest()}.{ext}"
- self._images[img_path] = img_bytes
- return img_path
-
- def update(self, images: dict[str, bytes]) -> None:
- """合并外部 sidecar 图片字节,供 API client 绑定远端输出。"""
- for image_path, image_bytes in images.items():
- self.register_bytes(image_bytes, image_path=image_path)
-
- def images(self) -> dict[str, bytes]:
- """返回 image_path 到图片字节的副本,避免调用方改写内部缓存。"""
- return dict(self._images)
-
-
def validate_image_sidecar_path(image_path: str) -> str:
"""校验图片 sidecar 路径只能是安全的相对子路径,并返回规范化 POSIX 路径。"""
posix_path = Path(image_path)
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index e17cdd21..b8bae2ec 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -2,7 +2,6 @@ from __future__ import annotations
from _span_test_utils import inline as _inline, inline_text
import asyncio
-import base64
import hashlib
import json
import subprocess
@@ -58,7 +57,6 @@ from mineru.doclib.services.parse_svc import (
filter_pages_by_user_range,
load_pages_from_done_batches,
parse_batch_json_path,
- parse_image_sidecar_dir,
)
from mineru.doclib.services.scan_svc import ScanService
from mineru.doclib.services.search_svc import SearchService
@@ -86,7 +84,6 @@ from mineru.types import (
TextBlock,
Tier,
)
-from mineru.utils.image_payload import ImagePayloadCache
from mineru.version import __version__
@@ -304,23 +301,6 @@ def _image_page(image_path: str) -> PageInfo:
return PageInfo(page_idx=0, blocks=[image_block])
-def _image_result(image_path: str, image_bytes: bytes = b"image-bytes") -> ParseResult:
- """构造带顶层图片缓存的 ParseResult,避免在 span 中保留 base64。"""
- image_cache = ImagePayloadCache()
- image_cache.register_bytes(image_bytes, "jpeg", image_path=image_path)
- return ParseResult(
- middle_json=MiddleJson(
- pages=[_image_page(image_path)],
- is_full_document=True,
- file_suffix="pdf",
- effort="medium",
- parse_mode="txt",
- mineru_version=__version__,
- ),
- _image_cache=image_cache,
- )
-
-
def _text_page(text: str) -> PageInfo:
block = TextBlock(type=BlockType.TEXT, index=0, bbox=(0.0, 0.0, 0.1, 0.1), content=_inline(text))
return PageInfo(page_idx=0, blocks=[block])
@@ -2198,7 +2178,7 @@ def test_remap_api_result_pages_to_non_contiguous_page_range() -> None:
assert [page.page_idx for page in result.pages] == [10, 12, 13]
-def test_remap_api_result_pages_refreshes_attached_export_cache() -> None:
+def test_remap_api_result_pages_remaps_page_indices() -> None:
from mineru.doclib.services.parse_svc import _remap_api_result_pages_to_page_range
result = ParseResult.from_dict(
@@ -2212,12 +2192,10 @@ def test_remap_api_result_pages_refreshes_attached_export_cache() -> None:
"mineru_version": __version__,
}
)
- result.attach_export_images({"images/figure.png": b"figure-bytes"})
_remap_api_result_pages_to_page_range(result, "5")
assert result.to_dict()["pages"][0]["page_idx"] == 4
- assert result.images() == {"images/figure.png": b"figure-bytes"}
def test_remap_api_result_pages_rejects_count_mismatch() -> None:
@@ -4766,80 +4744,6 @@ def test_process_doc_normalizes_full_document_range_from_actual_pages(tmp_path:
assert len(json.loads(batch_path.read_text(encoding="utf-8"))["pages"]) == 12
-def test_process_doc_writes_cached_image_sidecars(tmp_path: Path) -> None:
- sha256 = "c" * 64
- task = {
- "id": 1,
- "sha256": sha256,
- "tier": "flash",
- "page_range": "1",
- "status": "parsing",
- "privacy": "local",
- }
- parses = [
- {
- **task,
- "error_code": None,
- "error_msg": None,
- "done_at": None,
- "locked_at": 123,
- "updated_at": 123,
- }
- ]
- source = tmp_path / "doc.pdf"
- source.write_bytes(b"%PDF-1.4\n")
- db = _FakeDB(
- parses=parses,
- file_row={
- "path": str(source),
- "sha256": sha256,
- "status": "active",
- "filename": "doc.pdf",
- "title": "",
- "author": "",
- },
- )
- service = ParseService(db=db, fts=_FakeFTS(), config_svc=None, data_dir=str(tmp_path), parse_lock_timeout_sec=1800)
-
- async def _parse(file_row: dict, tier: Tier, page_range: str) -> ParseResult:
- return _image_result("figures/cache-hit.jpg", b"fresh-image")
-
- async def _skip_fts(*args: object, **kwargs: object) -> None:
- return None
-
- async def _skip_docs_meta(*args: object, **kwargs: object) -> None:
- return None
-
- service._parse_via_local = _parse # type: ignore[method-assign]
- service._maybe_update_fts = _skip_fts # type: ignore[method-assign]
- service._maybe_update_docs_meta = _skip_docs_meta # type: ignore[method-assign]
-
- success = asyncio.run(service.process_doc(task))
-
- assert success is True
- sidecar = tmp_path / "parsed" / sha256[:2] / sha256 / "flash" / "images" / "figures" / "cache-hit.jpg"
- assert sidecar.read_bytes() == b"fresh-image"
- batch_path = Path(parse_batch_json_path(str(tmp_path), sha256, "flash", "1", parses[0]["done_at"]))
- batch = json.loads(batch_path.read_text(encoding="utf-8"))
- image_body = batch["pages"][0]["blocks"][0]["content"][0]
- assert image_body["image_path"] == "figures/cache-hit.jpg"
- assert "image_base64" not in image_body
-
-
-def test_load_pages_from_done_batches_keeps_existing_image_sidecar(tmp_path: Path) -> None:
- sha256 = "e" * 64
- tier = "standard"
- page = _image_page("figures/existing.jpg")
- _write_batch(tmp_path, sha256, tier, "1", 1000, [page.to_dict(skip_defaults=True)])
- sidecar = tmp_path / "parsed" / sha256[:2] / sha256 / tier / "images" / "figures" / "existing.jpg"
- sidecar.parent.mkdir(parents=True, exist_ok=True)
- sidecar.write_bytes(b"existing-sidecar")
-
- load_pages_from_done_batches(str(tmp_path), sha256, tier, [{"page_range": "1", "done_at": 1000}])
-
- assert sidecar.read_bytes() == b"existing-sidecar"
-
-
def test_locator_after_uses_resolved_tier_when_locator_tier_is_absent() -> None:
locator = _LocatorParts(short_id="eeeeeee", tier=None, page_no=1, block_no=2, char_offset=8)
@@ -4929,13 +4833,10 @@ def test_doc_content_marker_uses_document_page_count_only(
],
)
def test_doclib_image_renderer_uses_type_label_and_canonical_locator(
- tmp_path: Path,
block_type: str,
label: str,
) -> None:
renderer = _make_doclib_image_renderer(
- data_dir=str(tmp_path),
- sha256="e" * 64,
short_id="eeeeeee",
tier="standard",
page_no=2,
@@ -4945,10 +4846,8 @@ def test_doclib_image_renderer_uses_type_label_and_canonical_locator(
assert renderer(block) == f"![{label}](doc:eeeeeee/tier:standard/page:2/block:4)"
-def test_doclib_image_renderer_rejects_non_finite_bbox(tmp_path: Path) -> None:
+def test_doclib_image_renderer_rejects_non_finite_bbox() -> None:
renderer = _make_doclib_image_renderer(
- data_dir=str(tmp_path),
- sha256="e" * 64,
short_id="eeeeeee",
tier="standard",
page_no=1,
@@ -4982,24 +4881,28 @@ def test_find_block_by_no_ignores_conflicting_child_indexes() -> None:
@pytest.mark.parametrize(
- ("sidecar_exists", "expected_target"),
+ ("has_base64", "expected_target"),
[(True, "doc:eeeeeee/tier:standard/page:1/block:1"), (False, "")],
)
-def test_progressive_markdown_uses_sidecar_availability_for_bboxless_blocks(
+def test_progressive_markdown_uses_base64_availability_for_bboxless_blocks(
tmp_path: Path,
- sidecar_exists: bool,
+ has_base64: bool,
expected_target: str,
) -> None:
sha256 = "e" * 64
tier = "standard"
- page = _image_page("figures/rendered.jpg")
- page.blocks[0].bbox = None
- page.blocks[0].content[0].bbox = None # type: ignore[union-attr]
+ data_uri = (
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
+ )
+ body = ImageBodyBlock(
+ type=BlockType.IMAGE_BODY,
+ index=0,
+ bbox=None,
+ content="",
+ image_base64=data_uri if has_base64 else None,
+ )
+ page = PageInfo(page_idx=0, blocks=[ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])])
_write_batch(tmp_path, sha256, tier, "1", 1000, [page.to_dict(skip_defaults=True)], file_suffix="docx")
- if sidecar_exists:
- sidecar = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier)) / "figures/rendered.jpg"
- sidecar.parent.mkdir(parents=True)
- sidecar.write_bytes(b"image")
db = _FakeDB(
parses=[{"sha256": sha256, "tier": tier, "status": "done", "page_range": "1", "done_at": 1000}],
file_row=None,
@@ -5022,21 +4925,16 @@ def test_progressive_markdown_uses_sidecar_availability_for_bboxless_blocks(
response = asyncio.run(server._execute_read_plan(plan))
assert f"![Image block]({expected_target})" in response.content
- assert "figures/rendered.jpg" not in response.content
-def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
+def test_doclib_office_image_asset_reads_base64(tmp_path: Path) -> None:
sha256 = "f" * 64
tier = "standard"
- image_dir = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier))
- image_path = "figures/office.png"
- sidecar = image_dir / image_path
- sidecar.parent.mkdir(parents=True)
- sidecar.write_bytes(
- base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
+ data_uri = (
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
)
- body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_base64=data_uri)
image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])
page = PageInfo(page_idx=0, blocks=[image_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
@@ -5072,26 +4970,23 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
(BlockType.EQUATION, None),
],
)
-def test_doclib_visual_block_asset_reads_cached_sidecar(
+def test_doclib_visual_block_asset_reads_base64(
tmp_path: Path,
block_type: str,
body_type: str | None,
) -> None:
sha256 = "f" * 64
tier = "standard"
- image_path = f"figures/{block_type}.png"
- sidecar = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier)) / image_path
- sidecar.parent.mkdir(parents=True)
- sidecar.write_bytes(
- base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
+ data_uri = (
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
)
if body_type is None:
- visual_block = EquationBlock(type=BlockType.EQUATION, index=0, bbox=None, content="", image_path=image_path)
+ visual_block = EquationBlock(type=BlockType.EQUATION, index=0, bbox=None, content="", image_base64=data_uri)
elif block_type == BlockType.TABLE:
- body = TableBodyBlock(type=BlockType.TABLE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ body = TableBodyBlock(type=BlockType.TABLE_BODY, index=0, bbox=None, content="", image_base64=data_uri)
visual_block = TableBlock(type=BlockType.TABLE, index=0, bbox=None, content=[body])
else:
- body = ChartBodyBlock(type=BlockType.CHART_BODY, index=0, bbox=None, content="", image_path=image_path)
+ body = ChartBodyBlock(type=BlockType.CHART_BODY, index=0, bbox=None, content="", image_base64=data_uri)
visual_block = ChartBlock(type=BlockType.CHART, index=0, bbox=None, content=[body])
page = PageInfo(page_idx=0, blocks=[visual_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
@@ -5195,15 +5090,11 @@ def test_doclib_image_block_locator_crops_source_image_at_original_resolution(tm
def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path) -> None:
sha256 = "f" * 64
tier = "standard"
- image_dir = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier))
- image_path = "figures/office.png"
- sidecar = image_dir / image_path
- sidecar.parent.mkdir(parents=True)
- sidecar.write_bytes(
- base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
+ data_uri = (
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
)
- body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_base64=data_uri)
image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])
page = PageInfo(page_idx=0, blocks=[image_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
@@ -5231,11 +5122,10 @@ def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path
assert image.format == "JPEG"
-def test_doclib_office_image_asset_missing_sidecar_reports_asset_not_available(tmp_path: Path) -> None:
+def test_doclib_office_image_asset_missing_payload_reports_asset_not_available(tmp_path: Path) -> None:
sha256 = "f" * 64
tier = "basic"
- image_path = "figures/missing.png"
- body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="", image_path=image_path)
+ body = ImageBodyBlock(type=BlockType.IMAGE_BODY, index=0, bbox=None, content="")
image_block = ImageBlock(type=BlockType.IMAGE, index=0, bbox=None, content=[body])
page = PageInfo(page_idx=0, blocks=[image_block])
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
diff --git a/tests/unittest/test_doclib_telemetry_core.py b/tests/unittest/test_doclib_telemetry_core.py
index 2ca4935a..e4a71a3a 100644
--- a/tests/unittest/test_doclib_telemetry_core.py
+++ b/tests/unittest/test_doclib_telemetry_core.py
@@ -407,70 +407,6 @@ def test_parse_service_process_doc_records_task_metrics(tmp_path) -> None:
asyncio.run(_run())
-def test_parse_service_requires_result_images_method(tmp_path) -> None:
- """验证 doclib 不再兼容缺少 images() 的解析结果替身。"""
-
- class _Fts:
- async def get_tier(self, sha256: str) -> str | None:
- return None
-
- async def replace(self, **kwargs) -> None:
- return None
-
- async def upsert_filename(self, *args, **kwargs) -> None:
- return None
-
- class _ResultWithoutImages:
- def to_dict(self, *, skip_defaults: bool = True) -> dict:
- return {"pages": [{"page_idx": 0, "blocks": []}]}
-
- def markdown(self, *, add_markers: bool = False) -> str:
- return "content"
-
- class _ParseService(ParseService):
- async def _parse_via_local(self, file_row, tier, page_range):
- return _ResultWithoutImages()
-
- async def _run() -> None:
- db = DatabaseManager(str(tmp_path / "doclib.db"))
- await db.initialize()
- store = TelemetryStore(db)
- telemetry = TelemetryService(store)
- await telemetry.initialize()
- parse_svc = _ParseService(
- db,
- _Fts(),
- ConfigService(db),
- str(tmp_path),
- parse_lock_timeout_sec=30,
- telemetry_svc=telemetry,
- )
- now = 1_700_000_000_000
- (tmp_path / "a.pdf").write_bytes(b"%PDF-1.4\n")
- await db.execute(
- "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?)",
- ("sha", "sha", 1, "pdf", 1, now, now),
- )
- await db.execute(
- "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, first_seen_at, updated_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
- (str(tmp_path / "a.pdf"), "a.pdf", "pdf", 1, now, "sha", now, now),
- )
- await db.execute(
- "INSERT INTO parses (sha256, tier, page_range, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
- ("sha", "flash", "1", "parsing", now, now),
- )
- task = await db.fetchone("SELECT * FROM parses WHERE sha256=?", ("sha",))
-
- assert await parse_svc.process_doc(task) is False
- updated = await db.fetchone("SELECT status, error_code FROM parses WHERE sha256=?", ("sha",))
- assert updated["status"] == "failed"
- assert updated["error_code"] == "parse_json_write_failed"
-
- asyncio.run(_run())
-
-
def test_scan_service_process_scan_records_task_metrics(tmp_path) -> None:
class _ScanService(ScanService):
async def _run_scan(self, task):
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 5c0b1ad4..e883f9f7 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -1263,7 +1263,6 @@ def test_html_local_base_images_styles_and_escape_are_bounded(tmp_path: Path) ->
markdown = result.markdown()
assert "hidden css" not in markdown
assert "Outside" in markdown
- assert outside.read_bytes() not in result.images().values()
exported = result.middle_json.export(tmp_path / "export")
assert len(exported.image_paths) == 1
assert exported.image_paths[0].read_bytes() == image_path.read_bytes()
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index f0367223..378a5940 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -48,11 +48,6 @@ def test_kit_main_configures_standard_streams_before_running_app(monkeypatch: py
assert calls == ["configure", "app"]
-def _assert_unsafe_sidecar_error(output: str) -> None:
- """归一化 Typer/Click 自动换行后的错误输出,再匹配 sidecar 安全错误。"""
- assert "Unsafe image sidecar path" in " ".join(output.split())
-
-
def _fake_apply_chat_template(_processor: Any, _config: Any, _prompt: Any, *_args: Any, **_kwargs: Any) -> str:
return "formatted"
@@ -1647,184 +1642,6 @@ def test_cli_old_async_hybrid_branch_keeps_effort(monkeypatch: Any, tmp_path: Pa
assert os.environ["MINERU_VLM_TABLE_ENABLE"] == "sentinel-table"
-def test_parse_single_file_middle_json_writes_image_sidecars(
- monkeypatch: Any,
- tmp_path: Path,
-) -> None:
- source = tmp_path / "demo.pdf"
- output = tmp_path / "out.json"
- source.write_bytes(b"%PDF-1.7\n")
-
- class _Result:
- def to_json(self) -> str:
- """返回带图片引用的 public middle_json。"""
- return '{"pages":[{"para_blocks":[{"lines":[{"spans":[{"image_path":"figure.png"}]}]}]}]}'
-
- def images(self) -> dict[str, bytes]:
- """返回需要随 public middle_json 一起落盘的图片 sidecar。"""
- return {"figure.png": b"figure-bytes"}
-
- monkeypatch.setattr(parse, "local_parse", lambda *args, **kwargs: _Result())
-
- result = runner.invoke(
- app,
- ["parse", str(source), "-o", str(output), "--format", "middle_json"],
- )
-
- assert result.exit_code == 0
- payload = output.read_text(encoding="utf-8")
- assert '"image_path":"figure.png"' in payload
- assert "image_base64" not in payload
- assert (tmp_path / "figure.png").read_bytes() == b"figure-bytes"
-
-
-def test_parse_single_file_middle_json_rejects_parent_sidecar_paths(
- monkeypatch: Any,
- tmp_path: Path,
-) -> None:
- """拒绝 API 或解析结果提供的父目录逃逸 sidecar 路径。"""
- source = tmp_path / "demo.pdf"
- output = tmp_path / "out.json"
- escaped = tmp_path / "escape.png"
- source.write_bytes(b"%PDF-1.7\n")
-
- class _Result:
- def to_json(self) -> str:
- """返回引用逃逸路径的 public middle_json。"""
- return '{"pages":[]}'
-
- def images(self) -> dict[str, bytes]:
- """模拟远端返回包含 .. 的图片 sidecar 路径。"""
- return {"../escape.png": b"escape-bytes"}
-
- monkeypatch.setattr(parse, "local_parse", lambda *args, **kwargs: _Result())
-
- result = runner.invoke(
- app,
- ["parse", str(source), "-o", str(output), "--format", "middle_json"],
- )
-
- assert result.exit_code == 1
- _assert_unsafe_sidecar_error(result.output)
- assert not escaped.exists()
-
-
-def test_parse_single_file_middle_json_rejects_absolute_sidecar_paths(
- monkeypatch: Any,
- tmp_path: Path,
-) -> None:
- """拒绝 API 或解析结果提供的绝对 sidecar 路径。"""
- source = tmp_path / "demo.pdf"
- output = tmp_path / "out.json"
- absolute = tmp_path / "absolute.png"
- source.write_bytes(b"%PDF-1.7\n")
-
- class _Result:
- def to_json(self) -> str:
- """返回普通 public middle_json 内容,重点验证 sidecar 路径。"""
- return '{"pages":[]}'
-
- def images(self) -> dict[str, bytes]:
- """模拟远端返回绝对图片 sidecar 路径。"""
- return {str(absolute): b"absolute-bytes"}
-
- monkeypatch.setattr(parse, "local_parse", lambda *args, **kwargs: _Result())
-
- result = runner.invoke(
- app,
- ["parse", str(source), "-o", str(output), "--format", "middle_json"],
- )
-
- assert result.exit_code == 1
- _assert_unsafe_sidecar_error(result.output)
- assert not absolute.exists()
-
-
-def test_parse_single_file_middle_json_rejects_windows_rooted_sidecar_paths(
- monkeypatch: Any,
- tmp_path: Path,
-) -> None:
- """拒绝 Windows rooted 形式的 sidecar 路径,避免跨平台逃逸。"""
- source = tmp_path / "demo.pdf"
- output = tmp_path / "out.json"
- source.write_bytes(b"%PDF-1.7\n")
-
- class _Result:
- def to_json(self) -> str:
- """返回普通 public middle_json 内容,重点验证 Windows 路径。"""
- return '{"pages":[]}'
-
- def images(self) -> dict[str, bytes]:
- """模拟远端返回 Windows rooted 图片 sidecar 路径。"""
- return {"\\escape.png": b"escape-bytes"}
-
- monkeypatch.setattr(parse, "local_parse", lambda *args, **kwargs: _Result())
-
- result = runner.invoke(
- app,
- ["parse", str(source), "-o", str(output), "--format", "middle_json"],
- )
-
- assert result.exit_code == 1
- _assert_unsafe_sidecar_error(result.output)
- assert not (tmp_path / "\\escape.png").exists()
-
-
-def test_parse_single_file_markdown_writes_image_sidecars(
- monkeypatch: Any,
- tmp_path: Path,
-) -> None:
- """markdown 单文件输出也要写出渲染结果引用的图片 sidecar。"""
- source = tmp_path / "demo.pdf"
- output = tmp_path / "out.md"
- source.write_bytes(b"%PDF-1.7\n")
-
- class _Result:
- def markdown(self) -> str:
- """返回带相对图片引用的 markdown 内容。"""
- return "![](figure.png)\n"
-
- def images(self) -> dict[str, bytes]:
- """返回 markdown 引用的图片 sidecar。"""
- return {"figure.png": b"figure-bytes"}
-
- monkeypatch.setattr(parse, "local_parse", lambda *args, **kwargs: _Result())
-
- result = runner.invoke(app, ["parse", str(source), "-o", str(output)])
-
- assert result.exit_code == 0
- assert output.read_text(encoding="utf-8") == "![](figure.png)\n"
- assert (tmp_path / "figure.png").read_bytes() == b"figure-bytes"
-
-
-def test_parse_single_file_markdown_rejects_unsafe_sidecar_paths(
- monkeypatch: Any,
- tmp_path: Path,
-) -> None:
- """markdown 补写 sidecar 时同样不能允许路径逃逸输出目录。"""
- source = tmp_path / "demo.pdf"
- output = tmp_path / "out.md"
- escaped = tmp_path / "escape.png"
- source.write_bytes(b"%PDF-1.7\n")
-
- class _Result:
- def markdown(self) -> str:
- """返回引用逃逸路径的 markdown 内容。"""
- return "![](../escape.png)\n"
-
- def images(self) -> dict[str, bytes]:
- """模拟远端或解析结果返回逃逸图片路径。"""
- return {"../escape.png": b"escape-bytes"}
-
- monkeypatch.setattr(parse, "local_parse", lambda *args, **kwargs: _Result())
-
- result = runner.invoke(app, ["parse", str(source), "-o", str(output)])
-
- assert result.exit_code == 1
- _assert_unsafe_sidecar_error(result.output)
- assert not escaped.exists()
-
-
def test_parse_output_replaces_surrogate_chars(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
output = tmp_path / "out.md"
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index 7f433e5e..41f0df29 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -8,7 +8,6 @@ from pydantic import ValidationError
from mineru.parser.base import ParseResult
from mineru.parser import MIDDLE_JSON_SCHEMA_VERSION
from mineru.types import BlockType, MiddleJson, PageFootnoteBlock, PageInfo, TableBlock, TableBodyBlock, TextBlock
-from mineru.utils.image_payload import ImagePayloadCache
from mineru.version import __version__
@@ -189,12 +188,7 @@ def test_parse_result_rejects_legacy_schema_versions(schema_version: str | None)
def test_parse_result_export_pages_returns_defensive_copy() -> None:
"""验证调用方修改导出页面副本时不会污染 ParseResult 内部状态。"""
- image_cache = ImagePayloadCache()
- image_path = image_cache.register_bytes(
- b"defensive-table-image",
- "png",
- image_path="images/table.png",
- )
+ image_path = "images/table.png"
page = PageInfo(
page_idx=0,
blocks=[
@@ -222,7 +216,6 @@ def test_parse_result_export_pages_returns_defensive_copy() -> None:
parse_mode="txt",
mineru_version=__version__,
),
- _image_cache=image_cache,
)
first_export = result.export_pages()
first_export[0].blocks[0].content[0].content = "mutated by caller"
@@ -232,5 +225,4 @@ def test_parse_result_export_pages_returns_defensive_copy() -> None:
exported_json = json.dumps(result.to_dict(), ensure_ascii=False)
assert image_path in second_content
- assert result.images() == {image_path: b"defensive-table-image"}
assert "mutated by caller" not in exported_json
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index a17f8a0f..588c7575 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -57,7 +57,6 @@ from mineru.types import (
select_parsing_rule_tier,
validate_tier,
)
-from mineru.utils.image_payload import ImagePayloadCache
from mineru.version import __version__
runner = CliRunner()
@@ -719,7 +718,7 @@ def test_api_client_ignores_legacy_detail_error_envelope() -> None:
assert exc_info.value.message.startswith("HTTP 400:")
-def test_api_client_reads_image_cache_from_zip(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_api_client_inlines_image_sidecar_from_zip(monkeypatch: pytest.MonkeyPatch) -> None:
parser = MinerUApiParser(api_url="http://localhost:8000", tier="standard", include_images=True)
middle_json = _current_payload([_current_image_page("images/chart.png")])
zip_ref = {"file_id": "file-zip", "bytes": 10}
@@ -740,7 +739,9 @@ def test_api_client_reads_image_cache_from_zip(monkeypatch: pytest.MonkeyPatch)
parser,
)
- assert result.images() == {"images/chart.png": b"chart-bytes"}
+ image_body = result.pages[0].blocks[0].content[0] # type: ignore[union-attr]
+ assert image_body.image_base64 == "data:image/png;base64," + base64.b64encode(b"chart-bytes").decode("ascii") # type: ignore[union-attr]
+ assert image_body.image_path is None # type: ignore[union-attr]
def test_api_client_downloads_model_output_from_zip(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -825,7 +826,8 @@ def test_api_client_accepts_legacy_official_layout_json(monkeypatch: pytest.Monk
assert len(result.pages) == 1
assert result.pages[0].blocks[0].type.value == "image"
- assert result.images() == {"chart.png": b"chart-bytes"}
+ image_body = result.pages[0].blocks[0].content[0]
+ assert image_body.image_base64 == "data:image/png;base64," + base64.b64encode(b"chart-bytes").decode("ascii") # type: ignore[union-attr]
def test_api_client_async_downloads_model_output_from_zip(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -868,8 +870,7 @@ def test_api_client_include_images_downloads_single_zip(monkeypatch: pytest.Monk
include_model_output=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")
+ image_path = "images/chart.png"
image_body = ImageBodyBlock(
type=BlockType.IMAGE_BODY,
index=0,
@@ -889,7 +890,7 @@ def test_api_client_include_images_downloads_single_zip(monkeypatch: pytest.Monk
archive.writestr(
"middle_json.json",
json.dumps(
- ParseResult(middle_json=_full_middle_json(page), _image_cache=image_cache).to_dict(),
+ ParseResult(middle_json=_full_middle_json(page)).to_dict(),
ensure_ascii=False,
),
)
@@ -920,7 +921,8 @@ def test_api_client_include_images_downloads_single_zip(monkeypatch: pytest.Monk
assert download_calls == [zip_ref]
assert result.pages[0].page_idx == 0
- assert result.images() == {"images/chart.png": b"chart-bytes"}
+ image_body = result.pages[0].blocks[0].content[0]
+ assert image_body.image_base64 == "data:image/png;base64," + base64.b64encode(b"chart-bytes").decode("ascii") # type: ignore[union-attr]
assert result._model_output == [[{"raw": "model"}]]
@@ -946,7 +948,9 @@ def test_api_client_does_not_read_image_cache_from_zip_unless_requested(monkeypa
parser,
)
- assert result.images() == {}
+ image_body = result.pages[0].blocks[0].content[0]
+ assert image_body.image_base64 is None # type: ignore[union-attr]
+ assert image_body.image_path == "images/chart.png" # type: ignore[union-attr]
assert result._model_output == [[{"raw": "model"}]]
@@ -1851,9 +1855,7 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(
output_format: str,
output_attr: str,
) -> None:
- img_bytes = b"rendered-image-bytes"
- image_cache = ImagePayloadCache()
- image_path = image_cache.register_bytes(img_bytes, "png", image_path="rendered.png")
+ image_path = "rendered.png"
image_body = ImageBodyBlock(
type=BlockType.IMAGE_BODY,
index=0,
@@ -1874,7 +1876,6 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(
blocks=[image_block],
)
),
- _image_cache=image_cache,
)
async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:
@@ -2088,47 +2089,6 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(
assert "\n " in model_output_text
-def test_api_server_zip_rejects_unsafe_image_sidecar_path(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- parse_result = ParseResult(
- middle_json=_full_middle_json(PageInfo(page_idx=0)),
- _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": "standard",
- "output_formats": ["zip"],
- }
- )
- rec = api_server.JobStore().create(request, file_store)
-
- asyncio.run(
- api_server._run_job(
- rec,
- request,
- file_store,
- ocr_mode="auto",
- image_analysis=True,
- allow_local_source=True,
- )
- )
-
- 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,