Skip to content

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

feat: refactor export page handling to ensure clean public rendering without inline base64 images

myhlolie52bd0d19dff
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 05b3c852..6c00f908 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -298,10 +298,18 @@ def _process_output(
image_writer = FileBasedDataWriter(local_image_dir)
for img_path, img_bytes in export_result.images().items():
image_writer.write(img_path, img_bytes)
+ public_render_pages: list[PageInfo] | None = None
+
+ def get_public_render_pages() -> list[PageInfo]:
+ """按需生成 public 渲染页副本,避免 staged base64 载荷进入 markdown/content 输出。"""
+ nonlocal public_render_pages
+ if public_render_pages is None:
+ public_render_pages = export_result.export_pages()
+ return public_render_pages
if f_dump_md:
md_content_str = render_markdown(
- middle_json,
+ get_public_render_pages(),
image_dir,
no_rich_content=(f_make_md_mode != "mm_markdown"),
)
@@ -311,13 +319,13 @@ def _process_output(
)
if f_dump_content_list:
- content_list = render_content_list(middle_json, image_dir)
+ content_list = render_content_list(get_public_render_pages(), image_dir)
md_writer.write_string(
f"{pdf_file_name}_content_list.json",
json.dumps(content_list, ensure_ascii=False, indent=4),
)
- structured_content = render_structured_content(middle_json, image_dir)
+ structured_content = render_structured_content(get_public_render_pages(), image_dir)
md_writer.write_string(
f"{pdf_file_name}_structured_content.json",
json.dumps(structured_content, ensure_ascii=False, indent=4),
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index c47b046e..b235f27e 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -12,7 +12,6 @@ from ..render import render_content_list, render_markdown, render_structured_con
from ..schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
from ..types import PageInfo
from ..utils.image_payload import (
- collect_image_data_uri_bytes,
image_path_from_data_uri,
parse_image_data_uri,
replace_inline_data_uri_sources,
@@ -45,6 +44,7 @@ class ParseResult:
pages: list[PageInfo]
_pdf_doc: object | None = None
_model_output: Any = None
+ _export_pages_cache: list[PageInfo] | None = None
_images_cache: dict[str, bytes] | None = None
_retained_page_indices: list[int] | None = None
_broken_page_indices: list[int] | None = None
@@ -95,7 +95,7 @@ class ParseResult:
"""生成 public middle_json 视图:图片已落盘引用,base64 临时载荷不再输出。"""
payload = {
"schema_version": MIDDLE_JSON_SCHEMA_VERSION,
- "pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.export_pages()],
+ "pages": [page.to_dict(skip_defaults=skip_defaults) for page in self._public_render_pages()],
}
self._append_private_pdf_page_mapping(payload)
return payload
@@ -121,14 +121,19 @@ class ParseResult:
"""序列化导出 middle_json,供本地文件和 API 返回使用。"""
return json.dumps(self.to_export_dict(), ensure_ascii=False, indent=4)
+ def _public_render_pages(self) -> list[PageInfo]:
+ """返回 public 渲染使用的导出页副本,避免 staged base64 载荷进入用户产物。"""
+ export_pages, _ = self._ensure_export_cache()
+ return export_pages
+
def markdown(self, *, add_markers: bool = False) -> str:
- return render_markdown(self.pages, add_markers=add_markers)
+ return render_markdown(self._public_render_pages(), add_markers=add_markers)
def content_list(self) -> list[dict[str, Any]]:
- return render_content_list(self.pages)
+ return render_content_list(self._public_render_pages())
def structured_content(self) -> list[list[dict[str, Any]]]:
- return render_structured_content(self.pages)
+ return render_structured_content(self._public_render_pages())
def save(self, writer: Any) -> None:
writer.write_string("markdown.md", self.markdown())
@@ -153,16 +158,21 @@ class ParseResult:
writer.write(img_path, img_bytes)
def images(self) -> dict[str, bytes]:
- if self._images_cache is not None:
- return self._images_cache
- images = self._collect_images()
- self._images_cache = images
+ _, images = self._ensure_export_cache()
return images
def export_pages(self) -> list[PageInfo]:
"""返回可导出的页面副本:清理 base64,并把内联图片替换为本地路径。"""
- export_pages, _ = self._export_pages_and_images()
- return export_pages
+ export_pages, _ = self._ensure_export_cache()
+ return deepcopy(export_pages)
+
+ def _ensure_export_cache(self) -> tuple[list[PageInfo], dict[str, bytes]]:
+ """缓存 public 导出视图,避免多格式输出重复深拷贝和 base64 解码。"""
+ if self._export_pages_cache is None or self._images_cache is None:
+ export_pages, images = self._export_pages_and_images()
+ self._export_pages_cache = export_pages
+ self._images_cache = images
+ return self._export_pages_cache, self._images_cache
def _export_pages_and_images(self) -> tuple[list[PageInfo], dict[str, bytes]]:
"""构造导出页面和图片字节映射,避免 ParseResult.save 再渲染 PDF 页面。"""
@@ -174,35 +184,6 @@ class ParseResult:
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:
- 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 _collect_block_images(block: Any, images: dict[str, bytes]) -> None:
- """递归收集 block 内所有 span 的 base64 图片载荷。"""
- for line in block.lines:
- for span in line.spans:
- ParseResult._collect_span_images(span, images)
- for child in block.blocks:
- ParseResult._collect_block_images(child, images)
-
- @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 _prepare_block_images_for_export(block: Any, images: dict[str, bytes]) -> None:
"""递归处理 block 内所有 span,将 base64 图片转为 image_path 引用。"""
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index 234fc47c..c975b020 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -245,19 +245,24 @@ def test_parse_result_structured_content_method_and_save_name() -> None:
assert "content_list" + "_v2.json" not in writes
-def test_parse_result_render_methods_use_original_pages(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_parse_result_render_methods_use_export_pages_without_mutating_source(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ img_bytes = b"render-inline-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="text",
+ 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.TEXT, bbox=(0.0, 0.0, 10.0, 10.0), content="raw pages")],
+ spans=[Span(type=ContentType.TABLE, bbox=(0.0, 0.0, 10.0, 10.0), content=html)],
)
],
)
@@ -265,16 +270,40 @@ def test_parse_result_render_methods_use_original_pages(monkeypatch: pytest.Monk
_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"
+ captured: list[list[PageInfo]] = []
+
+ def _assert_clean_export_pages(pages: list[PageInfo]) -> None:
+ """确认 public 渲染入口收到的是清理后的导出页副本,而不是带 staged 载荷的原始页。"""
+ captured.append(pages)
+ content = pages[0].para_blocks[0].lines[0].spans[0].content
+ assert inline_image not in content
+ assert next(iter(result.images())) in content
+
+ def fake_render_markdown(pages: list[PageInfo], *args, **kwargs) -> str:
+ """记录 markdown 渲染输入,避免测试依赖具体 markdown 输出细节。"""
+ _assert_clean_export_pages(pages)
+ return "markdown"
+
+ def fake_render_content_list(pages: list[PageInfo], *args, **kwargs) -> list[dict[str, str]]:
+ """记录 content_list 渲染输入,验证导出视图在所有 public 渲染方法中一致。"""
+ _assert_clean_export_pages(pages)
+ return [{"type": "table"}]
+
+ def fake_render_structured_content(pages: list[PageInfo], *args, **kwargs) -> list[list[dict[str, str]]]:
+ """记录 structured_content 渲染输入,覆盖最新评论指出的 data URI 残留路径。"""
+ _assert_clean_export_pages(pages)
+ return [[{"type": "table"}]]
+
+ monkeypatch.setattr("mineru.parser.base.render_markdown", fake_render_markdown)
+ monkeypatch.setattr("mineru.parser.base.render_content_list", fake_render_content_list)
+ monkeypatch.setattr("mineru.parser.base.render_structured_content", fake_render_structured_content)
+
+ assert result.markdown() == "markdown"
+ assert result.content_list() == [{"type": "table"}]
+ assert result.structured_content() == [[{"type": "table"}]]
+ assert len(captured) == 3
+ assert all(pages is not result.pages for pages in captured)
+ assert inline_image in page.para_blocks[0].lines[0].spans[0].content
def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json() -> None:
@@ -326,6 +355,139 @@ def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json()
assert writes["figure.png"] == img_bytes
+def test_parse_result_save_renders_structured_content_from_clean_export_pages() -> 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])
+ writes: dict[str, bytes | str] = {}
+
+ class MemoryWriter:
+ def write_string(self, path: str, content: str) -> None:
+ """记录 save 写出的文本产物,验证 public 文件不再携带内联 base64 图片。"""
+ writes[path] = content
+
+ def write(self, path: str, content: bytes) -> None:
+ """记录 save 写出的图片产物,验证导出视图引用的图片确实落盘。"""
+ writes[path] = content
+
+ result.save(MemoryWriter())
+ image_path = next(iter(result.images()))
+ structured_content = writes["structured_content.json"]
+
+ assert isinstance(structured_content, str)
+ assert inline_image not in structured_content
+ assert image_path in structured_content
+ assert writes[image_path] == img_bytes
+ assert inline_image in page.para_blocks[0].lines[0].spans[0].content
+
+
+def test_parse_result_public_outputs_reuse_export_cache(monkeypatch: pytest.MonkeyPatch) -> None:
+ img_bytes = b"cached-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])
+ original_export = result._export_pages_and_images
+ export_call_count = 0
+
+ def counted_export_pages_and_images():
+ """统计导出视图构造次数,确保多 public 输出复用同一份缓存。"""
+ nonlocal export_call_count
+ export_call_count += 1
+ return original_export()
+
+ monkeypatch.setattr(result, "_export_pages_and_images", counted_export_pages_and_images)
+
+ output_text = json.dumps(
+ {
+ "markdown": result.markdown(),
+ "content_list": result.content_list(),
+ "structured_content": result.structured_content(),
+ "middle_json": result.to_export_dict(),
+ "images": sorted(result.images()),
+ },
+ ensure_ascii=False,
+ )
+
+ assert export_call_count == 1
+ assert inline_image not in output_text
+ assert next(iter(result.images())) in output_text
+ assert inline_image in page.para_blocks[0].lines[0].spans[0].content
+
+
+def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:
+ img_bytes = b"defensive-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])
+ first_export = result.export_pages()
+ first_export[0].para_blocks[0].lines[0].spans[0].content = "mutated by caller"
+
+ second_export = result.export_pages()
+ second_content = second_export[0].para_blocks[0].lines[0].spans[0].content
+ exported_json = json.dumps(result.to_export_dict(), ensure_ascii=False)
+
+ assert "mutated by caller" not in second_content
+ assert "mutated by caller" not in exported_json
+ assert inline_image not in second_content
+ assert inline_image not in exported_json
+ assert next(iter(result.images())) in exported_json
+
+
def test_parse_result_export_rewrites_inline_table_base64_images() -> None:
img_bytes = b"table-image"
inline_image = _data_uri(img_bytes)