Skip to content

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

feat: enhance typography processing by adding leading emphasis width detection and refining font family checks

myhloli41f6cd1b0d37
diff --git a/demo/pdfs/demo4.pdf b/demo/pdfs/demo4.pdf
new file mode 100644
index 00000000..033e782a
Binary files /dev/null and b/demo/pdfs/demo4.pdf differ
diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.py
index cc93f0a4..f819dcbc 100644
--- a/mineru/backend/flash/native_pdf/auxiliary_text.py
+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py
@@ -150,7 +150,13 @@ def _classify_page_footnotes(
for line, bbox in line_geometry
]
median_height = statistics.median(effective_heights) if effective_heights else 1.0
- lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)
+ lanes = _infer_text_lanes(
+ line_geometry,
+ local_page_width,
+ median_height,
+ # 脚注分隔线应对齐稳定栏锚点,不能被页眉或跨栏关键词的宽行扩张污染。
+ recalculate_intervals=False,
+ )
local_axis_lines = _transform_axis_lines(
drawing_lines,
page_size,
@@ -161,9 +167,10 @@ def _classify_page_footnotes(
for axis_line in local_axis_lines:
if axis_line.orientation != "horizontal":
continue
- # 分隔线中心必须进入页面下方 30%,上方的正文分隔线不参与脚注判定。
+ # 常规短分隔线仍要求进入页面下方 30%;栏宽分隔线可在下方 45% 内
+ # 依靠严格的单栏对齐和字号收缩证据提前触发。
rule_center_y = _bbox_center_y(axis_line.bbox)
- if rule_center_y < 0.7 * local_page_height:
+ if rule_center_y < 0.55 * local_page_height:
continue
# 表格边界会产生断裂横线;除框内线段外,也排除与其同高且近邻的框外线段。
if _rule_belongs_to_confirmed_table(
@@ -175,17 +182,48 @@ def _classify_page_footnotes(
continue
rule_source_indices: set[int] = set()
for lane in lanes:
+ following_rule_tops = [
+ other.bbox[1]
+ for other in local_axis_lines
+ if other.orientation == "horizontal"
+ and other.bbox[1] - axis_line.bbox[3] > 0.5 * median_height
+ and _bbox_axis_overlap_ratio(
+ axis_line.bbox,
+ other.bbox,
+ axis="x",
+ )
+ >= 0.8
+ ]
rule_source_indices.update(
_footnote_lane_members(
lane,
axis_line.bbox,
local_page_size,
+ page_median_height=median_height,
+ lane_width_reference=_footnote_lane_width_reference(
+ lane,
+ lanes,
+ median_height,
+ ),
+ allow_column_width_rule=(
+ rule_center_y >= 0.55 * local_page_height
+ ),
+ lower_barrier_y=(
+ min(following_rule_tops)
+ if following_rule_tops
+ else None
+ ),
)
)
if rule_source_indices:
candidate_groups.append(rule_source_indices)
page_footnote_groups = _merge_overlapping_source_groups(candidate_groups)
+ _augment_footnote_groups_with_edge_markers(
+ page_footnote_groups,
+ line_geometry,
+ median_height,
+ )
footnote_source_indices = set().union(*page_footnote_groups) if page_footnote_groups else set()
for line in available:
if line.source_index in footnote_source_indices:
@@ -193,6 +231,46 @@ def _classify_page_footnotes(
return page_footnote_groups
+def _augment_footnote_groups_with_edge_markers(
+ groups: list[set[int]],
+ line_geometry: list[tuple[_LineItem, BBox]],
+ median_height: float,
+) -> None:
+ """把脚注正文左侧同高的窄编号标记补入对应分隔线分组。"""
+
+ geometry_by_source = {
+ line.source_index: (line, bbox)
+ for line, bbox in line_geometry
+ }
+ for group in groups:
+ members = [
+ geometry_by_source[source_index]
+ for source_index in group
+ if source_index in geometry_by_source
+ ]
+ if not members:
+ continue
+ group_top = min(bbox[1] for _line, bbox in members)
+ group_bottom = max(bbox[3] for _line, bbox in members)
+ content_left = min(bbox[0] for _line, bbox in members)
+ for line, bbox in line_geometry:
+ if line.source_index in group:
+ continue
+ line_width = bbox[2] - bbox[0]
+ center_y = _bbox_center_y(bbox)
+ if (
+ line_width <= 1.5 * median_height
+ and content_left - 2.0 * median_height
+ <= bbox[0]
+ <= content_left
+ and bbox[2] <= content_left + 0.5 * median_height
+ and group_top - median_height
+ <= center_y
+ <= group_bottom + median_height
+ ):
+ group.add(line.source_index)
+
+
def _rule_belongs_to_confirmed_table(
candidate: _LocalAxisLine,
local_axis_lines: list[_LocalAxisLine],
@@ -245,6 +323,11 @@ def _footnote_lane_members(
lane: _TextLane,
rule_bbox: BBox,
local_page_size: tuple[float, float],
+ *,
+ page_median_height: float | None = None,
+ lane_width_reference: float | None = None,
+ allow_column_width_rule: bool = False,
+ lower_barrier_y: float | None = None,
) -> set[int]:
"""验证横线与单个栏带的对齐关系,并返回其下连续脚注行的来源编号。"""
@@ -253,18 +336,35 @@ def _footnote_lane_members(
return set()
lane_lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
local_page_width, local_page_height = local_page_size
- lane_width = max(0.1, lane.right - lane.left)
+ lane_width = max(
+ 0.1,
+ lane.right - lane.left,
+ lane_width_reference or 0.0,
+ )
lane_heights = [_line_effective_height(line, bbox) for line, bbox in lane_lines]
median_height = statistics.median(lane_heights) if lane_heights else 1.0
rule_width = max(0.0, rule_bbox[2] - rule_bbox[0])
# 同时限制绝对短线、相对长线和左缘偏移,排除图标、公式线及跨栏正文分隔线。
if rule_width < max(4.0 * median_height, 0.04 * local_page_width):
return set()
- if rule_width > 0.65 * lane_width:
- return set()
if abs(rule_bbox[0] - lane.left) > max(2.0 * median_height, 0.04 * lane_width):
return set()
+ rule_center_y = _bbox_center_y(rule_bbox)
+ is_regular_short_rule = (
+ rule_center_y >= 0.7 * local_page_height
+ and rule_width <= 0.65 * lane_width
+ )
+ endpoint_tolerance = max(2.0 * median_height, 0.05 * lane_width)
+ is_column_width_rule = (
+ allow_column_width_rule
+ and not lane.is_span
+ and 0.65 * lane_width <= rule_width <= 1.05 * lane_width
+ and abs(rule_bbox[2] - lane.right) <= endpoint_tolerance
+ )
+ if not is_regular_short_rule and not is_column_width_rule:
+ return set()
+
# 首行采用较宽的 3.5% 页高窗口;命中后仅按紧凑的连续净空向下扩展。
first_gap_limit = max(3.0 * median_height, 0.035 * local_page_height)
first_index: int | None = None
@@ -272,21 +372,257 @@ def _footnote_lane_members(
rule_gap = bbox[1] - rule_bbox[3]
if rule_gap < -0.5 * median_height:
continue
+ if lower_barrier_y is not None and bbox[1] >= lower_barrier_y:
+ break
if rule_gap <= first_gap_limit:
first_index = index
break
if first_index is None:
return set()
+ if is_column_width_rule:
+ # 页面中段的栏宽横线只有在下方首行相对上方正文明显收缩时才可触发脚注,
+ # 避免把章节分隔线或普通栏内横线误当成脚注边界。
+ body_heights = [
+ _line_effective_height(line, bbox)
+ for line, bbox in lane_lines
+ if bbox[3] <= rule_bbox[1] + 0.5 * median_height
+ ]
+ first_height = _line_effective_height(*lane_lines[first_index])
+ body_reference_height = statistics.median(body_heights) if body_heights else 0.0
+ if page_median_height is not None:
+ body_reference_height = max(
+ body_reference_height,
+ page_median_height,
+ )
+ if (
+ len(body_heights) < 3
+ or first_height > 0.95 * body_reference_height
+ ):
+ return set()
+
continuation_gap_limit = max(1.25 * median_height, 0.01 * local_page_height)
members = [lane_lines[first_index]]
for current in lane_lines[first_index + 1 :]:
+ if lower_barrier_y is not None and current[1][1] >= lower_barrier_y:
+ break
if _effective_text_row_gap(members[-1], current) > continuation_gap_limit:
break
members.append(current)
return {line.source_index for line, _bbox in members}
+def _footnote_lane_width_reference(
+ lane: _TextLane,
+ lanes: list[_TextLane],
+ median_height: float,
+) -> float:
+ """用下一稳定栏的左缘补偿当前栏因正文右缘参差造成的宽度低估。"""
+
+ lane_width = max(0.1, lane.right - lane.left)
+ stable_lanes = sorted(
+ [
+ candidate
+ for candidate in lanes
+ if not candidate.is_span and len(candidate.lines) >= 3
+ ],
+ key=lambda candidate: candidate.left,
+ )
+ if lane not in stable_lanes:
+ return lane_width
+ lane_index = stable_lanes.index(lane)
+ if lane_index + 1 >= len(stable_lanes):
+ return lane_width
+ minimum_gutter = max(6.0, 0.75 * median_height)
+ next_lane = stable_lanes[lane_index + 1]
+ return max(
+ lane_width,
+ next_lane.left - lane.left - minimum_gutter,
+ )
+
+
+def _classify_rule_delimited_headers(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,
+ )
+ candidates = [
+ axis_line
+ for axis_line in local_axis_lines
+ if axis_line.orientation == "horizontal"
+ and _bbox_center_y(axis_line.bbox) <= 0.15 * local_page_height
+ and axis_line.bbox[2] - axis_line.bbox[0]
+ >= 0.6 * local_page_width
+ and not _rule_belongs_to_confirmed_table(
+ axis_line,
+ local_axis_lines,
+ page.table_bboxes,
+ local_page_width,
+ )
+ and not _rule_overlaps_fixed_container(
+ axis_line,
+ page.fixed_blocks,
+ page.page_size,
+ )
+ ]
+ if not candidates:
+ continue
+ separator = max(candidates, key=lambda item: _bbox_center_y(item.bbox))
+ separator_y = _bbox_center_y(separator.bbox)
+ local_lines = [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page.page_size,
+ dominant_angle,
+ ),
+ )
+ for line in available
+ if line.angle == dominant_angle
+ ]
+ heights = [
+ _line_effective_height(line, bbox)
+ for line, bbox in local_lines
+ ]
+ median_height = statistics.median(heights) if heights else 1.0
+ if not any(
+ _bbox_center_y(bbox) >= separator_y + median_height
+ for _line, bbox in local_lines
+ ):
+ continue
+ for line, bbox in local_lines:
+ if bbox[3] <= separator_y:
+ line.semantic_type = "header"
+
+
+def _rule_overlaps_fixed_container(
+ rule: _LocalAxisLine,
+ fixed_blocks: list[dict[str, object]],
+ page_size: tuple[float, float],
+) -> bool:
+ """排除落在表格、图片或公式容器内的页首横线。"""
+
+ expanded_rule = _expand_bbox(
+ rule.original_bbox,
+ max(1.0, rule.width),
+ )
+ for block in fixed_blocks:
+ if block.get("type") not in {"table", "image", "equation"}:
+ continue
+ bbox = _clip_bbox(_coerce_bbox(block.get("bbox")), page_size)
+ if bbox is not None and _bbox_intersects(expanded_rule, bbox):
+ return True
+ return False
+
+
+def _classify_page_number_outer_companions(
+ pages: list[_PreparedPage],
+) -> None:
+ """把上下页码外侧的未分类文本和图片标为对应页眉或页脚。"""
+
+ for page in pages:
+ page_numbers = [
+ line
+ for line in page.remaining_lines
+ if line.semantic_type == "page_number"
+ ]
+ for page_number in page_numbers:
+ angle = page_number.angle
+ local_page_size = (
+ (page.page_size[1], page.page_size[0])
+ if angle in {90, 270}
+ else page.page_size
+ )
+ local_page_height = local_page_size[1]
+ if local_page_height <= 0:
+ continue
+ page_number_bbox = _rotate_bbox_to_upright(
+ page_number.bbox,
+ page.page_size,
+ angle,
+ )
+ normalized_center_y = (
+ _bbox_center_y(page_number_bbox) / local_page_height
+ )
+ if normalized_center_y <= 0.3:
+ target_type: Literal["header", "footer"] = "header"
+ outward_limit = page_number_bbox[1]
+ elif normalized_center_y >= 0.7:
+ target_type = "footer"
+ outward_limit = page_number_bbox[3]
+ else:
+ continue
+ for line in page.remaining_lines:
+ if line.semantic_type is not None or line.angle != angle:
+ continue
+ local_bbox = _rotate_bbox_to_upright(
+ line.bbox,
+ page.page_size,
+ angle,
+ )
+ is_outward = (
+ local_bbox[3] <= outward_limit
+ if target_type == "header"
+ else local_bbox[1] >= outward_limit
+ )
+ if is_outward:
+ line.semantic_type = target_type
+ for block in page.fixed_blocks:
+ if block.get("type") != "image":
+ continue
+ block_angle = int(block.get("angle", 0) or 0) % 360
+ if block_angle != angle:
+ continue
+ bbox = _clip_bbox(
+ _coerce_bbox(block.get("bbox")),
+ page.page_size,
+ )
+ if bbox is None:
+ continue
+ local_bbox = _rotate_bbox_to_upright(
+ bbox,
+ page.page_size,
+ angle,
+ )
+ is_outward = (
+ local_bbox[3] <= outward_limit
+ if target_type == "header"
+ else local_bbox[1] >= outward_limit
+ )
+ if is_outward:
+ block["type"] = target_type
+
+
def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:
"""仅用相邻或同奇偶页的重复证据标注页码、页眉和页脚。"""
@@ -350,11 +686,6 @@ def _classify_repeated_visual_headers(pages: list[_PreparedPage]) -> None:
for block in page.fixed_blocks:
if block.get("type") != "image":
continue
- content = block.get("content")
- # 当前 model_list 不保留空文本 header;这里只限制输出可表示性,
- # 跨页匹配本身完全不比较 content。
- if not isinstance(content, str) or not content.strip():
- continue
bbox = _clip_bbox(_coerce_bbox(block.get("bbox")), page.page_size)
if bbox is None or bbox[3] > 0.12 * page_height:
continue
diff --git a/mineru/backend/flash/native_pdf/formulas.py b/mineru/backend/flash/native_pdf/formulas.py
index 700c763f..bfc91d54 100644
--- a/mineru/backend/flash/native_pdf/formulas.py
+++ b/mineru/backend/flash/native_pdf/formulas.py
@@ -753,6 +753,13 @@ def _find_formula_spatial_anchors(
):
# 一条粗行被多个大空格拆成密集词组时更像普通排版行,不能把末词当作公式编号锚点。
continue
+ if _split_visual_row_has_prose_continuation(
+ lane,
+ line,
+ same_row_fragments,
+ median_height,
+ ):
+ continue
if abs(lane.right - bbox[2]) > max(3.0, 0.02 * lane_width):
continue
center_y = _bbox_center_y(bbox)
@@ -811,6 +818,67 @@ def _find_formula_spatial_anchors(
return _deduplicate_formula_anchors(anchors, median_height)
+def _split_visual_row_has_prose_continuation(
+ lane: _TextLane,
+ anchor_line: _LineItem,
+ same_row_fragments: list[_LineItem],
+ median_height: float,
+) -> bool:
+ """识别覆盖大部分栏宽且紧接下一正文行的同行拆分文本。"""
+
+ if len(same_row_fragments) < 3 or anchor_line.visual_row_id is None:
+ return False
+ fragment_sources = {
+ line.source_index
+ for line in same_row_fragments
+ }
+ fragment_geometry = [
+ (line, bbox)
+ for line, bbox in lane.lines
+ if line.source_index in fragment_sources
+ ]
+ if len(fragment_geometry) < 3:
+ return False
+ lane_width = max(0.1, lane.right - lane.left)
+ row_bbox = _bbox_union_many([bbox for _line, bbox in fragment_geometry])
+ if row_bbox[2] - row_bbox[0] < 0.75 * lane_width:
+ return False
+ row_center = statistics.median(
+ _bbox_center_y(bbox)
+ for _line, bbox in fragment_geometry
+ )
+ if any(
+ abs(_bbox_center_y(bbox) - row_center) > 0.25 * median_height
+ or not 0.7 * median_height
+ <= _line_effective_height(line, bbox)
+ <= 1.3 * median_height
+ for line, bbox in fragment_geometry
+ ):
+ return False
+ following_rows = [
+ (line, bbox)
+ for line, bbox in lane.lines
+ if line.source_index not in fragment_sources
+ and _bbox_center_y(bbox) > row_center + 0.5 * median_height
+ ]
+ if not following_rows:
+ return False
+ following_line, following_bbox = min(
+ following_rows,
+ key=lambda item: (_bbox_center_y(item[1]), item[1][0]),
+ )
+ following_height = _line_effective_height(
+ following_line,
+ following_bbox,
+ )
+ return (
+ following_bbox[2] - following_bbox[0] >= 0.6 * lane_width
+ and abs(following_bbox[0] - lane.left) <= 0.75 * median_height
+ and 0.75 * median_height <= following_height <= 1.3 * median_height
+ and following_bbox[1] - row_bbox[3] <= 1.25 * median_height
+ )
+
+
def _infer_formula_body_font(
lane: _TextLane,
median_height: float,
diff --git a/mineru/backend/flash/native_pdf/line_layout.py b/mineru/backend/flash/native_pdf/line_layout.py
index 6670964f..6bbe62d0 100644
--- a/mineru/backend/flash/native_pdf/line_layout.py
+++ b/mineru/backend/flash/native_pdf/line_layout.py
@@ -36,14 +36,46 @@ def _title_fonts_compatible(first: _LineItem, second: _LineItem) -> bool:
and second.font_coverage >= 0.75
and first.font_signature != second.font_signature
)
- weight_conflicts = (
+ weight_conflicts = _font_weights_conflict(first, second)
+ return not (font_conflicts or weight_conflicts)
+
+
+def _normalized_font_family(
+ signature: tuple[str, int] | None,
+) -> str | None:
+ """移除 PDF 字体子集前缀并归一化字体族名称,供几何续行作软兼容判断。"""
+
+ if signature is None:
+ return None
+ name = re.sub(r"^[A-Z]{6}\+", "", signature[0])
+ return re.sub(r"[\s_-]+", "", name).casefold() or None
+
+
+def _font_signatures_share_family(
+ first: tuple[str, int] | None,
+ second: tuple[str, int] | None,
+) -> bool:
+ """判断两个可靠字体签名是否仅因 PDF 子集前缀或描述标志不同。"""
+
+ first_family = _normalized_font_family(first)
+ second_family = _normalized_font_family(second)
+ return (
+ first_family is not None
+ and second_family is not None
+ and first_family == second_family
+ )
+
+
+def _font_weights_conflict(first: _LineItem, second: _LineItem) -> bool:
+ """判断两行是否存在足以构成段落硬边界的显著字重差异。"""
+
+ return (
first.dominant_font_weight is not None
and second.dominant_font_weight is not None
and abs(first.dominant_font_weight - second.dominant_font_weight) >= 100.0
and max(first.dominant_font_weight, second.dominant_font_weight)
>= 1.15 * min(first.dominant_font_weight, second.dominant_font_weight)
)
- return not (font_conflicts or weight_conflicts)
def _should_connect_semantic_rows(
@@ -137,15 +169,17 @@ def _infer_text_lanes(
line_geometry: list[tuple[_LineItem, BBox]],
local_page_width: float,
median_height: float,
+ *,
+ recalculate_intervals: bool = True,
) -> list[_TextLane]:
- """从重复左右边缘推断稳定栏带,并把跨栏行放入独立 span lane。"""
+ """从重复左右边缘推断稳定栏带,并按需用已分配成员重算边界。"""
anchor_tolerance = max(3.0, 0.75 * median_height)
anchor_geometry = [
item
for item in line_geometry
if item[0].semantic_type
- not in {"header", "footer", "page_number", "page_footnote", "aside_text"}
+ not in {"header", "footer", "page_number", "aside_text"}
]
regular_lines = [
item
@@ -233,15 +267,30 @@ def _infer_text_lanes(
(coverage for coverage, _lane in scored_lanes),
reverse=True,
)
- if len(coverage_scores) > 1 and coverage_scores[1] >= 0.2:
+ best_coverage, best_lane = max(scored_lanes, key=lambda value: value[0])
+ fits_only_one_lane = _fits_only_one_lane(
+ bbox,
+ best_lane,
+ nested_lanes,
+ anchor_tolerance,
+ )
+ if (
+ len(coverage_scores) > 1
+ and coverage_scores[1] >= 0.2
+ and not fits_only_one_lane
+ ):
span_lines.append(item)
continue
- best_coverage, best_lane = max(scored_lanes, key=lambda value: value[0])
- if best_coverage >= 0.5:
+ if best_coverage >= 0.5 or fits_only_one_lane:
best_lane.lines.append(item)
else:
span_lines.append(item)
lanes = [lane for lane in nested_lanes if lane.lines]
+ if recalculate_intervals:
+ _expand_nested_lane_intervals_from_members(
+ lanes,
+ anchor_tolerance,
+ )
if fallback_lane.lines:
lanes.append(fallback_lane)
if span_lines:
@@ -272,21 +321,32 @@ def _infer_text_lanes(
(coverage for coverage, _lane in scored_lanes),
reverse=True,
)
- # 同时覆盖两个稳定正文栏的短尾行仍属于跨栏内容,不能按中心点落回单栏。
- if len(coverage_scores) > 1 and coverage_scores[1] >= 0.2:
- span_lines.append(item)
- continue
best_coverage, best_lane = max(scored_lanes, key=lambda value: value[0])
- if len(lanes) == 1 or (
- best_coverage >= 0.5
- and best_lane.left - anchor_tolerance
- <= _bbox_center_x(bbox)
- <= best_lane.right + anchor_tolerance
+ fits_only_one_lane = _fits_only_one_lane(
+ bbox,
+ best_lane,
+ lanes,
+ anchor_tolerance,
+ )
+ # 同时覆盖两个稳定正文栏的行仍属于跨栏内容;只进入单侧栏且未越过栏沟的
+ # 宽正文行则回到该栏,避免窄图注把正文错误挤入 span lane。
+ if (
+ len(coverage_scores) > 1
+ and coverage_scores[1] >= 0.2
+ and not fits_only_one_lane
):
+ span_lines.append(item)
+ continue
+ if len(lanes) == 1 or fits_only_one_lane:
best_lane.lines.append(item)
else:
span_lines.append(item)
+ if recalculate_intervals:
+ _expand_nested_lane_intervals_from_members(
+ lanes,
+ anchor_tolerance,
+ )
if span_lines:
lanes.append(
_TextLane(
@@ -300,6 +360,66 @@ def _infer_text_lanes(
return lanes
+def _fits_only_one_lane(
+ bbox: BBox,
+ best_lane: _TextLane,
+ lanes: list[_TextLane],
+ tolerance: float,
+) -> bool:
+ """判断宽行是否仍完整停留在某一栏及其栏沟边界以内。"""
+
+ ordered = sorted(lanes, key=lambda lane: lane.left)
+ lane_index = ordered.index(best_lane)
+ if lane_index > 0 and bbox[0] < ordered[lane_index - 1].right - tolerance:
+ return False
+ if (
+ lane_index + 1 < len(ordered)
+ and bbox[2] > ordered[lane_index + 1].left - 0.25 * tolerance
+ ):
+ return False
+ return (
+ best_lane.left - tolerance
+ <= _bbox_center_x(bbox)
+ <= best_lane.right + max(tolerance, bbox[2] - best_lane.right)
+ )
+
+
+def _expand_nested_lane_intervals_from_members(
+ lanes: list[_TextLane],
+ tolerance: float,
+) -> None:
+ """按已归属成员扩展局部栏边界,并在相邻栏相交前保留稳定栏沟。"""
+
+ for lane in lanes:
+ alignment_tolerance = max(1.0, 0.5 * tolerance)
+ body_members = [
+ bbox
+ for line, bbox in lane.lines
+ if line.semantic_type is None
+ ]
+ if not body_members:
+ continue
+ aligned_members = [
+ bbox
+ for bbox in body_members
+ if abs(bbox[0] - lane.left) <= alignment_tolerance
+ or abs(bbox[2] - lane.right) <= alignment_tolerance
+ ]
+ if not aligned_members:
+ continue
+ # 页眉、页码和标题不参与;同时只让至少一侧锚点稳定的正文扩张栏宽,
+ # 避免页面后续另一版式区段把当前局部栏整体拉宽。
+ lane.left = min(lane.left, min(bbox[0] for bbox in aligned_members))
+ lane.right = max(lane.right, max(bbox[2] for bbox in aligned_members))
+ ordered = sorted(lanes, key=lambda lane: lane.left)
+ for left_lane, right_lane in zip(ordered, ordered[1:]):
+ if left_lane.right < right_lane.left - tolerance:
+ continue
+ midpoint = (left_lane.right + right_lane.left) / 2.0
+ left_lane.right = min(left_lane.right, midpoint)
+ right_lane.left = max(right_lane.left, midpoint)
+
+
def _infer_nested_column_band(
line_geometry: list[tuple[_LineItem, BBox]],
local_page_width: float,
@@ -542,6 +662,29 @@ def _estimate_lane_gap(lane: _TextLane) -> tuple[float, float]:
return regular_gap, gap_mad
+def _is_structural_typography_gap(
+ previous_height: float,
+ current_height: float,
+ vertical_gap: float,
+ regular_gap: float,
+ gap_mad: float,
+ *,
+ reliable_style_change: bool = False,
+) -> bool:
+ """判断异常段间净空是否同时具有行高或可靠字体层级变化。"""
+
+ pair_height = max(previous_height, current_height)
+ minimum_height = max(0.1, min(previous_height, current_height))
+ prominent_gap = vertical_gap > regular_gap + max(
+ 0.75 * pair_height,
+ 3.0 * gap_mad,
+ )
+ return prominent_gap and (
+ pair_height / minimum_height >= 1.12
+ or reliable_style_change
+ )
+
+
def _should_connect_text_rows(
previous: tuple[_LineItem, BBox],
current: tuple[_LineItem, BBox],
@@ -586,6 +729,10 @@ def _should_connect_text_rows(
or previous_line.font_coverage < 0.75
or current_line.font_coverage < 0.75
or previous_line.font_signature == current_line.font_signature
+ or _font_signatures_share_family(
+ previous_line.font_signature,
+ current_line.font_signature,
+ )
or (
current_width <= 0.5 * lane_width
and previous_line.font_signature[1] == current_line.font_signature[1]
@@ -596,6 +743,7 @@ def _should_connect_text_rows(
and current_width <= 0.7 * lane_width
and (aligned_left_edges or current_returns_to_lane_left)
and reliable_font_match
+ and not _font_weights_conflict(previous_line, current_line)
and -0.25 * pair_height
<= vertical_gap
<= regular_gap + max(0.75 * pair_height, 3.0 * gap_mad)
@@ -605,7 +753,40 @@ def _should_connect_text_rows(
previous_line.font_signature is not None
and current_line.font_signature is not None
and previous_line.font_signature[1] != current_line.font_signature[1]
+ and not _font_signatures_share_family(
+ previous_line.font_signature,
+ current_line.font_signature,
+ )
)
+ reliable_style_conflict = (
+ previous_line.font_signature is not None
+ and current_line.font_signature is not None
+ and previous_line.font_coverage >= 0.75
+ and current_line.font_coverage >= 0.75
+ and (
+ (
+ previous_line.font_signature != current_line.font_signature
+ and not _font_signatures_share_family(
+ previous_line.font_signature,
+ current_line.font_signature,
+ )
+ )
+ or _font_weights_conflict(previous_line, current_line)
+ )
+ )
+ if (
+ not is_hyphen_at_line_end(previous_line.text)
+ and _is_structural_typography_gap(
+ previous_height,
+ current_height,
+ vertical_gap,
+ regular_gap,
+ gap_mad,
+ reliable_style_change=reliable_style_conflict,
+ )
+ ):
+ # 图注到正文等排版层级转换即使同栏满行,也不能被常规续行规则重新吸收。
+ return False
full_width_continuation = (
both_fill_lane
and aligned_left_edges
@@ -654,11 +835,7 @@ def _should_connect_text_rows(
abnormal_gap = vertical_gap > regular_gap + max(0.25 * pair_height, 3.0 * gap_mad)
if (
- previous_line.font_signature is not None
- and current_line.font_signature is not None
- and previous_line.font_coverage >= 0.75
- and current_line.font_coverage >= 0.75
- and previous_line.font_signature != current_line.font_signature
+ reliable_style_conflict
and (abnormal_gap or min(previous_width, current_width) <= 0.7 * lane_width)
and not both_fill_lane
and not safe_short_tail
diff --git a/mineru/backend/flash/native_pdf/line_merging.py b/mineru/backend/flash/native_pdf/line_merging.py
index 31b8cf0d..18e6c4f5 100644
--- a/mineru/backend/flash/native_pdf/line_merging.py
+++ b/mineru/backend/flash/native_pdf/line_merging.py
@@ -329,6 +329,7 @@ def _merge_overlapping_inline_cluster(
font_coverage=host.font_coverage,
dominant_font_weight=host.dominant_font_weight,
median_glyph_width=host.median_glyph_width,
+ leading_emphasis_width=ordered_members[0].leading_emphasis_width,
split_from_row=any(line.split_from_row for line in ordered_members),
semantic_type=host.semantic_type,
restored_inline_cluster=True,
@@ -600,6 +601,7 @@ def _merge_same_baseline_group(
)
if any(member.median_glyph_width is not None for member in members)
else None,
+ leading_emphasis_width=members[0].leading_emphasis_width,
split_from_row=any(member.split_from_row for member in members),
semantic_type=members[0].semantic_type,
restored_inline_cluster=any(
@@ -938,6 +940,7 @@ def _merge_dense_split_visual_row(
)
if any(member.median_glyph_width is not None for member in ordered_members)
else None,
+ leading_emphasis_width=ordered_members[0].leading_emphasis_width,
split_from_row=False,
semantic_type=ordered_members[0].semantic_type,
restored_inline_cluster=any(
@@ -950,4 +953,3 @@ def _merge_dense_split_visual_row(
if merged.chars:
_fill_native_typography(merged, page_size)
return merged
-
diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.py
index b84fed7c..a8d674ee 100644
--- a/mineru/backend/flash/native_pdf/models.py
+++ b/mineru/backend/flash/native_pdf/models.py
@@ -29,6 +29,7 @@ class _LineItem:
font_coverage: float = 0.0
dominant_font_weight: float | None = None
median_glyph_width: float | None = None
+ leading_emphasis_width: float | None = None
split_from_row: bool = False
semantic_type: str | None = None
restored_inline_cluster: bool = False
diff --git a/mineru/backend/flash/native_pdf/native_text.py b/mineru/backend/flash/native_pdf/native_text.py
index 7734afb7..ab0981f5 100644
--- a/mineru/backend/flash/native_pdf/native_text.py
+++ b/mineru/backend/flash/native_pdf/native_text.py
@@ -281,6 +281,45 @@ def _sanitize_pdf_control_text(text: str, *, preserve_newlines: bool) -> str:
return _PDF_CONTROL_CHAR_RE.sub("", normalized)
+def _detect_leading_emphasis_width(
+ glyphs: list[tuple[BBox, tuple[str, int] | None, float | None]],
+) -> float | None:
+ """从行首连续字体 run 中提取字重显著高于后续正文的几何宽度。"""
+
+ if len(glyphs) < 4:
+ return None
+ first_signature = glyphs[0][1]
+ if first_signature is None:
+ return None
+
+ prefix: list[tuple[BBox, tuple[str, int] | None, float | None]] = []
+ body: list[tuple[BBox, tuple[str, int] | None, float | None]] = []
+ reached_body = False
+ for glyph in glyphs:
+ if not reached_body and glyph[1] == first_signature:
+ prefix.append(glyph)
+ continue
+ reached_body = True
+ body.append(glyph)
+ if len(prefix) < 2 or len(body) < 2:
+ return None
+
+ prefix_weights = [weight for _bbox, _signature, weight in prefix if weight is not None]
+ body_weights = [weight for _bbox, _signature, weight in body if weight is not None]
+ if not prefix_weights or not body_weights:
+ return None
+ prefix_weight = statistics.median(prefix_weights)
+ body_weight = statistics.median(body_weights)
+ if (
+ prefix_weight - body_weight < 100.0
+ or prefix_weight < 1.15 * max(1.0, body_weight)
+ ):
+ return None
+
+ prefix_bbox = _bbox_union_many([bbox for bbox, _signature, _weight in prefix])
+ return max(0.1, prefix_bbox[2] - prefix_bbox[0])
+
+
def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) -> None:
"""使用非空字符 bbox 高度和 dominant font 填充原生行排版特征。"""
@@ -288,6 +327,7 @@ def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) ->
glyph_widths: list[float] = []
font_counts: dict[tuple[str, int], int] = {}
font_weights: dict[tuple[str, int], list[float]] = {}
+ glyph_typography: list[tuple[BBox, tuple[str, int] | None, float | None]] = []
valid_font_chars = 0
for char in line.chars:
raw_char = str(char.get("char") or "")
@@ -302,6 +342,7 @@ def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) ->
font = char.get("font") or {}
font_name = str(font.get("name") or "")
if not font_name:
+ glyph_typography.append((local_bbox, None, None))
continue
try:
font_flags = int(font.get("flags") or 0)
@@ -315,6 +356,9 @@ def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) ->
font_weight = math.nan
if math.isfinite(font_weight):
font_weights.setdefault(signature, []).append(font_weight)
+ glyph_typography.append((local_bbox, signature, font_weight))
+ else:
+ glyph_typography.append((local_bbox, signature, None))
valid_font_chars += 1
local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)
@@ -329,6 +373,7 @@ def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) ->
line.font_signature = None
line.font_coverage = 0.0
line.dominant_font_weight = None
+ line.leading_emphasis_width = _detect_leading_emphasis_width(glyph_typography)
def _is_detached_inline_script_candidate(
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index b8b37c2d..23c746d7 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -59,7 +59,9 @@ from .formulas import (
_build_vector_formula_blocks,
)
from .auxiliary_text import (
+ _classify_page_number_outer_companions,
_classify_page_auxiliary_text,
+ _classify_rule_delimited_headers,
_classify_repeated_page_marginals,
_classify_repeated_visual_headers,
)
@@ -188,6 +190,8 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
_classify_repeated_visual_headers(prepared_pages)
_classify_repeated_page_marginals(prepared_pages)
+ _classify_rule_delimited_headers(prepared_pages)
+ _classify_page_number_outer_companions(prepared_pages)
document_body_profile = _infer_document_body_profile(prepared_pages)
return [
_finalize_prepared_page(
@@ -685,7 +689,7 @@ def _normalize_output_block(
content = _sanitize_pdf_control_text(content, preserve_newlines=True)
block_type = block.get("type")
normalized_type = block_type if block_type in _OUTPUT_BLOCK_TYPES else "text"
- if normalized_type not in {"image", "equation"} and not content.strip():
+ if normalized_type not in {"image", "equation", "header", "footer"} and not content.strip():
return None
normalized_bbox = _normalize_bbox_to_thousandths(bbox, page_size)
return {
diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.py
index 37a74d64..52b46916 100644
--- a/mineru/backend/flash/native_pdf/tables.py
+++ b/mineru/backend/flash/native_pdf/tables.py
@@ -597,9 +597,185 @@ def _build_rule_table_candidates(
+ min(fill_band_count, 8)
)
candidates.append(candidate)
+ return _expand_candidates_to_connected_rule_grids(
+ candidates,
+ rows,
+ page_size,
+ angle,
+ median_height,
+ axis_lines,
+ excluded_bboxes,
+ )
+
+
+def _expand_candidates_to_connected_rule_grids(
+ candidates: list[_TableCandidate],
+ rows: list[_VisualRow],
+ page_size: tuple[float, float],
+ angle: int,
+ median_height: float,
+ axis_lines: list[_LocalAxisLine],
+ excluded_bboxes: list[BBox],
+) -> list[_TableCandidate]:
+ """把已确认候选沿连续横边界和贯穿竖轨扩展到完整物理网格。"""
+
+ grid_bboxes = [
+ grid_bbox
+ for grid_bbox in _connected_rule_grid_bboxes(axis_lines, median_height)
+ if not any(
+ _bbox_overlap_in_smaller(grid_bbox, excluded_bbox) >= 0.5
+ for excluded_bbox in excluded_bboxes
+ )
+ ]
+ if not grid_bboxes:
+ return candidates
+
+ tolerance = max(2.0, median_height)
+ for candidate in candidates:
+ if candidate.core_bbox is None:
+ continue
+ core_local_bbox = _rotate_bbox_to_upright(
+ candidate.core_bbox,
+ page_size,
+ angle,
+ )
+ matches = [
+ grid_bbox
+ for grid_bbox in grid_bboxes
+ if _bbox_axis_overlap_ratio(
+ core_local_bbox,
+ grid_bbox,
+ axis="x",
+ )
+ >= 0.9
+ and core_local_bbox[3] >= grid_bbox[1] - tolerance
+ and core_local_bbox[1] <= grid_bbox[3] + tolerance
+ ]
+ if not matches:
+ continue
+ grid_bbox = max(
+ matches,
+ key=lambda bbox: (
+ min(core_local_bbox[3], bbox[3])
+ - max(core_local_bbox[1], bbox[1]),
+ _bbox_area(bbox),
+ ),
+ )
+ expanded_core_bbox = _bbox_union(core_local_bbox, grid_bbox)
+ candidate.local_bbox = _bbox_union(candidate.local_bbox, grid_bbox)
+ candidate.core_bbox = _rotate_bbox_from_upright(
+ expanded_core_bbox,
+ page_size,
+ angle,
+ )
+ candidate.bbox = _rotate_bbox_from_upright(
+ candidate.local_bbox,
+ page_size,
+ angle,
+ )
+ for row in rows:
+ if not expanded_core_bbox[1] <= row.center_y <= expanded_core_bbox[3]:
+ continue
+ candidate.line_indices.update(
+ fragment.line_index
+ for fragment in row.fragments
+ if _point_in_bbox(
+ (
+ _bbox_center_x(fragment.local_bbox),
+ _bbox_center_y(fragment.local_bbox),
+ ),
+ expanded_core_bbox,
+ )
+ )
return candidates
+def _connected_rule_grid_bboxes(
+ axis_lines: list[_LocalAxisLine],
+ median_height: float,
+) -> list[BBox]:
+ """把端点一致且由外轨或至少两条列轨贯穿的相邻横线组成网格框。"""
+
+ output: list[BBox] = []
+ for rule_group in _group_long_horizontal_rules(axis_lines, median_height):
+ components: list[list[_LocalAxisLine]] = []
+ for rule in rule_group:
+ if not components or not _rule_bands_share_grid_tracks(
+ components[-1][-1],
+ rule,
+ axis_lines,
+ median_height,
+ ):
+ components.append([rule])
+ else:
+ components[-1].append(rule)
+ output.extend(
+ _bbox_union_many([rule.bbox for rule in component])
+ for component in components
+ if len(component) >= 2
+ )
+ return output
+
+
+def _rule_bands_share_grid_tracks(
+ top_rule: _LocalAxisLine,
+ bottom_rule: _LocalAxisLine,
+ axis_lines: list[_LocalAxisLine],
+ median_height: float,
+) -> bool:
+ """校验相邻横边界的跨度,并确认其间存在连续外框或稳定列分隔线。"""
+
+ top_width = max(0.1, top_rule.bbox[2] - top_rule.bbox[0])
+ bottom_width = max(0.1, bottom_rule.bbox[2] - bottom_rule.bbox[0])
+ overlap_left = max(top_rule.bbox[0], bottom_rule.bbox[0])
+ overlap_right = min(top_rule.bbox[2], bottom_rule.bbox[2])
+ overlap_width = max(0.0, overlap_right - overlap_left)
+ endpoint_tolerance = max(4.0, 2.0 * median_height)
+ if (
+ overlap_width / max(top_width, bottom_width) < 0.9
+ or abs(top_rule.bbox[0] - bottom_rule.bbox[0]) > endpoint_tolerance
+ or abs(top_rule.bbox[2] - bottom_rule.bbox[2]) > endpoint_tolerance
+ ):
+ return False
+
+ top_y = _bbox_center_y(top_rule.bbox)
+ bottom_y = _bbox_center_y(bottom_rule.bbox)
+ track_tolerance = max(1.0, 0.25 * median_height)
+ raw_positions = [
+ _bbox_center_x(line.bbox)
+ for line in axis_lines
+ if line.orientation == "vertical"
+ and line.bbox[1] <= top_y + track_tolerance
+ and line.bbox[3] >= bottom_y - track_tolerance
+ and overlap_left - track_tolerance
+ <= _bbox_center_x(line.bbox)
+ <= overlap_right + track_tolerance
+ ]
+ position_groups: list[list[float]] = []
+ for position in sorted(raw_positions):
+ if (
+ position_groups
+ and abs(position - statistics.mean(position_groups[-1]))
+ <= track_tolerance
+ ):
+ position_groups[-1].append(position)
+ else:
+ position_groups.append([position])
+ positions = [statistics.mean(group) for group in position_groups]
+ has_outer_tracks = (
+ any(abs(position - overlap_left) <= endpoint_tolerance for position in positions)
+ and any(abs(position - overlap_right) <= endpoint_tolerance for position in positions)
+ )
+ interior_tracks = [
+ position
+ for position in positions
+ if overlap_left + track_tolerance
+ < position
+ < overlap_right - track_tolerance
+ ]
+ return has_outer_tracks or len(interior_tracks) >= 2
+
+
def _group_long_horizontal_rules(
axis_lines: list[_LocalAxisLine],
median_height: float,
diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.py
index 1e5b9212..e32cf065 100644
--- a/mineru/backend/flash/native_pdf/text_blocks.py
+++ b/mineru/backend/flash/native_pdf/text_blocks.py
@@ -38,6 +38,7 @@ from .line_layout import (
_estimate_lane_gap,
_horizontal_rule_separates_rows,
_infer_text_lanes,
+ _is_structural_typography_gap,
_line_effective_height,
_should_connect_semantic_rows,
_should_connect_text_rows,
@@ -184,9 +185,10 @@ def _build_hanging_indent_group_map(
row_index += 1
continue
- next_start_index, continuation_left = first_entry
- start_indices = [row_index, next_start_index]
- current_start_index = next_start_index
+ _next_start_index, continuation_left = first_entry
+ start_indices = [row_index]
+ current_start_index = row_index
+ end_index: int | None = None
while True:
next_entry = consume_entry(
current_start_index,
@@ -195,21 +197,32 @@ def _build_hanging_indent_group_map(
require_next_start=True,
)
if next_entry is None:
+ final_entry = consume_entry(
+ current_start_index,
+ start_left,
+ continuation_left,
+ require_next_start=False,
+ )
+ if final_entry is not None:
+ end_index = final_entry[0]
break
next_start_index, _continuation_left = next_entry
+ prospective_entry = consume_entry(
+ next_start_index,
+ start_left,
+ continuation_left,
+ require_next_start=False,
+ )
+ if prospective_entry is None:
+ # 当前条目已经完整确认;后面的普通左对齐段落只作为终止边界,
+ # 不能让它反向使此前所有悬挂缩进条目失效。
+ end_index = next_start_index
+ break
start_indices.append(next_start_index)
current_start_index = next_start_index
-
- final_entry = consume_entry(
- start_indices[-1],
- start_left,
- continuation_left,
- require_next_start=False,
- )
- if final_entry is None:
+ if len(start_indices) < 2 or end_index is None:
row_index += 1
continue
- end_index, _continuation_left = final_entry
entry_ranges = [
(start, end)
@@ -336,6 +349,153 @@ def _split_page_footnote_entries(
indent_threshold = max(1.5 * median_height, 2.0 * median_glyph_width)
base_left = min(bbox[0] for _line, bbox in line_geometry)
maximum_row_width = max(bbox[2] - bbox[0] for _line, bbox in line_geometry)
+ marker_rows = _find_page_footnote_marker_rows(
+ line_geometry,
+ median_height,
+ median_glyph_width,
+ base_left,
+ )
+ if len(marker_rows) >= 2:
+ return _split_marked_page_footnote_entries(
+ line_geometry,
+ marker_rows,
+ median_height,
+ median_glyph_width,
+ base_left,
+ maximum_row_width,
+ indent_threshold,
+ )
+ return _split_unmarked_page_footnote_entries(
+ line_geometry,
+ base_left,
+ maximum_row_width,
+ indent_threshold,
+ )
+
+
+def _find_page_footnote_marker_rows(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ median_height: float,
+ median_glyph_width: float,
+ base_left: float,
+) -> list[tuple[tuple[_LineItem, BBox], tuple[_LineItem, BBox]]]:
+ """用同视觉行的窄左片段和右侧正文识别脚注编号锚点。"""
+
+ by_visual_row: dict[int, list[tuple[_LineItem, BBox]]] = {}
+ for item in line_geometry:
+ line = item[0]
+ if line.visual_row_id is None or not line.split_from_row:
+ continue
+ by_visual_row.setdefault(line.visual_row_id, []).append(item)
+
+ marker_rows: list[tuple[tuple[_LineItem, BBox], tuple[_LineItem, BBox]]] = []
+ marker_width_limit = max(1.5 * median_glyph_width, 0.75 * median_height)
+ for members in by_visual_row.values():
+ ordered = sorted(members, key=lambda item: item[1][0])
+ if len(ordered) < 2:
+ continue
+ marker, body = ordered[0], ordered[1]
+ marker_width = marker[1][2] - marker[1][0]
+ body_width = body[1][2] - body[1][0]
+ horizontal_gap = body[1][0] - marker[1][2]
+ if (
+ marker_width > marker_width_limit
+ or marker[1][0] - base_left > 0.5 * median_height
+ or not 0.0 <= horizontal_gap <= 1.5 * median_height
+ or body[1][0] - base_left < max(1.5 * marker_width, 0.75 * median_height)
+ or body_width < max(4.0 * marker_width, 4.0 * median_glyph_width)
+ or abs(_bbox_center_y(marker[1]) - _bbox_center_y(body[1]))
+ > 0.4 * median_height
+ ):
+ continue
+ marker_rows.append((marker, body))
+ marker_rows.sort(key=lambda pair: (min(pair[0][1][1], pair[1][1][1]), pair[0][1][0]))
+ return marker_rows
+
+
+def _split_marked_page_footnote_entries(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ marker_rows: list[tuple[tuple[_LineItem, BBox], tuple[_LineItem, BBox]]],
+ median_height: float,
+ median_glyph_width: float,
+ base_left: float,
+ maximum_row_width: float,
+ indent_threshold: float,
+) -> list[list[_LineItem]]:
+ """把编号、右侧首行和对齐续行聚合,并保留编号区之前的独立脚注。"""
+
+ first_marker_top = min(marker_rows[0][0][1][1], marker_rows[0][1][1][1])
+ prefix_geometry = [item for item in line_geometry if item[1][1] < first_marker_top]
+ entries = _split_unmarked_page_footnote_entries(
+ prefix_geometry,
+ base_left,
+ maximum_row_width,
+ indent_threshold,
+ )
+ consumed = {
+ line.source_index
+ for entry in entries
+ for line in entry
+ }
+ continuation_tolerance = max(0.75 * median_height, 2.0 * median_glyph_width)
+ for marker_index, (marker, body) in enumerate(marker_rows):
+ next_marker_top = (
+ min(marker_rows[marker_index + 1][0][1][1], marker_rows[marker_index + 1][1][1][1])
+ if marker_index + 1 < len(marker_rows)
+ else float("inf")
+ )
+ entry_items = [marker, body]
+ consumed.update((marker[0].source_index, body[0].source_index))
+ previous = body
+ for candidate in line_geometry:
+ if candidate[0].source_index in consumed:
+ continue
+ if candidate[1][1] < body[1][1] or candidate[1][1] >= next_marker_top:
+ continue
+ if abs(candidate[1][0] - body[1][0]) > continuation_tolerance:
+ continue
+ if _effective_text_row_gap(previous, candidate) > 1.5 * median_height:
+ continue
+ entry_items.append(candidate)
+ consumed.add(candidate[0].source_index)
+ previous = candidate
+ entry_items.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ entries.append([line for line, _bbox in entry_items])
+
+ leftovers = [
+ item
+ for item in line_geometry
+ if item[0].source_index not in consumed
+ ]
+ entries.extend(
+ _split_unmarked_page_footnote_entries(
+ leftovers,
+ base_left,
+ maximum_row_width,
+ indent_threshold,
+ )
+ )
+ entries.sort(
+ key=lambda entry: min(
+ bbox[1]
+ for line in entry
+ for candidate, bbox in line_geometry
+ if candidate.source_index == line.source_index
+ )
+ )
+ return entries
+
+
+def _split_unmarked_page_footnote_entries(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ base_left: float,
+ maximum_row_width: float,
+ indent_threshold: float,
+) -> list[list[_LineItem]]:
+ """沿用首行和续行缩进模式切分没有稳定编号锚点的脚注行。"""
+
+ if not line_geometry:
+ return []
first_line_is_indented = line_geometry[0][1][0] - base_left > indent_threshold
entries: list[list[_LineItem]] = [[line_geometry[0][0]]]
@@ -407,6 +567,140 @@ def _tight_page_footnote_bboxes(
return output
+def _infer_local_text_lane_map(lane: _TextLane) -> dict[int, _TextLane]:
+ """从连续同左缘正文推导局部栏宽,修正跨栏上文污染的全宽栏带。"""
+
+ if lane.is_span or len(lane.lines) < 3:
+ return {}
+ rows = sorted(
+ lane.lines,
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ median_height = statistics.median(
+ _line_effective_height(line, bbox) for line, bbox in rows
+ )
+ left_tolerance = max(3.0, 0.75 * median_height)
+ height_ratio_limit = 1.25
+ runs: list[list[tuple[_LineItem, BBox]]] = []
+ current_run: list[tuple[_LineItem, BBox]] = []
+
+ def submit_run() -> None:
+ """提交当前连续正文行,语义行和明显左缘变化都会结束该局部区段。"""
+
+ nonlocal current_run
+ if current_run:
+ runs.append(current_run)
+ current_run = []
+
+ for item in rows:
+ line, bbox = item
+ if line.semantic_type is not None:
+ submit_run()
+ continue
+ if not current_run:
+ current_run = [item]
+ continue
+ run_left = statistics.median(member[1][0] for member in current_run)
+ run_heights = [
+ _line_effective_height(member, member_bbox)
+ for member, member_bbox in current_run
+ ]
+ current_height = _line_effective_height(line, bbox)
+ if (
+ abs(bbox[0] - run_left) <= left_tolerance
+ and max([*run_heights, current_height])
+ / max(0.1, min([*run_heights, current_height]))
+ <= height_ratio_limit
+ ):
+ current_run.append(item)
+ else:
+ submit_run()
+ current_run = [item]
+ submit_run()
+
+ global_width = max(0.1, lane.right - lane.left)
+ local_by_source: dict[int, _TextLane] = {}
+ for run in runs:
+ if len(run) < 3:
+ continue
+ local_left = statistics.median(bbox[0] for _line, bbox in run)
+ local_right = max(bbox[2] for _line, bbox in run)
+ local_width = max(0.1, local_right - local_left)
+ wide_support = sum(
+ bbox[2] - bbox[0] >= 0.7 * local_width
+ for _line, bbox in run
+ )
+ if global_width < 1.4 * local_width or wide_support < 3:
+ continue
+ local_lane = _TextLane(
+ left=local_left,
+ right=local_right,
+ lines=run,
+ is_span=False,
+ )
+ for line, _bbox in run:
+ local_by_source[line.source_index] = local_lane
+ return local_by_source
+
+
+def _structured_text_break_sources(
+ lane: _TextLane,
+ regular_gap: float,
+ gap_mad: float,
+) -> set[int]:
+ """用重复强调首行和前行右侧留白确认结构化正文的新段起点。"""
+
+ rows = sorted(
+ lane.lines,
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ lane_width = max(0.1, lane.right - lane.left)
+ break_sources: set[int] = set()
+ regions: list[list[tuple[_LineItem, BBox]]] = []
+ for row in rows:
+ if row[0].semantic_type is not None:
+ if regions and regions[-1]:
+ regions.append([])
+ continue
+ if not regions:
+ regions.append([])
+ regions[-1].append(row)
+
+ for region in regions:
+ candidates: list[int] = []
+ for index, (line, bbox) in enumerate(region):
+ height = _line_effective_height(line, bbox)
+ line_width = bbox[2] - bbox[0]
+ if (
+ line.leading_emphasis_width is not None
+ and line.leading_emphasis_width <= 0.2 * lane_width
+ and line_width >= 0.95 * lane_width
+ and abs(bbox[0] - lane.left) <= 0.75 * height
+ ):
+ candidates.append(index)
+ if len(candidates) < 3:
+ continue
+ for index in candidates:
+ if index == 0:
+ continue
+ previous = region[index - 1]
+ current = region[index]
+ pair_height = max(
+ _line_effective_height(*previous),
+ _line_effective_height(*current),
+ )
+ previous_fill = (previous[1][2] - lane.left) / lane_width
+ vertical_gap = _effective_text_row_gap(previous, current)
+ if (
+ previous_fill <= 0.8
+ and -0.25 * pair_height
+ <= vertical_gap
+ <= regular_gap + max(0.75 * pair_height, 3.0 * gap_mad)
+ ):
+ break_sources.add(current[0].source_index)
+ return break_sources
+
+
def _build_text_blocks(
lines: list[_LineItem],
table_bboxes: list[BBox],
@@ -443,6 +737,12 @@ def _build_text_blocks(
if not lane.lines:
continue
regular_gap, gap_mad = _estimate_lane_gap(lane)
+ local_lane_by_source = _infer_local_text_lane_map(lane)
+ structured_break_sources = _structured_text_break_sources(
+ lane,
+ regular_gap,
+ gap_mad,
+ )
hanging_indent_groups = _build_hanging_indent_group_map(
lane,
table_bboxes,
@@ -467,7 +767,21 @@ def _build_text_blocks(
else:
previous_group = hanging_indent_groups.get(previous[0].source_index)
current_group = hanging_indent_groups.get(current[0].source_index)
- if _starts_structural_reference_entry(previous, current):
+ previous_local_lane = local_lane_by_source.get(
+ previous[0].source_index
+ )
+ current_local_lane = local_lane_by_source.get(
+ current[0].source_index
+ )
+ connection_lane = (
+ current_local_lane
+ if current_local_lane is not None
+ and previous_local_lane is current_local_lane
+ else lane
+ )
+ if current[0].source_index in structured_break_sources:
+ should_connect = False
+ elif _starts_structural_reference_entry(previous, current):
# 编号只确认已经由悬挂缩进几何形成的新条目,不能单独扩张范围。
should_connect = False
elif is_hyphen_at_line_end(previous[0].text):
@@ -475,7 +789,7 @@ def _build_text_blocks(
should_connect = _should_connect_text_rows(
previous,
current,
- lane,
+ connection_lane,
regular_gap,
gap_mad,
table_bboxes,
@@ -487,7 +801,7 @@ def _build_text_blocks(
should_connect = _should_connect_text_rows(
previous,
current,
- lane,
+ connection_lane,
regular_gap,
gap_mad,
table_bboxes,
@@ -502,6 +816,14 @@ def _build_text_blocks(
for component_geometry in components:
component_lines = [item[0] for item in component_geometry]
+ component_local_lane = local_lane_by_source.get(
+ component_lines[0].source_index
+ )
+ if component_local_lane is None or not all(
+ local_lane_by_source.get(line.source_index) is component_local_lane
+ for line in component_lines
+ ):
+ component_local_lane = lane
if component_lines[0].semantic_type == "doc_title":
# 文档标题保留自然换行,避免混排标题因语言检测在中文折行处插入空格。
content = "\n".join(
@@ -544,8 +866,11 @@ def _build_text_blocks(
if line.font_signature is not None
and line.font_coverage >= 0.5
},
- "_lane_interval": (lane.left, lane.right),
- "_lane_is_span": lane.is_span,
+ "_lane_interval": (
+ component_local_lane.left,
+ component_local_lane.right,
+ ),
+ "_lane_is_span": component_local_lane.is_span,
}
)
return _merge_spatial_text_components(blocks, page_size)
@@ -654,6 +979,67 @@ def _caption_seed_matches_image(
)
+def _caption_body_has_structural_gap(
+ seed: dict[str, Any],
+ candidate: dict[str, Any],
+) -> bool:
+ """用图注末行、候选首行和图注内部行距阻止跨排版层级回并。"""
+
+ seed_bboxes = seed.get("_local_line_bboxes")
+ seed_heights = seed.get("_line_heights")
+ candidate_bboxes = candidate.get("_local_line_bboxes")
+ candidate_heights = candidate.get("_line_heights")
+ if not (
+ isinstance(seed_bboxes, list)
+ and isinstance(seed_heights, list)
+ and len(seed_bboxes) == len(seed_heights)
+ and seed_bboxes
+ and isinstance(candidate_bboxes, list)
+ and isinstance(candidate_heights, list)
+ and len(candidate_bboxes) == len(candidate_heights)
+ and candidate_bboxes
+ ):
+ return False
+
+ seed_rows = sorted(
+ zip(seed_bboxes, seed_heights, strict=True),
+ key=lambda item: (item[0][1], item[0][0]),
+ )
+ candidate_rows = sorted(
+ zip(candidate_bboxes, candidate_heights, strict=True),
+ key=lambda item: (item[0][1], item[0][0]),
+ )
+ previous_bbox, previous_height = seed_rows[-1]
+ current_bbox, current_height = candidate_rows[0]
+ internal_gaps = [
+ max(0.0, current[0][1] - (previous[0][1] + float(previous[1])))
+ for previous, current in zip(seed_rows, seed_rows[1:])
+ ]
+ regular_gap = statistics.median(internal_gaps) if internal_gaps else 0.0
+ gap_mad = (
+ statistics.median(abs(gap - regular_gap) for gap in internal_gaps)
+ if internal_gaps
+ else 0.0
+ )
+ seed_fonts = seed.get("_font_signatures")
+ candidate_fonts = candidate.get("_font_signatures")
+ reliable_style_change = (
+ isinstance(seed_fonts, set)
+ and bool(seed_fonts)
+ and isinstance(candidate_fonts, set)
+ and bool(candidate_fonts)
+ and seed_fonts.isdisjoint(candidate_fonts)
+ )
+ return _is_structural_typography_gap(
+ float(previous_height),
+ float(current_height),
+ current_bbox[1] - (previous_bbox[1] + float(previous_height)),
+ regular_gap,
+ gap_mad,
+ reliable_style_change=reliable_style_change,
+ )
+
+
def _caption_tail_matches_seed(
seed: dict[str, Any],
candidate: dict[str, Any],
@@ -667,6 +1053,8 @@ def _caption_tail_matches_seed(
candidate_bbox = candidate["bbox"]
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
diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.py
index a029bef1..502c8bc4 100644
--- a/mineru/backend/flash/native_pdf/titles.py
+++ b/mineru/backend/flash/native_pdf/titles.py
@@ -27,6 +27,8 @@ from .geometry import (
from .line_layout import (
_effective_text_row_gap,
_estimate_lane_gap,
+ _font_signatures_share_family,
+ _font_weights_conflict,
_infer_text_lanes,
_line_effective_height,
_should_connect_semantic_rows,
@@ -107,6 +109,7 @@ def _classify_page_titles(
physical_gaps=physical_gaps,
grid_title_suppressions=grid_title_suppressions,
document_body_profile=document_body_profile,
+ page_index=page_index,
)
@@ -577,6 +580,7 @@ def _classify_paragraph_titles_in_lane(
physical_gaps: dict[int, tuple[float | None, float | None]],
grid_title_suppressions: set[int],
document_body_profile: _DocumentBodyProfile | None,
+ page_index: int,
) -> None:
"""以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""
@@ -637,14 +641,20 @@ def _classify_paragraph_titles_in_lane(
and profile.body_font is not None
and line.font_signature is not None
and line.font_coverage >= 0.75
- and line.font_signature != profile.body_font
+ and not _font_signatures_share_family(
+ line.font_signature,
+ profile.body_font,
+ )
)
low_coverage_style_differs = (
not recurrent_regular_font
and profile.body_font is not None
and line.font_signature is not None
and 0.5 <= line.font_coverage < 0.75
- and line.font_signature != profile.body_font
+ and not _font_signatures_share_family(
+ line.font_signature,
+ profile.body_font,
+ )
)
style_support = profile.style_support.get(line.font_signature, 1.0) if line.font_signature is not None else 1.0
weight_emphasized = (
@@ -692,19 +702,20 @@ def _classify_paragraph_titles_in_lane(
profile,
):
continue
+ has_following_body_row = _has_following_body_row(
+ rows,
+ index,
+ lane_width,
+ lane.left,
+ profile,
+ )
compact_local_transition = (
low_coverage_style_differs
and left_aligned
and width_ratio <= 0.65
and gap_above >= 0.1
and gap_below >= 0.2
- and _has_following_body_row(
- rows,
- index,
- lane_width,
- lane.left,
- profile,
- )
+ and has_following_body_row
)
compact_text_section = (
height_ratio < 0.9
@@ -721,13 +732,7 @@ def _classify_paragraph_titles_in_lane(
if (
height_ratio < 0.9
and not inside_front_matter
- and not _has_following_body_row(
- rows,
- index,
- lane_width,
- lane.left,
- profile,
- )
+ and not has_following_body_row
and not compact_text_section
):
continue
@@ -759,17 +764,39 @@ def _classify_paragraph_titles_in_lane(
if left_aligned:
score += 0.25
+ precisely_centered = (
+ abs(
+ _bbox_center_x(bbox)
+ - (lane.left + lane.right) / 2.0
+ )
+ <= 0.05 * lane_width
+ )
+ centered_structural_fallback = (
+ 0.75 <= height_ratio <= 1.15
+ and precisely_centered
+ and width_ratio <= 0.7
+ and not inside_front_matter
+ and not (
+ page_index == 0
+ and _bbox_center_y(bbox) <= 0.2 * local_page_height
+ )
+ and 0.35 <= gap_above <= 1.5
+ and 0.2 <= gap_below <= 1.5
+ and has_following_body_row
+ and not _is_continuous_field_row(
+ rows,
+ index,
+ lane_width,
+ profile,
+ )
+ )
strong_layout_signal = (
height_ratio >= 1.18
or style_differs
or compact_local_transition
or weight_emphasized
- or (
- centered
- and width_ratio <= 0.7
- and gap_above >= 0.35
- and gap_below >= 0.2
- )
+ or centered_structural_fallback
+ or compact_text_section
)
if (
score >= 4.0
@@ -813,7 +840,10 @@ def _line_uses_document_regular_font(
document_body_profile is not None
and line.font_signature is not None
and line.font_coverage >= 0.5
- and line.font_signature in document_body_profile.regular_fonts
+ and any(
+ _font_signatures_share_family(line.font_signature, regular_font)
+ for regular_font in document_body_profile.regular_fonts
+ )
)
@@ -906,16 +936,43 @@ def _continues_local_body_row(
line, bbox = rows[index]
if previous_line.semantic_type is not None:
return False
+ previous_visual_row = (
+ [
+ item
+ for item in rows[:index]
+ if item[0].visual_row_id == previous_line.visual_row_id
+ ]
+ if previous_line.visual_row_id is not None
+ else [rows[index - 1]]
+ )
+ previous_style_members = [
+ member
+ for member, _member_bbox in previous_visual_row
+ if member.font_signature is not None and member.font_coverage >= 0.5
+ ]
if (
- previous_line.font_signature is not None
- and line.font_signature is not None
- and previous_line.font_signature != line.font_signature
+ line.font_signature is not None
+ and previous_style_members
+ and not any(
+ _font_signatures_share_family(member.font_signature, line.font_signature)
+ and not _font_weights_conflict(member, line)
+ for member in previous_style_members
+ )
):
return False
- previous_height = _line_effective_height(previous_line, previous_bbox)
+ previous_bbox = _bbox_union_many(
+ [member_bbox for _member, member_bbox in previous_visual_row]
+ )
+ previous_height = statistics.median(
+ _line_effective_height(member, member_bbox)
+ for member, member_bbox in previous_visual_row
+ )
line_height = _line_effective_height(line, bbox)
pair_height = max(previous_height, line_height)
- gap = _effective_text_row_gap(rows[index - 1], rows[index])
+ gap = _effective_text_row_gap(
+ (previous_line, previous_bbox),
+ rows[index],
+ )
return (
0.8 <= line_height / previous_height <= 1.25
and previous_bbox[2] - previous_bbox[0] >= 0.75 * lane_width
@@ -926,6 +983,38 @@ def _continues_local_body_row(
)
+def _is_continuous_field_row(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+ lane_width: float,
+ profile: _LaneBodyProfile,
+) -> bool:
+ """识别同缩进、同尺度且紧邻的连续字段行,阻止其借居中误差成为标题。"""
+
+ _line, bbox = rows[index]
+ line_height = _line_effective_height(*rows[index])
+ if not 0.85 <= line_height / profile.body_height <= 1.15:
+ return False
+ for neighbor_index in (index - 1, index + 1):
+ if not 0 <= neighbor_index < len(rows):
+ continue
+ neighbor_line, neighbor_bbox = rows[neighbor_index]
+ neighbor_height = _line_effective_height(neighbor_line, neighbor_bbox)
+ if (
+ neighbor_line.semantic_type is None
+ and 0.85 <= neighbor_height / profile.body_height <= 1.15
+ and neighbor_bbox[2] - neighbor_bbox[0] >= 0.35 * lane_width
+ and abs(neighbor_bbox[0] - bbox[0]) <= 0.75 * profile.body_height
+ and max(
+ _effective_text_row_gap(rows[neighbor_index], rows[index]),
+ _effective_text_row_gap(rows[index], rows[neighbor_index]),
+ )
+ <= 1.5 * profile.body_height
+ ):
+ return True
+ return False
+
+
def _is_full_width_inline_heading(
rows: list[tuple[_LineItem, BBox]],
index: int,
@@ -949,7 +1038,10 @@ def _is_full_width_inline_heading(
profile.body_font is None
or next_line.font_signature is None
or next_line.font_coverage < 0.75
- or next_line.font_signature == profile.body_font
+ or _font_signatures_share_family(
+ next_line.font_signature,
+ profile.body_font,
+ )
)
return (
next_line.semantic_type is None
diff --git a/tests/unittest/_flash_pdf_test_utils.py b/tests/unittest/_flash_pdf_test_utils.py
index 4a7514cc..3ca6d10a 100644
--- a/tests/unittest/_flash_pdf_test_utils.py
+++ b/tests/unittest/_flash_pdf_test_utils.py
@@ -21,6 +21,7 @@ def _text_line(
font_coverage: float = 0.0,
dominant_font_weight: float | None = None,
median_glyph_width: float | None = None,
+ leading_emphasis_width: float | None = None,
semantic_type: str | None = None,
) -> models._LineItem:
"""构造栏带、排版恢复与图形标签测试使用的原生文本行。"""
@@ -37,6 +38,7 @@ def _text_line(
font_coverage=font_coverage,
dominant_font_weight=dominant_font_weight,
median_glyph_width=median_glyph_width,
+ leading_emphasis_width=leading_emphasis_width,
split_from_row=split_from_row,
semantic_type=semantic_type,
)
@@ -56,4 +58,3 @@ def _prepared_text_page(
fixed_blocks=[],
)
-
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index 4dc8587c..e7e18594 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -92,6 +92,129 @@ def test_page_footnote_supports_independent_column_rules() -> None:
assert page.page_footnote_groups == [{6, 7}, {8, 9}]
+def test_page_footnote_accepts_lower_half_column_width_rule_with_smaller_text() -> None:
+ """验证页面下半部的栏宽横线可凭字号收缩识别单栏脚注。"""
+
+ lines = [
+ _text_line(
+ f"body {index}",
+ (100.0, 180.0 + 24.0 * index, 900.0, 190.0 + 24.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ]
+ lines.extend(
+ [
+ _text_line(
+ "note one",
+ (100.0, 620.0, 650.0, 628.0),
+ 4,
+ effective_height=8.0,
+ ),
+ _text_line(
+ "note two",
+ (100.0, 632.0, 620.0, 640.0),
+ 5,
+ effective_height=8.0,
+ ),
+ ]
+ )
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.drawing_lines = [
+ models._AxisLine((100.0, 600.0, 900.0, 602.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_page_auxiliary_text(page)
+
+ assert all(line.semantic_type is None for line in lines[:4])
+ assert [line.semantic_type for line in lines[4:]] == [
+ "page_footnote",
+ "page_footnote",
+ ]
+ assert page.page_footnote_groups == [{4, 5}]
+
+
+def test_page_footnote_stops_at_next_aligned_column_rule() -> None:
+ """验证同栏第二条分隔线会把贡献说明和作者单位拆成两个脚注组。"""
+
+ lines = [
+ *[
+ _text_line(
+ f"body {index}",
+ (100.0, 150.0 + 30.0 * index, 500.0, 160.0 + 30.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ],
+ _text_line(
+ "contribution one",
+ (100.0, 590.0, 430.0, 598.0),
+ 4,
+ effective_height=8.0,
+ ),
+ _text_line(
+ "contribution two",
+ (100.0, 602.0, 240.0, 610.0),
+ 5,
+ effective_height=8.0,
+ ),
+ _text_line(
+ "affiliation one",
+ (120.0, 640.0, 460.0, 648.0),
+ 6,
+ effective_height=8.0,
+ ),
+ _text_line(
+ "affiliation two",
+ (120.0, 652.0, 400.0, 660.0),
+ 7,
+ effective_height=8.0,
+ ),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.drawing_lines = [
+ models._AxisLine((100.0, 570.0, 500.0, 572.0), 1.0, "horizontal"),
+ models._AxisLine((100.0, 620.0, 500.0, 622.0), 1.0, "horizontal"),
+ ]
+
+ auxiliary_text._classify_page_auxiliary_text(page)
+
+ assert page.page_footnote_groups == [{4, 5}, {6, 7}]
+ assert all(line.semantic_type == "page_footnote" for line in lines[4:])
+
+
+def test_page_footnote_rejects_column_width_rule_without_size_contraction() -> None:
+ """验证栏宽横线下的正常字号正文不会仅凭下半页位置变成脚注。"""
+
+ lines = [
+ _text_line(
+ f"body {index}",
+ (100.0, 180.0 + 24.0 * index, 900.0, 190.0 + 24.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ]
+ lines.append(
+ _text_line(
+ "continued body",
+ (100.0, 620.0, 700.0, 630.0),
+ 4,
+ effective_height=10.0,
+ )
+ )
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.drawing_lines = [
+ models._AxisLine((100.0, 600.0, 900.0, 602.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_page_auxiliary_text(page)
+
+ assert all(line.semantic_type is None for line in lines)
+
+
def test_page_footnote_unions_aligned_regular_and_span_lanes_only() -> None:
"""验证同左缘 regular/span 栏可联合认领,但不会吞掉右侧正文栏。"""
@@ -372,6 +495,9 @@ def test_auxiliary_text_classifiers_do_not_read_line_text() -> None:
auxiliary_text._classify_aside_text,
auxiliary_text._geometric_text_support_by_angle,
auxiliary_text._classify_page_footnotes,
+ auxiliary_text._augment_footnote_groups_with_edge_markers,
+ auxiliary_text._classify_rule_delimited_headers,
+ auxiliary_text._classify_page_number_outer_companions,
auxiliary_text._rule_belongs_to_confirmed_table,
auxiliary_text._merge_overlapping_source_groups,
auxiliary_text._footnote_lane_members,
@@ -441,6 +567,131 @@ def test_repeated_marginals_require_cross_page_evidence_and_separate_page_number
]
+def test_top_rule_marks_only_unclassified_text_above_it_as_header() -> None:
+ """验证页码先保留类型,长横线上方其余文本补标页眉且线下正文不变。"""
+
+ page_number = _text_line(
+ "7",
+ (900.0, 30.0, 920.0, 40.0),
+ 0,
+ semantic_type="page_number",
+ )
+ journal = _text_line("journal", (100.0, 30.0, 600.0, 40.0), 1)
+ doi = _text_line("doi", (100.0, 44.0, 500.0, 54.0), 2)
+ body = _text_line("body", (100.0, 80.0, 700.0, 90.0), 3)
+ page = _prepared_text_page(
+ page_number,
+ journal,
+ doi,
+ body,
+ page_size=(1000.0, 1000.0),
+ )
+ page.drawing_lines = [
+ models._AxisLine((80.0, 60.0, 920.0, 62.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_rule_delimited_headers([page])
+
+ assert [line.semantic_type for line in page.remaining_lines] == [
+ "page_number",
+ "header",
+ "header",
+ None,
+ ]
+
+
+def test_top_rule_inside_graphic_does_not_mark_header() -> None:
+ """验证图形容器内的页首长横线不会把其上方普通文本误标为页眉。"""
+
+ upper_text = _text_line("upper text", (100.0, 30.0, 600.0, 40.0), 0)
+ body = _text_line("body", (100.0, 80.0, 700.0, 90.0), 1)
+ page = _prepared_text_page(
+ upper_text,
+ body,
+ page_size=(1000.0, 1000.0),
+ )
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (50.0, 50.0, 950.0, 70.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+ page.drawing_lines = [
+ models._AxisLine((80.0, 60.0, 920.0, 62.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_rule_delimited_headers([page])
+
+ assert upper_text.semantic_type is None
+ assert body.semantic_type is None
+
+
+def test_page_number_outer_companions_classify_top_and_bottom_text_and_images() -> None:
+ """验证上下页码外侧的文本和空内容图片对称转换为页眉页脚。"""
+
+ top_page = _prepared_text_page(
+ _text_line("top visual", (20.0, 1.0, 80.0, 5.0), 0),
+ _text_line(
+ "1",
+ (90.0, 8.0, 95.0, 13.0),
+ 1,
+ semantic_type="page_number",
+ ),
+ _text_line("top body", (20.0, 18.0, 80.0, 28.0), 2),
+ )
+ top_page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (40.0, 0.0, 60.0, 5.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+ bottom_page = _prepared_text_page(
+ _text_line("bottom body", (20.0, 70.0, 80.0, 80.0), 0),
+ _text_line(
+ "2",
+ (90.0, 82.0, 95.0, 87.0),
+ 1,
+ semantic_type="page_number",
+ ),
+ _text_line("bottom visual", (20.0, 91.0, 80.0, 96.0), 2),
+ )
+ bottom_page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (40.0, 90.0, 60.0, 99.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+
+ auxiliary_text._classify_page_number_outer_companions(
+ [top_page, bottom_page]
+ )
+
+ assert [line.semantic_type for line in top_page.remaining_lines] == [
+ "header",
+ "page_number",
+ None,
+ ]
+ assert top_page.fixed_blocks[0]["type"] == "header"
+ assert [line.semantic_type for line in bottom_page.remaining_lines] == [
+ None,
+ "page_number",
+ "footer",
+ ]
+ assert bottom_page.fixed_blocks[0]["type"] == "footer"
+
+ blocks = pipeline._finalize_prepared_page(bottom_page, page_index=1)
+ assert any(
+ block["type"] == "footer" and block["content"] == ""
+ for block in blocks
+ )
+
+
def test_page_number_sequence_survives_portrait_to_landscape_edge_change() -> None:
"""验证横竖版切换时连续页码可从底边迁移到侧边,且后续侧边序列继续命中。"""
@@ -478,10 +729,10 @@ def test_single_page_marginal_content_remains_text() -> None:
def test_repeated_visual_headers_use_geometry_and_skip_first_page() -> None:
- """验证三页重复页首图片重标为 header,首页与 content 差异不参与匹配。"""
+ """验证重复页首图片仅按几何重标,空 content 也可保留为 header。"""
pages = [_prepared_text_page(page_size=(100.0, 100.0)) for _ in range(5)]
- contents = ["cover", "alpha", "beta", "gamma", "delta"]
+ contents = ["cover", "", "beta", "", "delta"]
for page, content in zip(pages, contents, strict=True):
page.fixed_blocks = [
{
diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.py
index d1945455..d57d5e66 100644
--- a/tests/unittest/test_flash_pdf_formulas.py
+++ b/tests/unittest/test_flash_pdf_formulas.py
@@ -721,3 +721,102 @@ def test_compact_multiline_cluster_becomes_one_isolated_equation() -> None:
}
]
assert compact_cluster not in remaining
+
+
+def test_justified_mixed_font_visual_row_before_body_is_not_formula_anchor() -> None:
+ """验证粗体短语与常规字体混排的满栏同行不会因右缘短词误判公式。"""
+
+ body_font = ("Body", 0)
+ heading_font = ("Heading", 1)
+ lines = [
+ _text_line(
+ f"body-{index}",
+ (0.0, top, 100.0, top + 10.0),
+ index,
+ visual_row_id=index,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ for index, top in enumerate((0.0, 12.0, 24.0))
+ ]
+ fragments = [
+ _text_line(
+ "label",
+ (0.0, 36.0, 20.0, 46.0),
+ 10,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "one",
+ (24.0, 36.0, 38.0, 46.0),
+ 11,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "two",
+ (43.0, 36.0, 57.0, 46.0),
+ 12,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "three",
+ (63.0, 36.0, 80.0, 46.0),
+ 13,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "contains",
+ (86.0, 36.0, 100.0, 46.0),
+ 14,
+ visual_row_id=10,
+ split_from_row=True,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ ]
+ continuation = _text_line(
+ "continuation body row",
+ (0.0, 46.0, 100.0, 56.0),
+ 15,
+ visual_row_id=11,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+
+ blocks, remaining = formulas._build_formula_like_blocks(
+ [*lines, *fragments, continuation],
+ [],
+ (100.0, 100.0),
+ )
+
+ assert blocks == []
+ assert {line.source_index for line in remaining} == {
+ 0,
+ 1,
+ 2,
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ }
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index a29552ff..321c4361 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -301,6 +301,94 @@ def test_long_rule_group_uses_40pt_or_ten_times_height_threshold(
assert len(tables._group_long_horizontal_rules(accepted_lines, median_height)) == 1
+def test_connected_rule_grid_expands_core_and_reclaims_sparse_bottom_row() -> None:
+ """验证连续物理网格会补全候选底边,并重新认领稀疏末行文本。"""
+
+ bottom_bbox = (10.0, 66.0, 35.0, 72.0)
+ bottom_line = models._LineItem(
+ text="sparse bottom",
+ bbox=bottom_bbox,
+ angle=0,
+ source_index=9,
+ effective_height=6.0,
+ visual_row_id=3,
+ )
+ bottom_row = models._VisualRow(
+ fragments=[
+ models._Fragment(
+ text=bottom_line.text,
+ bbox=bottom_bbox,
+ local_bbox=bottom_bbox,
+ line_index=9,
+ visual_row_id=3,
+ )
+ ],
+ center_y=69.0,
+ bbox=bottom_bbox,
+ visual_row_id=3,
+ )
+ candidate = models._TableCandidate(
+ bbox=(0.0, 8.0, 110.0, 58.1),
+ local_bbox=(0.0, 8.0, 110.0, 58.1),
+ angle=0,
+ score=8.0,
+ core_bbox=(0.0, 8.0, 110.0, 58.1),
+ line_indices=set(range(9)),
+ )
+ axis_lines = [
+ *[
+ _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
+ for top in (8.0, 58.0, 80.0)
+ ],
+ *[
+ _axis_line("vertical", (left, 8.0, left + 0.1, 80.1))
+ for left in (0.0, 55.0, 109.9)
+ ],
+ ]
+
+ expanded = tables._expand_candidates_to_connected_rule_grids(
+ [candidate],
+ [bottom_row],
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ [],
+ )
+
+ assert expanded[0].core_bbox == pytest.approx((0.0, 8.0, 110.0, 80.1))
+ assert expanded[0].bbox == pytest.approx((0.0, 8.0, 110.0, 80.1))
+ assert 9 in expanded[0].line_indices
+
+
+def test_disconnected_stacked_rule_grids_remain_separate() -> None:
+ """验证竖轨未跨越空白间距时,同跨度上下网格仍保持为两张表。"""
+
+ axis_lines = [
+ *[
+ _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
+ for top in (8.0, 58.0, 90.0, 140.0)
+ ],
+ *[
+ _axis_line("vertical", (left, 8.0, left + 0.1, 58.1))
+ for left in (0.0, 55.0, 109.9)
+ ],
+ *[
+ _axis_line("vertical", (left, 90.0, left + 0.1, 140.1))
+ for left in (0.0, 55.0, 109.9)
+ ],
+ ]
+
+ grid_bboxes = tables._connected_rule_grid_bboxes(axis_lines, 5.0)
+
+ assert grid_bboxes == pytest.approx(
+ [
+ (0.0, 8.0, 110.0, 58.1),
+ (0.0, 90.0, 110.0, 140.1),
+ ]
+ )
+
+
def _rule_table_fixture(
rule_count: int = 3,
*,
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index f0c5ff58..dafea0e7 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -8,6 +8,7 @@ from mineru.backend.flash.native_pdf import (
line_merging,
models,
native_text,
+ pipeline,
text_blocks,
)
@@ -155,6 +156,32 @@ def test_first_line_indent_and_large_gap_do_not_form_hanging_indent_groups() ->
assert text_blocks._build_hanging_indent_group_map(lane, [], []) == {}
+def test_hanging_indent_keeps_confirmed_entries_before_plain_trailing_paragraph() -> None:
+ """验证尾随普通左对齐段落不会让此前已确认的悬挂缩进条目整体失效。"""
+
+ lines = [
+ _text_line("entry one", (0.0, 0.0, 100.0, 10.0), 0),
+ _text_line("entry one tail", (15.0, 10.0, 100.0, 20.0), 1),
+ _text_line("entry two", (0.0, 20.0, 100.0, 30.0), 2),
+ _text_line("entry two tail", (15.0, 30.0, 100.0, 40.0), 3),
+ _text_line("entry three", (0.0, 40.0, 100.0, 50.0), 4),
+ _text_line("entry three tail", (15.0, 50.0, 100.0, 60.0), 5),
+ _text_line("plain trailing paragraph", (0.0, 60.0, 100.0, 70.0), 6),
+ _text_line("plain continuation", (0.0, 70.0, 100.0, 80.0), 7),
+ ]
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(line, line.bbox) for line in lines],
+ )
+
+ group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])
+
+ assert [group_map[index] for index in range(6)] == [0, 0, 1, 1, 2, 2]
+ assert 6 not in group_map
+ assert 7 not in group_map
+
+
def test_twelve_point_gutter_keeps_two_text_lanes_and_paragraphs_separate() -> None:
"""验证约 12pt 行高和栏沟仍识别为双栏,左右正文不会交叉拼接。"""
@@ -548,6 +575,84 @@ def test_full_lane_large_height_mismatch_only_recovers_aligned_continuation() ->
)
+def test_pdf_subset_font_variants_keep_full_rows_and_short_tail_connected() -> None:
+ """验证同字体族的 PDF 子集签名差异不会拆断满栏正文及其短尾行。"""
+
+ first = _text_line(
+ "first full row",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ font_signature=("ABCDEF+TimesNewRomanPSMT", 1),
+ font_coverage=1.0,
+ )
+ second = _text_line(
+ "second full row",
+ (0.0, 10.0, 100.0, 20.0),
+ 1,
+ font_signature=("TimesNewRomanPSMT", 29),
+ font_coverage=1.0,
+ )
+ tail = _text_line(
+ "short tail",
+ (0.0, 20.0, 45.0, 30.0),
+ 2,
+ font_signature=("GHIJKL+TimesNewRomanPSMT", 17),
+ font_coverage=1.0,
+ )
+ lane = models._TextLane(left=0.0, right=100.0)
+
+ assert line_layout._should_connect_text_rows(
+ (first, first.bbox),
+ (second, second.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+ assert line_layout._should_connect_text_rows(
+ (second, second.bbox),
+ (tail, tail.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
+def test_pdf_subset_font_short_tail_keeps_significant_weight_barrier() -> None:
+ """验证字体族相同但字重显著变化时,短尾续行仍保持硬分段。"""
+
+ body = _text_line(
+ "full body row",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ font_signature=("ABCDEF+Body", 1),
+ font_coverage=1.0,
+ dominant_font_weight=400.0,
+ )
+ emphasized_tail = _text_line(
+ "bold short row",
+ (0.0, 10.0, 45.0, 20.0),
+ 1,
+ font_signature=("GHIJKL+Body", 29),
+ font_coverage=1.0,
+ dominant_font_weight=700.0,
+ )
+ lane = models._TextLane(left=0.0, right=100.0)
+
+ assert not line_layout._should_connect_text_rows(
+ (body, body.bbox),
+ (emphasized_tail, emphasized_tail.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
def test_smaller_footnote_after_abnormal_gap_forces_text_block_break() -> None:
"""验证字号不足前行 88% 且净空偏大时,正文与脚注强制分块。"""
@@ -841,6 +946,110 @@ def test_local_two_column_band_survives_full_width_body_below() -> None:
assert {f"wide-{index}" for index in range(4)} in lane_texts
+def test_nested_lane_accepts_wider_one_sided_rows_and_expands_interval() -> None:
+ """验证窄图注推断的局部栏仍可接纳未进入另一栏的宽正文行。"""
+
+ lines: list[models._LineItem] = []
+ for row_index, top in enumerate((0.0, 10.0, 20.0, 30.0, 40.0)):
+ lines.extend(
+ [
+ _text_line(
+ f"narrow-left-{row_index}",
+ (10.0, top, 55.0, top + 8.0),
+ row_index * 2,
+ ),
+ _text_line(
+ f"right-{row_index}",
+ (115.0, top, 190.0, top + 8.0),
+ row_index * 2 + 1,
+ ),
+ ]
+ )
+ lines.extend(
+ [
+ _text_line("wide-left-one", (10.0, 32.0, 105.0, 40.0), 20),
+ _text_line("wide-left-two", (10.0, 42.0, 105.0, 50.0), 21),
+ ]
+ )
+ lines.extend(
+ _text_line(
+ f"outer-{row_index}",
+ (10.0, top, 190.0, top + 8.0),
+ 30 + row_index,
+ )
+ for row_index, top in enumerate(
+ (90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0)
+ )
+ )
+
+ lanes = line_layout._infer_text_lanes(
+ [(line, line.bbox) for line in lines],
+ 200.0,
+ 8.0,
+ )
+
+ left_lane = next(
+ lane
+ for lane in lanes
+ if any(line.text == "wide-left-one" for line, _bbox in lane.lines)
+ )
+ assert not left_lane.is_span
+ assert left_lane.right == pytest.approx(105.0)
+ assert {
+ line.text
+ for line, _bbox in left_lane.lines
+ if line.text.startswith("wide-left")
+ } == {"wide-left-one", "wide-left-two"}
+
+
+def test_regular_lanes_accept_wider_one_sided_rows_but_keep_gutter_crossing_span() -> None:
+ """验证普通双栏会扩展单侧栏宽,同时不吸收越过栏沟的通栏行。"""
+
+ lines: list[models._LineItem] = []
+ for row_index, top in enumerate((0.0, 10.0, 20.0, 30.0, 40.0)):
+ lines.extend(
+ [
+ _text_line(
+ f"narrow-left-{row_index}",
+ (10.0, top, 55.0, top + 8.0),
+ row_index * 2,
+ ),
+ _text_line(
+ f"right-{row_index}",
+ (115.0, top, 190.0, top + 8.0),
+ row_index * 2 + 1,
+ ),
+ ]
+ )
+ lines.extend(
+ [
+ _text_line("wide-left-one", (10.0, 52.0, 105.0, 60.0), 20),
+ _text_line("wide-left-two", (10.0, 62.0, 105.0, 70.0), 21),
+ _text_line("crosses-gutter", (10.0, 74.0, 130.0, 82.0), 22),
+ ]
+ )
+
+ lanes = line_layout._infer_text_lanes(
+ [(line, line.bbox) for line in lines],
+ 200.0,
+ 8.0,
+ )
+
+ left_lane = next(
+ lane
+ for lane in lanes
+ if any(line.text == "wide-left-one" for line, _bbox in lane.lines)
+ )
+ span_lane = next(
+ lane
+ for lane in lanes
+ if any(line.text == "crosses-gutter" for line, _bbox in lane.lines)
+ )
+ assert not left_lane.is_span
+ assert left_lane.right == pytest.approx(105.0)
+ assert span_lane.is_span
+
+
def test_short_span_tail_reattaches_before_later_cross_layout_region() -> None:
"""验证局部通栏段的短尾行不会因页面后续另有通栏行而留在单栏。"""
@@ -1376,3 +1585,351 @@ def test_spatial_post_merge_limits_tapered_tail_to_parallel_information_grid() -
"left body",
"left tail",
]
+
+
+def test_repeated_leading_emphasis_and_tail_gap_split_structured_text() -> None:
+ """验证重复行首强调只在前行留白充分时形成结构化正文边界。"""
+
+ lines = [
+ _text_line(
+ "Purpose first section opener",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ leading_emphasis_width=12.0,
+ ),
+ _text_line("purpose tail.", (0.0, 10.0, 78.0, 20.0), 1),
+ _text_line(
+ "Methods second section opener",
+ (0.0, 20.0, 100.0, 30.0),
+ 2,
+ leading_emphasis_width=12.0,
+ ),
+ _text_line("methods tail.", (0.0, 30.0, 60.0, 40.0), 3),
+ _text_line(
+ "Results third section opener",
+ (0.0, 40.0, 100.0, 50.0),
+ 4,
+ leading_emphasis_width=12.0,
+ ),
+ _text_line("results tail.", (0.0, 50.0, 35.0, 60.0), 5),
+ _text_line(
+ "Conclusions fourth section opener",
+ (0.0, 60.0, 100.0, 70.0),
+ 6,
+ leading_emphasis_width=15.0,
+ ),
+ _text_line("conclusions tail.", (0.0, 70.0, 70.0, 80.0), 7),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (100.0, 100.0))
+
+ assert [block["content"] for block in blocks] == [
+ "Purpose first section opener purpose tail.",
+ "Methods second section opener methods tail.",
+ "Results third section opener results tail.",
+ "Conclusions fourth section opener conclusions tail.",
+ ]
+
+
+def test_native_typography_caches_leading_emphasis_before_chars_are_cleared() -> None:
+ """验证字符释放前缓存短粗体前缀宽度,后续文本分块仍可读取。"""
+
+ chars = []
+ for index, char in enumerate("Lead"):
+ chars.append(
+ {
+ "char": char,
+ "bbox": (float(index * 5), 0.0, float(index * 5 + 5), 10.0),
+ "font": {"name": "LeadFont", "flags": 0, "weight": 600},
+ }
+ )
+ for index, char in enumerate("body", start=5):
+ chars.append(
+ {
+ "char": char,
+ "bbox": (float(index * 5), 0.0, float(index * 5 + 5), 10.0),
+ "font": {"name": "BodyFont", "flags": 0, "weight": 400},
+ }
+ )
+ line = models._LineItem(
+ text="Lead body",
+ bbox=(0.0, 0.0, 45.0, 10.0),
+ angle=0,
+ source_index=0,
+ chars=chars,
+ )
+
+ native_text._fill_native_typography(line, (100.0, 100.0))
+ pipeline._compact_prepared_lines([line], (100.0, 100.0))
+
+ assert line.leading_emphasis_width == 20.0
+ assert not line.chars
+
+
+def test_two_leading_emphasis_rows_do_not_activate_structured_text_split() -> None:
+ """验证不足三个重复强调首行时不会把普通混排正文切碎。"""
+
+ lines = [
+ _text_line(
+ "first emphasized opener",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ leading_emphasis_width=15.0,
+ ),
+ _text_line("first short tail", (0.0, 10.0, 60.0, 20.0), 1),
+ _text_line(
+ "second emphasized opener",
+ (0.0, 20.0, 100.0, 30.0),
+ 2,
+ leading_emphasis_width=15.0,
+ ),
+ _text_line("second short tail", (0.0, 30.0, 60.0, 40.0), 3),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (100.0, 100.0))
+
+ assert len(blocks) == 1
+
+
+def test_leading_emphasis_count_does_not_cross_semantic_title_boundary() -> None:
+ """验证不同语义区段的强调首行数量不能合并触发结构化正文模式。"""
+
+ lines = [
+ _text_line("first opener", (0.0, 0.0, 100.0, 10.0), 0, leading_emphasis_width=10.0),
+ _text_line("first tail", (0.0, 10.0, 60.0, 20.0), 1),
+ _text_line("second opener", (0.0, 20.0, 100.0, 30.0), 2, leading_emphasis_width=10.0),
+ _text_line("second tail", (0.0, 30.0, 60.0, 40.0), 3),
+ _text_line(
+ "semantic title",
+ (0.0, 50.0, 40.0, 60.0),
+ 4,
+ semantic_type="paragraph_title",
+ ),
+ _text_line("third opener", (0.0, 70.0, 100.0, 80.0), 5, leading_emphasis_width=10.0),
+ _text_line("third tail", (0.0, 80.0, 60.0, 90.0), 6),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (100.0, 100.0))
+
+ first_region = next(block for block in blocks if "first opener" in block["content"])
+ assert "second opener" in first_region["content"]
+
+
+def test_page_footnote_visual_markers_attach_six_affiliation_entries() -> None:
+ """验证同行窄编号与右侧单位首行、续行分别组成独立脚注条目。"""
+
+ lines = [
+ _text_line("contact name", (10.0, 0.0, 48.0, 10.0), 0, semantic_type="page_footnote"),
+ _text_line("contact email", (10.0, 10.0, 55.0, 20.0), 1, semantic_type="page_footnote"),
+ ]
+ source_index = 2
+ for marker in range(1, 7):
+ top = 20.0 + (marker - 1) * 20.0
+ visual_row_id = 100 + marker
+ lines.extend(
+ [
+ _text_line(
+ str(marker),
+ (0.0, top, 3.0, top + 8.0),
+ source_index,
+ visual_row_id=visual_row_id,
+ run_index=0,
+ split_from_row=True,
+ median_glyph_width=3.0,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ f"affiliation {marker} first row",
+ (10.0, top, 90.0, top + 10.0),
+ source_index + 1,
+ visual_row_id=visual_row_id,
+ run_index=1,
+ split_from_row=True,
+ median_glyph_width=4.0,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ f"affiliation {marker} continuation",
+ (10.0, top + 10.0, 75.0, top + 20.0),
+ source_index + 2,
+ visual_row_id=visual_row_id + 100,
+ median_glyph_width=4.0,
+ semantic_type="page_footnote",
+ ),
+ ]
+ )
+ source_index += 3
+
+ blocks = text_blocks._build_text_blocks(
+ lines,
+ [],
+ (100.0, 160.0),
+ page_footnote_groups=[{line.source_index for line in lines}],
+ )
+
+ assert [block["content"] for block in blocks[:2]] == [
+ "contact name",
+ "contact email",
+ ]
+ assert len(blocks[2:]) == 6
+ for marker, block in enumerate(blocks[2:], start=1):
+ assert block["content"].startswith(f"{marker} affiliation {marker} first row")
+ assert f"affiliation {marker} continuation" in block["content"]
+
+
+def test_local_aligned_column_replaces_polluted_full_width_lane() -> None:
+ """验证跨栏上文不会使后续稳定单栏正文被首行缩进规则拆开。"""
+
+ lines = [
+ _text_line("wide row one", (0.0, 0.0, 200.0, 10.0), 0),
+ _text_line("wide row two", (0.0, 10.0, 200.0, 20.0), 1),
+ _text_line("wide short tail", (0.0, 20.0, 150.0, 30.0), 2),
+ _text_line(
+ "Introduction",
+ (110.0, 40.0, 150.0, 50.0),
+ 3,
+ semantic_type="paragraph_title",
+ ),
+ _text_line("local first sentence.", (110.0, 55.0, 200.0, 65.0), 4),
+ _text_line("local second sentence", (110.0, 65.0, 200.0, 75.0), 5),
+ _text_line("local third sentence", (110.0, 75.0, 200.0, 85.0), 6),
+ _text_line("local final sentence.", (110.0, 85.0, 195.0, 95.0), 7),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (200.0, 120.0))
+ introduction_body = next(
+ block for block in blocks if "local first sentence" in block["content"]
+ )
+
+ assert introduction_body["content"] == (
+ "local first sentence. local second sentence local third sentence "
+ "local final sentence."
+ )
+ assert introduction_body["_lane_interval"] == (110.0, 200.0)
+
+
+def test_typographic_gap_splits_caption_body_without_image_geometry() -> None:
+ """验证异常净空与行高层级变化可独立于图片位置形成段落硬边界。"""
+
+ caption = _text_line(
+ "caption ends without punctuation",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ effective_height=10.0,
+ font_signature=("Body", 0),
+ font_coverage=1.0,
+ )
+ body = _text_line(
+ "body starts",
+ (0.0, 19.0, 100.0, 30.5),
+ 1,
+ effective_height=11.5,
+ font_signature=("Body", 0),
+ font_coverage=1.0,
+ )
+ lane = models._TextLane(left=0.0, right=100.0)
+
+ assert not line_layout._should_connect_text_rows(
+ (caption, caption.bbox),
+ (body, body.bbox),
+ lane,
+ regular_gap=0.0,
+ gap_mad=0.0,
+ table_bboxes=[],
+ axis_lines=[],
+ )
+
+
+def test_typographic_gap_requires_both_spacing_and_typography_evidence() -> None:
+ """验证单独字号变化或单独中等净空都不会触发新增段落屏障。"""
+
+ base = _text_line("base", (0.0, 0.0, 100.0, 10.0), 0, effective_height=10.0)
+ larger_nearby = _text_line(
+ "larger nearby",
+ (0.0, 10.0, 100.0, 21.5),
+ 1,
+ effective_height=11.5,
+ )
+ same_size_spaced = _text_line(
+ "same size spaced",
+ (0.0, 18.0, 100.0, 28.0),
+ 2,
+ effective_height=10.0,
+ )
+ lane = models._TextLane(left=0.0, right=100.0)
+
+ assert line_layout._should_connect_text_rows(
+ (base, base.bbox),
+ (larger_nearby, larger_nearby.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+ assert line_layout._should_connect_text_rows(
+ (base, base.bbox),
+ (same_size_spaced, same_size_spaced.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
+def test_hyphenated_row_bypasses_typographic_gap_barrier() -> None:
+ """验证排版断词仍可在现有近距离上限内跨过字号和净空变化。"""
+
+ previous = _text_line("hyphen-", (0.0, 0.0, 100.0, 10.0), 0, effective_height=10.0)
+ current = _text_line("ated", (0.0, 19.0, 100.0, 30.5), 1, effective_height=11.5)
+ lane = models._TextLane(left=0.0, right=100.0)
+
+ assert line_layout._should_connect_text_rows(
+ (previous, previous.bbox),
+ (current, current.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
+def test_caption_post_merge_respects_typographic_gap_barrier() -> None:
+ """验证图片邻接后处理不能跨过已确认的图注正文排版边界。"""
+
+ common = {
+ "type": "text",
+ "angle": 0,
+ "_single_run_row_id": None,
+ "_lane_interval": (0.0, 100.0),
+ "_lane_is_span": False,
+ "_font_signatures": {("Body", 0)},
+ }
+ caption = {
+ **common,
+ "bbox": (0.0, 50.0, 100.0, 60.0),
+ "content": "Fig. 1 caption",
+ "_visual_row_ids": {1},
+ "_local_line_bboxes": [(0.0, 50.0, 100.0, 60.0)],
+ "_line_heights": [10.0],
+ }
+ body = {
+ **common,
+ "bbox": (0.0, 69.0, 100.0, 80.5),
+ "content": "body starts",
+ "_visual_row_ids": {2},
+ "_local_line_bboxes": [(0.0, 69.0, 100.0, 80.5)],
+ "_line_heights": [11.5],
+ }
+
+ merged = text_blocks._merge_image_caption_text_blocks(
+ [caption, body],
+ [(0.0, 10.0, 100.0, 50.0)],
+ )
+
+ assert [block["content"] for block in merged] == [
+ "Fig. 1 caption",
+ "body starts",
+ ]
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index fade9955..8475fc31 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -420,6 +420,103 @@ def test_same_font_body_tail_with_moderate_gap_is_not_title() -> None:
assert lines[3].semantic_type is None
+def test_subset_font_visual_row_continues_into_short_body_tail() -> None:
+ """验证同一满行的拆分片段归一化子集字体后,短尾仍优先判为正文续行。"""
+
+ first = _text_line(
+ "prefix",
+ (0.0, 0.0, 12.0, 10.0),
+ 0,
+ visual_row_id=10,
+ split_from_row=True,
+ font_signature=("SimSun", 0),
+ font_coverage=1.0,
+ )
+ second = _text_line(
+ "full row remainder",
+ (15.0, 0.0, 100.0, 10.0),
+ 1,
+ visual_row_id=10,
+ split_from_row=True,
+ font_signature=("ABCDEF+SimSun", 0),
+ font_coverage=1.0,
+ )
+ tail = _text_line(
+ "short tail",
+ (0.0, 12.0, 35.0, 22.0),
+ 2,
+ font_signature=("UVWXYZ+SimSun", 0),
+ font_coverage=1.0,
+ )
+ rows = [(line, line.bbox) for line in (first, second, tail)]
+ profile = titles._LaneBodyProfile(
+ body_height=10.0,
+ body_font=("ABCDEF+SimSun", 0),
+ body_weight=400.0,
+ regular_gap=2.0,
+ style_support={},
+ )
+
+ assert titles._continues_local_body_row(rows, 2, 100.0, profile)
+
+
+def test_normal_body_font_needs_precise_centering_for_layout_title_fallback() -> None:
+ """验证普通正文样式只有精确居中且紧邻正文时才能使用版式标题兜底。"""
+
+ body_font = ("Body", 0)
+ imprecise_lines = [
+ _text_line("body one", (0.0, 0.0, 100.0, 10.0), 0, font_signature=body_font, font_coverage=1.0),
+ _text_line("body two", (0.0, 12.0, 100.0, 22.0), 1, font_signature=body_font, font_coverage=1.0),
+ _text_line("imprecise label", (20.0, 35.0, 65.0, 45.0), 2, font_signature=body_font, font_coverage=1.0),
+ _text_line("body three", (0.0, 58.0, 100.0, 68.0), 3, font_signature=body_font, font_coverage=1.0),
+ _text_line("body four", (0.0, 70.0, 100.0, 80.0), 4, font_signature=body_font, font_coverage=1.0),
+ ]
+ precise_lines = [
+ _text_line("body one", (0.0, 0.0, 100.0, 10.0), 10, font_signature=body_font, font_coverage=1.0),
+ _text_line("body two", (0.0, 12.0, 100.0, 22.0), 11, font_signature=body_font, font_coverage=1.0),
+ _text_line("precise label", (30.0, 35.0, 70.0, 45.0), 12, font_signature=body_font, font_coverage=1.0),
+ _text_line("body three", (0.0, 58.0, 100.0, 68.0), 13, font_signature=body_font, font_coverage=1.0),
+ _text_line("body four", (0.0, 70.0, 100.0, 80.0), 14, font_signature=body_font, font_coverage=1.0),
+ ]
+
+ titles._classify_page_titles(
+ imprecise_lines,
+ (100.0, 120.0),
+ page_index=1,
+ container_bboxes=[],
+ )
+ titles._classify_page_titles(
+ precise_lines,
+ (100.0, 120.0),
+ page_index=1,
+ container_bboxes=[],
+ )
+
+ assert imprecise_lines[2].semantic_type is None
+ assert precise_lines[2].semantic_type == "paragraph_title"
+
+
+def test_first_page_centered_body_style_metadata_does_not_use_title_fallback() -> None:
+ """验证首页上部普通字号居中元数据不会仅凭留白升级为段落标题。"""
+
+ body_font = ("Body", 0)
+ lines = [
+ _text_line("metadata", (30.0, 20.0, 70.0, 30.0), 0, font_signature=body_font, font_coverage=1.0),
+ _text_line("body one", (0.0, 43.0, 100.0, 53.0), 1, font_signature=body_font, font_coverage=1.0),
+ _text_line("body two", (0.0, 55.0, 100.0, 65.0), 2, font_signature=body_font, font_coverage=1.0),
+ _text_line("body three", (0.0, 67.0, 100.0, 77.0), 3, font_signature=body_font, font_coverage=1.0),
+ ]
+
+ titles._classify_page_titles(
+ lines,
+ (100.0, 150.0),
+ page_index=0,
+ container_bboxes=[],
+ )
+
+ assert lines[0].semantic_type is None
+
+
def test_cross_column_document_title_uses_thirteen_tenths_body_height_fallback() -> None:
"""验证首页跨栏居中标题达到正文 1.30 倍时可命中,作者行保持正文类型。"""
@@ -775,6 +872,7 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
titles._visual_row_has_body_style_sibling,
titles._is_near_full_mixed_inline_row,
titles._continues_local_body_row,
+ titles._is_continuous_field_row,
titles._is_full_width_inline_heading,
titles._has_following_body_row,
titles._has_following_compact_text_section,