Skip to content

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

feat: integrate ImagePayloadCache for improved image handling and path management

myhloli4c1548d8b0cb
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index 21b0afd3..0999732a 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -19,6 +19,7 @@ from ...types import NOT_EXTRACT_TYPES, BBox, PageInfo
from ...types import BlockType as MineruBlockType
from ...utils.config_reader import get_device, get_processing_window_size
from ...utils.enum_class import ImageType
+from ...utils.image_payload import ImagePayloadCache
from ...utils.model_utils import clean_memory, crop_img, get_vram
from ...utils.ocr_utils import (
OcrConfidence,
@@ -739,6 +740,7 @@ def doc_analyze(
server_url: str | None = None,
image_analysis: bool = True,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
**kwargs: object,
) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -835,6 +837,7 @@ def doc_analyze(
_ocr_enable=_ocr_enable,
_vlm_ocr_enable=_vlm_ocr_enable,
progress_bar=progress_bar,
+ image_cache=image_cache,
)
last_append_end_time = time.time()
finally:
@@ -890,6 +893,7 @@ async def aio_doc_analyze(
server_url: str | None = None,
image_analysis: bool = True,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
**kwargs: object,
) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -988,6 +992,7 @@ async def aio_doc_analyze(
_ocr_enable=_ocr_enable,
_vlm_ocr_enable=_vlm_ocr_enable,
progress_bar=progress_bar,
+ image_cache=image_cache,
)
last_append_end_time = time.time()
finally:
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.py
index 62f5525b..c5f8918e 100644
--- a/mineru/backend/hybrid/model_output_to_middle_json.py
+++ b/mineru/backend/hybrid/model_output_to_middle_json.py
@@ -8,6 +8,7 @@ from typing import Any
from ...types import Block, BlockType, PageInfo
from ...utils.config_reader import get_table_enable
from ...utils.hash_utils import bytes_md5
+from ...utils.image_payload import ImagePayloadCache
from ...utils.pdf_document import PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ..pipeline.model_init import MineruHybridModel
@@ -45,6 +46,7 @@ def blocks_to_page_info(
page_index: int,
_ocr_enable: bool,
_vlm_ocr_enable: bool,
+ image_cache: ImagePayloadCache | None = None,
) -> PageInfo:
"""将blocks转换为页面信息"""
@@ -104,6 +106,7 @@ def blocks_to_page_info(
page_img_md5,
page_index,
scale=scale,
+ image_cache=image_cache,
)
page_info = PageInfo(
diff --git a/mineru/backend/office/docx_analyze.py b/mineru/backend/office/docx_analyze.py
index 6912f5e8..584a9781 100644
--- a/mineru/backend/office/docx_analyze.py
+++ b/mineru/backend/office/docx_analyze.py
@@ -7,10 +7,11 @@ from loguru import logger
from ...model.docx.main import convert_binary
from ...types import PageInfo
+from ...utils.image_payload import ImagePayloadCache
from .model_output_to_middle_json import result_to_middle_json
-def office_docx_analyze(file_bytes: bytes) -> tuple[list[PageInfo], list[Any]]:
+def office_docx_analyze(file_bytes: bytes, image_cache: ImagePayloadCache | None = None) -> tuple[list[PageInfo], list[Any]]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
@@ -20,7 +21,7 @@ def office_docx_analyze(file_bytes: bytes) -> tuple[list[PageInfo], list[Any]]:
safe_time = max(infer_time, 0.01)
logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / safe_time, 3)} page/s")
- middle_json = result_to_middle_json(results)
+ middle_json = result_to_middle_json(results, image_cache=image_cache)
return middle_json, results
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
index f4cb9b95..c5161b9d 100644
--- a/mineru/backend/office/model_output_to_middle_json.py
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -6,14 +6,18 @@ from collections import defaultdict
from typing import Any
from ...types import Block, BlockType, PageInfo
-from ...utils.image_payload import image_path_from_data_uri
+from ...utils.image_payload import ImagePayloadCache
from .office_magic_model import MagicModel
-def blocks_to_page_info(page_blocks: list[dict[str, Any]], page_index: int) -> PageInfo:
+def blocks_to_page_info(
+ page_blocks: list[dict[str, Any]],
+ page_index: int,
+ image_cache: ImagePayloadCache | None = None,
+) -> PageInfo:
"""将blocks转换为页面信息"""
- magic_model = MagicModel(page_blocks)
+ magic_model = MagicModel(page_blocks, image_cache)
image_blocks = magic_model.get_image_blocks()
table_blocks = magic_model.get_table_blocks()
chart_blocks = magic_model.get_chart_blocks()
@@ -45,22 +49,9 @@ def blocks_to_page_info(page_blocks: list[dict[str, Any]], page_index: int) -> P
page_idx=page_index,
_backend="office",
)
- _populate_image_paths_from_base64(page_info)
return page_info
-def _populate_image_paths_from_base64(page_info: PageInfo) -> None:
- """为 Office 内联 base64 图片生成稳定 image_path,保留图片字节给后续统一写出。"""
- for block_list in (page_info.para_blocks, page_info.discarded_blocks):
- for block in block_list:
- for span in block.all_spans():
- if span.image_path or not span.image_base64:
- continue
- image_path = image_path_from_data_uri(span.image_base64)
- if image_path is not None:
- span.image_path = image_path
-
-
def _extract_section_parts_from_content(content: str, level: int) -> list[int] | None:
"""Try to extract a leading section number (e.g. '1.2.1') from title content.
@@ -118,10 +109,13 @@ def _link_index_entries_by_anchor(middle_json: list[PageInfo]) -> None:
text_block.anchor = anchor
-def result_to_middle_json(model_output_blocks_list: list[list[dict[str, Any]]]) -> list[PageInfo]:
+def result_to_middle_json(
+ model_output_blocks_list: list[list[dict[str, Any]]],
+ image_cache: ImagePayloadCache | None = None,
+) -> list[PageInfo]:
middle_json: list[PageInfo] = []
for index, page_blocks in enumerate(model_output_blocks_list):
- page_info = blocks_to_page_info(page_blocks, index)
+ page_info = blocks_to_page_info(page_blocks, index, image_cache=image_cache)
middle_json.append(page_info)
section_counters: dict[int, int] = defaultdict(int)
diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.py
index c2850586..5ead7251 100644
--- a/mineru/backend/office/office_magic_model.py
+++ b/mineru/backend/office/office_magic_model.py
@@ -7,12 +7,14 @@ from typing import Any, Literal
from urllib.parse import urlparse
from ...types import EMPTY_BBOX, Block, BlockType, ContentType, Line, Span
+from ...utils.image_payload import ImagePayloadCache
from ..utils.magic_model_utils import tie_up_category_by_index
class MagicModel:
- def __init__(self, page_blocks: list[dict[str, Any]]) -> None:
+ def __init__(self, page_blocks: list[dict[str, Any]], image_cache: ImagePayloadCache | None = None) -> None:
blocks: list[Block] = []
+ image_cache = image_cache or ImagePayloadCache()
# 对caption块进行分类,将其分类为image_caption, table_caption, chart_caption
page_blocks = classify_caption_blocks(page_blocks)
@@ -38,15 +40,27 @@ class MagicModel:
elif block_type in ["image"]:
block_type = BlockType.IMAGE_BODY
- span = Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_base64=block_content)
+ span = Span(
+ type=ContentType.IMAGE,
+ bbox=EMPTY_BBOX,
+ image_path=image_cache.register_data_uri(block_content),
+ )
elif block_type in ["table"]:
block_type = BlockType.TABLE_BODY
- span = Span(type=ContentType.TABLE, bbox=EMPTY_BBOX, content=clean_table_html(block_content))
+ span = Span(
+ type=ContentType.TABLE,
+ bbox=EMPTY_BBOX,
+ content=image_cache.replace_html_data_uri_sources(clean_table_html(block_content)),
+ )
elif block_type in ["chart"]:
block_type = BlockType.CHART_BODY
- span = Span(type=ContentType.CHART, bbox=EMPTY_BBOX, content=block_content)
+ span = Span(
+ type=ContentType.CHART,
+ bbox=EMPTY_BBOX,
+ content=image_cache.replace_html_data_uri_sources(block_content),
+ )
if block_info.get("image_base64"):
- span.image_base64 = block_info["image_base64"]
+ span.image_path = image_cache.register_data_uri(block_info["image_base64"])
elif block_type in ["equation"]:
block_type = BlockType.INTERLINE_EQUATION
span = Span(type=ContentType.INTERLINE_EQUATION, bbox=EMPTY_BBOX, content=block_content)
diff --git a/mineru/backend/office/pptx_analyze.py b/mineru/backend/office/pptx_analyze.py
index 3ba3c5d6..b3d23fcd 100644
--- a/mineru/backend/office/pptx_analyze.py
+++ b/mineru/backend/office/pptx_analyze.py
@@ -9,10 +9,11 @@ from loguru import logger
from ...model.pptx.main import convert_binary
from ...types import PageInfo
+from ...utils.image_payload import ImagePayloadCache
from .model_output_to_middle_json import result_to_middle_json
-def office_pptx_analyze(file_bytes: bytes) -> tuple[list[PageInfo], list[Any]]:
+def office_pptx_analyze(file_bytes: bytes, image_cache: ImagePayloadCache | None = None) -> tuple[list[PageInfo], list[Any]]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
@@ -22,7 +23,7 @@ def office_pptx_analyze(file_bytes: bytes) -> tuple[list[PageInfo], list[Any]]:
safe_time = max(infer_time, 0.01)
logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / safe_time, 3)} page/s")
- middle_json = result_to_middle_json(results)
+ middle_json = result_to_middle_json(results, image_cache=image_cache)
return middle_json, results
diff --git a/mineru/backend/office/xlsx_analyze.py b/mineru/backend/office/xlsx_analyze.py
index a66d387b..d03bd272 100644
--- a/mineru/backend/office/xlsx_analyze.py
+++ b/mineru/backend/office/xlsx_analyze.py
@@ -9,10 +9,11 @@ from loguru import logger
from ...model.xlsx.main import convert_binary
from ...types import PageInfo
+from ...utils.image_payload import ImagePayloadCache
from .model_output_to_middle_json import result_to_middle_json
-def office_xlsx_analyze(file_bytes: bytes) -> tuple[list[PageInfo], list[Any]]:
+def office_xlsx_analyze(file_bytes: bytes, image_cache: ImagePayloadCache | None = None) -> tuple[list[PageInfo], list[Any]]:
infer_start = time.time()
file_stream = BytesIO(file_bytes)
@@ -22,7 +23,7 @@ def office_xlsx_analyze(file_bytes: bytes) -> tuple[list[PageInfo], list[Any]]:
safe_time = max(infer_time, 0.01)
logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / safe_time, 3)} page/s")
- middle_json = result_to_middle_json(results)
+ middle_json = result_to_middle_json(results, image_cache=image_cache)
return middle_json, results
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 4041611b..686840ed 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -3,6 +3,7 @@ from typing import Any
from ...types import Block, BlockType, ContentType, PageInfo, Span
from ...utils.hash_utils import bytes_md5
+from ...utils.image_payload import ImagePayloadCache
from ...utils.page_index import resolve_output_page_idx
from ...utils.pdf_document import PDFDocument, PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
@@ -21,6 +22,7 @@ def blocks_to_page_info(
pdf_page: PDFPage,
page_index: int,
ocr_enable: bool = False,
+ image_cache: ImagePayloadCache | None = None,
) -> PageInfo:
scale = image_dict["scale"]
page_pil_img = image_dict["img_pil"]
@@ -39,6 +41,7 @@ def blocks_to_page_info(
page_img_md5,
page_index,
scale=scale,
+ image_cache=image_cache,
)
return PageInfo(
@@ -65,6 +68,7 @@ def append_batch_results_to_middle_json(
model_list: list[dict[str, Any]] | None = None,
page_index_map: list[int] | None = None,
progress_bar: Any = None,
+ image_cache: ImagePayloadCache | None = None,
) -> None:
page_model_infos = []
for offset, (image_dict, page_layout_dets) in enumerate(zip(images_list, batch_results)):
@@ -86,6 +90,7 @@ def append_batch_results_to_middle_json(
page_index_map=page_index_map,
ocr_enable=ocr_enable,
progress_bar=progress_bar,
+ image_cache=image_cache,
)
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index a2c44fc5..94152207 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -12,6 +12,7 @@ from tqdm import tqdm
from ...utils.config_reader import get_device, get_processing_window_size
from ...utils.enum_class import ImageType
+from ...utils.image_payload import ImagePayloadCache
from ...utils.model_utils import clean_memory, get_vram
from ...utils.pdf_document import PDFDocument
from ...utils.pdf_image_tools import load_images_from_pdf_bytes_range
@@ -148,11 +149,14 @@ def doc_analyze_streaming(
table_enable: bool = True,
client_side_output_generation: bool = False,
page_index_map_list: list[list[int] | None] | None = None,
+ image_cache_list: list[ImagePayloadCache] | None = None,
) -> None:
if len(pdf_bytes_list) != len(lang_list):
raise ValueError("pdf_bytes_list and lang_list must have the same length")
if page_index_map_list is not None and len(page_index_map_list) != len(pdf_bytes_list):
raise ValueError("page_index_map_list must have the same length as pdf_bytes_list")
+ if image_cache_list is not None and len(image_cache_list) != len(pdf_bytes_list):
+ raise ValueError("image_cache_list must have the same length as pdf_bytes_list")
doc_contexts = []
try:
@@ -173,6 +177,7 @@ def doc_analyze_streaming(
"lang": lang,
"ocr_enable": _ocr_enable,
"page_index_map": page_index_map_list[doc_index] if page_index_map_list is not None else None,
+ "image_cache": image_cache_list[doc_index] if image_cache_list is not None else None,
"closed": False,
}
except Exception:
@@ -278,6 +283,7 @@ def doc_analyze_streaming(
model_list=context["model_list"],
page_index_map=context["page_index_map"],
progress_bar=progress_bar,
+ image_cache=context["image_cache"],
)
result_offset += take_count
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index 3a25d16d..f437222a 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -11,6 +11,7 @@ import copy
from typing import Any, Callable, Iterator, TypeVar, Union
from ...types import Block, PageInfo, Span
+from ...utils.image_payload import ImagePayloadCache
from ...utils.ocr_utils import OcrConfidence, rotate_vertical_crop_if_needed
from ...utils.page_index import resolve_output_page_idx
from ...utils.pdf_document import PDFDocument, PDFPage
@@ -33,6 +34,7 @@ def append_pages(
page_start_index: int = 0,
page_index_map: list[int] | None = None,
progress_bar: Any = None,
+ image_cache: ImagePayloadCache | None = None,
**kwargs: Any,
) -> None:
"""Append per-page results to `middle_json` list.
@@ -46,7 +48,16 @@ def append_pages(
output_page_idx = resolve_output_page_idx(physical_page_idx, page_index_map)
pdf_page = pdf_doc[physical_page_idx]
- page_info = page_cvt_fn(copy.deepcopy(page_data), image_dict, pdf_page, output_page_idx, **kwargs)
+ converter_kwargs = dict(kwargs)
+ if image_cache is not None:
+ converter_kwargs["image_cache"] = image_cache
+ page_info = page_cvt_fn(
+ copy.deepcopy(page_data),
+ image_dict,
+ pdf_page,
+ output_page_idx,
+ **converter_kwargs,
+ )
if page_info is None:
page_w, page_h = map(int, pdf_page.size)
diff --git a/mineru/backend/utils/visual_span_utils.py b/mineru/backend/utils/visual_span_utils.py
index dc54223d..6bb383aa 100644
--- a/mineru/backend/utils/visual_span_utils.py
+++ b/mineru/backend/utils/visual_span_utils.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from typing import Any
from ...types import Block, ContentType
+from ...utils.image_payload import ImagePayloadCache
from ...utils.cut_image import cut_image_and_table
from .para_block_utils import iter_block_spans
@@ -21,6 +22,7 @@ def cut_visual_spans_in_blocks(
page_img_md5: str,
page_index: int,
scale: float = 2,
+ image_cache: ImagePayloadCache | None = None,
) -> None:
"""在最终 block tree 中裁剪视觉 span,避免 regroup/deepcopy 后 image_path 写回旧对象。"""
for block in blocks:
@@ -32,4 +34,5 @@ def cut_visual_spans_in_blocks(
page_img_md5,
page_index,
scale=scale,
+ image_cache=image_cache,
)
diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.py
index 0639186c..79a18343 100644
--- a/mineru/backend/vlm/model_output_to_middle_json.py
+++ b/mineru/backend/vlm/model_output_to_middle_json.py
@@ -9,6 +9,7 @@ from mineru_vl_utils.structs import ExtractResult
from ...types import PageInfo
from ...utils.config_reader import get_table_enable
from ...utils.hash_utils import bytes_md5
+from ...utils.image_payload import ImagePayloadCache
from ...utils.pdf_document import PDFPage
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ..utils.para_block_utils import (
@@ -26,6 +27,7 @@ def blocks_to_page_info(
image_dict: dict[str, Any],
pdf_page: PDFPage,
page_index: int,
+ image_cache: ImagePayloadCache | None = None,
) -> PageInfo:
"""将blocks转换为页面信息"""
@@ -70,6 +72,7 @@ def blocks_to_page_info(
page_img_md5,
page_index,
scale=scale,
+ image_cache=image_cache,
)
page_info = PageInfo(
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index 4f79150f..eb116745 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -21,6 +21,7 @@ from ...types import PageInfo
from ...utils.check_sys_env import is_mac_os_version_supported
from ...utils.config_reader import get_device, get_processing_window_size
from ...utils.enum_class import ImageType
+from ...utils.image_payload import ImagePayloadCache
from ...utils.models_download_utils import auto_download_and_get_model_root_path
from ...utils.pdf_document import PDFDocument
from ...utils.pdf_image_tools import aio_load_images_from_pdf_bytes_range, load_images_from_pdf_bytes_range
@@ -453,6 +454,7 @@ def doc_analyze(
server_url: str | None = None,
image_analysis: bool = True,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
**kwargs: Any,
) -> tuple[list[PageInfo], list[ExtractResult]]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -516,6 +518,7 @@ def doc_analyze(
page_start_index=window_start,
page_index_map=page_index_map,
progress_bar=progress_bar,
+ image_cache=image_cache,
)
last_append_end_time = time.time()
finally:
@@ -553,6 +556,7 @@ async def aio_doc_analyze(
server_url: str | None = None,
image_analysis: bool = True,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
**kwargs: Any,
) -> tuple[list[PageInfo], list[ExtractResult]]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -616,6 +620,7 @@ async def aio_doc_analyze(
page_start_index=window_start,
page_index_map=page_index_map,
progress_bar=progress_bar,
+ image_cache=image_cache,
)
last_append_end_time = time.time()
finally:
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index b2dba5f6..e5610487 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -25,6 +25,7 @@ from mineru.render import render_content_list, render_markdown, render_structure
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes
+from mineru.utils.image_payload import ImagePayloadCache
from mineru.utils.pdf_image_tools import images_bytes_to_pdf_bytes
from mineru.utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium, safe_rewrite_pdf_bytes_with_pdfium_result
@@ -262,6 +263,7 @@ def _process_output(
backend: str,
retained_page_indices: list[int] | None = None,
broken_page_indices: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> None:
"""处理输出文件"""
visualization_pages = select_pages_for_pdf_visualization(middle_json, retained_page_indices)
@@ -292,6 +294,7 @@ def _process_output(
image_dir = str(os.path.basename(local_image_dir))
export_result = ParseResult(
pages=middle_json,
+ _image_cache=image_cache,
_retained_page_indices=retained_page_indices,
_broken_page_indices=broken_page_indices,
)
@@ -374,6 +377,7 @@ def _process_pipeline(
md_writer_list = []
local_output_info = []
+ image_cache_list = [ImagePayloadCache() for _ in pdf_bytes_list]
for idx, pdf_bytes in enumerate(pdf_bytes_list):
pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
@@ -411,6 +415,7 @@ def _process_pipeline(
backend="pipeline",
retained_page_indices=retained_page_indices,
broken_page_indices=broken_page_indices,
+ image_cache=image_cache_list[doc_index],
)
logger.debug(f"Pipeline output complete: doc{doc_index}")
except Exception:
@@ -433,6 +438,7 @@ def _process_pipeline(
table_enable=p_table_enable,
client_side_output_generation=client_side_output_generation,
page_index_map_list=page_index_map_list,
+ image_cache_list=image_cache_list,
)
for future in output_futures:
@@ -468,12 +474,14 @@ async def _async_process_vlm(
pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
md_writer = FileBasedDataWriter(local_md_dir)
+ image_cache = ImagePayloadCache()
middle_json, infer_result = await aio_vlm_doc_analyze(
pdf_bytes,
backend=backend,
server_url=server_url,
page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
+ image_cache=image_cache,
**kwargs,
)
@@ -497,6 +505,7 @@ async def _async_process_vlm(
backend="vlm",
retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
+ image_cache=image_cache,
)
@@ -528,12 +537,14 @@ def _process_vlm(
pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, parse_method)
md_writer = FileBasedDataWriter(local_md_dir)
+ image_cache = ImagePayloadCache()
middle_json, infer_result = vlm_doc_analyze(
pdf_bytes,
backend=backend,
server_url=server_url,
page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
+ image_cache=image_cache,
**kwargs,
)
@@ -557,6 +568,7 @@ def _process_vlm(
backend="vlm",
retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
+ image_cache=image_cache,
)
@@ -593,6 +605,7 @@ def _process_hybrid(
pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")
md_writer = FileBasedDataWriter(local_md_dir)
+ image_cache = ImagePayloadCache()
middle_json, infer_result, _vlm_ocr_enable = hybrid_doc_analyze(
pdf_bytes,
@@ -602,6 +615,7 @@ def _process_hybrid(
inline_formula_enable=inline_formula_enable,
server_url=server_url,
page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
+ image_cache=image_cache,
**kwargs,
)
@@ -628,6 +642,7 @@ def _process_hybrid(
backend="bybrid",
retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
+ image_cache=image_cache,
)
@@ -664,6 +679,7 @@ async def _async_process_hybrid(
pdf_file_name = pdf_file_names[idx]
local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"hybrid_{parse_method}")
md_writer = FileBasedDataWriter(local_md_dir)
+ image_cache = ImagePayloadCache()
middle_json, infer_result, _vlm_ocr_enable = await aio_hybrid_doc_analyze(
pdf_bytes,
@@ -673,6 +689,7 @@ async def _async_process_hybrid(
inline_formula_enable=inline_formula_enable,
server_url=server_url,
page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
+ image_cache=image_cache,
**kwargs,
)
@@ -699,6 +716,7 @@ async def _async_process_hybrid(
backend="bybrid",
retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
+ image_cache=image_cache,
)
@@ -732,7 +750,8 @@ def _process_office_doc(
else:
raise ValueError(f"Unsupported office suffix: {file_suffix}")
- middle_json, infer_result = office_analyze(file_bytes)
+ image_cache = ImagePayloadCache()
+ middle_json, infer_result = office_analyze(file_bytes, image_cache=image_cache)
f_draw_layout_bbox = False
f_draw_span_bbox = False
@@ -755,6 +774,7 @@ def _process_office_doc(
infer_result,
process_mode=file_suffix,
backend="office",
+ image_cache=image_cache,
)
return need_remove_index
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 5a9afd3f..f7186d47 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import asyncio
-import base64
import os
import re
import signal
@@ -1238,8 +1237,10 @@ class DoclibServer(AsyncDoclibInterface):
raise InvalidRequestError(
"format_not_supported", "Office image output is only supported for image blocks.", "format"
)
- image_bytes, ext, mime_type = _span_image_bytes(image_span)
- if image_bytes is None and image_span.image_path:
+ image_bytes = None
+ ext = "png"
+ mime_type = "image/png"
+ if 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():
@@ -1553,19 +1554,6 @@ def _iter_block_spans(block: Block) -> Iterator[Span]:
yield from _iter_block_spans(child)
-def _span_image_bytes(span: Span) -> tuple[bytes | None, str, str]:
- 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)
-
-
def _pil_image_to_bytes(image: Image.Image) -> bytes:
with BytesIO() as buffer:
image.save(buffer, format="JPEG")
diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.py
index fd4d6b7c..bd77132d 100644
--- a/mineru/doclib/services/cleanup_svc.py
+++ b/mineru/doclib/services/cleanup_svc.py
@@ -109,6 +109,7 @@ class CleanupService:
raise InvalidRequestError("invalid_request", "Path is required.", "path")
watches = cast(list[WatchTargetRow], await self.db.fetchall("SELECT * FROM watches WHERE enabled=1"))
+ _raise_if_watch_root(normalized, watches)
file_ids = await self._forget_file_ids(normalized)
matched_as = await self._forget_matched_as(normalized, file_ids)
@@ -211,6 +212,13 @@ def _active_watch_warning(path: str, watches: list[WatchTargetRow]) -> str | Non
return None
+def _raise_if_watch_root(path: str, watches: list[WatchTargetRow]) -> None:
+ """拒绝直接 forget 已配置的 watch root,避免用户误删持续扫描入口。"""
+ for watch in watches:
+ if _normalize_path(watch["path"]) == path:
+ raise InvalidRequestError("invalid_request", "Path is a configured watch root.", "path")
+
+
def _forget_warnings(path: str, watches: list[WatchTargetRow]) -> list[str]:
for watch in watches:
if watch["path"] == path:
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 3f486082..ce62232e 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -16,7 +16,6 @@ from urllib.parse import urlparse
from ...errors import MineruError
from ...parser.base import ParseResult
from ...types import TIER_ORDER, PageInfo, Tier
-from ...utils.image_payload import parse_image_data_uri
from ..constants import ALLOWED_EXTENSIONS, TEXT_EXTENSIONS, is_office_temp_lock_file
from ..core.db import DatabaseManager
from ..core.file_io import FileStat, MetadataExtractionError, compute_sha256, extract_metadata, get_file_stat
@@ -1322,28 +1321,9 @@ def _write_cached_image_sidecars(image_dir: str, images: dict[str, bytes]) -> No
sidecar_path.write_bytes(image_bytes)
-def _restore_missing_image_sidecars(page: PageInfo, image_dir: str) -> None:
- """读取历史缓存时先找 image_path 文件,缺失时再从 image_base64 补写同名 sidecar。"""
- for block_list in (page.preproc_blocks, page.para_blocks, page.discarded_blocks):
- for block in block_list:
- for span in block.all_spans():
- sidecar_path = resolve_image_sidecar_path(image_dir, span.image_path)
- if sidecar_path is None or sidecar_path.is_file() or not span.image_base64:
- continue
- parsed = parse_image_data_uri(span.image_base64)
- if parsed is None:
- continue
- try:
- sidecar_path.parent.mkdir(parents=True, exist_ok=True)
- sidecar_path.write_bytes(parsed[0])
- except OSError:
- continue
-
-
def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_rows: Sequence[ParseBatchRow]) -> list[PageInfo]:
"""Load valid done JSON batches and keep the newest page for duplicate page_idx values."""
pages_by_page_idx: dict[int, PageInfo] = {}
- image_dir = parse_image_sidecar_dir(data_dir, sha256, tier)
for row in reversed(done_rows):
fpath = parse_batch_json_path(data_dir, sha256, tier, row["page_range"], row["done_at"])
if not os.path.isfile(fpath):
@@ -1353,7 +1333,6 @@ def load_pages_from_done_batches(data_dir: str, sha256: str, tier: Tier, done_ro
data = json.load(f)
parse_result = ParseResult.from_dict(data)
for page in parse_result.pages:
- _restore_missing_image_sidecars(page, image_dir)
pages_by_page_idx[page.page_idx] = page
except Exception:
pass
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 001f48f6..523cf59d 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -11,11 +11,7 @@ from typing import Any
from ..render import render_content_list, render_markdown, render_structured_content
from ..schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
from ..types import PageInfo
-from ..utils.image_payload import (
- image_path_from_data_uri,
- parse_image_data_uri,
- replace_inline_data_uri_sources,
-)
+from ..utils.image_payload import ImagePayloadCache
from ..utils.pdf_document import PDFDocument
_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"
@@ -45,11 +41,17 @@ class ParseResult:
pages: list[PageInfo]
_pdf_doc: PDFDocument | None = None
_model_output: Any = None
- _export_pages_cache: list[PageInfo] | None = None
- _images_cache: dict[str, bytes] | None = None
+ _image_cache: ImagePayloadCache | dict[str, bytes] | None = None
_retained_page_indices: list[int] | None = None
_broken_page_indices: list[int] | None = None
+ def __post_init__(self) -> None:
+ """规范化顶层图片缓存,确保 public middle_json 不再从 span 携带图片字节。"""
+ if self._image_cache is None:
+ self._image_cache = ImagePayloadCache()
+ elif isinstance(self._image_cache, dict):
+ self._image_cache = ImagePayloadCache(self._image_cache)
+
@staticmethod
def from_dict(d: dict[str, Any]) -> ParseResult:
if not isinstance(d, dict):
@@ -94,15 +96,8 @@ class ParseResult:
return payload
def to_export_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
- """生成 public middle_json 视图:图片已落盘引用,base64 临时载荷不再输出。"""
- export_pages = self._public_render_pages()
- payload = {
- "schema_version": MIDDLE_JSON_SCHEMA_VERSION,
- "pages": [page.to_dict(skip_defaults=skip_defaults) for page in export_pages],
- }
- self._append_root_backend(payload, export_pages)
- self._append_private_pdf_page_mapping(payload)
- return payload
+ """兼容旧调用名;当前 pages 已经是 public clean middle_json。"""
+ return self.to_dict(skip_defaults=skip_defaults)
@staticmethod
def _append_root_backend(payload: dict[str, Any], pages: list[PageInfo]) -> None:
@@ -131,13 +126,12 @@ class ParseResult:
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)
+ """兼容旧调用名;当前与 to_json 输出一致。"""
+ return self.to_json()
def _public_render_pages(self) -> list[PageInfo]:
- """返回 public 渲染使用的导出页副本,避免 staged base64 载荷进入用户产物。"""
- export_pages, _ = self._ensure_export_cache()
- return export_pages
+ """返回 public 渲染页;图片载荷已在 middle_json 生成阶段外置。"""
+ return self.pages
def markdown(self, *, add_markers: bool = False) -> str:
return render_markdown(self._public_render_pages(), add_markers=add_markers)
@@ -171,66 +165,22 @@ class ParseResult:
writer.write(img_path, img_bytes)
def images(self) -> dict[str, bytes]:
- _, images = self._ensure_export_cache()
- return images
+ assert isinstance(self._image_cache, ImagePayloadCache)
+ return self._image_cache.images()
def attach_export_images(self, images: dict[str, bytes]) -> None:
"""绑定 API sidecar 下载到的图片字节,供后续 images/save 统一写出。"""
- self._export_pages_cache = deepcopy(self.pages)
- self._images_cache = dict(images)
+ assert isinstance(self._image_cache, ImagePayloadCache)
+ self._image_cache.update(images)
def refresh_export_cache(self, *, preserve_images: bool = False) -> None:
- """调用方原地修改 pages 后刷新导出缓存;必要时保留已绑定的 sidecar 字节。"""
- if preserve_images and self._images_cache is not None:
- self._export_pages_cache = deepcopy(self.pages)
- return
- self._export_pages_cache = None
- self._images_cache = None
+ """保留历史方法名;当前仅按需清空顶层图片缓存。"""
+ if not preserve_images:
+ self._image_cache = ImagePayloadCache()
def export_pages(self) -> list[PageInfo]:
- """返回可导出的页面副本:清理 base64,并把内联图片替换为本地路径。"""
- 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 页面。"""
- 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
-
- @staticmethod
- def _prepare_block_images_for_export(block: Any, images: dict[str, bytes]) -> None:
- """递归处理 block 内所有 span,将 base64 图片转为 image_path 引用。"""
- for line in block.lines:
- for span in line.spans:
- ParseResult._prepare_span_images_for_export(span, images)
- for child in block.blocks:
- ParseResult._prepare_block_images_for_export(child, images)
-
- @staticmethod
- def _prepare_span_images_for_export(span: Any, images: dict[str, bytes]) -> None:
- """处理单个 span 的图片载荷,保留路径字段并清理 base64 临时字段。"""
- 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]
- span.image_path = img_path
- span.image_base64 = ""
- if span.content:
- span.content = replace_inline_data_uri_sources(span.content, images)
+ """返回页面树副本,避免调用方修改污染 ParseResult.pages。"""
+ return deepcopy(self.pages)
class DocumentParser(ABC):
diff --git a/mineru/parser/html.py b/mineru/parser/html.py
index 89941cae..bd681716 100644
--- a/mineru/parser/html.py
+++ b/mineru/parser/html.py
@@ -7,6 +7,7 @@ from bs4 import BeautifulSoup, Tag
from .base import DocumentParser, ParseResult
from ..types import EMPTY_BBOX, Block, Line, PageInfo, Span
+from ..utils.image_payload import ImagePayloadCache
class HtmlParser(DocumentParser):
@@ -25,11 +26,13 @@ class HtmlParser(DocumentParser):
body = soup.body or soup
blocks: list[Block] = []
- _walk_elements(body, blocks)
+ image_cache = ImagePayloadCache()
+ _walk_elements(body, blocks, image_cache)
_assign_block_indexes(blocks)
return ParseResult(
pages=[PageInfo(page_idx=0, para_blocks=blocks)],
+ _image_cache=image_cache,
)
@@ -66,13 +69,13 @@ def _line_with_spans(spans: list[Span]) -> Line:
return Line(bbox=EMPTY_BBOX, spans=spans)
-def _build_span(element: Tag) -> Span:
+def _build_span(element: Tag, image_cache: ImagePayloadCache) -> Span:
content = _extract_text(element)
img = _find_image_element(element)
if img is not None:
src: str = img.get("src", "") or ""
if src.startswith("data:image"):
- return Span(type="image", bbox=EMPTY_BBOX, image_base64=src, content=content)
+ return Span(type="image", bbox=EMPTY_BBOX, image_path=image_cache.register_data_uri(src), content=content)
return Span(type="image", bbox=EMPTY_BBOX, image_path=src, content=content)
return Span(type="text", bbox=EMPTY_BBOX, content=content)
@@ -82,7 +85,7 @@ def _append_block(blocks: list[Block], block: Block) -> None:
blocks.append(block)
-def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[type-arg]
+def _walk_elements(parent: Tag, blocks: list[Block], image_cache: ImagePayloadCache) -> None: # type: ignore[type-arg]
for child in parent.children:
if not isinstance(child, Tag):
text = str(child).strip()
@@ -98,50 +101,50 @@ def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[ty
tag_name = child.name
if tag_name in _HEADING_TAGS:
- _append_block(blocks, _build_heading(child))
+ _append_block(blocks, _build_heading(child, image_cache))
elif tag_name in ("p", "span"):
- _append_block(blocks, _build_text_block(child))
+ _append_block(blocks, _build_text_block(child, image_cache))
elif tag_name in _BLOCK_CONTAINER_TAGS:
- _walk_elements(child, blocks)
+ _walk_elements(child, blocks, image_cache)
elif tag_name in ("ul", "ol"):
- _append_block(blocks, _build_list(child))
+ _append_block(blocks, _build_list(child, image_cache))
elif tag_name == "table":
- _append_block(blocks, _build_table(child))
+ _append_block(blocks, _build_table(child, image_cache))
elif tag_name == "pre":
_append_block(blocks, _build_code(child))
elif tag_name in ("img",):
- _append_block(blocks, _build_image_block(child))
+ _append_block(blocks, _build_image_block(child, image_cache))
elif tag_name in ("br",):
pass
else:
# fallback: treat unknown inline tags as text
if child.get_text(strip=True):
- _append_block(blocks, _build_text_block(child))
+ _append_block(blocks, _build_text_block(child, image_cache))
-def _build_heading(element: Tag) -> Block:
+def _build_heading(element: Tag, image_cache: ImagePayloadCache) -> Block:
level = _heading_level(element.name)
return Block(
index=0,
type="title",
bbox=EMPTY_BBOX,
level=level,
- lines=[_line_with_spans([_build_span(element)])],
+ lines=[_line_with_spans([_build_span(element, image_cache)])],
)
-def _build_text_block(element: Tag) -> Block:
+def _build_text_block(element: Tag, image_cache: ImagePayloadCache) -> Block:
# Collapse nested inline children into a single span.
return Block(
index=0,
type="text",
bbox=EMPTY_BBOX,
- lines=[_line_with_spans([_build_span(element)])],
+ lines=[_line_with_spans([_build_span(element, image_cache)])],
)
-def _build_image_block(element: Tag) -> Block:
- span = _build_span(element)
+def _build_image_block(element: Tag, image_cache: ImagePayloadCache) -> Block:
+ span = _build_span(element, image_cache)
return Block(
index=0,
type="image",
@@ -150,11 +153,11 @@ def _build_image_block(element: Tag) -> Block:
)
-def _build_list(element: Tag) -> Block:
+def _build_list(element: Tag, image_cache: ImagePayloadCache) -> Block:
items: list[Block] = []
for li in element.find_all("li", recursive=False):
nested_blocks: list[Block] = []
- _walk_elements(li, nested_blocks)
+ _walk_elements(li, nested_blocks, image_cache)
items.append(Block(
index=len(items),
type="list_item",
@@ -165,12 +168,16 @@ def _build_list(element: Tag) -> Block:
return Block(index=0, type="list", bbox=EMPTY_BBOX, blocks=items)
-def _build_table(element: Tag) -> Block:
+def _build_table(element: Tag, image_cache: ImagePayloadCache) -> Block:
return Block(
index=0,
type="table",
bbox=EMPTY_BBOX,
- lines=[_line_with_spans([Span(type="table", bbox=EMPTY_BBOX, content=str(element))])],
+ lines=[
+ _line_with_spans(
+ [Span(type="table", bbox=EMPTY_BBOX, content=image_cache.replace_html_data_uri_sources(str(element)))]
+ )
+ ],
)
diff --git a/mineru/parser/office.py b/mineru/parser/office.py
index ac19a946..bbfedcea 100644
--- a/mineru/parser/office.py
+++ b/mineru/parser/office.py
@@ -7,6 +7,7 @@ from typing import Any
from .base import DocumentParser, ParseResult
from ..types import PageInfo
+from ..utils.image_payload import ImagePayloadCache
class OfficeBaseParser(DocumentParser, ABC):
@@ -28,18 +29,21 @@ class OfficeBaseParser(DocumentParser, ABC):
file_name = path.stem
file_bytes = path.read_bytes()
- middle_json, model_output = self._analyze_fn(file_bytes)
- return self._build_result(middle_json, file_name, model_output)
+ image_cache = ImagePayloadCache()
+ middle_json, model_output = self._analyze_fn(file_bytes, image_cache=image_cache)
+ return self._build_result(middle_json, file_name, model_output, image_cache)
def _build_result(
self,
middle_json: list[PageInfo],
file_name: str,
model_output: Any = None,
+ image_cache: ImagePayloadCache | None = None,
) -> ParseResult:
return ParseResult(
pages=middle_json,
_model_output=model_output if self.return_model_output else None,
+ _image_cache=image_cache,
)
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index 084bc9e4..8356b568 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -9,6 +9,7 @@ from pathlib import Path
from typing import Any
from ..types import PageInfo
+from ..utils.image_payload import ImagePayloadCache
from .base import DocumentParser, ParseResult
_IMAGE_SUFFIXES = frozenset({"png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"})
@@ -75,9 +76,11 @@ class PdfBaseParser(DocumentParser):
raise FileNotFoundError(path)
prepared = self._prepare_input(path, page_range)
+ image_cache = ImagePayloadCache()
middle_json = self._run_analysis(
prepared.pdf_bytes,
page_index_map=prepared.retained_page_indices,
+ image_cache=image_cache,
)
self._insert_broken_pages(
middle_json,
@@ -90,6 +93,7 @@ class PdfBaseParser(DocumentParser):
prepared.file_name,
retained_page_indices=prepared.retained_page_indices,
broken_page_indices=prepared.broken_page_indices,
+ image_cache=image_cache,
)
async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
@@ -98,9 +102,11 @@ class PdfBaseParser(DocumentParser):
raise FileNotFoundError(path)
prepared = await asyncio.to_thread(self._prepare_input, path, page_range)
+ image_cache = ImagePayloadCache()
middle_json = await self._arun_analysis(
prepared.pdf_bytes,
page_index_map=prepared.retained_page_indices,
+ image_cache=image_cache,
)
self._insert_broken_pages(
middle_json,
@@ -113,6 +119,7 @@ class PdfBaseParser(DocumentParser):
prepared.file_name,
retained_page_indices=prepared.retained_page_indices,
broken_page_indices=prepared.broken_page_indices,
+ image_cache=image_cache,
)
@abstractmethod
@@ -120,6 +127,7 @@ class PdfBaseParser(DocumentParser):
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
"""Execute backend-specific analysis. Returns (middle_json, model_output)."""
@@ -127,8 +135,14 @@ class PdfBaseParser(DocumentParser):
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
- return await asyncio.to_thread(self._run_analysis, pdf_bytes, page_index_map)
+ return await asyncio.to_thread(
+ self._run_analysis,
+ pdf_bytes,
+ page_index_map,
+ image_cache,
+ )
def _prepare_input(self, path: Path, page_range: str = "") -> _PreparedPdfInput:
from ..utils.guess_suffix_or_lang import guess_suffix_by_path
@@ -207,11 +221,13 @@ class PdfBaseParser(DocumentParser):
*,
retained_page_indices: list[int] | None = None,
broken_page_indices: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> ParseResult:
return ParseResult(
pages=middle_json,
_retained_page_indices=retained_page_indices,
_broken_page_indices=broken_page_indices,
+ _image_cache=image_cache,
)
@@ -225,6 +241,7 @@ class PdfVlmParser(PdfBaseParser):
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
from ..backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
@@ -238,12 +255,14 @@ class PdfVlmParser(PdfBaseParser):
server_url=self.server_url,
image_analysis=self.image_analysis,
page_index_map=page_index_map,
+ image_cache=image_cache,
)[0]
async def _arun_analysis(
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
from ..backend.vlm.vlm_analyze import aio_doc_analyze as vlm_aio_doc_analyze
@@ -257,6 +276,7 @@ class PdfVlmParser(PdfBaseParser):
server_url=self.server_url,
image_analysis=self.image_analysis,
page_index_map=page_index_map,
+ image_cache=image_cache,
)
return middle_json
@@ -282,10 +302,12 @@ class PdfPipelineParser(PdfBaseParser):
prepared_inputs: list[_PreparedPdfInput] = []
pdf_bytes_list: list[bytes] = []
+ image_caches: list[ImagePayloadCache] = []
for p in paths:
prepared = self._prepare_input(Path(p), page_range)
prepared_inputs.append(prepared)
pdf_bytes_list.append(prepared.pdf_bytes)
+ image_caches.append(ImagePayloadCache())
results_by_index: dict[int, list[PageInfo]] = {}
@@ -300,6 +322,7 @@ class PdfPipelineParser(PdfBaseParser):
formula_enable=self.formula_enable,
table_enable=self.table_enable,
page_index_map_list=[prepared.retained_page_indices for prepared in prepared_inputs],
+ image_cache_list=image_caches,
)
parse_results: list[ParseResult] = []
@@ -317,6 +340,7 @@ class PdfPipelineParser(PdfBaseParser):
prepared.file_name,
retained_page_indices=prepared.retained_page_indices,
broken_page_indices=prepared.broken_page_indices,
+ image_cache=image_caches[idx],
)
parse_results.append(result)
@@ -331,6 +355,7 @@ class PdfPipelineParser(PdfBaseParser):
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
@@ -347,6 +372,7 @@ class PdfPipelineParser(PdfBaseParser):
formula_enable=self.formula_enable,
table_enable=self.table_enable,
page_index_map_list=[page_index_map],
+ image_cache_list=[image_cache or ImagePayloadCache()],
)
return result_holder["middle_json"]
@@ -370,6 +396,7 @@ class PdfHybridParser(PdfBaseParser):
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
@@ -387,6 +414,7 @@ class PdfHybridParser(PdfBaseParser):
server_url=server_url,
image_analysis=self.image_analysis,
page_index_map=page_index_map,
+ image_cache=image_cache,
)
return middle_json
@@ -395,6 +423,7 @@ class PdfHybridParser(PdfBaseParser):
self,
pdf_bytes: bytes,
page_index_map: list[int] | None = None,
+ image_cache: ImagePayloadCache | None = None,
) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import aio_doc_analyze as hybrid_aio_doc_analyze
@@ -412,6 +441,7 @@ class PdfHybridParser(PdfBaseParser):
server_url=server_url,
image_analysis=self.image_analysis,
page_index_map=page_index_map,
+ image_cache=image_cache,
)
return middle_json
diff --git a/mineru/schema/middle_json/__init__.py b/mineru/schema/middle_json/__init__.py
index f1cd76a0..19b2a68c 100644
--- a/mineru/schema/middle_json/__init__.py
+++ b/mineru/schema/middle_json/__init__.py
@@ -305,13 +305,13 @@ def _validate_span_content(span: Span, path: str, issues: list[ValidationIssue])
message="text span should provide content.",
)
)
- elif span.type in IMAGE_SPAN_TYPES and not (span.image_path or span.image_base64):
+ elif span.type in IMAGE_SPAN_TYPES and not span.image_path:
issues.append(
ValidationIssue(
severity="warning",
code="span_image_missing",
path=path,
- message="image span should provide image_path or image_base64.",
+ message="image span should provide image_path.",
)
)
elif span.type in TABLE_SPAN_TYPES and not span.content:
diff --git a/mineru/types.py b/mineru/types.py
index ae3eb69b..7bbe9742 100644
--- a/mineru/types.py
+++ b/mineru/types.py
@@ -403,12 +403,9 @@ class Span(_DocElement):
bbox: BBox
content: str = ""
score: float = 0.0
- image_path: InitVar[str] = ""
- image_base64: InitVar[str] = ""
+ image_path: str = ""
# Internal
- _image_path: str = ""
- _image_base64: str = ""
_cross_page: bool = False
_np_img: Any = None
@@ -418,48 +415,6 @@ class Span(_DocElement):
_extra: dict = field(default_factory=dict)
- def __post_init__(self, image_path: str, image_base64: str) -> None:
- """接收图片类 span 的路径字段,但仅在有值时序列化到 middle_json。"""
- self._image_path = _initvar_default(image_path, "")
- self._image_base64 = _initvar_default(image_base64, "")
-
- @property
- def image_path(self) -> str:
- """图片类/表格类/公式类 span 的外部图片产物路径。"""
- return self._image_path
-
- @image_path.setter
- def image_path(self, value: str) -> None:
- self._image_path = value
-
- @property
- def image_base64(self) -> str:
- """Office 等输入中的内联图片,仅在写出图片前临时保留。"""
- return self._image_base64
-
- @image_base64.setter
- def image_base64(self, value: str) -> None:
- self._image_base64 = value
-
- def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
- """按 span 类型输出实际载荷字段,避免文本 span 带空图片字段。"""
- result = super().to_dict(skip_defaults=skip_defaults)
- for name, value in (
- ("image_path", self.image_path),
- ("image_base64", self.image_base64),
- ):
- if value:
- result[name] = value
- return result
-
- @classmethod
- def from_dict(cls, d: dict) -> Span:
- """读取当前 middle_json 中图片类 span 的非 content 载荷字段。"""
- span = _DocElement.from_dict.__func__(cls, d)
- span.image_path = d.get("image_path", "")
- span.image_base64 = d.get("image_base64", "")
- return span
-
@dataclass
class Line(_DocElement):
diff --git a/mineru/utils/cut_image.py b/mineru/utils/cut_image.py
index 7fdec901..bc1d2070 100644
--- a/mineru/utils/cut_image.py
+++ b/mineru/utils/cut_image.py
@@ -6,7 +6,7 @@ from typing import Any
from loguru import logger
from ..types import BBox, Span
-from .image_payload import image_bytes_to_data_uri, image_path_from_key
+from .image_payload import ImagePayloadCache, image_path_from_key
from .pdf_image_tools import get_crop_img
from .pdf_reader import image_to_bytes
@@ -17,6 +17,7 @@ def cut_image_and_table(
page_img_md5: str,
page_id: int,
scale: int = 2,
+ image_cache: ImagePayloadCache | None = None,
) -> Span:
def return_path(path_type: str) -> str:
@@ -26,14 +27,14 @@ def cut_image_and_table(
if not check_img_bbox(span.bbox):
span.image_path = ""
- span.image_base64 = ""
else:
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")
+ if image_cache is not None:
+ image_cache.register_bytes(img_bytes, "jpeg", image_path=span.image_path)
return span
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.py
index bd219d9a..43024a9b 100644
--- a/mineru/utils/image_payload.py
+++ b/mineru/utils/image_payload.py
@@ -8,7 +8,7 @@ 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)
+INLINE_IMAGE_SRC_RE = re.compile(r"src=(?P<quote>[\"'])(?P re.DOTALL)
def normalize_image_extension(fmt: str) -> str:
@@ -51,6 +51,81 @@ def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:
return f"{str_sha256(path_key)}.{ext}"
+class ImagePayloadCache:
+ """保存运行时图片载荷,public middle_json 只通过 image_path 引用图片。"""
+
+ def __init__(
+ self,
+ images: dict[str, bytes] | None = None,
+ data_uris: dict[str, str] | None = None,
+ ) -> None:
+ self._images: dict[str, bytes] = dict(images or {})
+ self._data_uris: dict[str, str] = dict(data_uris or {})
+
+ def register_data_uri(self, data_uri: str, image_path: str | None = None) -> str:
+ """登记 data URI 图片,返回稳定的相对 image_path;非法载荷返回空串。"""
+ parsed = parse_image_data_uri(data_uri)
+ img_path = image_path or image_path_from_data_uri(data_uri)
+ if parsed is None or not img_path:
+ return ""
+ self._images[img_path] = parsed[0]
+ self._data_uris[img_path] = data_uri
+ return img_path
+
+ def register_bytes(
+ self,
+ img_bytes: bytes,
+ image_format: str = "JPEG",
+ *,
+ path_key: str | None = None,
+ image_path: str | None = None,
+ ) -> str:
+ """登记图片字节,优先使用显式路径,其次使用逻辑 path_key 生成稳定路径。"""
+ if image_path:
+ img_path = image_path
+ elif path_key:
+ img_path = image_path_from_key(path_key, image_format)
+ else:
+ ext = normalize_image_extension(image_format)
+ payload_key = base64.b64encode(img_bytes).decode("ascii")
+ img_path = f"{str_sha256(payload_key)}.{ext}"
+ self._images[img_path] = img_bytes
+ self._data_uris[img_path] = image_bytes_to_data_uri(img_bytes, image_format)
+ return img_path
+
+ def replace_html_data_uri_sources(self, markup: str) -> str:
+ """把 HTML 内联 data URI 图片替换为 image_path,并同步写入顶层图片缓存。"""
+ if not markup or "data:image/" not in markup:
+ return markup
+
+ def _replace_src(match: re.Match[str]) -> str:
+ img_path = self.register_data_uri(match.group("data_uri"))
+ if not img_path:
+ return match.group(0)
+ return f'src={match.group("quote")}{img_path}{match.group("quote")}'
+
+ replaced = INLINE_IMAGE_SRC_RE.sub(_replace_src, markup)
+
+ def _replace_bare_data_uri(match: re.Match[str]) -> str:
+ img_path = self.register_data_uri(match.group(0))
+ return img_path or match.group(0)
+
+ return INLINE_IMAGE_DATA_URI_RE.sub(_replace_bare_data_uri, replaced)
+
+ def update(self, images: dict[str, bytes]) -> None:
+ """合并外部 sidecar 图片字节,供 API client 绑定远端输出。"""
+ for image_path, image_bytes in images.items():
+ self.register_bytes(image_bytes, image_path=image_path)
+
+ def images(self) -> dict[str, bytes]:
+ """返回 image_path 到图片字节的副本,避免调用方改写内部缓存。"""
+ return dict(self._images)
+
+ def data_uris(self) -> dict[str, str]:
+ """返回 image_path 到 data URI 的副本,便于调试运行时图片来源。"""
+ return dict(self._data_uris)
+
+
def validate_image_sidecar_path(image_path: str) -> str:
"""校验图片 sidecar 路径只能是安全的相对子路径,并返回规范化 POSIX 路径。"""
posix_path = Path(image_path)
@@ -83,27 +158,8 @@ def collect_image_data_uri_bytes(markup: str, images: dict[str, bytes]) -> None:
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)
+ cache = ImagePayloadCache(images)
+ replaced = cache.replace_html_data_uri_sources(markup)
+ images.clear()
+ images.update(cache.images())
+ return replaced
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 2b57ad93..aab7c337 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -165,6 +165,8 @@ class PDFDocument:
def render_page(self, page_idx: int, *, scale: float | None = None) -> PDFPageImage:
if scale is None:
scale = self.render_scale
+ if scale <= 0:
+ raise ValueError("scale must be greater than 0")
with self._open_page(page_idx) as page:
return _page_to_image(page, scale, self.render_max_edge)
@@ -173,6 +175,8 @@ class PDFDocument:
end = self.page_count - 1
if scale is None:
scale = self.render_scale
+ if scale <= 0:
+ raise ValueError("scale must be greater than 0")
results = load_images_from_pdf_bytes_range(
pdf_bytes=self.bytes,
dpi=max(1, int(round(scale * POINTS_PER_INCH))),
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 64b6e582..6afdd7e2 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -41,7 +41,7 @@ from mineru.parser import backend_for_tier, resolve_tier_and_backend
from mineru.parser.base import ParseResult
from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span, Tier
-from mineru.utils.image_payload import image_bytes_to_data_uri
+from mineru.utils.image_payload import ImagePayloadCache
class _Cursor:
@@ -219,12 +219,11 @@ def _write_batch(data_dir: Path, sha256: str, tier: Tier, page_range: str, done_
path.write_text(json.dumps({"pages": json_pages}), encoding="utf-8")
-def _image_page(image_path: str, image_bytes: bytes = b"image-bytes") -> PageInfo:
+def _image_page(image_path: str) -> PageInfo:
image_span = Span(
type=ContentType.IMAGE,
bbox=(1, 1, 20, 20),
image_path=image_path,
- image_base64=image_bytes_to_data_uri(image_bytes, "jpeg"),
)
body = Block(
index=0,
@@ -236,6 +235,13 @@ def _image_page(image_path: str, image_bytes: bytes = b"image-bytes") -> PageInf
return PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="vlm")
+def _image_result(image_path: str, image_bytes: bytes = b"image-bytes") -> ParseResult:
+ """构造带顶层图片缓存的 ParseResult,避免在 span 中保留 base64。"""
+ image_cache = ImagePayloadCache()
+ image_cache.register_bytes(image_bytes, "jpeg", image_path=image_path)
+ return ParseResult(pages=[_image_page(image_path)], _image_cache=image_cache)
+
+
def test_load_pages_from_done_batches_keeps_newest_page_idx(tmp_path: Path) -> None:
sha256 = "a" * 64
tier = "standard"
@@ -2154,7 +2160,7 @@ def test_process_doc_writes_cached_image_sidecars(tmp_path: Path) -> None:
service = ParseService(db=db, fts=_FakeFTS(), config_svc=None, data_dir=str(tmp_path), parse_lock_timeout_sec=1800)
async def _parse(file_row: dict, tier: Tier, page_range: str) -> ParseResult:
- return ParseResult(pages=[_image_page("figures/cache-hit.jpg", b"fresh-image")])
+ return _image_result("figures/cache-hit.jpg", b"fresh-image")
async def _skip_fts(*args: object, **kwargs: object) -> None:
return None
@@ -2178,23 +2184,10 @@ def test_process_doc_writes_cached_image_sidecars(tmp_path: Path) -> None:
assert "image_base64" not in image_span
-def test_load_pages_from_done_batches_restores_missing_image_sidecars_from_base64(tmp_path: Path) -> None:
- sha256 = "d" * 64
- tier = "standard"
- page = _image_page("figures/recovered.jpg", b"legacy-image")
- _write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
-
- loaded_pages = load_pages_from_done_batches(str(tmp_path), sha256, tier, [{"page_range": "1", "done_at": 1000}])
-
- sidecar = tmp_path / "parsed" / sha256[:2] / sha256 / tier / "images" / "figures" / "recovered.jpg"
- assert sidecar.read_bytes() == b"legacy-image"
- assert loaded_pages[0].para_blocks[0].blocks[0].lines[0].spans[0].image_base64
-
-
def test_load_pages_from_done_batches_keeps_existing_image_sidecar(tmp_path: Path) -> None:
sha256 = "e" * 64
tier = "standard"
- page = _image_page("figures/existing.jpg", b"base64-image")
+ page = _image_page("figures/existing.jpg")
_write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
sidecar = tmp_path / "parsed" / sha256[:2] / sha256 / tier / "images" / "figures" / "existing.jpg"
sidecar.parent.mkdir(parents=True, exist_ok=True)
@@ -2208,7 +2201,7 @@ def test_load_pages_from_done_batches_keeps_existing_image_sidecar(tmp_path: Pat
def test_progressive_markdown_uses_public_image_sidecar_prefix(tmp_path: Path) -> None:
sha256 = "e" * 64
tier = "standard"
- page = _image_page("figures/rendered.jpg", b"image")
+ page = _image_page("figures/rendered.jpg")
_write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
image_dir = tmp_path / "parsed" / sha256[:2] / sha256 / tier / "images"
db = _FakeDB(
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index e301d222..e8f8e478 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -312,7 +312,7 @@ def test_parse_rejects_file_output_for_directory_input(tmp_path: Path) -> None:
result = runner.invoke(app, ["parse", str(source_dir), "-o", str(tmp_path / "out.md")])
assert result.exit_code == 1
- assert "directory path" in result.output
+ assert "directory path" in " ".join(result.output.split())
def test_parse_single_file_markdown(monkeypatch: Any, tmp_path: Path) -> None:
diff --git a/tests/unittest/test_office_parser_regressions.py b/tests/unittest/test_office_parser_regressions.py
index d163ce97..4985c3ae 100644
--- a/tests/unittest/test_office_parser_regressions.py
+++ b/tests/unittest/test_office_parser_regressions.py
@@ -48,7 +48,7 @@ def test_office_two_layer_blocks_accept_block_dataclasses() -> None:
Line(
bbox=EMPTY_BBOX,
spans=[
- Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_base64="data")
+ Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_path="figure.png")
],
)
],
diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.py
index c975b020..28892848 100644
--- a/tests/unittest/test_parse_result_contract.py
+++ b/tests/unittest/test_parse_result_contract.py
@@ -7,12 +7,41 @@ import pytest
from mineru.parser.base import ParseResult
from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
from mineru.types import Block, ContentType, Line, PageInfo, Span
+from mineru.utils.image_payload import ImagePayloadCache
def _data_uri(payload: bytes, image_type: str = "png") -> str:
return f"data:image/{image_type};base64,{base64.b64encode(payload).decode('ascii')}"
+def _table_page_with_cached_inline_image(img_bytes: bytes) -> tuple[PageInfo, ImagePayloadCache, str]:
+ """构造已完成图片外置化的表格页,验证 ParseResult 只承载顶层图片缓存。"""
+ image_cache = ImagePayloadCache()
+ inline_image = _data_uri(img_bytes)
+ html = image_cache.replace_html_data_uri_sources(
+ 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",
+ )
+ return page, image_cache, inline_image
+
+
def test_parse_result_does_not_expose_backend_version_or_file_name() -> None:
field_names = {field.name for field in fields(ParseResult)}
@@ -250,7 +279,8 @@ def test_parse_result_render_methods_use_export_pages_without_mutating_source(
) -> 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>'
+ image_cache = ImagePayloadCache()
+ html = image_cache.replace_html_data_uri_sources(f'<table><tr><td><img src="{inline_image}"/></td></tr></table>')
page = PageInfo(
page_idx=0,
page_size=(100, 100),
@@ -269,11 +299,11 @@ def test_parse_result_render_methods_use_export_pages_without_mutating_source(
],
_backend="pipeline",
)
- result = ParseResult(pages=[page])
+ result = ParseResult(pages=[page], _image_cache=image_cache)
captured: list[list[PageInfo]] = []
def _assert_clean_export_pages(pages: list[PageInfo]) -> None:
- """确认 public 渲染入口收到的是清理后的导出页副本,而不是带 staged 载荷的原始页。"""
+ """确认 public 渲染入口直接收到生成阶段清理后的 page tree。"""
captured.append(pages)
content = pages[0].para_blocks[0].lines[0].spans[0].content
assert inline_image not in content
@@ -302,12 +332,14 @@ def test_parse_result_render_methods_use_export_pages_without_mutating_source(
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
+ assert all(pages is result.pages for pages in captured)
+ assert inline_image not in page.para_blocks[0].lines[0].spans[0].content
-def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json() -> None:
+def test_parse_result_save_writes_cached_images_and_exports_clean_middle_json() -> None:
img_bytes = b"image-bytes"
+ image_cache = ImagePayloadCache()
+ image_path = image_cache.register_bytes(img_bytes, "jpeg", image_path="figure.png")
page = PageInfo(
page_idx=0,
page_size=(100, 100),
@@ -323,8 +355,7 @@ def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json()
Span(
type=ContentType.IMAGE,
bbox=(0.0, 0.0, 10.0, 10.0),
- image_path="figure.png",
- image_base64=_data_uri(img_bytes),
+ image_path=image_path,
)
],
)
@@ -333,7 +364,7 @@ def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json()
],
_backend="pipeline",
)
- result = ParseResult(pages=[page])
+ result = ParseResult(pages=[page], _image_cache=image_cache)
writes: dict[str, bytes | str] = {}
class MemoryWriter:
@@ -349,7 +380,6 @@ def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json()
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
@@ -357,27 +387,8 @@ def test_parse_result_save_writes_base64_images_and_exports_clean_middle_json()
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])
+ page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
+ result = ParseResult(pages=[page], _image_cache=image_cache)
writes: dict[str, bytes | str] = {}
class MemoryWriter:
@@ -397,42 +408,13 @@ def test_parse_result_save_renders_structured_content_from_clean_export_pages()
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
+ assert inline_image not in page.para_blocks[0].lines[0].spans[0].content
-def test_parse_result_public_outputs_reuse_export_cache(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_parse_result_public_outputs_use_top_level_image_cache() -> 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)
+ page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
+ result = ParseResult(pages=[page], _image_cache=image_cache)
output_text = json.dumps(
{
@@ -445,35 +427,15 @@ def test_parse_result_public_outputs_reuse_export_cache(monkeypatch: pytest.Monk
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
+ assert inline_image not 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])
+ page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
+ result = ParseResult(pages=[page], _image_cache=image_cache)
first_export = result.export_pages()
first_export[0].para_blocks[0].lines[0].spans[0].content = "mutated by caller"
@@ -490,28 +452,9 @@ def test_parse_result_export_pages_returns_defensive_copy_from_cache() -> None:
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",
- )
+ page, image_cache, inline_image = _table_page_with_cached_inline_image(img_bytes)
- result = ParseResult(pages=[page])
+ result = ParseResult(pages=[page], _image_cache=image_cache)
images = result.images()
exported_page = result.export_pages()[0]
exported_span = exported_page.para_blocks[0].lines[0].spans[0]
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 81a23dac..982b7c61 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -27,6 +27,7 @@ from mineru.parser.api_server import (
main,
)
from mineru.types import Block, Line, PageInfo, Span
+from mineru.utils.image_payload import ImagePayloadCache
runner = CliRunner()
@@ -396,8 +397,9 @@ def test_api_server_rendered_outputs_store_image_sidecars(
output_attr: str,
) -> None:
img_bytes = b"rendered-image-bytes"
- image_base64 = "data:image/png;base64,cmVuZGVyZWQtaW1hZ2UtYnl0ZXM="
- span = Span(type="image", bbox=(0, 0, 10, 10), image_base64=image_base64)
+ image_cache = ImagePayloadCache()
+ image_path = image_cache.register_bytes(img_bytes, "png", image_path="rendered.png")
+ span = Span(type="image", bbox=(0, 0, 10, 10), image_path=image_path)
line = Line(bbox=(0, 0, 10, 10), spans=[span])
block = Block(index=0, type="image", bbox=(0, 0, 10, 10), lines=[line])
parse_result = ParseResult(
@@ -408,7 +410,8 @@ def test_api_server_rendered_outputs_store_image_sidecars(
para_blocks=[block],
_backend="pipeline",
)
- ]
+ ],
+ _image_cache=image_cache,
)
async def fake_parse_async(*args, **kwargs) -> ParseResult: