Skip to content

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

feat: implement cross-lane caption handling with geometry-based classification and enhance related tests

myhlolicefd22cdaaf1
diff --git a/mineru/backend/flash/native_pdf/visual_annotations.py b/mineru/backend/flash/native_pdf/visual_annotations.py
index 631db17b..bf8051c2 100644
--- a/mineru/backend/flash/native_pdf/visual_annotations.py
+++ b/mineru/backend/flash/native_pdf/visual_annotations.py
@@ -30,6 +30,9 @@ _FOOTNOTE_MAX_GAP_IN_LINE_HEIGHTS = 6.0
_MIN_PROJECTION_OVERLAP = 0.8
_MIN_ANNOTATION_COVERAGE = 0.65
_COMPONENT_COVERAGE_GAIN = 0.15
+_CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE = 0.25
+_CROSS_LANE_CAPTION_MIN_LINE_HEIGHT_RATIO = 0.85
+_CROSS_LANE_CAPTION_MAX_LINE_HEIGHT_RATIO = 1.15
_TABLE_FOOTNOTE_CONTINUATION_MAX_GAP = 1.5
_TABLE_FOOTNOTE_FIRST_INDENT_MIN = 0.5
_TABLE_FOOTNOTE_FIRST_INDENT_MAX = 2.0
@@ -810,6 +813,169 @@ def _choose_annotation_relation(
)
+def _caption_blocks_use_distinct_regular_lanes(
+ anchor: dict[str, Any],
+ candidate: dict[str, Any],
+) -> bool:
+ """确认两个标题块分别属于互不重叠的普通栏带。"""
+
+ if (
+ anchor.get("_lane_is_span") is not False
+ or candidate.get("_lane_is_span") is not False
+ ):
+ return False
+ anchor_interval = _coerce_lane_interval(anchor.get("_lane_interval"))
+ candidate_interval = _coerce_lane_interval(candidate.get("_lane_interval"))
+ if anchor_interval is None or candidate_interval is None:
+ return False
+ return (
+ anchor_interval[1] <= candidate_interval[0]
+ or candidate_interval[1] <= anchor_interval[0]
+ )
+
+
+def _caption_blocks_have_compatible_typography(
+ anchor: dict[str, Any],
+ candidate: dict[str, Any],
+ page_size: tuple[float, float],
+) -> bool:
+ """用行高和字体交集确认跨栏标题块来自同一排版层级。"""
+
+ anchor_height = _block_median_line_height(anchor, page_size)
+ candidate_height = _block_median_line_height(candidate, page_size)
+ if anchor_height <= 0 or candidate_height <= 0:
+ return False
+ height_ratio = candidate_height / anchor_height
+ if not (
+ _CROSS_LANE_CAPTION_MIN_LINE_HEIGHT_RATIO
+ <= height_ratio
+ <= _CROSS_LANE_CAPTION_MAX_LINE_HEIGHT_RATIO
+ ):
+ return False
+
+ anchor_fonts = anchor.get("_font_signatures")
+ candidate_fonts = candidate.get("_font_signatures")
+ if not (
+ isinstance(anchor_fonts, (set, frozenset))
+ and isinstance(candidate_fonts, (set, frozenset))
+ and anchor_fonts
+ and candidate_fonts
+ ):
+ return False
+ return not anchor_fonts.isdisjoint(candidate_fonts)
+
+
+def _cross_lane_caption_companion_relation(
+ anchor_index: int,
+ candidate_index: int,
+ anchor_relation: _AnnotationRelation,
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ parents: list[_VisualParent],
+ annotation_indices: set[int],
+) -> _AnnotationRelation | None:
+ """仅凭空间、栏带和排版信息确认一个跨栏标题同伴。"""
+
+ if anchor_relation.direction not in {"above", "below"}:
+ return None
+ anchor = blocks[anchor_index]
+ candidate = blocks[candidate_index]
+ if (
+ candidate.get("type") != "text"
+ or _block_angle(candidate) != anchor_relation.parent.angle
+ ):
+ return None
+ if not _caption_blocks_use_distinct_regular_lanes(anchor, candidate):
+ return None
+ if not _caption_blocks_have_compatible_typography(
+ anchor,
+ candidate,
+ page_size,
+ ):
+ return None
+
+ angle = anchor_relation.parent.angle
+ anchor_first_row = _block_first_local_row_bbox(anchor, page_size, angle)
+ candidate_first_row = _block_first_local_row_bbox(
+ candidate,
+ page_size,
+ angle,
+ )
+ if anchor_first_row is None or candidate_first_row is None:
+ return None
+ pair_height = statistics.median(
+ (
+ _block_median_line_height(anchor, page_size),
+ _block_median_line_height(candidate, page_size),
+ )
+ )
+ if (
+ abs(anchor_first_row[1] - candidate_first_row[1])
+ > _CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE * pair_height
+ ):
+ return None
+
+ relation = _choose_annotation_relation(
+ candidate_index,
+ "caption",
+ blocks,
+ page_size,
+ parents,
+ annotation_indices | {candidate_index},
+ )
+ if (
+ relation is None
+ or relation.parent != anchor_relation.parent
+ or relation.direction != anchor_relation.direction
+ ):
+ return None
+ return relation
+
+
+def _expand_cross_lane_caption_assignments(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ parents: list[_VisualParent],
+ candidates: dict[int, _AnnotationKind],
+ assignments: dict[int, _AnnotationRelation],
+) -> dict[int, _AnnotationRelation]:
+ """从原始已绑定标题出发,保守补标唯一的跨栏空间同伴。"""
+
+ annotation_indices = set(candidates)
+ proposals: dict[int, list[_AnnotationRelation]] = {}
+ for anchor_index, anchor_relation in assignments.items():
+ if candidates.get(anchor_index) != "caption":
+ continue
+ matches = [
+ (index, relation)
+ for index in range(len(blocks))
+ if index not in annotation_indices
+ and (
+ relation := _cross_lane_caption_companion_relation(
+ anchor_index,
+ index,
+ anchor_relation,
+ blocks,
+ page_size,
+ parents,
+ annotation_indices,
+ )
+ )
+ is not None
+ ]
+ if len(matches) != 1:
+ continue
+ index, relation = matches[0]
+ proposals.setdefault(index, []).append(relation)
+
+ output: dict[int, _AnnotationRelation] = {}
+ for index, relations in proposals.items():
+ # 同伴同时被多个锚点认领时归属不唯一,保守地维持正文分类。
+ if len(relations) == 1:
+ output[index] = relations[0]
+ return output
+
+
def _merge_parent_assignment_groups(
assignments: dict[int, _AnnotationRelation],
) -> list[tuple[set[int], dict[int, _AnnotationRelation]]]:
@@ -866,6 +1032,87 @@ def _annotation_local_sort_key(
return (local_bbox[1], local_bbox[0], index)
+def _sort_annotation_indices_by_visual_rows(
+ indices: list[int],
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ relations: dict[int, _AnnotationRelation],
+) -> list[int]:
+ """先聚合首行对齐的标题视觉行,再按行内左到右稳定排序。"""
+
+ positioned: list[tuple[int, BBox, float]] = []
+ fallback: list[int] = []
+ for index in indices:
+ block = blocks[index]
+ angle = _block_angle(block)
+ first_row = _block_first_local_row_bbox(block, page_size, angle)
+ if first_row is None:
+ fallback.append(index)
+ continue
+ positioned.append(
+ (
+ index,
+ first_row,
+ _block_median_line_height(block, page_size),
+ )
+ )
+ positioned.sort(key=lambda item: (item[1][1], item[1][0], item[0]))
+
+ rows: list[list[tuple[int, BBox, float]]] = []
+ for item in positioned:
+ if rows:
+ current_row = rows[-1]
+ item_relation = relations.get(item[0])
+ shares_cross_lane_row = (
+ item_relation is not None
+ and item_relation.direction in {"above", "below"}
+ and all(
+ (
+ member_relation := relations.get(member[0])
+ ) is not None
+ and member_relation.direction == item_relation.direction
+ and _caption_blocks_use_distinct_regular_lanes(
+ blocks[member[0]],
+ blocks[item[0]],
+ )
+ for member in current_row
+ )
+ )
+ reference_top = statistics.median(
+ member[1][1]
+ for member in current_row
+ )
+ reference_height = statistics.median(
+ member[2]
+ for member in current_row
+ )
+ pair_height = statistics.median((reference_height, item[2]))
+ if (
+ shares_cross_lane_row
+ and abs(item[1][1] - reference_top)
+ <= _CROSS_LANE_CAPTION_ROW_TOP_TOLERANCE * pair_height
+ ):
+ current_row.append(item)
+ continue
+ rows.append([item])
+
+ output: list[int] = []
+ for row in rows:
+ row.sort(key=lambda item: (item[1][0], item[1][1], item[0]))
+ output.extend(item[0] for item in row)
+ output.extend(
+ sorted(
+ fallback,
+ key=lambda index: _annotation_local_sort_key(
+ index,
+ blocks,
+ page_size,
+ ),
+ )
+ )
+ return output
+
+
def _build_visual_annotation_regions(
assignments: dict[int, _AnnotationRelation],
blocks: list[dict[str, Any]],
@@ -896,25 +1143,21 @@ def _build_visual_annotation_regions(
[
*(
blocks[index]
- for index in sorted(
+ for index in _sort_annotation_indices_by_visual_rows(
leading,
- key=lambda value: _annotation_local_sort_key(
- value,
- blocks,
- page_size,
- ),
+ blocks,
+ page_size,
+ relations,
)
),
*_sort_visual_body_members(parent_indices, blocks, page_size),
*(
blocks[index]
- for index in sorted(
+ for index in _sort_annotation_indices_by_visual_rows(
trailing,
- key=lambda value: _annotation_local_sort_key(
- value,
- blocks,
- page_size,
- ),
+ blocks,
+ page_size,
+ relations,
)
),
*(
@@ -968,6 +1211,15 @@ def _classify_and_bind_visual_annotations(
)
is not None
}
+ cross_lane_assignments = _expand_cross_lane_caption_assignments(
+ blocks,
+ page_size,
+ parents,
+ candidates,
+ assignments,
+ )
+ candidates.update(dict.fromkeys(cross_lane_assignments, "caption"))
+ assignments.update(cross_lane_assignments)
consumed_indices = _merge_table_footnote_continuations(
blocks,
candidates,
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index e824faea..e83e39f2 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -121,14 +121,14 @@ def test_all_demo_pdfs_keep_expected_txt_block_inventory() -> None:
assert sum(inventory.values()) == 2591
assert inventory == Counter(
{
- "text": 900,
+ "text": 896,
"image": 530,
"paragraph_title": 214,
"header": 180,
"page_number": 179,
"footer": 177,
"table": 135,
- "caption": 120,
+ "caption": 124,
"equation": 50,
"footnote": 39,
"code": 33,
@@ -886,7 +886,7 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> N
def test_demo4_nct00083083_targeted_flash_regressions() -> None:
- """验证 demo4 的页眉脚注、续行、公式否决和参考文献分组。"""
+ """验证 demo4 的跨栏图注、页眉脚注、续行、公式否决和参考文献分组。"""
model_list = _native_model_list("demo4.pdf")
@@ -953,6 +953,43 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
str(introduction[0]["content"])
)
+ cross_lane_visual_regions = {
+ 4: [
+ [0.086, 0.073, 0.914, 0.282],
+ [0.086, 0.292, 0.486, 0.358],
+ [0.514, 0.293, 0.915, 0.359],
+ ],
+ 5: [
+ [0.086, 0.073, 0.914, 0.556],
+ [0.086, 0.566, 0.486, 0.683],
+ [0.514, 0.566, 0.915, 0.67],
+ ],
+ 6: [
+ [0.086, 0.073, 0.914, 0.344],
+ [0.086, 0.356, 0.486, 0.421],
+ [0.514, 0.355, 0.914, 0.408],
+ ],
+ 8: [
+ [0.086, 0.073, 0.914, 0.568],
+ [0.086, 0.579, 0.486, 0.695],
+ [0.514, 0.579, 0.914, 0.682],
+ ],
+ }
+ for page_number, expected_bboxes in cross_lane_visual_regions.items():
+ page = model_list[page_number - 1]
+ members = []
+ for bbox in expected_bboxes:
+ matches = [block for block in page if block["bbox"] == bbox]
+ assert len(matches) == 1
+ members.append(matches[0])
+ assert [block["type"] for block in members] == [
+ "image",
+ "caption",
+ "caption",
+ ]
+ first_index = page.index(members[0])
+ assert page[first_index : first_index + 3] == members
+
page4 = model_list[3]
caption_tail = _blocks_containing(page4, "included in the ACRIN 6668 study")
assert len(caption_tail) == 1
@@ -978,7 +1015,7 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
assert side_caption[0]["type"] == "caption"
assert side_caption[0]["bbox"][2] < side_image["bbox"][0]
assert page4.index(side_caption[0]) < page4.index(side_image)
- assert sum(block["type"] == "caption" for page in model_list for block in page) == 6
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 10
page2_table_caption = _blocks_containing(
model_list[1],
"Table 1 Patient demographics",
diff --git a/tests/unittest/test_flash_pdf_visual_annotations.py b/tests/unittest/test_flash_pdf_visual_annotations.py
index 7082dafa..66df5301 100644
--- a/tests/unittest/test_flash_pdf_visual_annotations.py
+++ b/tests/unittest/test_flash_pdf_visual_annotations.py
@@ -591,6 +591,231 @@ def test_caption_does_not_expand_hanging_indent_text() -> None:
assert regions == [[table, caption]]
[email protected]("visual_type", ["image", "table", "code"])
+def test_cross_lane_caption_companion_uses_geometry_for_all_visual_parents(
+ visual_type: str,
+) -> None:
+ """验证三类跨栏视觉父块均可仅凭空间补标另一栏标题。"""
+
+ parent = _visual_block(
+ (20.0, 20.0, 180.0, 80.0),
+ block_type=visual_type,
+ )
+ left_caption = _text_block(
+ "Figure 1: Spatial anchor",
+ (20.0, 90.5, 90.0, 120.5),
+ lane_interval=(20.0, 90.0),
+ )
+ right_companion = _text_block(
+ "plain continuation without a caption marker",
+ (110.0, 90.0, 180.0, 110.0),
+ lane_interval=(110.0, 180.0),
+ )
+ body = _text_block(
+ "ordinary body paragraph",
+ (20.0, 135.0, 90.0, 165.0),
+ line_height=13.0,
+ lane_interval=(20.0, 90.0),
+ )
+ blocks = [parent, left_caption, body, right_companion]
+
+ regions = _classify_with_text_block_merge(blocks)
+ ordered = pipeline._sort_blocks_with_visual_row_groups(
+ blocks,
+ _PAGE_SIZE,
+ visual_annotation_regions=regions,
+ )
+
+ assert left_caption["type"] == right_companion["type"] == "caption"
+ assert regions == [[parent, left_caption, right_companion]]
+ assert ordered == [parent, left_caption, right_companion, body]
+
+
+def test_cross_lane_caption_companion_above_parent_keeps_left_to_right_order() -> None:
+ """验证父块上方的双栏标题同样按左栏、右栏、主体展开。"""
+
+ table = _visual_block(
+ (20.0, 80.0, 180.0, 130.0),
+ block_type="table",
+ )
+ left_caption = _text_block(
+ "Table 1: Spatial anchor",
+ (20.0, 60.0, 90.0, 70.0),
+ lane_interval=(20.0, 90.0),
+ )
+ right_companion = _text_block(
+ "plain continuation",
+ (110.0, 59.5, 180.0, 69.5),
+ lane_interval=(110.0, 180.0),
+ )
+ blocks = [table, right_companion, left_caption]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert left_caption["type"] == right_companion["type"] == "caption"
+ assert regions == [[left_caption, right_companion, table]]
+
+
+def test_cross_lane_caption_companion_uses_rotated_local_coordinates() -> None:
+ """验证旋转页面在共同局部坐标中完成跨栏匹配和行内排序。"""
+
+ angle = 90
+ parent_local = (20.0, 20.0, 180.0, 80.0)
+ left_local = (20.0, 90.5, 90.0, 110.5)
+ right_local = (110.0, 90.0, 180.0, 110.0)
+ parent = _visual_block(
+ geometry._rotate_bbox_from_upright(parent_local, _PAGE_SIZE, angle),
+ )
+ left_caption = _text_block(
+ "Figure 1: Rotated anchor",
+ geometry._rotate_bbox_from_upright(left_local, _PAGE_SIZE, angle),
+ local_bbox=left_local,
+ lane_interval=(20.0, 90.0),
+ )
+ right_companion = _text_block(
+ "plain rotated continuation",
+ geometry._rotate_bbox_from_upright(
+ right_local,
+ _PAGE_SIZE,
+ angle,
+ ),
+ local_bbox=right_local,
+ lane_interval=(110.0, 180.0),
+ )
+ parent["angle"] = left_caption["angle"] = right_companion["angle"] = angle
+ blocks = [parent, right_companion, left_caption]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert left_caption["type"] == right_companion["type"] == "caption"
+ assert regions == [[parent, left_caption, right_companion]]
+
+
+ "case",
+ [
+ "no_anchor",
+ "same_lane",
+ "misaligned",
+ "line_height",
+ "font",
+ "missing_font",
+ "span_lane",
+ "narrow_parent",
+ "barrier",
+ "competing_parent",
+ ],
+)
+def test_cross_lane_caption_companion_rejects_unsafe_geometry(case: str) -> None:
+ """验证缺少任一关键空间或排版证据时不补标跨栏标题。"""
+
+ parent = _visual_block((20.0, 20.0, 180.0, 80.0))
+ anchor = _text_block(
+ "ordinary text" if case == "no_anchor" else "Figure 1: Spatial anchor",
+ (20.0, 90.5, 90.0, 110.5),
+ lane_interval=(20.0, 90.0),
+ )
+ companion_bbox = (
+ (110.0, 94.0, 180.0, 114.0)
+ if case == "misaligned"
+ else (110.0, 90.0, 180.0, 110.0)
+ )
+ companion = _text_block(
+ "plain continuation",
+ companion_bbox,
+ line_height=12.0 if case == "line_height" else 10.0,
+ lane_interval=(
+ (20.0, 90.0)
+ if case == "same_lane"
+ else (110.0, 180.0)
+ ),
+ lane_is_span=case == "span_lane",
+ font_signature=(
+ None
+ if case == "missing_font"
+ else ("OtherFont", 400)
+ if case == "font"
+ else ("TestFont", 400)
+ ),
+ )
+ extra_blocks: list[dict[str, object]] = []
+ if case == "narrow_parent":
+ parent["bbox"] = (20.0, 20.0, 90.0, 80.0)
+ elif case == "barrier":
+ extra_blocks.append(
+ _text_block(
+ "intervening body",
+ (110.0, 83.0, 180.0, 87.0),
+ lane_interval=(110.0, 180.0),
+ )
+ )
+ elif case == "competing_parent":
+ extra_blocks.append(
+ _visual_block((110.0, 82.0, 180.0, 86.0))
+ )
+ blocks = [parent, anchor, *extra_blocks, companion]
+
+ _classify_with_text_block_merge(blocks)
+
+ assert companion["type"] == "text"
+
+
+def test_cross_lane_caption_companion_rejects_multiple_spatial_peers() -> None:
+ """验证一个锚点同时命中多个栏带时保持全部同伴为正文。"""
+
+ parent = _visual_block((10.0, 20.0, 190.0, 80.0))
+ anchor = _text_block(
+ "Figure 1: Spatial anchor",
+ (10.0, 90.0, 60.0, 110.0),
+ lane_interval=(10.0, 60.0),
+ )
+ middle = _text_block(
+ "first possible continuation",
+ (75.0, 90.0, 125.0, 110.0),
+ lane_interval=(75.0, 125.0),
+ )
+ right = _text_block(
+ "second possible continuation",
+ (140.0, 90.0, 190.0, 110.0),
+ lane_interval=(140.0, 190.0),
+ )
+ blocks = [parent, anchor, middle, right]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert anchor["type"] == "caption"
+ assert middle["type"] == right["type"] == "text"
+ assert regions == [[parent, anchor]]
+
+
+def test_cross_lane_caption_companion_rejects_multiple_caption_anchors() -> None:
+ """验证一个同伴被多个标题锚点认领时维持正文分类。"""
+
+ parent = _visual_block((20.0, 20.0, 180.0, 80.0))
+ upper_anchor = _text_block(
+ "Figure 1: First spatial anchor",
+ (20.0, 90.0, 52.0, 110.0),
+ lane_interval=(20.0, 90.0),
+ )
+ lower_anchor = _text_block(
+ "Figure 2: Second spatial anchor",
+ (58.0, 90.0, 90.0, 110.0),
+ lane_interval=(20.0, 90.0),
+ )
+ companion = _text_block(
+ "plain shared continuation",
+ (110.0, 90.0, 180.0, 110.0),
+ lane_interval=(110.0, 180.0),
+ )
+ blocks = [parent, upper_anchor, lower_anchor, companion]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert upper_anchor["type"] == lower_anchor["type"] == "caption"
+ assert companion["type"] == "text"
+ assert regions == [[parent, upper_anchor, lower_anchor]]
+
+
def test_multi_panel_images_only_group_when_union_improves_coverage() -> None:
"""验证跨面板标题绑定图片并集,而单图标题不会无故吞并相邻图片。"""