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: enhance image handling in ParseResult for improved export and serialization
myhloli95a25fcd60d8
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.pyindex 2f40c5cb..4eff541d 100644--- a/mineru/backend/hybrid/model_output_to_middle_json.py+++ b/mineru/backend/hybrid/model_output_to_middle_json.py@@ -12,7 +12,6 @@ from ...utils.hash_utils import bytes_md5from ...utils.pdfium_guard import pdfium_guardfrom ...utils.title_level_postprocess import apply_title_leveling_to_pdf_infofrom ..pipeline.model_init import MineruHybridModel-from ..utils.html_image_utils import replace_inline_table_imagesfrom ..utils.middle_json_utils import apply_post_ocrfrom ..utils.para_block_utils import (build_para_blocks_from_preproc,@@ -111,8 +110,6 @@ def blocks_to_page_info(scale=scale,)- replace_inline_table_images(table_blocks, image_writer, page_index)-page_info = PageInfo(preproc_blocks=page_blocks,discarded_blocks=discarded_blocks,diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex 8db262eb..a3c012b5 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -6,7 +6,6 @@ from collections import defaultdictfrom typing import Anyfrom ...types import Block, BlockType, PageInfo-from ..utils.html_image_utils import replace_inline_table_images, save_span_image_if_neededfrom .office_magic_model import MagicModel@@ -18,29 +17,6 @@ def blocks_to_page_info(page_blocks: list[dict[str, Any]], image_writer: Any, patable_blocks = magic_model.get_table_blocks()chart_blocks = magic_model.get_chart_blocks()- if image_writer:- # Write embedded images to local storage via image_writer- for img_block in image_blocks:- for sub_block in img_block.blocks:- if sub_block.type != "image_body":- continue- for line in sub_block.lines:- for span in line.spans:- save_span_image_if_needed(span, image_writer, page_index)-- replace_inline_table_images(table_blocks, image_writer, page_index)-- # Replace inline base64 images inside chart content with local paths- for chart_block in chart_blocks:- for sub_block in chart_block.blocks:- if sub_block.type != "chart_body":- continue- for line in sub_block.lines:- for span in line.spans:- if span.type != "chart":- continue- save_span_image_if_needed(span, image_writer, page_index)-title_blocks = magic_model.get_title_blocks()discarded_blocks = magic_model.get_discarded_blocks()list_blocks = magic_model.get_list_blocks()diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.pyindex e0da24dc..5b0ae007 100644--- a/mineru/backend/pipeline/model_output_to_middle_json.py+++ b/mineru/backend/pipeline/model_output_to_middle_json.py@@ -7,7 +7,6 @@ from ...utils.hash_utils import bytes_md5from ...utils.pdfium_guard import pdfium_guardfrom ...utils.title_level_postprocess import apply_title_leveling_to_pdf_infofrom ..utils.char_utils import full_to_half-from ..utils.html_image_utils import replace_inline_table_imagesfrom ..utils.middle_json_utils import append_pages, apply_post_ocrfrom ..utils.runtime_utils import cross_page_table_mergefrom ..utils.visual_span_utils import cut_visual_spans_in_blocks@@ -45,9 +44,6 @@ def blocks_to_page_info(scale=scale,)- """构造page_info"""- replace_inline_table_images(preproc_blocks, image_writer, page_index)-return PageInfo(preproc_blocks=preproc_blocks,page_idx=page_index,diff --git a/mineru/backend/utils/html_image_utils.py b/mineru/backend/utils/html_image_utils.pydeleted file mode 100644index 91a4fd2f..00000000--- a/mineru/backend/utils/html_image_utils.py+++ /dev/null@@ -1,159 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from __future__ import annotations--import base64-import re--from loguru import logger--from ...data.data_reader_writer import DataWriter-from ...types import Block, BlockType, ContentType, Span-from ...utils.hash_utils import str_sha256-from .office_image import is_vector_image_part, serialize_office_image--INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,(.+)", re.DOTALL)---def _normalize_image_extension(fmt: str) -> str:- normalized = fmt.lower().split("+", 1)[0]- return "jpg" if normalized == "jpeg" else normalized---def _save_inline_vector_image(- img_bytes: bytes,- image_writer: DataWriter,- fmt: str,- page_index: int,-) -> str | None:- """将 HTML 表格内联的 WMF/EMF 矢量图转换为可渲染占位图后落盘。"""- content_type = f"image/{fmt.lower()}"- rendered_data_uri = serialize_office_image(- img_bytes,- content_type=content_type,- )- if not rendered_data_uri:- logger.warning(f"Failed to convert vector image data URI in page {page_index}.")- return None-- rendered_match = INLINE_IMAGE_DATA_URI_RE.match(rendered_data_uri)- if not rendered_match:- logger.warning(f"Unrecognized converted vector image format in page {page_index}, skipping.")- return None-- rendered_fmt = _normalize_image_extension(rendered_match.group(1))- try:- rendered_bytes = base64.b64decode(rendered_match.group(2))- except Exception as exc:- logger.warning(f"Failed to decode converted vector image on page {page_index}: {exc}")- return None-- img_path = f"{str_sha256(rendered_data_uri)}.{rendered_fmt}"- _write_image_once(image_writer, img_path, rendered_bytes)- return img_path---def _write_image_once(image_writer: DataWriter, img_path: str, img_bytes: bytes) -> None:- """同一 writer 生命周期内同一路径只写一次,便于复用标准占位图。"""- written_paths = getattr(image_writer, "_mineru_written_image_paths", None)- if written_paths is None:- written_paths = set()- try:- setattr(image_writer, "_mineru_written_image_paths", written_paths)- except Exception:- image_writer.write(img_path, img_bytes)- return-- if img_path in written_paths:- return-- image_writer.write(img_path, img_bytes)- written_paths.add(img_path)---def _save_base64_image(b64_data_uri: str, image_writer: DataWriter, page_index: int) -> str | None:- """Persist a data-URI image via image_writer and return a relative path."""- if not image_writer:- return None-- match = INLINE_IMAGE_DATA_URI_RE.match(b64_data_uri)- if not match:- logger.warning(f"Unrecognized image_base64 format in page {page_index}, skipping.")- return None-- raw_fmt = match.group(1)- fmt = _normalize_image_extension(raw_fmt)- try:- img_bytes = base64.b64decode(match.group(2))- except Exception as exc:- logger.warning(f"Failed to decode image_base64 on page {page_index}: {exc}")- return None-- if is_vector_image_part(content_type=f"image/{raw_fmt.lower()}"):- return _save_inline_vector_image(- img_bytes,- image_writer,- raw_fmt,- page_index,- )-- img_path = f"{str_sha256(b64_data_uri)}.{fmt}"- _write_image_once(image_writer, img_path, img_bytes)- return img_path---def _replace_inline_base64_img_src(markup: str, image_writer: DataWriter, page_index: int) -> str:- """Replace inline base64 image sources in HTML-like markup with local paths."""- if not markup or not image_writer or "base64," not in markup:- return markup-- def _replace_src(match: re.Match[str], _writer: DataWriter = image_writer, _idx: int = page_index) -> str:- img_path = _save_base64_image(match.group(1), _writer, _idx)- if img_path:- return f'src="{img_path}"'- return match.group(0)-- return re.sub(- r'src="(data:image/[^"]+)"',- _replace_src,- markup,- )---def replace_inline_table_images(- blocks: list[Block],- image_writer: DataWriter | None,- page_index: int,- table_block_type: str = BlockType.TABLE,- table_body_type: str = BlockType.TABLE_BODY,- table_span_type: str = ContentType.TABLE,-) -> None:- """Persist inline base64 images embedded inside table HTML."""- if not image_writer:- return-- for block in blocks:- if block.type != table_block_type:- continue-- for sub_block in block.blocks:- if sub_block.type != table_body_type:- continue-- for line in sub_block.lines:- for span in line.spans:- if span.type != table_span_type:- continue- span.content = _replace_inline_base64_img_src(- span.content,- image_writer,- page_index,- )---def save_span_image_if_needed(span: Span, image_writer: DataWriter, page_index: int) -> None:- """Persist a span-level base64 image and normalize the target path field."""- if span.image_base64:- image_path = _save_base64_image(span.image_base64, image_writer, page_index)- if image_path:- span.image_path = image_path- span.image_base64 = ""diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.pyindex 4ea9dd6e..1a744843 100644--- a/mineru/backend/vlm/model_output_to_middle_json.py+++ b/mineru/backend/vlm/model_output_to_middle_json.py@@ -12,7 +12,6 @@ from ...utils.config_reader import get_table_enablefrom ...utils.hash_utils import bytes_md5from ...utils.pdfium_guard import pdfium_guardfrom ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info-from ..utils.html_image_utils import replace_inline_table_imagesfrom ..utils.para_block_utils import (build_para_blocks_from_preproc,cleanup_internal_para_block_metadata,@@ -77,8 +76,6 @@ def blocks_to_page_info(scale=scale,)- replace_inline_table_images(table_blocks, image_writer, page_index)-page_info = PageInfo(preproc_blocks=blocks,discarded_blocks=discarded_blocks,diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.pyindex b4d14792..143e4c21 100644--- a/mineru/cli_old/common.py+++ b/mineru/cli_old/common.py@@ -247,6 +247,10 @@ def _process_output()image_dir = str(os.path.basename(local_image_dir))+ export_result = ParseResult(pages=middle_json)+ image_writer = FileBasedDataWriter(local_image_dir)+ for img_path, img_bytes in export_result.images().items():+ image_writer.write(img_path, img_bytes)if f_dump_md:md_content_str = render_markdown(@@ -273,7 +277,7 @@ def _process_output()if f_dump_middle_json:- dump_dict = ParseResult(pages=middle_json).to_dict()+ dump_dict = export_result.to_export_dict()dump_dict["_backend"] = backenddump_dict["_version_name"] = __version__md_writer.write_string(diff --git a/mineru/kit/common.py b/mineru/kit/common.pyindex 1b66ec92..0eb33cd0 100644--- a/mineru/kit/common.py+++ b/mineru/kit/common.py@@ -145,7 +145,7 @@ def save_parse_result(result: ParseResult, dest: Path, format: KitFormat) -> Non_write_utf8_text(dest, result.markdown())returnif format == "middle_json":- _write_utf8_text(dest, result.to_json())+ _write_utf8_text(dest, result.to_export_json())returnif format == "zip":tmp_dir = dest.parent / f".{dest.stem}"diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 304e2f9e..127f2766 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -1229,7 +1229,7 @@ async def _run_job(fid = file_store.create_file_for_output(f"{fr.name}.md", content_bytes, sha256hex=sha)output_files.markdown = OutputFileRef(file_id=fid, bytes=len(content_bytes))elif fmt == "middle_json":- mj = json.dumps(result.to_dict(skip_defaults=True), ensure_ascii=False).encode("utf-8")+ mj = json.dumps(result.to_export_dict(skip_defaults=True), ensure_ascii=False).encode("utf-8")sha = hashlib.sha256(mj).hexdigest()file_store.store_blob(mj, sha256hex=sha)fid = file_store.create_file_for_output(f"{fr.name}.middle.json", mj, sha256hex=sha)diff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex f333d517..74ad7a54 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -1,9 +1,8 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations-import base64+from copy import deepcopyimport json-import refrom abc import ABC, abstractmethodfrom dataclasses import dataclassfrom pathlib import Path@@ -12,8 +11,12 @@ from typing import Anyfrom ..render import render_content_list, render_markdown, render_structured_contentfrom ..schema.middle_json import MIDDLE_JSON_SCHEMA_VERSIONfrom ..types import PageInfo--_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)+from ..utils.image_payload import (+ collect_image_data_uri_bytes,+ image_path_from_data_uri,+ parse_image_data_uri,+ replace_inline_data_uri_sources,+)@dataclass@@ -58,6 +61,13 @@ class ParseResult:"pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.pages],}+ def to_export_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:+ """生成 public middle_json 视图:图片已落盘引用,base64 临时载荷不再输出。"""+ return {+ "schema_version": MIDDLE_JSON_SCHEMA_VERSION,+ "pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.export_pages()],+ }+@staticmethoddef from_json(s: str) -> ParseResult:data = json.loads(s)@@ -68,6 +78,10 @@ class ParseResult:def to_json(self) -> str:return json.dumps(self.to_dict(), ensure_ascii=False, indent=4)+ def to_export_json(self) -> str:+ """序列化导出 middle_json,供本地文件和 API 返回使用。"""+ return json.dumps(self.to_export_dict(), ensure_ascii=False, indent=4)+def markdown(self, *, add_markers: bool = False) -> str:return render_markdown(self.pages, add_markers=add_markers)@@ -79,7 +93,7 @@ class ParseResult:def save(self, writer: Any) -> None:writer.write_string("markdown.md", self.markdown())- writer.write_string("middle_json.json", self.to_json())+ writer.write_string("middle_json.json", self.to_export_json())writer.write_string("content_list.json",@@ -102,72 +116,75 @@ class ParseResult:def images(self) -> dict[str, bytes]:if self._images_cache is not None:return self._images_cache- if self._pdf_doc is not None:- return self._extract_pdf_images()- return self._extract_office_images()-- def _extract_pdf_images(self) -> dict[str, bytes]:- result: dict[str, bytes] = {}+ images = self._collect_images()+ self._images_cache = images+ return images++ def export_pages(self) -> list[PageInfo]:+ """返回可导出的页面副本:清理 base64,并把内联图片替换为本地路径。"""+ export_pages, _ = self._export_pages_and_images()+ return export_pages++ def _export_pages_and_images(self) -> tuple[list[PageInfo], dict[str, bytes]]:+ """构造导出页面和图片字节映射,避免 ParseResult.save 再渲染 PDF 页面。"""+ export_pages = deepcopy(self.pages)+ images: dict[str, bytes] = {}+ for page_info in export_pages:+ for block_list in (page_info.preproc_blocks, page_info.para_blocks, page_info.discarded_blocks):+ for block in block_list:+ self._prepare_block_images_for_export(block, images)+ return export_pages, images++ def _collect_images(self) -> dict[str, bytes]:+ """遍历原始 middle_json 收集图片字节,不修改页面和 span 内容。"""+ images: dict[str, bytes] = {}for page_info in self.pages:- pil_img, actual_scale = self._pdf_doc.render_page_with_actual_scale(page_info.page_idx) # type: ignore[union-attr]- try:- for block in page_info.preproc_blocks:- result.update(self._crop_block_spans(block, pil_img, actual_scale))- for block in page_info.para_blocks:- result.update(self._crop_block_spans(block, pil_img, actual_scale))- finally:- pil_img.close()- return result+ for block_list in (page_info.preproc_blocks, page_info.para_blocks, page_info.discarded_blocks):+ for block in block_list:+ self._collect_block_images(block, images)+ return images@staticmethod- def _crop_block_spans(block: Any, pil_img: Any, scale: float) -> dict[str, bytes]:- from ..utils.pdf_image_tools import get_crop_img, image_to_bytes-- result: dict[str, bytes] = {}+ def _collect_block_images(block: Any, images: dict[str, bytes]) -> None:+ """递归收集 block 内所有 span 的 base64 图片载荷。"""for line in block.lines:for span in line.spans:- if not span.image_path or span.bbox is None:- continue- crop = get_crop_img(span.bbox, pil_img, scale=scale)- result[span.image_path] = image_to_bytes(crop, image_format="JPEG")+ ParseResult._collect_span_images(span, images)for child in block.blocks:- result.update(ParseResult._crop_block_spans(child, pil_img, scale))- return result-- def _extract_office_images(self) -> dict[str, bytes]:- from ..utils.hash_utils import str_sha256+ ParseResult._collect_block_images(child, images)- result: dict[str, bytes] = {}- for page_info in self.pages:- for block in page_info.para_blocks:- for span in self._iter_block_spans(block):- result.update(self._decode_span_base64_images(span, str_sha256))- return result+ @staticmethod+ def _collect_span_images(span: Any, images: dict[str, bytes]) -> None:+ """收集单个 span 的图片字节,保持 span 原始内容不变。"""+ if span.image_base64:+ parsed = parse_image_data_uri(span.image_base64)+ img_path = span.image_path or image_path_from_data_uri(span.image_base64)+ if parsed is not None and img_path:+ images[img_path] = parsed[0]+ if span.content:+ collect_image_data_uri_bytes(span.content, images)@staticmethod- def _iter_block_spans(block: Any):+ def _prepare_block_images_for_export(block: Any, images: dict[str, bytes]) -> None:+ """递归处理 block 内所有 span,将 base64 图片转为 image_path 引用。"""for line in block.lines:- yield from line.spans+ for span in line.spans:+ ParseResult._prepare_span_images_for_export(span, images)for child in block.blocks:- yield from ParseResult._iter_block_spans(child)+ ParseResult._prepare_block_images_for_export(child, images)@staticmethod- def _decode_span_base64_images(span: Any, hash_fn) -> dict[str, bytes]:- result: dict[str, bytes] = {}+ def _prepare_span_images_for_export(span: Any, images: dict[str, bytes]) -> None:+ """处理单个 span 的图片载荷,保留路径字段并清理 base64 临时字段。"""if span.image_base64:- m = _INLINE_IMAGE_DATA_URI_RE.match(span.image_base64)- if m:- try:- result[span.image_path or f"{hash_fn(span.image_base64)}.{m.group(1)}"] = base64.b64decode(m.group(2))- except Exception:- pass+ parsed = parse_image_data_uri(span.image_base64)+ img_path = span.image_path or image_path_from_data_uri(span.image_base64)+ if parsed is not None and img_path:+ images[img_path] = parsed[0]+ span.image_path = img_path+ span.image_base64 = ""if span.content:- for m in _INLINE_IMAGE_DATA_URI_RE.finditer(span.content):- try:- result[f"{hash_fn(m.group(0))}.{m.group(1)}"] = base64.b64decode(m.group(2))- except Exception:- pass- return result+ span.content = replace_inline_data_uri_sources(span.content, images)class DocumentParser(ABC):diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.pyindex c7741211..aa8a8f4e 100644--- a/mineru/parser/pdf.py+++ b/mineru/parser/pdf.py@@ -133,12 +133,7 @@ class PdfBaseParser(DocumentParser):pdf_bytes: bytes,file_name: str,) -> ParseResult:- from ..utils.pdf_document import PDFDocument-- return ParseResult(- pages=middle_json,- _pdf_doc=PDFDocument(pdf_bytes),- )+ return ParseResult(pages=middle_json)class PdfVlmParser(PdfBaseParser):diff --git a/mineru/utils/cut_image.py b/mineru/utils/cut_image.pyindex da09f958..3bd263fd 100644--- a/mineru/utils/cut_image.py+++ b/mineru/utils/cut_image.py@@ -6,7 +6,8 @@ from typing import Anyfrom loguru import loggerfrom ..types import BBox, Span-from .pdf_image_tools import cut_image+from .image_payload import image_bytes_to_data_uri, image_path_from_key+from .pdf_image_tools import get_crop_img, image_to_bytesdef cut_image_and_table(@@ -23,17 +24,16 @@ def cut_image_and_table(span_type = span.type- if not check_img_bbox(span.bbox) or not image_writer:+ if not check_img_bbox(span.bbox):span.image_path = ""+ span.image_base64 = ""else:- span.image_path = cut_image(- span.bbox,- page_id,- page_pil_img,- return_path=return_path(span_type),- image_writer=image_writer,- scale=scale,- )+ filename = f"{page_id}_{int(span.bbox[0])}_{int(span.bbox[1])}_{int(span.bbox[2])}_{int(span.bbox[3])}"+ path_key = f"{return_path(span_type)}_{filename}"+ crop_img = get_crop_img(span.bbox, page_pil_img, scale=scale)+ img_bytes = image_to_bytes(crop_img, image_format="JPEG")+ span.image_path = image_path_from_key(path_key, "jpg")+ span.image_base64 = image_bytes_to_data_uri(img_bytes, "jpeg")return spandiff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.pynew file mode 100644index 00000000..9bafc3e9--- /dev/null+++ b/mineru/utils/image_payload.py@@ -0,0 +1,91 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++import base64+import re++from .hash_utils import str_sha256++INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;\"']+);base64,([^\"']+)", re.DOTALL)+INLINE_IMAGE_SRC_RE = re.compile(r'src="(data:image/[^"]+)"', re.DOTALL)+++def normalize_image_extension(fmt: str) -> str:+ """规范化图片扩展名,保证同一图片格式生成稳定文件名。"""+ normalized = fmt.lower().split("+", 1)[0]+ return "jpg" if normalized in {"jpeg", "jpg"} else normalized+++def image_bytes_to_data_uri(img_bytes: bytes, image_format: str = "JPEG") -> str:+ """把图片字节编码成 data URI,作为 middle_json 中的临时图片载荷。"""+ fmt = image_format.lower()+ mime_fmt = "jpeg" if fmt in {"jpg", "jpeg"} else fmt+ payload = base64.b64encode(img_bytes).decode("ascii")+ return f"data:image/{mime_fmt};base64,{payload}"+++def parse_image_data_uri(data_uri: str) -> tuple[bytes, str] | None:+ """解析 data URI,返回图片字节和规范化扩展名;非法输入返回 None。"""+ match = re.fullmatch(r"data:image/([^;]+);base64,(.+)", data_uri, re.DOTALL)+ if match is None:+ return None+ try:+ return base64.b64decode(match.group(2)), normalize_image_extension(match.group(1))+ except Exception:+ return None+++def image_path_from_data_uri(data_uri: str) -> str | None:+ """根据 data URI 内容生成稳定图片路径,供没有显式 image_path 的 span 使用。"""+ parsed = parse_image_data_uri(data_uri)+ if parsed is None:+ return None+ _, ext = parsed+ return f"{str_sha256(data_uri)}.{ext}"+++def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:+ """复用旧裁图路径哈希规则,根据逻辑路径生成稳定图片文件名。"""+ ext = normalize_image_extension(image_format)+ return f"{str_sha256(path_key)}.{ext}"+++def collect_image_data_uri_bytes(markup: str, images: dict[str, bytes]) -> None:+ """只收集文本或 HTML 中的 data URI 图片字节,不修改原始内容。"""+ if not markup or "data:image/" not in markup:+ return+ for match in INLINE_IMAGE_DATA_URI_RE.finditer(markup):+ data_uri = match.group(0)+ parsed = parse_image_data_uri(data_uri)+ img_path = image_path_from_data_uri(data_uri)+ if parsed is None or img_path is None:+ continue+ images[img_path] = parsed[0]+++def replace_inline_data_uri_sources(markup: str, images: dict[str, bytes]) -> str:+ """把 HTML src 中的 data URI 图片替换为本地路径,并同步收集图片字节。"""+ if not markup or "data:image/" not in markup:+ return markup++ def _store_data_uri(data_uri: str) -> str | None:+ parsed = parse_image_data_uri(data_uri)+ img_path = image_path_from_data_uri(data_uri)+ if parsed is None or img_path is None:+ return None+ images[img_path] = parsed[0]+ return img_path++ def _replace_src(match: re.Match[str]) -> str:+ img_path = _store_data_uri(match.group(1))+ if img_path is None:+ return match.group(0)+ return f'src="{img_path}"'++ replaced = INLINE_IMAGE_SRC_RE.sub(_replace_src, markup)++ def _replace_bare_data_uri(match: re.Match[str]) -> str:+ img_path = _store_data_uri(match.group(0))+ return img_path or match.group(0)++ return INLINE_IMAGE_DATA_URI_RE.sub(_replace_bare_data_uri, replaced)diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.pyindex 6188de99..5d3bdc3e 100644--- a/tests/unittest/test_parse_result_contract.py+++ b/tests/unittest/test_parse_result_contract.py@@ -1,3 +1,4 @@+import base64from dataclasses import fieldsimport json@@ -8,6 +9,10 @@ from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSIONfrom mineru.types import Block, ContentType, Line, PageInfo, Span+def _data_uri(payload: bytes, image_type: str = "png") -> str:+ return f"data:image/{image_type};base64,{base64.b64encode(payload).decode('ascii')}"++def test_parse_result_does_not_expose_backend_version_or_file_name() -> None:field_names = {field.name for field in fields(ParseResult)}@@ -207,3 +212,119 @@ def test_parse_result_structured_content_method_and_save_name() -> None:assert structured_content[0][0]["content"]["paragraph_content"][0]["content"] == "hello"assert "structured_content.json" in writesassert "content_list" + "_v2.json" not in writes+++def test_parse_result_render_methods_use_original_pages(monkeypatch: pytest.MonkeyPatch) -> None:+ page = PageInfo(+ page_idx=0,+ page_size=(100, 100),+ para_blocks=[+ Block(+ index=0,+ type="text",+ bbox=(0.0, 0.0, 10.0, 10.0),+ lines=[+ Line(+ bbox=(0.0, 0.0, 10.0, 10.0),+ spans=[Span(type=ContentType.TEXT, bbox=(0.0, 0.0, 10.0, 10.0), content="raw pages")],+ )+ ],+ )+ ],+ _backend="pipeline",+ )+ result = ParseResult(pages=[page])++ def fail_export_pages(self: ParseResult) -> list[PageInfo]:+ """如果 render 方法依赖导出视图,测试应立即失败。"""+ raise AssertionError("render methods should use original pages")++ monkeypatch.setattr(ParseResult, "export_pages", fail_export_pages)++ assert result.markdown() == "raw pages"+ assert result.content_list()[0]["text"] == "raw pages"+ assert result.structured_content()[0][0]["content"]["paragraph_content"][0]["content"] == "raw pages"+++def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json() -> None:+ img_bytes = b"image-bytes"+ page = PageInfo(+ page_idx=0,+ page_size=(100, 100),+ para_blocks=[+ Block(+ index=0,+ type="image",+ bbox=(0.0, 0.0, 10.0, 10.0),+ lines=[+ Line(+ bbox=(0.0, 0.0, 10.0, 10.0),+ spans=[+ Span(+ type=ContentType.IMAGE,+ bbox=(0.0, 0.0, 10.0, 10.0),+ image_path="figure.png",+ image_base64=_data_uri(img_bytes),+ )+ ],+ )+ ],+ )+ ],+ _backend="pipeline",+ )+ result = ParseResult(pages=[page])+ writes: dict[str, bytes | str] = {}++ class MemoryWriter:+ def write_string(self, path: str, content: str) -> None:+ """记录导出文本,确认 public middle_json 不再携带 base64。"""+ writes[path] = content++ def write(self, path: str, content: bytes) -> None:+ """记录导出图片,确认图片统一由 ParseResult 落盘。"""+ writes[path] = content++ result.save(MemoryWriter())+ exported = json.loads(writes["middle_json.json"]) # type: ignore[arg-type]+ exported_span = exported["pages"][0]["para_blocks"][0]["lines"][0]["spans"][0]++ assert result.to_dict()["pages"][0]["para_blocks"][0]["lines"][0]["spans"][0]["image_base64"]+ assert exported_span["image_path"] == "figure.png"+ assert "image_base64" not in exported_span+ assert writes["figure.png"] == img_bytes+++def test_parse_result_export_rewrites_inline_table_base64_images() -> None:+ img_bytes = b"table-image"+ inline_image = _data_uri(img_bytes)+ html = f'<table><tr><td><img src="{inline_image}"/></td></tr></table>'+ page = PageInfo(+ page_idx=0,+ page_size=(100, 100),+ para_blocks=[+ Block(+ index=0,+ type="table",+ bbox=(0.0, 0.0, 10.0, 10.0),+ lines=[+ Line(+ bbox=(0.0, 0.0, 10.0, 10.0),+ spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],+ )+ ],+ )+ ],+ _backend="pipeline",+ )++ result = ParseResult(pages=[page])+ images = result.images()+ exported_page = result.export_pages()[0]+ exported_span = exported_page.para_blocks[0].lines[0].spans[0]+ exported_json = json.dumps(result.to_export_dict(), ensure_ascii=False)++ assert list(images.values()) == [img_bytes]+ assert inline_image not in exported_json+ assert 'src="' in exported_span.content+ assert next(iter(images)) in exported_json