Skip to content

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

fix: enhance document title classification and improve handling of ink bounding boxes

myhloli87f7f37afdf2
diff --git a/mineru/model/flash/pdf/auxiliary_text.py b/mineru/model/flash/pdf/auxiliary_text.py
index 8694be2a..96a59949 100644
--- a/mineru/model/flash/pdf/auxiliary_text.py
+++ b/mineru/model/flash/pdf/auxiliary_text.py
@@ -723,7 +723,7 @@ def _classify_rule_delimited_headers(pages: list[_PreparedPage]) -> None:
(
line,
_rotate_bbox_to_upright(
- line.bbox,
+ line.ink_bbox or line.bbox,
page.page_size,
dominant_angle,
),
diff --git a/mineru/model/flash/pdf/char_geometry.py b/mineru/model/flash/pdf/char_geometry.py
index e780f929..fb5f4c80 100644
--- a/mineru/model/flash/pdf/char_geometry.py
+++ b/mineru/model/flash/pdf/char_geometry.py
@@ -103,6 +103,8 @@ class DocumentGeometryPlan:
char_repairs: dict[CharKey, CharLayoutGeometry] = field(default_factory=dict)
line_repairs: dict[LineKey, LineGeometryRepair] = field(default_factory=dict)
line_style_scales: dict[LineKey, float] = field(default_factory=dict)
+ line_ink_bboxes: dict[LineKey, BBox] = field(default_factory=dict)
+ line_baselines: dict[LineKey, float] = field(default_factory=dict)
style_inflated_runs: set[RunKey] = field(default_factory=set)
run_diagnostics: list[dict[str, Any]] = field(default_factory=list)
document_style_anomaly: bool = False
@@ -905,6 +907,37 @@ def _baseline_clusters(samples: list[_CharSample]) -> tuple[list[list[_CharSampl
return clusters, tolerance
+def _record_line_canonical_metrics(
+ plan: DocumentGeometryPlan,
+ by_line: dict[LineKey, list[_CharSample]],
+) -> None:
+ """为无需改写 bbox 的普通行保存 tight 字形并集和 dominant origin 基线。"""
+
+ for line_key, line_samples in by_line.items():
+ if not line_samples:
+ continue
+ line = line_samples[0].line
+ plan.line_ink_bboxes[line_key] = _bbox_union_many(
+ [sample.tight_bbox for sample in line_samples],
+ )
+ if line.formula_candidate_only or line.compact_formula_cluster:
+ continue
+ anchors = [sample for sample in line_samples if sample.is_anchor]
+ if len(anchors) < 2:
+ continue
+ clusters, _tolerance = _baseline_clusters(anchors)
+ dominant = max(
+ clusters,
+ key=lambda cluster: (
+ sum(sample.local_tight_bbox[2] - sample.local_tight_bbox[0] for sample in cluster),
+ len(cluster),
+ ),
+ )
+ if len(dominant) / len(anchors) < 0.5:
+ continue
+ plan.line_baselines[line_key] = statistics.median(sample.local_origin[1] for sample in dominant)
+
+
def _analyze_lines(
lines_by_page: list[list[_LineItem]],
by_line: dict[LineKey, list[_CharSample]],
@@ -1324,6 +1357,7 @@ def build_document_geometry_plan(
geometry.loose_bboxes.clear()
return plan
samples, by_line = _collect_samples(lines_by_page, geometries, page_sizes)
+ _record_line_canonical_metrics(plan, by_line)
runs = _build_run_stats(samples, by_line)
style_inflated_runs = _mark_style_inflated_runs(runs)
plan.style_inflated_runs = style_inflated_runs
@@ -1365,6 +1399,16 @@ def apply_line_geometry_repairs(
"""把文档计划应用到当前仍可参与 Flash 布局的行。"""
for line in lines:
+ canonical_ink_bbox = plan.line_ink_bboxes.get(
+ (page_index, line.source_index),
+ )
+ if canonical_ink_bbox is not None:
+ line.ink_bbox = canonical_ink_bbox
+ canonical_baseline = plan.line_baselines.get(
+ (page_index, line.source_index),
+ )
+ if canonical_baseline is not None:
+ line.baseline = canonical_baseline
style_scale = plan.line_style_scales.get(
(page_index, line.source_index),
)
@@ -1388,7 +1432,8 @@ def apply_line_geometry_repairs(
layout = repair.layout_bbox
line.source_bbox = repair.source_bbox
line.ink_bbox = repair.ink_bbox
- line.baseline = repair.baseline
+ if repair.baseline is not None:
+ line.baseline = repair.baseline
line.geometry_state = local_state
line.geometry_confidence = repair.confidence
line.split_y_candidate = repair.split_y_candidate
diff --git a/mineru/model/flash/pdf/formulas.py b/mineru/model/flash/pdf/formulas.py
index 32d679bd..66a41d5f 100644
--- a/mineru/model/flash/pdf/formulas.py
+++ b/mineru/model/flash/pdf/formulas.py
@@ -547,8 +547,16 @@ def _build_formula_like_blocks(
median_height,
):
continue
+ members = _expand_single_line_numbered_formula_members(
+ (line, bbox),
+ lane,
+ claimed_source_indices,
+ table_bboxes,
+ dominant_body_font,
+ median_height,
+ )
block = _formula_members_to_block(
- [(line, bbox)],
+ members,
page_size,
angle,
anchor_source_index=line.source_index,
@@ -556,7 +564,10 @@ def _build_formula_like_blocks(
if block is None:
continue
blocks.append(block)
- claimed_source_indices.add(line.source_index)
+ claimed_source_indices.update(
+ member_line.source_index
+ for member_line, _member_bbox in members
+ )
lane.lines = [
item
for item in lane.lines
@@ -749,6 +760,107 @@ def _is_single_line_numbered_formula(
)
+def _expand_single_line_numbered_formula_members(
+ core: tuple[_LineItem, BBox],
+ lane: _TextLane,
+ claimed_source_indices: set[int],
+ table_bboxes: list[BBox],
+ dominant_body_font: tuple[str, int] | None,
+ median_height: float,
+) -> list[tuple[_LineItem, BBox]]:
+ """为已带编号的公式核心吸收同栏连通的等号前缀和窄分式碎片。"""
+
+ core_line, core_bbox = core
+ lane_width = max(0.1, lane.right - lane.left)
+ candidates = []
+ for candidate_line, candidate_bbox in lane.lines:
+ if (
+ candidate_line.source_index == core_line.source_index
+ or candidate_line.source_index in claimed_source_indices
+ or candidate_bbox[2] - candidate_bbox[0] > 0.35 * lane_width
+ or _is_formula_body_barrier(
+ (candidate_line, candidate_bbox),
+ lane,
+ dominant_body_font,
+ median_height,
+ )
+ or _is_formula_title_barrier(
+ (candidate_line, candidate_bbox),
+ lane,
+ dominant_body_font,
+ median_height,
+ )
+ ):
+ continue
+ narrow_fragment = (
+ candidate_bbox[2] - candidate_bbox[0] <= 1.5 * median_height
+ and core_bbox[0] - median_height <= _bbox_center_x(candidate_bbox) <= core_bbox[2] + median_height
+ )
+ if not (
+ _formula_line_has_math_operator(candidate_line.text)
+ or candidate_line.compact_formula_cluster
+ or candidate_line.formula_candidate_only
+ or narrow_fragment
+ ):
+ continue
+ if not _formula_lines_are_connected(
+ core_line,
+ core_bbox,
+ candidate_line,
+ candidate_bbox,
+ table_bboxes,
+ ):
+ continue
+ candidates.append(
+ (candidate_line, candidate_bbox),
+ )
+
+ members = [core, *candidates]
+ member_sources = {line.source_index for line, _bbox in members}
+ changed = True
+ while changed:
+ changed = False
+ for candidate in lane.lines:
+ candidate_line, candidate_bbox = candidate
+ if (
+ candidate_line.source_index in member_sources
+ or candidate_line.source_index in claimed_source_indices
+ or candidate_bbox[2] - candidate_bbox[0] > 0.35 * lane_width
+ or _is_formula_body_barrier(
+ candidate,
+ lane,
+ dominant_body_font,
+ median_height,
+ )
+ or _is_formula_title_barrier(
+ candidate,
+ lane,
+ dominant_body_font,
+ median_height,
+ )
+ ):
+ continue
+ if any(
+ _formula_lines_are_connected(
+ member_line,
+ member_bbox,
+ candidate_line,
+ candidate_bbox,
+ table_bboxes,
+ )
+ for member_line, member_bbox in members
+ ) and (
+ _formula_line_has_math_operator(candidate_line.text)
+ or candidate_line.compact_formula_cluster
+ or candidate_line.formula_candidate_only
+ or candidate_bbox[2] - candidate_bbox[0] <= 1.5 * median_height
+ ):
+ members.append(candidate)
+ member_sources.add(candidate_line.source_index)
+ changed = True
+ return members
+
+
def _build_split_visual_row_formula_blocks(
lines: list[_LineItem],
table_bboxes: list[BBox],
diff --git a/mineru/model/flash/pdf/line_layout.py b/mineru/model/flash/pdf/line_layout.py
index a9e5852a..83da7ac7 100644
--- a/mineru/model/flash/pdf/line_layout.py
+++ b/mineru/model/flash/pdf/line_layout.py
@@ -196,6 +196,35 @@ def _effective_text_row_gap(
)
+def _effective_body_text_row_gap(
+ previous: tuple[_LineItem, BBox],
+ current: tuple[_LineItem, BBox],
+) -> float:
+ """正文连接优先使用 origin 基线节奏,缺证据时回退既有 bbox 净空。"""
+
+ previous_line, previous_bbox = previous
+ current_line, _current_bbox = current
+ if (
+ previous_line.baseline is not None
+ and current_line.baseline is not None
+ and current_line.baseline > previous_line.baseline
+ ):
+ previous_scale = _line_effective_height(previous_line, previous_bbox)
+ current_scale = _line_effective_height(*current)
+ pitch = current_line.baseline - previous_line.baseline
+ if (
+ 0.5 * min(previous_scale, current_scale)
+ <= pitch
+ <= 3.0
+ * max(
+ previous_scale,
+ current_scale,
+ )
+ ):
+ return pitch - previous_scale
+ return _effective_text_row_gap(previous, current)
+
+
def _infer_text_lanes(
line_geometry: list[tuple[_LineItem, BBox]],
local_page_width: float,
@@ -334,6 +363,7 @@ def _infer_text_lanes(
)
)
_reattach_span_lane_continuations(lanes, median_height)
+ _reattach_cross_lane_short_tails(lanes, median_height)
return lanes
lanes = [_TextLane(left=left, right=right) for left, right, _support in filtered_intervals]
@@ -388,6 +418,7 @@ def _infer_text_lanes(
)
)
_reattach_span_lane_continuations(lanes, median_height)
+ _reattach_cross_lane_short_tails(lanes, median_height)
return lanes
@@ -659,6 +690,85 @@ def _reattach_span_lane_continuations(
)
+def _reattach_cross_lane_short_tails(
+ lanes: list[_TextLane],
+ median_height: float,
+) -> None:
+ """把误入另一栏带、但完整落在唯一前序栏内的正文短尾迁回原栏。"""
+
+ while True:
+ moves: list[
+ tuple[
+ float,
+ _TextLane,
+ _TextLane,
+ tuple[_LineItem, BBox],
+ ]
+ ] = []
+ for source_lane in lanes:
+ for candidate in source_lane.lines:
+ candidate_line, candidate_bbox = candidate
+ if candidate_line.semantic_type is not None:
+ continue
+ matches: list[tuple[float, _TextLane]] = []
+ for target_lane in lanes:
+ if target_lane is source_lane or not target_lane.lines:
+ continue
+ preceding = [
+ item
+ for item in target_lane.lines
+ if item[0].semantic_type == candidate_line.semantic_type and item[1][1] < candidate_bbox[1]
+ ]
+ if not preceding:
+ continue
+ previous = max(
+ preceding,
+ key=lambda item: (item[1][1], item[1][0]),
+ )
+ previous_line, previous_bbox = previous
+ pair_height = max(
+ _line_effective_height(*previous),
+ _line_effective_height(*candidate),
+ median_height,
+ )
+ lane_width = max(0.1, target_lane.right - target_lane.left)
+ if (
+ previous_bbox[2] - previous_bbox[0] < 0.65 * lane_width
+ or candidate_bbox[2] - candidate_bbox[0] > 0.85 * lane_width
+ or candidate_bbox[0] < target_lane.left - 0.75 * pair_height
+ or candidate_bbox[2] > target_lane.right + 0.75 * pair_height
+ or abs(candidate_bbox[0] - previous_bbox[0]) > 0.75 * pair_height
+ or not _title_fonts_compatible(previous_line, candidate_line)
+ ):
+ continue
+ gap = _effective_body_text_row_gap(previous, candidate)
+ if not -0.25 * pair_height <= gap <= 0.9 * pair_height:
+ continue
+ if (
+ previous_line.visual_row_id is not None
+ and candidate_line.visual_row_id is not None
+ and not 0 < candidate_line.visual_row_id - previous_line.visual_row_id <= 2
+ ):
+ continue
+ matches.append((max(0.0, gap), target_lane))
+ if len(matches) == 1:
+ gap, target_lane = matches[0]
+ moves.append((candidate_bbox[1] + gap, source_lane, target_lane, candidate))
+ if not moves:
+ return
+ _score, source_lane, target_lane, candidate = min(
+ moves,
+ key=lambda item: item[0],
+ )
+ if candidate not in source_lane.lines:
+ continue
+ source_lane.lines.remove(candidate)
+ target_lane.lines.append(candidate)
+ target_lane.lines.sort(
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+
+
def _reattach_repeated_indented_span_tails(
span_lane: _TextLane,
regular_lanes: list[_TextLane],
@@ -812,7 +922,7 @@ def _should_connect_text_rows(
lane_width = max(0.1, lane.right - lane.left)
previous_width = previous_bbox[2] - previous_bbox[0]
current_width = current_bbox[2] - current_bbox[0]
- vertical_gap = _effective_text_row_gap(previous, current)
+ vertical_gap = _effective_body_text_row_gap(previous, current)
if previous_line.visual_row_id == current_line.visual_row_id and (
previous_line.split_from_row or current_line.split_from_row
):
@@ -846,6 +956,13 @@ def _should_connect_text_rows(
and previous_line.font_signature[1] == current_line.font_signature[1]
)
)
+ previous_indent = previous_bbox[0] - lane.left
+ repeated_indent_continuation = (
+ previous_indent >= max(5.0, 1.8 * pair_height)
+ and abs(current_bbox[0] - previous_bbox[0]) <= 0.5 * pair_height
+ and reliable_font_match
+ and -0.25 * pair_height <= vertical_gap <= regular_gap + max(0.75 * pair_height, 3.0 * gap_mad)
+ )
safe_short_tail = (
previous_width >= 0.75 * lane_width
and current_width <= 0.7 * lane_width
@@ -952,7 +1069,12 @@ def _should_connect_text_rows(
return False
terminal_previous = bool(re.search(r"[.!?。!?::;;][\]\)})】》”’'\"]*$", previous_line.text.rstrip()))
- if terminal_previous and vertical_gap > regular_gap + 0.5 * pair_height:
+ sparse_lane = sum(line.semantic_type is None for line, _bbox in lane.lines) <= 6
+ if (
+ terminal_previous
+ and not repeated_indent_continuation
+ and ((sparse_lane and vertical_gap > 0.65 * pair_height) or vertical_gap > regular_gap + 0.5 * pair_height)
+ ):
return False
# 局部版心可能比整栏推断边界更靠左,缩进需同时参考上一物理行。
@@ -964,6 +1086,7 @@ def _should_connect_text_rows(
next_indent >= max(5.0, 0.65 * pair_height)
and (previous_fill <= 0.8 or terminal_previous)
and not safe_short_tail
+ and not repeated_indent_continuation
):
# 已确认的同左缘短尾优先于栏左缘缩进,避免参考文献冒号后的末行被切断。
return False
diff --git a/mineru/model/flash/pdf/line_merging.py b/mineru/model/flash/pdf/line_merging.py
index 3da89883..d0701c99 100644
--- a/mineru/model/flash/pdf/line_merging.py
+++ b/mineru/model/flash/pdf/line_merging.py
@@ -350,6 +350,17 @@ def _merge_overlapping_inline_cluster(
bbox=_bbox_union_many([line.bbox for line in ordered_members]),
angle=host.angle,
source_index=min(line.source_index for line in ordered_members),
+ source_bbox=_bbox_union_many(
+ [line.source_bbox or line.bbox for line in ordered_members],
+ ),
+ ink_bbox=(
+ _bbox_union_many(
+ [line.ink_bbox for line in ordered_members if line.ink_bbox is not None],
+ )
+ if any(line.ink_bbox is not None for line in ordered_members)
+ else None
+ ),
+ baseline=host.baseline,
chars=[char for line in ordered_members for char in line.chars],
visual_row_id=host.visual_row_id,
run_index=host.run_index,
@@ -625,6 +636,21 @@ def _merge_same_baseline_group(
bbox=_bbox_union_many([member.bbox for member in members]),
angle=members[0].angle,
source_index=min(member.source_index for member in members),
+ source_bbox=_bbox_union_many(
+ [member.source_bbox or member.bbox for member in members],
+ ),
+ ink_bbox=(
+ _bbox_union_many(
+ [member.ink_bbox for member in members if member.ink_bbox is not None],
+ )
+ if any(member.ink_bbox is not None for member in members)
+ else None
+ ),
+ baseline=(
+ statistics.median(member.baseline for member in members if member.baseline is not None)
+ if any(member.baseline is not None for member in members)
+ else None
+ ),
chars=[char for member in members for char in member.chars],
visual_row_id=min(
(member.visual_row_id for member in members if member.visual_row_id is not None),
@@ -977,6 +1003,21 @@ def _merge_dense_split_visual_row(
bbox=_bbox_union_many([member.bbox for member in ordered_members]),
angle=ordered_members[0].angle,
source_index=min(member.source_index for member in ordered_members),
+ source_bbox=_bbox_union_many(
+ [member.source_bbox or member.bbox for member in ordered_members],
+ ),
+ ink_bbox=(
+ _bbox_union_many(
+ [member.ink_bbox for member in ordered_members if member.ink_bbox is not None],
+ )
+ if any(member.ink_bbox is not None for member in ordered_members)
+ else None
+ ),
+ baseline=(
+ statistics.median(member.baseline for member in ordered_members if member.baseline is not None)
+ if any(member.baseline is not None for member in ordered_members)
+ else None
+ ),
chars=[char for member in ordered_members for char in member.chars],
visual_row_id=ordered_members[0].visual_row_id,
run_index=0,
diff --git a/mineru/model/flash/pdf/native_text.py b/mineru/model/flash/pdf/native_text.py
index 006c3528..456ef020 100644
--- a/mineru/model/flash/pdf/native_text.py
+++ b/mineru/model/flash/pdf/native_text.py
@@ -32,6 +32,9 @@ from .geometry import (
_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
_PDF_LINE_END_SOFT_HYPHEN_RE = re.compile(r"(?<=[A-Za-z])[\x02\u00ad](?=[\t ]*(?:\n|$))")
+_INLINE_REFERENCE_MARKER_RE = re.compile(
+ r"^[\[(([]\s*\d{1,4}\s*[\]))]]$",
+)
# Unicode Zs 空格在 model_list 中只承担分词作用,统一成可互操作的 ASCII 空格。
_PDF_SEPARATOR_SPACE_CHARS = "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"
_PDF_UNICODE_TEXT_TRANSLATION = str.maketrans(
@@ -695,6 +698,23 @@ def _is_detached_inline_script_candidate(
)
+def _native_typographic_scale(line: _LineItem) -> float:
+ """返回原生行的字体尺度,禁止 loose 空间高度参与上下标字号比较。"""
+
+ font_sizes: list[float] = []
+ for char in line.chars:
+ try:
+ font_size = float((char.get("font") or {}).get("size") or 0.0)
+ except (TypeError, ValueError):
+ continue
+ if math.isfinite(font_size) and font_size > 0:
+ font_sizes.append(font_size)
+ return max(
+ 0.1,
+ statistics.median(font_sizes) if font_sizes else line.em_height or line.effective_height,
+ )
+
+
def _merge_native_inline_scripts(
lines: list[_LineItem],
page_size: tuple[float, float],
@@ -713,10 +733,22 @@ def _merge_native_inline_scripts(
continue
if small.effective_height <= 0 or base.effective_height <= 0:
continue
- height_ratio = small.effective_height / base.effective_height
+ canonical_small_scale = _native_typographic_scale(small)
+ canonical_base_scale = _native_typographic_scale(base)
+ legacy_small_scale = max(0.1, small.effective_height)
+ legacy_base_scale = max(0.1, base.effective_height)
+ legacy_ratio = legacy_small_scale / legacy_base_scale
+ use_canonical_reference_scale = (
+ _INLINE_REFERENCE_MARKER_RE.fullmatch(compact_text) is not None
+ and not 0.35 <= legacy_ratio <= 0.8
+ and 0.35 <= canonical_small_scale / canonical_base_scale <= 0.8
+ )
+ small_scale = canonical_small_scale if use_canonical_reference_scale else legacy_small_scale
+ base_scale = canonical_base_scale if use_canonical_reference_scale else legacy_base_scale
+ height_ratio = small_scale / base_scale
if not 0.35 <= height_ratio <= 0.8:
continue
- if len(compact_text) > 8 and small_local_bbox[2] - small_local_bbox[0] > 3.0 * base.effective_height:
+ if len(compact_text) > 8 and small_local_bbox[2] - small_local_bbox[0] > 3.0 * base_scale:
continue
base_local_bbox = _rotate_bbox_to_upright(base.bbox, page_size, base.angle)
vertical_overlap = max(
@@ -728,21 +760,21 @@ def _merge_native_inline_scripts(
detached_candidate = overlap_ratio < 0.5 and _is_detached_inline_script_candidate(
small_local_bbox,
base_local_bbox,
- base.effective_height,
+ base_scale,
)
if overlap_ratio < 0.5 and not detached_candidate:
continue
center_offset = abs(_bbox_center_y(small_local_bbox) - _bbox_center_y(base_local_bbox))
- if center_offset < max(0.5, 0.12 * base.effective_height):
+ if center_offset < max(0.5, 0.12 * base_scale):
# 同基线居中的小字号文本更可能是表格相邻 cell,而不是上下标。
continue
- gap_limit = max(1.5, 0.35 * base.effective_height)
+ gap_limit = max(1.5, 0.35 * base_scale)
edge_options: list[tuple[float, Literal["prefix", "suffix"], float]] = []
for position, gap in (
("prefix", base_local_bbox[0] - small_local_bbox[2]),
("suffix", small_local_bbox[0] - base_local_bbox[2]),
):
- if -0.35 * base.effective_height <= gap <= gap_limit:
+ if -0.35 * base_scale <= gap <= gap_limit:
edge_options.append((abs(gap), position, gap))
if not edge_options:
continue
@@ -752,11 +784,11 @@ def _merge_native_inline_scripts(
base_local_bbox[1] - small_local_bbox[1],
small_local_bbox[3] - base_local_bbox[3],
)
- tightly_attached = abs(gap) <= max(1.0, 0.1 * base.effective_height)
- if outside_offset < max(0.5, 0.08 * base.effective_height) and not tightly_attached:
+ tightly_attached = abs(gap) <= max(1.0, 0.1 * base_scale)
+ if outside_offset < max(0.5, 0.08 * base_scale) and not tightly_attached:
# 紧贴边缘的小字号上下标可能完全落入高字形 bbox;其余内嵌小字仍按普通 cell 排除。
continue
- metric = abs(gap) + (1.0 - overlap_ratio) * base.effective_height
+ metric = abs(gap) + (1.0 - overlap_ratio) * base_scale
candidates.append((metric, small_index, base_index, position))
if detached_candidate:
detached_candidate_pairs.add((small_index, base_index, position))
diff --git a/mineru/model/flash/pdf/pipeline.py b/mineru/model/flash/pdf/pipeline.py
index 69f20720..a3976509 100644
--- a/mineru/model/flash/pdf/pipeline.py
+++ b/mineru/model/flash/pdf/pipeline.py
@@ -98,6 +98,7 @@ from .auxiliary_text import (
)
from .titles import (
_classify_body_height_section_titles,
+ _classify_secondary_document_title_bands,
_classify_document_structural_titles,
_classify_page_titles,
_infer_document_body_profile,
@@ -316,6 +317,10 @@ def _analyze_native_document(
legacy_body_profile=document_body_profile,
document_title_profile=document_title_profile,
)
+ _classify_secondary_document_title_bands(
+ prepared_pages,
+ canonical_body_profile,
+ )
finalized_pages = [
_finalize_prepared_page(
prepared,
@@ -716,6 +721,7 @@ def _finalize_prepared_page(
prepared.page_size,
prepared.drawing_lines,
page_footnote_groups=prepared.page_footnote_groups,
+ page_index=page_index,
)
text_blocks = _merge_multiline_title_blocks(text_blocks)
text_blocks = _merge_front_matter_column_blocks(
diff --git a/mineru/model/flash/pdf/tables.py b/mineru/model/flash/pdf/tables.py
index 970c11af..456932ef 100644
--- a/mineru/model/flash/pdf/tables.py
+++ b/mineru/model/flash/pdf/tables.py
@@ -62,6 +62,13 @@ _TABLE_CAPTION_RE = re.compile(
)
+_TABLE_CONTINUATION_RE = re.compile(
+ r"^(?:续\s*表(?:\s*[0-90-9ivxlcdm一二三四五六七八九十]+)?"
+ r"|(?:table|tab\.?)\s*(?:[0-9ivxlcdm]+\s*)?(?:continued|cont\.?))$",
+ re.IGNORECASE,
+)
+
+
_TABLE_NOTE_RE = re.compile(
r"^(?:notes?|sources?)\b|^(?:注释?|说明)\s*[::]?|^for\s+[*†‡]"
r"|^[*†‡]\s*\S",
@@ -192,12 +199,138 @@ def _detect_table_candidates(
for filled_bbox in filled_grid_bboxes
)
]
+ candidates = [*filled_grid_candidates, *merged_rule_candidates]
+ _externalize_table_continuation_captions(
+ source,
+ candidates,
+ )
return sorted(
- [*filled_grid_candidates, *merged_rule_candidates],
+ candidates,
key=lambda candidate: (candidate.bbox[1], candidate.bbox[0]),
)
+def _externalize_table_continuation_captions(
+ source: _PageSource,
+ candidates: list[_TableCandidate],
+) -> None:
+ """以连通物理网格收紧表体,并把其上方续表标记外置为 caption。"""
+
+ for candidate in candidates:
+ angle_lines = [line for line in source.lines if line.angle == candidate.angle]
+ if not angle_lines:
+ continue
+ fragments = _build_fragments(
+ angle_lines,
+ source.page_size,
+ )
+ if not fragments:
+ continue
+ median_height = _median_fragment_height(fragments)
+ local_axis_lines = _transform_axis_lines(
+ source.drawing_lines,
+ source.page_size,
+ candidate.angle,
+ )
+ grid_matches = [
+ grid_bbox
+ for grid_bbox in _connected_rule_grid_bboxes(
+ local_axis_lines,
+ median_height,
+ )
+ if _bbox_axis_overlap_ratio(
+ grid_bbox,
+ candidate.local_bbox,
+ axis="x",
+ )
+ >= 0.9
+ and _bbox_overlap_in_smaller(
+ grid_bbox,
+ candidate.local_bbox,
+ )
+ >= 0.9
+ ]
+ if not grid_matches:
+ continue
+ grid_bbox = max(
+ grid_matches,
+ key=lambda bbox: _bbox_area(bbox),
+ )
+ continuation_lines = []
+ for line in angle_lines:
+ if (
+ _TABLE_CONTINUATION_RE.fullmatch(
+ line.text.strip(),
+ )
+ is None
+ ):
+ continue
+ local_bbox = _rotate_bbox_to_upright(
+ line.bbox,
+ source.page_size,
+ candidate.angle,
+ )
+ gap = grid_bbox[1] - local_bbox[3]
+ if (
+ local_bbox[3] <= grid_bbox[1] + 0.25 * median_height
+ and -0.25 * median_height <= gap <= 3.0 * median_height
+ and _bbox_axis_overlap_ratio(
+ local_bbox,
+ grid_bbox,
+ axis="x",
+ )
+ >= 0.8
+ ):
+ continuation_lines.append(
+ (line, local_bbox),
+ )
+ if len(continuation_lines) != 1:
+ continue
+ continuation_line, continuation_local_bbox = continuation_lines[0]
+ continuation_bbox = continuation_line.bbox
+ existing_caption = next(
+ (annotation for annotation in candidate.annotations if annotation.kind == "caption"),
+ None,
+ )
+ if existing_caption is None:
+ candidate.annotations.append(
+ _TableAnnotation(
+ kind="caption",
+ bbox=continuation_bbox,
+ line_indices={continuation_line.source_index},
+ line_bboxes={
+ continuation_line.source_index: continuation_bbox,
+ },
+ )
+ )
+ else:
+ existing_caption.bbox = _bbox_union(
+ existing_caption.bbox,
+ continuation_bbox,
+ )
+ existing_caption.line_indices.add(
+ continuation_line.source_index,
+ )
+ existing_caption.line_bboxes[continuation_line.source_index] = continuation_bbox
+ candidate.line_indices.discard(
+ continuation_line.source_index,
+ )
+ core_bbox = _rotate_bbox_from_upright(
+ grid_bbox,
+ source.page_size,
+ candidate.angle,
+ )
+ candidate.core_bbox = core_bbox
+ candidate.local_bbox = _bbox_union(
+ grid_bbox,
+ continuation_local_bbox,
+ )
+ candidate.bbox = _bbox_union(
+ core_bbox,
+ continuation_bbox,
+ )
+
+
def _detect_filled_grid_table_candidates(
path_infos: list[PDFPathInfo],
page_size: tuple[float, float],
diff --git a/mineru/model/flash/pdf/text_blocks.py b/mineru/model/flash/pdf/text_blocks.py
index 7c7989b6..282f36c7 100644
--- a/mineru/model/flash/pdf/text_blocks.py
+++ b/mineru/model/flash/pdf/text_blocks.py
@@ -34,6 +34,7 @@ from .geometry import (
from .native_text import _normalize_native_run_text
from .line_layout import (
_connection_crosses_table,
+ _effective_body_text_row_gap,
_effective_text_row_gap,
_estimate_lane_gap,
_horizontal_rule_separates_rows,
@@ -42,6 +43,7 @@ from .line_layout import (
_line_effective_height,
_should_connect_semantic_rows,
_should_connect_text_rows,
+ _title_fonts_compatible,
)
@@ -51,6 +53,32 @@ _FIGURE_CAPTION_MARKER_RE = re.compile(
re.IGNORECASE,
)
_INLINE_MATH_RECOVERY_MARKER = "_recovered_inline_math_fragments"
+_FRONT_MATTER_KEYWORDS_RE = re.compile(
+ r"^\s*(?:keywords?|key\s+words?|关键词)\s*[::]",
+ re.IGNORECASE,
+)
+_LIST_ITEM_RE = re.compile(
+ r"^\s*(?:[((]\s*(?:\d+|[ivxlcdm]+)\s*[))]|[①-⑳]|[•●▪])",
+ re.IGNORECASE,
+)
+_BULLET_ITEM_RE = re.compile(
+ r"^\s*[•●▪]",
+)
+_EMAIL_METADATA_RE = re.compile(
+ r"^\s*e[\s-]*mail\s*[::]",
+ re.IGNORECASE,
+)
+_ABSTRACT_METADATA_RE = re.compile(
+ r"^\s*(?:abstract|摘\s*要)\s*[::]",
+ re.IGNORECASE,
+)
+_LABELLED_METADATA_RE = re.compile(
+ r"^\s*(?P<label>[A-Za-z\u3400-\u9fff]{1,12})\s*[::]",
+)
+_URL_LINE_RE = re.compile(
+ r"^\s*(?:https?://|www\.)",
+ re.IGNORECASE,
+)
def _starts_structural_reference_entry(
@@ -123,6 +151,23 @@ def _build_hanging_indent_group_map(
) -> tuple[int, float] | None:
"""消费一个左突首行及其续行,并返回下一条首行位置。"""
+ lane_width = max(0.1, lane.right - lane.left)
+ full_width_midparagraph_entry = (
+ rows[start_index][1][2] - rows[start_index][1][0] >= 0.8 * lane_width
+ and start_index + 1 < len(rows)
+ and rows[start_index + 1][1][2] - rows[start_index + 1][1][0] <= 0.75 * lane_width
+ )
+ if (
+ start_index > 0
+ and rows_are_adjacent(
+ rows[start_index - 1],
+ rows[start_index],
+ )
+ and abs(rows[start_index - 1][1][0] - start_left) <= start_tolerance
+ and not full_width_midparagraph_entry
+ ):
+ # 同左缘正文仍在连续时不能从段落中部启动悬挂条目序列。
+ return None
if (
start_index > 0
and is_hyphen_at_line_end(rows[start_index - 1][0].text)
@@ -633,6 +678,164 @@ def _structured_text_break_sources(
return break_sources
+def _isolated_indented_paragraph_break_sources(
+ lane: _TextLane,
+ regular_gap: float,
+ gap_mad: float,
+) -> set[int]:
+ """识别短终止尾行之后的缩进首行,并要求下一行回到稳定栏左缘。"""
+
+ rows = sorted(
+ (item for item in lane.lines if item[0].semantic_type is None),
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ lane_width = max(0.1, lane.right - lane.left)
+ output: set[int] = set()
+ terminal_re = re.compile(r"[.!?。!?::;;][\]\)})】》”’'\"]*$")
+ for previous, current, following in zip(
+ rows,
+ rows[1:],
+ rows[2:],
+ ):
+ previous_height = _line_effective_height(*previous)
+ current_height = _line_effective_height(*current)
+ following_height = _line_effective_height(*following)
+ pair_height = max(
+ previous_height,
+ current_height,
+ following_height,
+ )
+ current_indent = current[1][0] - lane.left
+ if (
+ previous[1][2] - previous[1][0] > 0.3 * lane_width
+ or terminal_re.search(previous[0].text.rstrip()) is None
+ or not max(5.0, 0.65 * pair_height) <= current_indent <= 3.0 * pair_height
+ or current[1][2] - current[1][0] < 0.75 * lane_width
+ or abs(following[1][0] - lane.left) > 0.75 * pair_height
+ or following[1][2] - following[1][0] < 0.65 * lane_width
+ or not _title_fonts_compatible(current[0], following[0])
+ ):
+ continue
+ first_gap = _effective_body_text_row_gap(previous, current)
+ second_gap = _effective_body_text_row_gap(current, following)
+ gap_limit = regular_gap + max(
+ 0.75 * pair_height,
+ 3.0 * gap_mad,
+ )
+ if -0.25 * pair_height <= first_gap <= gap_limit and -0.25 * pair_height <= second_gap <= gap_limit:
+ output.add(current[0].source_index)
+ return output
+
+
+def _front_matter_keyword_break_sources(
+ lane: _TextLane,
+ local_page_height: float,
+ page_index: int | None,
+) -> set[int]:
+ """把首页前置信息中的通用关键词行固定为独立文本块起点。"""
+
+ if page_index != 0:
+ return set()
+ return {
+ line.source_index
+ for line, bbox in lane.lines
+ if line.semantic_type is None
+ and bbox[1] <= 0.65 * local_page_height
+ and _FRONT_MATTER_KEYWORDS_RE.match(line.text) is not None
+ }
+
+
+def _component_starts_with_emphasized_row(
+ lines: list[_LineItem],
+) -> bool:
+ """识别行内强调或首行字重显著高于后续正文的组件起点。"""
+
+ if not lines:
+ return False
+ if lines[0].leading_emphasis_width is not None:
+ return True
+ first_weight = lines[0].dominant_font_weight
+ following_weights = [line.dominant_font_weight for line in lines[1:] if line.dominant_font_weight is not None]
+ if first_weight is None or not following_weights:
+ return False
+ body_weight = statistics.median(following_weights)
+ return first_weight - body_weight >= 100.0 and first_weight >= 1.15 * max(1.0, body_weight)
+
+
+def _explicit_text_break_sources(
+ lane: _TextLane,
+) -> set[int]:
+ """用通用列表标记和 E-mail 元数据确认正文中的显式硬分段。"""
+
+ rows = sorted(
+ (item for item in lane.lines if item[0].semantic_type is None),
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ output = {line.source_index for line, _bbox in rows if _ABSTRACT_METADATA_RE.match(line.text) is not None}
+ lane_width = max(0.1, lane.right - lane.left)
+ output.update(
+ line.source_index
+ for line, bbox in rows
+ if _BULLET_ITEM_RE.match(line.text) is not None and bbox[2] - bbox[0] >= 0.8 * lane_width
+ )
+ for index, (line, bbox) in enumerate(rows):
+ if _EMAIL_METADATA_RE.match(line.text) is None or index == 0:
+ continue
+ previous_line, previous_bbox = rows[index - 1]
+ pair_height = max(
+ _line_effective_height(previous_line, previous_bbox),
+ _line_effective_height(line, bbox),
+ )
+ if abs(bbox[0] - previous_bbox[0]) <= 0.75 * pair_height:
+ output.add(line.source_index)
+ for row_index, (previous, current) in enumerate(
+ zip(rows, rows[1:]),
+ ):
+ previous_is_label = _LABELLED_METADATA_RE.match(
+ previous[0].text,
+ )
+ current_is_label = _LABELLED_METADATA_RE.match(
+ current[0].text,
+ )
+ label_pair_height = max(
+ _line_effective_height(*previous),
+ _line_effective_height(*current),
+ )
+ if (
+ previous_is_label is not None
+ and current_is_label is not None
+ and _URL_LINE_RE.match(current[0].text) is None
+ and len(previous_is_label.group("label")) >= 4
+ and len(current_is_label.group("label")) >= 4
+ and any("\u3400" <= char <= "\u9fff" for char in previous_is_label.group("label"))
+ and any("\u3400" <= char <= "\u9fff" for char in current_is_label.group("label"))
+ and previous_is_label.group("label").casefold() != current_is_label.group("label").casefold()
+ and current[1][1] - previous[1][1] <= 2.0 * label_pair_height
+ and previous[1][2] - previous[1][0] <= 0.75 * lane_width
+ and current[1][2] - current[1][0] <= 0.75 * lane_width
+ ):
+ output.add(current[0].source_index)
+ pair_height = max(
+ _line_effective_height(*previous),
+ _line_effective_height(*current),
+ )
+ next_row = rows[row_index + 2] if row_index + 2 < len(rows) else None
+ indented_item_continuation = (
+ current[1][0] - lane.left >= max(5.0, 0.65 * pair_height)
+ and next_row is not None
+ and next_row[1][0] - lane.left <= 0.5 * pair_height
+ and 0.5 * pair_height <= next_row[1][1] - current[1][1] <= 2.25 * pair_height
+ )
+ if (
+ _LIST_ITEM_RE.match(current[0].text) is not None
+ and previous[0].text.rstrip().endswith((":", ":"))
+ and previous[1][2] - previous[1][0] <= 0.8 * lane_width
+ and indented_item_continuation
+ ):
+ output.add(current[0].source_index)
+ return output
+
+
def _build_text_blocks(
lines: list[_LineItem],
table_bboxes: list[BBox],
@@ -640,6 +843,7 @@ def _build_text_blocks(
drawing_lines: list[_AxisLine] | None = None,
*,
page_footnote_groups: Sequence[set[int]] | None = None,
+ page_index: int | None = None,
) -> list[dict[str, Any]]:
"""先构建分组脚注,再按类型屏障、栏带和自然段边界聚合其余文本。"""
@@ -657,6 +861,7 @@ def _build_text_blocks(
effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]
median_height = statistics.median(effective_heights) if effective_heights else 1.0
local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ local_page_height = page_size[0] if angle in {90, 270} else page_size[1]
lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)
local_axis_lines = _transform_axis_lines(drawing_lines or [], page_size, angle)
split_row_counts: dict[int, int] = {}
@@ -677,6 +882,28 @@ def _build_text_blocks(
regular_gap,
gap_mad,
)
+ isolated_break_sources = _isolated_indented_paragraph_break_sources(
+ lane,
+ regular_gap,
+ gap_mad,
+ )
+ structured_break_sources.update(
+ isolated_break_sources,
+ )
+ protected_break_sources: set[int] = set()
+ protected_break_sources.update(
+ _front_matter_keyword_break_sources(
+ lane,
+ local_page_height,
+ page_index,
+ )
+ )
+ protected_break_sources.update(
+ _explicit_text_break_sources(lane),
+ )
+ structured_break_sources.update(
+ protected_break_sources,
+ )
hanging_indent_groups = _build_hanging_indent_group_map(
lane,
table_bboxes,
@@ -799,9 +1026,19 @@ def _build_text_blocks(
component_local_lane.right,
),
"_lane_is_span": component_local_lane.is_span,
+ "_hard_break_before": (component_lines[0].source_index in structured_break_sources),
+ "_protected_hard_break_before": (component_lines[0].source_index in protected_break_sources),
+ "_hanging_indent_group": hanging_indent_groups.get(
+ component_lines[0].source_index,
+ ),
+ "_leading_emphasis_start": _component_starts_with_emphasized_row(
+ component_lines,
+ ),
}
)
blocks = _merge_spatial_text_components(blocks, page_size)
+ blocks = _merge_list_intro_text_components(blocks)
+ blocks = _merge_unterminated_text_components(blocks)
blocks = _merge_overlapping_same_line_text_blocks(blocks, page_size)
return _merge_inline_math_fragment_text_blocks(blocks, page_size)
@@ -889,6 +1126,12 @@ def _merge_overlapping_same_line_text_blocks(
or second_bbox[2] - second_bbox[0] < 0.3 * local_page_width
):
continue
+ later_block = max(
+ (first, second),
+ key=_text_component_sort_key,
+ )
+ if later_block.get("_hard_break_before") is True:
+ continue
second_heights = [
float(height) for height in second.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
]
@@ -2115,6 +2358,263 @@ def _merge_spatial_text_components(
return output
+def _merge_list_intro_text_components(
+ blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """在编号列表硬边界前合并被误拆的连续引导段和冒号短尾。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ text_indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text" and isinstance(block.get("_local_line_bboxes"), list) and block["_local_line_bboxes"]
+ ]
+ for boundary_index in text_indices:
+ boundary = blocks[boundary_index]
+ if (
+ boundary.get("_hard_break_before") is not True
+ or _LIST_ITEM_RE.match(
+ str(boundary.get("content") or ""),
+ )
+ is None
+ ):
+ continue
+ preceding = [
+ index
+ for index in text_indices
+ if index not in consumed and _text_component_sort_key(blocks[index]) < _text_component_sort_key(boundary)
+ ]
+ if not preceding:
+ continue
+ immediate_index = max(
+ preceding,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ immediate = blocks[immediate_index]
+ immediate_rows = immediate["_local_line_bboxes"]
+ immediate_heights = [
+ float(height) for height in immediate.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
+ ]
+ pair_height = statistics.median(
+ immediate_heights
+ or [
+ immediate_rows[-1][3] - immediate_rows[-1][1],
+ ],
+ )
+ interval = _component_lane_interval(immediate)
+ if (
+ interval is None
+ or immediate_rows[-1][2] - immediate_rows[-1][0] > 0.35 * (interval[1] - interval[0])
+ or not str(immediate.get("content") or "").rstrip().endswith((":", ":"))
+ or not _components_share_lane_role(
+ immediate,
+ boundary,
+ pair_height,
+ )
+ ):
+ continue
+
+ group = [immediate_index]
+ cursor_index = immediate_index
+ while len(group) < 3:
+ earlier = [
+ index
+ for index in preceding
+ if index not in group
+ and _text_component_sort_key(blocks[index]) < _text_component_sort_key(blocks[cursor_index])
+ and _components_share_lane_role(
+ blocks[index],
+ blocks[cursor_index],
+ pair_height,
+ )
+ ]
+ if not earlier:
+ break
+ previous_index = max(
+ earlier,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ previous = blocks[previous_index]
+ current = blocks[cursor_index]
+ previous_rows = previous["_local_line_bboxes"]
+ current_rows = current["_local_line_bboxes"]
+ heights = [
+ float(height)
+ for block in (previous, current)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ local_height = statistics.median(heights or [pair_height])
+ vertical_gap = current_rows[0][1] - previous_rows[-1][3]
+ if (
+ previous.get("_hard_break_before") is True
+ or not _components_share_lane_role(
+ previous,
+ current,
+ local_height,
+ )
+ or not -local_height <= vertical_gap <= local_height
+ ):
+ break
+ group.append(previous_index)
+ cursor_index = previous_index
+ if len(group) < 2:
+ continue
+ ordered_group = sorted(
+ group,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ replacement_index = min(ordered_group)
+ replacements[replacement_index] = _merge_internal_text_block_group(
+ blocks,
+ ordered_group,
+ )
+ consumed.update(ordered_group)
+
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+def _merge_unterminated_text_components(
+ blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """合并同栏、满行且前块没有终止标点的紧邻正文组件。"""
+
+ output = list(blocks)
+ terminal_re = re.compile(
+ r"[.!?。!?::;;][\]\)})】》”’'\"]*$",
+ )
+ while True:
+ text_indices = sorted(
+ (
+ index
+ for index, block in enumerate(output)
+ if block.get("type") == "text"
+ and isinstance(
+ block.get("_local_line_bboxes"),
+ list,
+ )
+ and block["_local_line_bboxes"]
+ ),
+ key=lambda index: _text_component_sort_key(output[index]),
+ )
+ merged_pair: tuple[int, int] | None = None
+ for first_index, second_index in zip(
+ text_indices,
+ text_indices[1:],
+ ):
+ first = output[first_index]
+ second = output[second_index]
+ second_rows = second["_local_line_bboxes"]
+ first_rows = first["_local_line_bboxes"]
+ heights = [
+ float(height)
+ for block in (first, second)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ pair_height = statistics.median(
+ heights
+ or [
+ first_rows[-1][3] - first_rows[-1][1],
+ second_rows[0][3] - second_rows[0][1],
+ ],
+ )
+ second_interval = _component_lane_interval(second)
+ first_content = str(first.get("content") or "")
+ second_content = str(second.get("content") or "")
+ single_numbered_tail = (
+ len(second_rows) == 1
+ and second.get("_hard_break_before") is not True
+ and _LIST_ITEM_RE.match(second_content) is not None
+ and first_content.rstrip().endswith((":", ":"))
+ )
+ url_continuation = _URL_LINE_RE.match(second_content) is not None
+ aligned_short_tail = (
+ len(first_rows) >= 2
+ and len(second_rows) == 1
+ and abs(second_rows[0][0] - first_rows[-1][0]) <= 0.75 * pair_height
+ )
+ narrow_continuation = single_numbered_tail or url_continuation or aligned_short_tail
+ starts_wide_label = (
+ not url_continuation
+ and _LABELLED_METADATA_RE.match(
+ second_content,
+ )
+ is not None
+ and second_interval is not None
+ and second_rows[0][2] - second_rows[0][0] >= 0.5 * (second_interval[1] - second_interval[0])
+ )
+ if (
+ second.get("_protected_hard_break_before") is True
+ or (second.get("_hard_break_before") is True and not narrow_continuation)
+ or second.get("_leading_emphasis_start") is True
+ or (starts_wide_label and not aligned_short_tail)
+ or first.get("_hanging_indent_group") is not None
+ or second.get("_hanging_indent_group") is not None
+ or _FIGURE_CAPTION_MARKER_RE.match(
+ first_content,
+ )
+ is not None
+ or (
+ not single_numbered_tail
+ and not url_continuation
+ and terminal_re.search(
+ first_content.rstrip(),
+ )
+ is not None
+ )
+ ):
+ continue
+ interval = _component_lane_interval(first)
+ if interval is None or not _components_share_lane_role(
+ first,
+ second,
+ pair_height,
+ ):
+ continue
+ lane_width = interval[1] - interval[0]
+ vertical_gap = second_rows[0][1] - first_rows[-1][3]
+ minimum_first_fill = 0.5 if single_numbered_tail else 0.65
+ first_reference_width = (
+ max(row[2] - row[0] for row in first_rows) if narrow_continuation else first_rows[-1][2] - first_rows[-1][0]
+ )
+ first_fonts = first.get("_font_signatures")
+ second_fonts = second.get("_font_signatures")
+ fonts_conflict = (
+ isinstance(first_fonts, set)
+ and isinstance(second_fonts, set)
+ and first_fonts
+ and second_fonts
+ and first_fonts.isdisjoint(second_fonts)
+ )
+ if (
+ first_reference_width < minimum_first_fill * lane_width
+ or (not narrow_continuation and second_rows[0][2] - second_rows[0][0] < 0.65 * lane_width)
+ or not -pair_height <= vertical_gap <= 1.5 * pair_height
+ or fonts_conflict
+ or _component_connection_skips_block(
+ output,
+ first_index,
+ second_index,
+ pair_height,
+ )
+ ):
+ continue
+ merged_pair = (first_index, second_index)
+ break
+ if merged_pair is None:
+ return output
+ first_index, second_index = merged_pair
+ output[first_index] = _merge_internal_text_block_group(
+ output,
+ [first_index, second_index],
+ )
+ output.pop(second_index)
+
+
def _component_lane_interval(
block: dict[str, Any],
) -> tuple[float, float] | None:
@@ -2226,6 +2726,8 @@ def _find_short_opener_pairs(
for body_index in candidate_indices:
if body_index == opener_index:
continue
+ if blocks[body_index].get("_hard_break_before") is True:
+ continue
if not _components_share_lane_role(
blocks[opener_index],
blocks[body_index],
@@ -2275,6 +2777,8 @@ def _nearest_following_text_component(
for candidate_index in candidate_indices:
if candidate_index == current_index or candidate_index in section_starts:
continue
+ if blocks[candidate_index].get("_hard_break_before") is True:
+ continue
if not _components_share_lane_role(
blocks[current_index],
blocks[candidate_index],
@@ -2337,6 +2841,8 @@ def _nearest_tapered_tail_component(
for candidate_index in candidate_indices:
if candidate_index == current_index or candidate_index in section_starts:
continue
+ if blocks[candidate_index].get("_hard_break_before") is True:
+ continue
if not _components_share_lane_role(
blocks[current_index],
blocks[candidate_index],
diff --git a/mineru/model/flash/pdf/titles.py b/mineru/model/flash/pdf/titles.py
index 45b438be..5a05298f 100644
--- a/mineru/model/flash/pdf/titles.py
+++ b/mineru/model/flash/pdf/titles.py
@@ -421,6 +421,148 @@ def _classify_document_structural_titles(
line.style_scale_repaired = True
+def _classify_secondary_document_title_bands(
+ prepared_pages: list[_PreparedPage],
+ document_body_profile: _DocumentBodyProfile | None,
+) -> None:
+ """用标题、作者、单位和宽摘要的连续版式识别非首页双语标题带。"""
+
+ if document_body_profile is None:
+ return
+ body_height = max(0.1, document_body_profile.body_height)
+ for prepared in prepared_pages[1:]:
+ for angle in sorted(
+ {line.angle for line in prepared.remaining_lines if line.semantic_type in {None, "paragraph_title"}}
+ ):
+ geometry = sorted(
+ [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ prepared.page_size,
+ angle,
+ ),
+ )
+ for line in prepared.remaining_lines
+ if line.angle == angle and line.semantic_type in {None, "paragraph_title"}
+ ],
+ key=lambda item: (
+ item[1][1],
+ item[1][0],
+ item[0].source_index,
+ ),
+ )
+ if len(geometry) < 5:
+ continue
+ local_page_width = prepared.page_size[1] if angle in {90, 270} else prepared.page_size[0]
+ local_page_height = prepared.page_size[0] if angle in {90, 270} else prepared.page_size[1]
+ local_containers = [
+ _rotate_bbox_to_upright(
+ block["bbox"],
+ prepared.page_size,
+ angle,
+ )
+ for block in prepared.fixed_blocks
+ if isinstance(block.get("bbox"), (list, tuple))
+ ]
+ consumed_sources: set[int] = set()
+ for index, (line, bbox) in enumerate(geometry):
+ if line.source_index in consumed_sources:
+ continue
+ line_scale = _line_effective_height(line, bbox)
+ width_ratio = (bbox[2] - bbox[0]) / max(
+ 0.1,
+ local_page_width,
+ )
+ centered = abs(_bbox_center_x(bbox) - 0.5 * local_page_width) <= 0.08 * local_page_width
+ if (
+ line_scale < 1.35 * body_height
+ or not 0.45 <= width_ratio <= 0.85
+ or not centered
+ or not 0.12 * local_page_height <= _bbox_center_y(bbox) <= 0.75 * local_page_height
+ or _line_inside_visual_container(
+ bbox,
+ local_containers,
+ )
+ ):
+ continue
+
+ title_members = [(line, bbox)]
+ cursor = index + 1
+ while cursor < len(geometry):
+ candidate_line, candidate_bbox = geometry[cursor]
+ candidate_scale = _line_effective_height(
+ candidate_line,
+ candidate_bbox,
+ )
+ vertical_gap = max(
+ 0.0,
+ candidate_bbox[1] - title_members[-1][1][3],
+ )
+ if (
+ candidate_scale < 1.3 * body_height
+ or vertical_gap
+ > 1.5
+ * max(
+ line_scale,
+ candidate_scale,
+ )
+ or abs(_bbox_center_x(candidate_bbox) - 0.5 * local_page_width) > 0.1 * local_page_width
+ or candidate_bbox[2] - candidate_bbox[0] > 0.85 * local_page_width
+ or not _title_fonts_compatible(
+ title_members[-1][0],
+ candidate_line,
+ )
+ ):
+ break
+ title_members.append(
+ (candidate_line, candidate_bbox),
+ )
+ cursor += 1
+
+ followers = geometry[cursor:]
+ if len(followers) < 3:
+ continue
+ metadata = followers[:2]
+ if any(
+ not 0.2 * local_page_width <= metadata_bbox[2] - metadata_bbox[0] <= 0.7 * local_page_width
+ or abs(_bbox_center_x(metadata_bbox) - 0.5 * local_page_width) > 0.12 * local_page_width
+ or _line_effective_height(
+ metadata_line,
+ metadata_bbox,
+ )
+ > line_scale
+ for metadata_line, metadata_bbox in metadata
+ ):
+ continue
+ title_to_metadata_gap = max(
+ 0.0,
+ metadata[0][1][1] - title_members[-1][1][3],
+ )
+ metadata_gap = max(
+ 0.0,
+ metadata[1][1][1] - metadata[0][1][3],
+ )
+ abstract_line, abstract_bbox = followers[2]
+ abstract_gap = max(
+ 0.0,
+ abstract_bbox[1] - metadata[1][1][3],
+ )
+ if (
+ title_to_metadata_gap > 4.5 * body_height
+ or metadata_gap > 2.0 * body_height
+ or abstract_gap > 4.0 * body_height
+ or abstract_bbox[2] - abstract_bbox[0] < 0.7 * local_page_width
+ or abstract_bbox[0] > 0.15 * local_page_width
+ or abstract_bbox[2] < 0.85 * local_page_width
+ ):
+ continue
+ for title_line, _title_bbox in title_members:
+ title_line.semantic_type = "doc_title"
+ consumed_sources.add(title_line.source_index)
+
+
def _canonical_title_style_key(
line: _LineItem,
) -> tuple[str, int, float, int] | None:
diff --git a/tests/fixtures/flash_layout_block_expectations.json b/tests/fixtures/flash_layout_block_expectations.json
new file mode 100644
index 00000000..62cf43c4
--- /dev/null
+++ b/tests/fixtures/flash_layout_block_expectations.json
@@ -0,0 +1,230 @@
+{
+ "schema_version": 1,
+ "documents": [
+ {
+ "path": "demo/pdfs/中文论文.pdf",
+ "sha256": "7fe627f5c376d1fd32a231648a6d9f3cd95a071e0773bb4a00cb9d359ea20a9a",
+ "type_counts": {
+ "caption": 18,
+ "doc_title": 2,
+ "equation": 6,
+ "footnote": 1,
+ "header": 24,
+ "image": 8,
+ "page_footnote": 4,
+ "page_number": 9,
+ "paragraph_title": 19,
+ "table": 3,
+ "text": 106
+ },
+ "exact_typed_text": [
+ {"page_index": 0, "type": "header", "text": "2026年4月"},
+ {"page_index": 0, "type": "header", "text": "Apr.2026"},
+ {
+ "page_index": 9,
+ "type": "doc_title",
+ "text": "Predictionoffrozensiltysandshearstrengthbasedonfourensemblelearningmethods:Boosting,Bagging,Stacking,andVoting"
+ }
+ ],
+ "same_block_groups": [
+ {
+ "page_index": 8,
+ "type": "text",
+ "fragments": ["大冻结深度未来变化预测", "冰川冻土,2023,45(2):798-807.]"]
+ }
+ ],
+ "different_block_groups": [
+ {
+ "page_index": 0,
+ "fragments": ["2026年4月", "DOI:10.7522"]
+ }
+ ]
+ },
+ {
+ "path": "demo/pdfs/中文论文2.pdf",
+ "sha256": "937cfb51e9e8abc6b3a2d8c46d38003cd2ad795a0692eab3f9e92ac604fcc9ad",
+ "type_counts": {
+ "caption": 5,
+ "doc_title": 2,
+ "equation": 14,
+ "footer": 1,
+ "header": 50,
+ "image": 5,
+ "page_footnote": 1,
+ "page_number": 22,
+ "paragraph_title": 40,
+ "table": 2,
+ "text": 312
+ },
+ "exact_typed_text": [
+ {"page_index": 2, "type": "caption", "text": "续表"}
+ ],
+ "same_block_groups": [
+ {
+ "page_index": 0,
+ "type": "text",
+ "fragments": ["摘 要:大语言模型", "探讨了大语言模型评测的一些新方向"]
+ },
+ {
+ "page_index": 2,
+ "type": "text",
+ "fragments": ["自然语言处理分为自然语言理解", "经典评测的结构如图1所示"]
+ },
+ {
+ "page_index": 2,
+ "type": "text",
+ "fragments": ["常见的自然语言理解任务有情感分析", "然后再计算模型答案与参考答案的匹配程度"]
+ },
+ {
+ "page_index": 2,
+ "type": "text",
+ "fragments": ["上述基准仅限于英语", "涵盖19种语言"]
+ },
+ {
+ "page_index": 2,
+ "type": "text",
+ "fragments": ["在中文信息处理方面", "标准化的评估方式来测评模型的中文理解能力"]
+ },
+ {
+ "page_index": 2,
+ "type": "text",
+ "fragments": ["自然语言生成的典型任务", "BLEU值越接近1"]
+ },
+ {
+ "page_index": 3,
+ "type": "text",
+ "fragments": ["在国内,四川大学和微软", "GLGE-difficult"]
+ },
+ {
+ "page_index": 3,
+ "type": "text",
+ "fragments": ["为了更好地对通用语言能力", "精心设计的"]
+ },
+ {
+ "page_index": 3,
+ "type": "text",
+ "fragments": ["在国外,为了解决大语言模型", "版本控制"]
+ },
+ {
+ "page_index": 4,
+ "type": "text",
+ "fragments": ["响,探究大语言模型本身", "为更加全面地评测大语言模型提供了更多可能"]
+ },
+ {
+ "page_index": 4,
+ "type": "text",
+ "fragments": ["SAFETYPROMPTS", "指令攻击场景"]
+ },
+ {
+ "page_index": 5,
+ "type": "text",
+ "fragments": ["除了上述评测基准以外", "HaluEval[41]等"]
+ },
+ {
+ "page_index": 5,
+ "type": "text",
+ "fragments": ["为了凸显GPT-4的总体表现", "围绕日常"]
+ },
+ {
+ "page_index": 5,
+ "type": "text",
+ "fragments": ["事件的常识性推理", "(Swahili)等小语种"]
+ },
+ {
+ "page_index": 5,
+ "type": "text",
+ "fragments": ["以体现人类级别的认知能力", "当前的大语言模型"]
+ },
+ {
+ "page_index": 7,
+ "type": "text",
+ "fragments": ["准确率的评估方法因场景和任务而异", "NormalizedDiscountedCumulativeGain"]
+ },
+ {
+ "page_index": 7,
+ "type": "text",
+ "fragments": ["首先需要估计期望准确率", "如式(1)所示"]
+ },
+ {
+ "page_index": 7,
+ "type": "equation",
+ "fragments": ["acc(Bm)=", "\\tag{1}"]
+ },
+ {
+ "page_index": 8,
+ "type": "text",
+ "fragments": ["其中,^pi是模型对样例", "即ECE"]
+ },
+ {
+ "page_index": 8,
+ "type": "text",
+ "fragments": ["模型泛化能力的评估重点", "zero-shot)设置"]
+ },
+ {
+ "page_index": 8,
+ "type": "text",
+ "fragments": ["小样本是指模型在预测时", "In-ContextLearning"]
+ },
+ {
+ "page_index": 8,
+ "type": "text",
+ "fragments": ["在不更新模型参数的适配中", "明显不同"]
+ },
+ {
+ "page_index": 9,
+ "type": "text",
+ "fragments": ["基于表示端的评估方法主要利用词向量", "闭源大语言模型"]
+ },
+ {
+ "page_index": 12,
+ "type": "text",
+ "fragments": ["与GPTScore类似", "指标分数"]
+ },
+ {
+ "page_index": 12,
+ "type": "text",
+ "fragments": ["与GPTScore和Kocmi", "给出评判的原因"]
+ },
+ {
+ "page_index": 12,
+ "type": "text",
+ "fragments": ["由于PandaLM评测方法", "同时识别和纠正任务模"]
+ },
+ {
+ "page_index": 12,
+ "type": "text",
+ "fragments": ["型生成内容中可能存在", "研究方向:"]
+ },
+ {
+ "page_index": 12,
+ "type": "text",
+ "fragments": ["(1)更具鲁棒性的指标", "稳定性和可靠性"]
+ },
+ {
+ "page_index": 16,
+ "type": "text",
+ "fragments": ["为自然语言理解任务", "方向。"]
+ },
+ {
+ "page_index": 19,
+ "type": "text",
+ "fragments": ["ityofdeepneuralnetworks", "Knowledge-basedSystems"]
+ }
+ ],
+ "different_block_groups": [
+ {
+ "page_index": 0,
+ "fragments": ["Abstract:LargeLanguageModels", "Keywords:naturallanguageprocessing"]
+ },
+ {
+ "page_index": 12,
+ "fragments": ["研究方向:", "(1)更具鲁棒性的指标"]
+ }
+ ],
+ "forbidden_type_fragments": [
+ {"page_index": 2, "type": "table", "fragment": "续表"},
+ {"page_index": 7, "type": "text", "fragment": "acc(Bm)="}
+ ]
+ }
+ ]
+}
diff --git a/tests/fixtures/flash_layout_geometry_manifest.json b/tests/fixtures/flash_layout_geometry_manifest.json
index 5bb0bdf6..bbd78dd0 100644
--- a/tests/fixtures/flash_layout_geometry_manifest.json
+++ b/tests/fixtures/flash_layout_geometry_manifest.json
@@ -8691,8 +8691,8 @@
"pages": [
{
"page_index": 0,
- "fingerprint": "c430bec74924e663c166e0874e28dbc5b85d505610506b8d68d6cab7341f8476",
- "bbox_fingerprint": "ff2474981fbce8838921cde4e2bd335a0bb2123c5ff68ec31342d9749242599b",
+ "fingerprint": "29c6ee99392dc49b632c3bd813817d09eeb3dbb9ef87edb513612b2c0e08a91b",
+ "bbox_fingerprint": "d4a63ed84841a2ceaf45dcc54a9c8537befc6f18c7ceb7053cbcb4f862f1fe5b",
"approved": true,
"blocks": [
{
@@ -9555,8 +9555,8 @@
},
{
"page_index": 8,
- "fingerprint": "145b33d4455b49b2c416ea73890a09e5e33480fa63fd3eff73b9957b06978f22",
- "bbox_fingerprint": "d34e402346ff56a6af4732343f6b06390c50b7944d9da47e2869ee9ceb92cbce",
+ "fingerprint": "1969d30a25a6a6e1f081f42ae0aa62892e0af7f07922d778e190064c4c73c1a5",
+ "bbox_fingerprint": "c6113669a0acb7cf939fa4fc22db4b29638dae31b31f4a9e26b16efd9e876fda",
"approved": true,
"blocks": [
{
@@ -9708,8 +9708,8 @@
},
{
"page_index": 9,
- "fingerprint": "02ca0ed7955c9f467c43c057bc7d96f7c832efd9fef69f73adc3dec26739a3ac",
- "bbox_fingerprint": "d075e0defdf03d9095f855c2fb8fb91b4e0d92f6efc20003e4e90ebcda100f6d",
+ "fingerprint": "c828fb1b1140ce885c6e6e3cedd978dad87757a854d3b82725912f4913132f90",
+ "bbox_fingerprint": "27045585f31b3703a4ec7a4c092a89a09ce2ca2249aecd826c6eb3f7f3bcbeae",
"approved": true,
"blocks": [
{
@@ -9786,8 +9786,8 @@
"pages": [
{
"page_index": 0,
- "fingerprint": "65cd2196df8c682419e19849654dc5757a6637cb8ea230ba1b83b46711834996",
- "bbox_fingerprint": "8e0d3deb43be533f849147177ad3d9c6976093469d74e3eba10be03f99539687",
+ "fingerprint": "254df1be62bbc381ca1544555aaf8df143fdd1c6d31ab26970c72d2b3be83732",
+ "bbox_fingerprint": "b631489ddaa5e20c9eba3e123f8844358420376dd5e5f28f16760fbe38880652",
"approved": true,
"blocks": [
{
@@ -9972,8 +9972,8 @@
},
{
"page_index": 2,
- "fingerprint": "28d1ace0166a88f83c3f8966115568cea0ddab4a17bbae476eeba38416e57ee9",
- "bbox_fingerprint": "a937ff52b69a881e89a9aa7a1fb7a760a701a2b5a43647902534610c01701cdf",
+ "fingerprint": "cf2459e7e96bf155f79cd206280eddc901087b4bfb1f67ed1aa2b71d375bd5db",
+ "bbox_fingerprint": "21807761580c47764918b1a8a60ac8e501f313df39ca02a7f936091771c3fc90",
"approved": true,
"blocks": [
{
@@ -10100,8 +10100,8 @@
},
{
"page_index": 3,
- "fingerprint": "267c7b207d83d7fc6a50692329988419f1dad063e6d38c29ec6f737266e50e78",
- "bbox_fingerprint": "10b25930996900b607c259316630213f423e5638b42baf953ee1167d8155b01a",
+ "fingerprint": "a77ea73e04b9a1d6b03b7bb002b82a2a46ef22d3f557cc208c397309cc5784b9",
+ "bbox_fingerprint": "0eebaf50ac038f1f6f4688bd611c6530427d4ca13dfcbdfc6f530c9cf13d6fb2",
"approved": true,
"blocks": [
{
@@ -10223,8 +10223,8 @@
},
{
"page_index": 4,
- "fingerprint": "e4da55f7d7966098dafa66cdf9157ba3ec3bbb4e97d5f80ae66abb85a44da941",
- "bbox_fingerprint": "0ad7123638820ab672d0f813cadfb3bc2e4da8cec555ec3c0777f9eaeb13300c",
+ "fingerprint": "c515944b86d94b2645e6d0403183a698b2da98c672ba7ff7ec339912880c786f",
+ "bbox_fingerprint": "770e9a5c825bbc5197e79dc864ff4066210dc226a1b9525165fb6cd6f5437fa7",
"approved": true,
"blocks": [
{
@@ -10291,8 +10291,8 @@
},
{
"page_index": 5,
- "fingerprint": "d6f9ac12f68a9c891b8197923430d2da2457d1d4fd028626d15b1f365cd06975",
- "bbox_fingerprint": "7068074c70732dbfa845486a5c581f5ac7d5c49a055d36901b6ad8dc59d0678d",
+ "fingerprint": "7986ebc989b837e5bb0417a2fc746ca2410ee7fec80e4562fb89c6bccccf4717",
+ "bbox_fingerprint": "694db4bdebc8923eda308c00a401e3c706d334028cce294e071578baa540c5ab",
"approved": true,
"blocks": [
{
@@ -10502,8 +10502,8 @@
},
{
"page_index": 7,
- "fingerprint": "575ee01327eb3be8b14ba7018fea403d0dd5cd488a879088bb434abeef979359",
- "bbox_fingerprint": "d10f5c4d28795f789c98ce9e9c71ad7112925732ae1386c31957b937d3fc2216",
+ "fingerprint": "73af3d8ee5d4bb198a36bb25a7eb7ba0efcbc0d0cc8529aa4593d2f093307f14",
+ "bbox_fingerprint": "4515ac470ce259294c633d00a894d3482e54d85ef3d99e12834cc65a0010abfa",
"approved": true,
"blocks": [
{
@@ -10635,8 +10635,8 @@
},
{
"page_index": 8,
- "fingerprint": "e50b35226e5de9141996b51f048b49b559f24f10ac14052ac5bba5528126f3bf",
- "bbox_fingerprint": "59bb5c5de6e7e4110acc880342b7bf28547e3ddef9d48debd76fd717c8fee6d4",
+ "fingerprint": "e8a6877ad7fd10eff9c4ab51e8cf965ff5c69a0f528b0c49fa0fd6b01c65727c",
+ "bbox_fingerprint": "90d2d62d45ca7817d08d707e44ece155d25395f1940f72c7559ba48847b385d0",
"approved": true,
"blocks": [
{
@@ -10778,8 +10778,8 @@
},
{
"page_index": 9,
- "fingerprint": "098317d2b6eb0b8461c81313a97c1990d9ac26cefa012987490e44f1631cb8e8",
- "bbox_fingerprint": "598635df1d4f54da7a86c9c03716ed23fc2ccf912d30b3a5ae502e77f031204c",
+ "fingerprint": "e042ae6457bf5d66a3822d7ee5054ac604009fef57fe7dad3a0aebf9de636300",
+ "bbox_fingerprint": "76aaeeb26ef84f4d4843d0f35d7edd6df5e3869ce5480068124f6cc37d58d153",
"approved": true,
"blocks": [
{
@@ -11112,8 +11112,8 @@
},
{
"page_index": 12,
- "fingerprint": "9024efcd92112b36d215f0e8f1f77b7fcdb2faeccdd732af019cba29ab2f3a22",
- "bbox_fingerprint": "df1b44cd46da8a217af22a6c580de5e8b3c996a1aa02801a0e22a169b7f0bde6",
+ "fingerprint": "7762d0cded1992b9a620108bfa4b96c0c277e2284d7cc68cbdc168c714a3689e",
+ "bbox_fingerprint": "6e4abf9fe680ad7de513a57051781843a1efa659601dabf07f52b78b4004dbec",
"approved": true,
"blocks": [
{
@@ -11479,8 +11479,8 @@
},
{
"page_index": 16,
- "fingerprint": "fe428d70f88141ca8e1a5ef7b25708f161e7395063a8fc0ef2435f037c5b64e6",
- "bbox_fingerprint": "6b5104626c1f0736d7d6d240152baf512b47524e84920086f4665d691cee96d6",
+ "fingerprint": "04d2fffae87d96832073e4224f1fc6c39657124e7416df42999a8cfbae745876",
+ "bbox_fingerprint": "e44f923401b4d2358f535844464e3841497e4e0763c1720a9effc82dbdb4fbfc",
"approved": true,
"blocks": [
{
@@ -11928,8 +11928,8 @@
},
{
"page_index": 19,
- "fingerprint": "1b7c1206cbb4ec793d6494b85d51fb0749da31e2aa129e37fe72e9242103c33d",
- "bbox_fingerprint": "7199fb4d3f157578b9ed42d70ae609cf3b9ac87fb9cad91eccb0b222a429f4ec",
+ "fingerprint": "51882f9de7307ec46b4c6b1973576597212bbb2a46cf6e1485bc9bda41bc3bfc",
+ "bbox_fingerprint": "13829f83782eba0ce916c64b6adc9021e8ecff680cee96521490739d7c13735b",
"approved": true,
"blocks": [
{
@@ -15020,6 +15020,295 @@
"strong_x_runs": 0,
"sibling_x_runs": 0
}
+ },
+ {
+ "path": "tests/unittest/pdfs/flash_table_annotations_synthetic.pdf",
+ "sha256": "96672df6a6ee9e1da225db8ff4875ee298e1fbf600752733c19b404c05566aa7",
+ "role": "normal",
+ "approved": true,
+ "pages": [
+ {
+ "page_index": 0,
+ "fingerprint": "b40b329dc2048492e5c23a8748ee52aaf7c2e19b777d7d1bbdeb532589d149d5",
+ "bbox_fingerprint": "bab6f4432413b6e4031d821fa5ab44b75020049220c69e258c31f0f15d1b9a9c",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "72a98446e9fe7b023e10",
+ "type": "text",
+ "text_sha256": "a1651901d66e73f14786ff7647018ab96f4a86ed6c94fca114a70eed810380f0"
+ },
+ {
+ "id": "2b511f6688c0daa10a5c",
+ "type": "text",
+ "text_sha256": "076b93f99b4d475fa6901184349d0a47801c355b8ab34fd536cab39a8603eb7b"
+ },
+ {
+ "id": "be1716e96a4c2b385412",
+ "type": "text",
+ "text_sha256": "78040480dcfc3babdd717f05044fc477918cc96b62e3d60a6761c3a2bfdd6e48"
+ },
+ {
+ "id": "73ea78ab7d804cdebea6",
+ "type": "text",
+ "text_sha256": "4685501afe62d48aa3fab828d7e3ad9c59a52f819d1bc4a3a8f6df0745823eea"
+ },
+ {
+ "id": "0853b83c78cc55e8fa0b",
+ "type": "page_number",
+ "text_sha256": "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b"
+ }
+ ]
+ },
+ {
+ "page_index": 1,
+ "fingerprint": "a7156a7ace57c8b4d5e782d5727b124be42582b37bb7b539ab24109c08875abd",
+ "bbox_fingerprint": "2bd8d77744b40c893a071fd15f98e8f7b1cd8320185d6037f5e436b08c30760d",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "7df317607e92c3af638c",
+ "type": "text",
+ "text_sha256": "36f99e12e922f835217dfaf9fb4a327a3101a90802fe2935ffab32e0d931f793"
+ },
+ {
+ "id": "bcdf36ae7220ff408ffc",
+ "type": "caption",
+ "text_sha256": "ad9742fbe24b1dd60bc5e350e113251019b7425412999e0a688288ee141607d2"
+ },
+ {
+ "id": "0890463faa6b0b67a21e",
+ "type": "table",
+ "text_sha256": "a8445666cac9d2226906a025f33e0cb0fed07dd7453cf774cbff33f0ea6dd236"
+ },
+ {
+ "id": "c9018870b47b1deeb82f",
+ "type": "caption",
+ "text_sha256": "eae08b8f2bc41f970abd97e437f4c4aa07d75f7466270456cd9249a50cba1a9c"
+ },
+ {
+ "id": "98683ed25c65687f5792",
+ "type": "table",
+ "text_sha256": "957f2a719ae9cd7ce32fc281a42bc2a816af5a379bd3f7dd68bf46c460ca25a6"
+ },
+ {
+ "id": "8d010634f63722ac77af",
+ "type": "text",
+ "text_sha256": "5ea5a4ddfb0d6a1d45bd164d57e021ffb5232569f5881027a0935a06be980c78"
+ },
+ {
+ "id": "0b30a00442099f41090e",
+ "type": "page_number",
+ "text_sha256": "d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35"
+ }
+ ]
+ },
+ {
+ "page_index": 2,
+ "fingerprint": "f97b7927aa27004a3fac657fc9cd8d7ae98aa28bf2ebb758fc53be3f74c98347",
+ "bbox_fingerprint": "58c25b128f2ace7234b03022a54f8fb6fd462b95adbbb313697f1f1f261735aa",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "1f39b71f3bca5f253413",
+ "type": "text",
+ "text_sha256": "aacbe1b4a44cda2d2730227d69cb29c496c0d6153c1c4dbb29edea69044ed246"
+ },
+ {
+ "id": "d02cc89a134a97d93e19",
+ "type": "caption",
+ "text_sha256": "744d1577b5bed1dda57bf709b1f96e2db9525f8b3714762fb181952fb78209bf"
+ },
+ {
+ "id": "91a70726e7b6c10ebbaf",
+ "type": "table",
+ "text_sha256": "d5f6a5c451f9ae4089f2928b98d62a2eaccbf67ddaba2437f8ab07d52450b0cb"
+ },
+ {
+ "id": "1eaaf552bdccd1b73e3c",
+ "type": "footnote",
+ "text_sha256": "55961e7f61d48cbab537e9bb60bae26d3e7cfc25f3c8e0b193b99e30b4e6adbc"
+ },
+ {
+ "id": "e4a59a6aff34f977e36f",
+ "type": "page_number",
+ "text_sha256": "4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce"
+ }
+ ]
+ },
+ {
+ "page_index": 3,
+ "fingerprint": "1b67449d09d9d7da920b8dd3d1ed74ab3cc625978ae1d6e1b2c33c557ae83ff8",
+ "bbox_fingerprint": "db11fa265514491e1249280c0dc4ecd73a8592b1cb429c4d791f437822f97fa5",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "0fa5986eb897e89cac14",
+ "type": "text",
+ "text_sha256": "5e5259862d92fed6853691d7eedc1e61149413d3b84f50dd55ff76753aec3733"
+ },
+ {
+ "id": "01af7690a6d0f0534f87",
+ "type": "caption",
+ "text_sha256": "a65750dd777b56f13e5471b8ad88f6f270ca868629735ed5acc5ba027a8c09d0"
+ },
+ {
+ "id": "a3b67443cb54e739bc4c",
+ "type": "table",
+ "text_sha256": "86bdbea9f3f0e78132d0fe3b7c78c08c8749658233090ab7b2c12544dec6959b"
+ },
+ {
+ "id": "3ef18ec80ff123f38936",
+ "type": "page_number",
+ "text_sha256": "4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a"
+ }
+ ]
+ },
+ {
+ "page_index": 4,
+ "fingerprint": "c774d84ecf514f64ebda06f19bc7b6c99e141bc9aab0bdfe8b8be05218eccf81",
+ "bbox_fingerprint": "f6a36101ea7e77a906627fad813e6267a3d32c7d498186528138a7a8f6539fec",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "1fe719ce58f1859f5dad",
+ "type": "text",
+ "text_sha256": "25f5f3d294659e356faf950f7a9e0eb413ad3db0154d9379bd45a9be9a1ce7b3"
+ },
+ {
+ "id": "b4c1f42a01d812e5d063",
+ "type": "text",
+ "text_sha256": "9324d616cdb60798349539030d74ab84552bff5e164dc40a4d09a41645599da7"
+ },
+ {
+ "id": "00a3f777f2bb4064cd60",
+ "type": "text",
+ "text_sha256": "98aff62e7a6b5e349e79f2cea03515e610074399cc81f1b5f1cd8f2e43d5a772"
+ },
+ {
+ "id": "915a0341bf081c1b9fcb",
+ "type": "text",
+ "text_sha256": "25be3df992c5263e0809c3b395ea71572593c1c41099bb62240d79d95a5f8659"
+ },
+ {
+ "id": "3c982a362ae3ad1b43fe",
+ "type": "text",
+ "text_sha256": "e8a667eddd89ec298d5894e000e780bec67940b140c279bd6c961a38c4545257"
+ },
+ {
+ "id": "934eaec2daed65375780",
+ "type": "page_number",
+ "text_sha256": "ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d"
+ }
+ ]
+ },
+ {
+ "page_index": 5,
+ "fingerprint": "7f0382e702bf4d40bfe9e67f7b517134e03dd8d8ab8b8e0356c44126755b6832",
+ "bbox_fingerprint": "b81ccaa8d0fdf137579d8c4a98446343604f7bdd960a27e01dab43754d566f35",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "a93453a3fb88dbd66eef",
+ "type": "text",
+ "text_sha256": "f570c3c8bbae3510eb3c5c7e4907581fc1ad7fc4bbfdbf620bf89e6534741eed"
+ },
+ {
+ "id": "e1bae01dd01e4be58d45",
+ "type": "caption",
+ "text_sha256": "de6b19214333407f7689004345419f355b2151d21aca93b6610ad9bc87ef95a4"
+ },
+ {
+ "id": "6129678895b8f7edd0fb",
+ "type": "table",
+ "text_sha256": "883e8f4921220e9bec3566370c6eae0d85a9564627ca002bc39762d02af01694"
+ },
+ {
+ "id": "4b38762c94aebbbdb09a",
+ "type": "footnote",
+ "text_sha256": "5ab01c6634bf6576f435643da4c68af401ceca6d10557785d7d1904e2af12fff"
+ },
+ {
+ "id": "37936ffec5feadc4571e",
+ "type": "page_number",
+ "text_sha256": "e7f6c011776e8db7cd330b54174fd76f7d0216b612387a5ffcfb81e6f0919683"
+ }
+ ]
+ },
+ {
+ "page_index": 6,
+ "fingerprint": "78466fd315bf3c1261e072a11612c12edbe3518a40f91c8d1413769aec136840",
+ "bbox_fingerprint": "b487310a7b56b5357a0d1a46a3b4476eeb509c12a910fb39605fa16d9c118392",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "e8aad6f36b74bcca9658",
+ "type": "text",
+ "text_sha256": "af365dc173dc8de5755f0e4beff2ecb6bfe9234a420b25d654ddd99d9d163f6a"
+ },
+ {
+ "id": "e2b38dde10bd7bec0ff8",
+ "type": "caption",
+ "text_sha256": "17391ce8c2b13f60918ab8d72a661833c326c87d5cb4ca1d0dba4225549a02e3"
+ },
+ {
+ "id": "4f43ffc6b1decdef8f95",
+ "type": "table",
+ "text_sha256": "20bd127183945baf6e44dff2e1fa51822a9985694d4e40a0eecb3ef8c9056dfc"
+ },
+ {
+ "id": "9d19f3cfa801644cc374",
+ "type": "footnote",
+ "text_sha256": "bc63e022f6671ab799ae5e953a36afa94764ae89f6f4c6081248a4f8c4f9038f"
+ },
+ {
+ "id": "8d32af21b1874ea69e3c",
+ "type": "page_number",
+ "text_sha256": "7902699be42c8a8e46fbbb4501726517e86b22c56a189f7625a6da49081b2451"
+ }
+ ]
+ },
+ {
+ "page_index": 7,
+ "fingerprint": "0895d4f09ef47f536dce8135bc07e11a07cd5dda9499767fc99c2bea07284ac3",
+ "bbox_fingerprint": "8ec9c05473a0379936918a0b521c1a3f2002795497cd1aeb3dd6db0d13759431",
+ "approved": true,
+ "blocks": [
+ {
+ "id": "9043e5381beb56ed3809",
+ "type": "text",
+ "text_sha256": "27e956fce961385366a3b57ec12500d23d7fdd41ff46897357a533d596313a2b"
+ },
+ {
+ "id": "9f983df004bd11e1601b",
+ "type": "text",
+ "text_sha256": "8f36e56a1d3c48c527900962eb8d13e5704f90ec8ecec8f0c6a5f5f8a65ff31c"
+ },
+ {
+ "id": "42ee79b2a5aa31dfc75e",
+ "type": "text",
+ "text_sha256": "cdcfe987b7d478aae0a9b7a51e8a02175a581c4e57079efd9d61ef7cc873edca"
+ },
+ {
+ "id": "f1c226848ff4b7dce105",
+ "type": "page_number",
+ "text_sha256": "2c624232cdd221771294dfbb310aca000a0df6ac8b66b696d90ef06fdefb64a3"
+ },
+ {
+ "id": "e105726d549ef079d62e",
+ "type": "footer",
+ "text_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ }
+ ]
+ }
+ ],
+ "expected_geometry_summary": {
+ "repaired_chars": 0,
+ "repaired_lines": 0,
+ "split_y_candidates": 0,
+ "strong_x_runs": 0,
+ "sibling_x_runs": 0
+ }
}
],
"performance_validation": {
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index 54718274..5faad6e3 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -904,6 +904,50 @@ def test_top_rule_marks_only_unclassified_text_above_it_as_header() -> None:
]
+def test_top_rule_uses_ink_bbox_when_loose_bbox_crosses_separator() -> None:
+ """验证 loose 框穿过页首横线时仍按真实字形区分线上日期和线下 DOI。"""
+
+ date = _text_line(
+ "2026 年 4 月",
+ (100.0, 30.0, 240.0, 64.0),
+ 0,
+ effective_height=10.0,
+ )
+ date.ink_bbox = (100.0, 34.0, 240.0, 45.0)
+ doi = _text_line(
+ "DOI:10.1000/example",
+ (100.0, 58.0, 500.0, 76.0),
+ 1,
+ effective_height=10.0,
+ )
+ doi.ink_bbox = (100.0, 64.0, 500.0, 74.0)
+ body = _text_line(
+ "body",
+ (100.0, 90.0, 700.0, 100.0),
+ 2,
+ effective_height=10.0,
+ )
+ page = _prepared_text_page(
+ date,
+ 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 date.semantic_type == "header"
+ assert doi.semantic_type is None
+ assert body.semantic_type is None
+
+
def test_top_rule_inside_graphic_does_not_mark_header() -> None:
"""验证图形容器内的页首长横线不会把其上方普通文本误标为页眉。"""
diff --git a/tests/unittest/test_flash_pdf_char_geometry.py b/tests/unittest/test_flash_pdf_char_geometry.py
index 77f60960..97ca8758 100644
--- a/tests/unittest/test_flash_pdf_char_geometry.py
+++ b/tests/unittest/test_flash_pdf_char_geometry.py
@@ -207,6 +207,37 @@ def test_strong_x_run_repairs_advance_and_contains_tight_bbox() -> None:
assert plan.line_repairs[(0, 0)].state == "repair_x"
+def test_canonical_line_metrics_propagate_without_y_bbox_rewrite() -> None:
+ """验证只发生 X 修复的行仍获得 tight 字形并集和 dominant origin 基线。"""
+
+ line, geometry = _line_fixture(
+ source_index=0,
+ baseline=20.0,
+ loose_width=12.0,
+ )
+ plan = build_document_geometry_plan(
+ [[line]],
+ [geometry],
+ [(400.0, 100.0)],
+ )
+
+ apply_line_geometry_repairs(
+ [line],
+ page_index=0,
+ plan=plan,
+ allow_y_trim=False,
+ )
+
+ assert line.baseline == 20.0
+ assert line.ink_bbox == (
+ 10.5,
+ 13.0,
+ 249.0,
+ 20.0,
+ )
+ assert line.geometry_state == "repair_x"
+
+
def test_normal_monospace_run_keeps_identity_geometry() -> None:
"""验证 fixed cell 与 origin advance 一致时不会被判为异常。"""
@@ -401,8 +432,8 @@ def test_flash_layout_manifest_uses_portable_repository_paths() -> None:
project_root = Path(__file__).parents[2]
payload = json.loads((project_root / "tests" / "fixtures" / "flash_layout_geometry_manifest.json").read_text())
assert payload["schema_version"] == 1
- assert len(payload["documents"]) == 16
- assert sum(len(document["pages"]) for document in payload["documents"]) == 151
+ assert len(payload["documents"]) == 17
+ assert sum(len(document["pages"]) for document in payload["documents"]) == 159
for document in payload["documents"]:
path = Path(document["path"])
assert not path.is_absolute()
diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.py
index d171c4e1..07d3d70a 100644
--- a/tests/unittest/test_flash_pdf_formulas.py
+++ b/tests/unittest/test_flash_pdf_formulas.py
@@ -143,6 +143,68 @@ def test_single_line_formula_requires_numeric_trailing_marker() -> None:
)
+def test_single_line_numbered_formula_absorbs_connected_math_sidecars() -> None:
+ """验证带编号公式核心吸收等号前缀和窄分子,但不吸收后续正文。"""
+
+ core = _text_line(
+ "|Bm| sum(yi) (1)",
+ (40.0, 20.0, 95.0, 35.0),
+ 0,
+ effective_height=10.0,
+ )
+ prefix = _text_line(
+ "acc(Bm)=",
+ (10.0, 24.0, 39.5, 34.0),
+ 1,
+ effective_height=10.0,
+ )
+ numerator = _text_line(
+ "1",
+ (55.0, 15.0, 60.0, 23.0),
+ 2,
+ effective_height=8.0,
+ )
+ body = _text_line(
+ "ordinary following prose",
+ (0.0, 40.0, 100.0, 50.0),
+ 3,
+ effective_height=10.0,
+ font_signature=("Body", 0),
+ font_coverage=1.0,
+ )
+ core.style_scale_repaired = True
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[
+ (core, core.bbox),
+ (prefix, prefix.bbox),
+ (numerator, numerator.bbox),
+ (body, body.bbox),
+ ],
+ )
+
+ members = formulas._expand_single_line_numbered_formula_members(
+ (core, core.bbox),
+ lane,
+ set(),
+ [],
+ ("Body", 0),
+ 10.0,
+ )
+ block = formulas._formula_members_to_block(
+ members,
+ (100.0, 100.0),
+ 0,
+ anchor_source_index=core.source_index,
+ )
+
+ assert {line.source_index for line, _bbox in members} == {0, 1, 2}
+ assert block is not None
+ assert "acc(Bm)=" in block["content"]
+ assert block["content"].count("\\tag{1}") == 1
+
+
def test_vector_formula_paths_and_detached_path_number_form_one_empty_equation() -> None:
"""验证矢量主体与远距栏右缘路径编号形成一个空内容公式。"""
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index bd9c024c..9351e07d 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -367,16 +367,16 @@ def test_explicit_pdf_fixtures_keep_expected_txt_block_inventory() -> None:
Counter(
{
"caption": 18,
- "doc_title": 1,
+ "doc_title": 2,
"equation": 6,
"footnote": 1,
- "header": 22,
+ "header": 24,
"image": 8,
"page_footnote": 4,
"page_number": 9,
- "paragraph_title": 20,
+ "paragraph_title": 19,
"table": 3,
- "text": 108,
+ "text": 106,
}
),
),
@@ -389,7 +389,8 @@ def test_explicit_pdf_fixtures_keep_expected_txt_block_inventory() -> None:
"footnote": 3,
"page_number": 8,
"table": 6,
- "text": 16,
+ # 第 5 页三条等节奏句号行按当前正文段界规则拆开;视觉 gold 已完成人工批准。
+ "text": 18,
}
),
),
diff --git a/tests/unittest/test_flash_pdf_semantics.py b/tests/unittest/test_flash_pdf_semantics.py
index 04545b2e..12f25ed1 100644
--- a/tests/unittest/test_flash_pdf_semantics.py
+++ b/tests/unittest/test_flash_pdf_semantics.py
@@ -29,6 +29,12 @@ _GEOMETRY_MANIFEST_PATH = (
/ "fixtures"
/ "flash_layout_geometry_manifest.json"
)
+_BLOCK_EXPECTATION_PATH = (
+ _PROJECT_ROOT
+ / "tests"
+ / "fixtures"
+ / "flash_layout_block_expectations.json"
+)
_FROZEN_SOIL_PATH = _PROJECT_ROOT / "demo" / "pdfs" / "中文论文.pdf"
_NATURAL_TEXT_TYPES = {"text", "doc_title", "paragraph_title"}
@@ -87,6 +93,54 @@ def _frozen_soil_pages() -> tuple[tuple[dict[str, Any], ...], ...]:
return tuple(tuple(page) for page in pages)
+@lru_cache(maxsize=1)
+def _block_expectations() -> tuple[dict[str, Any], ...]:
+ """读取两篇中文论文的版本化 block 分组与类型库存期望。"""
+
+ payload = json.loads(
+ _BLOCK_EXPECTATION_PATH.read_text(encoding="utf-8"),
+ )
+ assert payload["schema_version"] == 1
+ for document in payload["documents"]:
+ source = _PROJECT_ROOT / document["path"]
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == document["sha256"]
+ return tuple(payload["documents"])
+
+
+def _pages_for_expectation(
+ expectation: dict[str, Any],
+) -> tuple[tuple[dict[str, Any], ...], ...]:
+ """按版本化路径返回已缓存的真实 Flash 页面。"""
+
+ if expectation["path"] == "demo/pdfs/中文论文.pdf":
+ return _frozen_soil_pages()
+ assert expectation["path"] == "demo/pdfs/中文论文2.pdf"
+ return _pages()
+
+
+def _block_containing_fragment(
+ page: tuple[dict[str, Any], ...],
+ fragment: str,
+ *,
+ block_type: str | None = None,
+) -> tuple[int, dict[str, Any]]:
+ """返回唯一包含规范化片段的顶层 block 及其页内索引。"""
+
+ normalized_fragment = _normalized_text(fragment)
+ matches = [
+ (index, block)
+ for index, block in enumerate(page)
+ if (block_type is None or block.get("type") == block_type)
+ and normalized_fragment in _normalized_text(block.get("content"))
+ ]
+ assert len(matches) == 1, (
+ fragment,
+ block_type,
+ [(index, block.get("type"), _normalized_text(block.get("content"))) for index, block in matches],
+ )
+ return matches[0]
+
+
def test_frozen_soil_paper_keeps_tracked_semantic_and_bbox_gold() -> None:
"""验证无长文档门槛时中文论文1仍逐页保持已有语义与 bbox 指纹。"""
@@ -246,3 +300,68 @@ def test_chinese_paper_preserves_visual_controls_and_unique_blocks() -> None:
)
)
assert overlaps == []
+
+
+def test_chinese_papers_match_versioned_block_group_expectations() -> None:
+ """验证两篇真实论文的类型库存、指定合并和指定拆分与人工审阅期望一致。"""
+
+ for expectation in _block_expectations():
+ pages = _pages_for_expectation(expectation)
+ counts = Counter(str(block.get("type")) for page in pages for block in page)
+ assert counts == Counter(expectation["type_counts"])
+
+ for item in expectation.get("exact_typed_text", []):
+ page = pages[item["page_index"]]
+ matches = [
+ block
+ for block in page
+ if block.get("type") == item["type"] and _normalized_text(block.get("content")) == item["text"]
+ ]
+ assert len(matches) == 1, item
+
+ for group in expectation.get("same_block_groups", []):
+ page = pages[group["page_index"]]
+ matched_indices = {
+ _block_containing_fragment(
+ page,
+ fragment,
+ block_type=group["type"],
+ )[0]
+ for fragment in group["fragments"]
+ }
+ assert len(matched_indices) == 1, group
+
+ for group in expectation.get("different_block_groups", []):
+ page = pages[group["page_index"]]
+ matched_indices = {
+ _block_containing_fragment(
+ page,
+ fragment,
+ )[0]
+ for fragment in group["fragments"]
+ }
+ assert len(matched_indices) == len(group["fragments"]), group
+
+ for item in expectation.get("forbidden_type_fragments", []):
+ page = pages[item["page_index"]]
+ normalized_fragment = _normalized_text(item["fragment"])
+ assert not any(
+ block.get("type") == item["type"] and normalized_fragment in _normalized_text(block.get("content"))
+ for block in page
+ ), item
+
+
+def test_chinese_paper_continuation_caption_precedes_tight_table_body() -> None:
+ """验证第3页续表 caption 不进入 HTML,且其边界位于收紧后的表体上方。"""
+
+ page = _pages()[2]
+ _caption_index, caption = _block_containing_fragment(
+ page,
+ "续表",
+ block_type="caption",
+ )
+ table = next(block for block in page if block.get("type") == "table")
+
+ assert _normalized_text(caption.get("content")) == "续表"
+ assert "续表" not in str(table.get("content") or "")
+ assert float(caption["bbox"][3]) < float(table["bbox"][1])
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index 19c54858..151e32a0 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -44,6 +44,64 @@ def _path_info(
)
+def test_continuation_marker_is_externalized_above_precise_rule_grid() -> None:
+ """验证续表标记成为独立 caption,表体从连通竖轨支撑的网格顶线开始。"""
+
+ continuation = models._LineItem(
+ text="续表",
+ bbox=(80.0, 10.0, 95.0, 18.0),
+ angle=0,
+ source_index=0,
+ effective_height=8.0,
+ )
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=[continuation],
+ chars=[],
+ drawing_lines=[
+ models._AxisLine(
+ bbox=(0.0, 30.0, 100.0, 30.5),
+ width=0.5,
+ orientation="horizontal",
+ ),
+ models._AxisLine(
+ bbox=(0.0, 60.0, 100.0, 60.5),
+ width=0.5,
+ orientation="horizontal",
+ ),
+ models._AxisLine(
+ bbox=(0.0, 30.0, 0.5, 60.5),
+ width=0.5,
+ orientation="vertical",
+ ),
+ models._AxisLine(
+ bbox=(99.5, 30.0, 100.0, 60.5),
+ width=0.5,
+ orientation="vertical",
+ ),
+ ],
+ )
+ candidate = models._TableCandidate(
+ bbox=(0.0, 0.0, 100.0, 60.5),
+ local_bbox=(0.0, 0.0, 100.0, 60.5),
+ angle=0,
+ score=1.0,
+ core_bbox=(0.0, 0.0, 100.0, 60.5),
+ line_indices={0},
+ )
+
+ tables._externalize_table_continuation_captions(
+ source,
+ [candidate],
+ )
+
+ assert candidate.core_bbox == (0.0, 30.0, 100.0, 60.5)
+ assert candidate.line_indices == set()
+ assert len(candidate.annotations) == 1
+ assert candidate.annotations[0].kind == "caption"
+ assert candidate.annotations[0].line_indices == {0}
+
+
def _filled_grid_path_fixture(
*,
band_count: int = 5,
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index 617974ca..e0e81980 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -182,6 +182,81 @@ def test_hanging_indent_keeps_confirmed_entries_before_plain_trailing_paragraph(
assert 7 not in group_map
+def test_full_width_hanging_entries_can_start_after_aligned_prose() -> None:
+ """验证近满栏的重复悬挂条目可在同左缘正文之后启动,普通单行仍留在前文。"""
+
+ lines = [
+ _text_line("plain disclosure", (0.0, 0.0, 100.0, 10.0), 0),
+ _text_line("plain single row", (0.0, 10.0, 100.0, 20.0), 1),
+ _text_line("first entry", (0.0, 20.0, 100.0, 30.0), 2),
+ _text_line("first entry tail", (15.0, 30.0, 70.0, 40.0), 3),
+ _text_line("second entry", (0.0, 40.0, 100.0, 50.0), 4),
+ _text_line("second entry tail", (15.0, 50.0, 80.0, 60.0), 5),
+ ]
+ 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 0 not in group_map
+ assert 1 not in group_map
+ assert [group_map[index] for index in range(2, 6)] == [0, 0, 1, 1]
+
+
+def test_bullet_rows_remain_independent_text_blocks() -> None:
+ """验证近满栏项目符号为显式段界,连续披露条目不会在后处理阶段串联。"""
+
+ lines = [
+ _text_line("• first disclosure.", (0.0, 0.0, 100.0, 10.0), 0),
+ _text_line("• second disclosure.", (0.0, 10.0, 100.0, 20.0), 1),
+ _text_line("• third disclosure.", (0.0, 20.0, 100.0, 30.0), 2),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))
+
+ assert [block["content"] for block in blocks] == [
+ "• first disclosure.",
+ "• second disclosure.",
+ "• third disclosure.",
+ ]
+
+
+def test_compact_bullet_rows_keep_one_list_block() -> None:
+ """验证短项目符号列表继续按紧凑列表成块,不套用近满栏披露条目的边界。"""
+
+ lines = [
+ _text_line("• first tool", (0.0, 0.0, 45.0, 10.0), 0),
+ _text_line("• second tool", (0.0, 10.0, 48.0, 20.0), 1),
+ _text_line("• third tool", (0.0, 20.0, 42.0, 30.0), 2),
+ ]
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(line, line.bbox) for line in lines],
+ )
+
+ assert text_blocks._explicit_text_break_sources(lane) == set()
+
+
+def test_adjacent_compact_label_rows_remain_separate() -> None:
+ """验证连续的短键值元数据行形成独立块,不因缺少句末标点而串联。"""
+
+ lines = [
+ _text_line("递交截止时间:09:30", (0.0, 0.0, 55.0, 10.0), 0),
+ _text_line("递交方式:paper", (0.0, 10.0, 60.0, 20.0), 1),
+ ]
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(line, line.bbox) for line in lines],
+ )
+
+ assert text_blocks._explicit_text_break_sources(lane) == {1}
+
+
def test_twelve_point_gutter_keeps_two_text_lanes_and_paragraphs_separate() -> None:
"""验证约 12pt 行高和栏沟仍识别为双栏,左右正文不会交叉拼接。"""
@@ -374,6 +449,99 @@ def test_effective_height_connects_body_line_after_tall_math_glyph() -> None:
)
+def test_body_row_gap_uses_canonical_baseline_without_changing_semantic_gap() -> None:
+ """验证正文连接使用 baseline 节奏,而其它语义路径仍保留 bbox 净空。"""
+
+ previous = _text_line(
+ "previous full body row",
+ (0.0, 0.0, 100.0, 24.0),
+ 0,
+ effective_height=24.0,
+ )
+ current = _text_line(
+ "current full body row",
+ (0.0, 30.0, 100.0, 54.0),
+ 1,
+ effective_height=24.0,
+ )
+ for line, baseline in ((previous, 20.0), (current, 36.0)):
+ line.em_height = 10.0
+ line.style_scale_repaired = True
+ line.baseline = baseline
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(previous, previous.bbox), (current, current.bbox)],
+ )
+
+ assert (
+ line_layout._effective_text_row_gap(
+ (previous, previous.bbox),
+ (current, current.bbox),
+ )
+ == 20.0
+ )
+ assert (
+ line_layout._effective_body_text_row_gap(
+ (previous, previous.bbox),
+ (current, current.bbox),
+ )
+ == 6.0
+ )
+ assert line_layout._should_connect_text_rows(
+ (previous, previous.bbox),
+ (current, current.bbox),
+ lane,
+ 6.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
+def test_cross_lane_short_tail_returns_to_unique_preceding_lane() -> None:
+ """验证完整落在唯一正文栏内的短尾不会继续停留在 span lane。"""
+
+ previous = _text_line(
+ "full preceding row",
+ (0.0, 10.0, 100.0, 20.0),
+ 0,
+ visual_row_id=1,
+ effective_height=10.0,
+ )
+ tail = _text_line(
+ "short tail",
+ (0.0, 20.0, 40.0, 30.0),
+ 1,
+ visual_row_id=2,
+ effective_height=10.0,
+ )
+ previous.baseline = 20.0
+ tail.baseline = 30.0
+ body_lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(previous, previous.bbox)],
+ )
+ span_lane = models._TextLane(
+ left=0.0,
+ right=180.0,
+ lines=[(tail, tail.bbox)],
+ is_span=True,
+ )
+
+ line_layout._reattach_cross_lane_short_tails(
+ [body_lane, span_lane],
+ 10.0,
+ )
+
+ assert [line.text for line, _bbox in body_lane.lines] == [
+ "full preceding row",
+ "short tail",
+ ]
+ assert span_lane.lines == []
+
+
def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:
"""验证紧贴上下标与低覆盖率同行后缀恢复,同时保留外置公式编号。"""
@@ -434,6 +602,217 @@ def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:
)
+def test_canonical_reference_scale_merges_bracket_marker_but_not_plain_number() -> None:
+ """验证 loose 高度相同的括号引用可按 PDF 字号并入宿主,普通数字保持独立。"""
+
+ def sized_line(
+ text: str,
+ bbox: tuple[float, float, float, float],
+ source_index: int,
+ font_size: float,
+ ) -> models._LineItem:
+ """构造带 PDF 字号证据的单字符原生行。"""
+
+ line = _text_line(
+ text,
+ bbox,
+ source_index,
+ visual_row_id=source_index,
+ effective_height=12.0,
+ )
+ line.chars = [
+ {
+ "char": text[0],
+ "bbox": bbox,
+ "font": {
+ "name": "Fixture",
+ "flags": 0,
+ "size": font_size,
+ "weight": 400,
+ },
+ }
+ ] # type: ignore[list-item]
+ return line
+
+ base = sized_line(
+ "TriviaQA",
+ (0.0, 10.0, 50.0, 22.0),
+ 0,
+ 10.0,
+ )
+ reference = sized_line(
+ "[38]",
+ (50.1, 5.0, 57.1, 14.0),
+ 1,
+ 6.0,
+ )
+ plain_number = sized_line(
+ "1",
+ (50.1, 5.0, 57.1, 14.0),
+ 2,
+ 6.0,
+ )
+
+ merged_reference = native_text._merge_native_inline_scripts(
+ [base, reference],
+ (120.0, 100.0),
+ )
+ separate_number = native_text._merge_native_inline_scripts(
+ [
+ sized_line(
+ "TriviaQA",
+ (0.0, 10.0, 50.0, 22.0),
+ 0,
+ 10.0,
+ ),
+ plain_number,
+ ],
+ (120.0, 100.0),
+ )
+
+ assert [line.text for line in merged_reference] == [
+ "TriviaQA[38]",
+ ]
+ assert [line.text for line in separate_number] == [
+ "TriviaQA",
+ "1",
+ ]
+
+
+def test_same_repeated_indent_continues_after_terminal_punctuation() -> None:
+ """验证同一悬挂缩进锚点的紧邻尾行不会因前行句号被再次切开。"""
+
+ previous = _text_line(
+ "first indented line.",
+ (20.0, 0.0, 100.0, 10.0),
+ 0,
+ effective_height=10.0,
+ )
+ current = _text_line(
+ "second indented line",
+ (20.0, 10.0, 80.0, 20.0),
+ 1,
+ effective_height=10.0,
+ )
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(previous, previous.bbox), (current, current.bbox)],
+ )
+
+ assert line_layout._should_connect_text_rows(
+ (previous, previous.bbox),
+ (current, current.bbox),
+ lane,
+ 0.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
+def test_sparse_lane_terminal_gap_remains_paragraph_boundary() -> None:
+ """验证稀疏页不会把唯一的句号后大间距反向估计成常规行距。"""
+
+ previous = _text_line(
+ "first generated paragraph.",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ effective_height=10.0,
+ )
+ current = _text_line(
+ "second generated paragraph",
+ (0.0, 18.0, 100.0, 28.0),
+ 1,
+ effective_height=10.0,
+ )
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(previous, previous.bbox), (current, current.bbox)],
+ )
+
+ assert not line_layout._should_connect_text_rows(
+ (previous, previous.bbox),
+ (current, current.bbox),
+ lane,
+ 8.0,
+ 0.0,
+ [],
+ [],
+ )
+
+
+def test_list_intro_chain_splits_before_item_and_keeps_intro_together() -> None:
+ """验证列表前的连续引导段与冒号短尾合并,而编号项保持硬边界。"""
+
+ lines = [
+ _text_line("paragraph continues", (0.0, 0.0, 100.0, 10.0), 0),
+ _text_line("paragraph closes.", (0.0, 10.0, 100.0, 20.0), 1),
+ _text_line("list introduction", (10.0, 20.0, 100.0, 30.0), 2),
+ _text_line("directions:", (0.0, 30.0, 25.0, 40.0), 3),
+ _text_line("(1) first item", (10.0, 40.0, 100.0, 50.0), 4),
+ _text_line("item continuation", (0.0, 50.0, 100.0, 60.0), 5),
+ ]
+
+ blocks = text_blocks._build_text_blocks(
+ lines,
+ [],
+ (120.0, 100.0),
+ )
+
+ assert [block["content"] for block in blocks] == [
+ "paragraph continues paragraph closes. list introduction directions:",
+ "(1) first item item continuation",
+ ]
+
+
+def test_single_numbered_tail_merges_back_into_colon_line() -> None:
+ """验证没有续行的单个编号尾项回并冒号行,不被稀疏页段界永久拆开。"""
+
+ lines = [
+ _text_line("scope includes:", (0.0, 0.0, 90.0, 10.0), 0),
+ _text_line("(001) only entry;", (10.0, 23.0, 70.0, 33.0), 1),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))
+
+ assert [block["content"] for block in blocks] == [
+ "scope includes: (001) only entry;",
+ ]
+
+
+def test_multiline_component_absorbs_aligned_short_tail() -> None:
+ """验证多行正文吸收同左缘的单行短尾,不要求短尾达到正文满栏宽度。"""
+
+ lines = [
+ _text_line("body starts", (0.0, 0.0, 100.0, 10.0), 0),
+ _text_line("body continues", (0.0, 10.0, 100.0, 20.0), 1),
+ _text_line("short tail", (0.0, 35.0, 35.0, 45.0), 2),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))
+
+ assert [block["content"] for block in blocks] == [
+ "body starts body continues short tail",
+ ]
+
+
+def test_url_rows_continue_colon_introduction() -> None:
+ """验证冒号引导后的 URL 行继续属于前一正文块,即使 URL 自身不满栏。"""
+
+ lines = [
+ _text_line("reference link:", (0.0, 0.0, 80.0, 10.0), 0),
+ _text_line("https://example.test/path", (0.0, 24.0, 55.0, 34.0), 1),
+ ]
+
+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))
+
+ assert [block["content"] for block in blocks] == [
+ "reference link: https://example.test/path",
+ ]
+
+
def test_low_overlap_detached_script_preserves_following_row_gap() -> None:
"""验证低重叠外置字形按几何归入主体,且抬高的顶边不会拆断后继行。"""
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index a182c90d..f71b0619 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -93,6 +93,88 @@ def test_document_regular_fonts_only_use_body_height_band() -> None:
assert profile.regular_fonts == frozenset({body_font})
+def test_secondary_document_title_requires_author_affiliation_and_wide_body() -> None:
+ """验证非首页大标题只有在作者、单位和宽摘要结构完整时才成为 doc_title。"""
+
+ title_font = ("Title", 0)
+ body_font = ("Body", 0)
+ title_first = _text_line(
+ "Translated document title first",
+ (15.0, 20.0, 85.0, 38.0),
+ 0,
+ effective_height=18.0,
+ font_signature=title_font,
+ font_coverage=1.0,
+ )
+ title_second = _text_line(
+ "translated title second",
+ (20.0, 38.0, 80.0, 56.0),
+ 1,
+ effective_height=18.0,
+ font_signature=title_font,
+ font_coverage=1.0,
+ )
+ author = _text_line(
+ "Author One, Author Two",
+ (20.0, 65.0, 80.0, 75.0),
+ 2,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ affiliation = _text_line(
+ "University affiliation",
+ (25.0, 77.0, 75.0, 87.0),
+ 3,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ abstract = _text_line(
+ "wide abstract body",
+ (5.0, 96.0, 95.0, 106.0),
+ 4,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ pages = [
+ _prepared_text_page(
+ _text_line(
+ "ordinary first page body",
+ (0.0, 20.0, 100.0, 30.0),
+ 0,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ page_size=(100.0, 150.0),
+ ),
+ _prepared_text_page(
+ title_first,
+ title_second,
+ author,
+ affiliation,
+ abstract,
+ page_size=(100.0, 150.0),
+ ),
+ ]
+ profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({body_font}),
+ )
+
+ titles._classify_secondary_document_title_bands(
+ pages,
+ profile,
+ )
+
+ assert title_first.semantic_type == "doc_title"
+ assert title_second.semantic_type == "doc_title"
+ assert all(line.semantic_type is None for line in (author, affiliation, abstract))
+
+
def test_document_body_profile_prefers_width_support_over_footer_page_count() -> None:
"""验证窄页脚覆盖更多页面时,累计行宽更大的正文高度仍优先。"""