Skip to content

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

feat: implement image block collapsing and container supplementation for enhanced visual analysis

myhlolib2c948ba1c77
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index cd8eb63b..c417e23a 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -15,6 +15,8 @@ import numpy as np
from PIL import Image
from loguru import logger
+# from mineru.backend.model_list_to_midlle_json import model_list_to_pages
+from mineru.version import __version__ as mineru_version
from mineru.backend.utils.table_text import project_ocr_table_text, project_pdf_table_text
from mineru.backend.local_model_runtime import (
AtomicModel,
@@ -68,6 +70,9 @@ LAYOUT_BASE_BATCH_SIZE = 1
MFR_BASE_BATCH_SIZE = 16
OCR_DET_BASE_BATCH_SIZE = 8
LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8
+IMAGE_BLOCK_CONTAINMENT_THRESHOLD = 0.8
+IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD = 0.9
+IMAGE_BLOCK_LAYOUT_MIN_IMAGE_COUNT = 2
BATCH_RATIO = 2
TABLE_TEXT_LINE_OVERLAP_THRESHOLD = 0.5
TABLE_TEXT_ORIENTATION_MIN_VALID_LINES = 3
@@ -1423,6 +1428,170 @@ def _encode_page_crop_as_jpeg_data_uri(
return f"data:image/jpeg;base64,{base64.b64encode(encoded.tobytes()).decode('ascii')}"
+def _normalize_model_bbox_for_containment(raw_bbox: Any) -> BBox | None:
+ """校验模型 block 的四点框,返回可用于面积包含判断的浮点坐标。"""
+ try:
+ if raw_bbox is None or len(raw_bbox) != 4:
+ return None
+ bbox = tuple(float(value) for value in raw_bbox)
+ except (TypeError, ValueError):
+ return None
+
+ if not all(math.isfinite(value) for value in bbox):
+ return None
+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ return None
+ return bbox
+
+
+def _collapse_image_blocks(
+ page_model_list: list[dict[str, Any]],
+ containment_threshold: float = IMAGE_BLOCK_CONTAINMENT_THRESHOLD,
+) -> None:
+ """将 image_block 折叠为单个图片,并删除面积上被其包裹的非容器子块。"""
+ image_blocks = [block for block in page_model_list if block.get("type") == "image_block"]
+ if not image_blocks:
+ return
+
+ image_block_ids = {id(block) for block in image_blocks}
+ image_block_bboxes = [
+ bbox
+ for block in image_blocks
+ if (bbox := _normalize_model_bbox_for_containment(block.get("bbox"))) is not None
+ ]
+
+ retained_blocks: list[dict[str, Any]] = []
+ for block in page_model_list:
+ if id(block) in image_block_ids:
+ block["type"] = BlockType.IMAGE
+ retained_blocks.append(block)
+ continue
+
+ block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))
+ is_contained = block_bbox is not None and any(
+ calculate_overlap_area_in_bbox1_area_ratio(block_bbox, image_block_bbox) >= containment_threshold
+ for image_block_bbox in image_block_bboxes
+ )
+ if not is_contained:
+ retained_blocks.append(block)
+
+ page_model_list[:] = retained_blocks
+
+
+def _supplement_missing_image_block_containers(
+ model_list: list[list[dict[str, Any]]],
+ layout_blocks_list: list[list[dict[str, Any]]],
+ containment_threshold: float = IMAGE_BLOCK_CONTAINMENT_THRESHOLD,
+ coverage_threshold: float = IMAGE_BLOCK_LAYOUT_COVERAGE_THRESHOLD,
+ min_image_count: int = IMAGE_BLOCK_LAYOUT_MIN_IMAGE_COUNT,
+) -> None:
+ """用本地 layout 整图框为 xhigh 结果补充缺失的 image_block 容器。"""
+ if len(model_list) != len(layout_blocks_list):
+ raise ValueError(
+ "Hybrid image-block fallback page count mismatch: "
+ f"model_list={len(model_list)}, layout_blocks={len(layout_blocks_list)}"
+ )
+
+ for page_model_list, page_layout_blocks in zip(model_list, layout_blocks_list):
+ existing_image_block_bboxes = [
+ bbox
+ for block in page_model_list
+ if block.get("type") == "image_block"
+ if (bbox := _normalize_model_bbox_for_containment(block.get("bbox"))) is not None
+ ]
+
+ existing_claimed_block_ids: set[int] = set()
+ if existing_image_block_bboxes:
+ for block in page_model_list:
+ if block.get("type") == "image_block":
+ continue
+ block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))
+ if block_bbox is not None and any(
+ calculate_overlap_area_in_bbox1_area_ratio(block_bbox, image_block_bbox)
+ >= containment_threshold
+ for image_block_bbox in existing_image_block_bboxes
+ ):
+ existing_claimed_block_ids.add(id(block))
+
+ candidates: list[tuple[int, float, int, int, dict[str, Any], set[int]]] = []
+ for layout_order, layout_block in enumerate(page_layout_blocks):
+ if layout_block.get("type") != BlockType.IMAGE or layout_block.get("sub_type") == "seal":
+ continue
+
+ layout_bbox = _normalize_model_bbox_for_containment(layout_block.get("bbox"))
+ if layout_bbox is None:
+ continue
+ if any(
+ calculate_overlap_area_2_minbox_area_ratio(layout_bbox, image_block_bbox)
+ >= containment_threshold
+ for image_block_bbox in existing_image_block_bboxes
+ ):
+ continue
+
+ contained_blocks: list[tuple[int, dict[str, Any], BBox]] = []
+ for block_index, block in enumerate(page_model_list):
+ if block.get("type") == "image_block" or id(block) in existing_claimed_block_ids:
+ continue
+ block_bbox = _normalize_model_bbox_for_containment(block.get("bbox"))
+ if block_bbox is None:
+ continue
+ if (
+ calculate_overlap_area_in_bbox1_area_ratio(block_bbox, layout_bbox)
+ >= containment_threshold
+ ):
+ contained_blocks.append((block_index, block, block_bbox))
+
+ contained_images = [
+ (block_index, block)
+ for block_index, block, _ in contained_blocks
+ if block.get("type") == BlockType.IMAGE
+ ]
+ if len(contained_images) < min_image_count:
+ continue
+
+ layout_area = (layout_bbox[2] - layout_bbox[0]) * (layout_bbox[3] - layout_bbox[1])
+ contained_area = sum(
+ (block_bbox[2] - block_bbox[0]) * (block_bbox[3] - block_bbox[1])
+ for _, _, block_bbox in contained_blocks
+ )
+ if contained_area / layout_area <= coverage_threshold:
+ continue
+
+ image_ids = {id(block) for _, block in contained_images}
+ first_block_index = min(block_index for block_index, _, _ in contained_blocks)
+ candidates.append(
+ (
+ -len(contained_images),
+ layout_area,
+ layout_order,
+ first_block_index,
+ layout_block,
+ image_ids,
+ )
+ )
+
+ claimed_image_ids: set[int] = set()
+ selected_containers: list[tuple[int, dict[str, Any]]] = []
+ for _, _, _, first_block_index, layout_block, image_ids in sorted(candidates):
+ if claimed_image_ids.intersection(image_ids):
+ continue
+ claimed_image_ids.update(image_ids)
+ selected_containers.append(
+ (
+ first_block_index,
+ {
+ "type": "image_block",
+ "bbox": list(layout_block["bbox"]),
+ "angle": layout_block.get("angle", 0),
+ "content": None,
+ },
+ )
+ )
+
+ for insert_index, image_block in sorted(selected_containers, reverse=True):
+ page_model_list.insert(insert_index, image_block)
+
+
def _attach_visual_block_images(
model_list: list[list[dict[str, Any]]],
images_list: list[dict[str, Any]],
@@ -1433,6 +1602,7 @@ def _attach_visual_block_images(
raise ValueError(f"Hybrid visual crop page count mismatch: model_list={len(model_list)}, images={len(images_list)}")
for page_offset, (page_model_list, image_dict) in enumerate(zip(model_list, images_list)):
+ _collapse_image_blocks(page_model_list)
visual_blocks = [
(block_idx, block)
for block_idx, block in enumerate(page_model_list)
@@ -2373,6 +2543,11 @@ def doc_analyze(
if effort in {"medium", "high"}:
_apply_seal_ocr(hybrid_model, window_model_list, np_images)
+ elif effort == "xhigh":
+ _supplement_missing_image_block_containers(
+ window_model_list,
+ vl_style_layout_blocks,
+ )
_attach_visual_block_images(
window_model_list,
@@ -2399,7 +2574,14 @@ def doc_analyze(
_log_infer_performance(file_suffix, len(model_list), infer_elapsed)
# PDF 与 Office 的 model_list 在此汇合,后续统一生产 Middle JSON。
- middle_json: list[PageInfo] = []
+ middle_json = {
+ "pages": [],
+ "file_suffix": file_suffix,
+ "effort": effort,
+ "parse_mode": parse_mode,
+ "mineru_version": mineru_version,
+ }
+ # middle_json["pages"] = model_list_to_pages(model_list, page_index_map)
return middle_json, model_list
@@ -2411,13 +2593,15 @@ if __name__ == "__main__":
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
demo_file_paths = [
# os.path.join(project_root, "demo", "office_docs", "docx_01.docx"),
- os.path.join(project_root, "demo", "pdfs", "NPU_开发环境部署_参考指南.pdf"),
+ # os.path.join(project_root, "demo", "pdfs", "NPU_开发环境部署_参考指南.pdf"),
+ "/Users/myhloli/pdf/png/demo2_page4.png"
]
for file_path in demo_file_paths:
file_bytes = read_fn(file_path)
file_suffix = os.path.splitext(file_path)[1].lstrip(".").lower()
- middle_json, model_list = doc_analyze(file_bytes, effort="medium", file_suffix=file_suffix)
+ file_suffix = "pdf"
+ middle_json, model_list = doc_analyze(file_bytes, effort="xhigh", file_suffix=file_suffix)
model_json = json.dumps(model_list, ensure_ascii=False, indent=4)
logger.info(f"file_path: {file_path}")
logger.info(f"middle_json: {middle_json}")
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index ff4cbe01..2dade4af 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -91,7 +91,7 @@ def test_visual_block_crop_rotates_to_upright(
analyze._attach_visual_block_images([[block]], [{"img_pil": page_image}])
- crop_image = _decode_jpeg_data_uri(block["image_base64"])
+ crop_image = _decode_jpeg_data_uri(block["_image_base64"])
try:
assert crop_image.size == expected_size
_assert_colors_close(_sample_quadrant_colors(crop_image), expected_colors)
@@ -139,7 +139,7 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:
"bbox": [0.1, 0.2, 0.6, 0.7],
"angle": 0,
"content": f"content-{block_type}",
- "image_base64": "stale",
+ "_image_base64": "stale",
}
for block_type in (
BlockType.IMAGE,
@@ -152,7 +152,7 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:
"type": BlockType.TEXT,
"bbox": [0.0, 0.0, 1.0, 1.0],
"content": "text",
- "image_base64": "keep-text-field",
+ "_image_base64": "keep-text-field",
}
analyze._attach_visual_block_images(
@@ -163,21 +163,21 @@ def test_visual_block_types_receive_jpeg_data_uri_only() -> None:
try:
for block in visual_blocks:
- assert block["image_base64"] != "stale"
- crop_image = _decode_jpeg_data_uri(block["image_base64"])
+ assert block["_image_base64"] != "stale"
+ crop_image = _decode_jpeg_data_uri(block["_image_base64"])
try:
assert crop_image.size == (50, 30)
finally:
crop_image.close()
assert block["content"] == f"content-{block['type']}"
assert block["bbox"] == [0.1, 0.2, 0.6, 0.7]
- assert text_block["image_base64"] == "keep-text-field"
+ assert text_block["_image_base64"] == "keep-text-field"
finally:
page_image.close()
def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:
- """验证像素框会裁到页面范围,无效框会清理旧载荷且不影响其他块。"""
+ """验证像素框会裁到页面范围,无效框会跳过载荷写入且不影响其他块。"""
page_image = Image.new("L", (100, 80), 128)
clipped_block = {
"type": BlockType.CHART,
@@ -188,7 +188,6 @@ def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:
"type": BlockType.TABLE,
"bbox": [0.5, 0.5, 0.5, 0.8],
"angle": 0,
- "image_base64": "stale",
}
analyze._attach_visual_block_images(
@@ -196,13 +195,235 @@ def test_visual_block_crop_clips_page_boundary_and_skips_invalid_bbox() -> None:
[{"img_pil": page_image}],
)
- crop_image = _decode_jpeg_data_uri(clipped_block["image_base64"])
+ crop_image = _decode_jpeg_data_uri(clipped_block["_image_base64"])
try:
assert crop_image.size == (30, 20)
finally:
crop_image.close()
page_image.close()
- assert "image_base64" not in invalid_block
+ assert "_image_base64" not in invalid_block
+
+
+def test_image_block_collapses_contained_blocks_before_visual_crop() -> None:
+ """验证 image_block 截图前吸收内部小块,并按子块面积应用 0.8 包含阈值。"""
+ page_image = Image.new("RGB", (100, 60), "white")
+ leading_text = {
+ "type": BlockType.TEXT,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "keep-leading-text",
+ }
+ image_block = {
+ "type": "image_block",
+ "bbox": [0.0, 0.0, 0.8, 0.8],
+ "angle": 0,
+ "content": None,
+ }
+ threshold_image = {
+ "type": BlockType.IMAGE,
+ "bbox": [0.0, 0.0, 1.0, 0.8],
+ "angle": 0,
+ }
+ contained_caption = {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.1, 0.1, 0.3, 0.2],
+ "content": "remove-contained-caption",
+ }
+ below_threshold_caption = {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.0, 0.0, 1.0, 0.81],
+ "content": "keep-below-threshold-caption",
+ }
+ invalid_caption = {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.2, 0.2, 0.2, 0.3],
+ "content": "keep-invalid-caption",
+ }
+ external_caption = {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.0, 0.82, 0.8, 0.9],
+ "content": "keep-external-caption",
+ }
+ page_model_list = [
+ leading_text,
+ image_block,
+ threshold_image,
+ contained_caption,
+ below_threshold_caption,
+ invalid_caption,
+ external_caption,
+ ]
+
+ analyze._attach_visual_block_images(
+ [page_model_list],
+ [{"img_pil": page_image}],
+ )
+
+ try:
+ assert page_model_list == [
+ leading_text,
+ image_block,
+ below_threshold_caption,
+ invalid_caption,
+ external_caption,
+ ]
+ assert image_block["type"] == BlockType.IMAGE
+ assert all(block.get("type") != "image_block" for block in page_model_list)
+ crop_image = _decode_jpeg_data_uri(image_block["_image_base64"])
+ try:
+ assert crop_image.size == (80, 48)
+ finally:
+ crop_image.close()
+ finally:
+ page_image.close()
+
+
+def test_image_block_collapse_keeps_invalid_bbox_blocks() -> None:
+ """验证无效容器或子块不会参与面积吸收,但容器类型仍会规范为 image。"""
+ invalid_image_block = {
+ "type": "image_block",
+ "bbox": None,
+ "content": None,
+ }
+ valid_child = {
+ "type": BlockType.IMAGE,
+ "bbox": [0.1, 0.1, 0.2, 0.2],
+ }
+ invalid_child = {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.2, 0.2, 0.2, 0.3],
+ }
+ page_model_list = [invalid_image_block, valid_child, invalid_child]
+
+ analyze._collapse_image_blocks(page_model_list)
+
+ assert page_model_list == [invalid_image_block, valid_child, invalid_child]
+ assert invalid_image_block["type"] == BlockType.IMAGE
+
+
+def test_xhigh_layout_image_supplements_missing_container_before_crop() -> None:
+ """验证 xhigh 可用高覆盖率 layout 整图框补容器并复用现有截图折叠流程。"""
+ page_image = Image.new("RGB", (1700, 2200), "white")
+ page_model_list = [
+ {"type": BlockType.IMAGE, "bbox": [0.083, 0.127, 0.278, 0.243]},
+ {"type": BlockType.IMAGE, "bbox": [0.281, 0.127, 0.477, 0.243]},
+ {"type": BlockType.IMAGE, "bbox": [0.084, 0.246, 0.278, 0.361]},
+ {"type": BlockType.IMAGE, "bbox": [0.281, 0.246, 0.477, 0.361]},
+ {"type": BlockType.IMAGE, "bbox": [0.084, 0.364, 0.278, 0.48]},
+ {"type": BlockType.IMAGE, "bbox": [0.281, 0.364, 0.477, 0.48]},
+ {"type": BlockType.IMAGE, "bbox": [0.083, 0.483, 0.279, 0.598]},
+ {"type": BlockType.IMAGE, "bbox": [0.281, 0.483, 0.477, 0.598]},
+ {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.154, 0.6, 0.214, 0.611],
+ "content": "Frame 30",
+ },
+ {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.35, 0.6, 0.41, 0.611],
+ "content": "Frame 90",
+ },
+ {
+ "type": BlockType.IMAGE_CAPTION,
+ "bbox": [0.074, 0.616, 0.493, 0.678],
+ "content": "Figure 2: keep external caption",
+ },
+ ]
+ layout_blocks_list = [
+ [
+ {
+ "type": BlockType.IMAGE,
+ "bbox": [0.082352941, 0.127272727, 0.477647059, 0.611818182],
+ "angle": 0,
+ }
+ ]
+ ]
+
+ analyze._supplement_missing_image_block_containers(
+ [page_model_list],
+ layout_blocks_list,
+ )
+ assert sum(block.get("type") == "image_block" for block in page_model_list) == 1
+
+ analyze._attach_visual_block_images(
+ [page_model_list],
+ [{"img_pil": page_image}],
+ )
+
+ try:
+ assert len(page_model_list) == 2
+ image_block, external_caption = page_model_list
+ assert image_block["type"] == BlockType.IMAGE
+ assert image_block["bbox"] == layout_blocks_list[0][0]["bbox"]
+ assert external_caption["content"] == "Figure 2: keep external caption"
+ crop_image = _decode_jpeg_data_uri(image_block["_image_base64"])
+ try:
+ assert crop_image.size == (674, 1068)
+ finally:
+ crop_image.close()
+ finally:
+ page_image.close()
+
+
+ ("image_bboxes", "layout_type", "expected_container_count"),
+ [
+ (([0.0, 0.0, 0.46, 1.0], [0.54, 0.0, 1.0, 1.0]), BlockType.IMAGE, 1),
+ (([0.0, 0.0, 0.45, 1.0], [0.55, 0.0, 1.0, 1.0]), BlockType.IMAGE, 0),
+ (([0.0, 0.0, 0.95, 1.0],), BlockType.IMAGE, 0),
+ (([0.0, 0.0, 0.46, 1.0], [0.54, 0.0, 1.0, 1.0]), BlockType.CHART, 0),
+ ],
+)
+def test_xhigh_layout_image_fallback_requires_image_count_and_strict_coverage(
+ image_bboxes: tuple[list[float], ...],
+ layout_type: str,
+ expected_container_count: int,
+) -> None:
+ """验证 layout 回退要求至少两个 image,且面积占比必须严格大于 0.9。"""
+ page_model_list = [
+ {"type": BlockType.IMAGE, "bbox": bbox}
+ for bbox in image_bboxes
+ ]
+ layout_blocks_list = [[{"type": layout_type, "bbox": [0.0, 0.0, 1.0, 1.0], "angle": 0}]]
+
+ analyze._supplement_missing_image_block_containers(
+ [page_model_list],
+ layout_blocks_list,
+ )
+
+ assert sum(block.get("type") == "image_block" for block in page_model_list) == expected_container_count
+
+
+def test_xhigh_layout_image_fallback_does_not_duplicate_existing_or_overlapping_containers() -> None:
+ """验证已有 VLM 容器和竞争 layout 框不会重复认领相同 image。"""
+ existing_image_block = {
+ "type": "image_block",
+ "bbox": [0.0, 0.0, 0.48, 1.0],
+ "angle": 0,
+ }
+ page_model_list = [
+ existing_image_block,
+ {"type": BlockType.IMAGE, "bbox": [0.0, 0.0, 0.24, 1.0]},
+ {"type": BlockType.IMAGE, "bbox": [0.24, 0.0, 0.48, 1.0]},
+ {"type": BlockType.IMAGE, "bbox": [0.52, 0.0, 0.76, 1.0]},
+ {"type": BlockType.IMAGE, "bbox": [0.76, 0.0, 1.0, 1.0]},
+ ]
+ layout_blocks_list = [
+ [
+ {"type": BlockType.IMAGE, "bbox": [0.0, 0.0, 0.48, 1.0], "angle": 0},
+ {"type": BlockType.IMAGE, "bbox": [0.5, 0.0, 1.0, 1.0], "angle": 0},
+ {"type": BlockType.IMAGE, "bbox": [0.51, 0.0, 1.0, 1.0], "angle": 0},
+ ]
+ ]
+
+ analyze._supplement_missing_image_block_containers(
+ [page_model_list],
+ layout_blocks_list,
+ )
+
+ image_blocks = [block for block in page_model_list if block.get("type") == "image_block"]
+ assert len(image_blocks) == 2
+ assert existing_image_block in image_blocks
+ assert sum(block.get("bbox") in ([0.5, 0.0, 1.0, 1.0], [0.51, 0.0, 1.0, 1.0]) for block in image_blocks) == 1
def test_visual_block_crop_rejects_page_count_mismatch() -> None:
@@ -574,9 +795,9 @@ def test_doc_analyze_flash_returns_complete_model_list_without_middle_json(monke
assert requested_ranges == [(0, 1), (2, 2)]
assert model_list[0][0]["content"] == "第一页 <eq>x+y</eq>"
assert model_list[2][0]["content"] == "第三页 <eq>z</eq>"
- assert "image_base64" not in model_list[0][0]
+ assert "_image_base64" not in model_list[0][0]
for block in (model_list[1][0], model_list[2][0]):
- crop_image = _decode_jpeg_data_uri(block["image_base64"])
+ crop_image = _decode_jpeg_data_uri(block["_image_base64"])
crop_image.close()
for image in rendered_images:
with pytest.raises(ValueError, match="closed image"):