Skip to content

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

feat: enhance code block detection by adding support for rule-delimited code candidates and refining footer classification

myhlolib60e9ebd5a40
diff --git a/demo/pdfs/mixed_elements_pages_03_06.pdf b/demo/pdfs/mixed_elements_pages_03_06.pdf
new file mode 100644
index 00000000..7825f87b
Binary files /dev/null and b/demo/pdfs/mixed_elements_pages_03_06.pdf differ
diff --git a/demo/pdfs/mixed_elements_pages_07_10.pdf b/demo/pdfs/mixed_elements_pages_07_10.pdf
new file mode 100644
index 00000000..a6ecd212
Binary files /dev/null and b/demo/pdfs/mixed_elements_pages_07_10.pdf differ
diff --git a/demo/pdfs/mixed_elements_pages_11_15.pdf b/demo/pdfs/mixed_elements_pages_11_15.pdf
new file mode 100644
index 00000000..f4a0fbe5
Binary files /dev/null and b/demo/pdfs/mixed_elements_pages_11_15.pdf differ
diff --git a/demo/pdfs/mixed_elements_pages_39_40.pdf b/demo/pdfs/mixed_elements_pages_39_40.pdf
new file mode 100644
index 00000000..a9b6701f
Binary files /dev/null and b/demo/pdfs/mixed_elements_pages_39_40.pdf differ
diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.py
index ab4459a8..a9401ebb 100644
--- a/mineru/backend/flash/native_pdf/auxiliary_text.py
+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py
@@ -18,6 +18,7 @@ from .models import (
_LineItem,
_LocalAxisLine,
_MarginalCandidate,
+ _PageSource,
_PreparedPage,
_TextLane,
)
@@ -67,6 +68,11 @@ def _classify_page_auxiliary_text(prepared: _PreparedPage) -> None:
prepared.table_bboxes,
prepared.drawing_lines,
prepared.page_size,
+ visual_bboxes=[
+ block["bbox"]
+ for block in prepared.fixed_blocks
+ if block.get("type") == "image"
+ ],
)
@@ -209,7 +215,8 @@ def _classify_image_footnotes(
- max(axis_line.bbox[0], image_bbox[0]),
)
>= 0.85 * image_width
- and -0.25 * body_height
+ # 图片外框的底边属于图形本身,不能拿来证明下方文字是图表脚注。
+ and 0.0
<= axis_line.bbox[1] - row_bottom
<= max(0.01 * local_page_height, 0.75 * body_height)
and not _rule_belongs_to_confirmed_table(
@@ -305,6 +312,8 @@ def _classify_page_footnotes(
table_bboxes: list[BBox],
drawing_lines: list[_AxisLine],
page_size: tuple[float, float],
+ *,
+ visual_bboxes: list[BBox] | None = None,
) -> list[set[int]]:
"""识别主方向页脚注,并按触发分隔线返回来源编号分组。"""
@@ -353,6 +362,7 @@ def _classify_page_footnotes(
)
candidate_groups: list[set[int]] = []
+ visual_bboxes = visual_bboxes or []
for axis_line in local_axis_lines:
if axis_line.orientation != "horizontal":
continue
@@ -369,6 +379,15 @@ def _classify_page_footnotes(
local_page_width,
):
continue
+ if any(
+ _bbox_intersects(
+ _expand_bbox(axis_line.original_bbox, max(0.5, axis_line.width)),
+ visual_bbox,
+ )
+ for visual_bbox in visual_bboxes
+ ):
+ # 图形坐标轴和外框不能充当页面脚注分隔线。
+ continue
rule_source_indices: set[int] = set()
for lane in lanes:
following_rule_tops = [
@@ -714,6 +733,106 @@ def _classify_rule_delimited_headers(pages: list[_PreparedPage]) -> None:
line.semantic_type = "header"
+def _classify_rule_delimited_footers(pages: list[_PreparedPage]) -> None:
+ """用页面底部两条同跨度横线确认其间孤立的居中页脚。"""
+
+ for page in pages:
+ available = [
+ line
+ for line in page.remaining_lines
+ if line.semantic_type is None
+ ]
+ if not available or not page.drawing_lines:
+ continue
+ support_by_angle = _geometric_text_support_by_angle(
+ page.remaining_lines,
+ page.page_size,
+ )
+ if not support_by_angle:
+ continue
+ dominant_angle = max(
+ sorted(support_by_angle),
+ key=lambda angle: support_by_angle[angle],
+ )
+ local_page_size = (
+ (page.page_size[1], page.page_size[0])
+ if dominant_angle in {90, 270}
+ else page.page_size
+ )
+ local_page_width, local_page_height = local_page_size
+ if local_page_width <= 0 or local_page_height <= 0:
+ continue
+ local_axis_lines = _transform_axis_lines(
+ page.drawing_lines,
+ page.page_size,
+ dominant_angle,
+ )
+ rules = [
+ rule
+ for rule in local_axis_lines
+ if rule.orientation == "horizontal"
+ and _bbox_center_y(rule.bbox) >= 0.85 * local_page_height
+ and rule.bbox[2] - rule.bbox[0] >= 0.2 * local_page_width
+ and not _rule_belongs_to_confirmed_table(
+ rule,
+ local_axis_lines,
+ page.table_bboxes,
+ local_page_width,
+ )
+ and not _rule_overlaps_fixed_container(
+ rule,
+ page.fixed_blocks,
+ page.page_size,
+ )
+ ]
+ local_lines = [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page.page_size,
+ dominant_angle,
+ ),
+ )
+ for line in available
+ if line.angle == dominant_angle
+ ]
+ if not local_lines:
+ continue
+ median_height = statistics.median(
+ _line_effective_height(line, bbox)
+ for line, bbox in local_lines
+ )
+ for upper_index, upper in enumerate(rules[:-1]):
+ for lower in rules[upper_index + 1 :]:
+ vertical_gap = lower.bbox[1] - upper.bbox[3]
+ if not 2.0 * median_height <= vertical_gap <= 6.0 * median_height:
+ continue
+ if _bbox_axis_overlap_ratio(upper.bbox, lower.bbox, axis="x") < 0.9:
+ continue
+ corridor_left = max(upper.bbox[0], lower.bbox[0])
+ corridor_right = min(upper.bbox[2], lower.bbox[2])
+ members = [
+ (line, bbox)
+ for line, bbox in local_lines
+ if bbox[1] >= upper.bbox[3]
+ and bbox[3] <= lower.bbox[1]
+ and bbox[0] >= corridor_left - 0.5 * median_height
+ and bbox[2] <= corridor_right + 0.5 * median_height
+ ]
+ if not 1 <= len(members) <= 3:
+ continue
+ if any(
+ abs(_bbox_center_x(bbox) - 0.5 * (corridor_left + corridor_right))
+ > 0.15 * max(0.1, corridor_right - corridor_left)
+ for _line, bbox in members
+ ):
+ continue
+ for line, _bbox in members:
+ line.semantic_type = "footer"
+ break
+
+
def _rule_overlaps_fixed_container(
rule: _LocalAxisLine,
fixed_blocks: list[dict[str, object]],
@@ -784,7 +903,15 @@ def _classify_page_number_outer_companions(
if target_type == "header"
else local_bbox[1] >= outward_limit
)
- if is_outward:
+ same_marginal_row = (
+ _bbox_axis_overlap_ratio(
+ local_bbox,
+ page_number_bbox,
+ axis="y",
+ )
+ >= 0.5
+ )
+ if is_outward or same_marginal_row:
line.semantic_type = target_type
for block in page.fixed_blocks:
if block.get("type") != "image":
@@ -808,10 +935,92 @@ def _classify_page_number_outer_companions(
if target_type == "header"
else local_bbox[1] >= outward_limit
)
- if is_outward:
+ same_marginal_row = (
+ _bbox_axis_overlap_ratio(
+ local_bbox,
+ page_number_bbox,
+ axis="y",
+ )
+ >= 0.5
+ )
+ if is_outward or same_marginal_row:
block["type"] = target_type
+def _classify_split_marginal_row_companions(
+ pages: list[_PreparedPage],
+) -> None:
+ """把页边缘同一拆分视觉行中的未分类碎片继承为页眉或页脚。"""
+
+ for page in pages:
+ row_groups: dict[tuple[int, int], list[_LineItem]] = {}
+ for line in page.remaining_lines:
+ if line.visual_row_id is None or not line.split_from_row:
+ continue
+ row_groups.setdefault((line.angle, line.visual_row_id), []).append(
+ line
+ )
+ for (angle, _row_id), members in row_groups.items():
+ local_page_height = (
+ page.page_size[0]
+ if angle in {90, 270}
+ else page.page_size[1]
+ )
+ local_bboxes = [
+ _rotate_bbox_to_upright(line.bbox, page.page_size, angle)
+ for line in members
+ ]
+ row_center = statistics.fmean(
+ _bbox_center_y(bbox)
+ for bbox in local_bboxes
+ )
+ if row_center <= 0.1 * local_page_height:
+ target_type: Literal["header", "footer"] = "header"
+ elif row_center >= 0.9 * local_page_height:
+ target_type = "footer"
+ else:
+ continue
+ anchor_types = {
+ line.semantic_type
+ for line in members
+ if line.semantic_type in {target_type, "page_number"}
+ }
+ if not anchor_types:
+ continue
+ for line in members:
+ if line.semantic_type is None:
+ line.semantic_type = target_type
+
+
+def _classify_raw_page_marginals(sources: list[_PageSource]) -> None:
+ """在视觉容器认领前保护强跨页页码、页眉和页脚文本。"""
+
+ if len(sources) < 2:
+ return
+ candidates = [
+ candidate
+ for page_index, source in enumerate(sources)
+ for line in source.lines
+ if (
+ candidate := _build_marginal_candidate(
+ page_index,
+ line,
+ source.page_size,
+ )
+ )
+ is not None
+ and (
+ _bbox_center_y(candidate.local_bbox)
+ / candidate.local_page_size[1]
+ <= 0.08
+ or _bbox_center_y(candidate.local_bbox)
+ / candidate.local_page_size[1]
+ >= 0.92
+ )
+ ]
+ _classify_marginal_candidates(candidates)
+
+
def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:
"""仅用相邻或同奇偶页的重复证据标注页码、页眉和页脚。"""
@@ -824,6 +1033,14 @@ def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:
if (candidate := _build_marginal_candidate(page_index, line, page.page_size)) is not None
]
+ _classify_marginal_candidates(candidates)
+
+
+def _classify_marginal_candidates(
+ candidates: list[_MarginalCandidate],
+) -> None:
+ """复用跨页递增页码和稳定边缘文本的强证据匹配。"""
+
for left_index, left in enumerate(candidates):
left_value = _parse_page_number_value(left.line.text)
if left_value is None:
@@ -1112,7 +1329,7 @@ def _build_marginal_candidate(
return None
if normalized_center_y <= 0.15:
region: Literal["header", "footer", "side"] = "header"
- elif normalized_center_y >= 0.85:
+ elif normalized_center_y >= 0.9:
region = "footer"
elif (
normalized_center_y <= 0.18
diff --git a/mineru/backend/flash/native_pdf/code_blocks.py b/mineru/backend/flash/native_pdf/code_blocks.py
index 7b6727da..937db404 100644
--- a/mineru/backend/flash/native_pdf/code_blocks.py
+++ b/mineru/backend/flash/native_pdf/code_blocks.py
@@ -19,6 +19,7 @@ from .geometry import (
_bbox_center_y,
_bbox_overlap_in_first,
_bbox_overlap_in_smaller,
+ _bbox_union_many,
)
from .models import _CodeCandidate, _LineItem, _PageSource
from .native_text import _sanitize_pdf_control_text
@@ -47,6 +48,30 @@ def _build_code_blocks(
excluded_bboxes,
claimed_line_indices,
)
+ return _materialize_code_candidates(source, candidates)
+
+
+def _build_rule_delimited_code_blocks(
+ source: _PageSource,
+ excluded_bboxes: list[BBox],
+ claimed_line_indices: set[int] | None = None,
+) -> tuple[list[dict[str, Any]], set[int]]:
+ """在表格认领前物化外框或上下横线限定的代码清单。"""
+
+ candidates = _detect_rule_delimited_code_candidates(
+ source,
+ excluded_bboxes,
+ claimed_line_indices or set(),
+ )
+ return _materialize_code_candidates(source, candidates)
+
+
+def _materialize_code_candidates(
+ source: _PageSource,
+ candidates: list[_CodeCandidate],
+) -> tuple[list[dict[str, Any]], set[int]]:
+ """统一投影代码候选,确保来源行只被一个 code block 认领。"""
+
if not candidates:
return [], set()
lines_by_index = {line.source_index: line for line in source.lines}
@@ -83,6 +108,201 @@ def _build_code_blocks(
return blocks, claimed
+def _detect_rule_delimited_code_candidates(
+ source: _PageSource,
+ excluded_bboxes: list[BBox],
+ claimed_line_indices: set[int],
+) -> list[_CodeCandidate]:
+ """按规则边界、稳定行距和缩进层次识别非等宽代码清单。"""
+
+ page_width, page_height = source.page_size
+ if page_width <= 0 or page_height <= 0:
+ return []
+ available = [
+ line
+ for line in source.lines
+ if line.source_index not in claimed_line_indices and line.angle == 0
+ ]
+ if len(available) < 5:
+ return []
+ median_height = statistics.median(
+ max(0.1, line.effective_height or line.bbox[3] - line.bbox[1])
+ for line in available
+ )
+ horizontal_rules = sorted(
+ [
+ line
+ for line in source.drawing_lines
+ if line.orientation == "horizontal"
+ and line.bbox[2] - line.bbox[0] >= 0.22 * page_width
+ ],
+ key=lambda line: (line.bbox[1], line.bbox[0]),
+ )
+ vertical_rules = [
+ line
+ for line in source.drawing_lines
+ if line.orientation == "vertical"
+ ]
+ raw_candidates: list[_CodeCandidate] = []
+ endpoint_tolerance = max(2.0, 0.75 * median_height)
+ for top_index, top_rule in enumerate(horizontal_rules[:-1]):
+ for bottom_rule in horizontal_rules[top_index + 1 :]:
+ if (
+ abs(top_rule.bbox[0] - bottom_rule.bbox[0]) > endpoint_tolerance
+ or abs(top_rule.bbox[2] - bottom_rule.bbox[2]) > endpoint_tolerance
+ ):
+ continue
+ candidate_bbox = _bbox_union_many(
+ [top_rule.bbox, bottom_rule.bbox]
+ )
+ candidate_height = candidate_bbox[3] - candidate_bbox[1]
+ if not 6.0 * median_height <= candidate_height <= 0.35 * page_height:
+ continue
+ if any(
+ _bbox_overlap_in_smaller(candidate_bbox, excluded_bbox) >= 0.5
+ for excluded_bbox in excluded_bboxes
+ ):
+ continue
+ interior_rules = [
+ rule
+ for rule in horizontal_rules
+ if top_rule.bbox[3] + 0.5 * median_height
+ < rule.bbox[1]
+ < bottom_rule.bbox[1] - 0.5 * median_height
+ and _bbox_overlap_in_first(rule.bbox, candidate_bbox) >= 0.8
+ and rule.bbox[2] - rule.bbox[0]
+ >= 0.6 * (candidate_bbox[2] - candidate_bbox[0])
+ ]
+ if interior_rules:
+ continue
+ internal_vertical_rules = [
+ rule
+ for rule in vertical_rules
+ if candidate_bbox[0] + median_height
+ < _bbox_center_x(rule.bbox)
+ < candidate_bbox[2] - median_height
+ and rule.bbox[3] - rule.bbox[1] >= 0.6 * candidate_height
+ and _bbox_overlap_in_first(rule.bbox, candidate_bbox) >= 0.8
+ ]
+ if internal_vertical_rules:
+ continue
+ members = [
+ line
+ for line in available
+ if candidate_bbox[0] - 0.5 * median_height
+ <= _bbox_center_x(line.bbox)
+ <= candidate_bbox[2] + 0.5 * median_height
+ and top_rule.bbox[3]
+ <= _bbox_center_y(line.bbox)
+ <= bottom_rule.bbox[1]
+ ]
+ if not _rule_delimited_code_members_are_structured(
+ members,
+ candidate_bbox,
+ median_height,
+ ):
+ continue
+ raw_candidates.append(
+ _CodeCandidate(
+ bbox=candidate_bbox,
+ angle=0,
+ line_indices={line.source_index for line in members},
+ )
+ )
+
+ accepted: list[_CodeCandidate] = []
+ for candidate in sorted(raw_candidates, key=lambda item: _bbox_area(item.bbox)):
+ if any(
+ _bbox_overlap_in_smaller(candidate.bbox, existing.bbox) >= 0.85
+ for existing in accepted
+ ):
+ continue
+ accepted.append(candidate)
+ return sorted(accepted, key=lambda item: (item.bbox[1], item.bbox[0]))
+
+
+def _rule_delimited_code_members_are_structured(
+ members: list[_LineItem],
+ candidate_bbox: BBox,
+ median_height: float,
+) -> bool:
+ """验证候选具有稳定基线、代码缩进或窄行号槽,并排除规则多列表格。"""
+
+ if len(members) < 5:
+ return False
+ rows: dict[int, list[_LineItem]] = {}
+ fallback_row = 1_000_000
+ for line in members:
+ row_key = line.visual_row_id
+ if row_key is None:
+ row_key = fallback_row
+ fallback_row += 1
+ rows.setdefault(row_key, []).append(line)
+ if len(rows) < 5:
+ return False
+ ordered_rows = sorted(
+ rows.values(),
+ key=lambda row: min(_bbox_center_y(line.bbox) for line in row),
+ )
+ row_centers = [
+ statistics.median(_bbox_center_y(line.bbox) for line in row)
+ for row in ordered_rows
+ ]
+ row_gaps = [
+ current - previous
+ for previous, current in zip(row_centers, row_centers[1:])
+ if current > previous
+ ]
+ if not row_gaps:
+ return False
+ base_pitch = statistics.median(row_gaps)
+ if base_pitch <= 0 or sum(
+ 0.65 * base_pitch <= gap <= 1.8 * base_pitch
+ for gap in row_gaps
+ ) / len(row_gaps) < 0.75:
+ return False
+ if sum(len(row) >= 3 for row in ordered_rows) / len(ordered_rows) >= 0.25:
+ return False
+
+ left_positions = sorted(line.bbox[0] for line in members)
+ indent_clusters: list[list[float]] = []
+ for position in left_positions:
+ if (
+ not indent_clusters
+ or position - statistics.median(indent_clusters[-1])
+ > 0.75 * median_height
+ ):
+ indent_clusters.append([position])
+ else:
+ indent_clusters[-1].append(position)
+ narrow_gutter_rows = 0
+ for row in ordered_rows:
+ ordered = sorted(row, key=lambda line: line.bbox[0])
+ if (
+ len(ordered) >= 2
+ and ordered[0].bbox[2] - ordered[0].bbox[0]
+ <= 2.0 * median_height
+ and ordered[1].bbox[0] - ordered[0].bbox[2]
+ >= 0.5 * median_height
+ ):
+ narrow_gutter_rows += 1
+ has_line_number_gutter = narrow_gutter_rows / len(ordered_rows) >= 0.35
+ has_indent_hierarchy = (
+ len(indent_clusters) >= 3
+ and sum(len(cluster) >= 2 for cluster in indent_clusters) >= 2
+ )
+ if not has_line_number_gutter and not has_indent_hierarchy:
+ return False
+
+ occupied_width = max(line.bbox[2] for line in members) - min(
+ line.bbox[0] for line in members
+ )
+ return occupied_width <= 0.95 * max(
+ 0.1,
+ candidate_bbox[2] - candidate_bbox[0],
+ )
+
+
def _code_member_chars(lines: list[_LineItem]) -> list[dict[str, Any]]:
"""按 char_idx 去重代码成员字符,避免区域内斜向水印混入空间投影。"""
diff --git a/mineru/backend/flash/native_pdf/formulas.py b/mineru/backend/flash/native_pdf/formulas.py
index 21f79a20..2120e188 100644
--- a/mineru/backend/flash/native_pdf/formulas.py
+++ b/mineru/backend/flash/native_pdf/formulas.py
@@ -557,13 +557,17 @@ def _build_formula_like_blocks(
) -> tuple[list[dict[str, Any]], list[_LineItem]]:
"""仅依据栏带、右侧短锚点和空间连通关系聚合公式状区域。"""
- blocks: list[dict[str, Any]] = []
- claimed_source_indices: set[int] = set()
+ blocks, claimed_source_indices = _build_split_visual_row_formula_blocks(
+ lines,
+ table_bboxes,
+ page_size,
+ )
for angle in sorted({line.angle for line in lines}):
angle_geometry = [
(line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
for line in lines
if line.angle == angle
+ and line.source_index not in claimed_source_indices
]
if len(angle_geometry) < 2:
continue
@@ -576,19 +580,35 @@ def _build_formula_like_blocks(
if lane.is_span:
continue
lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ dominant_body_font = _infer_formula_body_font(
+ lane,
+ median_height,
+ )
for line, bbox in list(lane.lines):
if (
- line.compact_formula_cluster
- and not _is_formula_component_in_page_margin(
- bbox,
- local_page_height,
+ (
+ line.compact_formula_cluster
+ and not _compact_cluster_has_nearby_number_anchor(
+ (line, bbox),
+ lane,
+ median_height,
+ )
+ and _is_isolated_compact_formula_cluster(
+ (line, bbox),
+ lane,
+ median_height,
+ )
)
- and _is_isolated_compact_formula_cluster(
+ or _is_isolated_unnumbered_formula_line(
(line, bbox),
lane,
median_height,
+ dominant_body_font,
)
- ):
+ ) and not _is_formula_component_in_page_margin(
+ bbox,
+ local_page_height,
+ ):
content = _sanitize_pdf_control_text(
line.text,
preserve_newlines=False,
@@ -611,7 +631,6 @@ def _build_formula_like_blocks(
]
if len(lane.lines) < 2:
continue
- dominant_body_font = _infer_formula_body_font(lane, median_height)
anchors = _find_formula_spatial_anchors(
lane,
median_height,
@@ -679,6 +698,151 @@ def _build_formula_like_blocks(
return blocks, remaining_lines
+def _build_split_visual_row_formula_blocks(
+ lines: list[_LineItem],
+ table_bboxes: list[BBox],
+ page_size: tuple[float, float],
+) -> tuple[list[dict[str, Any]], set[int]]:
+ """在栏带推断前恢复同一视觉行中带右侧编号的多字体公式。"""
+
+ row_groups: dict[tuple[int, int], list[_LineItem]] = {}
+ for line in lines:
+ if line.visual_row_id is None or not line.split_from_row:
+ continue
+ row_groups.setdefault((line.angle, line.visual_row_id), []).append(line)
+
+ blocks: list[dict[str, Any]] = []
+ claimed: set[int] = set()
+ for (angle, _row_id), members in row_groups.items():
+ if len(members) < 3:
+ continue
+ markers = [
+ member
+ for member in members
+ if _standalone_formula_number_marker(member.text) is not None
+ ]
+ if len(markers) != 1:
+ continue
+ marker = markers[0]
+ if any(
+ _bbox_intersects(member.bbox, table_bbox)
+ for member in members
+ for table_bbox in table_bboxes
+ ):
+ continue
+ local_members = [
+ (
+ member,
+ _rotate_bbox_to_upright(
+ member.bbox,
+ page_size,
+ angle,
+ ),
+ )
+ for member in members
+ ]
+ marker_bbox = next(
+ bbox
+ for member, bbox in local_members
+ if member is marker
+ )
+ body_members = [
+ (member, bbox)
+ for member, bbox in local_members
+ if member is not marker
+ ]
+ if not body_members or marker_bbox[0] <= max(
+ _bbox_center_x(bbox)
+ for _member, bbox in body_members
+ ):
+ continue
+ median_height = statistics.median(
+ _line_effective_height(member, bbox)
+ for member, bbox in local_members
+ )
+ row_center = statistics.median(
+ _bbox_center_y(bbox)
+ for _member, bbox in local_members
+ )
+ if any(
+ abs(_bbox_center_y(bbox) - row_center) > 0.75 * median_height
+ for _member, bbox in local_members
+ ):
+ continue
+ body_fonts = {
+ member.font_signature
+ for member, _bbox in body_members
+ if member.font_signature is not None
+ }
+ has_math_typography = (
+ len(body_fonts) >= 2
+ or any(
+ member.compact_formula_cluster
+ or member.font_coverage < 0.8
+ for member, _bbox in body_members
+ )
+ )
+ if not has_math_typography:
+ continue
+ body_bbox = _bbox_union_many(
+ [bbox for _member, bbox in body_members]
+ )
+ body_width = max(0.1, body_bbox[2] - body_bbox[0])
+ member_ids = {id(member) for member in members}
+ has_nearby_formula_fragment = False
+ for other in lines:
+ if id(other) in member_ids or other.angle != angle:
+ continue
+ other_bbox = _rotate_bbox_to_upright(
+ other.bbox,
+ page_size,
+ angle,
+ )
+ vertical_gap = max(
+ 0.0,
+ max(other_bbox[1], body_bbox[1])
+ - min(other_bbox[3], body_bbox[3]),
+ )
+ if (
+ vertical_gap <= 0.75 * median_height
+ and other_bbox[2] - other_bbox[0] <= 0.65 * body_width
+ and max(
+ 0.0,
+ max(other_bbox[0], body_bbox[0])
+ - min(other_bbox[2], body_bbox[2]),
+ )
+ <= median_height
+ ):
+ has_nearby_formula_fragment = True
+ break
+ if has_nearby_formula_fragment:
+ continue
+ block = _formula_members_to_block(
+ local_members,
+ page_size,
+ angle,
+ anchor_source_index=marker.source_index,
+ )
+ if block is None:
+ continue
+ local_bbox = _bbox_union_many(
+ [bbox for _member, bbox in local_members]
+ )
+ local_page_height = (
+ page_size[0]
+ if angle in {90, 270}
+ else page_size[1]
+ )
+ if _is_formula_component_in_page_margin(
+ local_bbox,
+ local_page_height,
+ ):
+ continue
+ blocks.append(block)
+ claimed.update(member.source_index for member in members)
+ return blocks, claimed
+
+
def _is_isolated_compact_formula_cluster(
candidate: tuple[_LineItem, BBox],
lane: _TextLane,
@@ -694,13 +858,18 @@ def _is_isolated_compact_formula_cluster(
return False
if bbox[3] - bbox[1] > 3.0 * median_height:
return False
+ if (
+ abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right))
+ > 0.2 * lane_width
+ ):
+ return False
candidate_center = _bbox_center_y(bbox)
body_rows = [
item
for item in lane.lines
if item[0].source_index != line.source_index
- and item[1][2] - item[1][0] >= 0.6 * lane_width
+ and item[1][2] - item[1][0] >= 0.45 * lane_width
and 0.8 * median_height
<= _line_effective_height(*item)
<= 1.25 * median_height
@@ -720,12 +889,139 @@ def _is_isolated_compact_formula_cluster(
previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
return (
- candidate_center - _bbox_center_y(previous[1]) <= 2.5 * median_height
+ candidate_center - _bbox_center_y(previous[1]) <= 8.0 * median_height
and _bbox_center_y(following[1]) - candidate_center
+ <= 8.0 * median_height
+ )
+
+
+def _compact_cluster_has_nearby_number_anchor(
+ candidate: tuple[_LineItem, BBox],
+ lane: _TextLane,
+ median_height: float,
+) -> bool:
+ """检测紧凑公式右侧的独立编号,保留给既有空间锚点统一扩张。"""
+
+ line, bbox = candidate
+ return any(
+ other_line.source_index != line.source_index
+ and _standalone_formula_number_marker(other_line.text) is not None
+ and other_bbox[0] > _bbox_center_x(bbox)
+ and abs(_bbox_center_y(other_bbox) - _bbox_center_y(bbox))
<= 2.5 * median_height
+ for other_line, other_bbox in lane.lines
)
+def _is_isolated_unnumbered_formula_line(
+ candidate: tuple[_LineItem, BBox],
+ lane: _TextLane,
+ median_height: float,
+ dominant_body_font: tuple[str, int] | None,
+) -> bool:
+ """用低正文覆盖的数学排版和上下正文邻接识别无编号行间公式。"""
+
+ line, bbox = candidate
+ if (
+ line.compact_formula_cluster
+ or dominant_body_font is None
+ or line.font_signature is None
+ or line.font_signature == dominant_body_font
+ or line.font_coverage >= 0.75
+ ):
+ return False
+ lane_width = max(0.1, lane.right - lane.left)
+ line_width = bbox[2] - bbox[0]
+ if not 0.15 * lane_width <= line_width <= 0.8 * lane_width:
+ return False
+ if (
+ abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right))
+ > 0.08 * lane_width
+ ):
+ return False
+ if bbox[3] - bbox[1] > 1.8 * median_height:
+ return False
+ candidate_center = _bbox_center_y(bbox)
+ if any(
+ other_line.source_index != line.source_index
+ and _standalone_formula_number_marker(other_line.text) is not None
+ and abs(_bbox_center_y(other_bbox) - candidate_center)
+ <= 4.0 * median_height
+ for other_line, other_bbox in lane.lines
+ ) or _has_nearby_punctuated_formula_number_anchor(
+ candidate,
+ lane,
+ median_height,
+ ):
+ return False
+ body_rows = [
+ item
+ for item in lane.lines
+ if item[0].source_index != line.source_index
+ and item[0].font_signature == dominant_body_font
+ and item[0].font_coverage >= 0.75
+ and item[1][2] - item[1][0] >= 0.45 * lane_width
+ and 0.8 * median_height
+ <= _line_effective_height(*item)
+ <= 1.25 * median_height
+ ]
+ rows_above = [
+ item
+ for item in body_rows
+ if _bbox_center_y(item[1]) < candidate_center
+ ]
+ rows_below = [
+ item
+ for item in body_rows
+ if _bbox_center_y(item[1]) > candidate_center
+ ]
+ if not rows_above or not rows_below:
+ return False
+ previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
+ following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
+ return (
+ candidate_center - _bbox_center_y(previous[1]) <= 4.0 * median_height
+ and _bbox_center_y(following[1]) - candidate_center
+ <= 4.0 * median_height
+ )
+
+
+def _has_nearby_punctuated_formula_number_anchor(
+ candidate: tuple[_LineItem, BBox],
+ lane: _TextLane,
+ median_height: float,
+) -> bool:
+ """识别同一公式带右侧仅带标点前缀的编号,避免分式上下行被提前认领。"""
+
+ line, bbox = candidate
+ for other_line, other_bbox in lane.lines:
+ if other_line.source_index == line.source_index:
+ continue
+ parts = _split_trailing_formula_number(other_line.text)
+ if parts is None:
+ continue
+ prefix, _marker = parts
+ compact_prefix = prefix.strip()
+ if (
+ not compact_prefix
+ or len(compact_prefix) > 3
+ or any(character.isalnum() for character in compact_prefix)
+ ):
+ continue
+ vertical_gap = max(
+ 0.0,
+ max(other_bbox[1], bbox[1]) - min(other_bbox[3], bbox[3]),
+ )
+ horizontal_gap = max(0.0, other_bbox[0] - bbox[2])
+ if (
+ other_bbox[0] >= bbox[2] - 0.5 * median_height
+ and vertical_gap <= 0.75 * median_height
+ and horizontal_gap <= 4.0 * median_height
+ ):
+ return True
+ return False
+
+
def _find_formula_spatial_anchors(
lane: _TextLane,
median_height: float,
diff --git a/mineru/backend/flash/native_pdf/graphics.py b/mineru/backend/flash/native_pdf/graphics.py
index 2d1c61cb..dbd585d1 100644
--- a/mineru/backend/flash/native_pdf/graphics.py
+++ b/mineru/backend/flash/native_pdf/graphics.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import math
+import re
import statistics
from typing import Any
@@ -57,6 +58,12 @@ _MAX_FORM_IMAGE_PAGE_AREA_RATIO = 0.8
_IMAGE_CONTAINER_OVERLAP_THRESHOLD = 0.5
+_FIGURE_CAPTION_LINE_RE = re.compile(
+ r"^\s*(?:fig(?:ure)?\.?)[ \t]*\d+[A-Za-z]?(?:\s*[.:])?",
+ re.IGNORECASE,
+)
+
+
def _form_supersedes_nested_bbox(form_bbox: BBox, nested_bbox: BBox) -> bool:
"""判断 Form 是否应整体吞并其内部面积明显更小的候选容器。"""
@@ -231,7 +238,18 @@ def _build_graphic_like_blocks(
[],
).append(line)
+ protected_caption_indices = _graphic_caption_line_indices_to_preserve(
+ lines,
+ candidates,
+ median_height,
+ )
+
for row_lines in row_groups.values():
+ if any(
+ line.source_index in protected_caption_indices
+ for line in row_lines
+ ):
+ continue
row_lane_index = _graphic_lane_index(row_lines[0].bbox, lanes)
matches: list[tuple[int, float, int]] = []
for candidate_index, candidate in enumerate(candidates):
@@ -286,6 +304,59 @@ def _build_graphic_like_blocks(
return blocks, claimed
+def _graphic_caption_line_indices_to_preserve(
+ lines: list[_LineItem],
+ candidates: list[_GraphicCandidate],
+ median_height: float,
+) -> set[int]:
+ """保护贴近图形下沿的图注及其同字体续行,避免末词被图片容器认领。"""
+
+ protected: set[int] = set()
+ ordered_lines = sorted(
+ (line for line in lines if line.angle == 0),
+ key=lambda line: (line.bbox[1], line.bbox[0], line.source_index),
+ )
+ for seed_index, seed in enumerate(ordered_lines):
+ if not _FIGURE_CAPTION_LINE_RE.match(seed.text):
+ continue
+ matching_candidates = [
+ candidate
+ for candidate in candidates
+ if _bbox_axis_overlap_ratio(
+ seed.bbox,
+ candidate.core_bbox,
+ axis="x",
+ )
+ >= 0.35
+ and candidate.core_bbox[3] - 2.5 * median_height
+ <= _bbox_center_y(seed.bbox)
+ <= candidate.core_bbox[3] + 2.5 * median_height
+ ]
+ if not matching_candidates:
+ continue
+ protected.add(seed.source_index)
+ previous = seed
+ for candidate_line in ordered_lines[seed_index + 1 :]:
+ if candidate_line.bbox[1] - previous.bbox[3] > 0.75 * median_height:
+ break
+ if _bbox_center_y(candidate_line.bbox) <= _bbox_center_y(previous.bbox):
+ continue
+ if (
+ abs(candidate_line.bbox[0] - seed.bbox[0]) > median_height
+ or (
+ seed.font_signature is not None
+ and candidate_line.font_signature is not None
+ and seed.font_signature != candidate_line.font_signature
+ )
+ ):
+ continue
+ protected.add(candidate_line.source_index)
+ previous = candidate_line
+ if candidate_line.text.rstrip().endswith((".", "!", "?")):
+ break
+ return protected
+
+
def _detect_strong_graphic_bboxes(source: _PageSource) -> list[BBox]:
"""仅按复杂 Path、容器尺度与成对坐标轴识别高置信图形核心。"""
diff --git a/mineru/backend/flash/native_pdf/line_merging.py b/mineru/backend/flash/native_pdf/line_merging.py
index 18e6c4f5..bed66634 100644
--- a/mineru/backend/flash/native_pdf/line_merging.py
+++ b/mineru/backend/flash/native_pdf/line_merging.py
@@ -471,7 +471,9 @@ def _can_merge_same_baseline_pair(
return False
if first.semantic_type != second.semantic_type:
return False
- if first.visual_row_id == second.visual_row_id and (first.split_from_row or second.split_from_row):
+ if first.visual_row_id == second.visual_row_id and (
+ first.split_from_row or second.split_from_row
+ ):
return False
if _connection_crosses_table(first.bbox, second.bbox, table_bboxes):
return False
@@ -836,9 +838,9 @@ def _can_restore_dense_split_visual_row(
table_bboxes: list[BBox],
lane_keys: dict[int, tuple[int, int]],
) -> bool:
- """检查 hard-split run 是否构成同栏、同字体且占用充分的完整视觉行。"""
+ """检查 hard-split run 是否构成同字体且占用充分的完整视觉行。"""
- if len(members) < 3 or not all(member.split_from_row for member in members):
+ if len(members) < 2 or not all(member.split_from_row for member in members):
return False
if len({member.semantic_type for member in members}) != 1:
return False
@@ -846,8 +848,7 @@ def _can_restore_dense_split_visual_row(
if [member.run_index for member in ordered] != list(range(len(ordered))):
return False
member_lane_keys = {lane_keys.get(member.source_index) for member in ordered}
- if None in member_lane_keys or len(member_lane_keys) != 1:
- return False
+ same_inferred_lane = None not in member_lane_keys and len(member_lane_keys) == 1
font_signatures = {member.font_signature for member in ordered}
if len(font_signatures) != 1:
return False
@@ -866,6 +867,15 @@ def _can_restore_dense_split_visual_row(
for member in ordered
]
local_geometry.sort(key=lambda item: (item[1][0], item[1][1], item[0].source_index))
+ if not same_inferred_lane:
+ member_widths = [
+ bbox[2] - bbox[0]
+ for _member, bbox in local_geometry
+ ]
+ if len(members) == 2 and min(member_widths) > 0.35 * max(member_widths):
+ return False
+ if 3 <= len(members) <= 6:
+ return False
heights = [_line_effective_height(member, bbox) for member, bbox in local_geometry]
median_height = statistics.median(heights)
glyph_widths = [
@@ -874,7 +884,11 @@ def _can_restore_dense_split_visual_row(
if (width := _median_native_glyph_width(member, page_size)) is not None
]
median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.0
- gap_limit = max(12.0, 1.75 * median_height, 3.0 * median_glyph_width)
+ gap_limit = (
+ max(12.0, 1.75 * median_height, 3.0 * median_glyph_width)
+ if same_inferred_lane
+ else max(8.0, 2.0 * median_height, 2.5 * median_glyph_width)
+ )
for previous, current in zip(local_geometry, local_geometry[1:]):
if not _same_baseline_geometry(
previous[1],
@@ -887,7 +901,19 @@ def _can_restore_dense_split_visual_row(
union_bbox = _bbox_union_many([bbox for _member, bbox in local_geometry])
occupied_width = sum(bbox[2] - bbox[0] for _member, bbox in local_geometry)
- return occupied_width / max(0.1, union_bbox[2] - union_bbox[0]) >= 0.65
+ minimum_occupancy = (
+ 0.8
+ if len(members) == 2 and same_inferred_lane
+ else 0.85
+ if len(members) == 2
+ else 0.65
+ if not same_inferred_lane
+ else 0.65
+ )
+ return (
+ occupied_width / max(0.1, union_bbox[2] - union_bbox[0])
+ >= minimum_occupancy
+ )
def _merge_dense_split_visual_row(
diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.py
index 08125fe7..8b483d39 100644
--- a/mineru/backend/flash/native_pdf/models.py
+++ b/mineru/backend/flash/native_pdf/models.py
@@ -100,7 +100,7 @@ class _GraphicCandidate:
@dataclass(slots=True)
class _CodeCandidate:
- """保存由浅色填充背景与等宽文本共同确认的代码区域。"""
+ """保存由填充背景或成对横线与稳定文本节奏确认的代码区域。"""
bbox: BBox
angle: int
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index b0dcbe82..6f1969c1 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+from dataclasses import replace
from typing import Any
@@ -59,13 +60,19 @@ from .formulas import (
_build_formula_like_blocks,
_build_vector_formula_blocks,
)
-from .code_blocks import _build_code_blocks
+from .code_blocks import (
+ _build_code_blocks,
+ _build_rule_delimited_code_blocks,
+)
from .auxiliary_text import (
_classify_deferred_image_footnotes,
_classify_isolated_first_page_footer,
_classify_page_number_outer_companions,
_classify_page_auxiliary_text,
+ _classify_raw_page_marginals,
+ _classify_rule_delimited_footers,
_classify_rule_delimited_headers,
+ _classify_split_marginal_row_companions,
_classify_repeated_page_marginals,
_classify_repeated_visual_headers,
_classify_single_page_compound_headers,
@@ -79,7 +86,9 @@ from .titles import (
from .text_blocks import (
_build_text_blocks,
_merge_fragmented_header_blocks,
+ _merge_front_matter_column_blocks,
_merge_image_caption_text_blocks,
+ _merge_multiline_title_blocks,
_merge_repeated_compact_title_continuations,
)
@@ -176,7 +185,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
page_sizes,
)
- prepared_pages: list[_PreparedPage] = []
+ page_sources: list[_PageSource] = []
for page_idx in range(pdf_doc.page_count):
page_size = page_sizes[page_idx]
chars = pdf_doc.get_page_chars(page_idx)
@@ -200,12 +209,20 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),
path_infos=pdf_doc.get_page_path_infos(page_idx),
)
- prepared_pages.append(_prepare_page_source(source))
+ page_sources.append(source)
+
+ _classify_raw_page_marginals(page_sources)
+ prepared_pages = [
+ _prepare_page_source(source)
+ for source in page_sources
+ ]
_classify_repeated_visual_headers(prepared_pages)
_classify_repeated_page_marginals(prepared_pages)
+ _classify_split_marginal_row_companions(prepared_pages)
_classify_single_page_compound_headers(prepared_pages)
_classify_rule_delimited_headers(prepared_pages)
+ _classify_rule_delimited_footers(prepared_pages)
_classify_page_number_outer_companions(prepared_pages)
_classify_isolated_first_page_footer(prepared_pages)
document_body_profile = _infer_document_body_profile(prepared_pages)
@@ -232,13 +249,36 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
def _prepare_page_source(source: _PageSource) -> _PreparedPage:
"""先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""
+ protected_line_indices = {
+ line.source_index
+ for line in source.lines
+ if line.semantic_type is not None
+ }
+ analysis_source = replace(
+ source,
+ lines=[
+ line
+ for line in source.lines
+ if line.source_index not in protected_line_indices
+ ],
+ )
form_bboxes = _select_form_image_bboxes(source)
- strong_graphic_bboxes = _detect_strong_graphic_bboxes(source)
+ strong_graphic_bboxes = _detect_strong_graphic_bboxes(analysis_source)
+ rule_code_blocks, claimed_rule_code_line_indices = (
+ _build_rule_delimited_code_blocks(
+ analysis_source,
+ form_bboxes
+ + strong_graphic_bboxes
+ + list(source.image_bboxes)
+ + list(source.signature_bboxes),
+ )
+ )
+ rule_code_bboxes = [block["bbox"] for block in rule_code_blocks]
candidates = [
candidate
for candidate in _detect_table_candidates(
- source,
- excluded_bboxes=strong_graphic_bboxes,
+ analysis_source,
+ excluded_bboxes=strong_graphic_bboxes + rule_code_bboxes,
)
if not any(
_form_supersedes_nested_bbox(form_bbox, candidate.bbox)
@@ -246,9 +286,10 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
)
]
table_blocks, claimed_line_indices = _materialize_table_blocks(
- source,
+ analysis_source,
candidates,
)
+ claimed_line_indices.update(claimed_rule_code_line_indices)
table_bboxes = [block["bbox"] for block in table_blocks]
active_form_bboxes = [
form_bbox
@@ -260,7 +301,7 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
)
]
code_blocks, claimed_code_line_indices = _build_code_blocks(
- source,
+ analysis_source,
table_bboxes
+ active_form_bboxes
+ strong_graphic_bboxes
@@ -270,27 +311,32 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
)
code_bboxes = [block["bbox"] for block in code_blocks]
form_image_blocks, claimed_form_line_indices = _build_form_image_blocks(
- source,
+ analysis_source,
active_form_bboxes,
claimed_line_indices | claimed_code_line_indices,
)
graphic_blocks, claimed_graphic_line_indices = _build_graphic_like_blocks(
- source,
- table_bboxes + active_form_bboxes + code_bboxes,
+ analysis_source,
+ table_bboxes + active_form_bboxes + rule_code_bboxes + code_bboxes,
claimed_line_indices | claimed_code_line_indices | claimed_form_line_indices,
strong_graphic_bboxes,
)
raster_image_blocks, claimed_raster_line_indices = _build_raster_image_blocks(
- source,
- table_blocks + code_blocks + form_image_blocks + graphic_blocks,
+ analysis_source,
+ table_blocks
+ + rule_code_blocks
+ + code_blocks
+ + form_image_blocks
+ + graphic_blocks,
claimed_line_indices
| claimed_code_line_indices
| claimed_form_line_indices
| claimed_graphic_line_indices,
)
vector_formula_blocks, claimed_vector_number_indices = _build_vector_formula_blocks(
- source,
+ analysis_source,
table_blocks
+ + rule_code_blocks
+ code_blocks
+ form_image_blocks
+ graphic_blocks
@@ -319,6 +365,12 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
source.page_size,
table_bboxes,
)
+ # 首轮同行合并可能补齐宿主 bbox,使相邻 hard-split 尾段具备二次闭包条件。
+ remaining_lines = _merge_same_baseline_text_lines(
+ remaining_lines,
+ source.page_size,
+ table_bboxes,
+ )
_compact_prepared_lines(remaining_lines, source.page_size)
prepared = _PreparedPage(
page_size=source.page_size,
@@ -326,7 +378,8 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
table_bboxes=table_bboxes,
drawing_lines=source.drawing_lines,
fixed_blocks=(
- table_blocks
+ rule_code_blocks
+ + table_blocks
+ code_blocks
+ form_image_blocks
+ graphic_blocks
@@ -374,16 +427,21 @@ def _finalize_prepared_page(
if line.semantic_type is not None
)
formula_input = [line for line in unresolved_lines if line.semantic_type is None]
- formula_blocks, remaining_lines = _build_formula_like_blocks(
+ formula_input = _restore_dense_split_visual_rows(
formula_input,
- prepared.table_bboxes,
prepared.page_size,
+ prepared.table_bboxes,
)
- remaining_lines = _restore_dense_split_visual_rows(
- remaining_lines,
+ formula_input = _merge_same_baseline_text_lines(
+ formula_input,
prepared.page_size,
prepared.table_bboxes,
)
+ formula_blocks, remaining_lines = _build_formula_like_blocks(
+ formula_input,
+ prepared.table_bboxes,
+ prepared.page_size,
+ )
fallback_index_blocks, remaining_lines = _extract_index_blocks(
remaining_lines,
prepared.page_size,
@@ -405,6 +463,11 @@ def _finalize_prepared_page(
for block in prepared.fixed_blocks
if not isinstance(block.get("_inline_visual_row_id"), int)
]
+ caption_container_bboxes = [
+ block["bbox"]
+ for block in prepared.fixed_blocks
+ if block.get("type") in {"image", "code"}
+ ]
_classify_body_height_section_titles(
remaining_lines,
prepared.page_size,
@@ -416,6 +479,7 @@ def _finalize_prepared_page(
prepared.page_size,
page_index=page_index,
container_bboxes=title_container_bboxes,
+ caption_container_bboxes=caption_container_bboxes,
document_body_profile=document_body_profile,
document_title_profile=document_title_profile,
)
@@ -435,6 +499,12 @@ def _finalize_prepared_page(
prepared.drawing_lines,
page_footnote_groups=prepared.page_footnote_groups,
)
+ text_blocks = _merge_multiline_title_blocks(text_blocks)
+ text_blocks = _merge_front_matter_column_blocks(
+ text_blocks,
+ prepared.page_size,
+ page_index=page_index,
+ )
text_blocks = _merge_image_caption_text_blocks(
text_blocks,
[
diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.py
index 180614ae..92cc70fb 100644
--- a/mineru/backend/flash/native_pdf/text_blocks.py
+++ b/mineru/backend/flash/native_pdf/text_blocks.py
@@ -882,7 +882,429 @@ def _build_text_blocks(
"_lane_is_span": component_local_lane.is_span,
}
)
- return _merge_spatial_text_components(blocks, page_size)
+ blocks = _merge_spatial_text_components(blocks, page_size)
+ blocks = _merge_overlapping_same_line_text_blocks(blocks, page_size)
+ return _merge_inline_math_fragment_text_blocks(blocks, page_size)
+
+
+def _merge_overlapping_same_line_text_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """合并同左沿且纵向重叠的宽正文块,修复同一视觉行被错误分栏的问题。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for first_index, first in enumerate(blocks):
+ first_bbox = first.get("bbox")
+ first_rows = first.get("_local_line_bboxes")
+ angle = int(first.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ if (
+ first_index in consumed
+ or first.get("type") != "text"
+ or not isinstance(first_bbox, (list, tuple))
+ or not isinstance(first_rows, list)
+ or not 1 <= len(first_rows) <= 2
+ or first_bbox[2] - first_bbox[0] < 0.3 * local_page_width
+ ):
+ continue
+ first_heights = [
+ float(height)
+ for height in first.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ first_height = (
+ statistics.median(first_heights)
+ if first_heights
+ else first_bbox[3] - first_bbox[1]
+ )
+ for second_index in range(first_index + 1, len(blocks)):
+ second = blocks[second_index]
+ second_bbox = second.get("bbox")
+ second_rows = second.get("_local_line_bboxes")
+ if (
+ second_index in consumed
+ or second.get("type") != "text"
+ or int(second.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(second_bbox, (list, tuple))
+ or not isinstance(second_rows, list)
+ or not 1 <= len(second_rows) <= 2
+ or min(len(first_rows), len(second_rows)) != 1
+ or second_bbox[2] - second_bbox[0] < 0.3 * local_page_width
+ ):
+ continue
+ second_heights = [
+ float(height)
+ for height in second.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ second_height = (
+ statistics.median(second_heights)
+ if second_heights
+ else second_bbox[3] - second_bbox[1]
+ )
+ pair_height = max(first_height, second_height, 0.1)
+ vertical_overlap = max(
+ 0.0,
+ min(first_bbox[3], second_bbox[3])
+ - max(first_bbox[1], second_bbox[1]),
+ )
+ minimum_box_height = max(
+ 0.1,
+ min(
+ first_bbox[3] - first_bbox[1],
+ second_bbox[3] - second_bbox[1],
+ ),
+ )
+ first_fonts = first.get("_font_signatures")
+ second_fonts = second.get("_font_signatures")
+ if (
+ abs(first_bbox[0] - second_bbox[0]) > pair_height
+ or vertical_overlap / minimum_box_height < 0.5
+ or _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x")
+ < 0.75
+ or (
+ isinstance(first_fonts, set)
+ and isinstance(second_fonts, set)
+ and first_fonts
+ and second_fonts
+ and first_fonts.isdisjoint(second_fonts)
+ )
+ ):
+ continue
+ union_bbox = _bbox_union_many([first_bbox, second_bbox])
+ if union_bbox[3] - union_bbox[1] > 4.0 * pair_height:
+ continue
+ replacement_index = min(first_index, second_index)
+ replacements[replacement_index] = _merge_internal_text_block_group(
+ blocks,
+ [first_index, second_index],
+ )
+ consumed.update({first_index, second_index})
+ break
+ return [
+ replacements.get(index, block)
+ for index, block in enumerate(blocks)
+ if index not in consumed or index in replacements
+ ]
+
+
+def _merge_inline_math_fragment_text_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把同一宽正文行上下叠放的多个小数学碎片收回一个文本块。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for host_index, host in enumerate(blocks):
+ host_bbox = host.get("bbox")
+ host_heights = host.get("_line_heights")
+ host_rows = host.get("_local_line_bboxes")
+ angle = int(host.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ if (
+ host_index in consumed
+ or host.get("type") != "text"
+ or (
+ host.get("_single_run_row_id") is None
+ and (
+ not isinstance(host_rows, list)
+ or len(host_rows) > 2
+ )
+ )
+ or not isinstance(host_bbox, (list, tuple))
+ or host_bbox[2] - host_bbox[0] < 0.35 * local_page_width
+ or not isinstance(host_heights, list)
+ or not host_heights
+ ):
+ continue
+ host_height = statistics.median(
+ float(height)
+ for height in host_heights
+ if isinstance(height, (int, float)) and height > 0
+ )
+ fragment_indices: list[int] = []
+ for candidate_index, candidate in enumerate(blocks):
+ candidate_bbox = candidate.get("bbox")
+ candidate_rows = candidate.get("_local_line_bboxes")
+ if (
+ candidate_index == host_index
+ or candidate_index in consumed
+ or candidate.get("type") != "text"
+ or int(candidate.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(candidate_bbox, (list, tuple))
+ or not isinstance(candidate_rows, list)
+ or len(candidate_rows) != 1
+ or candidate_bbox[2] - candidate_bbox[0]
+ > 0.25 * (host_bbox[2] - host_bbox[0])
+ or _bbox_axis_overlap_ratio(
+ host_bbox,
+ candidate_bbox,
+ axis="x",
+ )
+ <= 0.0
+ ):
+ continue
+ union_bbox = _bbox_union_many([host_bbox, candidate_bbox])
+ vertical_gap = max(
+ 0.0,
+ max(host_bbox[1], candidate_bbox[1])
+ - min(host_bbox[3], candidate_bbox[3]),
+ )
+ if (
+ vertical_gap <= 0.75 * host_height
+ and union_bbox[3] - union_bbox[1] <= 3.5 * host_height
+ ):
+ fragment_indices.append(candidate_index)
+ if len(fragment_indices) < 2:
+ continue
+ group_indices = [host_index, *fragment_indices]
+ replacement_index = min(group_indices)
+ replacements[replacement_index] = _merge_internal_text_block_group(
+ blocks,
+ group_indices,
+ )
+ consumed.update(group_indices)
+ output = [
+ replacements.get(index, block)
+ for index, block in enumerate(blocks)
+ if index not in consumed or index in replacements
+ ]
+ output = _merge_hostless_inline_math_fragment_blocks(output, page_size)
+ return _merge_residual_narrow_math_text_blocks(output, page_size)
+
+
+def _merge_residual_narrow_math_text_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把仍嵌在宽正文行范围内的单个窄数学碎片吸收到唯一宿主块。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for candidate_index, candidate in enumerate(blocks):
+ candidate_bbox = candidate.get("bbox")
+ candidate_rows = candidate.get("_local_line_bboxes")
+ angle = int(candidate.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ if (
+ candidate.get("type") != "text"
+ or not isinstance(candidate_bbox, (list, tuple))
+ or not isinstance(candidate_rows, list)
+ or len(candidate_rows) != 1
+ or candidate_bbox[2] - candidate_bbox[0] > 0.05 * local_page_width
+ ):
+ continue
+ candidate_heights = [
+ float(height)
+ for height in candidate.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ candidate_height = (
+ statistics.median(candidate_heights)
+ if candidate_heights
+ else candidate_bbox[3] - candidate_bbox[1]
+ )
+ hosts: list[tuple[float, float, int]] = []
+ for host_index, host in enumerate(blocks):
+ host_bbox = host.get("bbox")
+ host_heights = [
+ float(height)
+ for height in host.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ if (
+ host_index == candidate_index
+ or host_index in consumed
+ or host.get("type") != "text"
+ or int(host.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(host_bbox, (list, tuple))
+ or host_bbox[2] - host_bbox[0] < 0.3 * local_page_width
+ or candidate_bbox[0] < host_bbox[0]
+ or candidate_bbox[2] > host_bbox[2]
+ ):
+ continue
+ host_height = (
+ statistics.median(host_heights)
+ if host_heights
+ else host_bbox[3] - host_bbox[1]
+ )
+ vertical_overlap = max(
+ 0.0,
+ min(candidate_bbox[3], host_bbox[3])
+ - max(candidate_bbox[1], host_bbox[1]),
+ )
+ vertical_gap = max(
+ 0.0,
+ max(candidate_bbox[1], host_bbox[1])
+ - min(candidate_bbox[3], host_bbox[3]),
+ )
+ pair_height = max(candidate_height, host_height, 0.1)
+ union_bbox = _bbox_union_many([candidate_bbox, host_bbox])
+ if (
+ vertical_overlap < 0.35 * min(candidate_height, host_height)
+ and vertical_gap > 0.5 * pair_height
+ ) or union_bbox[3] - union_bbox[1] > 3.0 * pair_height:
+ continue
+ hosts.append(
+ (
+ -vertical_overlap,
+ abs(_bbox_center_y(candidate_bbox) - _bbox_center_y(host_bbox)),
+ host_index,
+ )
+ )
+ if len(hosts) != 1:
+ continue
+ host_index = hosts[0][2]
+ replacement_index = min(candidate_index, host_index)
+ replacements[replacement_index] = _merge_internal_text_block_group(
+ blocks,
+ [candidate_index, host_index],
+ )
+ consumed.update({candidate_index, host_index})
+ return [
+ replacements.get(index, block)
+ for index, block in enumerate(blocks)
+ if index not in consumed or index in replacements
+ ]
+
+
+def _merge_hostless_inline_math_fragment_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把没有单一宽宿主但在一栏内二维密集排列的数学碎片合成文本块。"""
+
+ grouped_indices: list[list[int]] = []
+ for angle in sorted(
+ {
+ int(block.get("angle", 0) or 0) % 360
+ for block in blocks
+ if block.get("type") == "text"
+ }
+ ):
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ candidates = {
+ 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("bbox"), (list, tuple))
+ and isinstance(block.get("_local_line_bboxes"), list)
+ and len(block["_local_line_bboxes"]) == 1
+ and block["bbox"][2] - block["bbox"][0]
+ <= 0.25 * local_page_width
+ }
+ while candidates:
+ component = {candidates.pop()}
+ changed = True
+ while changed:
+ changed = False
+ for candidate_index in list(candidates):
+ candidate_bbox = blocks[candidate_index]["bbox"]
+ candidate_heights = blocks[candidate_index].get(
+ "_line_heights",
+ [],
+ )
+ candidate_height = (
+ statistics.median(candidate_heights)
+ if candidate_heights
+ else candidate_bbox[3] - candidate_bbox[1]
+ )
+ if any(
+ (
+ max(
+ 0.0,
+ max(candidate_bbox[1], blocks[index]["bbox"][1])
+ - min(candidate_bbox[3], blocks[index]["bbox"][3]),
+ )
+ <= 0.75 * max(
+ candidate_height,
+ statistics.median(
+ blocks[index].get("_line_heights", [])
+ )
+ if blocks[index].get("_line_heights")
+ else blocks[index]["bbox"][3]
+ - blocks[index]["bbox"][1],
+ )
+ and max(
+ 0.0,
+ max(candidate_bbox[0], blocks[index]["bbox"][0])
+ - min(candidate_bbox[2], blocks[index]["bbox"][2]),
+ )
+ <= 1.5 * max(
+ candidate_height,
+ statistics.median(
+ blocks[index].get("_line_heights", [])
+ )
+ if blocks[index].get("_line_heights")
+ else blocks[index]["bbox"][3]
+ - blocks[index]["bbox"][1],
+ )
+ )
+ for index in component
+ ):
+ component.add(candidate_index)
+ candidates.remove(candidate_index)
+ changed = True
+ if len(component) < 4:
+ continue
+ component_heights = [
+ float(height)
+ for index in component
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ if not component_heights:
+ continue
+ median_height = statistics.median(component_heights)
+ union_bbox = _bbox_union_many(
+ [blocks[index]["bbox"] for index in component]
+ )
+ font_signatures = set().union(
+ *[
+ signatures
+ for index in component
+ if isinstance(
+ (signatures := blocks[index].get("_font_signatures")),
+ set,
+ )
+ ]
+ )
+ if (
+ len(font_signatures) < 2
+ or not 0.25 * local_page_width
+ <= union_bbox[2] - union_bbox[0]
+ <= 0.5 * local_page_width
+ or union_bbox[3] - union_bbox[1] > 3.5 * median_height
+ or sum(
+ blocks[index]["bbox"][2] - blocks[index]["bbox"][0]
+ >= 3.5 * median_height
+ for index in component
+ )
+ < 2
+ ):
+ continue
+ grouped_indices.append(sorted(component))
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for group in grouped_indices:
+ if any(index in consumed for index in group):
+ continue
+ replacement_index = min(group)
+ replacements[replacement_index] = _merge_internal_text_block_group(
+ blocks,
+ group,
+ )
+ consumed.update(group)
+ return [
+ replacements.get(index, block)
+ for index, block in enumerate(blocks)
+ if index not in consumed or index in replacements
+ ]
def _merge_image_caption_text_blocks(
@@ -907,6 +1329,10 @@ def _merge_image_caption_text_blocks(
if isinstance(height, (int, float)) and height > 0
]
median_height = statistics.median(all_heights) if all_heights else 1.0
+ caption_image_bboxes = _caption_image_group_bboxes(
+ image_bboxes,
+ median_height,
+ )
seed_indices = {
index
for index in text_indices
@@ -917,7 +1343,7 @@ def _merge_image_caption_text_blocks(
image_bbox,
median_height,
)
- for image_bbox in image_bboxes
+ for image_bbox in caption_image_bboxes
)
}
if not seed_indices:
@@ -967,6 +1393,54 @@ def _merge_image_caption_text_blocks(
]
+def _caption_image_group_bboxes(
+ image_bboxes: list[BBox],
+ median_height: float,
+) -> list[BBox]:
+ """合并同一视觉行的并排图片 bbox,使跨多图的统一图注也能建立邻接。"""
+
+ remaining = list(image_bboxes)
+ grouped_bboxes = list(image_bboxes)
+ while remaining:
+ group = [remaining.pop(0)]
+ changed = True
+ while changed:
+ changed = False
+ for candidate in list(remaining):
+ aligned = False
+ for member in group:
+ overlap = max(
+ 0.0,
+ min(candidate[3], member[3])
+ - max(candidate[1], member[1]),
+ )
+ minimum_height = max(
+ 0.1,
+ min(
+ candidate[3] - candidate[1],
+ member[3] - member[1],
+ ),
+ )
+ horizontal_gap = max(
+ 0.0,
+ max(candidate[0], member[0])
+ - min(candidate[2], member[2]),
+ )
+ if (
+ overlap / minimum_height >= 0.7
+ and horizontal_gap <= 2.0 * median_height
+ ):
+ aligned = True
+ break
+ if aligned:
+ group.append(candidate)
+ remaining.remove(candidate)
+ changed = True
+ if len(group) >= 2:
+ grouped_bboxes.append(_bbox_union_many(group))
+ return grouped_bboxes
+
+
def _caption_seed_matches_image(
block: dict[str, Any],
image_bbox: BBox,
@@ -1056,19 +1530,20 @@ def _caption_tail_matches_seed(
) -> bool:
"""只用同栏角色、字体、邻接和投影把无标记的图注续行接回锚点。"""
- if not _components_share_lane_role(seed, candidate, median_height):
- return False
seed_bbox = seed["bbox"]
candidate_bbox = candidate["bbox"]
+ if not _components_share_lane_role(seed, candidate, median_height) and (
+ _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.75
+ or abs(seed_bbox[0] - candidate_bbox[0]) > median_height
+ ):
+ return False
if _bbox_center_y(candidate_bbox) <= _bbox_center_y(seed_bbox):
return False
if _caption_body_has_structural_gap(seed, candidate):
return False
vertical_gap = max(0.0, candidate_bbox[1] - seed_bbox[3])
if (
- vertical_gap > 1.25 * median_height
- or _bbox_center_y(candidate_bbox) - _bbox_center_y(seed_bbox)
- > 2.0 * median_height
+ vertical_gap > 0.5 * median_height
or _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.35
):
return False
@@ -1083,16 +1558,98 @@ def _caption_tail_matches_seed(
)
+def _merge_multiline_title_blocks(
+ blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """跨错误栏带合并紧贴且字体兼容的多行文档标题和段落标题。"""
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for block_type in ("doc_title", "paragraph_title"):
+ indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == block_type
+ and isinstance(block.get("bbox"), (list, tuple))
+ ]
+ indices.sort(
+ key=lambda index: (
+ blocks[index]["bbox"][1],
+ blocks[index]["bbox"][0],
+ )
+ )
+ groups: list[list[int]] = []
+ for index in indices:
+ if not groups:
+ groups.append([index])
+ continue
+ previous_index = groups[-1][-1]
+ previous = blocks[previous_index]
+ current = blocks[index]
+ previous_bbox = previous["bbox"]
+ current_bbox = current["bbox"]
+ previous_heights = previous.get("_line_heights", [])
+ current_heights = current.get("_line_heights", [])
+ previous_height = (
+ statistics.median(previous_heights)
+ if isinstance(previous_heights, list) and previous_heights
+ else previous_bbox[3] - previous_bbox[1]
+ )
+ current_height = (
+ statistics.median(current_heights)
+ if isinstance(current_heights, list) and current_heights
+ else current_bbox[3] - current_bbox[1]
+ )
+ vertical_gap = current_bbox[1] - previous_bbox[3]
+ previous_fonts = previous.get("_font_signatures")
+ current_fonts = current.get("_font_signatures")
+ fonts_conflict = (
+ isinstance(previous_fonts, set)
+ and previous_fonts
+ and isinstance(current_fonts, set)
+ and current_fonts
+ and previous_fonts.isdisjoint(current_fonts)
+ )
+ if (
+ -0.2 * max(previous_height, current_height)
+ <= vertical_gap
+ <= 0.4 * max(previous_height, current_height)
+ and _bbox_axis_overlap_ratio(
+ previous_bbox,
+ current_bbox,
+ axis="x",
+ )
+ >= 0.2
+ and not fonts_conflict
+ ):
+ groups[-1].append(index)
+ else:
+ groups.append([index])
+ for group in groups:
+ if len(group) < 2:
+ continue
+ replacements[group[0]] = _merge_internal_text_block_group(
+ blocks,
+ group,
+ )
+ consumed.update(group[1:])
+ return [
+ replacements.get(index, block)
+ for index, block in enumerate(blocks)
+ if index not in consumed
+ ]
+
+
def _merge_fragmented_header_blocks(
blocks: list[dict[str, Any]],
) -> list[dict[str, Any]]:
- """聚合同一视觉行中等距分散的窄页眉字形,同时保留远端卷期信息。"""
+ """聚合同一视觉行中等距分散的页眉页脚片段。"""
grouped: dict[tuple[int, int], list[int]] = {}
for index, block in enumerate(blocks):
row_id = block.get("_single_run_row_id")
angle = int(block.get("angle", 0) or 0) % 360
- if block.get("type") == "header" and isinstance(row_id, int):
+ if block.get("type") in {"header", "footer"} and isinstance(row_id, int):
grouped.setdefault((angle, row_id), []).append(index)
replacements: dict[int, dict[str, Any]] = {}
@@ -1108,7 +1665,10 @@ def _merge_fragmented_header_blocks(
if isinstance(heights, list) and heights
else max(0.1, bbox[3] - bbox[1])
)
- if bbox[2] - bbox[0] > 1.25 * effective_height:
+ if (
+ blocks[index].get("type") == "header"
+ and bbox[2] - bbox[0] > 1.25 * effective_height
+ ):
continue
if not components:
components.append([index])
@@ -1147,6 +1707,152 @@ def _merge_fragmented_header_blocks(
]
+def _merge_front_matter_column_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ *,
+ page_index: int,
+) -> list[dict[str, Any]]:
+ """把首页标题下方规则排列的多列作者信息按列聚合。"""
+
+ if page_index != 0:
+ return blocks
+ page_width, page_height = page_size
+ if page_width <= 0 or page_height <= 0:
+ return blocks
+ title_blocks = [
+ block
+ for block in blocks
+ if block.get("type") == "doc_title"
+ and isinstance(block.get("bbox"), (list, tuple))
+ ]
+ if not title_blocks:
+ return blocks
+ title_bottom = max(block["bbox"][3] for block in title_blocks)
+ candidates = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text"
+ and isinstance(block.get("bbox"), (list, tuple))
+ and title_bottom < block["bbox"][1]
+ and block["bbox"][3] <= min(
+ 0.4 * page_height,
+ title_bottom + 0.22 * page_height,
+ )
+ and block["bbox"][2] - block["bbox"][0] <= 0.32 * page_width
+ and block["bbox"][3] - block["bbox"][1] <= 0.035 * page_height
+ ]
+ if len(candidates) < 9:
+ return blocks
+ median_height = statistics.median(
+ blocks[index]["bbox"][3] - blocks[index]["bbox"][1]
+ for index in candidates
+ )
+ row_groups: list[list[int]] = []
+ for index in sorted(
+ candidates,
+ key=lambda item: (
+ _bbox_center_y(blocks[item]["bbox"]),
+ blocks[item]["bbox"][0],
+ ),
+ ):
+ center_y = _bbox_center_y(blocks[index]["bbox"])
+ target = next(
+ (
+ row
+ for row in row_groups
+ if abs(
+ center_y
+ - statistics.median(
+ _bbox_center_y(blocks[member]["bbox"])
+ for member in row
+ )
+ )
+ <= 0.6 * median_height
+ ),
+ None,
+ )
+ if target is None:
+ row_groups.append([index])
+ else:
+ target.append(index)
+ dense_rows = [
+ row
+ for row in row_groups
+ if 3 <= len(row) <= 6
+ and (
+ max(blocks[index]["bbox"][2] for index in row)
+ - min(blocks[index]["bbox"][0] for index in row)
+ >= 0.55 * page_width
+ )
+ ]
+ if len(dense_rows) < 2:
+ return blocks
+ anchor_row = min(
+ dense_rows,
+ key=lambda row: (
+ -len(row),
+ statistics.median(
+ _bbox_center_y(blocks[index]["bbox"])
+ for index in row
+ ),
+ ),
+ )
+ anchor_centers = sorted(
+ _bbox_center_x(blocks[index]["bbox"])
+ for index in anchor_row
+ )
+ if len(anchor_centers) != 4:
+ return blocks
+ boundaries = [
+ 0.5 * (left + right)
+ for left, right in zip(anchor_centers, anchor_centers[1:])
+ ]
+ band_top = min(
+ min(blocks[index]["bbox"][1] for index in row)
+ for row in dense_rows
+ ) - median_height
+ band_bottom = max(
+ max(blocks[index]["bbox"][3] for index in row)
+ for row in dense_rows
+ ) + median_height
+ column_groups: list[list[int]] = [
+ [] for _center in anchor_centers
+ ]
+ for index in candidates:
+ bbox = blocks[index]["bbox"]
+ if not band_top <= _bbox_center_y(bbox) <= band_bottom:
+ continue
+ center_x = _bbox_center_x(bbox)
+ column_index = sum(center_x > boundary for boundary in boundaries)
+ if column_index >= len(column_groups):
+ continue
+ column_groups[column_index].append(index)
+ if any(len(group) < 3 for group in column_groups):
+ return blocks
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for group in column_groups:
+ ordered = sorted(
+ group,
+ key=lambda index: (
+ blocks[index]["bbox"][1],
+ blocks[index]["bbox"][0],
+ ),
+ )
+ replacements[ordered[0]] = _merge_internal_text_block_group(
+ blocks,
+ ordered,
+ )
+ consumed.update(ordered[1:])
+ return [
+ replacements.get(index, block)
+ for index, block in enumerate(blocks)
+ if index not in consumed
+ ]
+
+
def _merge_repeated_compact_title_continuations(
blocks: list[dict[str, Any]],
page_size: tuple[float, float],
@@ -1248,7 +1954,11 @@ def _merge_internal_text_block_group(
ordered_indices = sorted(
indices,
- key=lambda index: _text_component_sort_key(blocks[index]),
+ key=(
+ (lambda index: blocks[index]["bbox"][0])
+ if preserve_visual_spaces
+ else (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])
diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.py
index a80e10ad..5201658e 100644
--- a/mineru/backend/flash/native_pdf/titles.py
+++ b/mineru/backend/flash/native_pdf/titles.py
@@ -51,6 +51,7 @@ def _classify_page_titles(
*,
page_index: int,
container_bboxes: list[BBox],
+ caption_container_bboxes: list[BBox] | None = None,
document_body_profile: _DocumentBodyProfile | None = None,
document_title_profile: _DocumentTitleProfile | None = None,
) -> None:
@@ -97,11 +98,35 @@ def _classify_page_titles(
local_page_width,
document_body_profile=document_body_profile,
)
+ document_title_bottom = _expand_document_title_across_lanes(
+ line_geometry,
+ local_page_width,
+ local_page_height,
+ document_title_bottom,
+ )
preserve_front_matter_boundaries = _document_title_uses_page_fallback(
lanes,
document_body_profile=document_body_profile,
)
+ _classify_cross_lane_centered_section_titles(
+ line_geometry,
+ lanes,
+ local_page_width,
+ local_page_height,
+ local_container_bboxes,
+ document_title_bottom=document_title_bottom,
+ )
+ _classify_cross_lane_emphasized_section_titles(
+ line_geometry,
+ lanes,
+ local_page_width,
+ local_page_height,
+ local_container_bboxes,
+ document_title_bottom=document_title_bottom,
+ document_body_profile=document_body_profile,
+ )
+
for lane in lanes:
profile = _infer_lane_body_profile(lane)
_classify_paragraph_titles_in_lane(
@@ -118,6 +143,20 @@ def _classify_page_titles(
document_title_profile=document_title_profile,
page_index=page_index,
)
+ _expand_cross_lane_paragraph_title_neighbors(
+ line_geometry,
+ )
+ _demote_cross_lane_body_continuation_titles(
+ line_geometry,
+ lanes,
+ )
+ _demote_visual_container_caption_titles(
+ line_geometry,
+ [
+ _rotate_bbox_to_upright(bbox, page_size, angle)
+ for bbox in (caption_container_bboxes or [])
+ ],
+ )
def _infer_document_body_profile(
@@ -325,6 +364,8 @@ def _classify_body_height_section_titles(
if len(followers) < 3:
continue
gap_above = physical_gaps.get(line.source_index, (None, None))[0]
+ if gap_above is not None and gap_above <= 0.25 * body_height:
+ continue
starts_body = (
gap_above is None
and bbox[1] <= 0.2 * local_page_height
@@ -930,6 +971,493 @@ def _classify_document_title(
return max(bbox[3] for _line, bbox in selected)
+def _expand_document_title_across_lanes(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ local_page_width: float,
+ local_page_height: float,
+ document_title_bottom: float | None,
+) -> float | None:
+ """跨错误推断栏扩展紧邻、同字号且对齐的多行文档标题。"""
+
+ title_items = [
+ item
+ for item in line_geometry
+ if item[0].semantic_type == "doc_title"
+ ]
+ if not title_items:
+ return document_title_bottom
+ selected_ids = {id(line) for line, _bbox in title_items}
+ changed = True
+ while changed:
+ changed = False
+ title_bbox = _bbox_union_many([bbox for _line, bbox in title_items])
+ title_height = statistics.median(
+ _line_effective_height(line, bbox)
+ for line, bbox in title_items
+ )
+ anchors = [line for line, _bbox in title_items]
+ candidates = [
+ item
+ for item in line_geometry
+ if id(item[0]) not in selected_ids
+ and item[0].semantic_type is None
+ and _bbox_center_y(item[1]) <= 0.45 * local_page_height
+ ]
+ candidates.sort(
+ key=lambda item: min(
+ abs(item[1][1] - title_bbox[3]),
+ abs(title_bbox[1] - item[1][3]),
+ )
+ )
+ for candidate_line, candidate_bbox in candidates:
+ candidate_height = _line_effective_height(
+ candidate_line,
+ candidate_bbox,
+ )
+ if not 0.8 <= candidate_height / max(0.1, title_height) <= 1.25:
+ continue
+ if not any(
+ _document_title_fonts_compatible(anchor, candidate_line)
+ for anchor in anchors
+ ):
+ continue
+ vertical_gap = max(
+ candidate_bbox[1] - title_bbox[3],
+ title_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ centered = (
+ abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox))
+ <= 0.18 * local_page_width
+ )
+ aligned = (
+ abs(candidate_bbox[0] - title_bbox[0])
+ <= 0.75 * title_height
+ )
+ title_width = max(0.1, title_bbox[2] - title_bbox[0])
+ candidate_width = candidate_bbox[2] - candidate_bbox[0]
+ aligned_continuation = (
+ aligned and candidate_width >= 0.25 * title_width
+ )
+ centered_continuation = (
+ centered and candidate_width >= 0.45 * title_width
+ )
+ if (
+ vertical_gap > 1.1 * title_height
+ or not (aligned_continuation or centered_continuation)
+ ):
+ continue
+ candidate_line.semantic_type = "doc_title"
+ title_items.append((candidate_line, candidate_bbox))
+ selected_ids.add(id(candidate_line))
+ changed = True
+ break
+ return max(bbox[3] for _line, bbox in title_items)
+
+
+def _classify_cross_lane_centered_section_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+ local_page_width: float,
+ local_page_height: float,
+ container_bboxes: list[BBox],
+ *,
+ document_title_bottom: float | None,
+) -> None:
+ """用正文栏中心、上下留白和正文邻行补标被单独推成窄栏的标题。"""
+
+ stable_lanes = [
+ lane
+ for lane in lanes
+ if not lane.is_span
+ and len(lane.lines) >= 5
+ and lane.right - lane.left >= 0.2 * local_page_width
+ ]
+ for line, bbox in line_geometry:
+ if line.semantic_type is not None:
+ continue
+ if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
+ continue
+ candidate_lanes = [
+ lane
+ for lane in stable_lanes
+ if lane.left <= _bbox_center_x(bbox) <= lane.right
+ ]
+ if not candidate_lanes:
+ continue
+ lane = min(
+ candidate_lanes,
+ key=lambda candidate: abs(
+ _bbox_center_x(bbox)
+ - 0.5 * (candidate.left + candidate.right)
+ ),
+ )
+ profile = _infer_lane_body_profile(lane)
+ lane_width = max(0.1, lane.right - lane.left)
+ line_width = bbox[2] - bbox[0]
+ line_height = _line_effective_height(line, bbox)
+ if not 0.08 * lane_width <= line_width <= 0.7 * lane_width:
+ continue
+ if (
+ abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right))
+ > 0.05 * lane_width
+ ):
+ continue
+ if not 0.75 <= line_height / max(0.1, profile.body_height) <= 1.3:
+ continue
+ if (
+ document_title_bottom is not None
+ and bbox[1] <= document_title_bottom + profile.body_height
+ ):
+ continue
+ if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
+ bbox,
+ container_bboxes,
+ profile.body_height,
+ ):
+ continue
+ body_rows = [
+ item
+ for item in lane.lines
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[1][2] - item[1][0] >= 0.5 * lane_width
+ and 0.75
+ <= _line_effective_height(*item) / max(0.1, profile.body_height)
+ <= 1.3
+ ]
+ rows_above = [
+ item
+ for item in body_rows
+ if _bbox_center_y(item[1]) < _bbox_center_y(bbox)
+ ]
+ rows_below = [
+ item
+ for item in body_rows
+ if _bbox_center_y(item[1]) > _bbox_center_y(bbox)
+ ]
+ if not rows_above or not rows_below:
+ continue
+ previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
+ following_rows = sorted(
+ rows_below,
+ key=lambda item: _bbox_center_y(item[1]),
+ )
+ if len(following_rows) < 3 or any(
+ _effective_text_row_gap(previous_row, current_row)
+ > profile.regular_gap + 0.75 * profile.body_height
+ for previous_row, current_row in zip(
+ following_rows[:3],
+ following_rows[1:3],
+ )
+ ):
+ continue
+ following = following_rows[0]
+ gap_above = bbox[1] - previous[1][3]
+ gap_below = following[1][1] - bbox[3]
+ if (
+ gap_above < 0.3 * profile.body_height
+ or gap_below < -0.1 * profile.body_height
+ or max(gap_above, gap_below)
+ < profile.regular_gap + 0.2 * profile.body_height
+ ):
+ continue
+ line.semantic_type = "paragraph_title"
+
+
+def _demote_cross_lane_body_continuation_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+) -> None:
+ """把紧接上一正文行、同字号同字体的短续行从标题降回正文。"""
+
+ stable_lanes = [
+ lane
+ for lane in lanes
+ if not lane.is_span and len(lane.lines) >= 4
+ ]
+ for line, bbox in line_geometry:
+ if line.semantic_type != "paragraph_title":
+ continue
+ line_height = _line_effective_height(line, bbox)
+ global_preceding = [
+ item
+ for item in line_geometry
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[0].angle == line.angle
+ and _bbox_center_y(item[1]) < _bbox_center_y(bbox)
+ and abs(item[1][0] - bbox[0]) <= line_height
+ ]
+ if global_preceding:
+ previous_line, previous_bbox = max(
+ global_preceding,
+ key=lambda item: _bbox_center_y(item[1]),
+ )
+ previous_height = _line_effective_height(
+ previous_line,
+ previous_bbox,
+ )
+ same_family = (
+ previous_line.font_signature is None
+ or line.font_signature is None
+ or _font_signatures_share_family(
+ previous_line.font_signature,
+ line.font_signature,
+ )
+ )
+ if (
+ same_family
+ and 0.9
+ <= line_height / max(0.1, previous_height)
+ <= 1.1
+ and bbox[1] - previous_bbox[3]
+ <= 0.2 * max(line_height, previous_height)
+ and abs(bbox[0] - previous_bbox[0])
+ <= 0.75 * max(line_height, previous_height)
+ and previous_bbox[2] - previous_bbox[0]
+ >= 2.0 * (bbox[2] - bbox[0])
+ ):
+ line.semantic_type = None
+ continue
+ candidate_lanes = [
+ lane
+ for lane in stable_lanes
+ if lane.left <= _bbox_center_x(bbox) <= lane.right
+ ]
+ if not candidate_lanes:
+ continue
+ lane = min(
+ candidate_lanes,
+ key=lambda candidate: abs(
+ _bbox_center_x(bbox)
+ - 0.5 * (candidate.left + candidate.right)
+ ),
+ )
+ lane_width = max(0.1, lane.right - lane.left)
+ if bbox[2] - bbox[0] > 0.55 * lane_width:
+ continue
+ preceding = [
+ item
+ for item in line_geometry
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and _bbox_center_y(item[1]) < _bbox_center_y(bbox)
+ and lane.left <= _bbox_center_x(item[1]) <= lane.right
+ ]
+ if not preceding:
+ continue
+ previous_line, previous_bbox = max(
+ preceding,
+ key=lambda item: _bbox_center_y(item[1]),
+ )
+ previous_height = _line_effective_height(
+ previous_line,
+ previous_bbox,
+ )
+ line_height = _line_effective_height(line, bbox)
+ if not 0.9 <= line_height / max(0.1, previous_height) <= 1.1:
+ continue
+ if (
+ previous_line.font_signature is not None
+ and line.font_signature is not None
+ and not _font_signatures_share_family(
+ previous_line.font_signature,
+ line.font_signature,
+ )
+ ):
+ continue
+ if previous_bbox[2] - previous_bbox[0] < 0.5 * lane_width:
+ continue
+ if bbox[1] - previous_bbox[3] > 0.15 * max(line_height, previous_height):
+ continue
+ if abs(bbox[0] - lane.left) > max(1.0, 0.75 * line_height):
+ continue
+ line.semantic_type = None
+
+
+def _classify_cross_lane_emphasized_section_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+ local_page_width: float,
+ local_page_height: float,
+ container_bboxes: list[BBox],
+ *,
+ document_title_bottom: float | None,
+ document_body_profile: _DocumentBodyProfile | None,
+) -> None:
+ """用正文栏左缘、强调字体和段间留白补标跨栏推断失败的小节标题。"""
+
+ stable_lanes = [
+ lane
+ for lane in lanes
+ if not lane.is_span
+ and len(lane.lines) >= 5
+ and lane.right - lane.left >= 0.2 * local_page_width
+ ]
+ for line, bbox in line_geometry:
+ if line.semantic_type is not None or line.font_signature is None:
+ continue
+ if not line.font_signature[1] & _PDF_FONT_ITALIC_FLAG:
+ continue
+ if _line_uses_document_regular_font(line, document_body_profile):
+ continue
+ if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
+ continue
+ candidate_lanes = [
+ lane
+ for lane in stable_lanes
+ if lane.left <= _bbox_center_x(bbox) <= lane.right
+ ]
+ if not candidate_lanes:
+ continue
+ lane = min(
+ candidate_lanes,
+ key=lambda candidate: abs(bbox[0] - candidate.left),
+ )
+ profile = _infer_lane_body_profile(lane)
+ if (
+ profile.body_font is None
+ or line.font_signature == profile.body_font
+ or line.font_coverage < 0.75
+ ):
+ continue
+ lane_width = max(0.1, lane.right - lane.left)
+ line_height = _line_effective_height(line, bbox)
+ if bbox[2] - bbox[0] > 0.9 * lane_width:
+ continue
+ if abs(bbox[0] - lane.left) > 2.0 * profile.body_height:
+ continue
+ if not 0.8 <= line_height / max(0.1, profile.body_height) <= 1.35:
+ continue
+ if (
+ document_title_bottom is not None
+ and bbox[1] <= document_title_bottom + 2.0 * profile.body_height
+ ):
+ continue
+ if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
+ bbox,
+ container_bboxes,
+ profile.body_height,
+ ):
+ continue
+ body_rows = [
+ item
+ for item in lane.lines
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[0].font_signature == profile.body_font
+ and item[1][2] - item[1][0] >= 0.45 * lane_width
+ ]
+ rows_above = [
+ item
+ for item in body_rows
+ if _bbox_center_y(item[1]) < _bbox_center_y(bbox)
+ ]
+ rows_below = [
+ item
+ for item in body_rows
+ if _bbox_center_y(item[1]) > _bbox_center_y(bbox)
+ ]
+ if not rows_above or not rows_below:
+ continue
+ previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
+ following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
+ gap_above = bbox[1] - previous[1][3]
+ gap_below = following[1][1] - bbox[3]
+ if (
+ gap_above < 0.35 * profile.body_height
+ or gap_below > 3.0 * profile.body_height
+ or gap_below < -0.1 * profile.body_height
+ ):
+ continue
+ line.semantic_type = "paragraph_title"
+
+
+def _expand_cross_lane_paragraph_title_neighbors(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> None:
+ """把紧贴标题锚点的同字体相邻行跨栏补标为同一标题。"""
+
+ changed = True
+ while changed:
+ changed = False
+ title_items = [
+ item
+ for item in line_geometry
+ if item[0].semantic_type == "paragraph_title"
+ ]
+ for title_line, title_bbox in title_items:
+ title_height = _line_effective_height(title_line, title_bbox)
+ for candidate_line, candidate_bbox in line_geometry:
+ if candidate_line.semantic_type is not None:
+ continue
+ candidate_height = _line_effective_height(
+ candidate_line,
+ candidate_bbox,
+ )
+ if not 0.85 <= candidate_height / max(0.1, title_height) <= 1.2:
+ continue
+ title_width = max(0.1, title_bbox[2] - title_bbox[0])
+ candidate_width = candidate_bbox[2] - candidate_bbox[0]
+ if not 0.25 <= candidate_width / title_width <= 2.0:
+ continue
+ if (
+ title_line.font_signature is not None
+ and candidate_line.font_signature is not None
+ and title_line.font_signature != candidate_line.font_signature
+ ):
+ continue
+ vertical_gap = max(
+ candidate_bbox[1] - title_bbox[3],
+ title_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ if vertical_gap > 0.35 * max(title_height, candidate_height):
+ continue
+ if (
+ _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x")
+ < 0.2
+ and abs(candidate_bbox[0] - title_bbox[0])
+ > 2.0 * title_height
+ ):
+ continue
+ candidate_line.semantic_type = "paragraph_title"
+ changed = True
+ break
+ if changed:
+ break
+
+
+def _demote_visual_container_caption_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ container_bboxes: list[BBox],
+) -> None:
+ """把紧贴视觉容器下缘且水平居中的标题候选降回普通图注文本。"""
+
+ for line, bbox in line_geometry:
+ if line.semantic_type != "paragraph_title":
+ continue
+ line_height = _line_effective_height(line, bbox)
+ for container_bbox in container_bboxes:
+ vertical_gap = bbox[1] - container_bbox[3]
+ if not -0.25 * line_height <= vertical_gap <= 1.5 * line_height:
+ continue
+ if _bbox_axis_overlap_ratio(bbox, container_bbox, axis="x") < 0.35:
+ continue
+ if (
+ abs(_bbox_center_x(bbox) - _bbox_center_x(container_bbox))
+ > 0.35
+ * max(
+ container_bbox[2] - container_bbox[0],
+ bbox[2] - bbox[0],
+ )
+ ):
+ continue
+ line.semantic_type = None
+ break
+
+
def _document_title_fonts_compatible(
first: _LineItem,
second: _LineItem,
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index e43b412f..bf2f0d99 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -1075,3 +1075,144 @@ def test_repeated_visual_headers_require_matching_orientation() -> None:
auxiliary_text._classify_repeated_visual_headers(pages)
assert [page.fixed_blocks[0]["type"] for page in pages[1:]] == ["image"] * 3
+
+
+def test_image_bottom_border_does_not_create_image_or_page_footnote() -> None:
+ """验证图片下沿自身的坐标轴横线不会把紧邻图中文字判成脚注。"""
+
+ body = [
+ _text_line(
+ f"body {index}",
+ (50.0, 40.0 + 20.0 * index, 450.0, 50.0 + 20.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ]
+ axis_label = _text_line(
+ "T -1/4",
+ (150.0, 317.0, 230.0, 325.0),
+ 4,
+ effective_height=8.0,
+ )
+ page = _prepared_text_page(
+ *body,
+ axis_label,
+ page_size=(500.0, 500.0),
+ )
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (50.0, 140.0, 300.0, 315.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+ page.drawing_lines = [
+ models._AxisLine(
+ (50.0, 314.0, 300.0, 315.0),
+ 1.0,
+ "horizontal",
+ )
+ ]
+
+ auxiliary_text._classify_page_auxiliary_text(page)
+
+ assert axis_label.semantic_type is None
+ assert page.page_footnote_groups == []
+
+
+def test_two_bottom_rules_classify_centered_url_as_footer() -> None:
+ """验证页面底部两条同跨度横线把其间居中网址标为页脚。"""
+
+ body = [
+ _text_line(
+ f"body {index}",
+ (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ]
+ url = _text_line(
+ "https://example.test/journal",
+ (350.0, 920.0, 650.0, 930.0),
+ 10,
+ effective_height=10.0,
+ )
+ page = _prepared_text_page(
+ *body,
+ url,
+ page_size=(1000.0, 1000.0),
+ )
+ page.drawing_lines = [
+ models._AxisLine((300.0, 900.0, 700.0, 901.0), 1.0, "horizontal"),
+ models._AxisLine((300.0, 950.0, 700.0, 951.0), 1.0, "horizontal"),
+ ]
+
+ auxiliary_text._classify_rule_delimited_footers([page])
+
+ assert url.semantic_type == "footer"
+
+
+def test_split_footer_row_fragments_inherit_stable_anchor_type() -> None:
+ """验证同一页脚视觉行的左右碎片从稳定锚点继承 footer 类型。"""
+
+ fragments = [
+ _text_line(
+ "journal",
+ (100.0, 930.0, 300.0, 940.0),
+ 0,
+ visual_row_id=8,
+ split_from_row=True,
+ ),
+ _text_line(
+ "Vol. 1",
+ (420.0, 930.0, 500.0, 940.0),
+ 1,
+ visual_row_id=8,
+ split_from_row=True,
+ semantic_type="footer",
+ ),
+ _text_line(
+ "No. 2",
+ (650.0, 930.0, 750.0, 940.0),
+ 2,
+ visual_row_id=8,
+ split_from_row=True,
+ ),
+ ]
+ page = _prepared_text_page(
+ *fragments,
+ page_size=(1000.0, 1000.0),
+ )
+
+ auxiliary_text._classify_split_marginal_row_companions([page])
+
+ assert [line.semantic_type for line in fragments] == ["footer"] * 3
+
+
+def test_distant_same_row_text_inherits_top_page_number_header_type() -> None:
+ """验证页码与远距运行标题同基线时不依赖水平距离也能标为页眉。"""
+
+ page_number = _text_line(
+ "8",
+ (10.0, 10.0, 15.0, 15.0),
+ 0,
+ semantic_type="page_number",
+ )
+ running_title = _text_line(
+ "running title",
+ (60.0, 10.0, 90.0, 15.0),
+ 1,
+ )
+ page = _prepared_text_page(
+ page_number,
+ running_title,
+ page_size=(100.0, 100.0),
+ )
+
+ auxiliary_text._classify_page_number_outer_companions([page])
+
+ assert page_number.semantic_type == "page_number"
+ assert running_title.semantic_type == "header"
diff --git a/tests/unittest/test_flash_pdf_code_blocks.py b/tests/unittest/test_flash_pdf_code_blocks.py
index bb5aea94..5cb84094 100644
--- a/tests/unittest/test_flash_pdf_code_blocks.py
+++ b/tests/unittest/test_flash_pdf_code_blocks.py
@@ -139,3 +139,74 @@ def test_code_projection_preserves_columns_and_blank_rows() -> None:
)
assert content == "left right\n\n tail"
+
+
+def _rule_delimited_code_source(
+ *,
+ include_internal_grid: bool = False,
+) -> models._PageSource:
+ """构造带上下边界、行号槽和可选内部网格线的代码清单页面。"""
+
+ lines: list[models._LineItem] = []
+ for row_index, top in enumerate((30.0, 42.0, 54.0, 66.0, 78.0, 90.0)):
+ number = _text_line(
+ str(row_index + 1),
+ (25.0, top, 31.0, top + 8.0),
+ 2 * row_index,
+ visual_row_id=row_index,
+ split_from_row=True,
+ effective_height=8.0,
+ )
+ statement = _text_line(
+ f"statement {row_index}",
+ (42.0 + 6.0 * (row_index % 3), top, 125.0, top + 8.0),
+ 2 * row_index + 1,
+ visual_row_id=row_index,
+ split_from_row=True,
+ effective_height=8.0,
+ )
+ lines.extend((number, statement))
+ drawing_lines = [
+ models._AxisLine((20.0, 20.0, 180.0, 21.0), 1.0, "horizontal"),
+ models._AxisLine((20.0, 104.0, 180.0, 105.0), 1.0, "horizontal"),
+ ]
+ if include_internal_grid:
+ drawing_lines.append(
+ models._AxisLine(
+ (20.0, 60.0, 180.0, 61.0),
+ 1.0,
+ "horizontal",
+ )
+ )
+ return models._PageSource(
+ page_size=(200.0, 300.0),
+ lines=lines,
+ chars=[],
+ drawing_lines=drawing_lines,
+ )
+
+
+def test_rule_delimited_listing_materializes_code_before_table_claim() -> None:
+ """验证无内部网格的上下横线清单形成单一 code 并唯一认领全部来源行。"""
+
+ source = _rule_delimited_code_source()
+ blocks, claimed = code_blocks._build_rule_delimited_code_blocks(
+ source,
+ [],
+ )
+
+ assert len(blocks) == 1
+ assert blocks[0]["type"] == "code"
+ assert claimed == set(range(12))
+
+
+def test_rule_delimited_listing_rejects_real_table_internal_grid() -> None:
+ """验证带内部横向网格的区域不会被规则代码路径侵蚀。"""
+
+ blocks, claimed = code_blocks._build_rule_delimited_code_blocks(
+ _rule_delimited_code_source(include_internal_grid=True),
+ [],
+ )
+
+ assert blocks == []
+ assert claimed == set()
diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.py
index 7d1b4a16..6472b9ed 100644
--- a/tests/unittest/test_flash_pdf_formulas.py
+++ b/tests/unittest/test_flash_pdf_formulas.py
@@ -1053,3 +1053,142 @@ def test_justified_mixed_font_visual_row_before_body_is_not_formula_anchor() ->
14,
15,
}
+
+
+def test_split_visual_row_with_right_number_forms_one_equation() -> None:
+ """验证多字体同行公式及其右侧编号在栏推断前合成一个公式块。"""
+
+ body_font = ("Body", 0)
+ math_font = ("Math", 0)
+ lines = [
+ _text_line(
+ "body above",
+ (0.0, 10.0, 100.0, 20.0),
+ 0,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "E =",
+ (20.0, 35.0, 40.0, 45.0),
+ 1,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=math_font,
+ font_coverage=0.6,
+ ),
+ _text_line(
+ "mc2",
+ (42.0, 35.0, 65.0, 45.0),
+ 2,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=("MathItalic", 0),
+ font_coverage=0.6,
+ ),
+ _text_line(
+ "(8)",
+ (90.0, 35.0, 100.0, 45.0),
+ 3,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "body below",
+ (0.0, 60.0, 100.0, 70.0),
+ 4,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ ]
+
+ blocks, remaining = formulas._build_formula_like_blocks(
+ lines,
+ [],
+ (100.0, 100.0),
+ )
+
+ assert len(blocks) == 1
+ assert blocks[0]["type"] == "equation"
+ assert "(8)" in blocks[0]["content"]
+ assert {line.source_index for line in remaining} == {0, 4}
+
+
+def test_centered_low_body_font_line_forms_unnumbered_equation() -> None:
+ """验证上下正文之间居中且低正文覆盖的数学字体行形成无编号公式。"""
+
+ body_font = ("Body", 0)
+ lines = [
+ _text_line(
+ f"body {index}",
+ (0.0, top, 100.0, top + 10.0),
+ index,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ for index, top in enumerate((0.0, 14.0, 58.0, 72.0))
+ ]
+ lines.append(
+ _text_line(
+ "|E(X) - M| < n-1",
+ (25.0, 36.0, 75.0, 46.0),
+ 10,
+ effective_height=10.0,
+ font_signature=("Math", 0),
+ font_coverage=0.5,
+ )
+ )
+
+ blocks, remaining = formulas._build_formula_like_blocks(
+ lines,
+ [],
+ (100.0, 100.0),
+ )
+
+ assert len(blocks) == 1
+ assert blocks[0]["type"] == "equation"
+ assert blocks[0]["content"] == "|E(X) - M| < n-1"
+ assert {line.source_index for line in remaining} == {0, 1, 2, 3}
+
+
+def test_punctuated_number_anchor_protects_stacked_formula_member() -> None:
+ """验证右侧短标点编号会阻止分式成员被提前识别成无编号公式。"""
+
+ candidate = _text_line(
+ "fraction numerator",
+ (20.0, 30.0, 65.0, 40.0),
+ 1,
+ effective_height=10.0,
+ font_signature=("Math", 0),
+ font_coverage=0.5,
+ )
+ number_anchor = _text_line(
+ ", (4)",
+ (66.0, 32.0, 78.0, 42.0),
+ 2,
+ effective_height=10.0,
+ font_signature=("Body", 0),
+ font_coverage=1.0,
+ )
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[
+ (candidate, candidate.bbox),
+ (number_anchor, number_anchor.bbox),
+ ],
+ )
+
+ assert formulas._has_nearby_punctuated_formula_number_anchor(
+ (candidate, candidate.bbox),
+ lane,
+ median_height=10.0,
+ )
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 3639eb46..cfed3af8 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -26,6 +26,16 @@ def _native_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:
return pipeline._analyze_native_document(pdf_doc)
+def _txt_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:
+ """显式使用 Flash TXT 模式解析仓库内回归 PDF,禁止经过 auto 分类。"""
+
+ pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_name
+ return pdf_extractor.doc_analyze(
+ pdf_path.read_bytes(),
+ parse_mode="txt",
+ )
+
+
def _native_table_counts(pdf_name: str) -> list[int]:
"""返回仓库内数字 PDF 样例的逐页表格块数量。"""
@@ -953,3 +963,145 @@ 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
+
+
+def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:
+ """验证原文 3–6 页的标题、公式、图内坐标和边缘文本修复。"""
+
+ model_list = _txt_model_list("mixed_elements_pages_03_06.pdf")
+
+ assert len(model_list) == 4
+ for probe in (
+ "INTRODUCTION",
+ "EXPERIMENTAL",
+ "RESULTS AND DISCUSSION",
+ "CONCLUSIONS",
+ "REFERENCES",
+ ):
+ matches = _blocks_containing(
+ [block for page in model_list for block in page],
+ probe,
+ )
+ assert len(matches) == 1
+ assert matches[0]["type"] == "paragraph_title"
+
+ page4 = model_list[1]
+ assert sum(block["type"] == "equation" for block in page4) == 1
+ assert not [
+ block
+ for block in page4
+ if block["type"] == "text"
+ and 0.65 <= block["bbox"][1] <= 0.87
+ and block["bbox"][2] - block["bbox"][0] < 0.05
+ ]
+
+ page5 = model_list[2]
+ axis_label = _blocks_containing(page5, "T–1/4, K–1/4")
+ assert len(axis_label) == 1
+ assert axis_label[0]["type"] == "text"
+ assert _blocks_containing(page5, "MIKOLAICHUK et al.")[0]["type"] == "header"
+ assert len([block for block in page5 if block["type"] == "footer"]) == 1
+
+
+def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:
+ """验证原文 7–10 页作者列、代码边界、尾词标题和参考文献修复。"""
+
+ model_list = _txt_model_list("mixed_elements_pages_07_10.pdf")
+ page7, page8, _page9, page10 = model_list
+
+ author_blocks = [
+ block
+ for block in page7
+ if block["type"] == "text"
+ and 0.15 <= block["bbox"][1]
+ and block["bbox"][3] <= 0.28
+ ]
+ assert len(author_blocks) == 4
+ assert {
+ name
+ for name in ("Xing Wang", "Yingzhou Zhang", "Lian Zhao", "Xinghao Chen")
+ if any(name in str(block["content"]) for block in author_blocks)
+ } == {"Xing Wang", "Yingzhou Zhang", "Lian Zhao", "Xinghao Chen"}
+ for probe in ("general applicability.", "called static slicing."):
+ matches = _blocks_containing(page7, probe)
+ assert len(matches) == 1
+ assert matches[0]["type"] == "text"
+
+ code_blocks = [block for block in page8 if block["type"] == "code"]
+ assert len(code_blocks) == 3
+ 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"
+
+ reference5 = _blocks_containing(page10, "[5] A. Srivastava")
+ assert len(reference5) == 1
+ assert reference5[0]["type"] == "text"
+ assert "[6]" not in str(reference5[0]["content"])
+
+
+def test_mixed_elements_pages_11_15_force_txt_regressions() -> None:
+ """验证原文 11–15 页双行标题、正文小节、页码、图注与网址页脚。"""
+
+ model_list = _txt_model_list("mixed_elements_pages_11_15.pdf")
+ all_blocks = [block for page in model_list for block in page]
+ document_titles = [block for block in all_blocks if block["type"] == "doc_title"]
+
+ assert len(document_titles) == 1
+ assert "Ecabet sodium prevents esophageal lesions" in document_titles[0]["content"]
+ assert "reflux of gastric juice in rats" in document_titles[0]["content"]
+ for probe in (
+ "2. Effects on esophageal lesions",
+ "3. Effect on digestion of mucus",
+ ):
+ matches = _blocks_containing(all_blocks, probe)
+ assert len(matches) == 1
+ assert matches[0]["type"] == "paragraph_title"
+
+ assert {
+ block["content"]
+ for block in all_blocks
+ if block["type"] == "page_number"
+ } == {"91", "92", "93", "94"}
+ assert not [
+ block
+ for block in all_blocks
+ if block["type"] == "image"
+ and str(block["content"]).strip() in {"91", "92"}
+ ]
+
+ 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 "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"]
+
+ online_footer = _blocks_containing(model_list[4], "http://www.birkhauser.ch/IPh")
+ assert len(online_footer) == 1
+ assert online_footer[0]["type"] == "footer"
+
+
+def test_mixed_elements_pages_39_40_force_txt_regressions() -> None:
+ """验证原文 39–40 页三个公式和公式后同视觉行正文的唯一输出。"""
+
+ model_list = _txt_model_list("mixed_elements_pages_39_40.pdf")
+ page40 = model_list[1]
+ equations = [block for block in page40 if block["type"] == "equation"]
+
+ assert len(equations) == 3
+ assert sum("(8)" in str(block["content"]) for block in equations) == 1
+ assert sum("(9)" in str(block["content"]) for block in equations) == 1
+ inequality = _blocks_containing(equations, "Mπ(Xn)")
+ assert len(inequality) == 1
+ assert inequality[0]["type"] == "equation"
+
+ continuation = _blocks_containing(page40, "so that we have a near-unbiased estimator")
+ assert len(continuation) == 1
+ assert continuation[0]["type"] == "text"
+ assert "Coupling this observation" in continuation[0]["content"]
+ assert sum(
+ "Coupling this observation" in str(block["content"])
+ for block in page40
+ ) == 1
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index 066633e4..f88020d2 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -2242,3 +2242,180 @@ def test_compact_title_continuation_requires_repetition_and_font_switch() -> Non
"paragraph_title",
"text",
]
+
+
+def test_caption_neighbor_uses_union_of_aligned_image_row() -> None:
+ """验证三张并排图片会额外形成统一图注邻接使用的联合 bbox。"""
+
+ grouped = text_blocks._caption_image_group_bboxes(
+ [
+ (10.0, 10.0, 35.0, 40.0),
+ (37.0, 10.0, 62.0, 40.0),
+ (64.0, 10.0, 90.0, 40.0),
+ ],
+ median_height=10.0,
+ )
+
+ assert (10.0, 10.0, 90.0, 40.0) in grouped
+
+
+def test_inline_math_fragments_merge_into_wide_split_text_row() -> None:
+ """验证宽正文行上下叠放的多个小数学块收敛为一个文本块。"""
+
+ host = {
+ "type": "text",
+ "bbox": (10.0, 40.0, 90.0, 50.0),
+ "angle": 0,
+ "content": "body host",
+ "_visual_row_ids": {1},
+ "_single_run_row_id": 1,
+ "_local_line_bboxes": [(10.0, 40.0, 90.0, 50.0)],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body", 0)},
+ }
+ fragments = [
+ {
+ "type": "text",
+ "bbox": bbox,
+ "angle": 0,
+ "content": content,
+ "_visual_row_ids": {index + 2},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [bbox],
+ "_line_heights": [bbox[3] - bbox[1]],
+ "_font_signatures": {("Math", 0)},
+ }
+ for index, (bbox, content) in enumerate(
+ (
+ ((30.0, 34.0, 40.0, 43.0), "numerator"),
+ ((30.0, 47.0, 40.0, 56.0), "denominator"),
+ ((60.0, 35.0, 70.0, 44.0), "power"),
+ )
+ )
+ ]
+
+ merged = text_blocks._merge_inline_math_fragment_text_blocks(
+ [host, *fragments],
+ (200.0, 100.0),
+ )
+
+ assert len(merged) == 1
+ assert merged[0]["bbox"] == (10.0, 34.0, 90.0, 56.0)
+ assert all(
+ token in merged[0]["content"]
+ for token in ("body host", "numerator", "denominator", "power")
+ )
+
+
+def test_residual_narrow_math_fragment_merges_into_unique_wide_host() -> None:
+ """验证单个窄数学碎片与宽正文行重叠时会收回唯一宿主。"""
+
+ host = {
+ "type": "text",
+ "bbox": (10.0, 40.0, 90.0, 52.0),
+ "angle": 0,
+ "content": "body host",
+ "_local_line_bboxes": [(10.0, 40.0, 90.0, 52.0)],
+ "_line_heights": [12.0],
+ }
+ fragment = {
+ "type": "text",
+ "bbox": (50.0, 48.0, 54.0, 57.0),
+ "angle": 0,
+ "content": "gamma",
+ "_local_line_bboxes": [(50.0, 48.0, 54.0, 57.0)],
+ "_line_heights": [9.0],
+ }
+
+ merged = text_blocks._merge_residual_narrow_math_text_blocks(
+ [host, fragment],
+ (200.0, 100.0),
+ )
+
+ assert len(merged) == 1
+ assert merged[0]["bbox"] == (10.0, 40.0, 90.0, 57.0)
+ assert "body host" in merged[0]["content"]
+ assert "gamma" in merged[0]["content"]
+
+
+def test_overlapping_wide_text_rows_merge_without_broad_page_line_merge() -> None:
+ """验证同左沿宽正文的重叠行可在块级合并,且不依赖全页行合并。"""
+
+ first = {
+ "type": "text",
+ "bbox": (20.0, 40.0, 140.0, 52.0),
+ "angle": 0,
+ "content": "first row",
+ "_local_line_bboxes": [(20.0, 40.0, 140.0, 52.0)],
+ "_line_heights": [12.0],
+ "_font_signatures": {("Body", 0)},
+ }
+ second = {
+ "type": "text",
+ "bbox": (20.0, 42.0, 180.0, 65.0),
+ "angle": 0,
+ "content": "second row continuation",
+ "_local_line_bboxes": [
+ (100.0, 42.0, 180.0, 53.0),
+ (20.0, 54.0, 180.0, 65.0),
+ ],
+ "_line_heights": [11.0, 11.0],
+ "_font_signatures": {("Body", 0)},
+ }
+
+ merged = text_blocks._merge_overlapping_same_line_text_blocks(
+ [first, second],
+ (300.0, 200.0),
+ )
+
+ assert len(merged) == 1
+ assert merged[0]["bbox"] == (20.0, 40.0, 180.0, 65.0)
+ assert "first row" in merged[0]["content"]
+ assert "second row continuation" in merged[0]["content"]
+
+
+def test_front_matter_grid_merges_each_author_column_independently() -> None:
+ """验证标题后的四列规则前置信息按列合并且不横向串列。"""
+
+ title = {
+ "type": "doc_title",
+ "bbox": (200.0, 100.0, 800.0, 130.0),
+ "angle": 0,
+ "content": "document title",
+ "_visual_row_ids": {0},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [(200.0, 100.0, 800.0, 130.0)],
+ "_line_heights": [30.0],
+ "_font_signatures": {("Title", 0)},
+ }
+ author_parts = []
+ for column_index, left in enumerate((75.0, 325.0, 575.0, 825.0)):
+ for row_index, top in enumerate((150.0, 165.0, 180.0)):
+ bbox = (left, top, left + 100.0, top + 10.0)
+ author_parts.append(
+ {
+ "type": "text",
+ "bbox": bbox,
+ "angle": 0,
+ "content": f"author-{column_index}-row-{row_index}",
+ "_visual_row_ids": {10 + row_index},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [bbox],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body", 0)},
+ }
+ )
+
+ merged = text_blocks._merge_front_matter_column_blocks(
+ [title, *author_parts],
+ (1000.0, 1000.0),
+ page_index=0,
+ )
+ merged_authors = [block for block in merged if block["type"] == "text"]
+
+ assert len(merged_authors) == 4
+ for column_index, block in enumerate(merged_authors):
+ assert all(
+ f"author-{column_index}-row-{row_index}" in block["content"]
+ for row_index in range(3)
+ )