Skip to content

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

feat: implement visual annotation classification and binding for captions and footnotes

myhloli9a964ceb6370
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 5b109988..47bf97c9 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -92,6 +92,7 @@ from .text_blocks import (
_merge_multiline_title_blocks,
_merge_repeated_compact_title_continuations,
)
+from .visual_annotations import _classify_and_bind_visual_annotations
_TEXT_SEMANTIC_TYPES = {
@@ -100,6 +101,7 @@ _TEXT_SEMANTIC_TYPES = {
"header",
"footer",
"page_number",
+ "caption",
"footnote",
"page_footnote",
"aside_text",
@@ -547,7 +549,15 @@ def _finalize_prepared_page(
absolute_blocks = (
prepared.fixed_blocks + formula_blocks + index_blocks + text_blocks
)
- sorted_blocks = _sort_blocks_with_visual_row_groups(absolute_blocks, prepared.page_size)
+ visual_annotation_regions = _classify_and_bind_visual_annotations(
+ absolute_blocks,
+ prepared.page_size,
+ )
+ sorted_blocks = _sort_blocks_with_visual_row_groups(
+ absolute_blocks,
+ prepared.page_size,
+ visual_annotation_regions=visual_annotation_regions,
+ )
return [
normalized
for block in sorted_blocks
@@ -566,8 +576,10 @@ def _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:
def _sort_blocks_with_visual_row_groups(
blocks: list[dict[str, Any]],
page_size: tuple[float, float],
+ *,
+ visual_annotation_regions: list[list[dict[str, Any]]] | None = None,
) -> list[dict[str, Any]]:
- """把同一粗行拆出的单行 block 包装成虚拟项排序,再按局部 x 顺序展开。"""
+ """把视觉注释区域和拆分粗行包装成虚拟项排序,再按各自局部顺序展开。"""
top_marginals: list[dict[str, Any]] = []
bottom_marginals: list[dict[str, Any]] = []
@@ -587,7 +599,29 @@ def _sort_blocks_with_visual_row_groups(
else:
body_blocks.append(block)
- inline_grouped_indices = _collect_inline_image_text_groups(body_blocks)
+ body_index_by_identity = {
+ id(block): index for index, block in enumerate(body_blocks)
+ }
+ region_groups: list[list[dict[str, Any]]] = []
+ region_consumed_indices: set[int] = set()
+ for region in visual_annotation_regions or []:
+ indices = [
+ body_index_by_identity[id(member)]
+ for member in region
+ if id(member) in body_index_by_identity
+ ]
+ if len(indices) < 2 or any(index in region_consumed_indices for index in indices):
+ continue
+ members = [body_blocks[index] for index in indices]
+ for member in members:
+ member["_visual_annotation_region_member"] = True
+ region_groups.append(members)
+ region_consumed_indices.update(indices)
+
+ inline_grouped_indices = _collect_inline_image_text_groups(
+ body_blocks,
+ excluded_indices=region_consumed_indices,
+ )
inline_consumed_indices = {
index
for indices in inline_grouped_indices.values()
@@ -595,14 +629,25 @@ def _sort_blocks_with_visual_row_groups(
}
grouped_indices: dict[int, list[int]] = {}
for index, block in enumerate(body_blocks):
- if index in inline_consumed_indices:
+ if index in region_consumed_indices or 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: list[dict[str, Any]] = []
- consumed_indices: set[int] = set(inline_consumed_indices)
+ consumed_indices: set[int] = set(region_consumed_indices | inline_consumed_indices)
+ for members in region_groups:
+ virtual_groups.append(
+ {
+ "type": "_xycut_visual_annotation_region",
+ "bbox": _bbox_union_many([member["bbox"] for member in members]),
+ "angle": members[0].get("angle", 0),
+ "content": "",
+ "_members": members,
+ "_visual_annotation_region": True,
+ }
+ )
for row_id, indices in inline_grouped_indices.items():
members = [body_blocks[index] for index in indices]
virtual_groups.append(
@@ -642,6 +687,9 @@ def _sort_blocks_with_visual_row_groups(
if not isinstance(members, list):
output.append(payload)
continue
+ if payload.get("_visual_annotation_region") is True:
+ output.extend(members)
+ continue
if isinstance(payload.get("_inline_visual_row_id"), int):
members.sort(
key=lambda member: _inline_visual_group_member_sort_key(
@@ -669,11 +717,16 @@ def _sort_blocks_with_visual_row_groups(
def _collect_inline_image_text_groups(
body_blocks: list[dict[str, Any]],
+ *,
+ excluded_indices: set[int] | None = None,
) -> dict[int, list[int]]:
"""把复合图片与包含同一首行的正文块组成专用排序组。"""
+ excluded_indices = excluded_indices or set()
image_indices_by_row: dict[int, list[int]] = {}
for index, block in enumerate(body_blocks):
+ if index in excluded_indices:
+ continue
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)
@@ -684,7 +737,8 @@ def _collect_inline_image_text_groups(
text_indices = [
index
for index, block in enumerate(body_blocks)
- if index not in consumed_text_indices
+ if index not in excluded_indices
+ and 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"]
@@ -805,6 +859,10 @@ def _overlapping_lane_pair_is_inverted(
) -> bool:
"""判断相邻块是否属于同一内部栏带且视觉中心顺序与当前结果相反。"""
+ if first.get("_visual_annotation_region_member") or second.get(
+ "_visual_annotation_region_member"
+ ):
+ return False
first_interval = first.get("_lane_interval")
second_interval = second.get("_lane_interval")
if (
diff --git a/mineru/backend/flash/native_pdf/visual_annotations.py b/mineru/backend/flash/native_pdf/visual_annotations.py
new file mode 100644
index 00000000..ccd23893
--- /dev/null
+++ b/mineru/backend/flash/native_pdf/visual_annotations.py
@@ -0,0 +1,690 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""识别独立视觉块的强规则 caption/footnote,并构造局部阅读区域。"""
+
+from __future__ import annotations
+
+import re
+import statistics
+import unicodedata
+from dataclasses import dataclass
+from typing import Any, Literal
+
+
+from mineru.backend.utils.xycut_pp_sorter import sort_entries
+from mineru.types import BBox
+
+from .geometry import (
+ _bbox_center_x,
+ _bbox_center_y,
+ _bbox_union_many,
+ _coerce_bbox,
+ _rotate_bbox_to_upright,
+)
+
+
+_VISUAL_BLOCK_TYPES = {"image", "table", "code"}
+_CAPTION_MAX_GAP_IN_LINE_HEIGHTS = 2.5
+_FOOTNOTE_MAX_GAP_IN_LINE_HEIGHTS = 6.0
+_MIN_PROJECTION_OVERLAP = 0.8
+_MIN_ANNOTATION_COVERAGE = 0.65
+_COMPONENT_COVERAGE_GAIN = 0.15
+
+_IDENTIFIER_PATTERN = (
+ r"(?:"
+ r"[A-Z]?\d+(?:\s*[-./–—]\s*[A-Z]?\d+)*[A-Z]?"
+ r"|[IVXLCDM]+"
+ r"|[零〇一二三四五六七八九十百千两]+"
+ r")"
+)
+_ENGLISH_CAPTION_RE = re.compile(
+ rf"^\s*(?:fig(?:ure)?|tab(?:le)?|alg(?:orithm)?|listing|chart|scheme)\.?(?:\s*)"
+ rf"(?P<identifier>{_IDENTIFIER_PATTERN})(?P<tail>.*)$",
+ re.IGNORECASE | re.DOTALL,
+)
+_CHINESE_CAPTION_RE = re.compile(
+ rf"^\s*(?:程序清单|图表|表格|算法|图|表)\s*"
+ rf"(?P<identifier>{_IDENTIFIER_PATTERN})(?P<tail>.*)$",
+ re.IGNORECASE | re.DOTALL,
+)
+_FOOTNOTE_RE = re.compile(
+ r"^\s*(?:source(?:s|\(s\))?|data\s+source|note(?:s|\(s\))?"
+ r"|资料来源|数据来源|来源|注|备注)\s*[::]\s*\S",
+ re.IGNORECASE | re.DOTALL,
+)
+_ENGLISH_REFERENCE_TAIL_RE = re.compile(
+ r"^(?:[,;]|and\b|or\b|&|shows?\b|illustrates?\b|presents?\b|depicts?\b|"
+ r"demonstrates?\b|lists?\b|summari[sz]es?\b|reports?\b|compares?\b|"
+ r"provides?\b|is\b|are\b|was\b|were\b|has\b|have\b|can\b)",
+ re.IGNORECASE,
+)
+_CHINESE_REFERENCE_TAIL_RE = re.compile(
+ r"^(?:[,;,;、]|和|及|与|为|是|展示|显示|给出|说明|列出|分别|可见|表明|描述|呈现|汇总|所示|中(?:的|为)?)",
+)
+_SUBFIGURE_REFERENCE_TAIL_RE = re.compile(
+ r"^[((][^))]+[))]\s*(?:[、,,]|和|及|与)",
+)
+
+_Direction = Literal["above", "below", "left", "right"]
+_AnnotationKind = Literal["caption", "footnote"]
+
+
+@dataclass(frozen=True)
+class _VisualParent:
+ """记录单个视觉块或只用于关联的多图片组件。"""
+
+ member_indices: tuple[int, ...]
+ angle: int
+ local_bbox: BBox
+
+
+@dataclass(frozen=True)
+class _AnnotationRelation:
+ """记录注释与候选父块之间的方向和归一化几何代价。"""
+
+ parent: _VisualParent
+ direction: _Direction
+ normalized_gap: float
+ projection_overlap: float
+ annotation_coverage: float
+ center_offset: float
+
+
+def _normalize_annotation_text(text: str) -> str:
+ """统一全角字符和兼容罗马数字,保留原文仅供规则判断。"""
+
+ return unicodedata.normalize("NFKC", text).strip()
+
+
+def _caption_tail_is_reference(tail: str) -> bool:
+ """排除编号后紧接叙述谓语、并列编号或正文连接词的引用句。"""
+
+ stripped = tail.lstrip()
+ if not stripped:
+ return False
+ if _SUBFIGURE_REFERENCE_TAIL_RE.match(stripped):
+ return True
+ if stripped[0] in ".::-–—()[]()":
+ return False
+ if _ENGLISH_REFERENCE_TAIL_RE.match(stripped) or _CHINESE_REFERENCE_TAIL_RE.match(stripped):
+ return True
+ return stripped[0].isascii() and stripped[0].isalpha() and stripped[0].islower()
+
+
+def _is_strong_caption_text(text: str) -> bool:
+ """判断文本是否以带编号的中英文强图表标题标记开头。"""
+
+ normalized = _normalize_annotation_text(text)
+ match = _ENGLISH_CAPTION_RE.match(normalized) or _CHINESE_CAPTION_RE.match(normalized)
+ return match is not None and not _caption_tail_is_reference(match.group("tail"))
+
+
+def _is_strong_footnote_text(text: str) -> bool:
+ """判断文本是否以带冒号的来源或注释强标记开头。"""
+
+ return bool(_FOOTNOTE_RE.match(_normalize_annotation_text(text)))
+
+
+def _block_angle(block: dict[str, Any]) -> int:
+ """将块角度规范到四个正交方向。"""
+
+ return int(block.get("angle", 0) or 0) % 360
+
+
+def _block_local_bbox(
+ block: dict[str, Any],
+ page_size: tuple[float, float],
+ angle: int | None = None,
+) -> BBox | None:
+ """读取有效 bbox 并转换到指定文本方向的局部坐标。"""
+
+ bbox = _coerce_bbox(block.get("bbox"))
+ if bbox is None:
+ return None
+ return _rotate_bbox_to_upright(
+ bbox,
+ page_size,
+ _block_angle(block) if angle is None else angle,
+ )
+
+
+def _block_median_line_height(
+ block: dict[str, Any],
+ page_size: tuple[float, float],
+) -> float:
+ """优先使用原生行高,缺失时按局部块高和行框数量保守估计。"""
+
+ heights = [
+ float(height)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and float(height) > 0
+ ]
+ if heights:
+ return statistics.median(heights)
+ local_bbox = _block_local_bbox(block, page_size)
+ if local_bbox is None:
+ return 1.0
+ local_rows = block.get("_local_line_bboxes")
+ row_count = len(local_rows) if isinstance(local_rows, list) and local_rows else 1
+ return max(1.0, (local_bbox[3] - local_bbox[1]) / row_count)
+
+
+def _collect_annotation_candidates(
+ blocks: list[dict[str, Any]],
+) -> dict[int, _AnnotationKind]:
+ """仅从独立 text 和已有 footnote 中收集可参与视觉绑定的注释候选。"""
+
+ output: dict[int, _AnnotationKind] = {}
+ for index, block in enumerate(blocks):
+ block_type = block.get("type")
+ if block_type == "footnote":
+ output[index] = "footnote"
+ continue
+ if block_type != "text" or not isinstance(block.get("content"), str):
+ continue
+ content = str(block["content"])
+ if _is_strong_caption_text(content):
+ output[index] = "caption"
+ elif _is_strong_footnote_text(content):
+ output[index] = "footnote"
+ return output
+
+
+def _axis_overlap_metrics(
+ annotation_bbox: BBox,
+ parent_bbox: BBox,
+ *,
+ axis: Literal["x", "y"],
+ float_margin: float,
+) -> tuple[float, float, float]:
+ """在正交轴允许一行高浮动后计算较短投影、注释覆盖和中心偏移。"""
+
+ if axis == "x":
+ annotation_start, annotation_end = annotation_bbox[0], annotation_bbox[2]
+ parent_start, parent_end = parent_bbox[0], parent_bbox[2]
+ else:
+ annotation_start, annotation_end = annotation_bbox[1], annotation_bbox[3]
+ parent_start, parent_end = parent_bbox[1], parent_bbox[3]
+ expanded_parent_start = parent_start - float_margin
+ expanded_parent_end = parent_end + float_margin
+ overlap = max(
+ 0.0,
+ min(annotation_end, expanded_parent_end)
+ - max(annotation_start, expanded_parent_start),
+ )
+ annotation_length = max(0.1, annotation_end - annotation_start)
+ parent_length = max(0.1, expanded_parent_end - expanded_parent_start)
+ projection_overlap = overlap / min(annotation_length, parent_length)
+ annotation_coverage = overlap / annotation_length
+ center_offset = abs(
+ (annotation_start + annotation_end) / 2.0
+ - (parent_start + parent_end) / 2.0
+ ) / max(annotation_length, parent_end - parent_start, 0.1)
+ return projection_overlap, annotation_coverage, center_offset
+
+
+def _direction_relation(
+ parent: _VisualParent,
+ annotation_bbox: BBox,
+ line_height: float,
+ direction: _Direction,
+ max_gap_in_line_heights: float,
+) -> _AnnotationRelation | None:
+ """按一个方向检查边缘距离、深入量和正交投影约束。"""
+
+ parent_bbox = parent.local_bbox
+ if direction == "above":
+ if _bbox_center_y(annotation_bbox) > _bbox_center_y(parent_bbox):
+ return None
+ signed_gap = parent_bbox[1] - annotation_bbox[3]
+ projection_axis: Literal["x", "y"] = "x"
+ elif direction == "below":
+ if _bbox_center_y(annotation_bbox) < _bbox_center_y(parent_bbox):
+ return None
+ signed_gap = annotation_bbox[1] - parent_bbox[3]
+ projection_axis = "x"
+ elif direction == "left":
+ if _bbox_center_x(annotation_bbox) > _bbox_center_x(parent_bbox):
+ return None
+ signed_gap = parent_bbox[0] - annotation_bbox[2]
+ projection_axis = "y"
+ else:
+ if _bbox_center_x(annotation_bbox) < _bbox_center_x(parent_bbox):
+ return None
+ signed_gap = annotation_bbox[0] - parent_bbox[2]
+ projection_axis = "y"
+ gap = max(0.0, signed_gap)
+ penetration = max(0.0, -signed_gap)
+ if gap > max_gap_in_line_heights * line_height or penetration > line_height:
+ return None
+ projection_overlap, annotation_coverage, center_offset = _axis_overlap_metrics(
+ annotation_bbox,
+ parent_bbox,
+ axis=projection_axis,
+ float_margin=line_height,
+ )
+ if (
+ projection_overlap < _MIN_PROJECTION_OVERLAP
+ or annotation_coverage < _MIN_ANNOTATION_COVERAGE
+ ):
+ return None
+ return _AnnotationRelation(
+ parent=parent,
+ direction=direction,
+ normalized_gap=gap / line_height,
+ projection_overlap=projection_overlap,
+ annotation_coverage=annotation_coverage,
+ center_offset=center_offset,
+ )
+
+
+def _best_parent_relation(
+ parent: _VisualParent,
+ annotation_bbox: BBox,
+ line_height: float,
+ kind: _AnnotationKind,
+) -> _AnnotationRelation | None:
+ """为单个父块选择几何代价最小的合法注释方向。"""
+
+ directions: tuple[_Direction, ...]
+ if kind == "footnote":
+ directions = ("below",)
+ max_gap = _FOOTNOTE_MAX_GAP_IN_LINE_HEIGHTS
+ else:
+ directions = ("above", "below", "left", "right")
+ max_gap = _CAPTION_MAX_GAP_IN_LINE_HEIGHTS
+ relations = [
+ relation
+ for direction in directions
+ if (
+ relation := _direction_relation(
+ parent,
+ annotation_bbox,
+ line_height,
+ direction,
+ max_gap,
+ )
+ )
+ is not None
+ ]
+ if not relations:
+ return None
+ return min(
+ relations,
+ key=lambda relation: (
+ relation.normalized_gap,
+ -relation.annotation_coverage,
+ -relation.projection_overlap,
+ relation.center_offset,
+ ),
+ )
+
+
+def _image_blocks_form_component(
+ first_bbox: BBox,
+ second_bbox: BBox,
+ line_height: float,
+) -> bool:
+ """判断两张图片是否以小净空和足够正交投影组成相邻面板。"""
+
+ horizontal_gap = max(first_bbox[0] - second_bbox[2], second_bbox[0] - first_bbox[2], 0.0)
+ vertical_gap = max(first_bbox[1] - second_bbox[3], second_bbox[1] - first_bbox[3], 0.0)
+ x_overlap = max(0.0, min(first_bbox[2], second_bbox[2]) - max(first_bbox[0], second_bbox[0]))
+ y_overlap = max(0.0, min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]))
+ min_width = max(0.1, min(first_bbox[2] - first_bbox[0], second_bbox[2] - second_bbox[0]))
+ min_height = max(0.1, min(first_bbox[3] - first_bbox[1], second_bbox[3] - second_bbox[1]))
+ return (
+ horizontal_gap <= 2.0 * line_height and y_overlap / min_height >= 0.5
+ ) or (
+ vertical_gap <= 2.0 * line_height and x_overlap / min_width >= 0.5
+ )
+
+
+def _build_visual_parents(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ component_line_height: float,
+) -> list[_VisualParent]:
+ """构造单视觉块父候选,并为相邻图片补充只用于关联的连通组件。"""
+
+ parents: list[_VisualParent] = []
+ image_indices_by_angle: dict[int, list[int]] = {}
+ local_bboxes: dict[int, BBox] = {}
+ for index, block in enumerate(blocks):
+ if block.get("type") not in _VISUAL_BLOCK_TYPES:
+ continue
+ angle = _block_angle(block)
+ local_bbox = _block_local_bbox(block, page_size, angle)
+ if local_bbox is None:
+ continue
+ local_bboxes[index] = local_bbox
+ parents.append(_VisualParent((index,), angle, local_bbox))
+ if block.get("type") == "image":
+ image_indices_by_angle.setdefault(angle, []).append(index)
+
+ for angle, image_indices in image_indices_by_angle.items():
+ remaining = set(image_indices)
+ while remaining:
+ seed = min(remaining)
+ component = {seed}
+ remaining.remove(seed)
+ changed = True
+ while changed:
+ changed = False
+ for candidate in list(remaining):
+ if any(
+ _image_blocks_form_component(
+ local_bboxes[member],
+ local_bboxes[candidate],
+ component_line_height,
+ )
+ for member in component
+ ):
+ component.add(candidate)
+ remaining.remove(candidate)
+ changed = True
+ if len(component) < 2:
+ continue
+ member_indices = tuple(sorted(component))
+ parents.append(
+ _VisualParent(
+ member_indices,
+ angle,
+ _bbox_union_many([local_bboxes[index] for index in member_indices]),
+ )
+ )
+ return parents
+
+
+def _relation_has_intervening_block(
+ relation: _AnnotationRelation,
+ annotation_index: int,
+ annotation_bbox: BBox,
+ line_height: float,
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ annotation_indices: set[int],
+) -> bool:
+ """检查注释与父块净空走廊内是否横隔正文或另一个视觉块。"""
+
+ if relation.normalized_gap <= 0:
+ return False
+ parent_bbox = relation.parent.local_bbox
+ if relation.direction in {"above", "below"}:
+ orth_start = max(annotation_bbox[0], parent_bbox[0]) - 0.25 * line_height
+ orth_end = min(annotation_bbox[2], parent_bbox[2]) + 0.25 * line_height
+ if relation.direction == "above":
+ corridor = (orth_start, annotation_bbox[3], orth_end, parent_bbox[1])
+ else:
+ corridor = (orth_start, parent_bbox[3], orth_end, annotation_bbox[1])
+ else:
+ orth_start = max(annotation_bbox[1], parent_bbox[1]) - 0.25 * line_height
+ orth_end = min(annotation_bbox[3], parent_bbox[3]) + 0.25 * line_height
+ if relation.direction == "left":
+ corridor = (annotation_bbox[2], orth_start, parent_bbox[0], orth_end)
+ else:
+ corridor = (parent_bbox[2], orth_start, annotation_bbox[0], orth_end)
+ if corridor[2] <= corridor[0] or corridor[3] <= corridor[1]:
+ return False
+ ignored_indices = {
+ annotation_index,
+ *relation.parent.member_indices,
+ *annotation_indices,
+ }
+ for index, block in enumerate(blocks):
+ if index in ignored_indices or _block_angle(block) != relation.parent.angle:
+ continue
+ bbox = _block_local_bbox(block, page_size, relation.parent.angle)
+ if bbox is None:
+ continue
+ if (
+ min(bbox[2], corridor[2]) > max(bbox[0], corridor[0])
+ and min(bbox[3], corridor[3]) > max(bbox[1], corridor[1])
+ ):
+ return True
+ return False
+
+
+def _component_relation_is_materially_better(
+ relation: _AnnotationRelation,
+ single_relations: list[_AnnotationRelation],
+) -> bool:
+ """仅当图片并集明显提高注释覆盖时允许组件替代单图父块。"""
+
+ if len(relation.parent.member_indices) < 2:
+ return True
+ member_indices = set(relation.parent.member_indices)
+ comparable = [
+ single
+ for single in single_relations
+ if single.direction == relation.direction
+ and single.parent.member_indices[0] in member_indices
+ ]
+ if not comparable:
+ return True
+ best_single_coverage = max(single.annotation_coverage for single in comparable)
+ return relation.annotation_coverage >= best_single_coverage + _COMPONENT_COVERAGE_GAIN
+
+
+def _choose_annotation_relation(
+ annotation_index: int,
+ kind: _AnnotationKind,
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ parents: list[_VisualParent],
+ annotation_indices: set[int],
+) -> _AnnotationRelation | None:
+ """先过滤空间、组件收益和阻挡关系,再按距离、覆盖和居中选父块。"""
+
+ annotation = blocks[annotation_index]
+ angle = _block_angle(annotation)
+ annotation_bbox = _block_local_bbox(annotation, page_size, angle)
+ if annotation_bbox is None:
+ return None
+ line_height = _block_median_line_height(annotation, page_size)
+ relations = [
+ relation
+ for parent in parents
+ if parent.angle == angle
+ and (
+ relation := _best_parent_relation(
+ parent,
+ annotation_bbox,
+ line_height,
+ kind,
+ )
+ )
+ is not None
+ ]
+ single_relations = [
+ relation for relation in relations if len(relation.parent.member_indices) == 1
+ ]
+ relations = [
+ relation
+ for relation in relations
+ if _component_relation_is_materially_better(relation, single_relations)
+ and not _relation_has_intervening_block(
+ relation,
+ annotation_index,
+ annotation_bbox,
+ line_height,
+ blocks,
+ page_size,
+ annotation_indices,
+ )
+ ]
+ if not relations:
+ return None
+ return min(
+ relations,
+ key=lambda relation: (
+ relation.normalized_gap,
+ -relation.annotation_coverage,
+ -relation.projection_overlap,
+ relation.center_offset,
+ len(relation.parent.member_indices),
+ relation.parent.member_indices,
+ ),
+ )
+
+
+def _merge_parent_assignment_groups(
+ assignments: dict[int, _AnnotationRelation],
+) -> list[tuple[set[int], dict[int, _AnnotationRelation]]]:
+ """合并共享视觉成员的父候选,防止组件与单图重复展开同一主体。"""
+
+ groups: list[tuple[set[int], dict[int, _AnnotationRelation]]] = []
+ for annotation_index, relation in assignments.items():
+ parent_indices = set(relation.parent.member_indices)
+ overlapping = [
+ index
+ for index, (members, _relations) in enumerate(groups)
+ if members & parent_indices
+ ]
+ merged_members = set(parent_indices)
+ merged_relations = {annotation_index: relation}
+ for group_index in reversed(overlapping):
+ members, relations = groups.pop(group_index)
+ merged_members.update(members)
+ merged_relations.update(relations)
+ groups.append((merged_members, merged_relations))
+ return groups
+
+
+def _sort_visual_body_members(
+ member_indices: set[int],
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """在共同局部方向内用 XYCut++ 排列区域中的视觉主体成员。"""
+
+ if not member_indices:
+ return []
+ angle = _block_angle(blocks[min(member_indices)])
+ proxies: list[dict[str, Any]] = []
+ for index in sorted(member_indices):
+ local_bbox = _block_local_bbox(blocks[index], page_size, angle)
+ if local_bbox is None:
+ continue
+ proxies.append({"bbox": local_bbox, "_block": blocks[index]})
+ return [proxy["_block"] for proxy in sort_entries(proxies)]
+
+
+def _annotation_local_sort_key(
+ index: int,
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> tuple[float, float, int]:
+ """按注释自身方向的局部上、左坐标提供稳定排序键。"""
+
+ block = blocks[index]
+ local_bbox = _block_local_bbox(block, page_size)
+ if local_bbox is None:
+ return (float("inf"), float("inf"), index)
+ return (local_bbox[1], local_bbox[0], index)
+
+
+def _build_visual_annotation_regions(
+ assignments: dict[int, _AnnotationRelation],
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[list[dict[str, Any]]]:
+ """按前置标题、主体、后置标题、脚注顺序展开每个虚拟小区域。"""
+
+ regions: list[list[dict[str, Any]]] = []
+ for parent_indices, relations in _merge_parent_assignment_groups(assignments):
+ leading = [
+ index
+ for index, relation in relations.items()
+ if blocks[index].get("type") == "caption"
+ and relation.direction in {"above", "left"}
+ ]
+ trailing = [
+ index
+ for index, relation in relations.items()
+ if blocks[index].get("type") == "caption"
+ and relation.direction in {"below", "right"}
+ ]
+ footnotes = [
+ index
+ for index in relations
+ if blocks[index].get("type") == "footnote"
+ ]
+ regions.append(
+ [
+ *(
+ blocks[index]
+ for index in sorted(
+ leading,
+ key=lambda value: _annotation_local_sort_key(
+ value,
+ blocks,
+ page_size,
+ ),
+ )
+ ),
+ *_sort_visual_body_members(parent_indices, blocks, page_size),
+ *(
+ blocks[index]
+ for index in sorted(
+ trailing,
+ key=lambda value: _annotation_local_sort_key(
+ value,
+ blocks,
+ page_size,
+ ),
+ )
+ ),
+ *(
+ blocks[index]
+ for index in sorted(
+ footnotes,
+ key=lambda value: _annotation_local_sort_key(
+ value,
+ blocks,
+ page_size,
+ ),
+ )
+ ),
+ ]
+ )
+ return regions
+
+
+def _classify_and_bind_visual_annotations(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[list[dict[str, Any]]]:
+ """重分类强规则独立注释,并返回供全局 XYCut++ 使用的有序视觉区域。"""
+
+ candidates = _collect_annotation_candidates(blocks)
+ if not candidates:
+ return []
+ line_heights = [
+ _block_median_line_height(blocks[index], page_size)
+ for index in candidates
+ ]
+ component_line_height = statistics.median(line_heights) if line_heights else 8.0
+ parents = _build_visual_parents(blocks, page_size, component_line_height)
+ if not parents:
+ return []
+ annotation_indices = set(candidates)
+ assignments = {
+ index: relation
+ for index, kind in candidates.items()
+ if (
+ relation := _choose_annotation_relation(
+ index,
+ kind,
+ blocks,
+ page_size,
+ parents,
+ annotation_indices,
+ )
+ )
+ is not None
+ }
+ 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)
diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.py
index 9b7668ce..24ccad9b 100644
--- a/tests/unittest/test_flash_pdf_graphics.py
+++ b/tests/unittest/test_flash_pdf_graphics.py
@@ -727,7 +727,7 @@ def test_raster_images_filter_small_objects_avoid_containers_and_claim_text_once
def test_raster_image_content_is_removed_from_text_and_empty_image_page_is_kept() -> None:
- """验证图内文本只进入 image,caption 保持 text,纯图片页仍输出空 content。"""
+ """验证图内文本只进入 image,独立 caption 正确标记,纯图片页仍输出空 content。"""
source = models._PageSource(
page_size=(100.0, 100.0),
@@ -743,10 +743,10 @@ def test_raster_image_content_is_removed_from_text_and_empty_image_page_is_kept(
blocks = pipeline._analyze_page_source(source)
image_block = next(block for block in blocks if block["type"] == "image")
- text_block = next(block for block in blocks if block["type"] == "text")
+ caption_block = next(block for block in blocks if block["type"] == "caption")
assert image_block["content"] == "inside row one\ninside row two"
- assert text_block["content"] == "Figure 1: outside caption"
+ assert caption_block["content"] == "Figure 1: outside caption"
assert sum("inside row" in block["content"] for block in blocks) == 1
empty_page_blocks = pipeline._analyze_page_source(
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index ebf3c4a4..79305ff9 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -20,6 +20,7 @@ from mineru.backend.flash.native_pdf import (
tables,
text_blocks,
titles,
+ visual_annotations,
)
from mineru.utils.pdf_document import PDFImageInfo
@@ -153,6 +154,7 @@ def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:
tables,
text_blocks,
titles,
+ visual_annotations,
)
)
forbidden_tokens = (
@@ -192,6 +194,7 @@ def test_native_pdf_domain_modules_do_not_import_each_other() -> None:
tables,
text_blocks,
titles,
+ visual_annotations,
)
domain_names = {module.__name__.rsplit(".", 1)[-1] for module in domain_modules}
for module in domain_modules:
@@ -212,6 +215,8 @@ def test_native_pdf_domain_modules_do_not_import_each_other() -> None:
"header",
"footer",
"page_number",
+ "caption",
+ "footnote",
"page_footnote",
"aside_text",
"index",
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 8f8cee1f..575940a5 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -15,6 +15,7 @@ from mineru.backend.flash.native_pdf import (
pipeline,
tables,
)
+from mineru.backend.hybrid.magic_model import MagicModel
from mineru.utils.pdf_document import get_lines_from_chars
@@ -121,6 +122,7 @@ def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:
assert sum(block["type"] == "header" for page in model_list for block in page) == 12
assert sum(block["type"] == "page_number" for page in model_list for block in page) == 12
assert sum(block["type"] == "equation" for page in model_list for block in page) == 7
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 5
assert [block["bbox"] for block in model_list[5] if block["type"] == "table"] == [
[0.087, 0.125, 0.922, 0.363],
[0.087, 0.669, 0.922, 0.893],
@@ -187,6 +189,7 @@ def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() ->
for expected_text in ("dp", "¯x", "p =", "¯p =", "Left camera", "Right camera"):
assert expected_text in graphic_block["content"]
assert graphic_block is not caption_block
+ assert caption_block["type"] == "caption"
assert "Figure 1:" not in graphic_block["content"]
assert "Left camera" not in caption_block["content"]
assert sum(block["content"].count("Left camera") for block in page) == 1
@@ -208,6 +211,7 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert [sum(block["type"] == "image" for block in page) for page in model_list] == [1, 0, 0, 5, 2, 0]
assert [sum(block["type"] == "table" for block in page) for page in model_list] == [0, 0, 0, 1, 1, 0]
assert sum(block["type"] == "equation" for page in model_list for block in page) == 9
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 5
page2 = model_list[1]
page2_contents = [block["content"] for block in page2]
@@ -403,6 +407,7 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:
18,
]
assert sum(len(page) for page in model_list) == 173
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 8
page7_tables = [block for block in model_list[6] if block["type"] == "table"]
page7_table4 = next(
block for block in page7_tables if "Number of parameters" in block["content"]
@@ -438,6 +443,7 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:
)
)
assert page7_table4_caption["content"] not in page7_table4["content"]
+ assert page7_table4_caption["type"] == "caption"
assert page7_table4["bbox"][3] < page7_table4_caption["bbox"][1]
assert page7_inline_body["type"] == "text"
assert "With TAPASBASE" in page7_inline_body["content"]
@@ -581,7 +587,7 @@ def test_demo3_pages6_7_and10_fix_caption_inline_titles_and_reference_tail() ->
table2_caption = next(
block for block in page6 if block["content"].startswith("Table 2:")
)
- assert table2_caption["type"] == "text"
+ assert table2_caption["type"] == "caption"
assert "Median of 5 independent runs are reported." in table2_caption["content"]
assert table2_caption["content"].endswith("not reported in the original paper.")
assert sum(
@@ -659,7 +665,7 @@ def test_demo3_page3_form_image_formulas_titles_and_inline_body_are_whole() -> N
or "types of task independent biases" in block["content"]
]
assert len(caption_blocks) == 1
- assert caption_blocks[0]["type"] == "text"
+ assert caption_blocks[0]["type"] == "caption"
assert "This example corresponds to table (a)" in caption_blocks[0]["content"]
assert "associated text." in caption_blocks[0]["content"]
@@ -820,9 +826,21 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
assert len(figure_caption) == 1
assert len(figure_body) == 1
assert figure_caption[0] is not figure_body[0]
+ assert figure_caption[0]["type"] == "caption"
assert "inreducingglucoseuptake" not in _normalized_content_probe(
str(figure_caption[0]["content"])
)
+ side_caption = _blocks_containing(page4, "Fig. 2 [18F]FDG uptake")
+ side_image = next(
+ block
+ for block in page4
+ if block["type"] == "image" and block["bbox"] == [0.3, 0.608, 0.914, 0.897]
+ )
+ assert len(side_caption) == 1
+ 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) == 5
page5 = model_list[4]
right_continuation = _blocks_containing(
@@ -952,7 +970,34 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:
page77_note = _blocks_containing(model_list[76], "注:(1)指气量")
assert len(page77_note) == 1
- assert page77_note[0]["type"] == "text"
+ assert page77_note[0]["type"] == "footnote"
+
+ expected_footnote_pages = {6, 7, 31, 36, 39, 43, 49, 53, 55, 57, 58, 59, 77}
+ assert {
+ page_number
+ for page_number, page in enumerate(model_list, start=1)
+ if any(block["type"] == "footnote" for block in page)
+ } == expected_footnote_pages
+ assert sum(
+ block["type"] == "footnote"
+ for page in model_list
+ for block in page
+ ) == 13
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 3
+ page62_note = _blocks_containing(
+ model_list[61],
+ "排入城镇集中污水处理设施的生活污水",
+ )
+ page86_table20 = _blocks_containing(model_list[85], "表20 改正规定信息表")
+ 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",
+ ]
page9 = model_list[8]
page_number_block = next(
@@ -1007,6 +1052,12 @@ def test_demo6_default3_targeted_title_regressions() -> None:
assert [block["content"] for block in page7_images] == ["(签名)", "(盖章)"]
assert sum("签名" in str(block["content"]) for block in model_list[6]) == 1
assert sum("盖章" in str(block["content"]) for block in model_list[6]) == 1
+ assert not [
+ block
+ for page in model_list
+ for block in page
+ if block["type"] in {"caption", "footnote"}
+ ]
def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:
@@ -1069,7 +1120,7 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:
assert [
block["bbox"]
for block in page4
- if block["type"] in {"text", "image"}
+ if block["type"] in {"text", "image", "caption"}
and block["bbox"][0] >= 0.49
and block["bbox"][1] >= 0.49
] == [
@@ -1096,7 +1147,20 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:
assert "ular films." not in str(lower_graphs[0]["content"])
figure4_caption = _blocks_containing(page5, "Fig. 4. Plots of σT1/2")
assert len(figure4_caption) == 1
- assert figure4_caption[0]["type"] == "text"
+ assert figure4_caption[0]["type"] == "caption"
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 4
+
+ figure1_caption = _blocks_containing(page4, "Fig. 1. Electron micrographs")
+ panel_images = [
+ block
+ for block in page4
+ if block["type"] == "image" and block["bbox"][3] < 0.44
+ ]
+ assert len(figure1_caption) == 1
+ assert len(panel_images) == 4
+ assert max(page4.index(block) for block in panel_images) < page4.index(
+ figure1_caption[0]
+ )
def test_caibao_table_reclaims_repeated_dates_but_keeps_real_marginals() -> None:
@@ -1116,6 +1180,11 @@ def test_caibao_table_reclaims_repeated_dates_but_keeps_real_marginals() -> None
assert "2024 年" not in str(footers[0]["content"])
assert tables_on_page[0]["bbox"][3] < footers[0]["bbox"][1]
assert tables_on_page[0]["bbox"][3] < page_numbers[0]["bbox"][1]
+ assert not [block for block in page if block["type"] == "footnote"]
+
+ page18 = model_list[17]
+ assert len([block for block in page18 if block["type"] == "footer"]) == 1
+ assert not [block for block in page18 if block["type"] == "footnote"]
def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
@@ -1126,19 +1195,19 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
first_caption = [
block
for block in page
- if block["type"] == "text"
+ if block["type"] == "caption"
and str(block["content"]).startswith("图表1")
]
second_caption = [
block
for block in page
- if block["type"] == "text"
+ if block["type"] == "caption"
and str(block["content"]).startswith("图表2")
]
assert len(page) == 20
assert len(first_caption) == len(second_caption) == 1
- assert first_caption[0]["type"] == second_caption[0]["type"] == "text"
+ assert first_caption[0]["type"] == second_caption[0]["type"] == "caption"
assert first_caption[0]["bbox"] == [0.073, 0.235, 0.485, 0.245]
assert second_caption[0]["bbox"] == [0.513, 0.235, 0.843, 0.245]
assert "行业周涨幅" not in str(first_caption[0]["content"])
@@ -1151,17 +1220,76 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
[0.082, 0.267, 0.48, 0.447],
[0.522, 0.254, 0.92, 0.46],
]
+ first_index = page.index(first_caption[0])
+ second_index = page.index(second_caption[0])
+ assert [block["type"] for block in page[first_index : first_index + 3]] == [
+ "caption",
+ "image",
+ "footnote",
+ ]
+ assert [block["type"] for block in page[second_index : second_index + 3]] == [
+ "caption",
+ "image",
+ "footnote",
+ ]
+ assert first_index + 3 == second_index
page3_captions = [
block
for block in model_list[2]
- if block["type"] == "text"
+ if block["type"] == "caption"
and str(block["content"]).startswith(("图表4", "图表5"))
]
assert [block["bbox"] for block in page3_captions] == [
[0.073, 0.181, 0.298, 0.191],
[0.514, 0.181, 0.738, 0.191],
]
+ page3 = model_list[2]
+ for caption in page3_captions:
+ index = page3.index(caption)
+ assert [block["type"] for block in page3[index : index + 3]] == [
+ "caption",
+ "image",
+ "footnote",
+ ]
+
+ expected_new_footnotes = {1: 2, 6: 1, 7: 1, 8: 2, 17: 1, 19: 1}
+ assert {
+ page_number: sum(block["type"] == "footnote" for block in model_list[page_number - 1])
+ for page_number in expected_new_footnotes
+ } == expected_new_footnotes
+ assert all(
+ str(block["content"]).startswith("资料来源:")
+ for page_number in expected_new_footnotes
+ for block in model_list[page_number - 1]
+ if block["type"] == "footnote"
+ )
+ assert sum(
+ block["type"] == "caption"
+ for page_blocks in model_list
+ for block in page_blocks
+ ) == 15
+ assert sum(
+ block["type"] == "footnote"
+ for page_blocks in model_list
+ for block in page_blocks
+ ) == 16
+
+ page2_magic_model = MagicModel(page, 1000, 1000)
+ for caption_prefix in ("图表1", "图表2"):
+ image_group = next(
+ group
+ for group in page2_magic_model.get_image_blocks()
+ if any(
+ str(child.content).startswith(caption_prefix)
+ for child in group.blocks
+ )
+ )
+ assert [child.type for child in image_group.blocks] == [
+ "image_caption",
+ "image_body",
+ "image_footnote",
+ ]
def test_iebm_left_indented_compact_formula_is_equation() -> None:
@@ -1177,12 +1305,62 @@ def test_iebm_left_indented_compact_formula_is_equation() -> None:
assert len(target) == 1
assert target[0]["type"] == "equation"
assert target[0]["content"] == "F ¼ @ψ @Y, G ¼ @ψ @X."
+ assert not [block for block in page if block["type"] in {"caption", "footnote"}]
+
+
+def test_npu_numbered_figure_captions_are_independent_annotations() -> None:
+ """验证 NPU 指南十四个编号图注独立输出,且不产生视觉脚注误报。"""
+
+ model_list = _txt_model_list("NPU_开发环境部署_参考指南.pdf")
+ expected_counts = {6: 1, 7: 1, 14: 2, 15: 2, 16: 2, 17: 1, 18: 1, 19: 2, 20: 2}
+
+ assert {
+ page_number: sum(block["type"] == "caption" for block in model_list[page_number - 1])
+ for page_number in expected_counts
+ } == expected_counts
+ assert sum(
+ block["type"] == "caption"
+ for page in model_list
+ for block in page
+ ) == 14
+ assert all(
+ str(block["content"]).startswith("图 ")
+ for page in model_list
+ for block in page
+ if block["type"] == "caption"
+ )
+ assert not [block for page in model_list for block in page if block["type"] == "footnote"]
def test_frozen_soil_reference_tails_remain_single_text_blocks() -> None:
- """验证完整粉质砂土论文第 9 页的参考文献尾行不误报 equation。"""
+ """验证中文论文双语图注独立标记,正文图引用和参考文献保持 text。"""
- page = _auto_model_list("中文论文.pdf")[8]
+ model_list = _auto_model_list("中文论文.pdf")
+ page = model_list[8]
+
+ captions = [
+ block
+ for page_blocks in model_list
+ for block in page_blocks
+ if block["type"] == "caption"
+ ]
+ assert len(captions) == 15
+ page2 = model_list[1]
+ image = next(block for block in page2 if block["type"] == "image")
+ chinese_caption = _blocks_containing(page2, "图1 冻土抗剪强度试验流程示意图")
+ english_caption = _blocks_containing(page2, "Fig. 1 Schematic diagram")
+ assert len(chinese_caption) == len(english_caption) == 1
+ assert chinese_caption[0]["type"] == english_caption[0]["type"] == "caption"
+ assert page2.index(image) < page2.index(chinese_caption[0]) < page2.index(
+ english_caption[0]
+ )
+
+ narrative_reference = _blocks_containing(
+ model_list[7],
+ "图 8(a)、8(b)分别为",
+ )
+ assert len(narrative_reference) == 1
+ assert narrative_reference[0]["type"] == "text"
assert not [block for block in page if block["type"] == "equation"]
for probe in (
@@ -1226,7 +1404,29 @@ def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:
assert not [block for block in page8 if block["type"] == "table"]
figure_caption = _blocks_containing(page8, "Figure 1. Program containing dead code")
assert len(figure_caption) == 1
- assert figure_caption[0]["type"] == "text"
+ assert figure_caption[0]["type"] == "caption"
+ algorithm1 = _blocks_containing(page8, "Algorithm 1 Detection of Irrelevant Code")
+ algorithm2 = _blocks_containing(page8, "Algorithm 2 Detection of Unreachable Code")
+ assert len(algorithm1) == len(algorithm2) == 1
+ assert algorithm1[0]["type"] == algorithm2[0]["type"] == "caption"
+ assert page8.index(algorithm1[0]) + 1 == page8.index(code_blocks[1])
+ assert page8.index(algorithm2[0]) + 1 == page8.index(code_blocks[2])
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 4
+
+ page8_magic_model = MagicModel(page8, 1000, 1000)
+ algorithm_groups = [
+ group
+ for group in page8_magic_model.get_code_blocks()
+ if any(
+ str(child.content).startswith("Algorithm")
+ for child in group.blocks
+ )
+ ]
+ assert len(algorithm_groups) == 2
+ assert all(
+ [child.type for child in group.blocks] == ["code_caption", "code_body"]
+ for group in algorithm_groups
+ )
framework_title = _blocks_containing(
page9,
@@ -1280,10 +1480,11 @@ def test_mixed_elements_pages_11_15_force_txt_regressions() -> None:
figure2 = _blocks_containing(model_list[2], "Fig. 2. Pathological changes")
figure6 = _blocks_containing(model_list[3], "Fig. 6. Effect of ecabet")
assert len(figure2) == len(figure6) == 1
- assert figure2[0]["type"] == figure6[0]["type"] == "text"
+ assert figure2[0]["type"] == figure6[0]["type"] == "caption"
assert "Under anesthesia with ether" in figure2[0]["content"]
assert "pepsin. Isolated and everted esophagus" in figure6[0]["content"]
assert not [block for block in all_blocks if block["type"] == "footnote"]
+ assert sum(block["type"] == "caption" for block in all_blocks) == 6
online_footer = _blocks_containing(model_list[4], "http://www.birkhauser.ch/IPh")
assert len(online_footer) == 1
@@ -1308,6 +1509,12 @@ def test_mixed_elements_pages_39_40_force_txt_regressions() -> None:
assert len(continuation) == 1
assert continuation[0]["type"] == "text"
assert "Coupling this observation" in continuation[0]["content"]
+ assert not [
+ block
+ for page in model_list
+ for block in page
+ if block["type"] in {"caption", "footnote"}
+ ]
assert sum(
"Coupling this observation" in str(block["content"])
for block in page40
diff --git a/tests/unittest/test_flash_pdf_visual_annotations.py b/tests/unittest/test_flash_pdf_visual_annotations.py
new file mode 100644
index 00000000..8972e2f0
--- /dev/null
+++ b/tests/unittest/test_flash_pdf_visual_annotations.py
@@ -0,0 +1,337 @@
+from __future__ import annotations
+
+import pytest
+
+from mineru.backend.flash.native_pdf import pipeline, visual_annotations
+
+
+_PAGE_SIZE = (200.0, 200.0)
+
+
+def _text_block(
+ content: str,
+ bbox: tuple[float, float, float, float],
+ *,
+ block_type: str = "text",
+ row_id: int | None = None,
+) -> dict[str, object]:
+ """构造带稳定十点行高的独立文本测试块。"""
+
+ return {
+ "type": block_type,
+ "bbox": bbox,
+ "angle": 0,
+ "content": content,
+ "_line_heights": [10.0],
+ "_single_run_row_id": row_id,
+ "_lane_interval": (bbox[0], bbox[2]),
+ "_lane_is_span": False,
+ }
+
+
+def _visual_block(
+ bbox: tuple[float, float, float, float],
+ *,
+ block_type: str = "image",
+) -> dict[str, object]:
+ """构造不包含内部文本的视觉主体测试块。"""
+
+ return {
+ "type": block_type,
+ "bbox": bbox,
+ "angle": 0,
+ "content": "",
+ }
+
+
+ "content",
+ [
+ "Fig. 2. Overview",
+ "Figure A1: Overview",
+ "Tab. 2-1 Results",
+ "Table IV. Results",
+ "Alg. 1 Procedure",
+ "Algorithm 2: Procedure",
+ "Listing 3 Source code",
+ "Chart 4: Revenue",
+ "Scheme Ⅴ. Architecture",
+ "图20:系统结构",
+ "图表2-1 行业走势",
+ "表格三 实验结果",
+ "算法 A1:训练流程",
+ "程序清单2 示例",
+ ],
+)
+def test_strong_caption_markers_accept_numbered_titles(content: str) -> None:
+ """验证中英文强标题标记兼容常用编号写法。"""
+
+ assert visual_annotations._is_strong_caption_text(content)
+
+
+ "content",
+ [
+ "Figure 2 shows the result.",
+ "Table 1, 2 and 3 show the results.",
+ "Figure without a number",
+ "图2为系统结构。",
+ "表1展示实验结果。",
+ "图6和图7分别为输入与输出。",
+ "图 8(a)、8(b)分别为两个模型的结果。",
+ "普通正文中的 Figure 2",
+ ],
+)
+def test_strong_caption_markers_reject_body_references(content: str) -> None:
+ """验证正文引用、并列编号和无编号标签不会进入标题候选。"""
+
+ assert not visual_annotations._is_strong_caption_text(content)
+
+
+ "content",
+ [
+ "Source: survey",
+ "Sources: survey",
+ "Source(s): survey",
+ "Data source: survey",
+ "Note: adjusted values",
+ "Note(s): adjusted values",
+ "资料来源:公司公告",
+ "数据来源:统计局",
+ "来源:作者整理",
+ "注:数值经过调整",
+ "备注:数值经过调整",
+ ],
+)
+def test_strong_footnote_markers_require_colon_and_body(content: str) -> None:
+ """验证来源与注释强规则要求冒号和实际正文。"""
+
+ assert visual_annotations._is_strong_footnote_text(content)
+
+
+ "content",
+ ["Note that the value changes.", "Source material is public.", "注释内容", "来源:"],
+)
+def test_strong_footnote_markers_reject_narrative_text(content: str) -> None:
+ """验证无冒号的叙述句和空标记不会进入脚注候选。"""
+
+ assert not visual_annotations._is_strong_footnote_text(content)
+
+
+ ("caption_bbox", "expected_order"),
+ [
+ ((40.0, 25.0, 80.0, 35.0), ("caption", "image")),
+ ((40.0, 85.0, 80.0, 95.0), ("image", "caption")),
+ ((5.0, 40.0, 35.0, 80.0), ("caption", "image")),
+ ((85.0, 40.0, 115.0, 80.0), ("image", "caption")),
+ ],
+)
+def test_caption_binds_on_all_four_sides(
+ caption_bbox: tuple[float, float, float, float],
+ expected_order: tuple[str, str],
+) -> None:
+ """验证上下左右紧邻标题均能绑定,并按相对方向展开。"""
+
+ caption = _text_block("Figure 1: Overview", caption_bbox)
+ 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,
+ )
+
+ assert caption["type"] == "caption"
+ assert len(regions) == 1
+ assert tuple(block["type"] for block in regions[0]) == expected_order
+
+
+def test_rotated_caption_uses_parent_local_coordinates() -> None:
+ """验证九十度页面块会先转入共同局部坐标再判断上方标题。"""
+
+ caption = _text_block("Figure 1: Rotated", (165.0, 40.0, 175.0, 80.0))
+ image = _visual_block((120.0, 40.0, 160.0, 80.0))
+ caption["angle"] = image["angle"] = 90
+
+ regions = visual_annotations._classify_and_bind_visual_annotations(
+ [caption, image],
+ _PAGE_SIZE,
+ )
+
+ assert caption["type"] == "caption"
+ assert regions == [[caption, image]]
+
+
+def test_caption_rejects_more_than_one_line_height_penetration() -> None:
+ """验证边缘轻微浮入主体可接受,深入超过自身一行高则保持 text。"""
+
+ image = _visual_block((40.0, 40.0, 80.0, 80.0))
+ accepted = _text_block("Figure 1: Accepted", (40.0, 72.0, 80.0, 82.0))
+ accepted_regions = visual_annotations._classify_and_bind_visual_annotations(
+ [image, accepted],
+ _PAGE_SIZE,
+ )
+
+ rejected = _text_block("Figure 2: Rejected", (40.0, 69.0, 80.0, 79.0))
+ rejected_regions = visual_annotations._classify_and_bind_visual_annotations(
+ [image.copy(), rejected],
+ _PAGE_SIZE,
+ )
+
+ assert accepted["type"] == "caption"
+ assert accepted_regions
+ assert rejected["type"] == "text"
+ assert rejected_regions == []
+
+
+def test_footnote_accepts_six_line_gap_but_rejects_farther_text() -> None:
+ """验证视觉块下方脚注的六行高距离上限为闭区间。"""
+
+ image = _visual_block((20.0, 20.0, 100.0, 50.0))
+ accepted = _text_block("Note: accepted", (20.0, 110.0, 100.0, 120.0))
+ accepted_blocks = [image, accepted]
+ accepted_regions = visual_annotations._classify_and_bind_visual_annotations(
+ accepted_blocks,
+ _PAGE_SIZE,
+ )
+
+ rejected = _text_block("Note: rejected", (20.0, 110.1, 100.0, 120.1))
+ rejected_blocks = [image.copy(), rejected]
+ rejected_regions = visual_annotations._classify_and_bind_visual_annotations(
+ rejected_blocks,
+ _PAGE_SIZE,
+ )
+
+ assert accepted["type"] == "footnote"
+ assert [block["type"] for block in accepted_regions[0]] == ["image", "footnote"]
+ assert rejected["type"] == "text"
+ assert rejected_regions == []
+
+
+def test_existing_visual_footnote_binds_without_content_marker() -> None:
+ """验证已有横线小字 footnote 无需再次命中内容规则即可加入区域。"""
+
+ image = _visual_block((20.0, 20.0, 100.0, 60.0))
+ footnote = _text_block(
+ "calculated by the authors",
+ (20.0, 70.0, 100.0, 80.0),
+ block_type="footnote",
+ )
+
+ regions = visual_annotations._classify_and_bind_visual_annotations(
+ [image, footnote],
+ _PAGE_SIZE,
+ )
+
+ assert [block["type"] for block in regions[0]] == ["image", "footnote"]
+
+
+def test_multi_panel_images_only_group_when_union_improves_coverage() -> None:
+ """验证跨面板标题绑定图片并集,而单图标题不会无故吞并相邻图片。"""
+
+ caption = _text_block("Figure 1: Two panels", (10.0, 10.0, 90.0, 20.0))
+ left = _visual_block((10.0, 25.0, 45.0, 60.0))
+ right = _visual_block((50.0, 25.0, 90.0, 60.0))
+ blocks = [caption, left, right]
+
+ regions = visual_annotations._classify_and_bind_visual_annotations(
+ blocks,
+ _PAGE_SIZE,
+ )
+
+ assert len(regions) == 1
+ assert regions[0] == [caption, left, right]
+
+ left_caption = _text_block("Figure 2: Left", (10.0, 10.0, 45.0, 20.0))
+ independent_blocks = [left_caption, left.copy(), right.copy()]
+ independent_regions = visual_annotations._classify_and_bind_visual_annotations(
+ independent_blocks,
+ _PAGE_SIZE,
+ )
+
+ assert len(independent_regions) == 1
+ assert independent_regions[0] == [left_caption, independent_blocks[1]]
+
+
+def test_nearest_parent_wins_and_intervening_body_blocks_cross_binding() -> None:
+ """验证竞争父块优先选择归一化边距更小者,正文阻挡远距绑定。"""
+
+ upper = _visual_block((20.0, 10.0, 100.0, 40.0))
+ caption = _text_block("Figure 1: Upper", (20.0, 45.0, 100.0, 55.0))
+ lower = _visual_block((20.0, 80.0, 100.0, 110.0))
+ blocks = [upper, caption, lower]
+ regions = visual_annotations._classify_and_bind_visual_annotations(
+ blocks,
+ _PAGE_SIZE,
+ )
+
+ assert regions == [[upper, caption]]
+
+ body = _text_block("ordinary paragraph", (20.0, 55.0, 100.0, 65.0))
+ note = _text_block("Source: survey", (20.0, 75.0, 100.0, 85.0))
+ blocked = [upper.copy(), body, note]
+ blocked_regions = visual_annotations._classify_and_bind_visual_annotations(
+ blocked,
+ _PAGE_SIZE,
+ )
+
+ assert note["type"] == "text"
+ assert blocked_regions == []
+
+
+def test_visual_regions_prevent_cross_column_row_remerge() -> None:
+ """验证同一拆分视觉行的左右标题在区域化后不会先于两个主体一起输出。"""
+
+ left_caption = _text_block(
+ "Chart 1: Left",
+ (10.0, 10.0, 80.0, 20.0),
+ row_id=7,
+ )
+ right_caption = _text_block(
+ "Chart 2: Right",
+ (110.0, 10.0, 180.0, 20.0),
+ row_id=7,
+ )
+ left_image = _visual_block((10.0, 25.0, 80.0, 70.0))
+ right_image = _visual_block((110.0, 25.0, 180.0, 70.0))
+ blocks = [left_caption, right_caption, left_image, right_image]
+ regions = visual_annotations._classify_and_bind_visual_annotations(
+ blocks,
+ _PAGE_SIZE,
+ )
+
+ ordered = pipeline._sort_blocks_with_visual_row_groups(
+ blocks,
+ _PAGE_SIZE,
+ visual_annotation_regions=regions,
+ )
+
+ assert ordered == [left_caption, left_image, right_caption, right_image]
+
+
+def test_non_text_marginals_never_enter_visual_reclassification() -> None:
+ """验证 footer 与 page_footnote 即使内容像强规则也不会改为视觉脚注。"""
+
+ image = _visual_block((20.0, 20.0, 100.0, 60.0))
+ footer = _text_block(
+ "Source: disclaimer",
+ (20.0, 70.0, 100.0, 80.0),
+ block_type="footer",
+ )
+ page_footnote = _text_block(
+ "Note: author affiliation",
+ (20.0, 85.0, 100.0, 95.0),
+ block_type="page_footnote",
+ )
+
+ regions = visual_annotations._classify_and_bind_visual_annotations(
+ [image, footer, page_footnote],
+ _PAGE_SIZE,
+ )
+
+ assert regions == []
+ assert footer["type"] == "footer"
+ assert page_footnote["type"] == "page_footnote"