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
Update dependencies and refactor image handling in server implementation
myhloli81c7b7a407c3
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 828b809d..52e1a18d 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -1,7 +1,6 @@"""New doclib HTTP server implementation backed by the public interface."""from __future__ import annotations-from docvortex.content.tree import iter_child_blocks as _iter_child_blocksimport asyncioimport math@@ -12,14 +11,12 @@ import sysimport timefrom collections.abc import Callablefrom dataclasses import dataclass-from io import BytesIOfrom pathlib import Path-from typing import Any, Iterator, cast+from typing import Any, castfrom urllib.parse import urlparsefrom fastapi import APIRouter, FastAPI, Requestfrom fastapi.responses import JSONResponse-from PIL import Imagefrom pydantic import ValidationErrorfrom ..config import config@@ -34,14 +31,14 @@ from ..parser.page_range import (from ..parser.tier import TierDependencyError, ensure_tier_runtime_dependenciesfrom docvortex.render.markdown import build_markdown_imagefrom docvortex.render.markdown import render_single_block-from docvortex.foundation.image_payload import parse_image_data_uri_strict+from docvortex.assets import parse_image_data_uri_strict, transcode_image+from docvortex.content.tree import iter_image_payloadsfrom ..types import (DEPLOYMENT_TIERS,TIERS,BlockBase,BlockType,DeploymentTier,- ImagePayloadBlock,PageBlock,PageInfo,Tier,@@ -49,7 +46,7 @@ from ..types import ()from ..model.download import verify_model_repofrom ..model.registry import ModelRepo, model_repos_for_tier-from docvortex.document.pdf.document import PDFDocument+from docvortex.document.pdf import PDFDocumentfrom ..version import __version__from .background.parse_server_health import get_health, get_managed_parse_server_tierfrom .base import AsyncDoclibInterface@@ -1455,6 +1452,7 @@ class DoclibServer(AsyncDoclibInterface):return select_highest_cached_tier(tiers)async def _render_source_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:+ """查找源文件并调用公共图像输出,保留 Doclib 定位与错误协议。"""if plan.target is None:raise InvalidRequestError("format_not_supported", "image format requires a page or block locator.", "format")file_row = await accessible_file_for_sha256(self.state.db, plan.sha256)@@ -1474,46 +1472,37 @@ class DoclibServer(AsyncDoclibInterface):"format",)with doc:- if plan.target.block_no is None:- image = doc.render_page(plan.target.page_no - 1).pil_image- try:- image_bytes = _pil_image_to_bytes(image, plan.image_format)- width, height = image.size- finally:- image.close()- else:+ bbox = None+ if plan.target.block_no is not None: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")if block.bbox is None or _is_empty_bbox(block.bbox):raise InvalidRequestError("bbox_not_available", "Block bbox is not available for image output.", "locator")- image_bytes = _transcode_image_bytes(- doc.crop_image(block.bbox, plan.target.page_no - 1),- plan.image_format,- )- width, height = _image_size_from_bytes(image_bytes)+ bbox = block.bbox+ artifact = doc.render_image(plan.target.page_no - 1, bbox=bbox, image_format=plan.image_format)return _write_temp_asset(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,+ artifact.extension,+ artifact.data,+ mime_type=artifact.mime_type,+ width=artifact.width,+ height=artifact.height,)def _render_base64_image_asset(self, plan: _ReadPlan, data_uri: str) -> ContentAsset:+ """通过公共素材接口解码并转码,Doclib 只负责临时资产写出。"""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)+ artifact = transcode_image(image_bytes, image_format=plan.image_format)return _write_temp_asset(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,+ artifact.extension,+ artifact.data,+ mime_type=artifact.mime_type,+ width=artifact.width,+ height=artifact.height,)@@ -1800,7 +1789,7 @@ def _is_empty_bbox(bbox: object) -> bool: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):+ for payload in iter_image_payloads(block):if payload.image_base64:return _BlockImageSource(kind="base64", data_uri=payload.image_base64)return None@@ -1818,68 +1807,12 @@ def _make_doclib_image_renderer(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)- remote_url = next((payload.image_url for payload in _iter_block_image_payloads(block) if payload.image_url), None)+ remote_url = next((payload.image_url for payload in iter_image_payloads(block) if payload.image_url), None)return build_markdown_image(remote_url, label) if remote_url is not None else f"![{label}]()"return _render-def _iter_block_image_payloads(block: BlockBase) -> Iterator[ImagePayloadBlock]:- if isinstance(block, ImagePayloadBlock):- yield block- for child in _iter_child_blocks(block):- yield from _iter_block_image_payloads(child)---_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:- 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:- return image.size- except Exception:- return None, None--def _write_temp_asset(data_dir: str,short_id: str,diff --git a/pyproject.toml b/pyproject.tomlindex 9b2d72d4..450a3202 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -38,7 +38,7 @@ classifiers = ["Programming Language :: Python :: 3.13",]dependencies = [- "docvortex>=0.2.2,<1.0.0",+ "docvortex>=0.2.6,<1.0.0","mineru-vl-utils>=1.2.1,<2","mineru-llama-cpp>=0.1.0,<1","click>=8.1.7",diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex 25984c9c..9d7c52c3 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -5163,3 +5163,55 @@ def test_doclib_office_image_asset_missing_payload_reports_asset_not_available(tassert exc_info.value.code == "asset_not_available"assert exc_info.value.param == "locator"++[email protected]("image_format", ["jpeg", "png", "webp"])[email protected]("source_available", [False, True])+def test_doclib_bbox_precedes_embedded_image(+ tmp_path: Path,+ image_format: str,+ source_available: bool,+) -> None:+ """同时有 bbox 和内嵌图片时仍截图源文件,源文件缺失不回退。"""+ from io import BytesIO+ from docvortex.foundation.image_encoding import image_to_b64str++ source_path = tmp_path / "source.pdf"+ with Image.new("RGB", (100, 100), "white") as source:+ source.save(source_path, "PDF")+ with Image.new("RGB", (1, 1), "red") as embedded:+ data_uri = image_to_b64str(embedded, "PNG")+ page = _image_page("internal/not-persisted.png")+ page.blocks[0].content[0].image_base64 = data_uri+ db = _FakeDB(+ parses=[],+ file_row={"path": str(source_path), "ext": "pdf", "sha256": "a" * 64, "status": "active"} if source_available else None,+ )+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=db))+ plan = _ReadPlan(+ sha256="a" * 64,+ short_id="aaaaaaa",+ tier="standard",+ page_range="1",+ after=None,+ locator="doc:aaaaaaa/tier:standard/page:1/block:1",+ context=0,+ limit=30000,+ format="image",+ no_marker=False,+ image_format=image_format,+ target=ContentCursor(short_id="aaaaaaa", tier="standard", page_no=1, block_no=1),+ )+ if not source_available:+ with pytest.raises(NotFoundError) as error:+ asyncio.run(server._render_image_response(plan, [page]))+ assert error.value.code == "no_accessible_file"+ return+ asset = asyncio.run(server._render_image_response(plan, [page])).asset+ assert asset is not None+ assert asset.mime_type == f"image/{image_format}"+ with Image.open(BytesIO(Path(asset.path).read_bytes())) as actual:+ assert actual.format == image_format.upper()+ assert actual.size == (asset.width, asset.height)+ assert actual.width > 1+ assert min(actual.convert("RGB").getpixel((0, 0))) > 240