Skip to content

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

feat: enhance table footnote handling by merging continuations and refining visual annotation classification

myhloli42e820cc6089
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 47bf97c9..4dd68f79 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -89,6 +89,7 @@ from .text_blocks import (
_merge_fragmented_header_blocks,
_merge_front_matter_column_blocks,
_merge_image_caption_text_blocks,
+ _merge_internal_text_block_group,
_merge_multiline_title_blocks,
_merge_repeated_compact_title_continuations,
)
@@ -552,6 +553,7 @@ def _finalize_prepared_page(
visual_annotation_regions = _classify_and_bind_visual_annotations(
absolute_blocks,
prepared.page_size,
+ merge_text_block_group=_merge_internal_text_block_group,
)
sorted_blocks = _sort_blocks_with_visual_row_groups(
absolute_blocks,
diff --git a/mineru/backend/flash/native_pdf/visual_annotations.py b/mineru/backend/flash/native_pdf/visual_annotations.py
index ccd23893..19717e35 100644
--- a/mineru/backend/flash/native_pdf/visual_annotations.py
+++ b/mineru/backend/flash/native_pdf/visual_annotations.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import re
import statistics
import unicodedata
+from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Literal
@@ -29,6 +30,13 @@ _FOOTNOTE_MAX_GAP_IN_LINE_HEIGHTS = 6.0
_MIN_PROJECTION_OVERLAP = 0.8
_MIN_ANNOTATION_COVERAGE = 0.65
_COMPONENT_COVERAGE_GAIN = 0.15
+_TABLE_FOOTNOTE_CONTINUATION_MAX_GAP = 1.5
+_TABLE_FOOTNOTE_FIRST_INDENT_MIN = 0.5
+_TABLE_FOOTNOTE_FIRST_INDENT_MAX = 2.0
+_TABLE_FOOTNOTE_FOLLOWING_INDENT_TOLERANCE = 0.5
+_TABLE_FOOTNOTE_LANE_TOLERANCE = 0.5
+_TABLE_FOOTNOTE_MIN_LINE_HEIGHT_RATIO = 0.75
+_TABLE_FOOTNOTE_MAX_LINE_HEIGHT_RATIO = 1.25
_IDENTIFIER_PATTERN = (
r"(?:"
@@ -67,6 +75,10 @@ _SUBFIGURE_REFERENCE_TAIL_RE = re.compile(
_Direction = Literal["above", "below", "left", "right"]
_AnnotationKind = Literal["caption", "footnote"]
+_TextBlockGroupMerger = Callable[
+ [list[dict[str, Any]], list[int]],
+ dict[str, Any],
+]
@dataclass(frozen=True)
@@ -190,6 +202,275 @@ def _collect_annotation_candidates(
return output
+def _coerce_lane_interval(value: object) -> tuple[float, float] | None:
+ """读取内部栏带区间,拒绝缺失、逆序或非数值元数据。"""
+
+ if not isinstance(value, (list, tuple)) or len(value) != 2:
+ return None
+ try:
+ start, end = float(value[0]), float(value[1])
+ except (TypeError, ValueError):
+ return None
+ if end <= start:
+ return None
+ return start, end
+
+
+def _block_first_local_row_bbox(
+ block: dict[str, Any],
+ page_size: tuple[float, float],
+ angle: int,
+) -> BBox | None:
+ """返回块在指定方向局部坐标中的首个文本行框。"""
+
+ rows = block.get("_local_line_bboxes")
+ local_rows = [bbox for row in rows if (bbox := _coerce_bbox(row)) is not None] if isinstance(rows, list) else []
+ if local_rows:
+ return min(local_rows, key=lambda bbox: (bbox[1], bbox[0]))
+ return _block_local_bbox(block, page_size, angle)
+
+
+def _blocks_share_table_footnote_lane(
+ anchor: dict[str, Any],
+ candidate: dict[str, Any],
+ line_height: float,
+) -> bool:
+ """要求表注锚点与续块来自同一内部栏带和 span 层级。"""
+
+ if anchor.get("_lane_is_span") != candidate.get("_lane_is_span"):
+ 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
+ tolerance = _TABLE_FOOTNOTE_LANE_TOLERANCE * line_height
+ return (
+ abs(anchor_interval[0] - candidate_interval[0]) <= tolerance
+ and abs(anchor_interval[1] - candidate_interval[1]) <= tolerance
+ )
+
+
+def _block_overlaps_table_footnote_lane(
+ block: dict[str, Any],
+ lane_interval: tuple[float, float],
+ page_size: tuple[float, float],
+ angle: int,
+) -> bool:
+ """判断任意块是否横穿表注栏带,用于保证收集过程不跨越障碍。"""
+
+ local_bbox = _block_local_bbox(block, page_size, angle)
+ if local_bbox is None:
+ return False
+ overlap = max(
+ 0.0,
+ min(local_bbox[2], lane_interval[1]) - max(local_bbox[0], lane_interval[0]),
+ )
+ shorter_width = max(
+ 0.1,
+ min(
+ local_bbox[2] - local_bbox[0],
+ lane_interval[1] - lane_interval[0],
+ ),
+ )
+ return overlap / shorter_width >= 0.5
+
+
+def _table_footnote_fonts_are_compatible(
+ previous: dict[str, Any],
+ candidate: dict[str, Any],
+) -> bool:
+ """仅在两侧都有可靠字体信息且完全不相交时拒绝续块。"""
+
+ previous_fonts = previous.get("_font_signatures")
+ candidate_fonts = candidate.get("_font_signatures")
+ return not (
+ isinstance(previous_fonts, set)
+ and isinstance(candidate_fonts, set)
+ and previous_fonts
+ and candidate_fonts
+ and previous_fonts.isdisjoint(candidate_fonts)
+ )
+
+
+def _table_footnote_candidate_fits_parent(
+ candidate_bbox: BBox,
+ parent_bbox: BBox,
+ line_height: float,
+) -> bool:
+ """要求续块位于父表格下方并保持既有横向投影覆盖标准。"""
+
+ if _bbox_center_y(candidate_bbox) < _bbox_center_y(parent_bbox):
+ return False
+ projection_overlap, annotation_coverage, _center_offset = _axis_overlap_metrics(
+ candidate_bbox,
+ parent_bbox,
+ axis="x",
+ float_margin=line_height,
+ )
+ return projection_overlap >= _MIN_PROJECTION_OVERLAP and annotation_coverage >= _MIN_ANNOTATION_COVERAGE
+
+
+def _table_footnote_continuation_is_compatible(
+ anchor: dict[str, Any],
+ previous: dict[str, Any],
+ candidate: dict[str, Any],
+ parent_bbox: BBox,
+ page_size: tuple[float, float],
+ angle: int,
+ continuation_left: float | None,
+) -> tuple[bool, float | None]:
+ """按栏带、字体、行高、净空和悬挂缩进确认单个表注续块。"""
+
+ previous_bbox = _block_local_bbox(previous, page_size, angle)
+ candidate_bbox = _block_local_bbox(candidate, page_size, 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 previous_bbox is None or candidate_bbox is None or anchor_first_row is None or candidate_first_row is None:
+ return False, continuation_left
+
+ previous_height = _block_median_line_height(previous, page_size)
+ candidate_height = _block_median_line_height(candidate, page_size)
+ if previous_height <= 0 or candidate_height <= 0:
+ return False, continuation_left
+ height_ratio = candidate_height / previous_height
+ pair_height = statistics.median((previous_height, candidate_height))
+ vertical_gap = max(0.0, candidate_bbox[1] - previous_bbox[3])
+ if (
+ not _TABLE_FOOTNOTE_MIN_LINE_HEIGHT_RATIO <= height_ratio <= _TABLE_FOOTNOTE_MAX_LINE_HEIGHT_RATIO
+ or vertical_gap > _TABLE_FOOTNOTE_CONTINUATION_MAX_GAP * pair_height
+ or not _blocks_share_table_footnote_lane(anchor, candidate, pair_height)
+ or not _table_footnote_fonts_are_compatible(previous, candidate)
+ or not _table_footnote_candidate_fits_parent(
+ candidate_bbox,
+ parent_bbox,
+ pair_height,
+ )
+ ):
+ return False, continuation_left
+
+ candidate_left = candidate_first_row[0]
+ if continuation_left is None:
+ indent = candidate_left - anchor_first_row[0]
+ if not (_TABLE_FOOTNOTE_FIRST_INDENT_MIN * pair_height <= indent <= _TABLE_FOOTNOTE_FIRST_INDENT_MAX * pair_height):
+ return False, continuation_left
+ return True, candidate_left
+ if abs(candidate_left - continuation_left) > _TABLE_FOOTNOTE_FOLLOWING_INDENT_TOLERANCE * pair_height:
+ return False, continuation_left
+ return True, continuation_left
+
+
+def _collect_table_footnote_continuation_indices(
+ anchor_index: int,
+ relation: _AnnotationRelation,
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ annotation_indices: set[int],
+ consumed_indices: set[int],
+) -> list[int]:
+ """从表注锚点向下连续收集同栏悬挂缩进文本,不跨越首个障碍。"""
+
+ anchor = blocks[anchor_index]
+ angle = relation.parent.angle
+ anchor_bbox = _block_local_bbox(anchor, page_size, angle)
+ lane_interval = _coerce_lane_interval(anchor.get("_lane_interval"))
+ if anchor_bbox is None or lane_interval is None:
+ return []
+
+ ordered_indices = sorted(
+ (
+ index
+ for index, block in enumerate(blocks)
+ if index != anchor_index
+ and index not in relation.parent.member_indices
+ and index not in consumed_indices
+ and _block_angle(block) == angle
+ and (local_bbox := _block_local_bbox(block, page_size, angle)) is not None
+ and _bbox_center_y(local_bbox) > _bbox_center_y(anchor_bbox)
+ and _block_overlaps_table_footnote_lane(
+ block,
+ lane_interval,
+ page_size,
+ angle,
+ )
+ ),
+ key=lambda index: (
+ _block_local_bbox(blocks[index], page_size, angle)[1],
+ _block_local_bbox(blocks[index], page_size, angle)[0],
+ index,
+ ),
+ )
+
+ output: list[int] = []
+ previous = anchor
+ continuation_left: float | None = None
+ for index in ordered_indices:
+ candidate = blocks[index]
+ if index in annotation_indices or candidate.get("type") != "text":
+ break
+ compatible, continuation_left = _table_footnote_continuation_is_compatible(
+ anchor,
+ previous,
+ candidate,
+ relation.parent.local_bbox,
+ page_size,
+ angle,
+ continuation_left,
+ )
+ if not compatible:
+ break
+ output.append(index)
+ previous = candidate
+ return output
+
+
+def _merge_table_footnote_continuations(
+ blocks: list[dict[str, Any]],
+ candidates: dict[int, _AnnotationKind],
+ assignments: dict[int, _AnnotationRelation],
+ page_size: tuple[float, float],
+ merge_text_block_group: _TextBlockGroupMerger | None,
+) -> set[int]:
+ """合并已绑定单表格的强标记脚注及其页内续块,并返回被消费索引。"""
+
+ if merge_text_block_group is None:
+ return set()
+ annotation_indices = set(candidates)
+ consumed_indices: set[int] = set()
+ for anchor_index in sorted(
+ assignments,
+ key=lambda index: _annotation_local_sort_key(index, blocks, page_size),
+ ):
+ relation = assignments[anchor_index]
+ parent_indices = relation.parent.member_indices
+ anchor = blocks[anchor_index]
+ if (
+ candidates.get(anchor_index) != "footnote"
+ or anchor.get("type") != "text"
+ or not isinstance(anchor.get("content"), str)
+ or not _is_strong_footnote_text(str(anchor["content"]))
+ or relation.direction != "below"
+ or len(parent_indices) != 1
+ or blocks[parent_indices[0]].get("type") != "table"
+ ):
+ continue
+ continuation_indices = _collect_table_footnote_continuation_indices(
+ anchor_index,
+ relation,
+ blocks,
+ page_size,
+ annotation_indices,
+ consumed_indices,
+ )
+ if not continuation_indices:
+ continue
+ blocks[anchor_index] = merge_text_block_group(
+ blocks,
+ [anchor_index, *continuation_indices],
+ )
+ consumed_indices.update(continuation_indices)
+ return consumed_indices
+
+
def _axis_overlap_metrics(
annotation_bbox: BBox,
parent_bbox: BBox,
@@ -654,6 +935,8 @@ def _build_visual_annotation_regions(
def _classify_and_bind_visual_annotations(
blocks: list[dict[str, Any]],
page_size: tuple[float, float],
+ *,
+ merge_text_block_group: _TextBlockGroupMerger | None = None,
) -> list[list[dict[str, Any]]]:
"""重分类强规则独立注释,并返回供全局 XYCut++ 使用的有序视觉区域。"""
@@ -684,7 +967,21 @@ def _classify_and_bind_visual_annotations(
)
is not None
}
+ consumed_indices = _merge_table_footnote_continuations(
+ blocks,
+ candidates,
+ assignments,
+ page_size,
+ merge_text_block_group,
+ )
for index, relation in assignments.items():
blocks[index]["type"] = candidates[index]
blocks[index]["_visual_annotation_direction"] = relation.direction
- return _build_visual_annotation_regions(assignments, blocks, page_size)
+ regions = _build_visual_annotation_regions(assignments, blocks, page_size)
+ if consumed_indices:
+ blocks[:] = [
+ block
+ for index, block in enumerate(blocks)
+ if index not in consumed_indices
+ ]
+ return regions
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index ed8c6a6a..ea8ab073 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -972,6 +972,47 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:
assert len(page77_note) == 1
assert page77_note[0]["type"] == "footnote"
+ merged_table_footnotes = {
+ 6: (
+ [0.086, 0.412, 0.522, 0.567],
+ "注:(1)指主要生产单元所采用的工艺名称。",
+ "(7)指设计年生产时间。",
+ ),
+ 7: (
+ [0.086, 0.552, 0.572, 0.652],
+ "注:(1)指材料种类,选填“原料”或“辅料”。",
+ "(4)指有毒有害物质或元素",
+ ),
+ 31: (
+ [0.086, 0.535, 0.36, 0.675],
+ "注:(1)指主要生产设施。",
+ "(4)指有组织排放或无组织排放。",
+ ),
+ }
+ for page_number, (expected_bbox, prefix, tail_probe) in merged_table_footnotes.items():
+ page = model_list[page_number - 1]
+ footnotes = [block for block in page if block["type"] == "footnote"]
+ assert len(footnotes) == 1
+ footnote = footnotes[0]
+ assert footnote["bbox"] == expected_bbox
+ assert str(footnote["content"]).startswith(prefix)
+ assert _blocks_containing(page, tail_probe) == [footnote]
+ assert not _blocks_containing(
+ [block for block in page if block["type"] == "text"],
+ tail_probe,
+ )
+
+ magic_model = MagicModel(page, 1000, 1000)
+ table_blocks = magic_model.get_table_blocks()
+ assert len(table_blocks) == 1
+ assert [child.type for child in table_blocks[0].blocks] == [
+ "table_body",
+ "table_footnote",
+ ]
+ table_footnote = table_blocks[0].blocks[1]
+ assert table_footnote.bbox == tuple(round(value * 1000) for value in expected_bbox)
+ assert _normalized_content_probe(tail_probe) in _normalized_content_probe(str(table_footnote.content))
+
expected_footnote_pages = {6, 7, 31, 36, 39, 43, 49, 53, 55, 57, 58, 59, 77}
assert {
page_number
@@ -992,12 +1033,21 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:
assert len(page62_note) == len(page86_table20) == 1
assert page62_note[0]["type"] == page86_table20[0]["type"] == "text"
- page6_magic_model = MagicModel(model_list[5], 1000, 1000)
- page6_table = page6_magic_model.get_table_blocks()[0]
- assert [child.type for child in page6_table.blocks] == [
- "table_body",
- "table_footnote",
+ page36_footnotes = [block for block in model_list[35] if block["type"] == "footnote"]
+ assert [block["bbox"] for block in page36_footnotes] == [[0.086, 0.587, 0.404, 0.654]]
+ page57_footnotes = [block for block in model_list[56] if block["type"] == "footnote"]
+ page58_continuation = [
+ block
+ for block in _blocks_containing(
+ model_list[57],
+ "可通过排污许可证管理信息平台中的GIS系统点选后自动生成经纬度",
+ )
+ if block["type"] == "text"
]
+ assert len(page57_footnotes) == len(page58_continuation) == 1
+ assert page57_footnotes[0]["type"] == "footnote"
+ assert page58_continuation[0]["type"] == "text"
+ assert page58_continuation[0]["bbox"] == [0.086, 0.155, 0.803, 0.221]
page9 = model_list[8]
page_number_block = next(
diff --git a/tests/unittest/test_flash_pdf_visual_annotations.py b/tests/unittest/test_flash_pdf_visual_annotations.py
index 8972e2f0..3ab14d09 100644
--- a/tests/unittest/test_flash_pdf_visual_annotations.py
+++ b/tests/unittest/test_flash_pdf_visual_annotations.py
@@ -2,7 +2,12 @@ from __future__ import annotations
import pytest
-from mineru.backend.flash.native_pdf import pipeline, visual_annotations
+from mineru.backend.flash.native_pdf import (
+ geometry,
+ pipeline,
+ text_blocks,
+ visual_annotations,
+)
_PAGE_SIZE = (200.0, 200.0)
@@ -14,18 +19,26 @@ def _text_block(
*,
block_type: str = "text",
row_id: int | None = None,
+ line_height: float = 10.0,
+ local_bbox: tuple[float, float, float, float] | None = None,
+ lane_interval: tuple[float, float] | None = None,
+ lane_is_span: bool = False,
+ font_signature: tuple[str, int] | None = ("TestFont", 400),
) -> dict[str, object]:
- """构造带稳定十点行高的独立文本测试块。"""
+ """构造带稳定行框、字体和栏带元数据的独立文本测试块。"""
return {
"type": block_type,
"bbox": bbox,
"angle": 0,
"content": content,
- "_line_heights": [10.0],
+ "_line_heights": [line_height],
+ "_local_line_bboxes": [local_bbox or bbox],
+ "_font_signatures": {font_signature} if font_signature else set(),
+ "_visual_row_ids": {row_id} if row_id is not None else set(),
"_single_run_row_id": row_id,
- "_lane_interval": (bbox[0], bbox[2]),
- "_lane_is_span": False,
+ "_lane_interval": lane_interval or (bbox[0], bbox[2]),
+ "_lane_is_span": lane_is_span,
}
@@ -44,6 +57,18 @@ def _visual_block(
}
+def _classify_with_text_block_merge(
+ blocks: list[dict[str, object]],
+) -> list[list[dict[str, object]]]:
+ """通过 pipeline 使用的文本合并回调运行视觉注释分类。"""
+
+ return visual_annotations._classify_and_bind_visual_annotations(
+ blocks,
+ _PAGE_SIZE,
+ merge_text_block_group=text_blocks._merge_internal_text_block_group,
+ )
+
+
@pytest.mark.parametrize(
"content",
[
@@ -139,10 +164,7 @@ def test_caption_binds_on_all_four_sides(
image = _visual_block((40.0, 40.0, 80.0, 80.0))
blocks = [caption, image]
- regions = visual_annotations._classify_and_bind_visual_annotations(
- blocks,
- _PAGE_SIZE,
- )
+ regions = _classify_with_text_block_merge(blocks)
assert caption["type"] == "caption"
assert len(regions) == 1
@@ -229,6 +251,316 @@ def test_existing_visual_footnote_binds_without_content_marker() -> None:
assert [block["type"] for block in regions[0]] == ["image", "footnote"]
+def test_table_footnote_merges_multiple_hanging_indent_continuations() -> None:
+ """验证表注强标记会吸收多个同栏悬挂缩进续块并保留内部元数据。"""
+
+ table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")
+ anchor = _text_block(
+ "注:(1)首项。",
+ (20.0, 70.0, 100.0, 80.0),
+ row_id=1,
+ lane_interval=(20.0, 160.0),
+ )
+ continuation1 = _text_block(
+ "(2)续项。",
+ (30.0, 85.0, 130.0, 95.0),
+ row_id=2,
+ lane_interval=(20.0, 160.0),
+ )
+ continuation2 = _text_block(
+ "(3)末项。",
+ (30.0, 100.0, 150.0, 110.0),
+ row_id=3,
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, anchor, continuation1, continuation2]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert len(blocks) == 2
+ merged = blocks[1]
+ assert merged["type"] == "footnote"
+ assert merged["content"] == "注:(1)首项。(2)续项。(3)末项。"
+ assert merged["bbox"] == (20.0, 70.0, 150.0, 110.0)
+ assert merged["_local_line_bboxes"] == [
+ (20.0, 70.0, 100.0, 80.0),
+ (30.0, 85.0, 130.0, 95.0),
+ (30.0, 100.0, 150.0, 110.0),
+ ]
+ assert merged["_line_heights"] == [10.0, 10.0, 10.0]
+ assert merged["_font_signatures"] == {("TestFont", 400)}
+ assert merged["_visual_row_ids"] == {1, 2, 3}
+ assert merged["_single_run_row_id"] is None
+ assert regions == [[table, merged]]
+
+
+ ("gap", "should_merge"),
+ [(13.5, True), (13.6, False)],
+)
+def test_table_footnote_uses_pair_median_gap_limit(
+ gap: float,
+ should_merge: bool,
+) -> None:
+ """验证 page 31 型净空按配对中位行高的一点五倍闭区间判定。"""
+
+ table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")
+ anchor = _text_block(
+ "注:(1)首项。",
+ (20.0, 70.0, 100.0, 78.0),
+ line_height=8.0,
+ lane_interval=(20.0, 160.0),
+ )
+ continuation = _text_block(
+ "(2)续项。",
+ (30.0, 78.0 + gap, 130.0, 88.0 + gap),
+ line_height=10.0,
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, anchor, continuation]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ if should_merge:
+ assert len(blocks) == 2
+ assert blocks[1]["content"] == "注:(1)首项。(2)续项。"
+ assert regions == [[table, blocks[1]]]
+ else:
+ assert blocks == [table, anchor, continuation]
+ assert regions == [[table, anchor]]
+
+
+ "candidate",
+ [
+ _text_block(
+ "(2)间距过大。",
+ (30.0, 95.1, 130.0, 105.1),
+ lane_interval=(20.0, 160.0),
+ ),
+ _text_block(
+ "(2)没有悬挂缩进。",
+ (20.0, 85.0, 130.0, 95.0),
+ lane_interval=(20.0, 160.0),
+ ),
+ _text_block(
+ "(2)字体不同。",
+ (30.0, 85.0, 130.0, 95.0),
+ lane_interval=(20.0, 160.0),
+ font_signature=("OtherFont", 400),
+ ),
+ _text_block(
+ "(2)行高不同。",
+ (30.0, 85.0, 130.0, 95.0),
+ line_height=13.4,
+ lane_interval=(20.0, 160.0),
+ ),
+ _text_block(
+ "(2)栏带不同。",
+ (30.0, 85.0, 130.0, 95.0),
+ lane_interval=(30.0, 170.0),
+ ),
+ _text_block(
+ "(2)跨栏属性不同。",
+ (30.0, 85.0, 130.0, 95.0),
+ lane_interval=(20.0, 160.0),
+ lane_is_span=True,
+ ),
+ ],
+)
+def test_table_footnote_rejects_incompatible_continuation(
+ candidate: dict[str, object],
+) -> None:
+ """验证间距、缩进、字体、行高或栏带突变均终止表注聚合。"""
+
+ table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")
+ anchor = _text_block(
+ "注:(1)首项。",
+ (20.0, 70.0, 100.0, 80.0),
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, anchor, candidate]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert len(blocks) == 3
+ assert anchor["type"] == "footnote"
+ assert candidate["type"] == "text"
+ assert regions == [[table, anchor]]
+
+
[email protected]("barrier_type", ["paragraph_title", "image"])
+def test_table_footnote_does_not_skip_semantic_or_visual_barrier(
+ barrier_type: str,
+) -> None:
+ """验证语义块或视觉块横隔栏带时,不会越过它吸收后续文本。"""
+
+ table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")
+ anchor = _text_block(
+ "注:(1)首项。",
+ (20.0, 70.0, 100.0, 80.0),
+ lane_interval=(20.0, 160.0),
+ )
+ barrier = (
+ _text_block(
+ "正文标题",
+ (20.0, 85.0, 130.0, 95.0),
+ block_type=barrier_type,
+ lane_interval=(20.0, 160.0),
+ )
+ if barrier_type != "image"
+ else _visual_block((20.0, 85.0, 160.0, 95.0))
+ )
+ continuation = _text_block(
+ "(2)不得吸收。",
+ (30.0, 100.0, 130.0, 110.0),
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, anchor, barrier, continuation]
+
+ _classify_with_text_block_merge(blocks)
+
+ assert len(blocks) == 4
+ assert anchor["type"] == "footnote"
+ assert continuation["type"] == "text"
+
+
+def test_table_footnote_stops_before_second_strong_annotation() -> None:
+ """验证第二个强标记注释保持独立,不会成为前一个表注的续块。"""
+
+ table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")
+ first = _text_block(
+ "注:(1)首项。",
+ (20.0, 70.0, 100.0, 80.0),
+ lane_interval=(20.0, 160.0),
+ )
+ second = _text_block(
+ "备注:另一条注释。",
+ (20.0, 85.0, 130.0, 95.0),
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, first, second]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert [block["type"] for block in blocks] == ["table", "footnote", "footnote"]
+ assert regions == [[table, first, second]]
+
+
+def test_table_footnote_continuation_uses_rotated_local_coordinates() -> None:
+ """验证九十度表注在共同局部坐标中按相同缩进规则完成合并。"""
+
+ angle = 90
+ table_local = (20.0, 20.0, 180.0, 60.0)
+ anchor_local = (20.0, 70.0, 100.0, 80.0)
+ continuation_local = (30.0, 85.0, 150.0, 95.0)
+ table = _visual_block(
+ geometry._rotate_bbox_from_upright(table_local, _PAGE_SIZE, angle),
+ block_type="table",
+ )
+ anchor = _text_block(
+ "注:(1)首项。",
+ geometry._rotate_bbox_from_upright(anchor_local, _PAGE_SIZE, angle),
+ local_bbox=anchor_local,
+ lane_interval=(20.0, 160.0),
+ )
+ continuation = _text_block(
+ "(2)续项。",
+ geometry._rotate_bbox_from_upright(
+ continuation_local,
+ _PAGE_SIZE,
+ angle,
+ ),
+ local_bbox=continuation_local,
+ lane_interval=(20.0, 160.0),
+ )
+ table["angle"] = anchor["angle"] = continuation["angle"] = angle
+ blocks = [table, anchor, continuation]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert len(blocks) == 2
+ merged_local_bbox = visual_annotations._block_local_bbox(
+ blocks[1],
+ _PAGE_SIZE,
+ angle,
+ )
+ assert merged_local_bbox == pytest.approx((20.0, 70.0, 150.0, 95.0))
+ assert regions == [[table, blocks[1]]]
+
+
[email protected]("visual_type", ["image", "code"])
+def test_non_table_or_existing_footnote_does_not_expand_continuations(
+ visual_type: str,
+) -> None:
+ """验证图片、代码脚注和既有 footnote 不进入表格强标记聚合范围。"""
+
+ image = _visual_block(
+ (20.0, 20.0, 180.0, 60.0),
+ block_type=visual_type,
+ )
+ image_note = _text_block(
+ "注:(1)图片注释。",
+ (20.0, 70.0, 100.0, 80.0),
+ lane_interval=(20.0, 160.0),
+ )
+ image_continuation = _text_block(
+ "(2)图片续块。",
+ (30.0, 85.0, 130.0, 95.0),
+ lane_interval=(20.0, 160.0),
+ )
+ image_blocks = [image, image_note, image_continuation]
+
+ _classify_with_text_block_merge(image_blocks)
+
+ table = _visual_block((20.0, 110.0, 180.0, 140.0), block_type="table")
+ existing_note = _text_block(
+ "既有脚注",
+ (20.0, 150.0, 100.0, 160.0),
+ block_type="footnote",
+ lane_interval=(20.0, 160.0),
+ )
+ existing_continuation = _text_block(
+ "缩进正文",
+ (30.0, 165.0, 130.0, 175.0),
+ lane_interval=(20.0, 160.0),
+ )
+ table_blocks = [table, existing_note, existing_continuation]
+
+ _classify_with_text_block_merge(table_blocks)
+
+ assert len(image_blocks) == 3
+ assert image_note["type"] == "footnote"
+ assert image_continuation["type"] == "text"
+ assert len(table_blocks) == 3
+ assert existing_note["type"] == "footnote"
+ assert existing_continuation["type"] == "text"
+
+
+def test_caption_does_not_expand_hanging_indent_text() -> None:
+ """验证表格 caption 即使后接悬挂缩进正文也不会触发表注聚合。"""
+
+ table = _visual_block((20.0, 20.0, 180.0, 60.0), block_type="table")
+ caption = _text_block(
+ "表1:测试表格",
+ (20.0, 70.0, 100.0, 80.0),
+ lane_interval=(20.0, 160.0),
+ )
+ continuation = _text_block(
+ "缩进正文",
+ (30.0, 85.0, 130.0, 95.0),
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, caption, continuation]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert blocks == [table, caption, continuation]
+ assert caption["type"] == "caption"
+ assert continuation["type"] == "text"
+ assert regions == [[table, caption]]
+
+
def test_multi_panel_images_only_group_when_union_improves_coverage() -> None:
"""验证跨面板标题绑定图片并集,而单图标题不会无故吞并相邻图片。"""