Skip to content

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

feat: enhance graphic detection by implementing strong graphic bounding box detection and refining visual header classification

myhloli1d01204ba046
diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.py
index 21d95ac6..cc93f0a4 100644
--- a/mineru/backend/flash/native_pdf/auxiliary_text.py
+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py
@@ -26,6 +26,8 @@ from .geometry import (
_bbox_center_x,
_bbox_center_y,
_bbox_intersects,
+ _clip_bbox,
+ _coerce_bbox,
_expand_bbox,
_horizontal_bbox_gap,
_rotate_bbox_to_upright,
@@ -334,6 +336,110 @@ def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:
right.line.semantic_type = right.region
+def _classify_repeated_visual_headers(pages: list[_PreparedPage]) -> None:
+ """仅按页首位置与跨页重复几何,把整体图片重标为视觉页眉。"""
+
+ candidates: list[tuple[int, dict[str, object], BBox, int]] = []
+ for page_index, page in enumerate(pages):
+ # 首页常使用独立封面版式,不参与正文页视觉页眉聚类。
+ if page_index == 0:
+ continue
+ page_width, page_height = page.page_size
+ if page_width <= 0 or page_height <= 0:
+ continue
+ for block in page.fixed_blocks:
+ if block.get("type") != "image":
+ continue
+ content = block.get("content")
+ # 当前 model_list 不保留空文本 header;这里只限制输出可表示性,
+ # 跨页匹配本身完全不比较 content。
+ if not isinstance(content, str) or not content.strip():
+ continue
+ bbox = _clip_bbox(_coerce_bbox(block.get("bbox")), page.page_size)
+ if bbox is None or bbox[3] > 0.12 * page_height:
+ continue
+ normalized_bbox = (
+ bbox[0] / page_width,
+ bbox[1] / page_height,
+ bbox[2] / page_width,
+ bbox[3] / page_height,
+ )
+ angle = int(block.get("angle", 0) or 0) % 360
+ candidates.append((page_index, block, normalized_bbox, angle))
+
+ if len(candidates) < 3:
+ return
+
+ parents = list(range(len(candidates)))
+
+ def find(index: int) -> int:
+ """查找视觉页眉候选所属几何簇的根节点。"""
+
+ while parents[index] != index:
+ parents[index] = parents[parents[index]]
+ index = parents[index]
+ return index
+
+ def union(first_index: int, second_index: int) -> None:
+ """合并跨页距离和归一化几何均匹配的两个候选。"""
+
+ first_root = find(first_index)
+ second_root = find(second_index)
+ if first_root != second_root:
+ parents[second_root] = first_root
+
+ for first_index, (
+ first_page,
+ _first_block,
+ first_bbox,
+ first_angle,
+ ) in enumerate(candidates):
+ for second_index in range(first_index + 1, len(candidates)):
+ second_page, _second_block, second_bbox, second_angle = candidates[
+ second_index
+ ]
+ page_delta = second_page - first_page
+ if page_delta > 2:
+ break
+ if (
+ page_delta > 0
+ and first_angle == second_angle
+ and _visual_header_geometry_matches(first_bbox, second_bbox)
+ ):
+ union(first_index, second_index)
+
+ clusters: dict[int, list[int]] = {}
+ for candidate_index in range(len(candidates)):
+ clusters.setdefault(find(candidate_index), []).append(candidate_index)
+ for member_indices in clusters.values():
+ page_indices = {candidates[index][0] for index in member_indices}
+ if len(page_indices) < 3:
+ continue
+ for index in member_indices:
+ candidates[index][1]["type"] = "header"
+
+
+def _visual_header_geometry_matches(first: BBox, second: BBox) -> bool:
+ """比较两个归一化页首图片的 IoU 与宽高尺度。"""
+
+ first_width = first[2] - first[0]
+ first_height = first[3] - first[1]
+ second_width = second[2] - second[0]
+ second_height = second[3] - second[1]
+ if min(first_width, first_height, second_width, second_height) <= 0:
+ return False
+ if max(first_width, second_width) / min(first_width, second_width) > 1.1:
+ return False
+ if max(first_height, second_height) / min(first_height, second_height) > 1.1:
+ return False
+
+ intersection_width = max(0.0, min(first[2], second[2]) - max(first[0], second[0]))
+ intersection_height = max(0.0, min(first[3], second[3]) - max(first[1], second[1]))
+ intersection = intersection_width * intersection_height
+ union_area = first_width * first_height + second_width * second_height - intersection
+ return union_area > 0 and intersection / union_area >= 0.9
+
+
def _build_marginal_candidate(
page_index: int,
line: _LineItem,
diff --git a/mineru/backend/flash/native_pdf/graphics.py b/mineru/backend/flash/native_pdf/graphics.py
index 6ea0577d..ab08d04a 100644
--- a/mineru/backend/flash/native_pdf/graphics.py
+++ b/mineru/backend/flash/native_pdf/graphics.py
@@ -10,6 +10,7 @@ from typing import Any
from mineru.types import BBox
+from mineru.utils.pdf_document import PDFPathInfo
from .models import (
_AxisLine,
@@ -152,11 +153,14 @@ def _build_graphic_like_blocks(
source: _PageSource,
table_bboxes: list[BBox],
claimed_line_indices: set[int],
+ strong_core_bboxes: list[BBox] | None = None,
) -> tuple[list[dict[str, Any]], set[int]]:
"""在表格认领后把紧凑绘图组件及其短标签聚成内部图形文本块。"""
lines = [line for line in source.lines if line.source_index not in claimed_line_indices]
- if len(lines) < 2 or len(source.drawing_lines) < 4:
+ if strong_core_bboxes is None:
+ strong_core_bboxes = _detect_strong_graphic_bboxes(source)
+ if len(lines) < 2 or (len(source.drawing_lines) < 4 and not strong_core_bboxes):
return [], set()
effective_heights = [
@@ -172,13 +176,43 @@ def _build_graphic_like_blocks(
]
median_height = statistics.median(effective_heights)
lanes = _infer_graphic_text_lanes(lines, source.page_size, median_height)
- candidates = _detect_graphic_candidates(
+ line_candidates = _detect_graphic_candidates(
source.drawing_lines,
source.page_size,
median_height,
lanes,
table_bboxes,
)
+ # 复杂 Path 或成对坐标轴形成的强图形核心优先于普通绘图线组件,
+ # 避免同一图表被拆成多个相互重叠的 image。
+ candidates = [
+ candidate
+ for candidate in line_candidates
+ if not any(
+ _bbox_overlap_in_smaller(candidate.core_bbox, core_bbox) >= 0.5
+ for core_bbox in strong_core_bboxes
+ )
+ ]
+ candidates.extend(
+ _GraphicCandidate(
+ core_bbox=core_bbox,
+ lane_index=-1,
+ label_margin_scale=(
+ 2.5
+ if any(
+ _bbox_overlap_in_smaller(candidate.core_bbox, core_bbox) >= 0.5
+ and _bbox_area(candidate.core_bbox) >= 0.8 * _bbox_area(core_bbox)
+ for candidate in line_candidates
+ )
+ else 1.0
+ ),
+ )
+ for core_bbox in strong_core_bboxes
+ if not any(
+ _bbox_overlap_in_smaller(core_bbox, table_bbox) >= 0.5
+ for table_bbox in table_bboxes
+ )
+ )
if not candidates:
return [], set()
@@ -198,10 +232,15 @@ def _build_graphic_like_blocks(
row_lane_index = _graphic_lane_index(row_lines[0].bbox, lanes)
matches: list[tuple[int, float, int]] = []
for candidate_index, candidate in enumerate(candidates):
- if candidate.lane_index != row_lane_index:
+ if candidate.lane_index >= 0 and candidate.lane_index != row_lane_index:
continue
member_flags = [
- _is_graphic_label_member(line, candidate.core_bbox, median_height)
+ _is_graphic_label_member(
+ line,
+ candidate.core_bbox,
+ median_height,
+ margin_scale=candidate.label_margin_scale,
+ )
for line in row_lines
]
# 同一 pdftext 视觉行必须整体归属或整体保留,避免只吞掉 caption 的短碎片。
@@ -244,6 +283,203 @@ def _build_graphic_like_blocks(
return blocks, claimed
+def _detect_strong_graphic_bboxes(source: _PageSource) -> list[BBox]:
+ """仅按复杂 Path、容器尺度与成对坐标轴识别高置信图形核心。"""
+
+ if not source.path_infos:
+ return []
+ effective_heights = [
+ _line_effective_height(line, line.bbox)
+ for line in source.lines
+ if line.angle == 0
+ ]
+ median_height = statistics.median(effective_heights) if effective_heights else 1.0
+ candidates = [
+ *_detect_complex_path_containers(
+ source.path_infos,
+ source.page_size,
+ median_height,
+ ),
+ *_detect_axis_path_graphics(
+ source.path_infos,
+ source.page_size,
+ median_height,
+ ),
+ *_detect_complex_drawing_components(
+ source.drawing_lines,
+ source.path_infos,
+ source.page_size,
+ median_height,
+ ),
+ ]
+
+ output: list[BBox] = []
+ for bbox in sorted(candidates, key=_bbox_area, reverse=True):
+ if any(_bbox_overlap_in_first(bbox, accepted) >= 0.9 for accepted in output):
+ continue
+ output.append(bbox)
+ return sorted(output, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))
+
+
+def _detect_complex_path_containers(
+ path_infos: list[PDFPathInfo],
+ page_size: tuple[float, float],
+ median_height: float,
+) -> list[BBox]:
+ """筛选包含多个内部 Path 且至少含一个二维复杂轮廓的大容器。"""
+
+ page_area = max(0.1, page_size[0] * page_size[1])
+ output: list[BBox] = []
+ for path_info in path_infos:
+ bbox = path_info.bbox
+ width = bbox[2] - bbox[0]
+ height = bbox[3] - bbox[1]
+ area_ratio = _bbox_area(bbox) / page_area
+ if (
+ path_info.form_depth != 0
+ or not path_info.fill_visible
+ or not 0.005 <= area_ratio <= 0.5
+ or width < 4.0 * median_height
+ or height < 4.0 * median_height
+ ):
+ continue
+ inner_paths = [
+ item
+ for item in path_infos
+ if item.source_index != path_info.source_index
+ and _bbox_overlap_in_first(item.bbox, bbox) >= 0.9
+ and _bbox_area(item.bbox) < 0.95 * _bbox_area(bbox)
+ ]
+ if len(inner_paths) < 4:
+ continue
+ if not any(_is_two_dimensional_complex_path(item, median_height) for item in inner_paths):
+ continue
+ output.append(bbox)
+ return output
+
+
+def _detect_axis_path_graphics(
+ path_infos: list[PDFPathInfo],
+ page_size: tuple[float, float],
+ median_height: float,
+) -> list[BBox]:
+ """用相交的长横纵轴和内部二维复杂路径补充无外框图表。"""
+
+ thin_limit = max(1.0, 0.5 * median_height)
+ minimum_axis_length = 6.0 * median_height
+ horizontal_axes = [
+ item
+ for item in path_infos
+ if item.form_depth == 0
+ and item.stroke_visible
+ and item.bbox[3] - item.bbox[1] <= thin_limit
+ and item.bbox[2] - item.bbox[0] >= minimum_axis_length
+ ]
+ vertical_axes = [
+ item
+ for item in path_infos
+ if item.form_depth == 0
+ and item.stroke_visible
+ and item.bbox[2] - item.bbox[0] <= thin_limit
+ and item.bbox[3] - item.bbox[1] >= minimum_axis_length
+ ]
+ tolerance = max(2.0, median_height)
+ output: list[BBox] = []
+ for horizontal in horizontal_axes:
+ horizontal_y = _bbox_center_y(horizontal.bbox)
+ for vertical in vertical_axes:
+ vertical_x = _bbox_center_x(vertical.bbox)
+ touches_x = min(
+ abs(vertical_x - horizontal.bbox[0]),
+ abs(vertical_x - horizontal.bbox[2]),
+ ) <= tolerance
+ touches_y = min(
+ abs(horizontal_y - vertical.bbox[1]),
+ abs(horizontal_y - vertical.bbox[3]),
+ ) <= tolerance
+ if not (touches_x and touches_y):
+ continue
+ plot_bbox = _bbox_union(horizontal.bbox, vertical.bbox)
+ width = plot_bbox[2] - plot_bbox[0]
+ height = plot_bbox[3] - plot_bbox[1]
+ if width > 0.65 * page_size[0] or height > 0.5 * page_size[1]:
+ continue
+ complex_paths = [
+ item
+ for item in path_infos
+ if _is_two_dimensional_complex_path(item, median_height)
+ and _bbox_overlap_in_smaller(item.bbox, plot_bbox) >= 0.2
+ ]
+ if not complex_paths:
+ continue
+ output.append(
+ _bbox_union(
+ plot_bbox,
+ _bbox_union_many([item.bbox for item in complex_paths]),
+ )
+ )
+ return output
+
+
+def _is_two_dimensional_complex_path(
+ path_info: PDFPathInfo,
+ median_height: float,
+) -> bool:
+ """排除细轴线,只保留横纵均有尺寸且段数较多的图形轮廓。"""
+
+ width = path_info.bbox[2] - path_info.bbox[0]
+ height = path_info.bbox[3] - path_info.bbox[1]
+ return (
+ path_info.form_depth == 0
+ and path_info.segment_count >= 6
+ and width >= 1.5 * median_height
+ and height >= 1.5 * median_height
+ )
+
+
+def _detect_complex_drawing_components(
+ drawing_lines: list[_AxisLine],
+ path_infos: list[PDFPathInfo],
+ page_size: tuple[float, float],
+ median_height: float,
+) -> list[BBox]:
+ """以横纵绘图线组件和内部二维复杂 Path 识别坐标图或嵌入式图表。"""
+
+ tolerance = max(2.0, 0.75 * median_height)
+ output: list[BBox] = []
+ for component in _connected_drawing_line_components(drawing_lines, tolerance):
+ horizontal_count = sum(line.orientation == "horizontal" for line in component)
+ vertical_count = len(component) - horizontal_count
+ core_bbox = _bbox_union_many([line.bbox for line in component])
+ width = core_bbox[2] - core_bbox[0]
+ height = core_bbox[3] - core_bbox[1]
+ if (
+ len(component) < 4
+ or horizontal_count < 2
+ or vertical_count < 2
+ or width < 4.0 * median_height
+ or height < 3.0 * median_height
+ or width > 0.65 * page_size[0]
+ or height > 0.5 * page_size[1]
+ ):
+ continue
+ complex_paths = [
+ path_info
+ for path_info in path_infos
+ if _is_two_dimensional_complex_path(path_info, median_height)
+ and _bbox_overlap_in_smaller(path_info.bbox, core_bbox) >= 0.2
+ ]
+ if not complex_paths:
+ continue
+ output.append(
+ _bbox_union(
+ core_bbox,
+ _bbox_union_many([path_info.bbox for path_info in complex_paths]),
+ )
+ )
+ return output
+
+
def _infer_graphic_text_lanes(
lines: list[_LineItem],
page_size: tuple[float, float],
@@ -365,6 +601,8 @@ def _is_graphic_label_member(
line: _LineItem,
core_bbox: BBox,
median_height: float,
+ *,
+ margin_scale: float = 2.5,
) -> bool:
"""判断短文本是否位于图形核心内部或对应轴向的邻近标签区。"""
@@ -392,11 +630,19 @@ def _is_graphic_label_member(
horizontal_gap = max(core_bbox[0] - line.bbox[2], line.bbox[0] - core_bbox[2], 0.0)
vertical_gap = max(core_bbox[1] - line.bbox[3], line.bbox[1] - core_bbox[3], 0.0)
if _bbox_axis_overlap_ratio(line.bbox, core_bbox, axis="x") >= 0.15:
- return vertical_gap <= 2.5 * median_height
+ return vertical_gap <= margin_scale * median_height
if _bbox_axis_overlap_ratio(line.bbox, core_bbox, axis="y") >= 0.15:
- horizontal_limit = max(2.5 * median_height, 0.2 * (core_bbox[2] - core_bbox[0]))
+ horizontal_limit = max(
+ margin_scale * median_height,
+ 0.2 * (core_bbox[2] - core_bbox[0]),
+ )
return horizontal_gap <= horizontal_limit
- return False
+ corner_limit = min(margin_scale, 1.5) * median_height
+ return (
+ horizontal_gap <= corner_limit
+ and vertical_gap <= corner_limit
+ and math.hypot(horizontal_gap, vertical_gap) <= corner_limit
+ )
def _image_members_to_content(
diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.py
index 9c5a7f8e..1cc3efcf 100644
--- a/mineru/backend/flash/native_pdf/models.py
+++ b/mineru/backend/flash/native_pdf/models.py
@@ -77,7 +77,7 @@ class _LocalAxisLine:
@dataclass(slots=True)
class _TableCandidate:
- """保存已通过三横线与文本分布校验的表格候选。"""
+ """保存已通过相邻横线边界与文本分布校验的表格候选。"""
bbox: BBox
local_bbox: BBox
@@ -93,6 +93,7 @@ class _GraphicCandidate:
core_bbox: BBox
lane_index: int
+ label_margin_scale: float = 2.5
line_indices: set[int] = field(default_factory=set)
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 693e26c4..b45e4384 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -45,6 +45,7 @@ from .graphics import (
_build_form_image_blocks,
_build_graphic_like_blocks,
_build_raster_image_blocks,
+ _detect_strong_graphic_bboxes,
_form_supersedes_nested_bbox,
_select_form_image_bboxes,
)
@@ -55,6 +56,7 @@ from .formulas import (
from .auxiliary_text import (
_classify_page_auxiliary_text,
_classify_repeated_page_marginals,
+ _classify_repeated_visual_headers,
)
from .titles import _classify_page_titles
from .text_blocks import _build_text_blocks
@@ -98,6 +100,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
)
prepared_pages.append(_prepare_page_source(source))
+ _classify_repeated_visual_headers(prepared_pages)
_classify_repeated_page_marginals(prepared_pages)
return [
_finalize_prepared_page(prepared, page_index)
@@ -109,9 +112,13 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
"""先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""
form_bboxes = _select_form_image_bboxes(source)
+ strong_graphic_bboxes = _detect_strong_graphic_bboxes(source)
candidates = [
candidate
- for candidate in _detect_table_candidates(source)
+ for candidate in _detect_table_candidates(
+ source,
+ excluded_bboxes=strong_graphic_bboxes,
+ )
if not any(
_form_supersedes_nested_bbox(form_bbox, candidate.bbox)
for form_bbox in form_bboxes
@@ -140,6 +147,7 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
source,
table_bboxes + active_form_bboxes,
claimed_line_indices | claimed_form_line_indices,
+ strong_graphic_bboxes,
)
raster_image_blocks, claimed_raster_line_indices = _build_raster_image_blocks(
source,
diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.py
index 1441be46..b32e8599 100644
--- a/mineru/backend/flash/native_pdf/tables.py
+++ b/mineru/backend/flash/native_pdf/tables.py
@@ -12,6 +12,7 @@ from loguru import logger
from mineru.backend.hybrid.table_text import project_pdf_table_text
from mineru.types import BBox
+from mineru.utils.pdf_document import PDFPathInfo
from .models import (
_Fragment,
@@ -22,12 +23,14 @@ from .models import (
_VisualRow,
)
from .geometry import (
+ _bbox_area,
_bbox_axis_overlap_ratio,
_bbox_center_x,
_bbox_center_y,
_bbox_overlap_in_smaller,
_bbox_union,
_bbox_union_many,
+ _expand_bbox,
_point_in_bbox,
_rotate_bbox_from_upright,
_rotate_bbox_to_upright,
@@ -57,10 +60,26 @@ _TABLE_SPLIT_NUMBER_RE = re.compile(
)
-def _detect_table_candidates(source: _PageSource) -> list[_TableCandidate]:
- """按文本方向融合三条长横线与规则文本分布,生成表格候选。"""
+_FILLED_GRID_MIN_PAGE_AREA_RATIO = 0.005
+_FILLED_GRID_MAX_PAGE_AREA_RATIO = 0.25
+_FILLED_GRID_MIN_PAGE_WIDTH_RATIO = 0.12
+_FILLED_GRID_MIN_PAGE_HEIGHT_RATIO = 0.03
- candidates: list[_TableCandidate] = []
+
+def _detect_table_candidates(
+ source: _PageSource,
+ excluded_bboxes: list[BBox] | None = None,
+) -> list[_TableCandidate]:
+ """按文本方向融合横线区间、规则文本和填充行带,生成表格候选。"""
+
+ excluded_bboxes = excluded_bboxes or []
+ filled_grid_candidates = _detect_filled_grid_table_candidates(
+ source.path_infos,
+ source.page_size,
+ excluded_bboxes,
+ )
+ filled_grid_bboxes = [candidate.bbox for candidate in filled_grid_candidates]
+ rule_candidates: list[_TableCandidate] = []
angles = sorted({line.angle for line in source.lines})
for angle in angles:
angle_lines = [line for line in source.lines if line.angle == angle]
@@ -76,7 +95,14 @@ def _detect_table_candidates(source: _PageSource) -> list[_TableCandidate]:
source.page_size,
angle,
)
- candidates.extend(
+ local_excluded_bboxes = [
+ _expand_bbox(
+ _rotate_bbox_to_upright(bbox, source.page_size, angle),
+ 2.5 * median_height,
+ )
+ for bbox in [*excluded_bboxes, *filled_grid_bboxes]
+ ]
+ rule_candidates.extend(
_build_rule_table_candidates(
rows,
angle_lines,
@@ -84,9 +110,254 @@ def _detect_table_candidates(source: _PageSource) -> list[_TableCandidate]:
angle,
median_height,
local_axis_lines,
+ path_infos=source.path_infos,
+ excluded_bboxes=local_excluded_bboxes,
+ )
+ )
+ merged_rule_candidates = [
+ candidate
+ for candidate in _merge_table_candidates(rule_candidates)
+ if not any(
+ _bbox_overlap_in_smaller(candidate.bbox, filled_bbox) >= 0.2
+ for filled_bbox in filled_grid_bboxes
+ )
+ ]
+ return sorted(
+ [*filled_grid_candidates, *merged_rule_candidates],
+ key=lambda candidate: (candidate.bbox[1], candidate.bbox[0]),
+ )
+
+
+def _detect_filled_grid_table_candidates(
+ path_infos: list[PDFPathInfo],
+ page_size: tuple[float, float],
+ excluded_bboxes: list[BBox] | None = None,
+) -> list[_TableCandidate]:
+ """仅按根层填充矩形的嵌套行带识别精确表格外框。"""
+
+ page_width, page_height = page_size
+ page_area = page_width * page_height
+ if page_area <= 0:
+ return []
+ excluded_bboxes = excluded_bboxes or []
+ rectangles = [
+ path_info.bbox
+ for path_info in path_infos
+ if path_info.form_depth == 0
+ and path_info.fill_visible
+ and path_info.segment_count == 5
+ and _bbox_area(path_info.bbox) > 0
+ ]
+ evidence: list[tuple[_TableCandidate, int, float, float]] = []
+ for outer_bbox in rectangles:
+ outer_width = outer_bbox[2] - outer_bbox[0]
+ outer_height = outer_bbox[3] - outer_bbox[1]
+ outer_area = _bbox_area(outer_bbox)
+ if not (
+ _FILLED_GRID_MIN_PAGE_AREA_RATIO
+ <= outer_area / page_area
+ <= _FILLED_GRID_MAX_PAGE_AREA_RATIO
+ and outer_width >= _FILLED_GRID_MIN_PAGE_WIDTH_RATIO * page_width
+ and outer_height >= _FILLED_GRID_MIN_PAGE_HEIGHT_RATIO * page_height
+ ):
+ continue
+ if any(
+ _bbox_overlap_in_smaller(outer_bbox, excluded_bbox) >= 0.5
+ for excluded_bbox in excluded_bboxes
+ ):
+ continue
+
+ cells = _select_maximal_filled_grid_cells(rectangles, outer_bbox)
+ bands = _group_filled_grid_cells_into_bands(cells, outer_bbox)
+ accepted_bands = [
+ band
+ for band in bands
+ if _filled_grid_band_covers_outer_width(band, outer_bbox)
+ ]
+ if len(accepted_bands) < 4:
+ continue
+ accepted_bands.sort(
+ key=lambda band: (
+ min(cell[1] for cell in band),
+ min(cell[0] for cell in band),
+ )
+ )
+ covered_height = sum(
+ max(cell[3] for cell in band) - min(cell[1] for cell in band)
+ for band in accepted_bands
+ )
+ vertical_coverage = covered_height / outer_height
+ if vertical_coverage < 0.75:
+ continue
+ if any(
+ min(cell[1] for cell in next_band)
+ - max(cell[3] for cell in current_band)
+ > 0.05 * outer_height
+ for current_band, next_band in zip(
+ accepted_bands,
+ accepted_bands[1:],
+ )
+ ):
+ continue
+ candidate = _TableCandidate(
+ bbox=outer_bbox,
+ local_bbox=outer_bbox,
+ angle=0,
+ score=float(100.0 + len(accepted_bands) + vertical_coverage),
+ core_bbox=outer_bbox,
+ line_indices=set(),
+ )
+ evidence.append(
+ (
+ candidate,
+ len(accepted_bands),
+ vertical_coverage,
+ outer_area,
)
)
- return _merge_table_candidates(candidates)
+
+ output: list[_TableCandidate] = []
+ for candidate, _band_count, _coverage, _outer_area in sorted(
+ evidence,
+ key=lambda item: (item[1], item[2], item[3]),
+ reverse=True,
+ ):
+ if any(
+ _bbox_overlap_in_smaller(candidate.bbox, accepted.bbox) >= 0.9
+ for accepted in output
+ ):
+ continue
+ output.append(candidate)
+ return sorted(output, key=lambda candidate: (candidate.bbox[1], candidate.bbox[0]))
+
+
+def _select_maximal_filled_grid_cells(
+ rectangles: list[BBox],
+ outer_bbox: BBox,
+) -> list[BBox]:
+ """移除边缘细条、重复 Path 和同跨度半行底纹,保留最大单元格。"""
+
+ outer_width = outer_bbox[2] - outer_bbox[0]
+ outer_height = outer_bbox[3] - outer_bbox[1]
+ outer_area = _bbox_area(outer_bbox)
+ x_tolerance = 0.01 * outer_width
+ y_tolerance = 0.02 * outer_height
+ nested_rectangles = [
+ rectangle
+ for rectangle in rectangles
+ if rectangle != outer_bbox
+ and _bbox_is_contained_with_tolerance(
+ rectangle,
+ outer_bbox,
+ x_tolerance,
+ y_tolerance,
+ )
+ and _bbox_area(rectangle) <= 0.8 * outer_area
+ and rectangle[2] - rectangle[0] >= 0.1 * outer_width
+ and rectangle[3] - rectangle[1] >= 0.06 * outer_height
+ ]
+ output: list[BBox] = []
+ for rectangle in sorted(
+ nested_rectangles,
+ key=lambda bbox: (-_bbox_area(bbox), bbox[1], bbox[0]),
+ ):
+ if any(
+ rectangle != other
+ and _bbox_is_contained_with_tolerance(
+ rectangle,
+ other,
+ x_tolerance,
+ y_tolerance,
+ )
+ and _bbox_area(other) >= 1.08 * _bbox_area(rectangle)
+ and _bbox_area(other) <= 0.8 * outer_area
+ and abs(
+ (rectangle[2] - rectangle[0])
+ - (other[2] - other[0])
+ )
+ <= 0.01 * outer_width
+ for other in nested_rectangles
+ ):
+ continue
+ if any(
+ _bbox_overlap_in_smaller(rectangle, accepted) >= 0.95
+ for accepted in output
+ ):
+ continue
+ output.append(rectangle)
+ return sorted(output, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))
+
+
+def _bbox_is_contained_with_tolerance(
+ inner_bbox: BBox,
+ outer_bbox: BBox,
+ x_tolerance: float,
+ y_tolerance: float,
+) -> bool:
+ """按横纵独立容差判断一个矩形是否完整位于另一个矩形内。"""
+
+ return (
+ inner_bbox[0] >= outer_bbox[0] - x_tolerance
+ and inner_bbox[1] >= outer_bbox[1] - y_tolerance
+ and inner_bbox[2] <= outer_bbox[2] + x_tolerance
+ and inner_bbox[3] <= outer_bbox[3] + y_tolerance
+ )
+
+
+def _group_filled_grid_cells_into_bands(
+ cells: list[BBox],
+ outer_bbox: BBox,
+) -> list[list[BBox]]:
+ """按相近上下边界把最大填充单元格聚成水平行带。"""
+
+ y_tolerance = 0.02 * (outer_bbox[3] - outer_bbox[1])
+ bands: list[list[BBox]] = []
+ for cell in sorted(cells, key=lambda bbox: (bbox[1], bbox[0], bbox[3])):
+ target = next(
+ (
+ band
+ for band in bands
+ if abs(cell[1] - band[0][1]) <= y_tolerance
+ and abs(cell[3] - band[0][3]) <= y_tolerance
+ ),
+ None,
+ )
+ if target is None:
+ bands.append([cell])
+ else:
+ target.append(cell)
+ return bands
+
+
+def _filled_grid_band_covers_outer_width(
+ band: list[BBox],
+ outer_bbox: BBox,
+) -> bool:
+ """校验单个填充行带的单元格数量、横向覆盖、间隙和端点。"""
+
+ if len(band) < 2:
+ return False
+ outer_width = outer_bbox[2] - outer_bbox[0]
+ segments = sorted((cell[0], cell[2]) for cell in band)
+ current_left, current_right = segments[0]
+ covered_width = 0.0
+ maximum_gap = 0.0
+ for left, right in segments[1:]:
+ if left <= current_right:
+ current_right = max(current_right, right)
+ continue
+ covered_width += current_right - current_left
+ maximum_gap = max(maximum_gap, left - current_right)
+ current_left, current_right = left, right
+ covered_width += current_right - current_left
+ return (
+ covered_width >= 0.9 * outer_width
+ and maximum_gap <= 0.01 * outer_width
+ and abs(min(cell[0] for cell in band) - outer_bbox[0])
+ <= 0.02 * outer_width
+ and abs(max(cell[2] for cell in band) - outer_bbox[2])
+ <= 0.02 * outer_width
+ )
def _build_fragments(
@@ -174,37 +445,134 @@ def _build_rule_table_candidates(
angle: int,
median_height: float,
axis_lines: list[_LocalAxisLine],
+ *,
+ path_infos: list[PDFPathInfo] | None = None,
+ excluded_bboxes: list[BBox] | None = None,
) -> list[_TableCandidate]:
- """用三条长横线确定区域,再以连续多列文本分布确认表格。"""
+ """枚举同跨度横线边界区间,再以连续多列文本分布确认表格。"""
candidates: list[_TableCandidate] = []
+ path_infos = path_infos or []
+ excluded_bboxes = excluded_bboxes or []
for rule_group in _group_long_horizontal_rules(axis_lines, median_height):
- rule_bbox = _bbox_union_many([line.bbox for line in rule_group])
- core_rows: list[_VisualRow] = []
- for row in rows:
- clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=0.0)
- if clipped_row is not None and rule_bbox[1] <= clipped_row.center_y <= rule_bbox[3]:
- core_rows.append(clipped_row)
-
- dense_rows = _longest_dense_multi_cell_rows(core_rows, median_height)
- if len(dense_rows) < 3:
- continue
- stable_columns, column_coverage = _count_stable_columns(dense_rows, median_height)
- if stable_columns < 2 or column_coverage < 0.5:
- continue
-
- caption_line = _find_table_caption(lines, rule_bbox, page_size, angle, median_height)
- candidate = _expand_rule_table_candidate(
- rule_group,
- core_rows,
- rows,
- page_size,
- angle,
- median_height,
- caption_line,
- )
- candidate.score = float(len(rule_group) + len(dense_rows) + stable_columns)
- candidates.append(candidate)
+ for first_index, top_rule in enumerate(rule_group[:-1]):
+ for bottom_index in range(first_index + 1, len(rule_group)):
+ bottom_rule = rule_group[bottom_index]
+ boundary_rules = [top_rule, bottom_rule]
+ rule_bbox = _bbox_union_many([line.bbox for line in boundary_rules])
+ core_rows = _rows_inside_rule_interval(
+ rows,
+ rule_bbox,
+ excluded_bboxes,
+ )
+ if not _every_rule_interval_has_multi_cell_row(
+ core_rows,
+ rule_group[first_index : bottom_index + 1],
+ median_height,
+ ):
+ continue
+ if not _rule_intervals_are_column_compatible(
+ core_rows,
+ rule_group[first_index : bottom_index + 1],
+ median_height,
+ ):
+ continue
+
+ fill_band_count = _count_repeated_fill_bands(
+ path_infos,
+ rule_bbox,
+ page_size,
+ angle,
+ median_height,
+ )
+ aligned_vertical_count = _count_aligned_vertical_rules(
+ axis_lines,
+ rule_bbox,
+ median_height,
+ )
+
+ row_segments = _continuous_table_row_segments(core_rows, median_height)
+ accepted: tuple[list[_VisualRow], list[_VisualRow], int, float] | None = None
+ for row_segment in row_segments:
+ dense_rows = [row for row in row_segment if len(row.fragments) >= 2]
+ if len(dense_rows) < 3:
+ continue
+ # 真表格的多单元行会在整个数据带内反复出现;少数图题、图例和
+ # 坐标刻度偶然形成的多列行不能支撑一大片正文区域。
+ if len(dense_rows) / len(row_segment) < 0.2:
+ continue
+ stable_columns, column_coverage = _count_stable_columns(
+ dense_rows,
+ median_height,
+ )
+ if stable_columns < 2 or column_coverage < 0.5:
+ continue
+ if _looks_like_page_column_prose(
+ row_segment,
+ dense_rows,
+ stable_columns,
+ fill_band_count,
+ aligned_vertical_count,
+ rule_bbox,
+ ):
+ continue
+ if not _table_segment_reaches_boundaries(
+ row_segment,
+ rule_bbox,
+ median_height,
+ ):
+ continue
+ if not _table_rows_align_with_rule_span(
+ row_segment,
+ rule_bbox,
+ median_height,
+ ):
+ continue
+ result = (
+ row_segment,
+ dense_rows,
+ stable_columns,
+ column_coverage,
+ )
+ if accepted is None or (
+ len(row_segment),
+ len(dense_rows),
+ stable_columns,
+ column_coverage,
+ ) > (
+ len(accepted[0]),
+ len(accepted[1]),
+ accepted[2],
+ accepted[3],
+ ):
+ accepted = result
+ if accepted is None:
+ continue
+
+ accepted_rows, dense_rows, stable_columns, _coverage = accepted
+ caption_line = _find_table_caption(
+ lines,
+ rule_bbox,
+ page_size,
+ angle,
+ median_height,
+ )
+ candidate = _expand_rule_table_candidate(
+ boundary_rules,
+ accepted_rows,
+ rows,
+ page_size,
+ angle,
+ median_height,
+ caption_line,
+ )
+ candidate.score = float(
+ 2
+ + len(dense_rows)
+ + stable_columns
+ + min(fill_band_count, 8)
+ )
+ candidates.append(candidate)
return candidates
@@ -212,7 +580,7 @@ def _group_long_horizontal_rules(
axis_lines: list[_LocalAxisLine],
median_height: float,
) -> list[list[_LocalAxisLine]]:
- """按近似左右端点和纵向距离聚合长横线,并去除同位置重复路径。"""
+ """按近似左右端点聚合长横线,并去除同位置重复路径。"""
minimum_length = max(40.0, 10.0 * median_height)
horizontal_lines = [
@@ -236,29 +604,274 @@ def _group_long_horizontal_rules(
target.append(line)
output: list[list[_LocalAxisLine]] = []
- maximum_vertical_gap = 24.0 * median_height
for span_group in span_groups:
- vertical_groups: list[list[_LocalAxisLine]] = []
+ unique_lines: list[_LocalAxisLine] = []
for line in sorted(span_group, key=lambda item: _bbox_center_y(item.bbox)):
- if (
- not vertical_groups
- or _bbox_center_y(line.bbox) - _bbox_center_y(vertical_groups[-1][-1].bbox) > maximum_vertical_gap
+ if any(
+ abs(_bbox_center_y(line.bbox) - _bbox_center_y(item.bbox)) <= 1.0
+ for item in unique_lines
):
- vertical_groups.append([line])
- else:
- vertical_groups[-1].append(line)
-
- for vertical_group in vertical_groups:
- unique_lines: list[_LocalAxisLine] = []
- for line in vertical_group:
- if any(abs(_bbox_center_y(line.bbox) - _bbox_center_y(item.bbox)) <= 1.0 for item in unique_lines):
- continue
- unique_lines.append(line)
- if len(unique_lines) >= 3:
- output.append(unique_lines)
+ continue
+ unique_lines.append(line)
+ if len(unique_lines) >= 2:
+ output.append(unique_lines)
+ return output
+
+
+def _rows_inside_rule_interval(
+ rows: list[_VisualRow],
+ rule_bbox: BBox,
+ excluded_bboxes: list[BBox],
+) -> list[_VisualRow]:
+ """截取边界走廊内文本行,并移除已由强图形核心覆盖的片段。"""
+
+ output: list[_VisualRow] = []
+ for row in rows:
+ clipped_row = _clip_visual_row_to_corridor(row, rule_bbox, margin=0.0)
+ if clipped_row is None or not rule_bbox[1] <= clipped_row.center_y <= rule_bbox[3]:
+ continue
+ fragments = [
+ fragment
+ for fragment in clipped_row.fragments
+ if not any(
+ _point_in_bbox(
+ (
+ _bbox_center_x(fragment.local_bbox),
+ _bbox_center_y(fragment.local_bbox),
+ ),
+ excluded_bbox,
+ )
+ for excluded_bbox in excluded_bboxes
+ )
+ ]
+ if not fragments:
+ continue
+ output.append(
+ _VisualRow(
+ fragments=fragments,
+ center_y=sum(
+ _bbox_center_y(fragment.local_bbox) for fragment in fragments
+ )
+ / len(fragments),
+ bbox=_bbox_union_many([fragment.local_bbox for fragment in fragments]),
+ visual_row_id=clipped_row.visual_row_id,
+ )
+ )
return output
+def _every_rule_interval_has_multi_cell_row(
+ rows: list[_VisualRow],
+ rule_group: list[_LocalAxisLine],
+ median_height: float,
+) -> bool:
+ """要求候选跨过的每个相邻横线区间都存在至少一行多单元文本。"""
+
+ if len(rule_group) < 2:
+ return False
+ for interval_index, (top_rule, bottom_rule) in enumerate(
+ zip(rule_group, rule_group[1:])
+ ):
+ top = _bbox_center_y(top_rule.bbox)
+ bottom = _bbox_center_y(bottom_rule.bbox)
+ interval_rows = [row for row in rows if top <= row.center_y <= bottom]
+ if any(len(row.fragments) >= 2 for row in interval_rows):
+ continue
+ # 紧邻顶边界的合并表头可能由 pdftext 输出为一个短 fragment;
+ # 只放宽高度很小的首区间,避免把远处章节标题接到表格上。
+ if (
+ interval_index == 0
+ and interval_rows
+ and bottom - top <= 2.5 * median_height
+ ):
+ continue
+ return False
+ return True
+
+
+def _rule_intervals_are_column_compatible(
+ rows: list[_VisualRow],
+ rule_group: list[_LocalAxisLine],
+ median_height: float,
+) -> bool:
+ """拒绝跨过长篇栏式正文、导致稳定列数明显塌缩的多表合并区间。"""
+
+ profiles: list[tuple[int, float]] = []
+ for top_rule, bottom_rule in zip(rule_group, rule_group[1:]):
+ top = _bbox_center_y(top_rule.bbox)
+ bottom = _bbox_center_y(bottom_rule.bbox)
+ interval_rows = [
+ row
+ for row in rows
+ if top <= row.center_y <= bottom and len(row.fragments) >= 2
+ ]
+ stable_columns, _coverage = _count_stable_columns(
+ interval_rows,
+ median_height,
+ )
+ profiles.append((stable_columns, bottom - top))
+ maximum_columns = max((columns for columns, _height in profiles), default=0)
+ if maximum_columns < 4:
+ return True
+ for interval_index, (columns, interval_height) in enumerate(profiles):
+ # 首个区间可能只是跨列表头;后续长区间若退化成普通双栏正文,
+ # 就不能把前后两张表合成一个候选。
+ if interval_index == 0:
+ continue
+ if columns < max(2, int(0.5 * maximum_columns)) and interval_height > 4.0 * median_height:
+ return False
+ return True
+
+
+def _continuous_table_row_segments(
+ rows: list[_VisualRow],
+ median_height: float,
+) -> list[list[_VisualRow]]:
+ """按物理行距切分边界区间,保留单元格换行参与连续性判断。"""
+
+ segments: list[list[_VisualRow]] = []
+ for row in sorted(rows, key=lambda item: item.center_y):
+ if (
+ not segments
+ or max(0.0, row.bbox[1] - segments[-1][-1].bbox[3])
+ > 3.0 * median_height
+ ):
+ segments.append([row])
+ else:
+ segments[-1].append(row)
+ return segments
+
+
+def _table_segment_reaches_boundaries(
+ rows: list[_VisualRow],
+ rule_bbox: BBox,
+ median_height: float,
+) -> bool:
+ """要求数据行链分别贴近最近的上下边界,排除页眉线和远处章节标题。"""
+
+ if not rows:
+ return False
+ maximum_gap = 2.5 * median_height
+ top_gap = max(0.0, rows[0].bbox[1] - rule_bbox[1])
+ bottom_gap = max(0.0, rule_bbox[3] - rows[-1].bbox[3])
+ return top_gap <= maximum_gap and bottom_gap <= maximum_gap
+
+
+def _table_rows_align_with_rule_span(
+ rows: list[_VisualRow],
+ rule_bbox: BBox,
+ median_height: float,
+) -> bool:
+ """校验数据行总体跨度与横线走廊重叠,拒绝仅在边缘偶遇的多列文本。"""
+
+ if not rows:
+ return False
+ rows_bbox = _bbox_union_many([row.bbox for row in rows])
+ rule_width = max(0.1, rule_bbox[2] - rule_bbox[0])
+ rows_width = max(0.1, rows_bbox[2] - rows_bbox[0])
+ overlap = max(
+ 0.0,
+ min(rows_bbox[2], rule_bbox[2]) - max(rows_bbox[0], rule_bbox[0]),
+ )
+ return (
+ overlap / min(rule_width, rows_width) >= 0.9
+ and rows_width >= max(8.0 * median_height, 0.25 * rule_width)
+ )
+
+
+def _count_aligned_vertical_rules(
+ axis_lines: list[_LocalAxisLine],
+ rule_bbox: BBox,
+ median_height: float,
+) -> int:
+ """统计贯穿候选主要高度且位于横线跨度内的竖向分隔线。"""
+
+ required_height = max(4.0 * median_height, 0.5 * (rule_bbox[3] - rule_bbox[1]))
+ return sum(
+ line.orientation == "vertical"
+ and rule_bbox[0] - median_height <= _bbox_center_x(line.bbox) <= rule_bbox[2] + median_height
+ and line.bbox[3] - line.bbox[1] >= required_height
+ and _bbox_axis_overlap_ratio(line.bbox, rule_bbox, axis="y") >= 0.8
+ for line in axis_lines
+ )
+
+
+def _looks_like_page_column_prose(
+ rows: list[_VisualRow],
+ dense_rows: list[_VisualRow],
+ stable_columns: int,
+ fill_band_count: int,
+ aligned_vertical_count: int,
+ rule_bbox: BBox,
+) -> bool:
+ """用双栏占宽率识别夹在远横线间的普通并排正文。"""
+
+ if (
+ stable_columns != 2
+ or fill_band_count >= 2
+ or aligned_vertical_count > 0
+ or len(dense_rows) / len(rows) < 0.55
+ ):
+ return False
+ corridor_width = max(0.1, rule_bbox[2] - rule_bbox[0])
+ occupied_ratios = [
+ sum(fragment.local_bbox[2] - fragment.local_bbox[0] for fragment in row.fragments)
+ / corridor_width
+ for row in dense_rows
+ ]
+ return statistics.median(occupied_ratios) >= 0.75
+
+
+def _count_repeated_fill_bands(
+ path_infos: list[PDFPathInfo],
+ rule_bbox: BBox,
+ page_size: tuple[float, float],
+ angle: int,
+ median_height: float,
+) -> int:
+ """统计区间内左右端点和高度重复的填充行带,并对重叠 Path 去重。"""
+
+ minimum_width = max(8.0 * median_height, 0.3 * (rule_bbox[2] - rule_bbox[0]))
+ candidates: list[BBox] = []
+ for path_info in path_infos:
+ if path_info.form_depth != 0 or not path_info.fill_visible:
+ continue
+ bbox = _rotate_bbox_to_upright(path_info.bbox, page_size, angle)
+ width = bbox[2] - bbox[0]
+ height = bbox[3] - bbox[1]
+ if (
+ width < minimum_width
+ or not 0.25 * median_height <= height <= 3.0 * median_height
+ or _bbox_center_y(bbox) < rule_bbox[1]
+ or _bbox_center_y(bbox) > rule_bbox[3]
+ or _bbox_axis_overlap_ratio(bbox, rule_bbox, axis="x") < 0.8
+ ):
+ continue
+ if any(_bbox_overlap_in_smaller(bbox, item) >= 0.9 for item in candidates):
+ continue
+ candidates.append(bbox)
+
+ endpoint_tolerance = max(3.0, median_height)
+ groups: list[list[BBox]] = []
+ for bbox in candidates:
+ target = next(
+ (
+ group
+ for group in groups
+ if abs(bbox[0] - group[0][0]) <= endpoint_tolerance
+ and abs(bbox[2] - group[0][2]) <= endpoint_tolerance
+ and abs((bbox[3] - bbox[1]) - (group[0][3] - group[0][1]))
+ <= endpoint_tolerance
+ ),
+ None,
+ )
+ if target is None:
+ groups.append([bbox])
+ else:
+ target.append(bbox)
+ return max((len(group) for group in groups), default=0)
+
+
def _clip_visual_row_to_corridor(
row: _VisualRow,
corridor_bbox: BBox,
diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.py
index da1d7e1b..bd23fd1c 100644
--- a/mineru/backend/flash/native_pdf/text_blocks.py
+++ b/mineru/backend/flash/native_pdf/text_blocks.py
@@ -22,6 +22,7 @@ from .models import (
_TextLane,
)
from .geometry import (
+ _bbox_axis_overlap_ratio,
_bbox_center_y,
_bbox_union_many,
_rotate_bbox_from_upright,
@@ -489,9 +490,366 @@ def _build_text_blocks(
"content": content,
"_visual_row_ids": visual_row_ids,
"_single_run_row_id": single_run_row_id,
+ "_local_line_bboxes": [bbox for _line, bbox in component_geometry],
+ "_line_heights": [
+ _line_effective_height(line, bbox)
+ for line, bbox in component_geometry
+ ],
+ "_lane_interval": (lane.left, lane.right),
+ "_lane_is_span": lane.is_span,
}
)
- return blocks
+ return _merge_spatial_text_components(blocks, page_size)
+
+
+def _merge_spatial_text_components(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """按短首行、紧邻续行和双栏递减尾行二次连接被栏带拆开的正文块。"""
+
+ parents = list(range(len(blocks)))
+
+ def find(index: int) -> int:
+ """查找正文组件所属合并组的根节点。"""
+
+ while parents[index] != index:
+ parents[index] = parents[parents[index]]
+ index = parents[index]
+ return index
+
+ def union(first_index: int, second_index: int) -> None:
+ """合并两个已经通过空间连续性校验的正文组件。"""
+
+ first_root = find(first_index)
+ second_root = find(second_index)
+ if first_root != second_root:
+ parents[second_root] = first_root
+
+ for angle in sorted(
+ {
+ int(block.get("angle", 0) or 0) % 360
+ for block in blocks
+ if block.get("type") == "text" and block.get("_local_line_bboxes")
+ }
+ ):
+ candidate_indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text"
+ and int(block.get("angle", 0) or 0) % 360 == angle
+ and isinstance(block.get("_local_line_bboxes"), list)
+ and block["_local_line_bboxes"]
+ ]
+ if len(candidate_indices) < 2:
+ continue
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ all_heights = [
+ float(height)
+ for index in candidate_indices
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ median_height = statistics.median(all_heights) if all_heights else 1.0
+ section_starts = {
+ index
+ for index in candidate_indices
+ if _block_starts_with_short_wide_rows(
+ blocks[index],
+ local_page_width,
+ )
+ }
+
+ opener_pairs = _find_short_opener_pairs(
+ blocks,
+ candidate_indices,
+ local_page_width,
+ median_height,
+ )
+ for opener_index, body_index in opener_pairs:
+ section_starts.add(opener_index)
+ union(opener_index, body_index)
+
+ for current_index in sorted(
+ candidate_indices,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ ):
+ section_roots = {find(index) for index in section_starts}
+ if find(current_index) not in section_roots:
+ continue
+ next_index = _nearest_following_text_component(
+ blocks,
+ current_index,
+ candidate_indices,
+ maximum_gap=0.75 * median_height,
+ section_starts=section_starts,
+ )
+ if next_index is not None:
+ union(current_index, next_index)
+
+ for current_index in candidate_indices:
+ if not _has_parallel_text_component(
+ blocks,
+ current_index,
+ candidate_indices,
+ ):
+ continue
+ next_index = _nearest_tapered_tail_component(
+ blocks,
+ current_index,
+ candidate_indices,
+ median_height,
+ section_starts,
+ )
+ if next_index is not None:
+ union(current_index, next_index)
+
+ grouped_indices: dict[int, list[int]] = {}
+ for index in range(len(blocks)):
+ grouped_indices.setdefault(find(index), []).append(index)
+
+ output: list[dict[str, Any]] = []
+ for indices in grouped_indices.values():
+ if len(indices) == 1:
+ output.append(blocks[indices[0]])
+ continue
+ ordered_indices = sorted(
+ indices,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ merged = dict(blocks[ordered_indices[0]])
+ merged["bbox"] = _bbox_union_many([blocks[index]["bbox"] for index in ordered_indices])
+ merged["content"] = _merge_text_line_content(
+ [str(blocks[index].get("content", "")) for index in ordered_indices]
+ )
+ merged["_visual_row_ids"] = set().union(
+ *[
+ block_ids
+ for index in ordered_indices
+ if isinstance(
+ (block_ids := blocks[index].get("_visual_row_ids")),
+ set,
+ )
+ ]
+ )
+ merged["_single_run_row_id"] = None
+ merged["_local_line_bboxes"] = [
+ bbox
+ for index in ordered_indices
+ for bbox in blocks[index].get("_local_line_bboxes", [])
+ ]
+ merged["_line_heights"] = [
+ height
+ for index in ordered_indices
+ for height in blocks[index].get("_line_heights", [])
+ ]
+ output.append(merged)
+ return output
+
+
+def _component_lane_interval(
+ block: dict[str, Any],
+) -> tuple[float, float] | None:
+ """读取普通文本组件所属的有效非跨栏栏带区间。"""
+
+ if block.get("_lane_is_span") is not False:
+ return None
+ interval = block.get("_lane_interval")
+ if (
+ not isinstance(interval, (list, tuple))
+ or len(interval) != 2
+ or not all(isinstance(value, (int, float)) for value in interval)
+ ):
+ return None
+ left, right = float(interval[0]), float(interval[1])
+ return (left, right) if right > left else None
+
+
+def _component_reference_width(
+ block: dict[str, Any],
+ local_page_width: float,
+) -> float:
+ """优先返回组件的局部栏宽,缺少可靠栏带时回退页面宽度。"""
+
+ interval = _component_lane_interval(block)
+ return interval[1] - interval[0] if interval is not None else local_page_width
+
+
+def _compatible_component_lane_width(
+ first_block: dict[str, Any],
+ second_block: dict[str, Any],
+ local_page_width: float,
+ median_height: float,
+) -> float:
+ """同一局部栏带的两个组件使用栏宽,否则继续使用页面宽度。"""
+
+ first_interval = _component_lane_interval(first_block)
+ second_interval = _component_lane_interval(second_block)
+ if first_interval is None or second_interval is None:
+ return local_page_width
+ tolerance = 0.75 * median_height
+ if (
+ abs(first_interval[0] - second_interval[0]) > tolerance
+ or abs(first_interval[1] - second_interval[1]) > tolerance
+ ):
+ return local_page_width
+ return min(
+ first_interval[1] - first_interval[0],
+ second_interval[1] - second_interval[0],
+ )
+
+
+def _block_starts_with_short_wide_rows(
+ block: dict[str, Any],
+ local_page_width: float,
+) -> bool:
+ """判断组件内部是否以短首行和紧邻宽正文形成明确分组起点。"""
+
+ line_bboxes = block.get("_local_line_bboxes")
+ if not isinstance(line_bboxes, list) or len(line_bboxes) < 2:
+ return False
+ first_bbox, second_bbox = line_bboxes[:2]
+ first_width = first_bbox[2] - first_bbox[0]
+ second_width = second_bbox[2] - second_bbox[0]
+ reference_width = _component_reference_width(block, local_page_width)
+ return (
+ first_width <= 0.35 * reference_width
+ and second_width >= max(0.25 * reference_width, 1.8 * first_width)
+ )
+
+
+def _find_short_opener_pairs(
+ blocks: list[dict[str, Any]],
+ candidate_indices: list[int],
+ local_page_width: float,
+ median_height: float,
+) -> list[tuple[int, int]]:
+ """查找跨栏拆开的短首行与紧邻满宽正文组件。"""
+
+ output: list[tuple[int, int]] = []
+ for opener_index in candidate_indices:
+ opener_bboxes = blocks[opener_index]["_local_line_bboxes"]
+ if len(opener_bboxes) != 1:
+ continue
+ opener_bbox = opener_bboxes[0]
+ opener_width = opener_bbox[2] - opener_bbox[0]
+ matches: list[tuple[float, int]] = []
+ for body_index in candidate_indices:
+ if body_index == opener_index:
+ continue
+ body_bbox = blocks[body_index]["_local_line_bboxes"][0]
+ gap = body_bbox[1] - opener_bbox[3]
+ body_width = body_bbox[2] - body_bbox[0]
+ reference_width = _compatible_component_lane_width(
+ blocks[opener_index],
+ blocks[body_index],
+ local_page_width,
+ median_height,
+ )
+ if (
+ not 0.0 <= gap <= 0.75 * median_height
+ or abs(body_bbox[0] - opener_bbox[0]) > 0.75 * median_height
+ or opener_width > 0.35 * reference_width
+ or body_width < 0.6 * reference_width
+ ):
+ continue
+ matches.append((gap, body_index))
+ if matches:
+ output.append((opener_index, min(matches)[1]))
+ return output
+
+
+def _nearest_following_text_component(
+ blocks: list[dict[str, Any]],
+ current_index: int,
+ candidate_indices: list[int],
+ *,
+ maximum_gap: float,
+ section_starts: set[int],
+) -> int | None:
+ """返回同一水平流中紧邻且不是新分组起点的下一正文组件。"""
+
+ current_bbox = blocks[current_index]["_local_line_bboxes"][-1]
+ matches: list[tuple[float, float, int]] = []
+ for candidate_index in candidate_indices:
+ if candidate_index == current_index or candidate_index in section_starts:
+ continue
+ candidate_bbox = blocks[candidate_index]["_local_line_bboxes"][0]
+ gap = candidate_bbox[1] - current_bbox[3]
+ if not -0.25 * maximum_gap <= gap <= maximum_gap:
+ continue
+ overlap = _bbox_axis_overlap_ratio(current_bbox, candidate_bbox, axis="x")
+ left_gap = abs(candidate_bbox[0] - current_bbox[0])
+ if overlap < 0.5 and left_gap > 3.0 * maximum_gap:
+ continue
+ matches.append((max(0.0, gap), left_gap, candidate_index))
+ return min(matches)[2] if matches else None
+
+
+def _has_parallel_text_component(
+ blocks: list[dict[str, Any]],
+ current_index: int,
+ candidate_indices: list[int],
+) -> bool:
+ """检查当前组件同一纵向带内是否存在水平分离的并栏组件。"""
+
+ current_bbox = blocks[current_index]["bbox"]
+ for candidate_index in candidate_indices:
+ if candidate_index == current_index:
+ continue
+ candidate_bbox = blocks[candidate_index]["bbox"]
+ vertical_overlap = max(
+ 0.0,
+ min(current_bbox[3], candidate_bbox[3])
+ - max(current_bbox[1], candidate_bbox[1]),
+ )
+ horizontally_separate = (
+ candidate_bbox[0] >= current_bbox[2]
+ or current_bbox[0] >= candidate_bbox[2]
+ )
+ if vertical_overlap > 0 and horizontally_separate:
+ return True
+ return False
+
+
+def _nearest_tapered_tail_component(
+ blocks: list[dict[str, Any]],
+ current_index: int,
+ candidate_indices: list[int],
+ median_height: float,
+ section_starts: set[int],
+) -> int | None:
+ """查找左对齐、行宽递减且行距略大的信息组尾行组件。"""
+
+ previous_bbox = blocks[current_index]["_local_line_bboxes"][-1]
+ previous_width = previous_bbox[2] - previous_bbox[0]
+ matches: list[tuple[float, int]] = []
+ for candidate_index in candidate_indices:
+ if candidate_index == current_index or candidate_index in section_starts:
+ continue
+ candidate_bboxes = blocks[candidate_index]["_local_line_bboxes"]
+ first_bbox = candidate_bboxes[0]
+ last_bbox = candidate_bboxes[-1]
+ gap = first_bbox[1] - previous_bbox[3]
+ first_width = first_bbox[2] - first_bbox[0]
+ last_width = last_bbox[2] - last_bbox[0]
+ if (
+ not 0.75 * median_height < gap <= 1.5 * median_height
+ or len(candidate_bboxes) > 2
+ or abs(first_bbox[0] - previous_bbox[0]) > 0.75 * median_height
+ or first_width > 0.85 * previous_width
+ or last_width > first_width + 0.5 * median_height
+ ):
+ continue
+ matches.append((gap, candidate_index))
+ return min(matches)[1] if matches else None
+
+
+def _text_component_sort_key(block: dict[str, Any]) -> tuple[float, float]:
+ """返回正文组件按局部首行位置排序的稳定键。"""
+
+ first_bbox = block["_local_line_bboxes"][0]
+ return first_bbox[1], first_bbox[0]
def _merge_text_line_content(line_texts: Sequence[str]) -> str:
diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.py
index dd0149ef..b66ebd49 100644
--- a/mineru/backend/flash/native_pdf/titles.py
+++ b/mineru/backend/flash/native_pdf/titles.py
@@ -56,6 +56,11 @@ def _classify_page_titles(
lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)
for lane in lanes:
lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ physical_gaps = _build_physical_title_gap_map(line_geometry)
+ grid_title_suppressions = _find_repeated_grid_title_suppressions(
+ lanes,
+ median_height,
+ )
document_title_bottom: float | None = None
if page_index == 0:
@@ -80,9 +85,115 @@ def _classify_page_titles(
local_container_bboxes,
document_title_bottom=document_title_bottom,
preserve_front_matter_boundaries=preserve_front_matter_boundaries,
+ physical_gaps=physical_gaps,
+ grid_title_suppressions=grid_title_suppressions,
)
+def _build_physical_title_gap_map(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> dict[int, tuple[float | None, float | None]]:
+ """为每行记录同方向且水平投影相交的最近上、下物理行净空。"""
+
+ output: dict[int, tuple[float | None, float | None]] = {}
+ for line, bbox in line_geometry:
+ line_center = _bbox_center_y(bbox)
+ above_gaps: list[float] = []
+ below_gaps: list[float] = []
+ for other_line, other_bbox in line_geometry:
+ if other_line is line:
+ continue
+ if _bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") < 0.1:
+ # 双栏同高度正文并非当前行的物理上下文,不能抹掉真实标题留白。
+ continue
+ if (
+ line.visual_row_id is not None
+ and other_line.visual_row_id == line.visual_row_id
+ ):
+ continue
+ other_center = _bbox_center_y(other_bbox)
+ if other_center < line_center:
+ above_gaps.append(
+ max(
+ 0.0,
+ _effective_text_row_gap(
+ (other_line, other_bbox),
+ (line, bbox),
+ ),
+ )
+ )
+ elif other_center > line_center:
+ below_gaps.append(
+ max(
+ 0.0,
+ _effective_text_row_gap(
+ (line, bbox),
+ (other_line, other_bbox),
+ ),
+ )
+ )
+ output[line.source_index] = (
+ min(above_gaps) if above_gaps else None,
+ min(below_gaps) if below_gaps else None,
+ )
+ return output
+
+
+def _find_repeated_grid_title_suppressions(
+ lanes: list[_TextLane],
+ median_height: float,
+) -> set[int]:
+ """识别重复双栏信息网格中的短首行,避免把城市等记录头标成标题。"""
+
+ candidates: list[tuple[int, int, float]] = []
+ for lane_index, lane in enumerate(lanes):
+ if lane.is_span:
+ continue
+ lane_width = max(0.1, lane.right - lane.left)
+ for row_index, (line, bbox) in enumerate(lane.lines[:-1]):
+ next_line, next_bbox = lane.lines[row_index + 1]
+ width = bbox[2] - bbox[0]
+ next_width = next_bbox[2] - next_bbox[0]
+ gap = _effective_text_row_gap(
+ (line, bbox),
+ (next_line, next_bbox),
+ )
+ if (
+ line.semantic_type is not None
+ or next_line.semantic_type is not None
+ or width > 0.35 * lane_width
+ or next_width < max(0.6 * lane_width, 1.8 * width)
+ or abs(next_bbox[0] - bbox[0]) > 0.75 * median_height
+ or not -0.25 * median_height <= gap <= 0.75 * median_height
+ ):
+ continue
+ candidates.append((lane_index, line.source_index, _bbox_center_y(bbox)))
+
+ bands: list[list[tuple[int, int, float]]] = []
+ for candidate in sorted(candidates, key=lambda item: item[2]):
+ target = next(
+ (
+ band
+ for band in bands
+ if abs(candidate[2] - statistics.median(item[2] for item in band))
+ <= 0.5 * median_height
+ ),
+ None,
+ )
+ if target is None:
+ bands.append([candidate])
+ else:
+ target.append(candidate)
+ paired_bands = [
+ {source_index for _lane_index, source_index, _center_y in band}
+ for band in bands
+ if len({lane_index for lane_index, _source_index, _center_y in band}) >= 2
+ ]
+ if len(paired_bands) < 2:
+ return set()
+ return set().union(*paired_bands)
+
+
def _infer_lane_body_profile(lane: _TextLane) -> _LaneBodyProfile:
"""从栏带的长行主体估计正文行高、主字体、字重、常规行距和样式占比。"""
@@ -236,6 +347,8 @@ def _classify_paragraph_titles_in_lane(
*,
document_title_bottom: float | None,
preserve_front_matter_boundaries: bool,
+ physical_gaps: dict[int, tuple[float | None, float | None]],
+ grid_title_suppressions: set[int],
) -> None:
"""以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""
@@ -251,6 +364,8 @@ def _classify_paragraph_titles_in_lane(
for index, (line, bbox) in enumerate(rows):
if line.semantic_type is not None:
continue
+ if line.source_index in grid_title_suppressions:
+ continue
if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
continue
inside_front_matter = (
@@ -279,8 +394,20 @@ def _classify_paragraph_titles_in_lane(
and line.dominant_font_weight is not None
and line.dominant_font_weight >= max(profile.body_weight + 100.0, 1.15 * profile.body_weight)
)
- gap_above = _normalized_title_gap(rows, index, direction=-1, body_height=profile.body_height)
- gap_below = _normalized_title_gap(rows, index, direction=1, body_height=profile.body_height)
+ gap_above = _normalized_title_gap(
+ rows,
+ index,
+ direction=-1,
+ body_height=profile.body_height,
+ physical_gaps=physical_gaps,
+ )
+ gap_below = _normalized_title_gap(
+ rows,
+ index,
+ direction=1,
+ body_height=profile.body_height,
+ physical_gaps=physical_gaps,
+ )
has_spacing_signal = gap_above >= 0.35
if _visual_row_has_body_style_sibling(rows, index):
@@ -319,6 +446,7 @@ def _classify_paragraph_titles_in_lane(
rows,
index,
lane_width,
+ lane.left,
profile,
)
and not compact_text_section
@@ -500,16 +628,33 @@ def _has_following_body_row(
rows: list[tuple[_LineItem, BBox]],
index: int,
lane_width: float,
+ lane_left: float,
profile: _LaneBodyProfile,
) -> bool:
- """检查小字号候选下方是否仍有正常字号的正文续行。"""
+ """只检查紧邻且空间相关的下一行,禁止用远处正文支撑小字号标题。"""
- for line, bbox in rows[index + 1 :]:
- height_ratio = _line_effective_height(line, bbox) / profile.body_height
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- if 0.9 <= height_ratio <= 1.2 and width_ratio >= 0.45:
- return True
- return False
+ if index + 1 >= len(rows):
+ return False
+ current = rows[index]
+ line, bbox = rows[index + 1]
+ gap = _effective_text_row_gap(current, (line, bbox))
+ horizontally_related = (
+ _bbox_axis_overlap_ratio(current[1], bbox, axis="x") >= 0.35
+ or abs(current[1][0] - bbox[0]) <= 0.75 * profile.body_height
+ )
+ current_centered = abs(
+ _bbox_center_x(current[1]) - (lane_left + lane_width / 2.0)
+ ) <= 0.12 * lane_width
+ maximum_gap = (1.5 if current_centered else 0.75) * profile.body_height
+ height_ratio = _line_effective_height(line, bbox) / profile.body_height
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ return (
+ line.semantic_type is None
+ and horizontally_related
+ and -0.25 * profile.body_height <= gap <= maximum_gap
+ and 0.9 <= height_ratio <= 1.2
+ and width_ratio >= 0.45
+ )
def _has_following_compact_text_section(
@@ -625,16 +770,21 @@ def _normalized_title_gap(
*,
direction: Literal[-1, 1],
body_height: float,
+ physical_gaps: dict[int, tuple[float | None, float | None]],
) -> float:
- """返回标题候选与相邻物理行之间按正文行高归一化的有效净空。"""
+ """返回栏内邻行和页面最近物理邻行中较小的归一化净空。"""
neighbor_index = index + direction
- if not 0 <= neighbor_index < len(rows):
- return 0.5
- if direction < 0:
- gap = _effective_text_row_gap(rows[neighbor_index], rows[index])
+ if 0 <= neighbor_index < len(rows):
+ if direction < 0:
+ lane_gap = _effective_text_row_gap(rows[neighbor_index], rows[index])
+ else:
+ lane_gap = _effective_text_row_gap(rows[index], rows[neighbor_index])
else:
- gap = _effective_text_row_gap(rows[index], rows[neighbor_index])
+ lane_gap = 0.5 * body_height
+ physical_pair = physical_gaps.get(rows[index][0].source_index, (None, None))
+ physical_gap = physical_pair[0 if direction < 0 else 1]
+ gap = lane_gap if physical_gap is None else min(lane_gap, physical_gap)
return max(0.0, gap) / max(0.1, body_height)
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.py
index 98748f4f..86c9fdcb 100644
--- a/mineru/backend/flash/pdf_extractor.py
+++ b/mineru/backend/flash/pdf_extractor.py
@@ -82,7 +82,7 @@ if __name__ == '__main__':
if __name__ == "__main__":
# pdf_path = "/Users/myhloli/pdf/截断合并/demo1-3.pdf"
# pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png
- pdf_path = "/Users/myhloli/pdf/demo1.pdf"
+ pdf_path = "/Users/myhloli/pdf/caibao1.pdf"
pdf_bytes = read_fn(pdf_path)
model_list = doc_analyze(pdf_bytes, parse_mode="auto")
logger.info(f"model_list: {model_list}")
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index e6b35649..4dc8587c 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -477,3 +477,88 @@ def test_single_page_marginal_content_remains_text() -> None:
assert [line.semantic_type for line in page.remaining_lines] == [None, None]
+def test_repeated_visual_headers_use_geometry_and_skip_first_page() -> None:
+ """验证三页重复页首图片重标为 header,首页与 content 差异不参与匹配。"""
+
+ pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(5)]
+ contents = ["cover", "alpha", "beta", "gamma", "delta"]
+ for page, content in zip(pages, contents, strict=True):
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (10.0, 0.0, 90.0, 10.0),
+ "angle": 0,
+ "content": content,
+ }
+ ]
+
+ auxiliary_text._classify_repeated_visual_headers(pages)
+
+ assert pages[0].fixed_blocks[0]["type"] == "image"
+ assert [page.fixed_blocks[0]["type"] for page in pages[1:]] == ["header"] * 4
+
+
+def test_repeated_visual_headers_require_three_top_geometry_matches() -> None:
+ """验证两页重复、非页首图片和明显漂移的 bbox 均不形成视觉页眉。"""
+
+ pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(6)]
+ bboxes = [
+ (10.0, 0.0, 90.0, 10.0),
+ (10.0, 0.0, 90.0, 10.0),
+ (10.0, 0.0, 90.0, 10.0),
+ (10.0, 20.0, 90.0, 30.0),
+ (30.0, 0.0, 90.0, 10.0),
+ (10.0, 0.0, 90.0, 10.0),
+ ]
+ for page, bbox in zip(pages, bboxes, strict=True):
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": bbox,
+ "angle": 0,
+ "content": "value",
+ }
+ ]
+
+ auxiliary_text._classify_repeated_visual_headers(pages)
+
+ assert [page.fixed_blocks[0]["type"] for page in pages] == ["image"] * 6
+
+
+def test_repeated_visual_headers_support_alternating_pages() -> None:
+ """验证同奇偶页间隔为二的重复图片仍可形成视觉页眉簇。"""
+
+ pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(7)]
+ for page_index, page in enumerate(pages):
+ if page_index in {2, 4, 6}:
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (10.0, 0.0, 90.0, 10.0),
+ "angle": 0,
+ "content": f"page-{page_index}",
+ }
+ ]
+
+ auxiliary_text._classify_repeated_visual_headers(pages)
+
+ assert [pages[index].fixed_blocks[0]["type"] for index in (2, 4, 6)] == ["header"] * 3
+
+
+def test_repeated_visual_headers_require_matching_orientation() -> None:
+ """验证 bbox 相同但方向不一致的三页图片不会形成同一视觉页眉簇。"""
+
+ pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(4)]
+ for page_index, page in enumerate(pages[1:], start=1):
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (10.0, 0.0, 90.0, 10.0),
+ "angle": 90 if page_index == 3 else 0,
+ "content": f"page-{page_index}",
+ }
+ ]
+
+ auxiliary_text._classify_repeated_visual_headers(pages)
+
+ assert [page.fixed_blocks[0]["type"] for page in pages[1:]] == ["image"] * 3
diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.py
index 3e9affb0..96e94beb 100644
--- a/tests/unittest/test_flash_pdf_graphics.py
+++ b/tests/unittest/test_flash_pdf_graphics.py
@@ -7,6 +7,7 @@ from mineru.backend.flash.native_pdf import (
models,
pipeline,
)
+from mineru.utils.pdf_document import PDFPathInfo
from _flash_pdf_test_utils import (
@@ -27,6 +28,26 @@ def _drawing_axis_line(
)
+def _path_info(
+ bbox: tuple[float, float, float, float],
+ source_index: int,
+ *,
+ segment_count: int = 5,
+ fill_visible: bool = True,
+ stroke_visible: bool = False,
+) -> PDFPathInfo:
+ """构造强图形核心测试使用的根层 PDF Path。"""
+
+ return PDFPathInfo(
+ bbox=bbox,
+ segment_count=segment_count,
+ fill_visible=fill_visible,
+ stroke_visible=stroke_visible,
+ form_depth=0,
+ source_index=source_index,
+ )
+
+
def _graphic_source_fixture() -> models._PageSource:
"""构造双框图形、六个标签、拆分 caption 与邻近正文。"""
@@ -91,6 +112,35 @@ def test_double_box_graphic_claims_six_labels_but_not_caption_or_body() -> None:
assert "Nearby prose" not in blocks[0]["content"]
+def test_graphic_label_accepts_only_near_diagonal_corner_text() -> None:
+ """验证无轴向重叠的短标签仅在严格角部距离内归入图形。"""
+
+ core_bbox = (20.0, 20.0, 80.0, 80.0)
+ near_corner = _text_line("unit", (5.0, 5.0, 15.0, 15.0), 0)
+ distant_corner = _text_line("unit", (-5.0, -5.0, 5.0, 5.0), 1)
+ long_title = _text_line(
+ "deliberately wide title",
+ (0.0, 5.0, 80.0, 15.0),
+ 2,
+ )
+
+ assert graphics._is_graphic_label_member(
+ near_corner,
+ core_bbox,
+ 10.0,
+ )
+ assert not graphics._is_graphic_label_member(
+ distant_corner,
+ core_bbox,
+ 10.0,
+ )
+ assert not graphics._is_graphic_label_member(
+ long_title,
+ core_bbox,
+ 10.0,
+ )
+
+
def test_materialized_table_bbox_has_priority_over_graphic_candidate() -> None:
"""验证绘图组件与成功表格框重叠时跳过图形容器并保留全部文本身份。"""
@@ -104,6 +154,72 @@ def test_materialized_table_bbox_has_priority_over_graphic_candidate() -> None:
assert claimed == set()
+def test_complex_path_container_builds_graphic_without_drawing_lines() -> None:
+ """验证大 Path 容器和内部二维复杂轮廓可直接形成图形核心。"""
+
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=[
+ _text_line("10", (15.0, 20.0, 25.0, 25.0), 0, visual_row_id=1),
+ _text_line("label", (30.0, 55.0, 50.0, 60.0), 1, visual_row_id=2),
+ ],
+ chars=[],
+ drawing_lines=[],
+ path_infos=[
+ _path_info((10.0, 10.0, 90.0, 70.0), 0),
+ _path_info((20.0, 20.0, 75.0, 50.0), 1, segment_count=12),
+ _path_info((25.0, 25.0, 35.0, 35.0), 2),
+ _path_info((40.0, 25.0, 50.0, 40.0), 3),
+ _path_info((55.0, 20.0, 65.0, 45.0), 4),
+ ],
+ )
+
+ core_bboxes = graphics._detect_strong_graphic_bboxes(source)
+ blocks, claimed = graphics._build_graphic_like_blocks(
+ source,
+ [],
+ set(),
+ core_bboxes,
+ )
+
+ assert core_bboxes == [(10.0, 10.0, 90.0, 70.0)]
+ assert claimed == {0, 1}
+ assert blocks[0]["bbox"] == (10.0, 10.0, 90.0, 70.0)
+ assert blocks[0]["content"] == "10\nlabel"
+
+
+def test_axis_pair_requires_internal_two_dimensional_complex_path() -> None:
+ """验证相交坐标轴须有二维复杂曲线支撑,规则矩形行带不会误报图形。"""
+
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=[
+ _text_line("0", (12.0, 65.0, 17.0, 70.0), 0),
+ _text_line("x", (78.0, 72.0, 83.0, 77.0), 1),
+ ],
+ chars=[],
+ drawing_lines=[],
+ path_infos=[
+ _path_info((20.0, 20.0, 21.0, 70.0), 0, segment_count=2, fill_visible=False, stroke_visible=True),
+ _path_info((20.0, 69.0, 80.0, 70.0), 1, segment_count=2, fill_visible=False, stroke_visible=True),
+ _path_info((25.0, 30.0, 75.0, 60.0), 2, segment_count=12, fill_visible=False, stroke_visible=True),
+ ],
+ )
+
+ assert graphics._detect_strong_graphic_bboxes(source) == [
+ (20.0, 20.0, 80.0, 70.0)
+ ]
+
+ source.path_infos[2] = _path_info(
+ (25.0, 30.0, 75.0, 31.0),
+ 2,
+ segment_count=12,
+ fill_visible=False,
+ stroke_visible=True,
+ )
+ assert graphics._detect_strong_graphic_bboxes(source) == []
+
+
def test_form_image_claims_internal_text_and_small_table_but_not_caption() -> None:
"""验证有效 Form 吞并图内文字与小表候选,外部 caption 仍保留。"""
@@ -226,5 +342,3 @@ def test_raster_image_content_is_removed_from_text_and_empty_image_page_is_kept(
"content": "",
}
]
-
-
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index 10319223..8bdd346d 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -9,6 +9,7 @@ from mineru.backend.flash.native_pdf import (
models,
tables,
)
+from mineru.utils.pdf_document import PDFPathInfo
def _axis_line(
@@ -25,6 +26,250 @@ def _axis_line(
)
+def _path_info(
+ bbox: tuple[float, float, float, float],
+ source_index: int,
+ *,
+ form_depth: int = 0,
+) -> PDFPathInfo:
+ """构造填充网格测试使用的矩形 Path。"""
+
+ return PDFPathInfo(
+ bbox=bbox,
+ segment_count=5,
+ fill_visible=True,
+ stroke_visible=False,
+ form_depth=form_depth,
+ source_index=source_index,
+ )
+
+
+def _filled_grid_path_fixture(
+ *,
+ band_count: int = 5,
+ cell_gap: float = 0.0,
+ right_edge: float = 495.0,
+ form_depth: int = 0,
+) -> list[PDFPathInfo]:
+ """构造含重复 Path、半行底纹和边缘细条的五行双列填充网格。"""
+
+ output = [
+ _path_info((100.0, 100.0, 500.0, 400.0), 0, form_depth=form_depth),
+ _path_info((105.0, 101.0, 495.0, 104.0), 1, form_depth=form_depth),
+ _path_info((105.0, 396.0, 495.0, 399.0), 2, form_depth=form_depth),
+ ]
+ row_bounds = [
+ (105.0, 160.0),
+ (160.0, 230.0),
+ (230.0, 280.0),
+ (280.0, 335.0),
+ (335.0, 395.0),
+ ]
+ source_index = len(output)
+ for row_index, (top, bottom) in enumerate(row_bounds[:band_count]):
+ cells = [
+ (105.0, top, 300.0, bottom),
+ (300.0 + cell_gap, top, right_edge, bottom),
+ ]
+ for cell in cells:
+ output.append(
+ _path_info(cell, source_index, form_depth=form_depth)
+ )
+ source_index += 1
+ if row_index == 0:
+ output.append(
+ _path_info(cells[0], source_index, form_depth=form_depth)
+ )
+ source_index += 1
+ if row_index % 2 == 1:
+ middle = 0.5 * (top + bottom)
+ for left, _top, right, _bottom in cells:
+ for half_bbox in (
+ (left, top, right, middle),
+ (left, middle, right, bottom),
+ ):
+ output.append(
+ _path_info(
+ half_bbox,
+ source_index,
+ form_depth=form_depth,
+ )
+ )
+ source_index += 1
+ return output
+
+
+def test_filled_grid_geometry_detects_exact_outer_bbox_without_text() -> None:
+ """验证纯 Path 网格在没有文本时仍保留精确外框并清除嵌套副本。"""
+
+ path_infos = _filled_grid_path_fixture()
+ rectangles = [path_info.bbox for path_info in path_infos]
+ candidates = tables._detect_filled_grid_table_candidates(
+ path_infos,
+ (1000.0, 1000.0),
+ )
+ cells = tables._select_maximal_filled_grid_cells(
+ rectangles,
+ (100.0, 100.0, 500.0, 400.0),
+ )
+
+ assert len(cells) == 10
+ assert len(candidates) == 1
+ assert candidates[0].bbox == (100.0, 100.0, 500.0, 400.0)
+ assert candidates[0].core_bbox == candidates[0].bbox
+ assert candidates[0].line_indices == set()
+
+ source = models._PageSource(
+ page_size=(1000.0, 1000.0),
+ lines=[],
+ chars=[],
+ drawing_lines=[],
+ path_infos=path_infos,
+ )
+ assert [
+ candidate.bbox for candidate in tables._detect_table_candidates(source)
+ ] == [(100.0, 100.0, 500.0, 400.0)]
+
+ source.lines = [
+ models._LineItem(
+ text="任意替换内容",
+ bbox=(120.0, 120.0, 260.0, 140.0),
+ angle=0,
+ source_index=0,
+ effective_height=20.0,
+ )
+ ]
+ assert [
+ candidate.bbox for candidate in tables._detect_table_candidates(source)
+ ] == [(100.0, 100.0, 500.0, 400.0)]
+
+
+def test_filled_grid_geometry_rejects_incomplete_or_interfering_paths() -> None:
+ """验证行带不足、横向破损、非根层和强图形重叠均不能生成外框。"""
+
+ page_size = (1000.0, 1000.0)
+ assert tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(band_count=3),
+ page_size,
+ ) == []
+ assert tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(right_edge=450.0),
+ page_size,
+ ) == []
+ assert tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(cell_gap=10.0),
+ page_size,
+ ) == []
+ assert tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(form_depth=1),
+ page_size,
+ ) == []
+ assert tables._detect_filled_grid_table_candidates(
+ _filled_grid_path_fixture(),
+ page_size,
+ [(120.0, 120.0, 480.0, 380.0)],
+ ) == []
+
+
+def test_filled_grid_candidate_prevents_rule_bbox_expansion() -> None:
+ """验证填充网格优先后,重叠横线候选不能扩大其 Path 外框。"""
+
+ lines: list[models._LineItem] = []
+ source_index = 0
+ for row_index, top in enumerate((120.0, 190.0, 260.0, 330.0)):
+ for left, right in ((120.0, 280.0), (320.0, 480.0)):
+ lines.append(
+ models._LineItem(
+ text=f"cell-{source_index}",
+ bbox=(left, top, right, top + 20.0),
+ angle=0,
+ source_index=source_index,
+ effective_height=20.0,
+ visual_row_id=row_index,
+ )
+ )
+ source_index += 1
+ source = models._PageSource(
+ page_size=(1000.0, 1000.0),
+ lines=lines,
+ chars=[],
+ drawing_lines=[
+ models._AxisLine(
+ bbox=(80.0, 90.0, 520.0, 91.0),
+ width=1.0,
+ orientation="horizontal",
+ ),
+ models._AxisLine(
+ bbox=(80.0, 410.0, 520.0, 411.0),
+ width=1.0,
+ orientation="horizontal",
+ ),
+ ],
+ path_infos=_filled_grid_path_fixture(),
+ )
+
+ candidates = tables._detect_table_candidates(source)
+
+ assert [candidate.bbox for candidate in candidates] == [
+ (100.0, 100.0, 500.0, 400.0)
+ ]
+
+
+def test_filled_grid_materialization_uses_existing_spatial_projection(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证空成员候选由 core bbox 收集文本,不需要建立单元格归属。"""
+
+ lines = [
+ models._LineItem(
+ text="inside-left",
+ bbox=(120.0, 120.0, 240.0, 140.0),
+ angle=0,
+ source_index=0,
+ effective_height=20.0,
+ ),
+ models._LineItem(
+ text="inside-right",
+ bbox=(330.0, 120.0, 480.0, 140.0),
+ angle=0,
+ source_index=1,
+ effective_height=20.0,
+ ),
+ models._LineItem(
+ text="outside",
+ bbox=(120.0, 430.0, 240.0, 450.0),
+ angle=0,
+ source_index=2,
+ effective_height=20.0,
+ ),
+ ]
+ source = models._PageSource(
+ page_size=(1000.0, 1000.0),
+ lines=lines,
+ chars=[],
+ drawing_lines=[],
+ path_infos=_filled_grid_path_fixture(),
+ )
+ candidate = tables._detect_filled_grid_table_candidates(
+ source.path_infos,
+ source.page_size,
+ )[0]
+ projection = MagicMock(return_value="inside-left inside-right")
+ monkeypatch.setattr(tables, "project_pdf_table_text", projection)
+
+ blocks, claimed = tables._materialize_table_blocks(source, [candidate])
+
+ assert claimed == {0, 1}
+ assert blocks == [
+ {
+ "type": "table",
+ "bbox": (100.0, 100.0, 500.0, 400.0),
+ "angle": 0,
+ "content": "inside-left inside-right",
+ }
+ ]
+
+
@pytest.mark.parametrize(
("median_height", "rejected_length", "accepted_length"),
[
@@ -47,7 +292,12 @@ def test_long_rule_group_uses_40pt_or_ten_times_height_threshold(
]
accepted_lines = [_axis_line("horizontal", (0.0, top, accepted_length, top + 0.1)) for top in (10.0, 20.0, 30.0)]
- assert tables._group_long_horizontal_rules(rejected_lines, median_height) == []
+ grouped = tables._group_long_horizontal_rules(rejected_lines, median_height)
+ assert len(grouped) == 1
+ assert [line.bbox for line in grouped[0]] == [
+ (0.0, 20.0, accepted_length, 20.1),
+ (0.0, 30.0, accepted_length, 30.1),
+ ]
assert len(tables._group_long_horizontal_rules(accepted_lines, median_height)) == 1
@@ -106,7 +356,11 @@ def _rule_table_fixture(
visual_row_id=row_index,
)
)
- axis_lines = [_axis_line("horizontal", (0.0, top, 110.0, top + 0.1)) for top in (8.0, 33.0, 58.0)[:rule_count]]
+ rule_tops = (8.0, 58.0) if rule_count == 2 else (8.0, 33.0, 58.0)
+ axis_lines = [
+ _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
+ for top in rule_tops
+ ]
return rows, lines, axis_lines
@@ -147,8 +401,8 @@ def test_rule_table_candidate_accepts_center_aligned_columns_with_varying_widths
assert candidates[0].line_indices == set(range(6))
-def test_two_horizontal_rule_grid_is_deliberately_rejected() -> None:
- """验证即使存在竖线和规则文本,两条长横线也不再形成表格候选。"""
+def test_two_horizontal_rule_grid_is_accepted_by_spatial_distribution() -> None:
+ """验证两条长横线结合密集稳定列即可形成表格候选。"""
rows, lines, axis_lines = _rule_table_fixture(rule_count=2)
axis_lines.extend(
@@ -168,11 +422,12 @@ def test_two_horizontal_rule_grid_is_deliberately_rejected() -> None:
axis_lines,
)
- assert candidates == []
+ assert len(candidates) == 1
+ assert candidates[0].line_indices == set(range(9))
-def test_duplicate_horizontal_paths_do_not_satisfy_three_rule_requirement() -> None:
- """验证同一 y 位置的重复 PDF path 只计为一条横线。"""
+def test_duplicate_horizontal_paths_count_as_one_boundary() -> None:
+ """验证同一 y 位置的重复 PDF path 只计为一条边界。"""
axis_lines = [
_axis_line("horizontal", (0.0, 10.0, 100.0, 10.1)),
@@ -180,7 +435,32 @@ def test_duplicate_horizontal_paths_do_not_satisfy_three_rule_requirement() -> N
_axis_line("horizontal", (0.0, 30.0, 100.0, 30.1)),
]
- assert tables._group_long_horizontal_rules(axis_lines, 5.0) == []
+ groups = tables._group_long_horizontal_rules(axis_lines, 5.0)
+
+ assert len(groups) == 1
+ assert len(groups[0]) == 2
+ assert [line.bbox[1] for line in groups[0]] == [10.0, 30.0]
+ assert tables._group_long_horizontal_rules(axis_lines[:2], 5.0) == []
+
+
+def test_nearest_rule_pair_excludes_header_line_from_table_bbox() -> None:
+ """验证页首横线与表格上边界间没有多单元行时,不扩张表格 bbox。"""
+
+ rows, lines, axis_lines = _rule_table_fixture(rule_count=2)
+ axis_lines.insert(0, _axis_line("horizontal", (0.0, 0.0, 110.0, 0.1)))
+
+ candidates = tables._build_rule_table_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ )
+
+ assert len(candidates) == 1
+ assert candidates[0].core_bbox is not None
+ assert candidates[0].core_bbox[1] == pytest.approx(8.0)
def test_chart_tick_rows_fail_dense_multi_cell_distribution() -> None:
@@ -298,5 +578,3 @@ def test_failed_table_projection_does_not_claim_text(
assert blocks == []
assert claimed == set()
-
-
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index 41733a89..627f451b 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -735,3 +735,236 @@ def test_hyphen_continuation_cannot_start_false_hanging_indent_entry() -> None:
"The expression starts here the stream function is given below:",
"F = fraction",
]
+
+
+def test_spatial_post_merge_connects_short_opener_wide_body_and_tail() -> None:
+ """验证跨栏拆开的短首行、满宽正文和紧邻尾行仅按空间关系重新连接。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": (10.0, 10.0, 40.0, 20.0),
+ "angle": 0,
+ "content": "section",
+ "_visual_row_ids": {0},
+ "_local_line_bboxes": [(10.0, 10.0, 40.0, 20.0)],
+ "_line_heights": [10.0],
+ },
+ {
+ "type": "text",
+ "bbox": (10.0, 22.0, 190.0, 42.0),
+ "angle": 0,
+ "content": "wide body",
+ "_visual_row_ids": {1, 2},
+ "_local_line_bboxes": [
+ (10.0, 22.0, 190.0, 32.0),
+ (10.0, 32.0, 190.0, 42.0),
+ ],
+ "_line_heights": [10.0, 10.0],
+ },
+ {
+ "type": "text",
+ "bbox": (10.0, 44.0, 100.0, 54.0),
+ "angle": 0,
+ "content": "tail",
+ "_visual_row_ids": {3},
+ "_local_line_bboxes": [(10.0, 44.0, 100.0, 54.0)],
+ "_line_heights": [10.0],
+ },
+ ]
+
+ merged = text_blocks._merge_spatial_text_components(
+ blocks,
+ (200.0, 100.0),
+ )
+
+ assert len(merged) == 1
+ assert merged[0]["bbox"] == (10.0, 10.0, 190.0, 54.0)
+ assert merged[0]["content"] == "section wide body tail"
+ assert merged[0]["_visual_row_ids"] == {0, 1, 2, 3}
+
+
+def test_spatial_post_merge_uses_compatible_local_lane_width() -> None:
+ """验证半页栏内的短首行可连接多段正文,并在下一分组起点停止。"""
+
+ lane_metadata = {
+ "_lane_interval": (40.0, 370.0),
+ "_lane_is_span": False,
+ }
+ blocks = [
+ {
+ "type": "text",
+ "bbox": (40.0, 10.0, 80.0, 20.0),
+ "angle": 0,
+ "content": "opener",
+ "_visual_row_ids": {0},
+ "_local_line_bboxes": [(40.0, 10.0, 80.0, 20.0)],
+ "_line_heights": [10.0],
+ **lane_metadata,
+ },
+ {
+ "type": "text",
+ "bbox": (40.0, 22.0, 365.0, 42.0),
+ "angle": 0,
+ "content": "body one",
+ "_visual_row_ids": {1, 2},
+ "_local_line_bboxes": [
+ (40.0, 22.0, 365.0, 32.0),
+ (40.0, 32.0, 365.0, 42.0),
+ ],
+ "_line_heights": [10.0, 10.0],
+ **lane_metadata,
+ },
+ {
+ "type": "text",
+ "bbox": (40.0, 44.0, 365.0, 54.0),
+ "angle": 0,
+ "content": "body two",
+ "_visual_row_ids": {3},
+ "_local_line_bboxes": [(40.0, 44.0, 365.0, 54.0)],
+ "_line_heights": [10.0],
+ **lane_metadata,
+ },
+ {
+ "type": "text",
+ "bbox": (40.0, 56.0, 365.0, 76.0),
+ "angle": 0,
+ "content": "body three",
+ "_visual_row_ids": {4, 5},
+ "_local_line_bboxes": [
+ (40.0, 56.0, 365.0, 66.0),
+ (40.0, 66.0, 365.0, 76.0),
+ ],
+ "_line_heights": [10.0, 10.0],
+ **lane_metadata,
+ },
+ {
+ "type": "text",
+ "bbox": (40.0, 78.0, 230.0, 88.0),
+ "angle": 0,
+ "content": "body tail",
+ "_visual_row_ids": {6},
+ "_local_line_bboxes": [(40.0, 78.0, 230.0, 88.0)],
+ "_line_heights": [10.0],
+ **lane_metadata,
+ },
+ {
+ "type": "text",
+ "bbox": (40.0, 90.0, 365.0, 112.0),
+ "angle": 0,
+ "content": "next section body",
+ "_visual_row_ids": {7, 8},
+ "_local_line_bboxes": [
+ (40.0, 90.0, 90.0, 100.0),
+ (40.0, 102.0, 365.0, 112.0),
+ ],
+ "_line_heights": [10.0, 10.0],
+ **lane_metadata,
+ },
+ ]
+
+ merged = text_blocks._merge_spatial_text_components(
+ blocks,
+ (600.0, 200.0),
+ )
+
+ assert [block["content"] for block in merged] == [
+ "opener body one body two body three body tail",
+ "next section body",
+ ]
+ assert merged[0]["bbox"] == (40.0, 10.0, 365.0, 88.0)
+
+
+def test_spatial_post_merge_does_not_share_incompatible_lane_width() -> None:
+ """验证左右栏区间不兼容时仍使用页面宽度,不能放宽首段合并。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": (40.0, 10.0, 80.0, 20.0),
+ "angle": 0,
+ "content": "left opener",
+ "_visual_row_ids": {0},
+ "_local_line_bboxes": [(40.0, 10.0, 80.0, 20.0)],
+ "_line_heights": [10.0],
+ "_lane_interval": (40.0, 370.0),
+ "_lane_is_span": False,
+ },
+ {
+ "type": "text",
+ "bbox": (270.0, 22.0, 590.0, 42.0),
+ "angle": 0,
+ "content": "right body",
+ "_visual_row_ids": {1, 2},
+ "_local_line_bboxes": [
+ (270.0, 22.0, 590.0, 32.0),
+ (270.0, 32.0, 590.0, 42.0),
+ ],
+ "_line_heights": [10.0, 10.0],
+ "_lane_interval": (270.0, 590.0),
+ "_lane_is_span": False,
+ },
+ ]
+
+ merged = text_blocks._merge_spatial_text_components(
+ blocks,
+ (600.0, 100.0),
+ )
+
+ assert [block["content"] for block in merged] == [
+ "left opener",
+ "right body",
+ ]
+
+
+def test_spatial_post_merge_limits_tapered_tail_to_parallel_information_grid() -> None:
+ """验证略大间距的递减尾行只在并列信息网格中并回其左对齐主体。"""
+
+ blocks = [
+ {
+ "type": "text",
+ "bbox": (10.0, 10.0, 90.0, 40.0),
+ "angle": 0,
+ "content": "left body",
+ "_visual_row_ids": {0},
+ "_local_line_bboxes": [(10.0, 30.0, 90.0, 40.0)],
+ "_line_heights": [10.0],
+ },
+ {
+ "type": "text",
+ "bbox": (110.0, 10.0, 190.0, 40.0),
+ "angle": 0,
+ "content": "right body",
+ "_visual_row_ids": {1},
+ "_local_line_bboxes": [(110.0, 30.0, 190.0, 40.0)],
+ "_line_heights": [10.0],
+ },
+ {
+ "type": "text",
+ "bbox": (10.0, 50.0, 60.0, 60.0),
+ "angle": 0,
+ "content": "left tail",
+ "_visual_row_ids": {2},
+ "_local_line_bboxes": [(10.0, 50.0, 60.0, 60.0)],
+ "_line_heights": [10.0],
+ },
+ ]
+
+ merged = text_blocks._merge_spatial_text_components(
+ blocks,
+ (200.0, 100.0),
+ )
+
+ assert [block["content"] for block in merged] == [
+ "left body left tail",
+ "right body",
+ ]
+
+ isolated = text_blocks._merge_spatial_text_components(
+ [blocks[0], blocks[2]],
+ (200.0, 100.0),
+ )
+ assert [block["content"] for block in isolated] == [
+ "left body",
+ "left tail",
+ ]
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index 15e5c8e8..7b0294ae 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -58,6 +58,77 @@ def test_heading_like_content_with_body_layout_remains_text() -> None:
assert lines[2].semantic_type is None
+def test_physical_title_gap_ignores_disjoint_column_and_keeps_overlapping_row() -> None:
+ """验证物理邻行只在水平投影相交时参与标题留白,避免另一栏正文压缩间距。"""
+
+ target = _text_line("target", (0.0, 40.0, 40.0, 50.0), 0)
+ disjoint = _text_line("other column", (60.0, 39.0, 100.0, 49.0), 1)
+ overlapping = _text_line("wide row", (0.0, 25.0, 100.0, 35.0), 2)
+
+ gaps = titles._build_physical_title_gap_map(
+ [(target, target.bbox), (disjoint, disjoint.bbox), (overlapping, overlapping.bbox)]
+ )
+
+ assert gaps[target.source_index] == (5.0, None)
+
+
+def test_grid_title_suppression_requires_two_distinct_parallel_bands() -> None:
+ """验证单个三栏短首行带不足以抑制标题,重复两带才形成信息网格证据。"""
+
+ lanes = []
+ source_index = 0
+ for lane_index in range(3):
+ left = 110.0 * lane_index
+ first_opener = _text_line(
+ f"opener-{lane_index}-0",
+ (left, 10.0, left + 20.0, 20.0),
+ source_index,
+ )
+ source_index += 1
+ first_body = _text_line(
+ f"body-{lane_index}-0",
+ (left, 20.0, left + 80.0, 30.0),
+ source_index,
+ )
+ source_index += 1
+ lanes.append(
+ titles._TextLane(
+ left=left,
+ right=left + 100.0,
+ lines=[
+ (first_opener, first_opener.bbox),
+ (first_body, first_body.bbox),
+ ],
+ )
+ )
+
+ assert titles._find_repeated_grid_title_suppressions(lanes, 10.0) == set()
+
+ second_band_sources = set()
+ for lane in lanes[:2]:
+ second_opener = _text_line(
+ "second opener",
+ (lane.left, 40.0, lane.left + 20.0, 50.0),
+ source_index,
+ )
+ second_band_sources.add(source_index)
+ source_index += 1
+ second_body = _text_line(
+ "second body",
+ (lane.left, 50.0, lane.left + 80.0, 60.0),
+ source_index,
+ )
+ source_index += 1
+ lane.lines.extend(
+ [(second_opener, second_opener.bbox), (second_body, second_body.bbox)]
+ )
+
+ suppressions = titles._find_repeated_grid_title_suppressions(lanes, 10.0)
+
+ assert second_band_sources <= suppressions
+ assert len(suppressions) == 5
+
+
def test_centered_smaller_paragraph_title_uses_layout_contrast_only() -> None:
"""验证同字体的小字号居中标题可由栏宽和上下留白识别。"""
@@ -544,6 +615,8 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
inspect.getsource(function)
for function in (
titles._classify_page_titles,
+ titles._build_physical_title_gap_map,
+ titles._find_repeated_grid_title_suppressions,
titles._infer_lane_body_profile,
titles._classify_document_title,
titles._document_title_uses_page_fallback,
@@ -564,4 +637,3 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
)
assert ".text" not in source
-