Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
Fix read image output format handling
jinzhenj3aade22ae227
diff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.mdindex 640bd83a..a217cf36 100644--- a/docs/next/cli/mineru-e2e-test-cases.md+++ b/docs/next/cli/mineru-e2e-test-cases.md@@ -1581,6 +1581,8 @@ mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_- exit code = 0- 输出包含 `Written to` 或等价成功信息- 输出路径为命令指定路径+ - 输出文件后缀只允许 `.png`、`.jpg`、`.jpeg`、`.webp`+ - 输出文件真实编码必须与后缀匹配- 如果该 locator 不支持 image 输出:- exit code != 0- 输出包含 unsupported、not available、no image 或等价错误@@ -2818,18 +2820,39 @@ mineru read "doc:<short_id>/tier:flash/page:1" --output - --json- 不创建名为 `-` 的文件- stdout 不包含 `Written to`、Rich 表格、Markdown 正文或其它人类提示文本+补充分支:++```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output - --json+```++预期:++- exit code != 0+- stdout 为 JSON error envelope+- `error.code` = `image_output_extension_unsupported`+- `error.param` = `output`+- 不创建名为 `-` 的文件+### OUTPUT-002 read image output 后缀边界命令模板:```bash+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page.png"+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page.jpg"+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page.jpeg"+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page.webp"+mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page"mineru read "doc:<short_id>/tier:flash/page:1" --format image --output "$MINERU_E2E_FIXTURE_DIR/output-dir/page-as-md.md"```预期:-- 如果 image 输出支持任意后缀,exit code = 0,输出文件内容应为图片资产字节-- 如果要求后缀匹配,exit code != 0,输出包含 invalid extension、mime、image 或等价错误+- `.png`、`.jpg`、`.jpeg`、`.webp` 均 exit code = 0+- 输出文件真实编码必须分别匹配 PNG、JPEG、JPEG、WebP+- 无后缀和 `.md` 均 exit code != 0+- JSON 模式下错误为 JSON error envelope,`error.code` = `image_output_extension_unsupported`- 不包含 Python traceback### CONCURRENCY-001 并发 parse forcediff --git a/docs/next/cli/mineru-read.md b/docs/next/cli/mineru-read.mdindex b2e3d6d5..0c638176 100644--- a/docs/next/cli/mineru-read.md+++ b/docs/next/cli/mineru-read.md@@ -60,7 +60,7 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}| `--json` | bool | false | 将整个 CLI 响应包装为 JSON || `--limit` | int | `30000` | 文本输出软字符上限 || `--context` | int | `0` | 按 locator 周围扩展上下文 |-| `--output`, `-o` | path | 不传 | 将返回内容或 image asset 写入本地路径 |+| `--output`, `-o` | path | 不传 | 将返回内容或 image asset 写入本地路径;image 只支持 `.png`、`.jpg`、`.jpeg`、`.webp` || `--no-marker` | bool | false | 关闭 continuation marker |语义区分:@@ -115,6 +115,16 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}如果不带 `--output`,image 模式默认输出 server 返回的临时 asset path。+如果带 `--output`,CLI 根据输出路径后缀决定请求的图片编码:++| 后缀 | server `image_format` |+|------|------------------------|+| `.png` | `png` |+| `.jpg`, `.jpeg` | `jpeg` |+| `.webp` | `webp` |++image 输出路径必须带上述后缀。无后缀、其它后缀以及 `--output -` 都返回 `image_output_extension_unsupported`。CLI 不做图片转码;server 按 `image_format` 生成临时 asset,CLI 只把该 asset copy 到用户指定路径。+## 7. JSON 输出`--json` 时,CLI 输出 `DocContentResponse`。diff --git a/docs/next/decisions/0014-mineru-read-command.md b/docs/next/decisions/0014-mineru-read-command.mdindex 66f5fdc7..700daf58 100644--- a/docs/next/decisions/0014-mineru-read-command.md+++ b/docs/next/decisions/0014-mineru-read-command.md@@ -114,7 +114,9 @@ Office 的 image 输出规则:- 如果 Middle JSON 中只有 `span.image_path`,仅在该 path 可访问时作为 fallback。- 当前 doclib parsed 目录只持久化 JSON,不保证已额外持久化 Office image 文件;因此不能依赖 `ParseResult.save()` 产物存在。-默认情况下,image 输出打印 asset path。传入 `--output` 时,由 CLI 在 client 侧把 server 返回的 asset copy 到指定路径。传入 `--json` 时输出完整 `DocContentResponse`。+默认情况下,image 输出打印 asset path。传入 `--output` 时,CLI 先根据输出路径后缀选择 `image_format`,由 server 生成匹配编码的临时 asset,再由 CLI 在 client 侧 copy 到指定路径。传入 `--json` 时输出完整 `DocContentResponse`。++image 输出只接受 `.png`、`.jpg`、`.jpeg`、`.webp` 输出路径。无后缀、其它后缀以及 `--output -` 都在 CLI 参数校验阶段返回 `image_output_extension_unsupported`。CLI 不负责图片转码。## 响应模型扩展@@ -411,6 +413,7 @@ def read_content(context: int = 0,limit: int = 30000,format: Literal["markdown", "image"] = "markdown",+ image_format: Literal["jpeg", "png", "webp"] = "jpeg",no_marker: bool = False,) -> DocContentResponse: ...```@@ -419,10 +422,10 @@ HTTP 路由:```httpGET /api/v1/content?locator=doc:ab12cd3/tier:standard/page:4&format=markdown&limit=30000-GET /api/v1/content?locator=doc:ab12cd3/tier:standard/page:4/block:12&format=image+GET /api/v1/content?locator=doc:ab12cd3/tier:standard/page:4/block:12&format=image&image_format=png```-P0 不为 locator-first content API 提供 POST export。`GET /api/v1/content` 可以在 server 内部生成临时 image asset,但不接受 client 指定的 output path。CLI `read --output` 是 client 侧文件写入/copy 行为,不是 doclib HTTP API 行为。+P0 不为 locator-first content API 提供 POST export。`GET /api/v1/content` 可以在 server 内部生成临时 image asset,并接受 `image_format=jpeg|png|webp` 控制 asset 编码,但不接受 client 指定的 output path。CLI `read --output` 是 client 侧文件写入/copy 行为,不是 doclib HTTP API 行为。实现时在 Interface 中定义同步和异步方法,再由 client/server 使用相同签名实现。diff --git a/docs/next/decisions/0015-cli-output-json-composition.md b/docs/next/decisions/0015-cli-output-json-composition.mdindex 00fa18c6..f93ce23a 100644--- a/docs/next/decisions/0015-cli-output-json-composition.md+++ b/docs/next/decisions/0015-cli-output-json-composition.md@@ -143,12 +143,13 @@ mineru read <locator> --output out.md --json## `--output -`-`--output -` 表示输出到 stdout,等价于不指定 `--output`。+`--output -` 表示输出到 stdout,等价于不指定 `--output`。该规则只适用于文本类输出;`read --format image --output -` 不支持,因为图片二进制不写 stdout。规则:- `mineru parse ... --output -` 输出内容到 stdout。-- `mineru read ... --output -` 输出内容或 asset path 到 stdout。+- `mineru read ... --output -` 在 markdown/text 输出时输出内容到 stdout。+- `mineru read ... --format image --output -` 返回 `image_output_extension_unsupported`。- `--output - --json` 时,stdout 仍输出 JSON 响应,不写文件,也不新增 `output` 字段。- 不创建名为 `-` 的文件。@@ -212,6 +213,7 @@ Typer 在参数解析阶段产生的错误可以保持框架默认输出;但- `mineru parse --output PATH --json` 需要保持稳定的 `parse --json` 顶层结构,并增加 `output` 字段;不能输出 `Written to ...`。- `mineru read --output PATH --json` 需要保持稳定的 `read --json` 顶层结构,并增加 `output` 字段;不能静默忽略 `--output`。+- `mineru read --format image --output PATH` 应只接受 `.png`、`.jpg`、`.jpeg`、`.webp`,并让 server 生成匹配编码的 asset 后再 copy。- `parse` 和 `read` 的 help 文案应说明:- `--output` 可自动创建父目录。- 与 `--json` 同时指定时,stdout 输出写入结果 JSON。diff --git a/mineru/cli/commands/read.py b/mineru/cli/commands/read.pyindex e4a69e3f..6ab9d97f 100644--- a/mineru/cli/commands/read.py+++ b/mineru/cli/commands/read.py@@ -10,7 +10,7 @@ from typing import Literalimport typerfrom ...doclib.client import DoclibClient-from ...doclib.types import ContentNextRequest, DocContentResponse+from ...doclib.types import ContentNextRequest, DocContentResponse, ImageFormatfrom ...errors import MineruErrorfrom ..contracts import CliContext, CliResultfrom ..runtime import cli_ok, run_cli@@ -57,13 +57,25 @@ def _read(no_marker: bool,json_mode: bool,) -> DocContentResponse | dict[str, object] | CliResult[ReadTextOutput] | CliResult[None]:- content = DoclibClient(timeout=60).read_content(- locator,- context=context,- limit=limit,- format=format,- no_marker=no_marker,- )+ image_format = _image_format_for_output(format=format, output=output) if format == "image" else "jpeg"+ client = DoclibClient(timeout=60)+ if format == "image":+ content = client.read_content(+ locator,+ context=context,+ limit=limit,+ format=format,+ image_format=image_format,+ no_marker=no_marker,+ )+ else:+ content = client.read_content(+ locator,+ context=context,+ limit=limit,+ format=format,+ no_marker=no_marker,+ )return _prepare_read_output(content, json_mode=json_mode, output=output, no_marker=no_marker)@@ -123,6 +135,29 @@ def _render_read_text(data: ReadTextOutput) -> str:return data.text+def _image_format_for_output(*, format: Literal["markdown", "image"], output: str | None) -> ImageFormat:+ if format != "image" or output is None:+ return "jpeg"+ if output == "-":+ raise MineruError(+ "image_output_extension_unsupported",+ "Image output requires a file path ending with .png, .jpg, .jpeg, or .webp; stdout is not supported.",+ "output",+ )+ suffix = Path(output).suffix.lower()+ if suffix == ".png":+ return "png"+ if suffix in {".jpg", ".jpeg"}:+ return "jpeg"+ if suffix == ".webp":+ return "webp"+ raise MineruError(+ "image_output_extension_unsupported",+ "Image output path must end with .png, .jpg, .jpeg, or .webp.",+ "output",+ )++def _read_next_marker(next_request: ContentNextRequest) -> str | None:if not next_request.locator:return Nonediff --git a/mineru/doclib/base.py b/mineru/doclib/base.pyindex 4e98c155..d00ff83d 100644--- a/mineru/doclib/base.py+++ b/mineru/doclib/base.py@@ -21,6 +21,7 @@ from .types import (DocContentExportResponse,DocContentResponse,ContentFormat,+ ImageFormat,DocInfo,ExcludeRuleInfo,ExcludeRuleListResponse,@@ -287,6 +288,7 @@ class DoclibInterface(ABC):context: int = 0,limit: int = 30000,format: ContentFormat = "markdown",+ image_format: ImageFormat = "jpeg",no_marker: bool = False,) -> DocContentResponse:"""Render stored doc content from a stable content locator.@@ -667,6 +669,7 @@ class AsyncDoclibInterface(ABC):context: int = 0,limit: int = 30000,format: ContentFormat = "markdown",+ image_format: ImageFormat = "jpeg",no_marker: bool = False,) -> DocContentResponse:"""Async version of ``DoclibInterface.read_content``."""diff --git a/mineru/doclib/client.py b/mineru/doclib/client.pyindex 0c029752..fdf8f946 100644--- a/mineru/doclib/client.py+++ b/mineru/doclib/client.py@@ -34,6 +34,7 @@ from .types import (ConfigUnsetResponse,ConfigValueResponse,ContentFormat,+ ImageFormat,DocContentExportRequest,DocContentExportResponse,DocContentResponse,@@ -255,6 +256,7 @@ class DoclibClient(DoclibInterface):context: int = 0,limit: int = 30000,format: ContentFormat = "markdown",+ image_format: ImageFormat = "jpeg",no_marker: bool = False,) -> DocContentResponse:return self._request_model(@@ -264,6 +266,7 @@ class DoclibClient(DoclibInterface):"context": context,"limit": limit,"format": format,+ "image_format": image_format,"no_marker": no_marker,},)diff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 7aadb17e..1f3fd2bd 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -98,6 +98,7 @@ from .types import (FindResult,ForgetPathRequest,ForgetPathResponse,+ ImageFormat,InvalidateRequest,InvalidateResponse,ListDocsResponse,@@ -167,6 +168,7 @@ class _ReadPlan:limit: intformat: ContentFormatno_marker: bool+ image_format: ImageFormat = "jpeg"target: ContentCursor | None = Nonenext_mode: str = "parse"@@ -396,7 +398,9 @@ class DoclibServer(AsyncDoclibInterface):short_id = doc_row["short_id"] if doc_row else await self._short_id_for_sha256(sha256)count = await self.state.parse_svc.invalidate(sha256, request.tier)- return InvalidateResponse(target=request.target, sha256=sha256, short_id=short_id, tier=request.tier, invalidated_count=count)+ return InvalidateResponse(+ target=request.target, sha256=sha256, short_id=short_id, tier=request.tier, invalidated_count=count+ )@route("POST", "/forget", tags=("files",))async def forget_path(self, request: ForgetPathRequest) -> ForgetPathResponse:@@ -566,6 +570,7 @@ class DoclibServer(AsyncDoclibInterface):context: int = 0,limit: int = 30000,format: ContentFormat = "markdown",+ image_format: ImageFormat = "jpeg",no_marker: bool = False,) -> DocContentResponse:start_ms = _now_ms()@@ -578,6 +583,7 @@ class DoclibServer(AsyncDoclibInterface):context=context,limit=limit,format=format,+ image_format=image_format,no_marker=no_marker,))@@ -633,6 +639,7 @@ class DoclibServer(AsyncDoclibInterface):context: int,limit: int,format: ContentFormat,+ image_format: ImageFormat,no_marker: bool,) -> _ReadPlan:limit = max(1, limit)@@ -661,6 +668,7 @@ class DoclibServer(AsyncDoclibInterface):context=context,limit=limit,format=format,+ image_format=image_format,no_marker=no_marker,target=ContentCursor(short_id=doc["short_id"],@@ -695,7 +703,9 @@ class DoclibServer(AsyncDoclibInterface):finished_dims = dims | {"status": "succeeded"}await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)await _record_telemetry_duration(self.state, "content.duration_bucket.count", start_ms, dimensions=finished_dims)- return DocContentExportResponse(sha256=doc["sha256"], short_id=doc["short_id"], tier=request.tier, output=output_path)+ return DocContentExportResponse(+ sha256=doc["sha256"], short_id=doc["short_id"], tier=request.tier, output=output_path+ )except Exception:finished_dims = dims | {"status": "failed"}await _record_telemetry_count(self.state, "content.finished.count", dimensions=finished_dims)@@ -1194,6 +1204,7 @@ class DoclibServer(AsyncDoclibInterface):limit=plan.limit,locator=plan.locator,context=plan.context,+ image_format=plan.image_format,),content_ranges=[ContentRange(page_range=str(plan.target.page_no), start=target_ref, end=target_ref)],truncated=False,@@ -1283,7 +1294,7 @@ class DoclibServer(AsyncDoclibInterface):with PDFDocument(pdf_bytes) as doc:if plan.target.block_no is None:image = doc.render_page(plan.target.page_no - 1, scale=2).pil_image- image_bytes = _pil_image_to_bytes(image)+ image_bytes = _pil_image_to_bytes(image, plan.image_format)width, height = image.sizeelse:block = _find_block_by_no(page, plan.target.block_no)@@ -1291,10 +1302,18 @@ class DoclibServer(AsyncDoclibInterface):raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")if _is_empty_bbox(block.bbox):raise InvalidRequestError("bbox_not_available", "Block bbox is not available for image output.", "locator")- image_bytes = doc.crop_image(block.bbox, plan.target.page_no - 1, scale=2)+ image_bytes = _transcode_image_bytes(+ doc.crop_image(block.bbox, plan.target.page_no - 1, scale=2), plan.image_format+ )width, height = _image_size_from_bytes(image_bytes)return _write_temp_asset(- self.state.data_dir, plan.short_id, "jpg", image_bytes, mime_type="image/jpeg", width=width, height=height+ self.state.data_dir,+ plan.short_id,+ _image_format_ext(plan.image_format),+ image_bytes,+ mime_type=_mime_type_for_image_format(plan.image_format),+ width=width,+ height=height,)async def _render_office_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:@@ -1308,21 +1327,24 @@ class DoclibServer(AsyncDoclibInterface):raise InvalidRequestError("format_not_supported", "Office image output is only supported for image blocks.", "format")- image_bytes = None- ext = "png"- mime_type = "image/png"- if image_span.image_path:+ image_bytes, _, _ = _span_image_bytes(image_span)+ if image_bytes is None and image_span.image_path:image_dir = parse_image_sidecar_dir(self.state.data_dir, plan.sha256, plan.tier)candidate = resolve_image_sidecar_path(image_dir, image_span.image_path)if candidate is not None and candidate.is_file():image_bytes = candidate.read_bytes()- ext = candidate.suffix.lstrip(".") or "png"- mime_type = _mime_type_for_ext(ext)if image_bytes is None:raise NotFoundError("asset_not_available", "Office image asset is not available.", "locator")+ image_bytes = _transcode_image_bytes(image_bytes, plan.image_format)width, height = _image_size_from_bytes(image_bytes)return _write_temp_asset(- self.state.data_dir, plan.short_id, ext or "png", image_bytes, mime_type=mime_type, width=width, height=height+ self.state.data_dir,+ plan.short_id,+ _image_format_ext(plan.image_format),+ image_bytes,+ mime_type=_mime_type_for_image_format(plan.image_format),+ width=width,+ height=height,)@@ -1641,12 +1663,61 @@ def _iter_block_spans(block: Block) -> Iterator[Span]:yield from _iter_block_spans(child)-def _pil_image_to_bytes(image: Image.Image) -> bytes:+def _span_image_bytes(span: Span) -> tuple[bytes | None, str, str]:+ # TODO: how to get image from office span?+ if not span.image_base64:+ return None, "png", "image/png"+ match = re.match(r"^data:image/(?P<ext>[^;]+);base64,(?P<data>.+)$", span.image_base64, re.DOTALL)+ if match is None:+ return None, "png", "image/png"+ ext = match.group("ext").lower()+ try:+ return base64.b64decode(match.group("data")), ext, _mime_type_for_ext(ext)+ except Exception:+ return None, ext, _mime_type_for_ext(ext)+++_PIL_IMAGE_FORMATS: dict[ImageFormat, str] = {+ "jpeg": "JPEG",+ "png": "PNG",+ "webp": "WEBP",+}++_IMAGE_FORMAT_EXTENSIONS: dict[ImageFormat, str] = {+ "jpeg": "jpg",+ "png": "png",+ "webp": "webp",+}++_IMAGE_FORMAT_MIME_TYPES: dict[ImageFormat, str] = {+ "jpeg": "image/jpeg",+ "png": "image/png",+ "webp": "image/webp",+}+++def _pil_image_to_bytes(image: Image.Image, image_format: ImageFormat) -> bytes:+ output_image = image+ if image_format == "jpeg" and image.mode != "RGB":+ output_image = image.convert("RGB")with BytesIO() as buffer:- image.save(buffer, format="JPEG")+ output_image.save(buffer, format=_PIL_IMAGE_FORMATS[image_format])return buffer.getvalue()+def _transcode_image_bytes(image_bytes: bytes, image_format: ImageFormat) -> bytes:+ with Image.open(BytesIO(image_bytes)) as image:+ return _pil_image_to_bytes(image, image_format)+++def _image_format_ext(image_format: ImageFormat) -> str:+ return _IMAGE_FORMAT_EXTENSIONS[image_format]+++def _mime_type_for_image_format(image_format: ImageFormat) -> str:+ return _IMAGE_FORMAT_MIME_TYPES[image_format]++def _image_size_from_bytes(image_bytes: bytes) -> tuple[int | None, int | None]:try:with Image.open(BytesIO(image_bytes)) as image:diff --git a/mineru/doclib/types.py b/mineru/doclib/types.pyindex b8476357..076ba1eb 100644--- a/mineru/doclib/types.py+++ b/mineru/doclib/types.py@@ -21,6 +21,7 @@ InvalidateTarget = Literal["parses"]ForgetMatchedAs = Literal["file", "directory", "none"]ConfigSource = Literal["default", "override"]ContentFormat = Literal["markdown", "image"]+ImageFormat = Literal["jpeg", "png", "webp"]PARSE_STATUS_PENDING: ParseStatus = "pending"PARSE_STATUS_PARSING: ParseStatus = "parsing"@@ -278,6 +279,7 @@ class ContentRequestScope(DoclibModel):limit: int = 30000locator: str | None = Nonecontext: int = 0+ image_format: ImageFormat | None = Noneclass ContentRange(DoclibModel):diff --git a/mineru/errors.py b/mineru/errors.pyindex 54bb18bb..ca65dff4 100644--- a/mineru/errors.py+++ b/mineru/errors.py@@ -26,6 +26,7 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {"file_not_found": "invalid_request_error","file_permission_denied": "invalid_request_error","file_hash_mismatch": "invalid_request_error",+ "image_output_extension_unsupported": "invalid_request_error","bytes_mismatch": "invalid_request_error","upload_not_found": "invalid_request_error","upload_not_ready": "invalid_request_error",diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex b13f2297..7a7ae2e3 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -1931,6 +1931,7 @@ def test_read_json_output_writes_image_file_and_returns_output_object(monkeypatcassert timeout == 60def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:+ assert kwargs["image_format"] == "png"return DocContentResponse(sha256="a" * 64,short_id="ab12cd3",@@ -1953,6 +1954,67 @@ def test_read_json_output_writes_image_file_and_returns_output_object(monkeypatcassert "Written to" not in result.output+ ("suffix", "expected_image_format"),+ [+ (".png", "png"),+ (".jpg", "jpeg"),+ (".jpeg", "jpeg"),+ (".webp", "webp"),+ ],+)+def test_read_image_output_extension_selects_server_image_format(+ monkeypatch: Any, tmp_path: Path, suffix: str, expected_image_format: str+) -> None:+ asset = tmp_path / f"server{suffix}"+ asset.write_bytes(b"image-bytes")+ output = tmp_path / "nested" / f"local{suffix}"++ class _Client:+ def __init__(self, *, timeout: int) -> None:+ assert timeout == 60++ def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:+ assert kwargs["image_format"] == expected_image_format+ return DocContentResponse(+ sha256="a" * 64,+ short_id="ab12cd3",+ tier="standard",+ format="image",+ content="",+ request_scope=ContentRequestScope(locator=locator, context=0, limit=30000),+ asset=ContentAsset(path=str(asset), mime_type=f"image/{expected_image_format}"),+ )++ monkeypatch.setattr(read, "DoclibClient", _Client)++ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--format", "image", "--output", str(output)])++ assert result.exit_code == 0+ assert output.read_bytes() == b"image-bytes"++[email protected]("output_arg", ["-", "page", "page.gif", "page.md"])+def test_read_image_output_rejects_unsupported_output_extension_before_client_call(+ monkeypatch: Any, tmp_path: Path, output_arg: str+) -> None:+ class _Client:+ def __init__(self, *, timeout: int) -> None:+ raise AssertionError("DoclibClient should not be called for invalid image output paths")++ monkeypatch.setattr(read, "DoclibClient", _Client)+ output = output_arg if output_arg == "-" else str(tmp_path / output_arg)++ result = runner.invoke(app, ["read", "doc:ab12cd3/tier:standard/page:4", "--format", "image", "--output", output, "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "image_output_extension_unsupported"+ assert payload["error"]["param"] == "output"+ if output != "-":+ assert not Path(output).exists()++def test_read_json_image_output_missing_asset_reports_error_envelope(monkeypatch: Any, tmp_path: Path) -> None:output = tmp_path / "nested" / "local.png"@@ -1961,6 +2023,7 @@ def test_read_json_image_output_missing_asset_reports_error_envelope(monkeypatchassert timeout == 60def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:+ assert kwargs["image_format"] == "png"return DocContentResponse(sha256="a" * 64,short_id="ab12cd3",@@ -1993,6 +2056,7 @@ def test_read_image_output_copies_server_asset_locally(monkeypatch: Any, tmp_patassert timeout == 60def read_content(self, locator: str, **kwargs: Any) -> DocContentResponse:+ assert kwargs["image_format"] == "png"return DocContentResponse(sha256="a" * 64,short_id="ab12cd3",diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex d6aa0628..f1081290 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -11,6 +11,7 @@ from types import SimpleNamespacefrom typing import Anyimport pytest+from PIL import Imagefrom mineru.config import LogConfig, ManagedParseServerConfigfrom mineru.doclib.background.compaction import Compaction@@ -3005,10 +3006,59 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:limit=30000,format="image",no_marker=False,+ image_format="png",target=ContentCursor(short_id="fffffff", tier=tier, page_no=1, block_no=1),)asset = asyncio.run(server._render_office_image_asset(plan, page))- assert Path(asset.path).read_bytes() == sidecar.read_bytes()assert asset.mime_type == "image/png"+ assert Path(asset.path).suffix == ".png"+ with Image.open(asset.path) as image:+ assert image.format == "PNG"+++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"+ )+ )++ image_span = Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)+ body = Block(+ index=0,+ type=BlockType.IMAGE_BODY,+ bbox=(1, 1, 20, 20),+ lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],+ )+ image_block = Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 20), blocks=[body])+ page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))+ plan = _ReadPlan(+ sha256=sha256,+ short_id="fffffff",+ tier=tier,+ page_range=None,+ after=None,+ locator="doc:fffffff/tier:standard/page:1/block:1",+ context=0,+ limit=30000,+ format="image",+ no_marker=False,+ image_format="jpeg",+ target=ContentCursor(short_id="fffffff", tier=tier, page_no=1, block_no=1),+ )++ asset = asyncio.run(server._render_office_image_asset(plan, page))++ assert asset.mime_type == "image/jpeg"+ assert Path(asset.path).suffix == ".jpg"+ with Image.open(asset.path) as image:+ assert image.format == "JPEG"diff --git a/tests/unittest/test_errors.py b/tests/unittest/test_errors.pyindex 894b9551..3f80f645 100644--- a/tests/unittest/test_errors.py+++ b/tests/unittest/test_errors.py@@ -27,6 +27,7 @@ DOCLIB_CONTRACT_ERROR_CODES = {"doc_not_found","engine_unavailable","format_not_supported",+ "image_output_extension_unsupported","invalid_config_key","invalid_locator","multi_page_image_not_supported",@@ -58,6 +59,7 @@ def test_doclib_error_code_types_are_stable() -> None:assert error_type_for("bbox_not_available") == "invalid_request_error"assert error_type_for("context_not_applicable") == "invalid_request_error"assert error_type_for("format_not_supported") == "invalid_request_error"+ assert error_type_for("image_output_extension_unsupported") == "invalid_request_error"assert error_type_for("invalid_config_key") == "invalid_request_error"assert error_type_for("invalid_locator") == "invalid_request_error"assert error_type_for("multi_page_image_not_supported") == "invalid_request_error"