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
feat(artifacts): update image naming convention for materialized assets and improve image resolution handling
myhloli3103e954a464
diff --git a/docs/en/reference/changelog.md b/docs/en/reference/changelog.mdindex 80bfda51..2180c405 100644--- a/docs/en/reference/changelog.md+++ b/docs/en/reference/changelog.md@@ -4,6 +4,8 @@ This document records the release history of MinerU, including major capability## Unreleased+- Image naming change: newly materialized CLI/API ZIP images now use Gradio visual-parent names, inline ordinals count all img src attributes, and collisions receive `_duplicate_n`. References update together; image bytes and MiddleJson 2.0 are unchanged. Historical ZIPs retain their stored references. Requires `docvortex>=0.4.19,<1`.+- Breaking change: removed the `--backend` option from `mineru-kit parse` (introduced during the 4.0 alphas). The option only inferred a tier and had no independent effect, so use `--tier` instead: `pipeline` → `--tier basic`; `vlm-engine`, `vlm-auto-engine`, and `vlm-http-client` → `--tier advanced`; `hybrid-engine` and `hybrid-auto-engine` → `--tier standard` (or omit the option); `flash` → `--tier flash`. Parsing with a remote VLM service is configured through the VLM server settings and is unrelated to this option.- Breaking change: removed the `PARSER_BACKENDS` constant from the `mineru.parser` exports (present in the 4.0 release). Backends are derived from tiers and are no longer a public choice or a public symbol; configure engines through `model.small_backend` and `model.vlm.engine` instead.diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.mdindex 6ff61e7a..6ce668a7 100644--- a/docs/en/reference/output_files.md+++ b/docs/en/reference/output_files.md@@ -15,6 +15,26 @@A `mineru parse --json` response is not MiddleJson and cannot be passed directly to `ParseResult.from_dict()`. Remote output availability is defined by the remote service.+## ZIP image names++`mineru-kit parse --format zip`, V1 API ZIP, and Gradio Markdown/JSON/LaTeX downloads+share DocVortex image materialization and naming (`docvortex>=0.4.19,<1`). Each entrypoint+keeps its existing archive name and document members.++Direct image/table/chart payloads use `images/page_{page_idx}_{parent_type}_{parent_index}.{ext}`;+standalone equations use `equation`. Images inside visual HTML use `image_{index}_{ordinal}`,+`table_image_{index}_{ordinal}`, or `chart_image_{index}_{ordinal}` after the page prefix.+Page indices refer to the original document and start at zero. Inline ordinals start at one+within each body, counting every `<img src=...>`, including external images whose URLs remain unchanged.++Identical bytes at the same path are reused; different bytes receive `_duplicate_n` suffixes.+Different semantic names remain separate even when their bytes match. Extensions are lowercase;+image bytes are not re-encoded. All document references are updated together with image paths.++Historical ZIPs retain their stored references, with no automatic migration or old-name aliases.+Consumers should follow actual document references instead of constructing `*_body_*` filenames.+CLI image acquisition is unchanged; local file loading and PDF crop fallback remain Gradio features.+## Nine rendering targets| `RenderFormat` | Format | Python return type |@@ -76,7 +96,7 @@ and report `pdf_title_geometry_conflict`; unavailable expansion clearance report`pdf_title_clearance_unavailable`. Only rendering context changes, with no input,asset, protocol or public-option changes.-Requires `docvortex>=0.4.12,<1` (the current minimum dependency declared by MinerU 4.0). DocVortex clears native TXT PDF display equation+Requires `docvortex>=0.4.19,<1` (the current minimum dependency declared by MinerU 4.0). DocVortex clears native TXT PDF display equation`content` once when producing model output; MinerU Flash TXT uses that output.Flash OCR already leaves display equation content empty. MinerU does not clearequation content again. Both Flash paths retain the bbox, orientation, image anddiff --git a/docs/zh/reference/changelog.md b/docs/zh/reference/changelog.mdindex 85c31ad6..2269072c 100644--- a/docs/zh/reference/changelog.md+++ b/docs/zh/reference/changelog.md@@ -4,6 +4,8 @@## 未发布+- 图片命名变更:CLI/API ZIP 的新物化图片统一采用 Gradio 的视觉父块命名,表内图按所有 img src 顺序编号,冲突追加 `_duplicate_n`。引用同步更新,图片字节及 MiddleJson 2.0 不变;历史 ZIP 仍按已有引用读取。需要 `docvortex>=0.4.19,<1`。+- 破坏性变更:移除 `mineru-kit parse` 的 `--backend` 参数(该参数在 4.0 alpha 阶段引入)。它仅用于推断 tier,没有独立作用,请改用 `--tier`:`pipeline` → `--tier basic`;`vlm-engine`、`vlm-auto-engine`、`vlm-http-client` → `--tier advanced`;`hybrid-engine`、`hybrid-auto-engine` → `--tier standard`(或省略该参数);`flash` → `--tier flash`。使用远程 VLM 服务由 VLM 服务配置表达,与该参数无关。- 破坏性变更:移除 `mineru.parser` 公开导出中的 `PARSER_BACKENDS` 常量(4.0 正式版包含该导出)。backend 由 tier 派生,不再是公开选择或公开符号;请通过 `model.small_backend` 与 `model.vlm.engine` 配置引擎。diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.mdindex f4dd021c..3e8c944d 100644--- a/docs/zh/reference/output_files.md+++ b/docs/zh/reference/output_files.md@@ -15,6 +15,26 @@`mineru parse --json` 的响应不是 MiddleJson,不能直接传给 `ParseResult.from_dict()`。远端服务的产物范围由该服务声明。+## ZIP 图片命名++`mineru-kit parse --format zip`、V1 API ZIP 和 Gradio 的 Markdown/JSON/LaTeX 下载共用+DocVortex 图片物化与命名规则(需要 `docvortex>=0.4.19,<1`)。ZIP 文件名和正文成员组织仍由各入口决定。++| 图片位置 | 路径示例 |+| --- | --- |+| 图片、表格、图表的直接载荷 | `images/page_0_image_1.png`、`images/page_0_table_2.png`、`images/page_0_chart_3.png` |+| 图片正文的内嵌图 | `images/page_0_image_1_1.png` |+| 表格、图表正文的内嵌图 | `images/page_0_table_image_2_1.png`、`images/page_0_chart_image_3_1.png` |+| 独立公式图片 | `images/page_0_equation_4.png` |++页号是从 0 开始的原始 `page_idx`,块号取所属视觉父块 index;正文内序号从 1 开始,+按所有 `<img src=...>` 的顺序计数,外链图片保留原地址但也占序号。+同名同字节复用,同名不同字节追加 `_duplicate_n`;不同语义位置不按内容合并名称。+扩展名转小写,图片字节不重新编码。命名与 Markdown、JSON、HTML/LaTeX 引用同步更新。++历史 ZIP 按已有引用读取,不自动改名或生成旧名称别名。下游应读取实际图片引用,避免拼接旧的+`image_body` / `table_body` 文件名。此次统一不扩展 CLI 的素材获取能力:仅 Gradio 保留本地读图和 PDF 补裁图。+## 九种渲染目标| `RenderFormat` | 格式 | Python 返回类型 |@@ -47,7 +67,7 @@ pdf_bytes = render(result.middle_json, RenderFormat.PDF,`pdf_title_layout_expanded` 记录扩展;`pdf_layout_font_exception` 记录局部正文较大或空间不足的调整原因、参考/目标/最终字号、原框和绘制框。原始几何重叠时不扩大占用并报告 `pdf_title_geometry_conflict`;原始间距过紧、没有安全扩展区域时报告 `pdf_title_clearance_unavailable`。字号和绘制区域仅存在于渲染上下文,不修改 MiddleJson 或素材,不新增接口参数。-使用 `docvortex>=0.4.12,<1`(MinerU 4.0 当前声明的最低依赖)。DocVortex 在生产原生 TXT PDF 模型输出时将行间公式的 `content` 清空一次,MinerU Flash TXT 直接使用该输出;Flash OCR 原本不填充行间公式内容,MinerU 不再重复清空。两条 Flash 路径保留 bbox、方向、图片及检测到的编号区域,PDF、Markdown、HTML、DOCX、EPUB、LaTeX 沿用图片回退。行内公式、非 Flash tier 的公式文本不变。旧缓存不会自动改写,重新解析才获得新几何和空内容公式。+使用 `docvortex>=0.4.19,<1`(MinerU 4.0 当前声明的最低依赖)。DocVortex 在生产原生 TXT PDF 模型输出时将行间公式的 `content` 清空一次,MinerU Flash TXT 直接使用该输出;Flash OCR 原本不填充行间公式内容,MinerU 不再重复清空。两条 Flash 路径保留 bbox、方向、图片及检测到的编号区域,PDF、Markdown、HTML、DOCX、EPUB、LaTeX 沿用图片回退。行内公式、非 Flash tier 的公式文本不变。旧缓存不会自动改写,重新解析才获得新几何和空内容公式。```pythonfrom pathlib import Pathdiff --git a/mineru/kit/gradio/artifacts.py b/mineru/kit/gradio/artifacts.pyindex 8f727655..c4d0dfef 100644--- a/mineru/kit/gradio/artifacts.py+++ b/mineru/kit/gradio/artifacts.py@@ -12,12 +12,13 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import Any, Callable, Literal, cast-from urllib.parse import quote, unquote, urlsplit+from urllib.parse import quote, urlsplitfrom bs4 import BeautifulSoup-from docvortex.assets import parse_image_data_uri_strict, validate_image_sidecar_path+from docvortex.assets import AssetStore, parse_image_data_uri_strict, validate_image_sidecar_pathfrom docvortex.document.pdf import PDFDocumentfrom docvortex.document.pdf.pdfium import safe_rewrite_pdf_bytes_with_pdfium_result+from docvortex.export import materialize_middlefrom loguru import loggerfrom ...filetypes import IMAGE_EXTENSIONS, PDF_EXTENSIONS@@ -34,29 +35,10 @@ from ...render import (StructuredContentRenderOptions,render,)-from ...types import (- AlgorithmBodyBlock,- BlockBase,- ChartBlock,- ChartBodyBlock,- CodeBlock,- CodeBodyBlock,- ImageBlock,- ImageBodyBlock,- ImagePayloadBlock,- MiddleJson,- TableBlock,- TableBodyBlock,-)+from ...types import BlockBase, ImagePayloadBlock, MiddleJsonDownloadFormat = Literal["markdown", "json", "html", "docx", "latex", "epub", "pdf"]-_HTML_IMAGE_RE = re.compile(- r"(?P<prefix><img\b[^>]*?\bsrc\s*=\s*)(?P<quote>[\"'])(?P<src>[^\"']+)(?P=quote)",- re.IGNORECASE,-)-_IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tiff", ".svg"}-@dataclassclass RunArtifacts:@@ -540,34 +522,26 @@ def _close_image_context(context: _ImageContext) -> None:def _materialize_middle_json(middle_json: MiddleJson, context: _ImageContext) -> MiddleJson:- """复制 Middle JSON,并为 PDF bbox 或 inline image 准备目标 renderer 所需的图片载荷。"""- copied = middle_json.model_copy(deep=True)- for page in copied.pages:- page.blocks = [_materialize_block(block, context, middle_page_idx=page.page_idx, owner=block) for block in page.blocks]- return copied-+ """由宿主提供素材字节,统一交给 DocVortex 命名、消解冲突并改写引用。"""+ images = context.output_dir / "images"+ _ensure_path_inside(context.output_dir, images)+ existing = AssetStore()+ for path in sorted(images.rglob("*")):+ _ensure_path_inside(images, path)+ if path.is_symlink():+ raise ValueError(f"Image assets must not contain symlinks: {path}")+ if path.is_file():+ existing.add(path.relative_to(context.output_dir).as_posix(), path.read_bytes())-def _materialize_block(- block: BlockBase,- context: _ImageContext,- *,- middle_page_idx: int,- owner: BlockBase,-) -> BlockBase:- """沿语义树传递所属视觉父块,仅为图片载荷和富 HTML 正文物化素材。"""- if isinstance(block, (CodeBlock, CodeBodyBlock, AlgorithmBodyBlock)):- return block- if isinstance(block, (ImageBlock, TableBlock, ChartBlock)):- owner = block- updates: dict[str, Any] = {}- if isinstance(block, ImagePayloadBlock):+ def resolve_image(block: ImagePayloadBlock, page_idx: int) -> tuple[bytes, str] | None:+ """保持内嵌载荷、本地路径及 PDF 补裁的现有分支顺序和错误处理。"""data: bytes | None = Noneextension = "jpg"if block.image_base64:try:data, extension = parse_image_data_uri_strict(block.image_base64)except ValueError:- data = None+ return Noneelif block.image_path:safe_path = validate_image_sidecar_path(block.image_path)candidate = (context.asset_root / safe_path).resolve()@@ -576,103 +550,24 @@ def _materialize_block(data = candidate.read_bytes()extension = candidate.suffix.lstrip(".") or extensionelif block.bbox is not None:- data = context.crop_for_block(block, middle_page_idx=middle_page_idx)- if data:- updates["image_path"] = _write_materialized_asset(- context.output_dir,- data,- extension,- page_idx=middle_page_idx,- owner=owner,- )- updates["image_base64"] = None- updates["image_url"] = None-- content = getattr(block, "content", None)- if isinstance(content, list):- updates["content"] = [- _materialize_block(child, context, middle_page_idx=middle_page_idx, owner=owner)- if isinstance(child, BlockBase)- else child- for child in content- ]- elif isinstance(block, (ImageBodyBlock, TableBodyBlock, ChartBodyBlock)) and "<img" in content.lower():- updates["content"] = _materialize_markup_images(content, context, page_idx=middle_page_idx, owner=owner)-- return block.model_copy(update=updates, deep=True) if updates else block---def _write_materialized_asset(- output_dir: Path,- data: bytes,- extension: str,- *,- page_idx: int,- owner: BlockBase,- ordinal: int | None = None,-) -> str:- """使用原始页索引和所属块命名,表内多图区分序号,冲突文件禁止覆盖。"""- safe_extension = extension.lower().lstrip(".") or "jpg"- if f".{safe_extension}" not in _IMAGE_SUFFIXES:- raise ValueError(f"Unsupported image extension: {extension}")- if owner.index is None:- raise ValueError("Image owner must have a block index")- kind = str(owner.type)- if ordinal is not None and kind != "image":- kind += "_image"- suffix = f"_{ordinal}" if ordinal is not None else ""- stem = f"page_{page_idx}_{kind}_{owner.index}{suffix}"- # 冲突后缀独立于表内图片序号,避免占用另一张内嵌图片的正式名称。- for attempt in range(10000):- duplicate = f"_duplicate_{attempt}" if attempt else ""- relative = validate_image_sidecar_path(f"images/{stem}{duplicate}.{safe_extension}")- target = output_dir / relative- _ensure_path_inside(output_dir, target)+ data = context.crop_for_block(block, middle_page_idx=page_idx)+ return (data, extension) if data else None++ document, assets = materialize_middle(+ middle_json,+ existing,+ image_resolver=resolve_image,+ asset_resolver=_asset_resolver(context.asset_root),+ )+ for relative_path, payload in assets.items():+ target = context.output_dir / relative_path+ _ensure_path_inside(context.output_dir, target)+ if target.is_symlink():+ raise ValueError(f"Image assets must not contain symlinks: {target}")target.parent.mkdir(parents=True, exist_ok=True)- if not target.exists():- target.write_bytes(data)- return relative- if target.is_file() and target.read_bytes() == data:- return relative- raise ValueError("Too many conflicting image assets")---def _materialize_markup_images(- content: str,- context: _ImageContext,- *,- page_idx: int,- owner: BlockBase,-) -> str:- """按富 HTML 中的出现顺序,为所属视觉块的内嵌图片分配语义名称。"""- ordinal = 0-- def replace(match: re.Match[str]) -> str:- """解析一个 img 的图片载荷并保留原有 HTML 属性及引号。"""- nonlocal ordinal- ordinal += 1- source = html.unescape(match.group("src")).strip()- if source.startswith("data:"):- data, extension = parse_image_data_uri_strict(source)- elif _is_external_source(source):- return match.group(0)- else:- safe_path = validate_image_sidecar_path(unquote(source))- candidate = context.asset_root / safe_path- _ensure_path_inside(context.asset_root, candidate)- data = candidate.read_bytes()- extension = candidate.suffix.lstrip(".")- relative = _write_materialized_asset(- context.output_dir,- data,- extension,- page_idx=page_idx,- owner=owner,- ordinal=ordinal,- )- return f"{match.group('prefix')}{match.group('quote')}{relative}{match.group('quote')}"-- return _HTML_IMAGE_RE.sub(replace, content)+ if relative_path not in existing:+ target.write_bytes(payload)+ return documentdef _copy_materialized_images(asset_root: Path, output_dir: Path) -> None:@@ -770,11 +665,6 @@ def _safe_stem(value: str) -> str:return truncated.strip("._") or "document"-def _is_external_source(value: str) -> bool:- """判断图片引用是否已经是 scheme URL 或 data URI。"""- return bool(re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", value))--__all__ = ["DownloadFormat","RunArtifacts",diff --git a/pyproject.toml b/pyproject.tomlindex 5c07a423..a5086450 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,7 +39,7 @@ classifiers = ["Programming Language :: Python :: 3.14",]dependencies = [- "docvortex>=0.4.15,<1",+ "docvortex>=0.4.19,<1","gradio>=6.8,<7","mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'","mineru-vl-utils>=2.0.5,<3",diff --git a/tests/unittest/test_kit_gradio_image_names.py b/tests/unittest/test_kit_gradio_image_names.pyindex 5b60615f..93eb16a4 100644--- a/tests/unittest/test_kit_gradio_image_names.py+++ b/tests/unittest/test_kit_gradio_image_names.py@@ -5,20 +5,24 @@ from __future__ import annotationsimport base64import jsonimport zipfile+from io import BytesIOfrom pathlib import Pathimport pytestfrom bs4 import BeautifulSoupfrom PIL import Image, ImageStat+from test_kit_gradio import _colored_pdf_bytes, _middle_json+from test_kit_gradio_html import _image_bytes+from mineru.kit.common import save_parse_resultfrom mineru.kit.gradio.artifacts import (_build_image_context,_close_image_context,_materialize_middle_json,- _write_materialized_asset,persist_parse_result,render_download,)+from mineru.parser.api_server import _build_self_contained_zip_outputfrom mineru.parser.base import ParseResultfrom mineru.types import (AlgorithmBodyBlock,@@ -32,8 +36,6 @@ from mineru.types import (TableBodyBlock,TextSpan,)-from test_kit_gradio import _colored_pdf_bytes, _middle_json-from test_kit_gradio_html import _image_bytesdef _image_uri(color: str) -> str:@@ -142,6 +144,15 @@ def test_parent_names_table_images_and_repeated_materialization(tmp_path: Path)assert images == beforestructured = json.loads(artifacts.structured_content_path.read_text())assert structured["pages"][0]["blocks"][2]["image_source"] == "images/page_0_table_2.png"+ # 同一份解析结果经 CLI/API 保存,图片名称、字节和对应正文必须与 Gradio 一致。+ cli_zip = tmp_path / "cli.zip"+ save_parse_result(ParseResult(middle), cli_zip, "zip")+ for archive_source in (cli_zip, BytesIO(_build_self_contained_zip_output(ParseResult(middle)))):+ with zipfile.ZipFile(archive_source) as archive:+ assert {Path(name).name: archive.read(name) for name in archive.namelist() if name.startswith("images/")} == before+ assert archive.read("markdown.md").decode() == artifacts.markdown_path.read_text(encoding="utf-8")+ assert json.loads(archive.read("structured_content.json")) == structured+ assert json.loads(archive.read("middle_json.json")) == json.loads(artifacts.middle_json_path.read_text())def test_identical_images_on_different_pages_keep_their_names(tmp_path: Path) -> None:@@ -160,15 +171,22 @@ def test_identical_images_on_different_pages_keep_their_names(tmp_path: Path) ->def test_conflicting_contents_never_overwrite_or_take_inline_ordinals(tmp_path: Path) -> None:"""同名不同内容分配独立冲突后缀,并避免占用正文内嵌图片的正式序号。"""- owner = _middle_json(file_suffix="docx").pages[0].blocks[1]- first = _write_materialized_asset(tmp_path, _image_bytes("red"), "png", page_idx=1, owner=owner)- second = _write_materialized_asset(tmp_path, _image_bytes("blue"), "png", page_idx=1, owner=owner)+ middle = _middle_json(file_suffix="docx")+ middle.pages[0].page_idx = 1+ body = middle.pages[0].blocks[1].content[0]+ body.image_base64 = _image_uri("red")+ context = _build_image_context(middle, None, tmp_path)+ first = _materialize_middle_json(middle, context).pages[0].blocks[1].content[0].image_path+ body.image_base64 = _image_uri("blue")+ body.content = f'<img src="{_image_uri("blue")}">'+ saved = _materialize_middle_json(middle, context)+ second = saved.pages[0].blocks[1].content[0].image_pathassert first == "images/page_1_image_1.png"assert second == "images/page_1_image_1_duplicate_1.png"- assert _write_materialized_asset(tmp_path, _image_bytes("blue"), "png", page_idx=1, owner=owner) == second- inline = _write_materialized_asset(tmp_path, _image_bytes("blue"), "png", page_idx=1, owner=owner, ordinal=1)- assert inline == "images/page_1_image_1_1.png"+ assert _materialize_middle_json(saved, context) == saved+ assert saved.pages[0].blocks[1].content[0].content == '<img src="images/page_1_image_1_1.png">'assert (tmp_path / first).read_bytes() == _image_bytes("red")+ assert (tmp_path / second).read_bytes() == _image_bytes("blue")assert len(list((tmp_path / "images").iterdir())) == 3diff --git a/tests/unittest/test_parse_result_assets.py b/tests/unittest/test_parse_result_assets.pyindex 31ff47cd..ad6f907c 100644--- a/tests/unittest/test_parse_result_assets.py+++ b/tests/unittest/test_parse_result_assets.py@@ -4,16 +4,16 @@ from __future__ import annotationsimport asyncioimport base64-from io import BytesIOimport json+import zipfile+from io import BytesIOfrom pathlib import Pathfrom unittest.mock import AsyncMock-import zipfile+import pytestfrom bs4 import BeautifulSoupfrom docvortex.document.pdf import PDFDocumentfrom PIL import Image-import pytestfrom reportlab.pdfgen.canvas import Canvasfrom mineru.kit.common import save_parse_result@@ -91,8 +91,8 @@ def test_save_externalizes_assets_without_changing_json_only_contract(tmp_path:"middle_json.json","markdown.md","structured_content.json",- "images/page_4_table_body_2.png",- "images/page_4_table_body_2_1.png",+ "images/page_4_table_2.png",+ "images/page_4_table_image_2_1.png",}for name, payload in entries.items():if name.startswith("images/"):@@ -101,7 +101,7 @@ def test_save_externalizes_assets_without_changing_json_only_contract(tmp_path:assert saved["extensions"] == result.middle_json.extensionsfor name in ("middle_json.json", "markdown.md", "structured_content.json"):assert b"data:image/" not in entries[name]- assert b"images/page_4_table_body_2_1.png" in entries[name]+ assert b"images/page_4_table_image_2_1.png" in entries[name]assert result.middle_json.to_json() == beforeassert "image_base64" not in result.to_json()dest = tmp_path / "result.zip"@@ -142,8 +142,8 @@ def test_server_zip_roundtrip_restores_direct_and_markup_images(assert body.content == markupassert _entries(api_server._build_self_contained_zip_output(restored)) == _entries(payload)else:- assert body.image_base64 is None and body.image_path == "images/page_4_table_body_2.png"- assert "images/page_4_table_body_2_1.png" in body.content+ assert body.image_base64 is None and body.image_path == "images/page_4_table_2.png"+ assert "images/page_4_table_image_2_1.png" in body.content@pytest.mark.parametrize("angle", [0, 90, 180, 270])