Skip to content

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

feat: enhance footer classification by adding support for single rule footers and refining visual row merging

myhlolid6bc2b17a63e
diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.py
index a9401ebb..5fbd5ca6 100644
--- a/mineru/backend/flash/native_pdf/auxiliary_text.py
+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py
@@ -734,7 +734,7 @@ def _classify_rule_delimited_headers(pages: list[_PreparedPage]) -> None:
def _classify_rule_delimited_footers(pages: list[_PreparedPage]) -> None:
- """用页面底部两条同跨度横线确认其间孤立的居中页脚。"""
+ """用页面底部横线确认双线间页脚或单线下方的小字号栏内页脚。"""
for page in pages:
available = [
@@ -803,6 +803,16 @@ def _classify_rule_delimited_footers(pages: list[_PreparedPage]) -> None:
_line_effective_height(line, bbox)
for line, bbox in local_lines
)
+ lanes = [
+ lane
+ for lane in _infer_text_lanes(
+ local_lines,
+ local_page_width,
+ median_height,
+ recalculate_intervals=False,
+ )
+ if not lane.is_span
+ ]
for upper_index, upper in enumerate(rules[:-1]):
for lower in rules[upper_index + 1 :]:
vertical_gap = lower.bbox[1] - upper.bbox[3]
@@ -831,6 +841,80 @@ def _classify_rule_delimited_footers(pages: list[_PreparedPage]) -> None:
for line, _bbox in members:
line.semantic_type = "footer"
break
+ for rule in rules:
+ for line in _single_rule_footer_members(
+ rule,
+ local_lines,
+ lanes,
+ median_height,
+ ):
+ line.semantic_type = "footer"
+
+
+def _single_rule_footer_members(
+ rule: _LocalAxisLine,
+ local_lines: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+ body_height: float,
+) -> list[_LineItem]:
+ """返回底部单横线下方、唯一栏内连续的小字号页脚行。"""
+
+ rule_width = max(0.1, rule.bbox[2] - rule.bbox[0])
+ rule_center_x = _bbox_center_x(rule.bbox)
+ matching_lanes = []
+ for lane in lanes:
+ overlap = max(
+ 0.0,
+ min(rule.bbox[2], lane.right) - max(rule.bbox[0], lane.left),
+ )
+ if overlap / rule_width >= 0.8 and lane.left <= rule_center_x <= lane.right:
+ matching_lanes.append(lane)
+ if len(matching_lanes) != 1:
+ return []
+
+ lane = matching_lanes[0]
+ if (
+ len(lanes) > 1
+ and lane.left < max(candidate_lane.left for candidate_lane in lanes) - body_height
+ ):
+ return []
+ tolerance = 0.5 * body_height
+ rows_below = sorted(
+ (
+ (line, bbox)
+ for line, bbox in local_lines
+ if line.semantic_type is None
+ and bbox[1] >= rule.bbox[3]
+ and bbox[0] >= lane.left - tolerance
+ and bbox[2] <= lane.right + tolerance
+ ),
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ if not rows_below:
+ return []
+ first_line, first_bbox = rows_below[0]
+ if (
+ first_bbox[1] - rule.bbox[3] > body_height
+ or _line_effective_height(first_line, first_bbox) > 0.9 * body_height
+ ):
+ return []
+
+ members = [(first_line, first_bbox)]
+ for line, bbox in rows_below[1:]:
+ previous_bbox = members[-1][1]
+ if (
+ bbox[1] - previous_bbox[3] > body_height
+ or bbox[3] - first_bbox[1] > 5.0 * body_height
+ or _line_effective_height(line, bbox) > 0.9 * body_height
+ ):
+ break
+ members.append((line, bbox))
+ if not 2 <= len(members) <= 8:
+ return []
+ member_left_edges = [bbox[0] for _line, bbox in members]
+ if max(member_left_edges) - min(member_left_edges) > 0.75 * body_height:
+ return []
+ return [line for line, _bbox in members]
def _rule_overlaps_fixed_container(
diff --git a/mineru/backend/flash/native_pdf/graphics.py b/mineru/backend/flash/native_pdf/graphics.py
index dbd585d1..858856d8 100644
--- a/mineru/backend/flash/native_pdf/graphics.py
+++ b/mineru/backend/flash/native_pdf/graphics.py
@@ -206,7 +206,11 @@ def _build_graphic_like_blocks(
candidates.extend(
_GraphicCandidate(
core_bbox=core_bbox,
- lane_index=-1,
+ lane_index=_strong_graphic_lane_index(
+ core_bbox,
+ lanes,
+ median_height,
+ ),
label_margin_scale=(
2.5
if any(
@@ -598,6 +602,30 @@ def _graphic_lane_index(bbox: BBox, lanes: list[_TextLane]) -> int:
return best_index
+def _strong_graphic_lane_index(
+ core_bbox: BBox,
+ lanes: list[_TextLane],
+ median_height: float,
+) -> int:
+ """仅把几乎完整落入唯一栏带的强图形核心绑定到该栏。"""
+
+ core_width = max(0.1, core_bbox[2] - core_bbox[0])
+ tolerance = max(1.0, median_height)
+ matching_indices = []
+ for lane_index, lane in enumerate(lanes):
+ overlap = max(
+ 0.0,
+ min(core_bbox[2], lane.right) - max(core_bbox[0], lane.left),
+ )
+ if (
+ overlap / core_width >= 0.9
+ and core_bbox[0] >= lane.left - tolerance
+ and core_bbox[2] <= lane.right + tolerance
+ ):
+ matching_indices.append(lane_index)
+ return matching_indices[0] if len(matching_indices) == 1 else -1
+
+
def _detect_graphic_candidates(
drawing_lines: list[_AxisLine],
page_size: tuple[float, float],
diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.py
index 92cc70fb..0445ea32 100644
--- a/mineru/backend/flash/native_pdf/text_blocks.py
+++ b/mineru/backend/flash/native_pdf/text_blocks.py
@@ -50,6 +50,7 @@ _FIGURE_CAPTION_MARKER_RE = re.compile(
r"^(?:图\s*[0-90-9一二三四五六七八九十]|fig(?:ure)?\.?\s*[0-9])",
re.IGNORECASE,
)
+_INLINE_MATH_RECOVERY_MARKER = "_recovered_inline_math_fragments"
def _starts_structural_reference_entry(
@@ -887,11 +888,55 @@ def _build_text_blocks(
return _merge_inline_math_fragment_text_blocks(blocks, page_size)
+def _blocks_share_boundary_visual_row(
+ first: dict[str, Any],
+ second: dict[str, Any],
+ pair_height: float,
+) -> bool:
+ """检查前块末行与后块首行是否为被错误切开的同一视觉行。"""
+
+ first_rows = first.get("_local_line_bboxes")
+ second_rows = second.get("_local_line_bboxes")
+ if (
+ not isinstance(first_rows, list)
+ or not isinstance(second_rows, list)
+ or max(len(first_rows), len(second_rows)) < 3
+ or len(first_rows) + len(second_rows) > 6
+ or not _components_share_lane_role(first, second, pair_height)
+ ):
+ return False
+ if first["bbox"][1] <= second["bbox"][1]:
+ upper_rows, lower_rows = first_rows, second_rows
+ else:
+ upper_rows, lower_rows = second_rows, first_rows
+ upper_boundary = max(upper_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
+ lower_boundary = min(lower_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
+ vertical_overlap = max(
+ 0.0,
+ min(upper_boundary[3], lower_boundary[3])
+ - max(upper_boundary[1], lower_boundary[1]),
+ )
+ shorter_height = max(
+ 0.1,
+ min(
+ upper_boundary[3] - upper_boundary[1],
+ lower_boundary[3] - lower_boundary[1],
+ ),
+ )
+ horizontal_gap = lower_boundary[0] - upper_boundary[2]
+ union_bbox = _bbox_union_many([first["bbox"], second["bbox"]])
+ return (
+ vertical_overlap / shorter_height >= 0.7
+ and -0.2 * pair_height <= horizontal_gap <= 0.75 * pair_height
+ and union_bbox[3] - union_bbox[1] <= 6.0 * pair_height
+ )
+
+
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]] = {}
@@ -905,7 +950,7 @@ def _merge_overlapping_same_line_text_blocks(
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 not 1 <= len(first_rows) <= 5
or first_bbox[2] - first_bbox[0] < 0.3 * local_page_width
):
continue
@@ -929,8 +974,7 @@ def _merge_overlapping_same_line_text_blocks(
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 not 1 <= len(second_rows) <= 5
or second_bbox[2] - second_bbox[0] < 0.3 * local_page_width
):
continue
@@ -959,22 +1003,34 @@ def _merge_overlapping_same_line_text_blocks(
)
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)
- )
- ):
+ fonts_conflict = (
+ isinstance(first_fonts, set)
+ and isinstance(second_fonts, set)
+ and first_fonts
+ and second_fonts
+ and first_fonts.isdisjoint(second_fonts)
+ )
+ compact_overlap = (
+ len(first_rows) <= 2
+ and len(second_rows) <= 2
+ and min(len(first_rows), len(second_rows)) == 1
+ and abs(first_bbox[0] - second_bbox[0]) <= pair_height
+ and vertical_overlap / minimum_box_height >= 0.5
+ and _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x")
+ >= 0.75
+ )
+ boundary_overlap = _blocks_share_boundary_visual_row(
+ first,
+ second,
+ pair_height,
+ )
+ if fonts_conflict or not (compact_overlap or boundary_overlap):
continue
union_bbox = _bbox_union_many([first_bbox, second_bbox])
- if union_bbox[3] - union_bbox[1] > 4.0 * pair_height:
+ if (
+ not boundary_overlap
+ and 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(
@@ -1062,7 +1118,7 @@ def _merge_inline_math_fragment_text_blocks(
continue
group_indices = [host_index, *fragment_indices]
replacement_index = min(group_indices)
- replacements[replacement_index] = _merge_internal_text_block_group(
+ replacements[replacement_index] = _merge_inline_math_recovery_group(
blocks,
group_indices,
)
@@ -1073,7 +1129,8 @@ def _merge_inline_math_fragment_text_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)
+ output = _merge_residual_narrow_math_text_blocks(output, page_size)
+ return _merge_inline_math_paragraph_continuations(output, page_size)
def _merge_residual_narrow_math_text_blocks(
@@ -1159,7 +1216,7 @@ def _merge_residual_narrow_math_text_blocks(
continue
host_index = hosts[0][2]
replacement_index = min(candidate_index, host_index)
- replacements[replacement_index] = _merge_internal_text_block_group(
+ replacements[replacement_index] = _merge_inline_math_recovery_group(
blocks,
[candidate_index, host_index],
)
@@ -1295,7 +1352,7 @@ def _merge_hostless_inline_math_fragment_blocks(
if any(index in consumed for index in group):
continue
replacement_index = min(group)
- replacements[replacement_index] = _merge_internal_text_block_group(
+ replacements[replacement_index] = _merge_inline_math_recovery_group(
blocks,
group,
)
@@ -1307,6 +1364,184 @@ def _merge_hostless_inline_math_fragment_blocks(
]
+def _merge_inline_math_recovery_group(
+ blocks: list[dict[str, Any]],
+ indices: list[int],
+) -> dict[str, Any]:
+ """合并数学碎片并保留仅供后续段落闭合使用的内部标记。"""
+
+ merged = _merge_internal_text_block_group(blocks, indices)
+ merged[_INLINE_MATH_RECOVERY_MARKER] = True
+ return merged
+
+
+def _merge_inline_math_paragraph_continuations(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """在数学碎片恢复后,合并同栏连续且足够宽的正文段落块。"""
+
+ if (
+ sum(
+ block.get(_INLINE_MATH_RECOVERY_MARKER) is True
+ for block in blocks
+ )
+ < 2
+ ):
+ return blocks
+
+ lane_groups: list[list[int]] = []
+ for index, block in sorted(
+ enumerate(blocks),
+ key=lambda item: (
+ int(item[1].get("angle", 0) or 0) % 360,
+ _text_component_sort_key(item[1])
+ if isinstance(item[1].get("_local_line_bboxes"), list)
+ and item[1]["_local_line_bboxes"]
+ else (float("inf"), float("inf")),
+ ),
+ ):
+ local_rows = block.get("_local_line_bboxes")
+ if (
+ block.get("type") != "text"
+ or not isinstance(block.get("_lane_is_span"), bool)
+ or not isinstance(local_rows, list)
+ or not local_rows
+ ):
+ continue
+ block_heights = [
+ float(height)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ if not block_heights:
+ continue
+ for lane_group in lane_groups:
+ representative = blocks[lane_group[0]]
+ if int(representative.get("angle", 0) or 0) % 360 != int(
+ block.get("angle", 0) or 0
+ ) % 360:
+ continue
+ representative_heights = [
+ float(height)
+ for height in representative.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ pair_height = statistics.median(
+ [*representative_heights, *block_heights]
+ )
+ if _components_share_lane_role(representative, block, pair_height):
+ lane_group.append(index)
+ break
+ else:
+ lane_groups.append([index])
+
+ candidate_chains: list[list[int]] = []
+ for lane_group in lane_groups:
+ ordered_indices = sorted(
+ lane_group,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ chain = [ordered_indices[0]]
+ for current_index in ordered_indices[1:]:
+ previous_index = chain[-1]
+ previous = blocks[previous_index]
+ current = blocks[current_index]
+ previous_rows = previous["_local_line_bboxes"]
+ current_rows = current["_local_line_bboxes"]
+ previous_local_bbox = _bbox_union_many(previous_rows)
+ current_local_bbox = _bbox_union_many(current_rows)
+ pair_heights = [
+ float(height)
+ for block in (previous, current)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ pair_height = statistics.median(pair_heights)
+ angle = int(previous.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ lane_width = _compatible_component_lane_width(
+ previous,
+ current,
+ local_page_width,
+ pair_height,
+ )
+ previous_fonts = previous.get("_font_signatures")
+ current_fonts = current.get("_font_signatures")
+ fonts_conflict = (
+ isinstance(previous_fonts, set)
+ and isinstance(current_fonts, set)
+ and previous_fonts
+ and current_fonts
+ and previous_fonts.isdisjoint(current_fonts)
+ )
+ vertical_gap = current_local_bbox[1] - previous_local_bbox[3]
+ connects = (
+ _components_share_lane_role(previous, current, pair_height)
+ and previous_local_bbox[2] - previous_local_bbox[0]
+ >= 0.8 * lane_width
+ and current_local_bbox[2] - current_local_bbox[0]
+ >= 0.8 * lane_width
+ and abs(previous_local_bbox[0] - current_local_bbox[0])
+ <= 0.75 * pair_height
+ and -0.75 * pair_height
+ <= vertical_gap
+ <= 0.75 * pair_height
+ and not fonts_conflict
+ and not _component_connection_skips_block(
+ blocks,
+ previous_index,
+ current_index,
+ pair_height,
+ )
+ )
+ if connects:
+ chain.append(current_index)
+ else:
+ candidate_chains.append(chain)
+ chain = [current_index]
+ candidate_chains.append(chain)
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for chain in candidate_chains:
+ if (
+ len(chain) < 3
+ or sum(
+ blocks[index].get(_INLINE_MATH_RECOVERY_MARKER) is True
+ for index in chain
+ )
+ < 2
+ ):
+ continue
+ chain_heights = [
+ float(height)
+ for index in chain
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ median_height = statistics.median(chain_heights)
+ local_union = _bbox_union_many(
+ [
+ bbox
+ for index in chain
+ for bbox in blocks[index]["_local_line_bboxes"]
+ ]
+ )
+ if local_union[3] - local_union[1] > 24.0 * median_height:
+ continue
+ replacement_index = min(chain)
+ merged = _merge_internal_text_block_group(blocks, chain)
+ merged[_INLINE_MATH_RECOVERY_MARKER] = True
+ replacements[replacement_index] = merged
+ consumed.update(chain)
+ 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(
blocks: list[dict[str, Any]],
image_bboxes: list[BBox],
diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.py
index 5201658e..de143174 100644
--- a/mineru/backend/flash/native_pdf/titles.py
+++ b/mineru/backend/flash/native_pdf/titles.py
@@ -1374,6 +1374,28 @@ def _classify_cross_lane_emphasized_section_titles(
line.semantic_type = "paragraph_title"
+def _is_wide_leading_title_continuation(
+ title_bbox: BBox,
+ candidate_bbox: BBox,
+ title_height: float,
+ candidate_height: float,
+) -> bool:
+ """识别紧贴在窄标题锚点上方、同中心的较宽首行。"""
+
+ pair_height = max(0.1, title_height, candidate_height)
+ title_width = max(0.1, title_bbox[2] - title_bbox[0])
+ width_ratio = (candidate_bbox[2] - candidate_bbox[0]) / title_width
+ vertical_gap = title_bbox[1] - candidate_bbox[3]
+ return (
+ 2.0 < width_ratio <= 2.5
+ and _bbox_center_y(candidate_bbox) < _bbox_center_y(title_bbox)
+ and -0.1 * pair_height <= vertical_gap <= 0.15 * pair_height
+ and _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") >= 0.8
+ and abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox))
+ <= 0.5 * pair_height
+ )
+
+
def _expand_cross_lane_paragraph_title_neighbors(
line_geometry: list[tuple[_LineItem, BBox]],
) -> None:
@@ -1400,7 +1422,15 @@ def _expand_cross_lane_paragraph_title_neighbors(
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:
+ if not (
+ 0.25 <= candidate_width / title_width <= 2.0
+ or _is_wide_leading_title_continuation(
+ title_bbox,
+ candidate_bbox,
+ title_height,
+ candidate_height,
+ )
+ ):
continue
if (
title_line.font_signature is not None
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index bf2f0d99..3e8cbd9c 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -1155,6 +1155,136 @@ def test_two_bottom_rules_classify_centered_url_as_footer() -> None:
assert url.semantic_type == "footer"
+def test_single_bottom_rule_classifies_small_right_lane_rows_as_footer() -> None:
+ """验证底部单横线下方的右栏连续小字被标为页脚。"""
+
+ body = [
+ _text_line(
+ f"body {column}-{row}",
+ (
+ 80.0 + 500.0 * column,
+ 100.0 + 25.0 * row,
+ 420.0 + 500.0 * column,
+ 110.0 + 25.0 * row,
+ ),
+ 10 * column + row,
+ effective_height=10.0,
+ )
+ for column in range(2)
+ for row in range(5)
+ ]
+ footer_rows = [
+ _text_line(
+ f"footer {index}",
+ (600.0, 858.0 + 10.0 * index, 880.0, 866.0 + 10.0 * index),
+ 20 + index,
+ effective_height=8.0,
+ )
+ for index in range(3)
+ ]
+ page = _prepared_text_page(
+ *body,
+ *footer_rows,
+ page_size=(1000.0, 1000.0),
+ )
+ page.drawing_lines = [
+ models._AxisLine((580.0, 850.0, 900.0, 851.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_rule_delimited_footers([page])
+
+ assert [line.semantic_type for line in footer_rows] == ["footer"] * 3
+ assert all(line.semantic_type is None for line in body)
+
+
[email protected]("inside_image", [False, True])
+def test_single_bottom_rule_rejects_body_sized_or_container_rows(
+ inside_image: bool,
+) -> None:
+ """验证正文大小的行和图片内部横线均不能触发单横线页脚。"""
+
+ body = [
+ _text_line(
+ f"body {index}",
+ (100.0, 100.0 + 25.0 * index, 900.0, 110.0 + 25.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(6)
+ ]
+ bottom_rows = [
+ _text_line(
+ f"bottom {index}",
+ (150.0, 858.0 + 12.0 * index, 850.0, 868.0 + 12.0 * index),
+ 10 + index,
+ effective_height=8.0 if inside_image else 10.0,
+ )
+ for index in range(2)
+ ]
+ page = _prepared_text_page(
+ *body,
+ *bottom_rows,
+ page_size=(1000.0, 1000.0),
+ )
+ page.drawing_lines = [
+ models._AxisLine((100.0, 850.0, 900.0, 851.0), 1.0, "horizontal")
+ ]
+ if inside_image:
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (80.0, 800.0, 920.0, 900.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+
+ auxiliary_text._classify_rule_delimited_footers([page])
+
+ assert all(line.semantic_type is None for line in bottom_rows)
+
+
+def test_single_bottom_rule_rejects_formula_fragments_with_unstable_left_edges() -> None:
+ """验证分数线下横向起点离散的公式碎片不能被误判为页脚。"""
+
+ body = [
+ _text_line(
+ f"body {column}-{row}",
+ (
+ 80.0 + 500.0 * column,
+ 100.0 + 25.0 * row,
+ 420.0 + 500.0 * column,
+ 110.0 + 25.0 * row,
+ ),
+ 10 * column + row,
+ effective_height=10.0,
+ )
+ for column in range(2)
+ for row in range(5)
+ ]
+ formula_fragments = [
+ _text_line(
+ f"fragment {index}",
+ (left, 858.0 + 9.0 * index, left + 80.0, 866.0 + 9.0 * index),
+ 20 + index,
+ effective_height=8.0,
+ )
+ for index, left in enumerate((590.0, 710.0, 620.0))
+ ]
+ page = _prepared_text_page(
+ *body,
+ *formula_fragments,
+ page_size=(1000.0, 1000.0),
+ )
+ page.drawing_lines = [
+ models._AxisLine((600.0, 850.0, 850.0, 851.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_rule_delimited_footers([page])
+
+ assert all(line.semantic_type is None for line in formula_fragments)
+
+
def test_split_footer_row_fragments_inherit_stable_anchor_type() -> None:
"""验证同一页脚视觉行的左右碎片从稳定锚点继承 footer 类型。"""
diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.py
index 633a5a5c..adff3170 100644
--- a/tests/unittest/test_flash_pdf_graphics.py
+++ b/tests/unittest/test_flash_pdf_graphics.py
@@ -190,6 +190,26 @@ def test_complex_path_container_builds_graphic_without_drawing_lines() -> None:
assert blocks[0]["content"] == "10\nlabel"
+def test_strong_graphic_core_binds_only_to_unique_containing_lane() -> None:
+ """验证单栏强图形不会吸收邻栏文本,而真正跨栏核心仍保持跨栏。"""
+
+ lanes = [
+ models._TextLane(left=50.0, right=290.0),
+ models._TextLane(left=305.0, right=545.0),
+ ]
+
+ assert graphics._strong_graphic_lane_index(
+ (73.0, 516.0, 281.0, 655.0),
+ lanes,
+ 10.0,
+ ) == 0
+ assert graphics._strong_graphic_lane_index(
+ (73.0, 516.0, 520.0, 655.0),
+ lanes,
+ 10.0,
+ ) == -1
+
+
def test_axis_pair_requires_internal_two_dimensional_complex_path() -> None:
"""验证相交坐标轴须有二维复杂曲线支撑,规则矩形行带不会误报图形。"""
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index cfed3af8..7562dcc3 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -994,6 +994,45 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:
and 0.65 <= block["bbox"][1] <= 0.87
and block["bbox"][2] - block["bbox"][0] < 0.05
]
+ math_paragraph = _blocks_containing(
+ page4,
+ "This allowed us to estimate the low-temperature hop distance",
+ )
+ assert len(math_paragraph) == 1
+ assert math_paragraph[0]["bbox"] == [0.081, 0.665, 0.475, 0.911]
+ assert set(math_paragraph[0]) == {"type", "bbox", "angle", "content"}
+ for probe in (
+ "where T0",
+ "Fermi-level density",
+ "ized states N(EF)",
+ "frequency factor",
+ "Boltzmann constant",
+ ):
+ assert _blocks_containing(page4, probe) == math_paragraph
+ assert [
+ block
+ for block in page4
+ if block["type"] == "text"
+ and block != math_paragraph[0]
+ and block["bbox"][0] < 0.49
+ and block["bbox"][1] < 0.92
+ and block["bbox"][3] > 0.66
+ ] == []
+ page4_footer = [block for block in page4 if block["type"] == "footer"]
+ assert len(page4_footer) == 1
+ assert page4_footer[0]["bbox"] == [0.104, 0.93, 0.449, 0.941]
+ assert math_paragraph[0]["bbox"][3] < page4_footer[0]["bbox"][1]
+ assert [
+ block["bbox"]
+ for block in page4
+ if block["type"] in {"text", "image"}
+ and block["bbox"][0] >= 0.49
+ and block["bbox"][1] >= 0.49
+ ] == [
+ [0.498, 0.509, 0.892, 0.634],
+ [0.503, 0.66, 0.886, 0.871],
+ [0.521, 0.889, 0.869, 0.911],
+ ]
page5 = model_list[2]
axis_label = _blocks_containing(page5, "T–1/4, K–1/4")
@@ -1001,13 +1040,21 @@ def test_mixed_elements_pages_03_06_force_txt_regressions() -> None:
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
+ lower_graphs = [
+ block
+ for block in page5
+ if block["type"] == "image" and block["bbox"][1] >= 0.6
+ ]
+ assert len(lower_graphs) == 1
+ assert lower_graphs[0]["bbox"][2] <= 0.48
+ assert "ular films." not in str(lower_graphs[0]["content"])
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
+ page7, page8, page9, page10 = model_list
author_blocks = [
block
@@ -1034,6 +1081,19 @@ def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:
assert len(figure_caption) == 1
assert figure_caption[0]["type"] == "text"
+ framework_title = _blocks_containing(
+ page9,
+ "IV. DEAD CODE DETECTION FRAMEWORK BASED ON LLVM INFRASTRUCTURE",
+ )
+ assert len(framework_title) == 1
+ assert framework_title[0]["type"] == "paragraph_title"
+ experiment_title = _blocks_containing(page9, "V. EXPERIMENT RESULTS")
+ assert len(experiment_title) == 1
+ assert experiment_title[0]["type"] == "paragraph_title"
+ url_footer = _blocks_containing(page9, "http://klee.github.io")
+ assert len(url_footer) == 1
+ assert url_footer[0]["type"] == "footer"
+
reference5 = _blocks_containing(page10, "[5] A. Srivastava")
assert len(reference5) == 1
assert reference5[0]["type"] == "text"
@@ -1105,3 +1165,11 @@ def test_mixed_elements_pages_39_40_force_txt_regressions() -> None:
"Coupling this observation" in str(block["content"])
for block in page40
) == 1
+ equation9_following = _blocks_containing(
+ page40,
+ "Clearly, the random variable",
+ )
+ assert len(equation9_following) == 1
+ assert equation9_following[0]["type"] == "text"
+ assert "is an unbiased estimator" in equation9_following[0]["content"]
+ assert "McAllester and Schapire" in equation9_following[0]["content"]
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index f88020d2..8f3d69e3 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -2305,6 +2305,7 @@ def test_inline_math_fragments_merge_into_wide_split_text_row() -> None:
token in merged[0]["content"]
for token in ("body host", "numerator", "denominator", "power")
)
+ assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True
def test_residual_narrow_math_fragment_merges_into_unique_wide_host() -> None:
@@ -2336,6 +2337,156 @@ def test_residual_narrow_math_fragment_merges_into_unique_wide_host() -> None:
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"]
+ assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True
+
+
+def test_hostless_inline_math_fragments_keep_recovery_marker() -> None:
+ """验证无宽宿主的数学碎片合并后也保留内部恢复标记。"""
+
+ fragments = [
+ {
+ "type": "text",
+ "bbox": bbox,
+ "angle": 0,
+ "content": f"fragment {index}",
+ "_local_line_bboxes": [bbox],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body" if index < 2 else "Math", 0)},
+ }
+ for index, bbox in enumerate(
+ (
+ (20.0, 40.0, 60.0, 50.0),
+ (62.0, 40.0, 100.0, 50.0),
+ (20.0, 52.0, 55.0, 62.0),
+ (57.0, 52.0, 100.0, 62.0),
+ )
+ )
+ ]
+
+ merged = text_blocks._merge_hostless_inline_math_fragment_blocks(
+ fragments,
+ (200.0, 100.0),
+ )
+
+ assert len(merged) == 1
+ assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True
+
+
+def _inline_math_paragraph_test_blocks(
+ marker_indices: tuple[int, ...] = (0, 2),
+) -> list[dict[str, object]]:
+ """构造同一栏内连续的五个宽正文块,供数学段落闭合测试复用。"""
+
+ bboxes = (
+ (20.0, 40.0, 172.0, 70.0),
+ (20.0, 74.0, 172.0, 94.0),
+ (20.0, 99.0, 172.0, 129.0),
+ (20.0, 122.0, 172.0, 145.0),
+ (20.0, 145.0, 172.0, 175.0),
+ )
+ blocks: list[dict[str, object]] = []
+ for index, bbox in enumerate(bboxes):
+ block: dict[str, object] = {
+ "type": "text",
+ "bbox": bbox,
+ "angle": 0,
+ "content": f"paragraph part {index}",
+ "_local_line_bboxes": [bbox],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body", 0)},
+ "_lane_interval": (20.0, 180.0),
+ "_lane_is_span": False,
+ }
+ if index in marker_indices:
+ block[text_blocks._INLINE_MATH_RECOVERY_MARKER] = True
+ blocks.append(block)
+ return blocks
+
+
+def test_inline_math_paragraph_continuations_merge_five_wide_blocks() -> None:
+ """验证至少两个数学恢复块可带动同栏五段正文闭合为一个块。"""
+
+ merged = text_blocks._merge_inline_math_paragraph_continuations(
+ _inline_math_paragraph_test_blocks(),
+ (300.0, 300.0),
+ )
+
+ assert len(merged) == 1
+ assert merged[0]["bbox"] == (20.0, 40.0, 172.0, 175.0)
+ assert all(
+ f"paragraph part {index}" in str(merged[0]["content"])
+ for index in range(5)
+ )
+ assert merged[0][text_blocks._INLINE_MATH_RECOVERY_MARKER] is True
+
+
+def test_inline_math_paragraph_does_not_merge_ordinary_paragraphs() -> None:
+ """验证缺少两个数学恢复锚点时不合并普通连续段落。"""
+
+ merged = text_blocks._merge_inline_math_paragraph_continuations(
+ _inline_math_paragraph_test_blocks(marker_indices=(0,)),
+ (300.0, 300.0),
+ )
+
+ assert len(merged) == 5
+
+
[email protected]("variant", ["different_lane", "large_gap", "font_conflict"])
+def test_inline_math_paragraph_rejects_geometry_or_font_conflict(
+ variant: str,
+) -> None:
+ """验证跨栏、过大间距或字体冲突会切断数学正文段落链。"""
+
+ blocks = _inline_math_paragraph_test_blocks()
+ if variant == "different_lane":
+ for block in blocks[2:]:
+ left, top, right, bottom = block["bbox"]
+ shifted = (left + 170.0, top, right + 170.0, bottom)
+ block["bbox"] = shifted
+ block["_local_line_bboxes"] = [shifted]
+ block["_lane_interval"] = (190.0, 350.0)
+ elif variant == "large_gap":
+ for block in blocks[2:]:
+ left, top, right, bottom = block["bbox"]
+ shifted = (left, top + 20.0, right, bottom + 20.0)
+ block["bbox"] = shifted
+ block["_local_line_bboxes"] = [shifted]
+ else:
+ for block in blocks[2:]:
+ block["_font_signatures"] = {("Other", 0)}
+
+ merged = text_blocks._merge_inline_math_paragraph_continuations(
+ blocks,
+ (400.0, 300.0),
+ )
+
+ assert len(merged) == 5
+
+
+def test_inline_math_paragraph_does_not_cross_footer_boundary() -> None:
+ """验证位于相邻正文块之间的 footer 会阻断数学段落闭合。"""
+
+ blocks = _inline_math_paragraph_test_blocks()
+ footer_bbox = (20.0, 95.0, 172.0, 98.0)
+ footer = {
+ "type": "footer",
+ "bbox": footer_bbox,
+ "angle": 0,
+ "content": "footer",
+ "_local_line_bboxes": [footer_bbox],
+ "_line_heights": [3.0],
+ "_font_signatures": {("Body", 0)},
+ "_lane_interval": (20.0, 180.0),
+ "_lane_is_span": False,
+ }
+
+ merged = text_blocks._merge_inline_math_paragraph_continuations(
+ [*blocks[:2], footer, *blocks[2:]],
+ (300.0, 300.0),
+ )
+
+ assert len(merged) == 6
+ assert sum(block["type"] == "footer" for block in merged) == 1
def test_overlapping_wide_text_rows_merge_without_broad_page_line_merge() -> None:
@@ -2374,6 +2525,89 @@ def test_overlapping_wide_text_rows_merge_without_broad_page_line_merge() -> Non
assert "second row continuation" in merged[0]["content"]
+def test_boundary_visual_row_merges_two_and_three_row_text_blocks() -> None:
+ """验证前块末行与后块首行拼接时可合并二行块和三行块。"""
+
+ first = {
+ "type": "text",
+ "bbox": (20.0, 40.0, 280.0, 64.0),
+ "angle": 0,
+ "content": "first block ending",
+ "_local_line_bboxes": [
+ (20.0, 40.0, 280.0, 51.0),
+ (20.0, 52.0, 200.0, 64.0),
+ ],
+ "_line_heights": [11.0, 12.0],
+ "_font_signatures": {("Body", 0)},
+ }
+ second = {
+ "type": "text",
+ "bbox": (20.0, 54.0, 280.0, 90.0),
+ "angle": 0,
+ "content": "continued on the same visual row",
+ "_local_line_bboxes": [
+ (204.0, 54.0, 280.0, 64.0),
+ (20.0, 66.0, 280.0, 77.0),
+ (20.0, 79.0, 280.0, 90.0),
+ ],
+ "_line_heights": [10.0, 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 "first block ending" in merged[0]["content"]
+ assert "continued on the same visual row" in merged[0]["content"]
+
+
+ ("boundary_left", "second_font"),
+ [(220.0, ("Body", 0)), (204.0, ("Other", 0))],
+)
+def test_boundary_visual_row_rejects_large_gap_or_font_conflict(
+ boundary_left: float,
+ second_font: tuple[str, int],
+) -> None:
+ """验证边界行横向间隔过大或字体集合冲突时不合并正文块。"""
+
+ first = {
+ "type": "text",
+ "bbox": (20.0, 40.0, 280.0, 64.0),
+ "angle": 0,
+ "content": "first",
+ "_local_line_bboxes": [
+ (20.0, 40.0, 280.0, 51.0),
+ (20.0, 52.0, 200.0, 64.0),
+ ],
+ "_line_heights": [11.0, 12.0],
+ "_font_signatures": {("Body", 0)},
+ }
+ second = {
+ "type": "text",
+ "bbox": (20.0, 54.0, 280.0, 90.0),
+ "angle": 0,
+ "content": "second",
+ "_local_line_bboxes": [
+ (boundary_left, 54.0, 280.0, 64.0),
+ (20.0, 66.0, 280.0, 77.0),
+ (20.0, 79.0, 280.0, 90.0),
+ ],
+ "_line_heights": [10.0, 11.0, 11.0],
+ "_font_signatures": {second_font},
+ }
+
+ merged = text_blocks._merge_overlapping_same_line_text_blocks(
+ [first, second],
+ (300.0, 200.0),
+ )
+
+ assert len(merged) == 2
+
+
def test_front_matter_grid_merges_each_author_column_independently() -> None:
"""验证标题后的四列规则前置信息按列合并且不横向串列。"""
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index b6684fe9..b8b958bc 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -1011,9 +1011,45 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
titles._infer_front_matter_boundary,
titles._normalized_title_gap,
titles._line_near_visual_container,
+ titles._is_wide_leading_title_continuation,
line_layout._title_fonts_compatible,
titles._expand_paragraph_title_neighbors,
)
)
assert ".text" not in source
+
+
+def test_cross_lane_title_expansion_accepts_only_wide_leading_line() -> None:
+ """验证较宽首行可并入下方窄标题锚点,反向的正文续行不会被扩成标题。"""
+
+ heading_font = ("Heading", 0)
+ leading = _text_line(
+ "wide leading line",
+ (72.0, 20.0, 287.0, 30.0),
+ 0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ )
+ anchor = _text_line(
+ "narrow anchor",
+ (130.0, 30.6, 230.0, 40.6),
+ 1,
+ semantic_type="paragraph_title",
+ font_signature=heading_font,
+ font_coverage=1.0,
+ )
+ following = _text_line(
+ "wide following line",
+ (72.0, 41.2, 287.0, 51.2),
+ 2,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ )
+
+ titles._expand_cross_lane_paragraph_title_neighbors(
+ [(leading, leading.bbox), (anchor, anchor.bbox), (following, following.bbox)]
+ )
+
+ assert leading.semantic_type == "paragraph_title"
+ assert following.semantic_type is None