Skip to content

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

feat: enhance raster image processing by refining inline image grouping and gap handling

myhloli3c7721c0dd60
diff --git a/mineru/backend/flash/native_pdf/graphics.py b/mineru/backend/flash/native_pdf/graphics.py
index ab08d04a..efd0c681 100644
--- a/mineru/backend/flash/native_pdf/graphics.py
+++ b/mineru/backend/flash/native_pdf/graphics.py
@@ -42,7 +42,7 @@ from .line_layout import (
from .line_merging import _join_formula_visual_row
-_MIN_RASTER_IMAGE_PAGE_AREA_RATIO = 0.005
+_MIN_RASTER_IMAGE_PAGE_AREA_RATIO = 0.0038
_MIN_FORM_IMAGE_PAGE_AREA_RATIO = 0.01
@@ -695,6 +695,182 @@ def _graphic_members_to_block(
}
+def _inline_raster_gap_member(
+ source: _PageSource,
+ left_bbox: BBox,
+ right_bbox: BBox,
+ claimed_line_indices: set[int],
+ median_height: float,
+) -> _LineItem | None:
+ """查找恰好填充两张同行图片间隙的唯一拆分文本 run。"""
+
+ left_height = max(0.1, left_bbox[3] - left_bbox[1])
+ right_height = max(0.1, right_bbox[3] - right_bbox[1])
+ vertical_overlap = max(
+ 0.0,
+ min(left_bbox[3], right_bbox[3])
+ - max(left_bbox[1], right_bbox[1]),
+ )
+ horizontal_gap = right_bbox[0] - left_bbox[2]
+ if (
+ max(left_height, right_height) / min(left_height, right_height) > 1.25
+ or vertical_overlap / min(left_height, right_height) < 0.8
+ or not 0.0 <= horizontal_gap <= 1.5 * median_height
+ ):
+ return None
+
+ edge_tolerance = max(0.5, 0.25 * median_height)
+ band_top = max(left_bbox[1], right_bbox[1])
+ band_bottom = min(left_bbox[3], right_bbox[3])
+ gap_members = [
+ line
+ for line in source.lines
+ if line.source_index not in claimed_line_indices
+ and line.angle == 0
+ and line.split_from_row
+ and line.visual_row_id is not None
+ and left_bbox[2] - edge_tolerance
+ <= _bbox_center_x(line.bbox)
+ <= right_bbox[0] + edge_tolerance
+ and band_top - edge_tolerance
+ <= _bbox_center_y(line.bbox)
+ <= band_bottom + edge_tolerance
+ ]
+ if len(gap_members) != 1:
+ return None
+ member = gap_members[0]
+ if (
+ abs(member.bbox[0] - left_bbox[2]) > edge_tolerance
+ or abs(member.bbox[2] - right_bbox[0]) > edge_tolerance
+ ):
+ return None
+ return member
+
+
+def _inline_raster_group_has_only_expected_text(
+ source: _PageSource,
+ image_bboxes: list[BBox],
+ gap_members: list[_LineItem],
+ group_bbox: BBox,
+ claimed_line_indices: set[int],
+) -> bool:
+ """确认复合图片框内没有图片内部文本和间隔符之外的正文。"""
+
+ gap_member_indices = {line.source_index for line in gap_members}
+ for line in source.lines:
+ if line.source_index in claimed_line_indices:
+ continue
+ center = (_bbox_center_x(line.bbox), _bbox_center_y(line.bbox))
+ if not _point_in_bbox(center, group_bbox):
+ continue
+ if line.source_index in gap_member_indices:
+ continue
+ if any(_point_in_bbox(center, image_bbox) for image_bbox in image_bboxes):
+ continue
+ return False
+ return True
+
+
+def _merge_inline_raster_image_candidates(
+ source: _PageSource,
+ candidate_bboxes: list[BBox],
+ container_bboxes: list[BBox],
+ claimed_line_indices: set[int],
+) -> list[tuple[BBox, int | None]]:
+ """把由同一视觉行间隔符连接的已准入图片合成为单一候选。"""
+
+ if len(candidate_bboxes) < 3:
+ return [(bbox, None) for bbox in candidate_bboxes]
+ effective_heights = [
+ _line_effective_height(line, line.bbox)
+ for line in source.lines
+ if line.source_index not in claimed_line_indices and line.angle == 0
+ ]
+ median_height = statistics.median(effective_heights) if effective_heights else 1.0
+
+ adjacency: dict[int, set[int]] = {
+ index: set() for index in range(len(candidate_bboxes))
+ }
+ gap_members: dict[tuple[int, int], _LineItem] = {}
+ for first_index, first_bbox in enumerate(candidate_bboxes):
+ for second_index, second_bbox in enumerate(candidate_bboxes):
+ if first_index == second_index or first_bbox[0] >= second_bbox[0]:
+ continue
+ member = _inline_raster_gap_member(
+ source,
+ first_bbox,
+ second_bbox,
+ claimed_line_indices,
+ median_height,
+ )
+ if member is None:
+ continue
+ adjacency[first_index].add(second_index)
+ adjacency[second_index].add(first_index)
+ gap_members[(first_index, second_index)] = member
+
+ components: list[list[int]] = []
+ visited: set[int] = set()
+ for start_index in range(len(candidate_bboxes)):
+ if start_index in visited:
+ continue
+ component: list[int] = []
+ pending = [start_index]
+ while pending:
+ current_index = pending.pop()
+ if current_index in visited:
+ continue
+ visited.add(current_index)
+ component.append(current_index)
+ pending.extend(adjacency[current_index] - visited)
+ components.append(component)
+
+ merged_specs: list[tuple[BBox, int | None]] = []
+ consumed_indices: set[int] = set()
+ for component in components:
+ if len(component) < 3:
+ continue
+ ordered_indices = sorted(
+ component,
+ key=lambda index: candidate_bboxes[index][0],
+ )
+ ordered_pairs = list(zip(ordered_indices, ordered_indices[1:]))
+ if not all(pair in gap_members for pair in ordered_pairs):
+ continue
+ members = [gap_members[pair] for pair in ordered_pairs]
+ visual_row_ids = {member.visual_row_id for member in members}
+ if len(visual_row_ids) != 1 or None in visual_row_ids:
+ continue
+ image_bboxes = [candidate_bboxes[index] for index in ordered_indices]
+ group_bbox = _bbox_union_many(
+ [*image_bboxes, *[member.bbox for member in members]],
+ )
+ if any(
+ _bbox_overlap_in_smaller(group_bbox, container_bbox)
+ >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD
+ for container_bbox in container_bboxes
+ ):
+ continue
+ if not _inline_raster_group_has_only_expected_text(
+ source,
+ image_bboxes,
+ members,
+ group_bbox,
+ claimed_line_indices,
+ ):
+ continue
+ merged_specs.append((group_bbox, next(iter(visual_row_ids))))
+ consumed_indices.update(ordered_indices)
+
+ merged_specs.extend(
+ (bbox, None)
+ for index, bbox in enumerate(candidate_bboxes)
+ if index not in consumed_indices
+ )
+ merged_specs.sort(key=lambda item: (item[0][1], item[0][0], item[0][3], item[0][2]))
+ return merged_specs
+
+
def _build_raster_image_blocks(
source: _PageSource,
container_blocks: list[dict[str, Any]],
@@ -725,6 +901,14 @@ def _build_raster_image_blocks(
if not candidate_bboxes:
return [], set()
+ candidate_specs = _merge_inline_raster_image_candidates(
+ source,
+ candidate_bboxes,
+ container_bboxes,
+ claimed_line_indices,
+ )
+ candidate_bboxes = [bbox for bbox, _row_id in candidate_specs]
+
members_by_candidate: list[list[_LineItem]] = [[] for _ in candidate_bboxes]
claimed: set[int] = set()
for line in source.lines:
@@ -746,14 +930,20 @@ def _build_raster_image_blocks(
members_by_candidate[candidate_index].append(line)
claimed.add(line.source_index)
- blocks = [
- {
+ blocks: list[dict[str, Any]] = []
+ for (bbox, visual_row_id), members in zip(
+ candidate_specs,
+ members_by_candidate,
+ strict=True,
+ ):
+ block = {
"type": "image",
"bbox": bbox,
"angle": 0,
"content": _image_members_to_content(members, source.page_size),
}
- for bbox, members in zip(candidate_bboxes, members_by_candidate, strict=True)
- ]
+ if visual_row_id is not None:
+ block["_inline_visual_row_id"] = visual_row_id
+ blocks.append(block)
blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))
return blocks, claimed
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 2e123bf6..b8b37c2d 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -326,11 +326,16 @@ def _finalize_prepared_page(
prepared.page_size,
container_bboxes,
)
+ title_container_bboxes = [
+ block["bbox"]
+ for block in prepared.fixed_blocks
+ if not isinstance(block.get("_inline_visual_row_id"), int)
+ ]
_classify_page_titles(
remaining_lines,
prepared.page_size,
page_index=page_index,
- container_bboxes=container_bboxes,
+ container_bboxes=title_container_bboxes,
document_body_profile=document_body_profile,
)
remaining_lines = _merge_title_resolved_visual_rows(
@@ -401,14 +406,34 @@ def _sort_blocks_with_visual_row_groups(
else:
body_blocks.append(block)
+ inline_grouped_indices = _collect_inline_image_text_groups(body_blocks)
+ inline_consumed_indices = {
+ index
+ for indices in inline_grouped_indices.values()
+ for index in indices
+ }
grouped_indices: dict[int, list[int]] = {}
for index, block in enumerate(body_blocks):
+ if index in inline_consumed_indices:
+ continue
row_id = block.get("_single_run_row_id")
if isinstance(row_id, int):
grouped_indices.setdefault(row_id, []).append(index)
- virtual_groups: dict[int, dict[str, Any]] = {}
- consumed_indices: set[int] = set()
+ virtual_groups: list[dict[str, Any]] = []
+ consumed_indices: set[int] = set(inline_consumed_indices)
+ for row_id, indices in inline_grouped_indices.items():
+ members = [body_blocks[index] for index in indices]
+ virtual_groups.append(
+ {
+ "type": "_xycut_visual_row_group",
+ "bbox": _bbox_union_many([member["bbox"] for member in members]),
+ "angle": members[0].get("angle", 0),
+ "content": "",
+ "_members": members,
+ "_inline_visual_row_id": row_id,
+ }
+ )
for row_id, indices in grouped_indices.items():
if len(indices) < 2:
continue
@@ -420,7 +445,7 @@ def _sort_blocks_with_visual_row_groups(
"content": "",
"_members": members,
}
- virtual_groups[row_id] = virtual_group
+ virtual_groups.append(virtual_group)
consumed_indices.update(indices)
sortable_blocks = [
@@ -428,7 +453,7 @@ def _sort_blocks_with_visual_row_groups(
for index, block in enumerate(body_blocks)
if index not in consumed_indices
]
- sortable_blocks.extend(virtual_groups.values())
+ sortable_blocks.extend(virtual_groups)
sorted_payloads = sort_entries(sortable_blocks)
output: list[dict[str, Any]] = []
for payload in sorted_payloads:
@@ -436,6 +461,15 @@ def _sort_blocks_with_visual_row_groups(
if not isinstance(members, list):
output.append(payload)
continue
+ if isinstance(payload.get("_inline_visual_row_id"), int):
+ members.sort(
+ key=lambda member: _inline_visual_group_member_sort_key(
+ member,
+ page_size,
+ )
+ )
+ output.extend(members)
+ continue
angle = int(payload.get("angle", 0) or 0) % 360
members.sort(
key=lambda member: (
@@ -452,6 +486,62 @@ def _sort_blocks_with_visual_row_groups(
]
+def _collect_inline_image_text_groups(
+ body_blocks: list[dict[str, Any]],
+) -> dict[int, list[int]]:
+ """把复合图片与包含同一首行的正文块组成专用排序组。"""
+
+ image_indices_by_row: dict[int, list[int]] = {}
+ for index, block in enumerate(body_blocks):
+ row_id = block.get("_inline_visual_row_id")
+ if block.get("type") == "image" and isinstance(row_id, int):
+ image_indices_by_row.setdefault(row_id, []).append(index)
+
+ output: dict[int, list[int]] = {}
+ consumed_text_indices: set[int] = set()
+ for row_id, image_indices in sorted(image_indices_by_row.items()):
+ text_indices = [
+ index
+ for index, block in enumerate(body_blocks)
+ if index not in consumed_text_indices
+ and block.get("type") == "text"
+ and isinstance(block.get("_visual_row_ids"), set)
+ and row_id in block["_visual_row_ids"]
+ ]
+ if not text_indices:
+ continue
+ output[row_id] = [*image_indices, *text_indices]
+ consumed_text_indices.update(text_indices)
+ return output
+
+
+def _inline_visual_group_member_sort_key(
+ block: dict[str, Any],
+ page_size: tuple[float, float],
+) -> tuple[float, float, int]:
+ """按图片位置或正文首个局部行位置确定复合视觉行的组内顺序。"""
+
+ local_line_bboxes = block.get("_local_line_bboxes")
+ if (
+ block.get("type") == "text"
+ and isinstance(local_line_bboxes, list)
+ and local_line_bboxes
+ ):
+ local_bbox = local_line_bboxes[0]
+ else:
+ angle = int(block.get("angle", 0) or 0) % 360
+ local_bbox = _rotate_bbox_to_upright(
+ block["bbox"],
+ page_size,
+ angle,
+ )
+ return (
+ float(local_bbox[0]),
+ float(local_bbox[1]),
+ 0 if block.get("type") == "image" else 1,
+ )
+
+
def _sort_marginal_blocks(
blocks: list[dict[str, Any]],
page_size: tuple[float, float],
diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.py
index 96e94beb..c5a2265b 100644
--- a/tests/unittest/test_flash_pdf_graphics.py
+++ b/tests/unittest/test_flash_pdf_graphics.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import pytest
+
from mineru.backend.flash.native_pdf import (
graphics,
@@ -264,6 +266,187 @@ def test_form_image_claims_internal_text_and_small_table_but_not_caption() -> No
]
+def _inline_raster_sequence_source() -> models._PageSource:
+ """构造四张点阵图、三个同行间隔符及其右侧三行正文。"""
+
+ return models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=[
+ _text_line(
+ "、",
+ (20.0, 22.0, 22.0, 25.0),
+ 0,
+ visual_row_id=7,
+ run_index=0,
+ split_from_row=True,
+ ),
+ _text_line(
+ "、",
+ (32.0, 22.0, 34.0, 25.0),
+ 1,
+ visual_row_id=7,
+ run_index=1,
+ split_from_row=True,
+ ),
+ _text_line(
+ "、",
+ (48.0, 22.0, 50.0, 25.0),
+ 2,
+ visual_row_id=7,
+ run_index=2,
+ split_from_row=True,
+ ),
+ _text_line(
+ "尾随文字",
+ (60.0, 22.0, 90.0, 25.0),
+ 3,
+ visual_row_id=7,
+ run_index=3,
+ split_from_row=True,
+ ),
+ _text_line("正文第一行", (10.0, 27.0, 90.0, 30.0), 4, visual_row_id=8),
+ _text_line("正文第二行", (10.0, 32.0, 50.0, 35.0), 5, visual_row_id=9),
+ ],
+ chars=[],
+ drawing_lines=[],
+ image_bboxes=[
+ (10.0, 20.0, 20.0, 24.0),
+ (22.0, 20.0, 32.0, 24.0),
+ (34.0, 20.0, 48.0, 24.0),
+ (50.0, 20.0, 60.0, 24.0),
+ ],
+ )
+
+
+def test_raster_image_threshold_accepts_point_38_percent_only() -> None:
+ """验证页面面积达到 0.38% 时准入,略低于阈值的孤立图片仍过滤。"""
+
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=[],
+ chars=[],
+ drawing_lines=[],
+ image_bboxes=[
+ (0.0, 0.0, 9.5, 4.0),
+ (20.0, 0.0, 29.49, 4.0),
+ ],
+ )
+
+ blocks, claimed = graphics._build_raster_image_blocks(source, [], set())
+
+ assert [block["bbox"] for block in blocks] == [(0.0, 0.0, 9.5, 4.0)]
+ assert claimed == set()
+
+
+def test_inline_raster_images_and_gap_runs_form_one_composite_image() -> None:
+ """验证四张已准入图片与三个同行间隔符合成一个复合 image。"""
+
+ source = _inline_raster_sequence_source()
+
+ blocks, claimed = graphics._build_raster_image_blocks(source, [], set())
+
+ assert len(blocks) == 1
+ assert blocks[0]["bbox"] == (10.0, 20.0, 60.0, 25.0)
+ assert blocks[0]["content"].replace(" ", "") == "、、、"
+ assert blocks[0]["_inline_visual_row_id"] == 7
+ assert claimed == {0, 1, 2}
+ assert 3 not in claimed
+
+
+ "failure_mode",
+ [
+ "misaligned",
+ "wide_gap",
+ "missing_gap",
+ "inconsistent_row",
+ "too_few_images",
+ "container_bridge",
+ ],
+)
+def test_inline_raster_composite_requires_complete_spatial_sequence(
+ failure_mode: str,
+) -> None:
+ """验证图片或间隔符结构不完整时保留独立图片而不生成复合容器。"""
+
+ source = _inline_raster_sequence_source()
+ container_blocks: list[dict[str, object]] = []
+ if failure_mode == "misaligned":
+ source.image_bboxes[1] = (22.0, 10.0, 32.0, 14.0)
+ elif failure_mode == "wide_gap":
+ source.image_bboxes[2] = (42.0, 20.0, 56.0, 24.0)
+ source.image_bboxes[3] = (58.0, 20.0, 68.0, 24.0)
+ source.lines[2].bbox = (56.0, 22.0, 58.0, 25.0)
+ elif failure_mode == "missing_gap":
+ source.lines = [line for line in source.lines if line.source_index != 1]
+ elif failure_mode == "inconsistent_row":
+ source.lines[1].visual_row_id = 8
+ elif failure_mode == "too_few_images":
+ source.image_bboxes = source.image_bboxes[:2]
+ else:
+ container_blocks = [
+ {
+ "type": "table",
+ "bbox": (32.5, 20.0, 33.5, 25.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+
+ blocks, claimed = graphics._build_raster_image_blocks(
+ source,
+ container_blocks,
+ set(),
+ )
+
+ assert len(blocks) == len(source.image_bboxes)
+ assert not [block for block in blocks if "_inline_visual_row_id" in block]
+ assert claimed == set()
+
+
+def test_inline_composite_sorts_before_overlapping_multiline_text() -> None:
+ """验证复合图片与含同行首行的多行正文绑定后始终先输出图片。"""
+
+ blocks = [
+ {
+ "type": "image",
+ "bbox": (10.0, 20.0, 60.0, 25.0),
+ "angle": 0,
+ "content": "、、、",
+ "_inline_visual_row_id": 7,
+ },
+ {
+ "type": "text",
+ "bbox": (10.0, 22.0, 90.0, 35.0),
+ "angle": 0,
+ "content": "尾随文字正文第一行正文第二行",
+ "_visual_row_ids": {7, 8, 9},
+ "_local_line_bboxes": [
+ (60.0, 22.0, 90.0, 25.0),
+ (10.0, 27.0, 90.0, 30.0),
+ (10.0, 32.0, 50.0, 35.0),
+ ],
+ },
+ {
+ "type": "paragraph_title",
+ "bbox": (10.0, 40.0, 30.0, 44.0),
+ "angle": 0,
+ "content": "下一节",
+ },
+ ]
+
+ sorted_blocks = pipeline._sort_blocks_with_visual_row_groups(
+ blocks,
+ (100.0, 100.0),
+ )
+
+ assert [block["type"] for block in sorted_blocks] == [
+ "image",
+ "text",
+ "paragraph_title",
+ ]
+
+
def test_raster_images_filter_small_objects_avoid_containers_and_claim_text_once() -> None:
"""验证点阵图过滤、容器优先、空 content 和重叠对象的唯一文本归属。"""
@@ -280,7 +463,7 @@ def test_raster_images_filter_small_objects_avoid_containers_and_claim_text_once
(10.0, 10.0, 50.0, 50.0),
(20.0, 20.0, 40.0, 40.0),
(60.0, 10.0, 90.0, 40.0),
- (0.0, 90.0, 10.0, 94.0),
+ (0.0, 90.0, 9.0, 94.0),
(10.0, 60.0, 50.0, 90.0),
],
)