Skip to content

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

refactor: make Flash PDF semantic and table assembly stages explicit

myhlolidef58ac0828c
diff --git a/mineru/model/flash/pdf/pipeline.py b/mineru/model/flash/pdf/pipeline.py
index ba78a639..8f40e7af 100644
--- a/mineru/model/flash/pdf/pipeline.py
+++ b/mineru/model/flash/pdf/pipeline.py
@@ -104,25 +104,25 @@ from .auxiliary_text import (
_marginal_geometry_matches,
_marginal_text_matches,
)
-from .titles import (
+from .title_analysis.body_profile import _infer_document_body_profile
+from .title_analysis.document_profile import _infer_document_title_profile
+from .title_analysis.page_titles import _classify_page_titles
+from .title_analysis.structural import (
_classify_body_height_section_titles,
_classify_explicit_section_titles,
_classify_inline_typography_reset_titles,
_classify_document_structural_titles,
- _classify_page_titles,
- _infer_document_body_profile,
- _infer_document_title_profile,
_promote_noninitial_document_title_band,
)
-from .text_blocks import (
- _build_text_blocks,
+from .text_assembly.annotations import (
_merge_fragmented_header_blocks,
_merge_front_matter_column_blocks,
_merge_image_caption_text_blocks,
- _merge_internal_text_block_group,
_merge_multiline_title_blocks,
_merge_repeated_compact_title_continuations,
)
+from .text_assembly.assembly import _build_text_blocks
+from .text_assembly.common import _merge_internal_text_block_group
from .visual_annotations import _classify_and_bind_visual_annotations
@@ -408,34 +408,17 @@ def _prepare_document_sources(
return prepared_pages
-def _analyze_native_document(
- pdf_doc: PDFDocument,
- *,
- script_diagnostics: list[dict[str, Any]] | None = None,
- geometry_diagnostics: list[dict[str, Any]] | None = None,
-) -> list[list[dict[str, Any]]]:
- """逐页读取数字 PDF,并在轻量页面上完成跨页文本类型判定。"""
+@dataclass(frozen=True, slots=True)
+class _DocumentTextProfiles:
+ """分别保存原始正文尺度、规范正文尺度及全文标题原型。"""
+
+ body: _DocumentBodyProfile | None
+ canonical_body: _DocumentBodyProfile | None
+ title: _DocumentTitleProfile | None
- sources = _collect_document_sources(pdf_doc)
- prepared_pages = _prepare_document_sources(sources, geometry_diagnostics=geometry_diagnostics)
- if script_diagnostics is not None:
- script_diagnostics.extend(
- {
- "page_index": page_index,
- "page_size": prepared.page_size,
- "script_lines": list(prepared.script_lines),
- "lines": [
- {
- "source_index": line.source_index,
- "text": line.text,
- "bbox": line.bbox,
- "angle": line.angle,
- }
- for line in prepared.remaining_lines
- ],
- }
- for page_index, prepared in enumerate(prepared_pages)
- )
+
+def _classify_document_text(prepared_pages: list[_PreparedPage]) -> _DocumentTextProfiles:
+ """按既有顺序分类跨页辅助文本,再统计正文并确认结构标题。"""
_classify_repeated_visual_headers(prepared_pages)
_classify_repeated_page_marginals(prepared_pages)
@@ -466,16 +449,17 @@ def _analyze_native_document(
legacy_body_profile=document_body_profile,
document_title_profile=document_title_profile,
)
- finalized_pages = [
- _finalize_prepared_page(
- prepared,
- page_index,
- canonical_body_profile=canonical_body_profile,
- document_body_profile=document_body_profile,
- document_title_profile=document_title_profile,
- )
- for page_index, prepared in enumerate(prepared_pages)
- ]
+ return _DocumentTextProfiles(document_body_profile, canonical_body_profile, document_title_profile)
+
+
+def _materialize_document_inline(
+ finalized_pages: list[list[dict[str, Any]]],
+ prepared_pages: list[_PreparedPage],
+ sources: _DocumentSources,
+ script_diagnostics: list[dict[str, Any]] | None,
+) -> None:
+ """在页面归一化后按链接、样式、上下标顺序物化最终行内语义。"""
+
for page_index, (page_blocks, prepared, style_lines, link_lines, page_size) in enumerate(
zip(
finalized_pages,
@@ -499,6 +483,49 @@ def _analyze_native_document(
materialized_diagnostics=materialized_diagnostics,
)
materialize_pdf_inline_spans(page_blocks)
+
+
+def _analyze_native_document(
+ pdf_doc: PDFDocument,
+ *,
+ script_diagnostics: list[dict[str, Any]] | None = None,
+ geometry_diagnostics: list[dict[str, Any]] | None = None,
+) -> list[list[dict[str, Any]]]:
+ """逐页读取数字 PDF,并在轻量页面上完成跨页文本类型判定。"""
+
+ sources = _collect_document_sources(pdf_doc)
+ prepared_pages = _prepare_document_sources(sources, geometry_diagnostics=geometry_diagnostics)
+ if script_diagnostics is not None:
+ script_diagnostics.extend(
+ {
+ "page_index": page_index,
+ "page_size": prepared.page_size,
+ "script_lines": list(prepared.script_lines),
+ "lines": [
+ {
+ "source_index": line.source_index,
+ "text": line.text,
+ "bbox": line.bbox,
+ "angle": line.angle,
+ }
+ for line in prepared.remaining_lines
+ ],
+ }
+ for page_index, prepared in enumerate(prepared_pages)
+ )
+
+ profiles = _classify_document_text(prepared_pages)
+ finalized_pages = [
+ _finalize_prepared_page(
+ prepared,
+ page_index,
+ canonical_body_profile=profiles.canonical_body,
+ document_body_profile=profiles.body,
+ document_title_profile=profiles.title,
+ )
+ for page_index, prepared in enumerate(prepared_pages)
+ ]
+ _materialize_document_inline(finalized_pages, prepared_pages, sources, script_diagnostics)
return finalized_pages
diff --git a/mineru/model/flash/pdf/table_recovery/vector.py b/mineru/model/flash/pdf/table_recovery/vector.py
index ffe10a8b..1b90913c 100644
--- a/mineru/model/flash/pdf/table_recovery/vector.py
+++ b/mineru/model/flash/pdf/table_recovery/vector.py
@@ -1152,27 +1152,57 @@ def _looks_like_single_column_tracks(
)
-def _build_vector_candidate(
+@dataclass(frozen=True, slots=True)
+class _VectorTracks:
+ """保存已通过别名、尺寸和物理行数校验的规范轨道。"""
+
+ snap_tolerance: float
+ local_width: float
+ rules: list[_MergedRule]
+ canonical_x_tracks: list[_CanonicalTrack]
+ canonical_y_tracks: list[_CanonicalTrack]
+ x_tracks: list[float]
+ y_tracks: list[float]
+ narrow_empty_threshold: float
+ is_line_grid: bool
+ is_single_row_shape: bool
+ is_single_column_shape: bool
+ rows: int
+ cols: int
+
+
+@dataclass(frozen=True, slots=True)
+class _VectorTopology:
+ """保存隔断连接后的逻辑单元格及独立物理证据。"""
+
+ specs: tuple[GridCellSpec, ...]
+ separator_decisions: list[float]
+ ambiguous_ratio: float
+ alias_separator_recoveries: int
+ y_alias_separator_recoveries: int
+ alias_affected_rows: set[int]
+ single_row_evidence: _SingleRowEvidence | None
+ single_column_evidence: _SingleColumnEvidence | None
+
+
+def _reject_vector_candidate(diagnostics: dict[str, Any] | None, gate: str) -> None:
+ """记录当前假设的首个拒绝门,供各显式阶段保留统一诊断行为。"""
+
+ if diagnostics is not None:
+ diagnostics["first_rejection_gate"] = gate
+ return None
+
+
+def _build_vector_tracks(
table_input: NativeTableInput,
text: NativeTableText,
*,
include_drawing: bool,
include_rectangles: bool,
- evidence_label: str,
- prune_unsupported_horizontal: bool = False,
- diagnostics: dict[str, Any] | None = None,
-) -> NativeTableCandidate | None:
- """按单一证据来源构造一个显式 rowspan/colspan 候选。"""
-
- if diagnostics is not None:
- diagnostics["evidence"] = evidence_label
-
- def reject(gate: str) -> None:
- """记录当前假设的首个拒绝门并返回空候选。"""
-
- if diagnostics is not None:
- diagnostics["first_rejection_gate"] = gate
- return None
+ prune_unsupported_horizontal: bool,
+ diagnostics: dict[str, Any] | None,
+) -> _VectorTracks | None:
+ """构造并规范化轨道,保持 halo、别名及物理行数的原有拒绝顺序。"""
snap_tolerance = clamp(
0.08 * text.median_glyph_height,
@@ -1195,7 +1225,7 @@ def _build_vector_candidate(
)
table_bbox = normalize_bbox(table_input.table_bbox)
if table_bbox is None:
- return reject("table_geometry")
+ return _reject_vector_candidate(diagnostics, "table_geometry")
local_width, local_height = table_local_size(
table_bbox,
normalize_angle(table_input.angle),
@@ -1208,7 +1238,7 @@ def _build_vector_candidate(
evidence_halo=0.0,
)
if not exact_fragments or len(exact_fragments) > MAX_PRIMITIVES_PER_TABLE:
- return reject("raw_fragments")
+ return _reject_vector_candidate(diagnostics, "raw_fragments")
exact_rules = _merge_rule_fragments(
exact_fragments,
snap_tolerance,
@@ -1295,7 +1325,7 @@ def _build_vector_candidate(
snap_tolerance,
)
):
- return reject("rect_lattice")
+ return _reject_vector_candidate(diagnostics, "rect_lattice")
line_widths = [rule.width for rule in table_input.drawing_lines if rule.width > 0]
median_line_width = float(statistics.median(line_widths)) if line_widths else 0.0
narrow_empty_threshold = max(
@@ -1347,7 +1377,7 @@ def _build_vector_candidate(
snap_tolerance,
)
):
- return reject("canonical_alias")
+ return _reject_vector_candidate(diagnostics, "canonical_alias")
x_tracks = _canonical_track_coordinates(canonical_x_tracks)
y_tracks = _canonical_track_coordinates(canonical_y_tracks)
if diagnostics is not None:
@@ -1373,7 +1403,7 @@ def _build_vector_candidate(
right - left <= narrow_empty_threshold and not any(left < center < right for center in glyph_centers_x)
for left, right in zip(x_tracks, x_tracks[1:])
):
- return reject("remaining_narrow_track")
+ return _reject_vector_candidate(diagnostics, "remaining_narrow_track")
if any(
bottom_track.coordinate - top_track.coordinate <= narrow_empty_threshold
and not any(top_track.coordinate < center < bottom_track.coordinate for center in glyph_centers_y)
@@ -1400,7 +1430,7 @@ def _build_vector_candidate(
canonical_y_tracks[1:],
)
):
- return reject("remaining_narrow_track")
+ return _reject_vector_candidate(diagnostics, "remaining_narrow_track")
is_line_grid = include_drawing and not include_rectangles
is_single_row_shape = is_line_grid and len(y_tracks) == 2 and len(x_tracks) >= 3
is_single_column_shape = is_line_grid and len(x_tracks) == 2 and len(y_tracks) >= 3
@@ -1410,13 +1440,13 @@ def _build_vector_candidate(
or len(x_tracks) > MAX_TRACKS_PER_AXIS
or len(y_tracks) > MAX_TRACKS_PER_AXIS
):
- return reject("track_count")
+ return _reject_vector_candidate(diagnostics, "track_count")
rows = len(y_tracks) - 1
cols = len(x_tracks) - 1
if diagnostics is not None:
diagnostics["grid"] = {"rows": rows, "cols": cols}
if rows * cols > MAX_ATOMIC_CELLS:
- return reject("atomic_cell_limit")
+ return _reject_vector_candidate(diagnostics, "atomic_cell_limit")
dense_baseline_pairs = (
_physical_row_dense_baseline_pairs(
text,
@@ -1429,7 +1459,43 @@ def _build_vector_candidate(
if diagnostics is not None:
diagnostics["physical_row_dense_baseline_pairs"] = list(dense_baseline_pairs)
if dense_baseline_pairs:
- return reject("physical_row_undercount")
+ return _reject_vector_candidate(diagnostics, "physical_row_undercount")
+
+ return _VectorTracks(
+ snap_tolerance=snap_tolerance,
+ local_width=local_width,
+ rules=rules,
+ canonical_x_tracks=canonical_x_tracks,
+ canonical_y_tracks=canonical_y_tracks,
+ x_tracks=x_tracks,
+ y_tracks=y_tracks,
+ narrow_empty_threshold=narrow_empty_threshold,
+ is_line_grid=is_line_grid,
+ is_single_row_shape=is_single_row_shape,
+ is_single_column_shape=is_single_column_shape,
+ rows=rows,
+ cols=cols,
+ )
+
+
+def _build_vector_topology(
+ tracks: _VectorTracks,
+ text: NativeTableText,
+ diagnostics: dict[str, Any] | None,
+) -> _VectorTopology | None:
+ """连接原子格并验证矩形拓扑,保留单行和单列的独立物理证据。"""
+
+ snap_tolerance = tracks.snap_tolerance
+ rules = tracks.rules
+ canonical_x_tracks = tracks.canonical_x_tracks
+ canonical_y_tracks = tracks.canonical_y_tracks
+ x_tracks = tracks.x_tracks
+ y_tracks = tracks.y_tracks
+ narrow_empty_threshold = tracks.narrow_empty_threshold
+ is_single_row_shape = tracks.is_single_row_shape
+ is_single_column_shape = tracks.is_single_column_shape
+ rows = tracks.rows
+ cols = tracks.cols
union_find = _UnionFind(rows * cols)
separator_decisions: list[float] = []
@@ -1517,7 +1583,7 @@ def _build_vector_candidate(
diagnostics["y_alias_separator_recoveries"] = y_alias_separator_recoveries
diagnostics["alias_affected_rows"] = sorted(alias_affected_rows)
if ambiguous_ratio > 0.05:
- return reject("ambiguous_separator")
+ return _reject_vector_candidate(diagnostics, "ambiguous_separator")
single_row_evidence: _SingleRowEvidence | None = None
if is_single_row_shape:
@@ -1541,7 +1607,7 @@ def _build_vector_candidate(
"glyph_crossing": single_row_evidence.glyph_crossing,
}
if not single_row_evidence.verified:
- return reject("single_row_physical_evidence")
+ return _reject_vector_candidate(diagnostics, "single_row_physical_evidence")
single_column_evidence: _SingleColumnEvidence | None = None
if is_single_column_shape:
@@ -1565,7 +1631,7 @@ def _build_vector_candidate(
"glyph_crossing": single_column_evidence.glyph_crossing,
}
if not single_column_evidence.verified:
- return reject("single_column_physical_evidence")
+ return _reject_vector_candidate(diagnostics, "single_column_physical_evidence")
specs = _build_component_specs(
union_find,
@@ -1575,11 +1641,55 @@ def _build_vector_candidate(
y_tracks,
)
if specs is None:
- return reject("nonrectangular_topology")
+ return _reject_vector_candidate(diagnostics, "nonrectangular_topology")
maximum_row_cells = max(sum(spec.row <= row_index < spec.row + spec.rowspan for spec in specs) for row_index in range(rows))
maximum_col_cells = max(sum(spec.col <= col_index < spec.col + spec.colspan for spec in specs) for col_index in range(cols))
if (maximum_row_cells < 2 and not is_single_column_shape) or (maximum_col_cells < 2 and not is_single_row_shape):
- return reject("degenerate_grid")
+ return _reject_vector_candidate(diagnostics, "degenerate_grid")
+ return _VectorTopology(
+ specs=specs,
+ separator_decisions=separator_decisions,
+ ambiguous_ratio=ambiguous_ratio,
+ alias_separator_recoveries=alias_separator_recoveries,
+ y_alias_separator_recoveries=y_alias_separator_recoveries,
+ alias_affected_rows=alias_affected_rows,
+ single_row_evidence=single_row_evidence,
+ single_column_evidence=single_column_evidence,
+ )
+
+
+def _materialize_vector_candidate(
+ tracks: _VectorTracks,
+ topology: _VectorTopology,
+ text: NativeTableText,
+ evidence_label: str,
+ diagnostics: dict[str, Any] | None,
+) -> NativeTableCandidate | None:
+ """将文本落格并评分,按原顺序执行完整性与空行发布门。"""
+
+ snap_tolerance = tracks.snap_tolerance
+ local_width = tracks.local_width
+ rules = tracks.rules
+ canonical_x_tracks = tracks.canonical_x_tracks
+ canonical_y_tracks = tracks.canonical_y_tracks
+ x_tracks = tracks.x_tracks
+ y_tracks = tracks.y_tracks
+ narrow_empty_threshold = tracks.narrow_empty_threshold
+ is_line_grid = tracks.is_line_grid
+ is_single_row_shape = tracks.is_single_row_shape
+ is_single_column_shape = tracks.is_single_column_shape
+ rows = tracks.rows
+ cols = tracks.cols
+
+ specs = topology.specs
+ separator_decisions = topology.separator_decisions
+ ambiguous_ratio = topology.ambiguous_ratio
+ alias_separator_recoveries = topology.alias_separator_recoveries
+ y_alias_separator_recoveries = topology.y_alias_separator_recoveries
+ alias_affected_rows = topology.alias_affected_rows
+ single_row_evidence = topology.single_row_evidence
+ single_column_evidence = topology.single_column_evidence
+
decisiveness = float(statistics.mean(separator_decisions)) if separator_decisions else 1.0
if single_row_evidence is not None:
decisiveness = max(
@@ -1684,11 +1794,11 @@ def _build_vector_candidate(
if diagnostics is not None and diagnostics.get("candidate_rejection_gate")
else "candidate_hard_gate"
)
- return reject(candidate_gate)
+ return _reject_vector_candidate(diagnostics, candidate_gate)
if is_single_row_shape and (candidate.text_capture < 1.0 or candidate.order_consistency < 1.0):
- return reject("single_row_text_integrity")
+ return _reject_vector_candidate(diagnostics, "single_row_text_integrity")
if is_single_column_shape and (candidate.text_capture < 1.0 or candidate.order_consistency < 1.0):
- return reject("single_column_text_integrity")
+ return _reject_vector_candidate(diagnostics, "single_column_text_integrity")
row_content_support = [
sum(bool(cell.content.strip()) for cell in candidate.cells if cell.row <= row_index < cell.row + cell.rowspan)
for row_index in range(candidate.rows)
@@ -1702,7 +1812,7 @@ def _build_vector_candidate(
):
if diagnostics is not None:
diagnostics["empty_rows"] = sorted(empty_rows)
- return reject("empty_row")
+ return _reject_vector_candidate(diagnostics, "empty_row")
if diagnostics is not None:
diagnostics["first_rejection_gate"] = None
diagnostics["score"] = candidate.score
@@ -1710,6 +1820,36 @@ def _build_vector_candidate(
return candidate
+def _build_vector_candidate(
+ table_input: NativeTableInput,
+ text: NativeTableText,
+ *,
+ include_drawing: bool,
+ include_rectangles: bool,
+ evidence_label: str,
+ prune_unsupported_horizontal: bool = False,
+ diagnostics: dict[str, Any] | None = None,
+) -> NativeTableCandidate | None:
+ """按轨道、拓扑、文本落格及评分的固定顺序构造矢量候选。"""
+
+ if diagnostics is not None:
+ diagnostics["evidence"] = evidence_label
+ tracks = _build_vector_tracks(
+ table_input,
+ text,
+ include_drawing=include_drawing,
+ include_rectangles=include_rectangles,
+ prune_unsupported_horizontal=prune_unsupported_horizontal,
+ diagnostics=diagnostics,
+ )
+ if tracks is None:
+ return None
+ topology = _build_vector_topology(tracks, text, diagnostics)
+ if topology is None:
+ return None
+ return _materialize_vector_candidate(tracks, topology, text, evidence_label, diagnostics)
+
+
def build_vector_candidates(
table_input: NativeTableInput,
text: NativeTableText,
diff --git a/mineru/model/flash/pdf/text_assembly/__init__.py b/mineru/model/flash/pdf/text_assembly/__init__.py
new file mode 100644
index 00000000..b2b2d2a5
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""按职责拆分的 Flash PDF 内部实现。"""
+
+__all__: list[str] = []
diff --git a/mineru/model/flash/pdf/text_assembly/annotations.py b/mineru/model/flash/pdf/text_assembly/annotations.py
new file mode 100644
index 00000000..4547824a
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/annotations.py
@@ -0,0 +1,589 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""组装跨行标题、图片注释、页眉及首页信息块。"""
+
+from __future__ import annotations
+
+import statistics
+from typing import Any
+
+from .....types import BBox
+from ..geometry import (
+ _bbox_axis_overlap_ratio,
+ _bbox_center_x,
+ _bbox_center_y,
+ _bbox_union_many,
+)
+from ..line_layout import (
+ _is_structural_typography_gap,
+)
+from .common import _FIGURE_CAPTION_MARKER_RE, _components_share_lane_role, _merge_internal_text_block_group
+
+
+def _merge_image_caption_text_blocks(
+ blocks: list[dict[str, Any]],
+ image_bboxes: list[BBox],
+) -> list[dict[str, Any]]:
+ """在图像邻接已成立后,用通用图注标记确认锚点并吸收同字体续行。"""
+
+ if not image_bboxes:
+ return blocks
+ text_indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text"
+ and isinstance(block.get("content"), str)
+ and isinstance(block.get("bbox"), (list, tuple))
+ ]
+ all_heights = [
+ float(height)
+ for index in text_indices
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ median_height = statistics.median(all_heights) if all_heights else 1.0
+ caption_image_bboxes = _caption_image_group_bboxes(
+ image_bboxes,
+ median_height,
+ )
+ seed_indices = {
+ index
+ for index in text_indices
+ if _FIGURE_CAPTION_MARKER_RE.match(str(blocks[index]["content"]).strip())
+ and any(
+ _caption_seed_matches_image(
+ blocks[index],
+ image_bbox,
+ median_height,
+ )
+ for image_bbox in caption_image_bboxes
+ )
+ }
+ if not seed_indices:
+ return blocks
+
+ assignments: dict[int, list[int]] = {index: [] for index in seed_indices}
+ for candidate_index in text_indices:
+ if candidate_index in seed_indices:
+ continue
+ candidate = blocks[candidate_index]
+ matches: list[tuple[float, float, int]] = []
+ for seed_index in seed_indices:
+ seed = blocks[seed_index]
+ if not _caption_tail_matches_seed(
+ seed,
+ candidate,
+ median_height,
+ ):
+ continue
+ seed_bbox = seed["bbox"]
+ candidate_bbox = candidate["bbox"]
+ matches.append(
+ (
+ _bbox_center_y(candidate_bbox) - _bbox_center_y(seed_bbox),
+ abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(seed_bbox)),
+ seed_index,
+ )
+ )
+ if matches:
+ assignments[min(matches)[2]].append(candidate_index)
+
+ merged_indices: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for seed_index, tail_indices in assignments.items():
+ if not tail_indices:
+ continue
+ group_indices = [seed_index, *tail_indices]
+ replacements[seed_index] = _merge_internal_text_block_group(
+ blocks,
+ group_indices,
+ )
+ merged_indices.update(tail_indices)
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in merged_indices]
+
+
+def _caption_image_group_bboxes(
+ image_bboxes: list[BBox],
+ median_height: float,
+) -> list[BBox]:
+ """合并同一视觉行的并排图片 bbox,使跨多图的统一图注也能建立邻接。"""
+
+ remaining = list(image_bboxes)
+ grouped_bboxes = list(image_bboxes)
+ while remaining:
+ group = [remaining.pop(0)]
+ changed = True
+ while changed:
+ changed = False
+ for candidate in list(remaining):
+ aligned = False
+ for member in group:
+ overlap = max(
+ 0.0,
+ min(candidate[3], member[3]) - max(candidate[1], member[1]),
+ )
+ minimum_height = max(
+ 0.1,
+ min(
+ candidate[3] - candidate[1],
+ member[3] - member[1],
+ ),
+ )
+ horizontal_gap = max(
+ 0.0,
+ max(candidate[0], member[0]) - min(candidate[2], member[2]),
+ )
+ if overlap / minimum_height >= 0.7 and horizontal_gap <= 2.0 * median_height:
+ aligned = True
+ break
+ if aligned:
+ group.append(candidate)
+ remaining.remove(candidate)
+ changed = True
+ if len(group) >= 2:
+ grouped_bboxes.append(_bbox_union_many(group))
+ return grouped_bboxes
+
+
+def _caption_seed_matches_image(
+ block: dict[str, Any],
+ image_bbox: BBox,
+ median_height: float,
+) -> bool:
+ """用上下位置、水平投影和居中关系确认图像下方的图注空间候选。"""
+
+ bbox = block["bbox"]
+ image_width = max(0.1, image_bbox[2] - image_bbox[0])
+ block_width = max(0.1, bbox[2] - bbox[0])
+ vertical_gap = max(0.0, bbox[1] - image_bbox[3])
+ return (
+ _bbox_center_y(bbox) >= image_bbox[3] - 0.25 * median_height
+ and vertical_gap <= 2.5 * median_height
+ and _bbox_axis_overlap_ratio(bbox, image_bbox, axis="x") >= 0.35
+ and abs(_bbox_center_x(bbox) - _bbox_center_x(image_bbox)) <= 0.35 * max(image_width, block_width)
+ and block_width <= 1.75 * image_width
+ )
+
+
+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],
+ median_height: float,
+) -> bool:
+ """只用同栏角色、字体、邻接和投影把无标记的图注续行接回锚点。"""
+
+ seed_bbox = seed["bbox"]
+ candidate_bbox = candidate["bbox"]
+ if not _components_share_lane_role(seed, candidate, median_height) and (
+ _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.75
+ or abs(seed_bbox[0] - candidate_bbox[0]) > median_height
+ ):
+ return False
+ if _bbox_center_y(candidate_bbox) <= _bbox_center_y(seed_bbox):
+ return False
+ if _caption_body_has_structural_gap(seed, candidate):
+ return False
+ vertical_gap = max(0.0, candidate_bbox[1] - seed_bbox[3])
+ if vertical_gap > 0.5 * median_height or _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.35:
+ return False
+ seed_fonts = seed.get("_font_signatures")
+ candidate_fonts = candidate.get("_font_signatures")
+ return not (
+ isinstance(seed_fonts, set)
+ and seed_fonts
+ and isinstance(candidate_fonts, set)
+ and candidate_fonts
+ and seed_fonts.isdisjoint(candidate_fonts)
+ )
+
+
+def _merge_multiline_title_blocks(
+ blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """跨错误栏带合并紧贴且字体兼容的多行文档标题和段落标题。"""
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for block_type in ("doc_title", "paragraph_title"):
+ indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == block_type and isinstance(block.get("bbox"), (list, tuple))
+ ]
+ indices.sort(
+ key=lambda index: (
+ blocks[index]["bbox"][1],
+ blocks[index]["bbox"][0],
+ )
+ )
+ groups: list[list[int]] = []
+ for index in indices:
+ if not groups:
+ groups.append([index])
+ continue
+ previous_index = groups[-1][-1]
+ previous = blocks[previous_index]
+ current = blocks[index]
+ previous_bbox = previous["bbox"]
+ current_bbox = current["bbox"]
+ previous_heights = previous.get("_line_heights", [])
+ current_heights = current.get("_line_heights", [])
+ previous_height = (
+ statistics.median(previous_heights)
+ if isinstance(previous_heights, list) and previous_heights
+ else previous_bbox[3] - previous_bbox[1]
+ )
+ current_height = (
+ statistics.median(current_heights)
+ if isinstance(current_heights, list) and current_heights
+ else current_bbox[3] - current_bbox[1]
+ )
+ vertical_gap = current_bbox[1] - previous_bbox[3]
+ previous_fonts = previous.get("_font_signatures")
+ current_fonts = current.get("_font_signatures")
+ fonts_conflict = (
+ isinstance(previous_fonts, set)
+ and previous_fonts
+ and isinstance(current_fonts, set)
+ and current_fonts
+ and previous_fonts.isdisjoint(current_fonts)
+ )
+ if (
+ -0.2 * max(previous_height, current_height) <= vertical_gap <= 0.4 * max(previous_height, current_height)
+ and _bbox_axis_overlap_ratio(
+ previous_bbox,
+ current_bbox,
+ axis="x",
+ )
+ >= 0.2
+ and not fonts_conflict
+ ):
+ groups[-1].append(index)
+ else:
+ groups.append([index])
+ for group in groups:
+ if len(group) < 2:
+ continue
+ replacements[group[0]] = _merge_internal_text_block_group(
+ blocks,
+ group,
+ )
+ consumed.update(group[1:])
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
+
+
+def _merge_fragmented_header_blocks(
+ blocks: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """聚合同一视觉行中等距分散的页眉页脚片段。"""
+
+ grouped: dict[tuple[int, int], list[int]] = {}
+ for index, block in enumerate(blocks):
+ row_id = block.get("_single_run_row_id")
+ angle = int(block.get("angle", 0) or 0) % 360
+ if block.get("type") in {"header", "footer"} and isinstance(row_id, int):
+ grouped.setdefault((angle, row_id), []).append(index)
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for indices in grouped.values():
+ ordered = sorted(indices, key=lambda index: blocks[index]["bbox"][0])
+ components: list[list[int]] = []
+ for index in ordered:
+ bbox = blocks[index]["bbox"]
+ heights = blocks[index].get("_line_heights", [])
+ effective_height = (
+ statistics.median(heights) if isinstance(heights, list) and heights else max(0.1, bbox[3] - bbox[1])
+ )
+ if blocks[index].get("type") == "header" and bbox[2] - bbox[0] > 1.25 * effective_height:
+ continue
+ if not components:
+ components.append([index])
+ continue
+ previous_index = components[-1][-1]
+ previous_bbox = blocks[previous_index]["bbox"]
+ previous_heights = blocks[previous_index].get("_line_heights", [])
+ previous_height = (
+ statistics.median(previous_heights)
+ if isinstance(previous_heights, list) and previous_heights
+ else max(0.1, previous_bbox[3] - previous_bbox[1])
+ )
+ if (
+ bbox[0] - previous_bbox[2] <= 4.0 * max(effective_height, previous_height)
+ and _bbox_axis_overlap_ratio(previous_bbox, bbox, axis="y") >= 0.5
+ ):
+ components[-1].append(index)
+ else:
+ components.append([index])
+ for component in components:
+ if len(component) < 2:
+ continue
+ replacement = _merge_internal_text_block_group(
+ blocks,
+ component,
+ preserve_visual_spaces=True,
+ )
+ replacement["_single_run_row_id"] = None
+ replacements[component[0]] = replacement
+ consumed.update(component[1:])
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
+
+
+def _merge_front_matter_column_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+ *,
+ page_index: int,
+) -> list[dict[str, Any]]:
+ """把首页标题下方规则排列的多列作者信息按列聚合。"""
+
+ if page_index != 0:
+ return blocks
+ page_width, page_height = page_size
+ if page_width <= 0 or page_height <= 0:
+ return blocks
+ title_blocks = [
+ block for block in blocks if block.get("type") == "doc_title" and isinstance(block.get("bbox"), (list, tuple))
+ ]
+ if not title_blocks:
+ return blocks
+ title_bottom = max(block["bbox"][3] for block in title_blocks)
+ candidates = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text"
+ and isinstance(block.get("bbox"), (list, tuple))
+ and title_bottom < block["bbox"][1]
+ and block["bbox"][3]
+ <= min(
+ 0.4 * page_height,
+ title_bottom + 0.22 * page_height,
+ )
+ and block["bbox"][2] - block["bbox"][0] <= 0.32 * page_width
+ and block["bbox"][3] - block["bbox"][1] <= 0.035 * page_height
+ ]
+ if len(candidates) < 9:
+ return blocks
+ median_height = statistics.median(blocks[index]["bbox"][3] - blocks[index]["bbox"][1] for index in candidates)
+ row_groups: list[list[int]] = []
+ for index in sorted(
+ candidates,
+ key=lambda item: (
+ _bbox_center_y(blocks[item]["bbox"]),
+ blocks[item]["bbox"][0],
+ ),
+ ):
+ center_y = _bbox_center_y(blocks[index]["bbox"])
+ target = next(
+ (
+ row
+ for row in row_groups
+ if abs(center_y - statistics.median(_bbox_center_y(blocks[member]["bbox"]) for member in row))
+ <= 0.6 * median_height
+ ),
+ None,
+ )
+ if target is None:
+ row_groups.append([index])
+ else:
+ target.append(index)
+ dense_rows = [
+ row
+ for row in row_groups
+ if 3 <= len(row) <= 6
+ and (
+ max(blocks[index]["bbox"][2] for index in row) - min(blocks[index]["bbox"][0] for index in row) >= 0.55 * page_width
+ )
+ ]
+ if len(dense_rows) < 2:
+ return blocks
+ anchor_row = min(
+ dense_rows,
+ key=lambda row: (
+ -len(row),
+ statistics.median(_bbox_center_y(blocks[index]["bbox"]) for index in row),
+ ),
+ )
+ anchor_centers = sorted(_bbox_center_x(blocks[index]["bbox"]) for index in anchor_row)
+ if len(anchor_centers) != 4:
+ return blocks
+ boundaries = [0.5 * (left + right) for left, right in zip(anchor_centers, anchor_centers[1:])]
+ band_top = min(min(blocks[index]["bbox"][1] for index in row) for row in dense_rows) - median_height
+ band_bottom = max(max(blocks[index]["bbox"][3] for index in row) for row in dense_rows) + median_height
+ column_groups: list[list[int]] = [[] for _center in anchor_centers]
+ for index in candidates:
+ bbox = blocks[index]["bbox"]
+ if not band_top <= _bbox_center_y(bbox) <= band_bottom:
+ continue
+ center_x = _bbox_center_x(bbox)
+ column_index = sum(center_x > boundary for boundary in boundaries)
+ if column_index >= len(column_groups):
+ continue
+ column_groups[column_index].append(index)
+ if any(len(group) < 3 for group in column_groups):
+ return blocks
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for group in column_groups:
+ ordered = sorted(
+ group,
+ key=lambda index: (
+ blocks[index]["bbox"][1],
+ blocks[index]["bbox"][0],
+ ),
+ )
+ replacements[ordered[0]] = _merge_internal_text_block_group(
+ blocks,
+ ordered,
+ )
+ consumed.update(ordered[1:])
+ return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
+
+
+def _merge_repeated_compact_title_continuations(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把重复出现的两行弱标题与紧邻异字体续行恢复为普通文本块。"""
+
+ candidate_pairs: list[tuple[int, int, float]] = []
+ for title_index, title in enumerate(blocks):
+ title_lines = title.get("_local_line_bboxes")
+ title_fonts = title.get("_font_signatures")
+ title_bbox = title.get("bbox")
+ if (
+ title.get("type") != "paragraph_title"
+ or not isinstance(title_bbox, (list, tuple))
+ or not isinstance(title_lines, list)
+ or len(title_lines) < 2
+ or not isinstance(title_fonts, set)
+ or not title_fonts
+ ):
+ continue
+ angle = int(title.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ line_heights = [
+ float(height) for height in title.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
+ ]
+ title_height = statistics.median(line_heights) if line_heights else 0.0
+ if title_height <= 0 or title_bbox[2] - title_bbox[0] > 0.55 * local_page_width:
+ continue
+
+ continuations: list[tuple[float, int]] = []
+ for text_index, text_block in enumerate(blocks):
+ text_bbox = text_block.get("bbox")
+ text_fonts = text_block.get("_font_signatures")
+ if (
+ text_block.get("type") != "text"
+ or int(text_block.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(text_bbox, (list, tuple))
+ or not isinstance(text_fonts, set)
+ or not text_fonts
+ or not title_fonts.isdisjoint(text_fonts)
+ or text_bbox[2] - text_bbox[0] > 0.6 * local_page_width
+ ):
+ continue
+ gap = text_bbox[1] - title_bbox[3]
+ if -0.25 * title_height <= gap <= 0.6 * title_height and abs(text_bbox[0] - title_bbox[0]) <= 0.75 * title_height:
+ continuations.append((max(0.0, gap), text_index))
+ if continuations:
+ _gap, text_index = min(continuations)
+ candidate_pairs.append((title_index, text_index, title_height))
+
+ supported_pairs: list[tuple[int, int]] = []
+ for title_index, text_index, title_height in candidate_pairs:
+ title_bbox = blocks[title_index]["bbox"]
+ support_count = sum(
+ abs(blocks[other_title]["bbox"][0] - title_bbox[0]) <= max(title_height, other_height)
+ and 0.75 <= other_height / title_height <= 1.25
+ for other_title, _other_text, other_height in candidate_pairs
+ )
+ if support_count >= 2:
+ supported_pairs.append((title_index, text_index))
+ if not supported_pairs:
+ return blocks
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for title_index, text_index in supported_pairs:
+ if title_index in consumed or text_index in consumed:
+ continue
+ merged = _merge_internal_text_block_group(
+ blocks,
+ [title_index, text_index],
+ )
+ merged["type"] = "text"
+ replacements[min(title_index, text_index)] = merged
+ consumed.update({title_index, text_index})
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+__all__ = [
+ "_merge_image_caption_text_blocks",
+ "_caption_image_group_bboxes",
+ "_caption_seed_matches_image",
+ "_caption_body_has_structural_gap",
+ "_caption_tail_matches_seed",
+ "_merge_multiline_title_blocks",
+ "_merge_fragmented_header_blocks",
+ "_merge_front_matter_column_blocks",
+ "_merge_repeated_compact_title_continuations",
+]
diff --git a/mineru/model/flash/pdf/text_assembly/assembly.py b/mineru/model/flash/pdf/text_assembly/assembly.py
new file mode 100644
index 00000000..ba3f5f1f
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/assembly.py
@@ -0,0 +1,297 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""保持既有顺序编排正文行分组与块级组装。"""
+
+from __future__ import annotations
+
+import statistics
+from typing import Any, Sequence
+
+from .....types import BBox
+from .....utils.text import is_hyphen_at_line_end
+from ..geometry import (
+ _bbox_union_many,
+ _rotate_bbox_to_upright,
+ _transform_axis_lines,
+)
+from ..line_layout import (
+ _estimate_lane_gap,
+ _infer_text_lanes,
+ _line_effective_height,
+ _should_connect_semantic_rows,
+ _should_connect_text_rows,
+)
+from ..models import _AxisLine, _LineItem
+from ..native_text import _normalize_native_run_text
+from .common import _PARAGRAPH_FORMULA_CONTEXT_MARKER, _merge_text_line_content
+from .footnotes import _build_grouped_page_footnote_blocks
+from .merging import (
+ _merge_inline_math_fragment_text_blocks,
+ _merge_list_intro_text_components,
+ _merge_overlapping_same_line_text_blocks,
+ _merge_paragraph_formula_context_blocks,
+ _merge_short_same_baseline_prefix_blocks,
+ _merge_spatial_text_components,
+ _merge_unterminated_text_components,
+)
+from .rows import (
+ _build_hanging_indent_group_map,
+ _centered_visual_reset_break_sources,
+ _component_starts_with_emphasized_row,
+ _explicit_text_break_sources,
+ _formula_style_text_row_break_sources,
+ _front_matter_keyword_break_sources,
+ _infer_local_text_lane_map,
+ _isolated_indented_paragraph_break_sources,
+ _leading_typography_reset_break_sources,
+ _local_tight_output_line_bboxes,
+ _starts_structural_reference_entry,
+ _structured_text_break_sources,
+)
+
+
+def _build_text_blocks(
+ lines: list[_LineItem],
+ table_bboxes: list[BBox],
+ page_size: tuple[float, float],
+ drawing_lines: list[_AxisLine] | None = None,
+ *,
+ page_footnote_groups: Sequence[set[int]] | None = None,
+ page_index: int | None = None,
+ visual_bboxes: Sequence[BBox] | None = None,
+) -> list[dict[str, Any]]:
+ """先构建分组脚注,再按类型屏障、栏带和自然段边界聚合其余文本。"""
+
+ blocks, grouped_footnote_indices = _build_grouped_page_footnote_blocks(
+ lines,
+ page_footnote_groups or [],
+ page_size,
+ )
+ lines = [line for line in lines if line.source_index not in grouped_footnote_indices]
+ for angle in sorted({line.angle for line in lines}):
+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]
+ if not line_geometry:
+ continue
+ line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ 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]
+ local_visual_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in (visual_bboxes or [])]
+ 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] = {}
+ for line, _bbox in line_geometry:
+ if line.visual_row_id is not None and line.split_from_row:
+ split_row_counts[line.visual_row_id] = split_row_counts.get(line.visual_row_id, 0) + 1
+
+ for lane in lanes:
+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ 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,
+ )
+ isolated_break_sources = _isolated_indented_paragraph_break_sources(
+ lane,
+ regular_gap,
+ gap_mad,
+ )
+ structured_break_sources.update(
+ isolated_break_sources,
+ )
+ visual_reset_sources = _centered_visual_reset_break_sources(
+ lane,
+ local_visual_bboxes,
+ local_page_height,
+ )
+ typography_reset_sources = _leading_typography_reset_break_sources(
+ lane,
+ regular_gap,
+ gap_mad,
+ )
+ formula_text_break_sources = _formula_style_text_row_break_sources(
+ lane,
+ )
+ structured_break_sources.update(visual_reset_sources)
+ structured_break_sources.update(typography_reset_sources)
+ structured_break_sources.update(formula_text_break_sources)
+ protected_break_sources: set[int] = set()
+ protected_break_sources.update(visual_reset_sources)
+ protected_break_sources.update(typography_reset_sources)
+ protected_break_sources.update(formula_text_break_sources)
+ 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,
+ local_axis_lines,
+ )
+ component: list[tuple[_LineItem, BBox]] = [lane.lines[0]]
+ components: list[list[tuple[_LineItem, BBox]]] = []
+ for previous, current in zip(lane.lines, lane.lines[1:]):
+ previous_type = previous[0].semantic_type
+ current_type = current[0].semantic_type
+ if previous_type != current_type:
+ should_connect = False
+ elif previous_type is not None:
+ should_connect = _should_connect_semantic_rows(
+ previous,
+ current,
+ lane,
+ regular_gap,
+ table_bboxes,
+ local_axis_lines,
+ )
+ else:
+ previous_group = hanging_indent_groups.get(previous[0].source_index)
+ current_group = hanging_indent_groups.get(current[0].source_index)
+ 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].style_scale_repaired
+ and current[0].split_from_row
+ and current[0].visual_row_id is not None
+ and split_row_counts.get(
+ current[0].visual_row_id,
+ 0,
+ )
+ >= 2
+ ):
+ should_connect = False
+ elif 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):
+ # 断词续行优先于悬挂缩进分组,但仍复用正文连接中的距离和障碍限制。
+ should_connect = _should_connect_text_rows(
+ previous,
+ current,
+ connection_lane,
+ regular_gap,
+ gap_mad,
+ table_bboxes,
+ local_axis_lines,
+ )
+ elif previous_group is not None or current_group is not None:
+ should_connect = previous_group is not None and previous_group == current_group
+ else:
+ should_connect = _should_connect_text_rows(
+ previous,
+ current,
+ connection_lane,
+ regular_gap,
+ gap_mad,
+ table_bboxes,
+ local_axis_lines,
+ )
+ if should_connect:
+ component.append(current)
+ else:
+ components.append(component)
+ component = [current]
+ components.append(component)
+
+ 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(
+ normalized for line in component_lines if (normalized := _normalize_native_run_text(line.text))
+ )
+ else:
+ content = _merge_text_line_content([line.text for line in component_lines])
+ if not content:
+ continue
+ visual_row_ids = {line.visual_row_id for line in component_lines if line.visual_row_id is not None}
+ single_run_row_id = (
+ component_lines[0].visual_row_id
+ if len(component_lines) == 1
+ and component_lines[0].split_from_row
+ and component_lines[0].visual_row_id is not None
+ else None
+ )
+ local_output_line_bboxes, output_bbox_repaired = _local_tight_output_line_bboxes(
+ component_lines,
+ page_size,
+ angle,
+ )
+ blocks.append(
+ {
+ "type": component_lines[0].semantic_type or "text",
+ "bbox": _bbox_union_many([line.bbox for line in component_lines]),
+ "angle": angle,
+ "content": content,
+ "_visual_row_ids": visual_row_ids,
+ "_single_run_row_id": single_run_row_id,
+ "_local_line_bboxes": [bbox for _line, bbox in component_geometry],
+ "_local_output_line_bboxes": local_output_line_bboxes,
+ "_output_bbox_repaired": output_bbox_repaired,
+ "_line_heights": [_line_effective_height(line, bbox) for line, bbox in component_geometry],
+ "_font_signatures": {
+ line.font_signature
+ for line in component_lines
+ if line.font_signature is not None and line.font_coverage >= 0.5
+ },
+ "_inline_math_regions": [region for line in component_lines for region in line.inline_math_regions],
+ _PARAGRAPH_FORMULA_CONTEXT_MARKER: any(line.paragraph_formula_context for line in component_lines),
+ "_lane_interval": (
+ component_local_lane.left,
+ 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_short_same_baseline_prefix_blocks(
+ blocks,
+ page_size,
+ )
+ 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)
+ blocks = _merge_inline_math_fragment_text_blocks(
+ blocks,
+ page_size,
+ )
+ return _merge_paragraph_formula_context_blocks(
+ blocks,
+ page_size,
+ )
+
+
+__all__ = ["_build_text_blocks"]
diff --git a/mineru/model/flash/pdf/text_assembly/common.py b/mineru/model/flash/pdf/text_assembly/common.py
new file mode 100644
index 00000000..b1d47771
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/common.py
@@ -0,0 +1,482 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""共享正文块连接的几何、内容拼接和来源规则。"""
+
+from __future__ import annotations
+
+import re
+from typing import Any, Sequence
+
+from .....utils.language import detect_lang
+from .....utils.text import merge_text_line_contents
+from ..geometry import (
+ _bbox_axis_overlap_ratio,
+ _bbox_center_y,
+ _bbox_union_many,
+)
+from ..native_text import _normalize_native_run_text
+
+_REFERENCE_ENTRY_RE = re.compile(r"^[[\[]\s*\d+\s*[]\]]")
+
+
+_FIGURE_CAPTION_MARKER_RE = re.compile(
+ r"^(?:图\s*[0-90-9一二三四五六七八九十]|fig(?:ure)?\.?\s*[0-9])",
+ re.IGNORECASE,
+)
+
+
+_INLINE_MATH_RECOVERY_MARKER = "_recovered_inline_math_fragments"
+
+
+_PARAGRAPH_FORMULA_CONTEXT_MARKER = "_paragraph_formula_context"
+
+
+_FRONT_MATTER_FIELD_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,
+)
+
+
+_SHORT_SAME_BASELINE_PREFIX_RE = re.compile(
+ r"^(?:[((]\s*\d{1,3}|\d{1,2}\s*[::]\s*\d{2})$",
+)
+
+
+def _merge_internal_text_block_group(
+ blocks: list[dict[str, Any]],
+ indices: list[int],
+ *,
+ preserve_visual_spaces: bool = False,
+) -> dict[str, Any]:
+ """合并内部文本块及其版面元数据,最终输出阶段仍会统一移除这些字段。"""
+
+ ordered_indices = sorted(
+ indices,
+ key=(
+ (lambda index: blocks[index]["bbox"][0])
+ if preserve_visual_spaces
+ else (lambda index: _text_component_sort_key(blocks[index]))
+ ),
+ )
+ merged = dict(blocks[ordered_indices[0]])
+ merged["bbox"] = _bbox_union_many([blocks[index]["bbox"] for index in ordered_indices])
+ contents = [str(blocks[index].get("content", "")) for index in ordered_indices]
+ merged["content"] = (
+ " ".join(content.strip() for content in contents if content.strip())
+ if preserve_visual_spaces
+ else _merge_text_line_content(contents)
+ )
+ merged["_visual_row_ids"] = set().union(
+ *[row_ids for index in ordered_indices if isinstance((row_ids := blocks[index].get("_visual_row_ids")), set)]
+ )
+ merged["_single_run_row_id"] = None
+ merged["_local_line_bboxes"] = [bbox for index in ordered_indices for bbox in blocks[index].get("_local_line_bboxes", [])]
+ merged["_local_output_line_bboxes"] = [
+ bbox for index in ordered_indices for bbox in blocks[index].get("_local_output_line_bboxes", [])
+ ]
+ merged["_output_bbox_repaired"] = any(blocks[index].get("_output_bbox_repaired") is True for index in ordered_indices)
+ merged["_line_heights"] = [height for index in ordered_indices for height in blocks[index].get("_line_heights", [])]
+ merged["_font_signatures"] = set().union(
+ *[
+ signatures
+ for index in ordered_indices
+ if isinstance(
+ (signatures := blocks[index].get("_font_signatures")),
+ set,
+ )
+ ]
+ )
+ merged["_inline_math_regions"] = [
+ region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
+ ]
+ merged[_PARAGRAPH_FORMULA_CONTEXT_MARKER] = any(
+ blocks[index].get(_PARAGRAPH_FORMULA_CONTEXT_MARKER) is True for index in ordered_indices
+ )
+ return merged
+
+
+def _component_declared_lane_interval(
+ block: dict[str, Any],
+) -> tuple[float, float] | None:
+ """读取组件声明的有效栏带区间,不区分普通栏或跨栏。"""
+
+ interval = block.get("_lane_interval")
+ if (
+ not isinstance(interval, (list, tuple))
+ or len(interval) != 2
+ or not all(isinstance(value, (int, float)) for value in interval)
+ ):
+ return None
+ left, right = float(interval[0]), float(interval[1])
+ return (left, right) if right > left else None
+
+
+def _component_lane_interval(
+ block: dict[str, Any],
+) -> tuple[float, float] | None:
+ """读取普通文本组件所属的有效非跨栏栏带区间。"""
+
+ if block.get("_lane_is_span") is not False:
+ return None
+ return _component_declared_lane_interval(block)
+
+
+def _component_reference_width(
+ block: dict[str, Any],
+ local_page_width: float,
+) -> float:
+ """优先返回组件的局部栏宽,缺少可靠栏带时回退页面宽度。"""
+
+ interval = _component_lane_interval(block)
+ return interval[1] - interval[0] if interval is not None else local_page_width
+
+
+def _compatible_component_lane_width(
+ first_block: dict[str, Any],
+ second_block: dict[str, Any],
+ local_page_width: float,
+ median_height: float,
+) -> float:
+ """同一局部栏带的两个组件使用栏宽,否则继续使用页面宽度。"""
+
+ first_interval = _component_lane_interval(first_block)
+ second_interval = _component_lane_interval(second_block)
+ if first_interval is None or second_interval is None:
+ return local_page_width
+ tolerance = 0.75 * median_height
+ if abs(first_interval[0] - second_interval[0]) > tolerance or abs(first_interval[1] - second_interval[1]) > tolerance:
+ return local_page_width
+ return min(
+ first_interval[1] - first_interval[0],
+ second_interval[1] - second_interval[0],
+ )
+
+
+def _components_share_lane_role(
+ first_block: dict[str, Any],
+ second_block: dict[str, Any],
+ median_height: float,
+) -> bool:
+ """要求二次合并组件同为跨栏或属于同一普通栏带。"""
+
+ first_role = first_block.get("_lane_is_span")
+ second_role = second_block.get("_lane_is_span")
+ if isinstance(first_role, bool) and isinstance(second_role, bool):
+ if first_role != second_role:
+ return False
+ if first_role:
+ return True
+ first_interval = _component_lane_interval(first_block)
+ second_interval = _component_lane_interval(second_block)
+ if first_interval is None or second_interval is None:
+ return False
+ tolerance = 0.75 * median_height
+ return (
+ abs(first_interval[0] - second_interval[0]) <= tolerance
+ and abs(first_interval[1] - second_interval[1]) <= tolerance
+ )
+ # 兼容缺少内部栏元数据的旧调用;生产路径始终会携带该字段。
+ return not isinstance(first_role, bool) and not isinstance(second_role, bool)
+
+
+def _block_starts_with_short_wide_rows(
+ block: dict[str, Any],
+ local_page_width: float,
+) -> bool:
+ """判断组件内部是否以短首行和紧邻宽正文形成明确分组起点。"""
+
+ line_bboxes = block.get("_local_line_bboxes")
+ if not isinstance(line_bboxes, list) or len(line_bboxes) < 2:
+ return False
+ first_bbox, second_bbox = line_bboxes[:2]
+ first_width = first_bbox[2] - first_bbox[0]
+ second_width = second_bbox[2] - second_bbox[0]
+ reference_width = _component_reference_width(block, local_page_width)
+ return first_width <= 0.35 * reference_width and second_width >= max(0.25 * reference_width, 1.8 * first_width)
+
+
+def _find_short_opener_pairs(
+ blocks: list[dict[str, Any]],
+ candidate_indices: list[int],
+ local_page_width: float,
+ median_height: float,
+) -> list[tuple[int, int]]:
+ """查找跨栏拆开的短首行与紧邻满宽正文组件。"""
+
+ output: list[tuple[int, int]] = []
+ for opener_index in candidate_indices:
+ opener_bboxes = blocks[opener_index]["_local_line_bboxes"]
+ if len(opener_bboxes) != 1:
+ continue
+ opener_bbox = opener_bboxes[0]
+ opener_width = opener_bbox[2] - opener_bbox[0]
+ matches: list[tuple[float, int]] = []
+ for body_index in candidate_indices:
+ if body_index == opener_index:
+ continue
+ if blocks[body_index].get("_hard_break_before") is True:
+ continue
+ if not _components_share_lane_role(
+ blocks[opener_index],
+ blocks[body_index],
+ median_height,
+ ):
+ continue
+ body_bbox = blocks[body_index]["_local_line_bboxes"][0]
+ gap = body_bbox[1] - opener_bbox[3]
+ body_width = body_bbox[2] - body_bbox[0]
+ reference_width = _compatible_component_lane_width(
+ blocks[opener_index],
+ blocks[body_index],
+ local_page_width,
+ median_height,
+ )
+ if (
+ not 0.0 <= gap <= 0.75 * median_height
+ or abs(body_bbox[0] - opener_bbox[0]) > 0.75 * median_height
+ or opener_width > 0.35 * reference_width
+ or body_width < 0.6 * reference_width
+ or _component_connection_skips_block(
+ blocks,
+ opener_index,
+ body_index,
+ median_height,
+ )
+ ):
+ continue
+ matches.append((gap, body_index))
+ if matches:
+ output.append((opener_index, min(matches)[1]))
+ return output
+
+
+def _nearest_following_text_component(
+ blocks: list[dict[str, Any]],
+ current_index: int,
+ candidate_indices: list[int],
+ *,
+ maximum_gap: float,
+ section_starts: set[int],
+) -> int | None:
+ """返回同一水平流中紧邻且不是新分组起点的下一正文组件。"""
+
+ current_bbox = blocks[current_index]["_local_line_bboxes"][-1]
+ matches: list[tuple[float, float, int]] = []
+ for candidate_index in candidate_indices:
+ if candidate_index == current_index or candidate_index in section_starts:
+ continue
+ if blocks[candidate_index].get("_hard_break_before") is True:
+ continue
+ if not _components_share_lane_role(
+ blocks[current_index],
+ blocks[candidate_index],
+ maximum_gap / 0.75,
+ ):
+ continue
+ candidate_bbox = blocks[candidate_index]["_local_line_bboxes"][0]
+ gap = candidate_bbox[1] - current_bbox[3]
+ if not -0.25 * maximum_gap <= gap <= maximum_gap:
+ continue
+ overlap = _bbox_axis_overlap_ratio(current_bbox, candidate_bbox, axis="x")
+ left_gap = abs(candidate_bbox[0] - current_bbox[0])
+ if overlap < 0.5 and left_gap > 3.0 * maximum_gap:
+ continue
+ if _component_connection_skips_block(
+ blocks,
+ current_index,
+ candidate_index,
+ maximum_gap / 0.75,
+ ):
+ continue
+ matches.append((max(0.0, gap), left_gap, candidate_index))
+ return min(matches)[2] if matches else None
+
+
+def _has_parallel_text_component(
+ blocks: list[dict[str, Any]],
+ current_index: int,
+ candidate_indices: list[int],
+) -> bool:
+ """检查当前组件同一纵向带内是否存在水平分离的并栏组件。"""
+
+ current_bbox = blocks[current_index]["bbox"]
+ for candidate_index in candidate_indices:
+ if candidate_index == current_index:
+ continue
+ candidate_bbox = blocks[candidate_index]["bbox"]
+ vertical_overlap = max(
+ 0.0,
+ min(current_bbox[3], candidate_bbox[3]) - max(current_bbox[1], candidate_bbox[1]),
+ )
+ horizontally_separate = candidate_bbox[0] >= current_bbox[2] or current_bbox[0] >= candidate_bbox[2]
+ if vertical_overlap > 0 and horizontally_separate:
+ return True
+ return False
+
+
+def _nearest_tapered_tail_component(
+ blocks: list[dict[str, Any]],
+ current_index: int,
+ candidate_indices: list[int],
+ median_height: float,
+ section_starts: set[int],
+) -> int | None:
+ """查找左对齐、行宽递减且行距略大的信息组尾行组件。"""
+
+ previous_bbox = blocks[current_index]["_local_line_bboxes"][-1]
+ previous_width = previous_bbox[2] - previous_bbox[0]
+ matches: list[tuple[float, int]] = []
+ for candidate_index in candidate_indices:
+ if candidate_index == current_index or candidate_index in section_starts:
+ continue
+ if blocks[candidate_index].get("_hard_break_before") is True:
+ continue
+ if not _components_share_lane_role(
+ blocks[current_index],
+ blocks[candidate_index],
+ median_height,
+ ):
+ continue
+ candidate_bboxes = blocks[candidate_index]["_local_line_bboxes"]
+ first_bbox = candidate_bboxes[0]
+ last_bbox = candidate_bboxes[-1]
+ gap = first_bbox[1] - previous_bbox[3]
+ first_width = first_bbox[2] - first_bbox[0]
+ last_width = last_bbox[2] - last_bbox[0]
+ if (
+ not 0.75 * median_height < gap <= 1.5 * median_height
+ or len(candidate_bboxes) > 2
+ or abs(first_bbox[0] - previous_bbox[0]) > 0.75 * median_height
+ or first_width > 0.85 * previous_width
+ or last_width > first_width + 0.5 * median_height
+ or _component_connection_skips_block(
+ blocks,
+ current_index,
+ candidate_index,
+ median_height,
+ )
+ ):
+ continue
+ matches.append((gap, candidate_index))
+ return min(matches)[1] if matches else None
+
+
+def _component_connection_skips_block(
+ blocks: list[dict[str, Any]],
+ first_index: int,
+ second_index: int,
+ median_height: float,
+) -> bool:
+ """检查两个正文组件之间是否已有同水平流的中间块,禁止二次合并跨越它。"""
+
+ first_bbox = blocks[first_index]["_local_line_bboxes"][-1]
+ second_bbox = blocks[second_index]["_local_line_bboxes"][0]
+ first_center = _bbox_center_y(first_bbox)
+ second_center = _bbox_center_y(second_bbox)
+ corridor_top, corridor_bottom = sorted((first_center, second_center))
+ corridor_bbox = (
+ min(first_bbox[0], second_bbox[0]),
+ corridor_top,
+ max(first_bbox[2], second_bbox[2]),
+ corridor_bottom,
+ )
+ for index, block in enumerate(blocks):
+ if index in {first_index, second_index}:
+ continue
+ local_bboxes = block.get("_local_line_bboxes")
+ if not isinstance(local_bboxes, list) or not local_bboxes:
+ continue
+ other_bbox = local_bboxes[0]
+ other_center = _bbox_center_y(other_bbox)
+ if not (corridor_top + 0.1 * median_height < other_center < corridor_bottom - 0.1 * median_height):
+ continue
+ if _bbox_axis_overlap_ratio(corridor_bbox, other_bbox, axis="x") >= 0.2:
+ return True
+ return False
+
+
+def _text_component_sort_key(block: dict[str, Any]) -> tuple[float, float]:
+ """返回正文组件按局部首行位置排序的稳定键。"""
+
+ first_bbox = block["_local_line_bboxes"][0]
+ return first_bbox[1], first_bbox[0]
+
+
+def _merge_text_line_content(line_texts: Sequence[str]) -> str:
+ """按 Hybrid 语言与行末连字规则折叠普通文本行。"""
+
+ normalized_lines = [_normalize_native_run_text(str(text or "")) for text in line_texts]
+ normalized_lines = [text for text in normalized_lines if text]
+ if not normalized_lines:
+ return ""
+ try:
+ block_language = detect_lang("".join(normalized_lines))
+ except Exception:
+ block_language = ""
+ return merge_text_line_contents(
+ normalized_lines,
+ block_language=block_language,
+ )
+
+
+__all__ = [
+ "_REFERENCE_ENTRY_RE",
+ "_FIGURE_CAPTION_MARKER_RE",
+ "_INLINE_MATH_RECOVERY_MARKER",
+ "_PARAGRAPH_FORMULA_CONTEXT_MARKER",
+ "_FRONT_MATTER_FIELD_RE",
+ "_LIST_ITEM_RE",
+ "_BULLET_ITEM_RE",
+ "_EMAIL_METADATA_RE",
+ "_ABSTRACT_METADATA_RE",
+ "_LABELLED_METADATA_RE",
+ "_URL_LINE_RE",
+ "_SHORT_SAME_BASELINE_PREFIX_RE",
+ "_merge_internal_text_block_group",
+ "_component_declared_lane_interval",
+ "_component_lane_interval",
+ "_component_reference_width",
+ "_compatible_component_lane_width",
+ "_components_share_lane_role",
+ "_block_starts_with_short_wide_rows",
+ "_find_short_opener_pairs",
+ "_nearest_following_text_component",
+ "_has_parallel_text_component",
+ "_nearest_tapered_tail_component",
+ "_component_connection_skips_block",
+ "_text_component_sort_key",
+ "_merge_text_line_content",
+]
diff --git a/mineru/model/flash/pdf/text_assembly/footnotes.py b/mineru/model/flash/pdf/text_assembly/footnotes.py
new file mode 100644
index 00000000..7b3ea10a
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/footnotes.py
@@ -0,0 +1,405 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""按来源行和标记组装页面脚注。"""
+
+from __future__ import annotations
+
+import statistics
+from typing import Any, Sequence
+
+from .....types import BBox
+from ..geometry import (
+ _bbox_center_y,
+ _bbox_union_many,
+ _rotate_bbox_from_upright,
+ _rotate_bbox_to_upright,
+)
+from ..line_layout import (
+ _effective_text_row_gap,
+ _line_effective_height,
+ _lines_tight_output_bbox,
+ _title_fonts_compatible,
+)
+from ..models import _LineItem
+from .common import _merge_text_line_content
+
+
+def _build_grouped_page_footnote_blocks(
+ lines: list[_LineItem],
+ source_groups: Sequence[set[int]],
+ page_size: tuple[float, float],
+) -> tuple[list[dict[str, Any]], set[int]]:
+ """按分隔线组切分几何脚注条目,并返回已消费的来源编号。"""
+
+ footnote_by_source = {line.source_index: line for line in lines if line.semantic_type == "page_footnote"}
+ blocks: list[dict[str, Any]] = []
+ consumed_source_indices: set[int] = set()
+ for source_group in source_groups:
+ group_lines = [footnote_by_source[source_index] for source_index in source_group if source_index in footnote_by_source]
+ for angle in sorted({line.angle for line in group_lines}):
+ directional_lines = [line for line in group_lines if line.angle == angle]
+ tight_bboxes = _tight_page_footnote_bboxes(
+ directional_lines,
+ page_size,
+ )
+ for entry_lines in _split_page_footnote_entries(
+ directional_lines,
+ page_size,
+ ):
+ ordered_lines = sorted(
+ entry_lines,
+ key=lambda line: (
+ _rotate_bbox_to_upright(line.bbox, page_size, angle)[1],
+ _rotate_bbox_to_upright(line.bbox, page_size, angle)[0],
+ line.source_index,
+ ),
+ )
+ content = _merge_text_line_content([line.text for line in ordered_lines])
+ if not content:
+ continue
+ visual_row_ids = {line.visual_row_id for line in ordered_lines if line.visual_row_id is not None}
+ single_run_row_id = (
+ ordered_lines[0].visual_row_id
+ if len(ordered_lines) == 1
+ and ordered_lines[0].split_from_row
+ and ordered_lines[0].visual_row_id is not None
+ else None
+ )
+ block = {
+ "type": "page_footnote",
+ "bbox": _bbox_union_many([tight_bboxes[line.source_index] for line in ordered_lines]),
+ "angle": angle,
+ "content": content,
+ "_visual_row_ids": visual_row_ids,
+ "_single_run_row_id": single_run_row_id,
+ "_inline_math_regions": [region for line in ordered_lines for region in line.inline_math_regions],
+ }
+ tight_output_bbox = _lines_tight_output_bbox(
+ ordered_lines,
+ page_size,
+ )
+ if tight_output_bbox is not None:
+ block["_tight_output_bbox"] = tight_output_bbox
+ blocks.append(block)
+ consumed_source_indices.update(line.source_index for line in ordered_lines)
+ return blocks, consumed_source_indices
+
+
+def _split_page_footnote_entries(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+) -> list[list[_LineItem]]:
+ """按首行或续行缩进模式,把同一分隔线下的脚注行切成条目。"""
+
+ if not lines:
+ return []
+ angle = lines[0].angle
+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines]
+ line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ if len(line_geometry) == 1:
+ return [[line_geometry[0][0]]]
+
+ effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]
+ median_height = statistics.median(effective_heights)
+ glyph_widths = [line.median_glyph_width for line, _bbox in line_geometry if line.median_glyph_width is not None]
+ median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.5 * median_height
+ 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 marker_rows:
+ 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]))
+ if not marker_rows:
+ marker_rows = _find_geometric_page_footnote_marker_rows(
+ line_geometry,
+ median_height,
+ median_glyph_width,
+ base_left,
+ )
+ return marker_rows
+
+
+def _find_geometric_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]]]:
+ """在 row id 缺失时用同基线窄标记和右侧正文恢复脚注首行。"""
+
+ marker_width_limit = max(
+ 1.5 * median_glyph_width,
+ 0.75 * median_height,
+ )
+ candidates: list[
+ tuple[
+ float,
+ tuple[_LineItem, BBox],
+ tuple[_LineItem, BBox],
+ ]
+ ] = []
+ for marker in line_geometry:
+ marker_width = marker[1][2] - marker[1][0]
+ if marker_width > marker_width_limit or marker[1][0] - base_left > 0.5 * median_height:
+ continue
+ for body in line_geometry:
+ if body is marker:
+ continue
+ body_width = body[1][2] - body[1][0]
+ horizontal_gap = body[1][0] - marker[1][2]
+ if (
+ not 0.0 <= horizontal_gap <= 1.5 * median_height
+ or body[1][0] - base_left
+ < max(
+ 1.5 * marker_width,
+ 0.4 * 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
+ or not _title_fonts_compatible(
+ marker[0],
+ body[0],
+ )
+ ):
+ continue
+ candidates.append(
+ (
+ horizontal_gap,
+ marker,
+ body,
+ )
+ )
+
+ output = []
+ consumed_sources: set[int] = set()
+ for _gap, marker, body in sorted(
+ candidates,
+ key=lambda item: (
+ min(item[1][1][1], item[2][1][1]),
+ item[0],
+ item[1][0].source_index,
+ item[2][0].source_index,
+ ),
+ ):
+ pair_sources = {
+ marker[0].source_index,
+ body[0].source_index,
+ }
+ if pair_sources & consumed_sources:
+ continue
+ output.append((marker, body))
+ consumed_sources.update(pair_sources)
+ return output
+
+
+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]]]
+ for previous, current in zip(line_geometry, line_geometry[1:]):
+ previous_width = previous[1][2] - previous[1][0]
+ previous_is_near_full = previous_width >= 0.8 * maximum_row_width
+ current_is_indented = current[1][0] - base_left > indent_threshold
+ same_left_compact_continuation = (
+ not first_line_is_indented
+ and previous_width >= 0.7 * maximum_row_width
+ and abs(current[1][0] - previous[1][0]) <= 0.5 * indent_threshold
+ and _title_fonts_compatible(previous[0], current[0])
+ and _effective_text_row_gap(previous, current) <= indent_threshold
+ )
+ # 满行后必然续接;其余行按首页观测到的首行/续行缩进模式决定边界。
+ continues_previous = (
+ previous_is_near_full
+ or same_left_compact_continuation
+ or (not current_is_indented if first_line_is_indented else current_is_indented)
+ )
+ if continues_previous:
+ entries[-1].append(current[0])
+ else:
+ entries.append([current[0]])
+ return entries
+
+
+def _tight_page_footnote_bboxes(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+) -> dict[int, BBox]:
+ """以有效行高和相邻行距收紧脚注框,避免异常字体框跨入相邻条目。"""
+
+ if not lines:
+ return {}
+ angle = lines[0].angle
+ line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines]
+ line_geometry.sort(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 line_geometry)
+ row_pitches = [
+ current[1][1] - previous[1][1]
+ for previous, current in zip(line_geometry, line_geometry[1:])
+ if current[1][1] - previous[1][1] > 0.25 * median_height
+ ]
+ median_pitch = statistics.median(row_pitches) if row_pitches else None
+
+ output: dict[int, BBox] = {}
+ for line, bbox in line_geometry:
+ tight_height = min(
+ bbox[3] - bbox[1],
+ _line_effective_height(line, bbox),
+ )
+ if median_pitch is not None:
+ tight_height = min(tight_height, 0.9 * median_pitch)
+ tight_height = max(0.1, tight_height)
+ center_y = _bbox_center_y(bbox)
+ tight_local_bbox = (
+ bbox[0],
+ center_y - 0.5 * tight_height,
+ bbox[2],
+ center_y + 0.5 * tight_height,
+ )
+ output[line.source_index] = _rotate_bbox_from_upright(
+ tight_local_bbox,
+ page_size,
+ angle,
+ )
+ return output
+
+
+__all__ = [
+ "_build_grouped_page_footnote_blocks",
+ "_split_page_footnote_entries",
+ "_find_page_footnote_marker_rows",
+ "_find_geometric_page_footnote_marker_rows",
+ "_split_marked_page_footnote_entries",
+ "_split_unmarked_page_footnote_entries",
+ "_tight_page_footnote_bboxes",
+]
diff --git a/mineru/model/flash/pdf/text_assembly/merging.py b/mineru/model/flash/pdf/text_assembly/merging.py
new file mode 100644
index 00000000..e06211d4
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/merging.py
@@ -0,0 +1,1280 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""合并正文、公式上下文和列表引导块的空间组件。"""
+
+from __future__ import annotations
+
+import re
+import statistics
+from typing import Any
+
+from .....types import BBox
+from ..geometry import (
+ _bbox_axis_overlap_ratio,
+ _bbox_center_y,
+ _bbox_union_many,
+ _rotate_bbox_from_upright,
+)
+from .common import (
+ _FIGURE_CAPTION_MARKER_RE,
+ _INLINE_MATH_RECOVERY_MARKER,
+ _LABELLED_METADATA_RE,
+ _LIST_ITEM_RE,
+ _PARAGRAPH_FORMULA_CONTEXT_MARKER,
+ _SHORT_SAME_BASELINE_PREFIX_RE,
+ _URL_LINE_RE,
+ _block_starts_with_short_wide_rows,
+ _compatible_component_lane_width,
+ _component_connection_skips_block,
+ _component_declared_lane_interval,
+ _component_lane_interval,
+ _components_share_lane_role,
+ _find_short_opener_pairs,
+ _has_parallel_text_component,
+ _merge_internal_text_block_group,
+ _merge_text_line_content,
+ _nearest_following_text_component,
+ _nearest_tapered_tail_component,
+ _text_component_sort_key,
+)
+
+
+def _merge_short_same_baseline_prefix_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """合并括号序号或时刻等短前缀与右侧同基线正文。"""
+
+ replacements: dict[int, dict[str, Any]] = {}
+ consumed: set[int] = set()
+ for prefix_index, prefix in enumerate(blocks):
+ prefix_rows = prefix.get("_local_line_bboxes")
+ prefix_content = str(prefix.get("content") or "").strip()
+ if (
+ prefix_index in consumed
+ or prefix.get("type") != "text"
+ or not isinstance(prefix_rows, list)
+ or len(prefix_rows) != 1
+ or _SHORT_SAME_BASELINE_PREFIX_RE.match(prefix_content) is None
+ ):
+ continue
+ prefix_bbox = prefix_rows[0]
+ prefix_heights = [
+ float(height)
+ for height in prefix.get("_line_heights", [])
+ if isinstance(height, (int, float)) and float(height) > 0
+ ]
+ prefix_height = statistics.median(prefix_heights) if prefix_heights else max(0.1, prefix_bbox[3] - prefix_bbox[1])
+ angle = int(prefix.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ matches: list[tuple[float, int]] = []
+ for host_index, host in enumerate(blocks):
+ host_rows = host.get("_local_line_bboxes")
+ if (
+ host_index == prefix_index
+ or host_index in consumed
+ or host.get("type") != "text"
+ or int(host.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(host_rows, list)
+ or not host_rows
+ ):
+ continue
+ host_bbox = host_rows[0]
+ host_width = host_bbox[2] - host_bbox[0]
+ horizontal_gap = host_bbox[0] - prefix_bbox[2]
+ if (
+ host_bbox[0] < prefix_bbox[2]
+ or horizontal_gap > 1.25 * prefix_height
+ or host_width < 0.15 * local_page_width
+ or _bbox_axis_overlap_ratio(
+ prefix_bbox,
+ host_bbox,
+ axis="y",
+ )
+ < 0.5
+ ):
+ continue
+ matches.append((horizontal_gap, host_index))
+ if not matches:
+ continue
+ _gap, host_index = min(matches)
+ replacement_index = min(prefix_index, host_index)
+ replacement = _merge_internal_text_block_group(
+ blocks,
+ [prefix_index, host_index],
+ preserve_visual_spaces=True,
+ )
+ replacement["type"] = "text"
+ replacements[replacement_index] = replacement
+ consumed.update({prefix_index, host_index})
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+def _blocks_share_boundary_visual_row(
+ first: dict[str, Any],
+ second: dict[str, Any],
+ pair_height: float,
+) -> bool:
+ """检查前块末行与后块首行是否为被错误切开的同一视觉行。"""
+
+ first_rows = first.get("_local_line_bboxes")
+ second_rows = second.get("_local_line_bboxes")
+ if (
+ not isinstance(first_rows, list)
+ or not isinstance(second_rows, list)
+ or max(len(first_rows), len(second_rows)) < 3
+ or len(first_rows) + len(second_rows) > 6
+ or not _components_share_lane_role(first, second, pair_height)
+ ):
+ return False
+ if first["bbox"][1] <= second["bbox"][1]:
+ upper_rows, lower_rows = first_rows, second_rows
+ else:
+ upper_rows, lower_rows = second_rows, first_rows
+ upper_boundary = max(upper_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
+ lower_boundary = min(lower_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
+ vertical_overlap = max(
+ 0.0,
+ min(upper_boundary[3], lower_boundary[3]) - max(upper_boundary[1], lower_boundary[1]),
+ )
+ shorter_height = max(
+ 0.1,
+ min(
+ upper_boundary[3] - upper_boundary[1],
+ lower_boundary[3] - lower_boundary[1],
+ ),
+ )
+ horizontal_gap = lower_boundary[0] - upper_boundary[2]
+ union_bbox = _bbox_union_many([first["bbox"], second["bbox"]])
+ return (
+ vertical_overlap / shorter_height >= 0.7
+ and -0.2 * pair_height <= horizontal_gap <= 0.75 * pair_height
+ and union_bbox[3] - union_bbox[1] <= 6.0 * pair_height
+ )
+
+
+def _merge_overlapping_same_line_text_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """合并块体或边界视觉行重叠的宽正文块,修复错误分栏。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for first_index, first in enumerate(blocks):
+ first_bbox = first.get("bbox")
+ first_rows = first.get("_local_line_bboxes")
+ angle = int(first.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ if (
+ first_index in consumed
+ or first.get("type") != "text"
+ or not isinstance(first_bbox, (list, tuple))
+ or not isinstance(first_rows, list)
+ or not 1 <= len(first_rows) <= 5
+ or first_bbox[2] - first_bbox[0] < 0.3 * local_page_width
+ ):
+ continue
+ first_heights = [
+ float(height) for height in first.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
+ ]
+ first_height = statistics.median(first_heights) if first_heights else first_bbox[3] - first_bbox[1]
+ for second_index in range(first_index + 1, len(blocks)):
+ second = blocks[second_index]
+ second_bbox = second.get("bbox")
+ second_rows = second.get("_local_line_bboxes")
+ if (
+ second_index in consumed
+ or second.get("type") != "text"
+ or int(second.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(second_bbox, (list, tuple))
+ or not isinstance(second_rows, list)
+ or not 1 <= len(second_rows) <= 5
+ 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
+ ]
+ second_height = statistics.median(second_heights) if second_heights else second_bbox[3] - second_bbox[1]
+ pair_height = max(first_height, second_height, 0.1)
+ vertical_overlap = max(
+ 0.0,
+ min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]),
+ )
+ minimum_box_height = max(
+ 0.1,
+ min(
+ first_bbox[3] - first_bbox[1],
+ second_bbox[3] - second_bbox[1],
+ ),
+ )
+ first_fonts = first.get("_font_signatures")
+ second_fonts = second.get("_font_signatures")
+ fonts_conflict = (
+ isinstance(first_fonts, set)
+ and isinstance(second_fonts, set)
+ and first_fonts
+ and second_fonts
+ and first_fonts.isdisjoint(second_fonts)
+ )
+ compact_overlap = (
+ len(first_rows) <= 2
+ and len(second_rows) <= 2
+ and min(len(first_rows), len(second_rows)) == 1
+ and abs(first_bbox[0] - second_bbox[0]) <= pair_height
+ and vertical_overlap / minimum_box_height >= 0.5
+ and _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x") >= 0.75
+ )
+ boundary_overlap = _blocks_share_boundary_visual_row(
+ first,
+ second,
+ pair_height,
+ )
+ if fonts_conflict or not (compact_overlap or boundary_overlap):
+ continue
+ union_bbox = _bbox_union_many([first_bbox, second_bbox])
+ if not boundary_overlap and union_bbox[3] - union_bbox[1] > 4.0 * pair_height:
+ continue
+ replacement_index = min(first_index, second_index)
+ replacements[replacement_index] = _merge_internal_text_block_group(
+ blocks,
+ [first_index, second_index],
+ )
+ consumed.update({first_index, second_index})
+ break
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+def _merge_inline_math_fragment_text_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把同一宽正文行上下叠放的多个小数学碎片收回一个文本块。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for host_index, host in enumerate(blocks):
+ host_bbox = host.get("bbox")
+ host_heights = host.get("_line_heights")
+ host_rows = host.get("_local_line_bboxes")
+ angle = int(host.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ if (
+ host_index in consumed
+ or host.get("type") != "text"
+ or (host.get("_single_run_row_id") is None and (not isinstance(host_rows, list) or len(host_rows) > 2))
+ or not isinstance(host_bbox, (list, tuple))
+ or host_bbox[2] - host_bbox[0] < 0.35 * local_page_width
+ or not isinstance(host_heights, list)
+ or not host_heights
+ ):
+ continue
+ host_height = statistics.median(
+ float(height) for height in host_heights if isinstance(height, (int, float)) and height > 0
+ )
+ fragment_indices: list[int] = []
+ for candidate_index, candidate in enumerate(blocks):
+ candidate_bbox = candidate.get("bbox")
+ candidate_rows = candidate.get("_local_line_bboxes")
+ if (
+ candidate_index == host_index
+ or candidate_index in consumed
+ or candidate.get("type") != "text"
+ or int(candidate.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(candidate_bbox, (list, tuple))
+ or not isinstance(candidate_rows, list)
+ or len(candidate_rows) != 1
+ or candidate_bbox[2] - candidate_bbox[0] > 0.25 * (host_bbox[2] - host_bbox[0])
+ or _bbox_axis_overlap_ratio(
+ host_bbox,
+ candidate_bbox,
+ axis="x",
+ )
+ <= 0.0
+ ):
+ continue
+ union_bbox = _bbox_union_many([host_bbox, candidate_bbox])
+ vertical_gap = max(
+ 0.0,
+ max(host_bbox[1], candidate_bbox[1]) - min(host_bbox[3], candidate_bbox[3]),
+ )
+ if vertical_gap <= 0.75 * host_height and union_bbox[3] - union_bbox[1] <= 3.5 * host_height:
+ fragment_indices.append(candidate_index)
+ if len(fragment_indices) < 2:
+ continue
+ group_indices = [host_index, *fragment_indices]
+ replacement_index = min(group_indices)
+ replacements[replacement_index] = _merge_inline_math_recovery_group(
+ blocks,
+ group_indices,
+ )
+ consumed.update(group_indices)
+ output = [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+ output = _merge_hostless_inline_math_fragment_blocks(output, page_size)
+ output = _merge_residual_narrow_math_text_blocks(output, page_size)
+ return _merge_inline_math_paragraph_continuations(output, page_size)
+
+
+def _component_local_union_bbox(
+ block: dict[str, Any],
+) -> BBox | None:
+ """合并正文组件持有的正向行框,非法或缺失元数据时返回空。"""
+
+ rows = block.get("_local_line_bboxes")
+ if not isinstance(rows, list):
+ return None
+ bboxes: list[BBox] = []
+ for row in rows:
+ if not isinstance(row, (list, tuple)) or len(row) != 4:
+ continue
+ try:
+ bbox = tuple(float(value) for value in row)
+ except (TypeError, ValueError):
+ continue
+ if bbox[2] > bbox[0] and bbox[3] > bbox[1]:
+ bboxes.append(bbox) # type: ignore[arg-type]
+ return _bbox_union_many(bboxes) if bboxes else None
+
+
+def _merge_paragraph_formula_context_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把误似行间公式的复杂行内分式与同栏前后正文恢复成一个块。"""
+
+ terminal_re = re.compile(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ )
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ seed_indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text" and block.get(_PARAGRAPH_FORMULA_CONTEXT_MARKER) is True
+ ]
+ for seed_index in seed_indices:
+ if seed_index in consumed:
+ continue
+ group = {seed_index}
+ changed = True
+ while changed:
+ changed = False
+ for candidate_index, candidate in enumerate(blocks):
+ if candidate_index in group or candidate_index in consumed or candidate.get("type") != "text":
+ continue
+ for member_index in group:
+ member = blocks[member_index]
+ if int(candidate.get("angle", 0) or 0) % 360 != int(member.get("angle", 0) or 0) % 360:
+ continue
+ pair_heights = [
+ float(height)
+ for block in (candidate, member)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and float(height) > 0
+ ]
+ if not pair_heights:
+ continue
+ pair_height = statistics.median(pair_heights)
+ if not _components_share_lane_role(
+ candidate,
+ member,
+ pair_height,
+ ):
+ continue
+ candidate_bbox = _component_local_union_bbox(candidate)
+ member_bbox = _component_local_union_bbox(member)
+ if candidate_bbox is None or member_bbox is None:
+ continue
+ vertical_gap = max(
+ candidate_bbox[1] - member_bbox[3],
+ member_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ if vertical_gap > 1.5 * pair_height:
+ continue
+ candidate_below = candidate_bbox[1] >= member_bbox[3]
+ member_below = member_bbox[1] >= candidate_bbox[3]
+ if candidate_below and (
+ candidate.get("_hard_break_before") is True
+ or terminal_re.search(str(member.get("content") or "").rstrip()) is not None
+ ):
+ continue
+ if member_below and (
+ member.get("_hard_break_before") is True
+ or terminal_re.search(str(candidate.get("content") or "").rstrip()) is not None
+ ):
+ continue
+ group.add(candidate_index)
+ changed = True
+ break
+ if changed:
+ break
+ if len(group) < 2:
+ continue
+ ordered_group = sorted(group)
+ replacement_index = min(ordered_group)
+ merged = _merge_internal_text_block_group(
+ blocks,
+ ordered_group,
+ )
+ local_rows = [
+ bbox for bbox in merged.get("_local_line_bboxes", []) if isinstance(bbox, (list, tuple)) and len(bbox) == 4
+ ]
+ maximum_width = max(
+ (bbox[2] - bbox[0] for bbox in local_rows),
+ default=0.0,
+ )
+ body_rows = [bbox for bbox in local_rows if bbox[2] - bbox[0] >= 0.75 * maximum_width]
+ if len(body_rows) >= 2:
+ # 复杂分式可能比正文左缘多探出少量 glyph;公开框按重复满行边界稳定收口。
+ local_merged_bbox = _bbox_union_many(local_rows)
+ local_output_bbox = (
+ min(bbox[0] for bbox in body_rows),
+ local_merged_bbox[1],
+ max(bbox[2] for bbox in body_rows),
+ local_merged_bbox[3],
+ )
+ merged["bbox"] = _rotate_bbox_from_upright(
+ local_output_bbox,
+ page_size,
+ int(merged.get("angle", 0) or 0) % 360,
+ )
+ replacements[replacement_index] = merged
+ 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_residual_narrow_math_text_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把仍嵌在宽正文行范围内的单个窄数学碎片吸收到唯一宿主块。"""
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for candidate_index, candidate in enumerate(blocks):
+ candidate_bbox = candidate.get("bbox")
+ candidate_rows = candidate.get("_local_line_bboxes")
+ angle = int(candidate.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ if (
+ candidate.get("type") != "text"
+ or not isinstance(candidate_bbox, (list, tuple))
+ or not isinstance(candidate_rows, list)
+ or len(candidate_rows) != 1
+ or candidate_bbox[2] - candidate_bbox[0] > 0.05 * local_page_width
+ ):
+ continue
+ candidate_heights = [
+ float(height) for height in candidate.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
+ ]
+ candidate_height = statistics.median(candidate_heights) if candidate_heights else candidate_bbox[3] - candidate_bbox[1]
+ hosts: list[tuple[float, float, int]] = []
+ for host_index, host in enumerate(blocks):
+ host_bbox = host.get("bbox")
+ host_heights = [
+ float(height) for height in host.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
+ ]
+ if (
+ host_index == candidate_index
+ or host_index in consumed
+ or host.get("type") != "text"
+ or int(host.get("angle", 0) or 0) % 360 != angle
+ or not isinstance(host_bbox, (list, tuple))
+ or host_bbox[2] - host_bbox[0] < 0.3 * local_page_width
+ or candidate_bbox[0] < host_bbox[0]
+ or candidate_bbox[2] > host_bbox[2]
+ ):
+ continue
+ host_height = statistics.median(host_heights) if host_heights else host_bbox[3] - host_bbox[1]
+ vertical_overlap = max(
+ 0.0,
+ min(candidate_bbox[3], host_bbox[3]) - max(candidate_bbox[1], host_bbox[1]),
+ )
+ vertical_gap = max(
+ 0.0,
+ max(candidate_bbox[1], host_bbox[1]) - min(candidate_bbox[3], host_bbox[3]),
+ )
+ pair_height = max(candidate_height, host_height, 0.1)
+ union_bbox = _bbox_union_many([candidate_bbox, host_bbox])
+ if (
+ vertical_overlap < 0.35 * min(candidate_height, host_height) and vertical_gap > 0.5 * pair_height
+ ) or union_bbox[3] - union_bbox[1] > 3.0 * pair_height:
+ continue
+ hosts.append(
+ (
+ -vertical_overlap,
+ abs(_bbox_center_y(candidate_bbox) - _bbox_center_y(host_bbox)),
+ host_index,
+ )
+ )
+ if len(hosts) != 1:
+ continue
+ host_index = hosts[0][2]
+ replacement_index = min(candidate_index, host_index)
+ replacements[replacement_index] = _merge_inline_math_recovery_group(
+ blocks,
+ [candidate_index, host_index],
+ )
+ consumed.update({candidate_index, host_index})
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+def _merge_hostless_inline_math_fragment_blocks(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """把没有单一宽宿主但在一栏内二维密集排列的数学碎片合成文本块。"""
+
+ grouped_indices: list[list[int]] = []
+ for angle in sorted({int(block.get("angle", 0) or 0) % 360 for block in blocks if block.get("type") == "text"}):
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ candidates = {
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text"
+ and int(block.get("angle", 0) or 0) % 360 == angle
+ and isinstance(block.get("bbox"), (list, tuple))
+ and isinstance(block.get("_local_line_bboxes"), list)
+ and len(block["_local_line_bboxes"]) == 1
+ and block["bbox"][2] - block["bbox"][0] <= 0.25 * local_page_width
+ }
+ while candidates:
+ component = {candidates.pop()}
+ changed = True
+ while changed:
+ changed = False
+ for candidate_index in list(candidates):
+ candidate_bbox = blocks[candidate_index]["bbox"]
+ candidate_heights = blocks[candidate_index].get(
+ "_line_heights",
+ [],
+ )
+ candidate_height = (
+ statistics.median(candidate_heights) if candidate_heights else candidate_bbox[3] - candidate_bbox[1]
+ )
+ if any(
+ (
+ max(
+ 0.0,
+ max(candidate_bbox[1], blocks[index]["bbox"][1])
+ - min(candidate_bbox[3], blocks[index]["bbox"][3]),
+ )
+ <= 0.75
+ * max(
+ candidate_height,
+ statistics.median(blocks[index].get("_line_heights", []))
+ if blocks[index].get("_line_heights")
+ else blocks[index]["bbox"][3] - blocks[index]["bbox"][1],
+ )
+ and max(
+ 0.0,
+ max(candidate_bbox[0], blocks[index]["bbox"][0])
+ - min(candidate_bbox[2], blocks[index]["bbox"][2]),
+ )
+ <= 1.5
+ * max(
+ candidate_height,
+ statistics.median(blocks[index].get("_line_heights", []))
+ if blocks[index].get("_line_heights")
+ else blocks[index]["bbox"][3] - blocks[index]["bbox"][1],
+ )
+ )
+ for index in component
+ ):
+ component.add(candidate_index)
+ candidates.remove(candidate_index)
+ changed = True
+ if len(component) < 4:
+ continue
+ component_heights = [
+ float(height)
+ for index in component
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ if not component_heights:
+ continue
+ median_height = statistics.median(component_heights)
+ union_bbox = _bbox_union_many([blocks[index]["bbox"] for index in component])
+ font_signatures = set().union(
+ *[
+ signatures
+ for index in component
+ if isinstance(
+ (signatures := blocks[index].get("_font_signatures")),
+ set,
+ )
+ ]
+ )
+ if (
+ len(font_signatures) < 2
+ or not 0.25 * local_page_width <= union_bbox[2] - union_bbox[0] <= 0.5 * local_page_width
+ or union_bbox[3] - union_bbox[1] > 3.5 * median_height
+ or sum(blocks[index]["bbox"][2] - blocks[index]["bbox"][0] >= 3.5 * median_height for index in component) < 2
+ ):
+ continue
+ grouped_indices.append(sorted(component))
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for group in grouped_indices:
+ if any(index in consumed for index in group):
+ continue
+ replacement_index = min(group)
+ replacements[replacement_index] = _merge_inline_math_recovery_group(
+ blocks,
+ group,
+ )
+ consumed.update(group)
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+def _merge_inline_math_recovery_group(
+ blocks: list[dict[str, Any]],
+ indices: list[int],
+) -> dict[str, Any]:
+ """合并数学碎片并保留仅供后续段落闭合使用的内部标记。"""
+ member_bboxes = [blocks[index]["bbox"] for index in indices]
+ widths = [bbox[2] - bbox[0] for bbox in member_bboxes]
+ maximum_width = max(widths, default=0.0)
+ detected_regions = [
+ bbox for bbox, width in zip(member_bboxes, widths) if maximum_width <= 0 or width <= 0.25 * maximum_width
+ ]
+ if not detected_regions:
+ detected_regions = list(member_bboxes)
+ merged = _merge_internal_text_block_group(blocks, indices)
+ merged[_INLINE_MATH_RECOVERY_MARKER] = True
+ merged["_inline_math_regions"] = [
+ *merged.get("_inline_math_regions", []),
+ *detected_regions,
+ ]
+ return merged
+
+
+def _merge_inline_math_paragraph_continuations(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """在数学碎片恢复后,合并同栏连续且足够宽的正文段落块。"""
+
+ if sum(block.get(_INLINE_MATH_RECOVERY_MARKER) is True for block in blocks) < 2:
+ return blocks
+
+ lane_groups: list[list[int]] = []
+ for index, block in sorted(
+ enumerate(blocks),
+ key=lambda item: (
+ int(item[1].get("angle", 0) or 0) % 360,
+ _text_component_sort_key(item[1])
+ if isinstance(item[1].get("_local_line_bboxes"), list) and item[1]["_local_line_bboxes"]
+ else (float("inf"), float("inf")),
+ ),
+ ):
+ local_rows = block.get("_local_line_bboxes")
+ if (
+ block.get("type") != "text"
+ or not isinstance(block.get("_lane_is_span"), bool)
+ or not isinstance(local_rows, list)
+ or not local_rows
+ ):
+ continue
+ block_heights = [
+ float(height) for height in block.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
+ ]
+ if not block_heights:
+ continue
+ for lane_group in lane_groups:
+ representative = blocks[lane_group[0]]
+ if int(representative.get("angle", 0) or 0) % 360 != int(block.get("angle", 0) or 0) % 360:
+ continue
+ representative_heights = [
+ float(height)
+ for height in representative.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ pair_height = statistics.median([*representative_heights, *block_heights])
+ if _components_share_lane_role(representative, block, pair_height):
+ lane_group.append(index)
+ break
+ else:
+ lane_groups.append([index])
+
+ candidate_chains: list[list[int]] = []
+ for lane_group in lane_groups:
+ ordered_indices = sorted(
+ lane_group,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ chain = [ordered_indices[0]]
+ for current_index in ordered_indices[1:]:
+ previous_index = chain[-1]
+ previous = blocks[previous_index]
+ current = blocks[current_index]
+ previous_rows = previous["_local_line_bboxes"]
+ current_rows = current["_local_line_bboxes"]
+ previous_local_bbox = _bbox_union_many(previous_rows)
+ current_local_bbox = _bbox_union_many(current_rows)
+ pair_heights = [
+ float(height)
+ for block in (previous, current)
+ for height in block.get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ pair_height = statistics.median(pair_heights)
+ angle = int(previous.get("angle", 0) or 0) % 360
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ lane_width = _compatible_component_lane_width(
+ previous,
+ current,
+ local_page_width,
+ pair_height,
+ )
+ previous_fonts = previous.get("_font_signatures")
+ current_fonts = current.get("_font_signatures")
+ fonts_conflict = (
+ isinstance(previous_fonts, set)
+ and isinstance(current_fonts, set)
+ and previous_fonts
+ and current_fonts
+ and previous_fonts.isdisjoint(current_fonts)
+ )
+ vertical_gap = current_local_bbox[1] - previous_local_bbox[3]
+ connects = (
+ _components_share_lane_role(previous, current, pair_height)
+ and previous_local_bbox[2] - previous_local_bbox[0] >= 0.8 * lane_width
+ and current_local_bbox[2] - current_local_bbox[0] >= 0.8 * lane_width
+ and abs(previous_local_bbox[0] - current_local_bbox[0]) <= 0.75 * pair_height
+ and -0.75 * pair_height <= vertical_gap <= 0.75 * pair_height
+ and not fonts_conflict
+ and not _component_connection_skips_block(
+ blocks,
+ previous_index,
+ current_index,
+ pair_height,
+ )
+ )
+ if connects:
+ chain.append(current_index)
+ else:
+ candidate_chains.append(chain)
+ chain = [current_index]
+ candidate_chains.append(chain)
+
+ consumed: set[int] = set()
+ replacements: dict[int, dict[str, Any]] = {}
+ for chain in candidate_chains:
+ if len(chain) < 3 or sum(blocks[index].get(_INLINE_MATH_RECOVERY_MARKER) is True for index in chain) < 2:
+ continue
+ chain_heights = [
+ float(height)
+ for index in chain
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ median_height = statistics.median(chain_heights)
+ local_union = _bbox_union_many([bbox for index in chain for bbox in blocks[index]["_local_line_bboxes"]])
+ if local_union[3] - local_union[1] > 24.0 * median_height:
+ continue
+ replacement_index = min(chain)
+ merged = _merge_internal_text_block_group(blocks, chain)
+ merged[_INLINE_MATH_RECOVERY_MARKER] = True
+ replacements[replacement_index] = merged
+ consumed.update(chain)
+ return [
+ replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
+ ]
+
+
+def _merge_spatial_text_components(
+ blocks: list[dict[str, Any]],
+ page_size: tuple[float, float],
+) -> list[dict[str, Any]]:
+ """按短首行、紧邻续行和双栏递减尾行二次连接被栏带拆开的正文块。"""
+
+ parents = list(range(len(blocks)))
+
+ def find(index: int) -> int:
+ """查找正文组件所属合并组的根节点。"""
+
+ while parents[index] != index:
+ parents[index] = parents[parents[index]]
+ index = parents[index]
+ return index
+
+ def union(first_index: int, second_index: int) -> None:
+ """合并两个已经通过空间连续性校验的正文组件。"""
+
+ first_root = find(first_index)
+ second_root = find(second_index)
+ if first_root != second_root:
+ parents[second_root] = first_root
+
+ for angle in sorted(
+ {
+ int(block.get("angle", 0) or 0) % 360
+ for block in blocks
+ if block.get("type") == "text" and block.get("_local_line_bboxes")
+ }
+ ):
+ candidate_indices = [
+ index
+ for index, block in enumerate(blocks)
+ if block.get("type") == "text"
+ and int(block.get("angle", 0) or 0) % 360 == angle
+ and isinstance(block.get("_local_line_bboxes"), list)
+ and block["_local_line_bboxes"]
+ ]
+ if len(candidate_indices) < 2:
+ continue
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ all_heights = [
+ float(height)
+ for index in candidate_indices
+ for height in blocks[index].get("_line_heights", [])
+ if isinstance(height, (int, float)) and height > 0
+ ]
+ median_height = statistics.median(all_heights) if all_heights else 1.0
+ section_starts = {
+ index
+ for index in candidate_indices
+ if _block_starts_with_short_wide_rows(
+ blocks[index],
+ local_page_width,
+ )
+ }
+
+ opener_pairs = _find_short_opener_pairs(
+ blocks,
+ candidate_indices,
+ local_page_width,
+ median_height,
+ )
+ for opener_index, body_index in opener_pairs:
+ section_starts.add(opener_index)
+ union(opener_index, body_index)
+
+ for current_index in sorted(
+ candidate_indices,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ ):
+ section_roots = {find(index) for index in section_starts}
+ if find(current_index) not in section_roots:
+ continue
+ next_index = _nearest_following_text_component(
+ blocks,
+ current_index,
+ candidate_indices,
+ maximum_gap=0.75 * median_height,
+ section_starts=section_starts,
+ )
+ if next_index is not None:
+ union(current_index, next_index)
+
+ for current_index in candidate_indices:
+ if not _has_parallel_text_component(
+ blocks,
+ current_index,
+ candidate_indices,
+ ):
+ continue
+ next_index = _nearest_tapered_tail_component(
+ blocks,
+ current_index,
+ candidate_indices,
+ median_height,
+ section_starts,
+ )
+ if next_index is not None:
+ union(current_index, next_index)
+
+ grouped_indices: dict[int, list[int]] = {}
+ for index in range(len(blocks)):
+ grouped_indices.setdefault(find(index), []).append(index)
+
+ output: list[dict[str, Any]] = []
+ for indices in grouped_indices.values():
+ if len(indices) == 1:
+ output.append(blocks[indices[0]])
+ continue
+ ordered_indices = sorted(
+ indices,
+ key=lambda index: _text_component_sort_key(blocks[index]),
+ )
+ merged = dict(blocks[ordered_indices[0]])
+ merged["bbox"] = _bbox_union_many([blocks[index]["bbox"] for index in ordered_indices])
+ merged["content"] = _merge_text_line_content([str(blocks[index].get("content", "")) for index in ordered_indices])
+ merged["_visual_row_ids"] = set().union(
+ *[
+ block_ids
+ for index in ordered_indices
+ if isinstance(
+ (block_ids := blocks[index].get("_visual_row_ids")),
+ set,
+ )
+ ]
+ )
+ merged["_single_run_row_id"] = None
+ merged["_local_line_bboxes"] = [
+ bbox for index in ordered_indices for bbox in blocks[index].get("_local_line_bboxes", [])
+ ]
+ merged["_local_output_line_bboxes"] = [
+ bbox for index in ordered_indices for bbox in blocks[index].get("_local_output_line_bboxes", [])
+ ]
+ merged["_output_bbox_repaired"] = any(blocks[index].get("_output_bbox_repaired") is True for index in ordered_indices)
+ merged["_line_heights"] = [height for index in ordered_indices for height in blocks[index].get("_line_heights", [])]
+ merged["_font_signatures"] = set().union(
+ *[
+ signatures
+ for index in ordered_indices
+ if isinstance(
+ (signatures := blocks[index].get("_font_signatures")),
+ set,
+ )
+ ]
+ )
+ merged["_inline_math_regions"] = [
+ region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
+ ]
+ output.append(merged)
+ 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]]:
+ """合并普通栏未终止正文,以及满足严格结构约束的满宽 span 正文。"""
+
+ 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_declared_interval = _component_declared_lane_interval(
+ first,
+ )
+ second_declared_interval = _component_declared_lane_interval(
+ second,
+ )
+ row_pair_height = statistics.median(
+ [
+ max(
+ 0.1,
+ first_rows[-1][3] - first_rows[-1][1],
+ ),
+ max(
+ 0.1,
+ second_rows[0][3] - second_rows[0][1],
+ ),
+ ],
+ )
+ span_connection_height = max(
+ pair_height,
+ row_pair_height,
+ )
+ span_tolerance = 0.75 * span_connection_height
+ span_pair = (
+ first.get("_lane_is_span") is True
+ and second.get("_lane_is_span") is True
+ and int(first.get("angle", 0) or 0) % 360 == int(second.get("angle", 0) or 0) % 360
+ and first_declared_interval is not None
+ and second_declared_interval is not None
+ and abs(
+ first_declared_interval[0] - second_declared_interval[0],
+ )
+ <= span_tolerance
+ and abs(
+ first_declared_interval[1] - second_declared_interval[1],
+ )
+ <= span_tolerance
+ )
+ 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 (reference_interval := (second_declared_interval if span_pair else second_interval)) is not None
+ and second_rows[0][2] - second_rows[0][0] >= 0.5 * (reference_interval[1] - reference_interval[0])
+ )
+ if (
+ second.get("_protected_hard_break_before") is True
+ or (second.get("_hard_break_before") is True and (span_pair or not narrow_continuation))
+ or second.get("_leading_emphasis_start") is True
+ or (starts_wide_label and (span_pair or 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 span_pair
+ and 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 span_pair:
+ interval = first_declared_interval
+ elif interval is None or not _components_share_lane_role(
+ first,
+ second,
+ pair_height,
+ ):
+ continue
+ if interval is None:
+ continue
+ lane_width = interval[1] - interval[0]
+ vertical_gap = second_rows[0][1] - first_rows[-1][3]
+ minimum_first_fill = 0.8 if span_pair else 0.5 if single_numbered_tail else 0.65
+ minimum_second_fill = 0.8 if span_pair else 0.65
+ connection_height = span_connection_height if span_pair else pair_height
+ 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 (
+ (span_pair or not narrow_continuation)
+ and second_rows[0][2] - second_rows[0][0] < minimum_second_fill * lane_width
+ )
+ or not -connection_height <= vertical_gap <= 1.5 * connection_height
+ or fonts_conflict
+ or _component_connection_skips_block(
+ output,
+ first_index,
+ second_index,
+ connection_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)
+
+
+__all__ = [
+ "_merge_short_same_baseline_prefix_blocks",
+ "_blocks_share_boundary_visual_row",
+ "_merge_overlapping_same_line_text_blocks",
+ "_merge_inline_math_fragment_text_blocks",
+ "_component_local_union_bbox",
+ "_merge_paragraph_formula_context_blocks",
+ "_merge_residual_narrow_math_text_blocks",
+ "_merge_hostless_inline_math_fragment_blocks",
+ "_merge_inline_math_recovery_group",
+ "_merge_inline_math_paragraph_continuations",
+ "_merge_spatial_text_components",
+ "_merge_list_intro_text_components",
+ "_merge_unterminated_text_components",
+]
diff --git a/mineru/model/flash/pdf/text_assembly/rows.py b/mineru/model/flash/pdf/text_assembly/rows.py
new file mode 100644
index 00000000..c9b573fa
--- /dev/null
+++ b/mineru/model/flash/pdf/text_assembly/rows.py
@@ -0,0 +1,697 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""依据栏带、缩进和排版重置寻找正文行分组边界。"""
+
+from __future__ import annotations
+
+import re
+import statistics
+from typing import Sequence
+
+from .....types import BBox
+from .....utils.text import is_hyphen_at_line_end
+from ..geometry import (
+ _bbox_axis_overlap_ratio,
+ _bbox_center_x,
+ _rotate_bbox_to_upright,
+)
+from ..line_layout import (
+ _connection_crosses_table,
+ _effective_body_text_row_gap,
+ _effective_text_row_gap,
+ _horizontal_rule_separates_rows,
+ _line_effective_height,
+ _line_tight_output_bbox,
+ _title_fonts_compatible,
+)
+from ..models import _LineItem, _LocalAxisLine, _TextLane
+from .common import (
+ _ABSTRACT_METADATA_RE,
+ _BULLET_ITEM_RE,
+ _EMAIL_METADATA_RE,
+ _FRONT_MATTER_FIELD_RE,
+ _LABELLED_METADATA_RE,
+ _LIST_ITEM_RE,
+ _REFERENCE_ENTRY_RE,
+ _URL_LINE_RE,
+)
+
+
+def _local_tight_output_line_bboxes(
+ lines: Sequence[_LineItem],
+ page_size: tuple[float, float],
+ angle: int,
+) -> tuple[list[BBox], bool]:
+ """返回与原行顺序一致的 tight+1pt 局部框及是否存在可靠候选。"""
+
+ output = []
+ changed = False
+ for line in lines:
+ candidate = _line_tight_output_bbox(line, page_size)
+ output.append(
+ _rotate_bbox_to_upright(
+ candidate or line.bbox,
+ page_size,
+ angle,
+ )
+ )
+ changed = changed or candidate is not None
+ return output, changed
+
+
+def _starts_structural_reference_entry(
+ previous: tuple[_LineItem, BBox],
+ current: tuple[_LineItem, BBox],
+) -> bool:
+ """仅在编号行相对续行明显左突时确认新的参考文献条目。"""
+
+ if _REFERENCE_ENTRY_RE.match(current[0].text.strip()) is None:
+ return False
+ previous_height = _line_effective_height(*previous)
+ current_height = _line_effective_height(*current)
+ pair_height = max(previous_height, current_height)
+ return (
+ current[1][0] <= previous[1][0] - max(5.0, 0.6 * min(previous_height, current_height))
+ and -0.75 * pair_height <= _effective_text_row_gap(previous, current) <= 1.5 * pair_height
+ )
+
+
+def _build_hanging_indent_group_map(
+ lane: _TextLane,
+ table_bboxes: list[BBox],
+ axis_lines: list[_LocalAxisLine],
+) -> dict[int, int]:
+ """仅按重复的左突首行和稳定续行缩进识别悬挂缩进条目。"""
+
+ if len(lane.lines) < 4:
+ return {}
+ 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),
+ )
+ if len(rows) < 4:
+ return {}
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in rows)
+ start_tolerance = max(5.0, 0.65 * median_height)
+ minimum_indent = max(7.0, 0.8 * median_height)
+ continuation_tolerance = max(4.0, 0.55 * median_height)
+
+ def rows_are_adjacent(
+ previous: tuple[_LineItem, BBox],
+ current: tuple[_LineItem, BBox],
+ ) -> bool:
+ """检查相邻行的净空和几何障碍是否允许组成同一缩进序列。"""
+
+ effective_gap = _effective_text_row_gap(previous, current)
+ top_pitch = current[1][1] - previous[1][1]
+ robust_pitch_fallback = 0.5 * median_height <= top_pitch <= 1.8 * median_height
+ if not -0.6 * median_height <= effective_gap <= 1.3 * median_height and not robust_pitch_fallback:
+ return False
+ if _connection_crosses_table(
+ previous[0].bbox,
+ current[0].bbox,
+ table_bboxes,
+ ):
+ return False
+ return not _horizontal_rule_separates_rows(
+ previous[1],
+ current[1],
+ lane,
+ axis_lines,
+ )
+
+ def consume_entry(
+ start_index: int,
+ start_left: float,
+ expected_continuation_left: float | None,
+ *,
+ require_next_start: bool,
+ ) -> 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)
+ and rows_are_adjacent(rows[start_index - 1], rows[start_index])
+ ):
+ # 排版断词后的下一物理行属于前文,不能被缩进几何误当成新条目首行。
+ return None
+ continuation_index = start_index + 1
+ if continuation_index >= len(rows):
+ return None
+ first_continuation = rows[continuation_index]
+ if not rows_are_adjacent(rows[start_index], first_continuation):
+ return None
+ continuation_left = first_continuation[1][0]
+ if continuation_left < start_left + minimum_indent:
+ return None
+ if (
+ expected_continuation_left is not None
+ and abs(continuation_left - expected_continuation_left) > continuation_tolerance
+ ):
+ return None
+
+ continuation_index += 1
+ while continuation_index < len(rows):
+ previous = rows[continuation_index - 1]
+ current = rows[continuation_index]
+ current_left = current[1][0]
+ if not rows_are_adjacent(previous, current):
+ break
+ if current_left < start_left + minimum_indent:
+ break
+ if abs(current_left - continuation_left) > continuation_tolerance:
+ break
+ continuation_index += 1
+
+ if not require_next_start:
+ return continuation_index, continuation_left
+ if continuation_index >= len(rows):
+ return None
+ if not rows_are_adjacent(rows[continuation_index - 1], rows[continuation_index]):
+ return None
+ if abs(rows[continuation_index][1][0] - start_left) > start_tolerance:
+ return None
+ return continuation_index, continuation_left
+
+ group_map: dict[int, int] = {}
+ group_index = 0
+ row_index = 0
+ while row_index < len(rows) - 3:
+ start_left = rows[row_index][1][0]
+ first_entry = consume_entry(
+ row_index,
+ start_left,
+ None,
+ require_next_start=True,
+ )
+ if first_entry is None:
+ row_index += 1
+ continue
+
+ _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,
+ start_left,
+ continuation_left,
+ 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
+ if len(start_indices) < 2 or end_index is None:
+ row_index += 1
+ continue
+
+ entry_ranges = [
+ (start, end)
+ for start, end in zip(
+ start_indices,
+ [*start_indices[1:], end_index],
+ strict=True,
+ )
+ ]
+ for start, end in entry_ranges:
+ for line, _bbox in rows[start:end]:
+ group_map[line.source_index] = group_index
+ group_index += 1
+ row_index = end_index
+
+ return group_map
+
+
+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 _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 _centered_visual_reset_break_sources(
+ lane: _TextLane,
+ visual_bboxes: Sequence[BBox],
+ local_page_height: float,
+) -> set[int]:
+ """识别视觉主体下方短居中行到更宽居中行的独立注释重启。"""
+
+ if not visual_bboxes:
+ return set()
+ 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: set[int] = set()
+ for previous, current in zip(rows, rows[1:]):
+ previous_bbox = previous[1]
+ current_bbox = current[1]
+ previous_width = previous_bbox[2] - previous_bbox[0]
+ current_width = current_bbox[2] - current_bbox[0]
+ pair_height = max(
+ _line_effective_height(*previous),
+ _line_effective_height(*current),
+ )
+ if (
+ previous_width > 0.7 * current_width
+ or current_bbox[0] > previous_bbox[0] - 0.25 * pair_height
+ or current_bbox[2] < previous_bbox[2] + 0.25 * pair_height
+ or abs(_bbox_center_x(previous_bbox) - _bbox_center_x(current_bbox)) > 0.1 * current_width
+ ):
+ continue
+ vertical_gap = _effective_text_row_gap(previous, current)
+ if not -0.25 * pair_height <= vertical_gap <= 0.75 * pair_height:
+ continue
+ if any(
+ -0.25 * pair_height <= previous_bbox[1] - visual_bbox[3] <= max(2.0 * pair_height, 0.03 * local_page_height)
+ and _bbox_axis_overlap_ratio(current_bbox, visual_bbox, axis="x") >= 0.8
+ and abs(_bbox_center_x(current_bbox) - _bbox_center_x(visual_bbox))
+ <= 0.12 * max(current_width, visual_bbox[2] - visual_bbox[0])
+ for visual_bbox in visual_bboxes
+ ):
+ output.add(current[0].source_index)
+ return output
+
+
+def _leading_typography_reset_break_sources(
+ lane: _TextLane,
+ regular_gap: float,
+ gap_mad: float,
+) -> set[int]:
+ """识别短尾之后以独立行首字体 run 开启的宽行结构段。"""
+
+ 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()
+ for previous, current in zip(rows, rows[1:]):
+ previous_width = previous[1][2] - previous[1][0]
+ current_width = current[1][2] - current[1][0]
+ pair_height = max(
+ _line_effective_height(*previous),
+ _line_effective_height(*current),
+ )
+ if (
+ current[0].leading_typography_width is None
+ or current[0].leading_typography_width > 0.2 * lane_width
+ or previous_width > 0.45 * lane_width
+ or current_width < 0.75 * lane_width
+ or abs(previous[1][0] - lane.left) > 0.75 * pair_height
+ or abs(current[1][0] - lane.left) > 0.75 * pair_height
+ or current[0].formula_candidate_only
+ or current[0].compact_formula_cluster
+ or current[0].inline_math_regions
+ ):
+ continue
+ vertical_gap = _effective_body_text_row_gap(previous, current)
+ if (
+ -0.25 * pair_height
+ <= vertical_gap
+ <= regular_gap
+ + max(
+ 0.75 * pair_height,
+ 3.0 * gap_mad,
+ )
+ ):
+ output.add(current[0].source_index)
+ return output
+
+
+def _formula_style_text_row_break_sources(
+ lane: _TextLane,
+) -> 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)
+ matching_edges: set[int] = set()
+ for index, (previous, current) in enumerate(zip(rows, rows[1:])):
+ previous_line, previous_bbox = previous
+ current_line, current_bbox = current
+ if not (previous_line.paragraph_formula_context and current_line.paragraph_formula_context):
+ continue
+ previous_height = _line_effective_height(*previous)
+ current_height = _line_effective_height(*current)
+ minimum_height = min(previous_height, current_height)
+ maximum_height = max(previous_height, current_height)
+ if minimum_height < 0.75 * maximum_height:
+ continue
+ previous_width = previous_bbox[2] - previous_bbox[0]
+ current_width = current_bbox[2] - current_bbox[0]
+ if min(previous_width, current_width) < 0.45 * lane_width or max(previous_width, current_width) > 0.95 * lane_width:
+ continue
+ lane_center = 0.5 * (lane.left + lane.right)
+ if (
+ abs(_bbox_center_x(previous_bbox) - lane_center) > 0.15 * lane_width
+ or abs(_bbox_center_x(current_bbox) - lane_center) > 0.15 * lane_width
+ ):
+ continue
+ vertical_overlap = max(
+ 0.0,
+ min(previous_bbox[3], current_bbox[3]) - max(previous_bbox[1], current_bbox[1]),
+ )
+ top_pitch = current_bbox[1] - previous_bbox[1]
+ pair_height = statistics.median((previous_height, current_height))
+ if vertical_overlap <= 0.2 * minimum_height and 0.9 * pair_height <= top_pitch <= 2.0 * pair_height:
+ matching_edges.add(index)
+
+ output: set[int] = set()
+ for index in matching_edges:
+ output.add(rows[index][0].source_index)
+ output.add(rows[index + 1][0].source_index)
+ if index + 2 < len(rows):
+ # 同时保护显示行组后的正文起点,避免上下文恢复阶段重新跨界合并。
+ output.add(rows[index + 2][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_FIELD_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
+
+
+__all__ = [
+ "_local_tight_output_line_bboxes",
+ "_starts_structural_reference_entry",
+ "_build_hanging_indent_group_map",
+ "_infer_local_text_lane_map",
+ "_structured_text_break_sources",
+ "_isolated_indented_paragraph_break_sources",
+ "_centered_visual_reset_break_sources",
+ "_leading_typography_reset_break_sources",
+ "_formula_style_text_row_break_sources",
+ "_front_matter_keyword_break_sources",
+ "_component_starts_with_emphasized_row",
+ "_explicit_text_break_sources",
+]
diff --git a/mineru/model/flash/pdf/text_blocks.py b/mineru/model/flash/pdf/text_blocks.py
index 5e4f87bf..061f5040 100644
--- a/mineru/model/flash/pdf/text_blocks.py
+++ b/mineru/model/flash/pdf/text_blocks.py
@@ -1,3524 +1,83 @@
# Copyright (c) Opendatalab. All rights reserved.
-
-"""将剩余文本行构造成正文和页脚注块。"""
-
-from __future__ import annotations
-
-import re
-import statistics
-from typing import Any, Sequence
-
-
-from ....utils.text import (
- is_hyphen_at_line_end,
- merge_text_line_contents,
-)
-from ....types import BBox
-from ....utils.language import detect_lang
-
-from .models import (
- _AxisLine,
- _LineItem,
- _LocalAxisLine,
- _TextLane,
-)
-from .geometry import (
- _bbox_axis_overlap_ratio,
- _bbox_center_x,
- _bbox_center_y,
- _bbox_union_many,
- _rotate_bbox_from_upright,
- _rotate_bbox_to_upright,
- _transform_axis_lines,
-)
-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,
- _infer_text_lanes,
- _is_structural_typography_gap,
- _line_effective_height,
- _line_tight_output_bbox,
- _lines_tight_output_bbox,
- _should_connect_semantic_rows,
- _should_connect_text_rows,
- _title_fonts_compatible,
-)
-
-
-_REFERENCE_ENTRY_RE = re.compile(r"^[[\[]\s*\d+\s*[]\]]")
-_FIGURE_CAPTION_MARKER_RE = re.compile(
- r"^(?:图\s*[0-90-9一二三四五六七八九十]|fig(?:ure)?\.?\s*[0-9])",
- re.IGNORECASE,
-)
-_INLINE_MATH_RECOVERY_MARKER = "_recovered_inline_math_fragments"
-_PARAGRAPH_FORMULA_CONTEXT_MARKER = "_paragraph_formula_context"
-_FRONT_MATTER_FIELD_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*[•●▪]",
+"""保留既有入口的 Flash PDF 门面,内部实现按职责显式组织。"""
+
+from .text_assembly.annotations import (
+ _merge_image_caption_text_blocks as _merge_image_caption_text_blocks,
+ _caption_image_group_bboxes as _caption_image_group_bboxes,
+ _caption_seed_matches_image as _caption_seed_matches_image,
+ _caption_body_has_structural_gap as _caption_body_has_structural_gap,
+ _caption_tail_matches_seed as _caption_tail_matches_seed,
+ _merge_multiline_title_blocks as _merge_multiline_title_blocks,
+ _merge_fragmented_header_blocks as _merge_fragmented_header_blocks,
+ _merge_front_matter_column_blocks as _merge_front_matter_column_blocks,
+ _merge_repeated_compact_title_continuations as _merge_repeated_compact_title_continuations,
)
-_EMAIL_METADATA_RE = re.compile(
- r"^\s*e[\s-]*mail\s*[::]",
- re.IGNORECASE,
+from .text_assembly.assembly import _build_text_blocks as _build_text_blocks
+from .text_assembly.common import (
+ _REFERENCE_ENTRY_RE as _REFERENCE_ENTRY_RE,
+ _FIGURE_CAPTION_MARKER_RE as _FIGURE_CAPTION_MARKER_RE,
+ _INLINE_MATH_RECOVERY_MARKER as _INLINE_MATH_RECOVERY_MARKER,
+ _PARAGRAPH_FORMULA_CONTEXT_MARKER as _PARAGRAPH_FORMULA_CONTEXT_MARKER,
+ _FRONT_MATTER_FIELD_RE as _FRONT_MATTER_FIELD_RE,
+ _LIST_ITEM_RE as _LIST_ITEM_RE,
+ _BULLET_ITEM_RE as _BULLET_ITEM_RE,
+ _EMAIL_METADATA_RE as _EMAIL_METADATA_RE,
+ _ABSTRACT_METADATA_RE as _ABSTRACT_METADATA_RE,
+ _LABELLED_METADATA_RE as _LABELLED_METADATA_RE,
+ _URL_LINE_RE as _URL_LINE_RE,
+ _SHORT_SAME_BASELINE_PREFIX_RE as _SHORT_SAME_BASELINE_PREFIX_RE,
+ _merge_internal_text_block_group as _merge_internal_text_block_group,
+ _component_declared_lane_interval as _component_declared_lane_interval,
+ _component_lane_interval as _component_lane_interval,
+ _component_reference_width as _component_reference_width,
+ _compatible_component_lane_width as _compatible_component_lane_width,
+ _components_share_lane_role as _components_share_lane_role,
+ _block_starts_with_short_wide_rows as _block_starts_with_short_wide_rows,
+ _find_short_opener_pairs as _find_short_opener_pairs,
+ _nearest_following_text_component as _nearest_following_text_component,
+ _has_parallel_text_component as _has_parallel_text_component,
+ _nearest_tapered_tail_component as _nearest_tapered_tail_component,
+ _component_connection_skips_block as _component_connection_skips_block,
+ _text_component_sort_key as _text_component_sort_key,
+ _merge_text_line_content as _merge_text_line_content,
)
-_ABSTRACT_METADATA_RE = re.compile(
- r"^\s*(?:abstract|摘\s*要)\s*[::]",
- re.IGNORECASE,
+from .text_assembly.footnotes import (
+ _build_grouped_page_footnote_blocks as _build_grouped_page_footnote_blocks,
+ _split_page_footnote_entries as _split_page_footnote_entries,
+ _find_page_footnote_marker_rows as _find_page_footnote_marker_rows,
+ _find_geometric_page_footnote_marker_rows as _find_geometric_page_footnote_marker_rows,
+ _split_marked_page_footnote_entries as _split_marked_page_footnote_entries,
+ _split_unmarked_page_footnote_entries as _split_unmarked_page_footnote_entries,
+ _tight_page_footnote_bboxes as _tight_page_footnote_bboxes,
)
-_LABELLED_METADATA_RE = re.compile(
- r"^\s*(?P<label>[A-Za-z\u3400-\u9fff]{1,12})\s*[::]",
+from .text_assembly.merging import (
+ _merge_short_same_baseline_prefix_blocks as _merge_short_same_baseline_prefix_blocks,
+ _blocks_share_boundary_visual_row as _blocks_share_boundary_visual_row,
+ _merge_overlapping_same_line_text_blocks as _merge_overlapping_same_line_text_blocks,
+ _merge_inline_math_fragment_text_blocks as _merge_inline_math_fragment_text_blocks,
+ _component_local_union_bbox as _component_local_union_bbox,
+ _merge_paragraph_formula_context_blocks as _merge_paragraph_formula_context_blocks,
+ _merge_residual_narrow_math_text_blocks as _merge_residual_narrow_math_text_blocks,
+ _merge_hostless_inline_math_fragment_blocks as _merge_hostless_inline_math_fragment_blocks,
+ _merge_inline_math_recovery_group as _merge_inline_math_recovery_group,
+ _merge_inline_math_paragraph_continuations as _merge_inline_math_paragraph_continuations,
+ _merge_spatial_text_components as _merge_spatial_text_components,
+ _merge_list_intro_text_components as _merge_list_intro_text_components,
+ _merge_unterminated_text_components as _merge_unterminated_text_components,
)
-_URL_LINE_RE = re.compile(
- r"^\s*(?:https?://|www\.)",
- re.IGNORECASE,
+from .text_assembly.rows import (
+ _local_tight_output_line_bboxes as _local_tight_output_line_bboxes,
+ _starts_structural_reference_entry as _starts_structural_reference_entry,
+ _build_hanging_indent_group_map as _build_hanging_indent_group_map,
+ _infer_local_text_lane_map as _infer_local_text_lane_map,
+ _structured_text_break_sources as _structured_text_break_sources,
+ _isolated_indented_paragraph_break_sources as _isolated_indented_paragraph_break_sources,
+ _centered_visual_reset_break_sources as _centered_visual_reset_break_sources,
+ _leading_typography_reset_break_sources as _leading_typography_reset_break_sources,
+ _formula_style_text_row_break_sources as _formula_style_text_row_break_sources,
+ _front_matter_keyword_break_sources as _front_matter_keyword_break_sources,
+ _component_starts_with_emphasized_row as _component_starts_with_emphasized_row,
+ _explicit_text_break_sources as _explicit_text_break_sources,
)
-_SHORT_SAME_BASELINE_PREFIX_RE = re.compile(
- r"^(?:[((]\s*\d{1,3}|\d{1,2}\s*[::]\s*\d{2})$",
-)
-
-
-def _local_tight_output_line_bboxes(
- lines: Sequence[_LineItem],
- page_size: tuple[float, float],
- angle: int,
-) -> tuple[list[BBox], bool]:
- """返回与原行顺序一致的 tight+1pt 局部框及是否存在可靠候选。"""
-
- output = []
- changed = False
- for line in lines:
- candidate = _line_tight_output_bbox(line, page_size)
- output.append(
- _rotate_bbox_to_upright(
- candidate or line.bbox,
- page_size,
- angle,
- )
- )
- changed = changed or candidate is not None
- return output, changed
-
-
-def _starts_structural_reference_entry(
- previous: tuple[_LineItem, BBox],
- current: tuple[_LineItem, BBox],
-) -> bool:
- """仅在编号行相对续行明显左突时确认新的参考文献条目。"""
-
- if _REFERENCE_ENTRY_RE.match(current[0].text.strip()) is None:
- return False
- previous_height = _line_effective_height(*previous)
- current_height = _line_effective_height(*current)
- pair_height = max(previous_height, current_height)
- return (
- current[1][0] <= previous[1][0] - max(5.0, 0.6 * min(previous_height, current_height))
- and -0.75 * pair_height <= _effective_text_row_gap(previous, current) <= 1.5 * pair_height
- )
-
-
-def _build_hanging_indent_group_map(
- lane: _TextLane,
- table_bboxes: list[BBox],
- axis_lines: list[_LocalAxisLine],
-) -> dict[int, int]:
- """仅按重复的左突首行和稳定续行缩进识别悬挂缩进条目。"""
-
- if len(lane.lines) < 4:
- return {}
- 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),
- )
- if len(rows) < 4:
- return {}
- median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in rows)
- start_tolerance = max(5.0, 0.65 * median_height)
- minimum_indent = max(7.0, 0.8 * median_height)
- continuation_tolerance = max(4.0, 0.55 * median_height)
-
- def rows_are_adjacent(
- previous: tuple[_LineItem, BBox],
- current: tuple[_LineItem, BBox],
- ) -> bool:
- """检查相邻行的净空和几何障碍是否允许组成同一缩进序列。"""
-
- effective_gap = _effective_text_row_gap(previous, current)
- top_pitch = current[1][1] - previous[1][1]
- robust_pitch_fallback = 0.5 * median_height <= top_pitch <= 1.8 * median_height
- if not -0.6 * median_height <= effective_gap <= 1.3 * median_height and not robust_pitch_fallback:
- return False
- if _connection_crosses_table(
- previous[0].bbox,
- current[0].bbox,
- table_bboxes,
- ):
- return False
- return not _horizontal_rule_separates_rows(
- previous[1],
- current[1],
- lane,
- axis_lines,
- )
-
- def consume_entry(
- start_index: int,
- start_left: float,
- expected_continuation_left: float | None,
- *,
- require_next_start: bool,
- ) -> 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)
- and rows_are_adjacent(rows[start_index - 1], rows[start_index])
- ):
- # 排版断词后的下一物理行属于前文,不能被缩进几何误当成新条目首行。
- return None
- continuation_index = start_index + 1
- if continuation_index >= len(rows):
- return None
- first_continuation = rows[continuation_index]
- if not rows_are_adjacent(rows[start_index], first_continuation):
- return None
- continuation_left = first_continuation[1][0]
- if continuation_left < start_left + minimum_indent:
- return None
- if (
- expected_continuation_left is not None
- and abs(continuation_left - expected_continuation_left) > continuation_tolerance
- ):
- return None
-
- continuation_index += 1
- while continuation_index < len(rows):
- previous = rows[continuation_index - 1]
- current = rows[continuation_index]
- current_left = current[1][0]
- if not rows_are_adjacent(previous, current):
- break
- if current_left < start_left + minimum_indent:
- break
- if abs(current_left - continuation_left) > continuation_tolerance:
- break
- continuation_index += 1
-
- if not require_next_start:
- return continuation_index, continuation_left
- if continuation_index >= len(rows):
- return None
- if not rows_are_adjacent(rows[continuation_index - 1], rows[continuation_index]):
- return None
- if abs(rows[continuation_index][1][0] - start_left) > start_tolerance:
- return None
- return continuation_index, continuation_left
-
- group_map: dict[int, int] = {}
- group_index = 0
- row_index = 0
- while row_index < len(rows) - 3:
- start_left = rows[row_index][1][0]
- first_entry = consume_entry(
- row_index,
- start_left,
- None,
- require_next_start=True,
- )
- if first_entry is None:
- row_index += 1
- continue
-
- _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,
- start_left,
- continuation_left,
- 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
- if len(start_indices) < 2 or end_index is None:
- row_index += 1
- continue
-
- entry_ranges = [
- (start, end)
- for start, end in zip(
- start_indices,
- [*start_indices[1:], end_index],
- strict=True,
- )
- ]
- for start, end in entry_ranges:
- for line, _bbox in rows[start:end]:
- group_map[line.source_index] = group_index
- group_index += 1
- row_index = end_index
-
- return group_map
-
-
-def _build_grouped_page_footnote_blocks(
- lines: list[_LineItem],
- source_groups: Sequence[set[int]],
- page_size: tuple[float, float],
-) -> tuple[list[dict[str, Any]], set[int]]:
- """按分隔线组切分几何脚注条目,并返回已消费的来源编号。"""
-
- footnote_by_source = {line.source_index: line for line in lines if line.semantic_type == "page_footnote"}
- blocks: list[dict[str, Any]] = []
- consumed_source_indices: set[int] = set()
- for source_group in source_groups:
- group_lines = [footnote_by_source[source_index] for source_index in source_group if source_index in footnote_by_source]
- for angle in sorted({line.angle for line in group_lines}):
- directional_lines = [line for line in group_lines if line.angle == angle]
- tight_bboxes = _tight_page_footnote_bboxes(
- directional_lines,
- page_size,
- )
- for entry_lines in _split_page_footnote_entries(
- directional_lines,
- page_size,
- ):
- ordered_lines = sorted(
- entry_lines,
- key=lambda line: (
- _rotate_bbox_to_upright(line.bbox, page_size, angle)[1],
- _rotate_bbox_to_upright(line.bbox, page_size, angle)[0],
- line.source_index,
- ),
- )
- content = _merge_text_line_content([line.text for line in ordered_lines])
- if not content:
- continue
- visual_row_ids = {line.visual_row_id for line in ordered_lines if line.visual_row_id is not None}
- single_run_row_id = (
- ordered_lines[0].visual_row_id
- if len(ordered_lines) == 1
- and ordered_lines[0].split_from_row
- and ordered_lines[0].visual_row_id is not None
- else None
- )
- block = {
- "type": "page_footnote",
- "bbox": _bbox_union_many([tight_bboxes[line.source_index] for line in ordered_lines]),
- "angle": angle,
- "content": content,
- "_visual_row_ids": visual_row_ids,
- "_single_run_row_id": single_run_row_id,
- "_inline_math_regions": [region for line in ordered_lines for region in line.inline_math_regions],
- }
- tight_output_bbox = _lines_tight_output_bbox(
- ordered_lines,
- page_size,
- )
- if tight_output_bbox is not None:
- block["_tight_output_bbox"] = tight_output_bbox
- blocks.append(block)
- consumed_source_indices.update(line.source_index for line in ordered_lines)
- return blocks, consumed_source_indices
-
-
-def _split_page_footnote_entries(
- lines: list[_LineItem],
- page_size: tuple[float, float],
-) -> list[list[_LineItem]]:
- """按首行或续行缩进模式,把同一分隔线下的脚注行切成条目。"""
-
- if not lines:
- return []
- angle = lines[0].angle
- line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines]
- line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
- if len(line_geometry) == 1:
- return [[line_geometry[0][0]]]
-
- effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]
- median_height = statistics.median(effective_heights)
- glyph_widths = [line.median_glyph_width for line, _bbox in line_geometry if line.median_glyph_width is not None]
- median_glyph_width = statistics.median(glyph_widths) if glyph_widths else 0.5 * median_height
- 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 marker_rows:
- 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]))
- if not marker_rows:
- marker_rows = _find_geometric_page_footnote_marker_rows(
- line_geometry,
- median_height,
- median_glyph_width,
- base_left,
- )
- return marker_rows
-
-
-def _find_geometric_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]]]:
- """在 row id 缺失时用同基线窄标记和右侧正文恢复脚注首行。"""
-
- marker_width_limit = max(
- 1.5 * median_glyph_width,
- 0.75 * median_height,
- )
- candidates: list[
- tuple[
- float,
- tuple[_LineItem, BBox],
- tuple[_LineItem, BBox],
- ]
- ] = []
- for marker in line_geometry:
- marker_width = marker[1][2] - marker[1][0]
- if (
- marker_width > marker_width_limit
- or marker[1][0] - base_left > 0.5 * median_height
- ):
- continue
- for body in line_geometry:
- if body is marker:
- continue
- body_width = body[1][2] - body[1][0]
- horizontal_gap = body[1][0] - marker[1][2]
- if (
- not 0.0 <= horizontal_gap <= 1.5 * median_height
- or body[1][0] - base_left
- < max(
- 1.5 * marker_width,
- 0.4 * 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
- or not _title_fonts_compatible(
- marker[0],
- body[0],
- )
- ):
- continue
- candidates.append(
- (
- horizontal_gap,
- marker,
- body,
- )
- )
-
- output = []
- consumed_sources: set[int] = set()
- for _gap, marker, body in sorted(
- candidates,
- key=lambda item: (
- min(item[1][1][1], item[2][1][1]),
- item[0],
- item[1][0].source_index,
- item[2][0].source_index,
- ),
- ):
- pair_sources = {
- marker[0].source_index,
- body[0].source_index,
- }
- if pair_sources & consumed_sources:
- continue
- output.append((marker, body))
- consumed_sources.update(pair_sources)
- return output
-
-
-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]]]
- for previous, current in zip(line_geometry, line_geometry[1:]):
- previous_width = previous[1][2] - previous[1][0]
- previous_is_near_full = previous_width >= 0.8 * maximum_row_width
- current_is_indented = current[1][0] - base_left > indent_threshold
- same_left_compact_continuation = (
- not first_line_is_indented
- and previous_width >= 0.7 * maximum_row_width
- and abs(current[1][0] - previous[1][0]) <= 0.5 * indent_threshold
- and _title_fonts_compatible(previous[0], current[0])
- and _effective_text_row_gap(previous, current) <= indent_threshold
- )
- # 满行后必然续接;其余行按首页观测到的首行/续行缩进模式决定边界。
- continues_previous = (
- previous_is_near_full
- or same_left_compact_continuation
- or (not current_is_indented if first_line_is_indented else current_is_indented)
- )
- if continues_previous:
- entries[-1].append(current[0])
- else:
- entries.append([current[0]])
- return entries
-
-
-def _tight_page_footnote_bboxes(
- lines: list[_LineItem],
- page_size: tuple[float, float],
-) -> dict[int, BBox]:
- """以有效行高和相邻行距收紧脚注框,避免异常字体框跨入相邻条目。"""
-
- if not lines:
- return {}
- angle = lines[0].angle
- line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines]
- line_geometry.sort(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 line_geometry)
- row_pitches = [
- current[1][1] - previous[1][1]
- for previous, current in zip(line_geometry, line_geometry[1:])
- if current[1][1] - previous[1][1] > 0.25 * median_height
- ]
- median_pitch = statistics.median(row_pitches) if row_pitches else None
-
- output: dict[int, BBox] = {}
- for line, bbox in line_geometry:
- tight_height = min(
- bbox[3] - bbox[1],
- _line_effective_height(line, bbox),
- )
- if median_pitch is not None:
- tight_height = min(tight_height, 0.9 * median_pitch)
- tight_height = max(0.1, tight_height)
- center_y = _bbox_center_y(bbox)
- tight_local_bbox = (
- bbox[0],
- center_y - 0.5 * tight_height,
- bbox[2],
- center_y + 0.5 * tight_height,
- )
- output[line.source_index] = _rotate_bbox_from_upright(
- tight_local_bbox,
- page_size,
- angle,
- )
- 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 _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 _centered_visual_reset_break_sources(
- lane: _TextLane,
- visual_bboxes: Sequence[BBox],
- local_page_height: float,
-) -> set[int]:
- """识别视觉主体下方短居中行到更宽居中行的独立注释重启。"""
-
- if not visual_bboxes:
- return set()
- 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: set[int] = set()
- for previous, current in zip(rows, rows[1:]):
- previous_bbox = previous[1]
- current_bbox = current[1]
- previous_width = previous_bbox[2] - previous_bbox[0]
- current_width = current_bbox[2] - current_bbox[0]
- pair_height = max(
- _line_effective_height(*previous),
- _line_effective_height(*current),
- )
- if (
- previous_width > 0.7 * current_width
- or current_bbox[0] > previous_bbox[0] - 0.25 * pair_height
- or current_bbox[2] < previous_bbox[2] + 0.25 * pair_height
- or abs(_bbox_center_x(previous_bbox) - _bbox_center_x(current_bbox)) > 0.1 * current_width
- ):
- continue
- vertical_gap = _effective_text_row_gap(previous, current)
- if not -0.25 * pair_height <= vertical_gap <= 0.75 * pair_height:
- continue
- if any(
- -0.25 * pair_height <= previous_bbox[1] - visual_bbox[3] <= max(2.0 * pair_height, 0.03 * local_page_height)
- and _bbox_axis_overlap_ratio(current_bbox, visual_bbox, axis="x") >= 0.8
- and abs(_bbox_center_x(current_bbox) - _bbox_center_x(visual_bbox))
- <= 0.12 * max(current_width, visual_bbox[2] - visual_bbox[0])
- for visual_bbox in visual_bboxes
- ):
- output.add(current[0].source_index)
- return output
-
-
-def _leading_typography_reset_break_sources(
- lane: _TextLane,
- regular_gap: float,
- gap_mad: float,
-) -> set[int]:
- """识别短尾之后以独立行首字体 run 开启的宽行结构段。"""
-
- 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()
- for previous, current in zip(rows, rows[1:]):
- previous_width = previous[1][2] - previous[1][0]
- current_width = current[1][2] - current[1][0]
- pair_height = max(
- _line_effective_height(*previous),
- _line_effective_height(*current),
- )
- if (
- current[0].leading_typography_width is None
- or current[0].leading_typography_width > 0.2 * lane_width
- or previous_width > 0.45 * lane_width
- or current_width < 0.75 * lane_width
- or abs(previous[1][0] - lane.left) > 0.75 * pair_height
- or abs(current[1][0] - lane.left) > 0.75 * pair_height
- or current[0].formula_candidate_only
- or current[0].compact_formula_cluster
- or current[0].inline_math_regions
- ):
- continue
- vertical_gap = _effective_body_text_row_gap(previous, current)
- if (
- -0.25 * pair_height
- <= vertical_gap
- <= regular_gap
- + max(
- 0.75 * pair_height,
- 3.0 * gap_mad,
- )
- ):
- output.add(current[0].source_index)
- return output
-
-
-def _formula_style_text_row_break_sources(
- lane: _TextLane,
-) -> 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)
- matching_edges: set[int] = set()
- for index, (previous, current) in enumerate(zip(rows, rows[1:])):
- previous_line, previous_bbox = previous
- current_line, current_bbox = current
- if not (
- previous_line.paragraph_formula_context
- and current_line.paragraph_formula_context
- ):
- continue
- previous_height = _line_effective_height(*previous)
- current_height = _line_effective_height(*current)
- minimum_height = min(previous_height, current_height)
- maximum_height = max(previous_height, current_height)
- if minimum_height < 0.75 * maximum_height:
- continue
- previous_width = previous_bbox[2] - previous_bbox[0]
- current_width = current_bbox[2] - current_bbox[0]
- if (
- min(previous_width, current_width) < 0.45 * lane_width
- or max(previous_width, current_width) > 0.95 * lane_width
- ):
- continue
- lane_center = 0.5 * (lane.left + lane.right)
- if (
- abs(_bbox_center_x(previous_bbox) - lane_center) > 0.15 * lane_width
- or abs(_bbox_center_x(current_bbox) - lane_center) > 0.15 * lane_width
- ):
- continue
- vertical_overlap = max(
- 0.0,
- min(previous_bbox[3], current_bbox[3])
- - max(previous_bbox[1], current_bbox[1]),
- )
- top_pitch = current_bbox[1] - previous_bbox[1]
- pair_height = statistics.median((previous_height, current_height))
- if (
- vertical_overlap <= 0.2 * minimum_height
- and 0.9 * pair_height <= top_pitch <= 2.0 * pair_height
- ):
- matching_edges.add(index)
-
- output: set[int] = set()
- for index in matching_edges:
- output.add(rows[index][0].source_index)
- output.add(rows[index + 1][0].source_index)
- if index + 2 < len(rows):
- # 同时保护显示行组后的正文起点,避免上下文恢复阶段重新跨界合并。
- output.add(rows[index + 2][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_FIELD_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],
- page_size: tuple[float, float],
- drawing_lines: list[_AxisLine] | None = None,
- *,
- page_footnote_groups: Sequence[set[int]] | None = None,
- page_index: int | None = None,
- visual_bboxes: Sequence[BBox] | None = None,
-) -> list[dict[str, Any]]:
- """先构建分组脚注,再按类型屏障、栏带和自然段边界聚合其余文本。"""
-
- blocks, grouped_footnote_indices = _build_grouped_page_footnote_blocks(
- lines,
- page_footnote_groups or [],
- page_size,
- )
- lines = [line for line in lines if line.source_index not in grouped_footnote_indices]
- for angle in sorted({line.angle for line in lines}):
- line_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]
- if not line_geometry:
- continue
- line_geometry.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
- 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]
- local_visual_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in (visual_bboxes or [])]
- 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] = {}
- for line, _bbox in line_geometry:
- if line.visual_row_id is not None and line.split_from_row:
- split_row_counts[line.visual_row_id] = split_row_counts.get(line.visual_row_id, 0) + 1
-
- for lane in lanes:
- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
- 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,
- )
- isolated_break_sources = _isolated_indented_paragraph_break_sources(
- lane,
- regular_gap,
- gap_mad,
- )
- structured_break_sources.update(
- isolated_break_sources,
- )
- visual_reset_sources = _centered_visual_reset_break_sources(
- lane,
- local_visual_bboxes,
- local_page_height,
- )
- typography_reset_sources = _leading_typography_reset_break_sources(
- lane,
- regular_gap,
- gap_mad,
- )
- formula_text_break_sources = _formula_style_text_row_break_sources(
- lane,
- )
- structured_break_sources.update(visual_reset_sources)
- structured_break_sources.update(typography_reset_sources)
- structured_break_sources.update(formula_text_break_sources)
- protected_break_sources: set[int] = set()
- protected_break_sources.update(visual_reset_sources)
- protected_break_sources.update(typography_reset_sources)
- protected_break_sources.update(formula_text_break_sources)
- 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,
- local_axis_lines,
- )
- component: list[tuple[_LineItem, BBox]] = [lane.lines[0]]
- components: list[list[tuple[_LineItem, BBox]]] = []
- for previous, current in zip(lane.lines, lane.lines[1:]):
- previous_type = previous[0].semantic_type
- current_type = current[0].semantic_type
- if previous_type != current_type:
- should_connect = False
- elif previous_type is not None:
- should_connect = _should_connect_semantic_rows(
- previous,
- current,
- lane,
- regular_gap,
- table_bboxes,
- local_axis_lines,
- )
- else:
- previous_group = hanging_indent_groups.get(previous[0].source_index)
- current_group = hanging_indent_groups.get(current[0].source_index)
- 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].style_scale_repaired
- and current[0].split_from_row
- and current[0].visual_row_id is not None
- and split_row_counts.get(
- current[0].visual_row_id,
- 0,
- )
- >= 2
- ):
- should_connect = False
- elif 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):
- # 断词续行优先于悬挂缩进分组,但仍复用正文连接中的距离和障碍限制。
- should_connect = _should_connect_text_rows(
- previous,
- current,
- connection_lane,
- regular_gap,
- gap_mad,
- table_bboxes,
- local_axis_lines,
- )
- elif previous_group is not None or current_group is not None:
- should_connect = previous_group is not None and previous_group == current_group
- else:
- should_connect = _should_connect_text_rows(
- previous,
- current,
- connection_lane,
- regular_gap,
- gap_mad,
- table_bboxes,
- local_axis_lines,
- )
- if should_connect:
- component.append(current)
- else:
- components.append(component)
- component = [current]
- components.append(component)
-
- 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(
- normalized for line in component_lines if (normalized := _normalize_native_run_text(line.text))
- )
- else:
- content = _merge_text_line_content([line.text for line in component_lines])
- if not content:
- continue
- visual_row_ids = {line.visual_row_id for line in component_lines if line.visual_row_id is not None}
- single_run_row_id = (
- component_lines[0].visual_row_id
- if len(component_lines) == 1
- and component_lines[0].split_from_row
- and component_lines[0].visual_row_id is not None
- else None
- )
- local_output_line_bboxes, output_bbox_repaired = _local_tight_output_line_bboxes(
- component_lines,
- page_size,
- angle,
- )
- blocks.append(
- {
- "type": component_lines[0].semantic_type or "text",
- "bbox": _bbox_union_many([line.bbox for line in component_lines]),
- "angle": angle,
- "content": content,
- "_visual_row_ids": visual_row_ids,
- "_single_run_row_id": single_run_row_id,
- "_local_line_bboxes": [bbox for _line, bbox in component_geometry],
- "_local_output_line_bboxes": local_output_line_bboxes,
- "_output_bbox_repaired": output_bbox_repaired,
- "_line_heights": [_line_effective_height(line, bbox) for line, bbox in component_geometry],
- "_font_signatures": {
- line.font_signature
- for line in component_lines
- if line.font_signature is not None and line.font_coverage >= 0.5
- },
- "_inline_math_regions": [region for line in component_lines for region in line.inline_math_regions],
- _PARAGRAPH_FORMULA_CONTEXT_MARKER: any(line.paragraph_formula_context for line in component_lines),
- "_lane_interval": (
- component_local_lane.left,
- 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_short_same_baseline_prefix_blocks(
- blocks,
- page_size,
- )
- 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)
- blocks = _merge_inline_math_fragment_text_blocks(
- blocks,
- page_size,
- )
- return _merge_paragraph_formula_context_blocks(
- blocks,
- page_size,
- )
-
-
-def _merge_short_same_baseline_prefix_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """合并括号序号或时刻等短前缀与右侧同基线正文。"""
-
- replacements: dict[int, dict[str, Any]] = {}
- consumed: set[int] = set()
- for prefix_index, prefix in enumerate(blocks):
- prefix_rows = prefix.get("_local_line_bboxes")
- prefix_content = str(prefix.get("content") or "").strip()
- if (
- prefix_index in consumed
- or prefix.get("type") != "text"
- or not isinstance(prefix_rows, list)
- or len(prefix_rows) != 1
- or _SHORT_SAME_BASELINE_PREFIX_RE.match(prefix_content) is None
- ):
- continue
- prefix_bbox = prefix_rows[0]
- prefix_heights = [
- float(height)
- for height in prefix.get("_line_heights", [])
- if isinstance(height, (int, float)) and float(height) > 0
- ]
- prefix_height = statistics.median(prefix_heights) if prefix_heights else max(0.1, prefix_bbox[3] - prefix_bbox[1])
- angle = int(prefix.get("angle", 0) or 0) % 360
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- matches: list[tuple[float, int]] = []
- for host_index, host in enumerate(blocks):
- host_rows = host.get("_local_line_bboxes")
- if (
- host_index == prefix_index
- or host_index in consumed
- or host.get("type") != "text"
- or int(host.get("angle", 0) or 0) % 360 != angle
- or not isinstance(host_rows, list)
- or not host_rows
- ):
- continue
- host_bbox = host_rows[0]
- host_width = host_bbox[2] - host_bbox[0]
- horizontal_gap = host_bbox[0] - prefix_bbox[2]
- if (
- host_bbox[0] < prefix_bbox[2]
- or horizontal_gap > 1.25 * prefix_height
- or host_width < 0.15 * local_page_width
- or _bbox_axis_overlap_ratio(
- prefix_bbox,
- host_bbox,
- axis="y",
- )
- < 0.5
- ):
- continue
- matches.append((horizontal_gap, host_index))
- if not matches:
- continue
- _gap, host_index = min(matches)
- replacement_index = min(prefix_index, host_index)
- replacement = _merge_internal_text_block_group(
- blocks,
- [prefix_index, host_index],
- preserve_visual_spaces=True,
- )
- replacement["type"] = "text"
- replacements[replacement_index] = replacement
- consumed.update({prefix_index, host_index})
- return [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
-
-
-def _blocks_share_boundary_visual_row(
- first: dict[str, Any],
- second: dict[str, Any],
- pair_height: float,
-) -> bool:
- """检查前块末行与后块首行是否为被错误切开的同一视觉行。"""
-
- first_rows = first.get("_local_line_bboxes")
- second_rows = second.get("_local_line_bboxes")
- if (
- not isinstance(first_rows, list)
- or not isinstance(second_rows, list)
- or max(len(first_rows), len(second_rows)) < 3
- or len(first_rows) + len(second_rows) > 6
- or not _components_share_lane_role(first, second, pair_height)
- ):
- return False
- if first["bbox"][1] <= second["bbox"][1]:
- upper_rows, lower_rows = first_rows, second_rows
- else:
- upper_rows, lower_rows = second_rows, first_rows
- upper_boundary = max(upper_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
- lower_boundary = min(lower_rows, key=lambda bbox: (_bbox_center_y(bbox), bbox[0]))
- vertical_overlap = max(
- 0.0,
- min(upper_boundary[3], lower_boundary[3]) - max(upper_boundary[1], lower_boundary[1]),
- )
- shorter_height = max(
- 0.1,
- min(
- upper_boundary[3] - upper_boundary[1],
- lower_boundary[3] - lower_boundary[1],
- ),
- )
- horizontal_gap = lower_boundary[0] - upper_boundary[2]
- union_bbox = _bbox_union_many([first["bbox"], second["bbox"]])
- return (
- vertical_overlap / shorter_height >= 0.7
- and -0.2 * pair_height <= horizontal_gap <= 0.75 * pair_height
- and union_bbox[3] - union_bbox[1] <= 6.0 * pair_height
- )
-
-
-def _merge_overlapping_same_line_text_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """合并块体或边界视觉行重叠的宽正文块,修复错误分栏。"""
-
- consumed: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- for first_index, first in enumerate(blocks):
- first_bbox = first.get("bbox")
- first_rows = first.get("_local_line_bboxes")
- angle = int(first.get("angle", 0) or 0) % 360
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- if (
- first_index in consumed
- or first.get("type") != "text"
- or not isinstance(first_bbox, (list, tuple))
- or not isinstance(first_rows, list)
- or not 1 <= len(first_rows) <= 5
- or first_bbox[2] - first_bbox[0] < 0.3 * local_page_width
- ):
- continue
- first_heights = [
- float(height) for height in first.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
- ]
- first_height = statistics.median(first_heights) if first_heights else first_bbox[3] - first_bbox[1]
- for second_index in range(first_index + 1, len(blocks)):
- second = blocks[second_index]
- second_bbox = second.get("bbox")
- second_rows = second.get("_local_line_bboxes")
- if (
- second_index in consumed
- or second.get("type") != "text"
- or int(second.get("angle", 0) or 0) % 360 != angle
- or not isinstance(second_bbox, (list, tuple))
- or not isinstance(second_rows, list)
- or not 1 <= len(second_rows) <= 5
- 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
- ]
- second_height = statistics.median(second_heights) if second_heights else second_bbox[3] - second_bbox[1]
- pair_height = max(first_height, second_height, 0.1)
- vertical_overlap = max(
- 0.0,
- min(first_bbox[3], second_bbox[3]) - max(first_bbox[1], second_bbox[1]),
- )
- minimum_box_height = max(
- 0.1,
- min(
- first_bbox[3] - first_bbox[1],
- second_bbox[3] - second_bbox[1],
- ),
- )
- first_fonts = first.get("_font_signatures")
- second_fonts = second.get("_font_signatures")
- fonts_conflict = (
- isinstance(first_fonts, set)
- and isinstance(second_fonts, set)
- and first_fonts
- and second_fonts
- and first_fonts.isdisjoint(second_fonts)
- )
- compact_overlap = (
- len(first_rows) <= 2
- and len(second_rows) <= 2
- and min(len(first_rows), len(second_rows)) == 1
- and abs(first_bbox[0] - second_bbox[0]) <= pair_height
- and vertical_overlap / minimum_box_height >= 0.5
- and _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x") >= 0.75
- )
- boundary_overlap = _blocks_share_boundary_visual_row(
- first,
- second,
- pair_height,
- )
- if fonts_conflict or not (compact_overlap or boundary_overlap):
- continue
- union_bbox = _bbox_union_many([first_bbox, second_bbox])
- if not boundary_overlap and union_bbox[3] - union_bbox[1] > 4.0 * pair_height:
- continue
- replacement_index = min(first_index, second_index)
- replacements[replacement_index] = _merge_internal_text_block_group(
- blocks,
- [first_index, second_index],
- )
- consumed.update({first_index, second_index})
- break
- return [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
-
-
-def _merge_inline_math_fragment_text_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """把同一宽正文行上下叠放的多个小数学碎片收回一个文本块。"""
-
- consumed: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- for host_index, host in enumerate(blocks):
- host_bbox = host.get("bbox")
- host_heights = host.get("_line_heights")
- host_rows = host.get("_local_line_bboxes")
- angle = int(host.get("angle", 0) or 0) % 360
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- if (
- host_index in consumed
- or host.get("type") != "text"
- or (host.get("_single_run_row_id") is None and (not isinstance(host_rows, list) or len(host_rows) > 2))
- or not isinstance(host_bbox, (list, tuple))
- or host_bbox[2] - host_bbox[0] < 0.35 * local_page_width
- or not isinstance(host_heights, list)
- or not host_heights
- ):
- continue
- host_height = statistics.median(
- float(height) for height in host_heights if isinstance(height, (int, float)) and height > 0
- )
- fragment_indices: list[int] = []
- for candidate_index, candidate in enumerate(blocks):
- candidate_bbox = candidate.get("bbox")
- candidate_rows = candidate.get("_local_line_bboxes")
- if (
- candidate_index == host_index
- or candidate_index in consumed
- or candidate.get("type") != "text"
- or int(candidate.get("angle", 0) or 0) % 360 != angle
- or not isinstance(candidate_bbox, (list, tuple))
- or not isinstance(candidate_rows, list)
- or len(candidate_rows) != 1
- or candidate_bbox[2] - candidate_bbox[0] > 0.25 * (host_bbox[2] - host_bbox[0])
- or _bbox_axis_overlap_ratio(
- host_bbox,
- candidate_bbox,
- axis="x",
- )
- <= 0.0
- ):
- continue
- union_bbox = _bbox_union_many([host_bbox, candidate_bbox])
- vertical_gap = max(
- 0.0,
- max(host_bbox[1], candidate_bbox[1]) - min(host_bbox[3], candidate_bbox[3]),
- )
- if vertical_gap <= 0.75 * host_height and union_bbox[3] - union_bbox[1] <= 3.5 * host_height:
- fragment_indices.append(candidate_index)
- if len(fragment_indices) < 2:
- continue
- group_indices = [host_index, *fragment_indices]
- replacement_index = min(group_indices)
- replacements[replacement_index] = _merge_inline_math_recovery_group(
- blocks,
- group_indices,
- )
- consumed.update(group_indices)
- output = [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
- output = _merge_hostless_inline_math_fragment_blocks(output, page_size)
- output = _merge_residual_narrow_math_text_blocks(output, page_size)
- return _merge_inline_math_paragraph_continuations(output, page_size)
-
-
-def _component_local_union_bbox(
- block: dict[str, Any],
-) -> BBox | None:
- """合并正文组件持有的正向行框,非法或缺失元数据时返回空。"""
-
- rows = block.get("_local_line_bboxes")
- if not isinstance(rows, list):
- return None
- bboxes: list[BBox] = []
- for row in rows:
- if not isinstance(row, (list, tuple)) or len(row) != 4:
- continue
- try:
- bbox = tuple(float(value) for value in row)
- except (TypeError, ValueError):
- continue
- if bbox[2] > bbox[0] and bbox[3] > bbox[1]:
- bboxes.append(bbox) # type: ignore[arg-type]
- return _bbox_union_many(bboxes) if bboxes else None
-
-
-def _merge_paragraph_formula_context_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """把误似行间公式的复杂行内分式与同栏前后正文恢复成一个块。"""
-
- terminal_re = re.compile(
- r"[.!?。!?][\]\)})】》”’'\"]*$",
- )
- consumed: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- seed_indices = [
- index
- for index, block in enumerate(blocks)
- if block.get("type") == "text" and block.get(_PARAGRAPH_FORMULA_CONTEXT_MARKER) is True
- ]
- for seed_index in seed_indices:
- if seed_index in consumed:
- continue
- group = {seed_index}
- changed = True
- while changed:
- changed = False
- for candidate_index, candidate in enumerate(blocks):
- if candidate_index in group or candidate_index in consumed or candidate.get("type") != "text":
- continue
- for member_index in group:
- member = blocks[member_index]
- if int(candidate.get("angle", 0) or 0) % 360 != int(member.get("angle", 0) or 0) % 360:
- continue
- pair_heights = [
- float(height)
- for block in (candidate, member)
- for height in block.get("_line_heights", [])
- if isinstance(height, (int, float)) and float(height) > 0
- ]
- if not pair_heights:
- continue
- pair_height = statistics.median(pair_heights)
- if not _components_share_lane_role(
- candidate,
- member,
- pair_height,
- ):
- continue
- candidate_bbox = _component_local_union_bbox(candidate)
- member_bbox = _component_local_union_bbox(member)
- if candidate_bbox is None or member_bbox is None:
- continue
- vertical_gap = max(
- candidate_bbox[1] - member_bbox[3],
- member_bbox[1] - candidate_bbox[3],
- 0.0,
- )
- if vertical_gap > 1.5 * pair_height:
- continue
- candidate_below = candidate_bbox[1] >= member_bbox[3]
- member_below = member_bbox[1] >= candidate_bbox[3]
- if candidate_below and (
- candidate.get("_hard_break_before") is True
- or terminal_re.search(str(member.get("content") or "").rstrip()) is not None
- ):
- continue
- if member_below and (
- member.get("_hard_break_before") is True
- or terminal_re.search(str(candidate.get("content") or "").rstrip()) is not None
- ):
- continue
- group.add(candidate_index)
- changed = True
- break
- if changed:
- break
- if len(group) < 2:
- continue
- ordered_group = sorted(group)
- replacement_index = min(ordered_group)
- merged = _merge_internal_text_block_group(
- blocks,
- ordered_group,
- )
- local_rows = [
- bbox for bbox in merged.get("_local_line_bboxes", []) if isinstance(bbox, (list, tuple)) and len(bbox) == 4
- ]
- maximum_width = max(
- (bbox[2] - bbox[0] for bbox in local_rows),
- default=0.0,
- )
- body_rows = [bbox for bbox in local_rows if bbox[2] - bbox[0] >= 0.75 * maximum_width]
- if len(body_rows) >= 2:
- # 复杂分式可能比正文左缘多探出少量 glyph;公开框按重复满行边界稳定收口。
- local_merged_bbox = _bbox_union_many(local_rows)
- local_output_bbox = (
- min(bbox[0] for bbox in body_rows),
- local_merged_bbox[1],
- max(bbox[2] for bbox in body_rows),
- local_merged_bbox[3],
- )
- merged["bbox"] = _rotate_bbox_from_upright(
- local_output_bbox,
- page_size,
- int(merged.get("angle", 0) or 0) % 360,
- )
- replacements[replacement_index] = merged
- 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_residual_narrow_math_text_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """把仍嵌在宽正文行范围内的单个窄数学碎片吸收到唯一宿主块。"""
-
- consumed: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- for candidate_index, candidate in enumerate(blocks):
- candidate_bbox = candidate.get("bbox")
- candidate_rows = candidate.get("_local_line_bboxes")
- angle = int(candidate.get("angle", 0) or 0) % 360
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- if (
- candidate.get("type") != "text"
- or not isinstance(candidate_bbox, (list, tuple))
- or not isinstance(candidate_rows, list)
- or len(candidate_rows) != 1
- or candidate_bbox[2] - candidate_bbox[0] > 0.05 * local_page_width
- ):
- continue
- candidate_heights = [
- float(height) for height in candidate.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
- ]
- candidate_height = statistics.median(candidate_heights) if candidate_heights else candidate_bbox[3] - candidate_bbox[1]
- hosts: list[tuple[float, float, int]] = []
- for host_index, host in enumerate(blocks):
- host_bbox = host.get("bbox")
- host_heights = [
- float(height) for height in host.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
- ]
- if (
- host_index == candidate_index
- or host_index in consumed
- or host.get("type") != "text"
- or int(host.get("angle", 0) or 0) % 360 != angle
- or not isinstance(host_bbox, (list, tuple))
- or host_bbox[2] - host_bbox[0] < 0.3 * local_page_width
- or candidate_bbox[0] < host_bbox[0]
- or candidate_bbox[2] > host_bbox[2]
- ):
- continue
- host_height = statistics.median(host_heights) if host_heights else host_bbox[3] - host_bbox[1]
- vertical_overlap = max(
- 0.0,
- min(candidate_bbox[3], host_bbox[3]) - max(candidate_bbox[1], host_bbox[1]),
- )
- vertical_gap = max(
- 0.0,
- max(candidate_bbox[1], host_bbox[1]) - min(candidate_bbox[3], host_bbox[3]),
- )
- pair_height = max(candidate_height, host_height, 0.1)
- union_bbox = _bbox_union_many([candidate_bbox, host_bbox])
- if (
- vertical_overlap < 0.35 * min(candidate_height, host_height) and vertical_gap > 0.5 * pair_height
- ) or union_bbox[3] - union_bbox[1] > 3.0 * pair_height:
- continue
- hosts.append(
- (
- -vertical_overlap,
- abs(_bbox_center_y(candidate_bbox) - _bbox_center_y(host_bbox)),
- host_index,
- )
- )
- if len(hosts) != 1:
- continue
- host_index = hosts[0][2]
- replacement_index = min(candidate_index, host_index)
- replacements[replacement_index] = _merge_inline_math_recovery_group(
- blocks,
- [candidate_index, host_index],
- )
- consumed.update({candidate_index, host_index})
- return [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
-
-
-def _merge_hostless_inline_math_fragment_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """把没有单一宽宿主但在一栏内二维密集排列的数学碎片合成文本块。"""
-
- grouped_indices: list[list[int]] = []
- for angle in sorted({int(block.get("angle", 0) or 0) % 360 for block in blocks if block.get("type") == "text"}):
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- candidates = {
- index
- for index, block in enumerate(blocks)
- if block.get("type") == "text"
- and int(block.get("angle", 0) or 0) % 360 == angle
- and isinstance(block.get("bbox"), (list, tuple))
- and isinstance(block.get("_local_line_bboxes"), list)
- and len(block["_local_line_bboxes"]) == 1
- and block["bbox"][2] - block["bbox"][0] <= 0.25 * local_page_width
- }
- while candidates:
- component = {candidates.pop()}
- changed = True
- while changed:
- changed = False
- for candidate_index in list(candidates):
- candidate_bbox = blocks[candidate_index]["bbox"]
- candidate_heights = blocks[candidate_index].get(
- "_line_heights",
- [],
- )
- candidate_height = (
- statistics.median(candidate_heights) if candidate_heights else candidate_bbox[3] - candidate_bbox[1]
- )
- if any(
- (
- max(
- 0.0,
- max(candidate_bbox[1], blocks[index]["bbox"][1])
- - min(candidate_bbox[3], blocks[index]["bbox"][3]),
- )
- <= 0.75
- * max(
- candidate_height,
- statistics.median(blocks[index].get("_line_heights", []))
- if blocks[index].get("_line_heights")
- else blocks[index]["bbox"][3] - blocks[index]["bbox"][1],
- )
- and max(
- 0.0,
- max(candidate_bbox[0], blocks[index]["bbox"][0])
- - min(candidate_bbox[2], blocks[index]["bbox"][2]),
- )
- <= 1.5
- * max(
- candidate_height,
- statistics.median(blocks[index].get("_line_heights", []))
- if blocks[index].get("_line_heights")
- else blocks[index]["bbox"][3] - blocks[index]["bbox"][1],
- )
- )
- for index in component
- ):
- component.add(candidate_index)
- candidates.remove(candidate_index)
- changed = True
- if len(component) < 4:
- continue
- component_heights = [
- float(height)
- for index in component
- for height in blocks[index].get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
- ]
- if not component_heights:
- continue
- median_height = statistics.median(component_heights)
- union_bbox = _bbox_union_many([blocks[index]["bbox"] for index in component])
- font_signatures = set().union(
- *[
- signatures
- for index in component
- if isinstance(
- (signatures := blocks[index].get("_font_signatures")),
- set,
- )
- ]
- )
- if (
- len(font_signatures) < 2
- or not 0.25 * local_page_width <= union_bbox[2] - union_bbox[0] <= 0.5 * local_page_width
- or union_bbox[3] - union_bbox[1] > 3.5 * median_height
- or sum(blocks[index]["bbox"][2] - blocks[index]["bbox"][0] >= 3.5 * median_height for index in component) < 2
- ):
- continue
- grouped_indices.append(sorted(component))
-
- consumed: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- for group in grouped_indices:
- if any(index in consumed for index in group):
- continue
- replacement_index = min(group)
- replacements[replacement_index] = _merge_inline_math_recovery_group(
- blocks,
- group,
- )
- consumed.update(group)
- return [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
-
-
-def _merge_inline_math_recovery_group(
- blocks: list[dict[str, Any]],
- indices: list[int],
-) -> dict[str, Any]:
- """合并数学碎片并保留仅供后续段落闭合使用的内部标记。"""
- member_bboxes = [blocks[index]["bbox"] for index in indices]
- widths = [bbox[2] - bbox[0] for bbox in member_bboxes]
- maximum_width = max(widths, default=0.0)
- detected_regions = [
- bbox for bbox, width in zip(member_bboxes, widths) if maximum_width <= 0 or width <= 0.25 * maximum_width
- ]
- if not detected_regions:
- detected_regions = list(member_bboxes)
- merged = _merge_internal_text_block_group(blocks, indices)
- merged[_INLINE_MATH_RECOVERY_MARKER] = True
- merged["_inline_math_regions"] = [
- *merged.get("_inline_math_regions", []),
- *detected_regions,
- ]
- return merged
-
-
-def _merge_inline_math_paragraph_continuations(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """在数学碎片恢复后,合并同栏连续且足够宽的正文段落块。"""
-
- if sum(block.get(_INLINE_MATH_RECOVERY_MARKER) is True for block in blocks) < 2:
- return blocks
-
- lane_groups: list[list[int]] = []
- for index, block in sorted(
- enumerate(blocks),
- key=lambda item: (
- int(item[1].get("angle", 0) or 0) % 360,
- _text_component_sort_key(item[1])
- if isinstance(item[1].get("_local_line_bboxes"), list) and item[1]["_local_line_bboxes"]
- else (float("inf"), float("inf")),
- ),
- ):
- local_rows = block.get("_local_line_bboxes")
- if (
- block.get("type") != "text"
- or not isinstance(block.get("_lane_is_span"), bool)
- or not isinstance(local_rows, list)
- or not local_rows
- ):
- continue
- block_heights = [
- float(height) for height in block.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
- ]
- if not block_heights:
- continue
- for lane_group in lane_groups:
- representative = blocks[lane_group[0]]
- if int(representative.get("angle", 0) or 0) % 360 != int(block.get("angle", 0) or 0) % 360:
- continue
- representative_heights = [
- float(height)
- for height in representative.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
- ]
- pair_height = statistics.median([*representative_heights, *block_heights])
- if _components_share_lane_role(representative, block, pair_height):
- lane_group.append(index)
- break
- else:
- lane_groups.append([index])
-
- candidate_chains: list[list[int]] = []
- for lane_group in lane_groups:
- ordered_indices = sorted(
- lane_group,
- key=lambda index: _text_component_sort_key(blocks[index]),
- )
- chain = [ordered_indices[0]]
- for current_index in ordered_indices[1:]:
- previous_index = chain[-1]
- previous = blocks[previous_index]
- current = blocks[current_index]
- previous_rows = previous["_local_line_bboxes"]
- current_rows = current["_local_line_bboxes"]
- previous_local_bbox = _bbox_union_many(previous_rows)
- current_local_bbox = _bbox_union_many(current_rows)
- pair_heights = [
- float(height)
- for block in (previous, current)
- for height in block.get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
- ]
- pair_height = statistics.median(pair_heights)
- angle = int(previous.get("angle", 0) or 0) % 360
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- lane_width = _compatible_component_lane_width(
- previous,
- current,
- local_page_width,
- pair_height,
- )
- previous_fonts = previous.get("_font_signatures")
- current_fonts = current.get("_font_signatures")
- fonts_conflict = (
- isinstance(previous_fonts, set)
- and isinstance(current_fonts, set)
- and previous_fonts
- and current_fonts
- and previous_fonts.isdisjoint(current_fonts)
- )
- vertical_gap = current_local_bbox[1] - previous_local_bbox[3]
- connects = (
- _components_share_lane_role(previous, current, pair_height)
- and previous_local_bbox[2] - previous_local_bbox[0] >= 0.8 * lane_width
- and current_local_bbox[2] - current_local_bbox[0] >= 0.8 * lane_width
- and abs(previous_local_bbox[0] - current_local_bbox[0]) <= 0.75 * pair_height
- and -0.75 * pair_height <= vertical_gap <= 0.75 * pair_height
- and not fonts_conflict
- and not _component_connection_skips_block(
- blocks,
- previous_index,
- current_index,
- pair_height,
- )
- )
- if connects:
- chain.append(current_index)
- else:
- candidate_chains.append(chain)
- chain = [current_index]
- candidate_chains.append(chain)
-
- consumed: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- for chain in candidate_chains:
- if len(chain) < 3 or sum(blocks[index].get(_INLINE_MATH_RECOVERY_MARKER) is True for index in chain) < 2:
- continue
- chain_heights = [
- float(height)
- for index in chain
- for height in blocks[index].get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
- ]
- median_height = statistics.median(chain_heights)
- local_union = _bbox_union_many([bbox for index in chain for bbox in blocks[index]["_local_line_bboxes"]])
- if local_union[3] - local_union[1] > 24.0 * median_height:
- continue
- replacement_index = min(chain)
- merged = _merge_internal_text_block_group(blocks, chain)
- merged[_INLINE_MATH_RECOVERY_MARKER] = True
- replacements[replacement_index] = merged
- consumed.update(chain)
- return [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
-
-
-def _merge_image_caption_text_blocks(
- blocks: list[dict[str, Any]],
- image_bboxes: list[BBox],
-) -> list[dict[str, Any]]:
- """在图像邻接已成立后,用通用图注标记确认锚点并吸收同字体续行。"""
-
- if not image_bboxes:
- return blocks
- text_indices = [
- index
- for index, block in enumerate(blocks)
- if block.get("type") == "text"
- and isinstance(block.get("content"), str)
- and isinstance(block.get("bbox"), (list, tuple))
- ]
- all_heights = [
- float(height)
- for index in text_indices
- for height in blocks[index].get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
- ]
- median_height = statistics.median(all_heights) if all_heights else 1.0
- caption_image_bboxes = _caption_image_group_bboxes(
- image_bboxes,
- median_height,
- )
- seed_indices = {
- index
- for index in text_indices
- if _FIGURE_CAPTION_MARKER_RE.match(str(blocks[index]["content"]).strip())
- and any(
- _caption_seed_matches_image(
- blocks[index],
- image_bbox,
- median_height,
- )
- for image_bbox in caption_image_bboxes
- )
- }
- if not seed_indices:
- return blocks
-
- assignments: dict[int, list[int]] = {index: [] for index in seed_indices}
- for candidate_index in text_indices:
- if candidate_index in seed_indices:
- continue
- candidate = blocks[candidate_index]
- matches: list[tuple[float, float, int]] = []
- for seed_index in seed_indices:
- seed = blocks[seed_index]
- if not _caption_tail_matches_seed(
- seed,
- candidate,
- median_height,
- ):
- continue
- seed_bbox = seed["bbox"]
- candidate_bbox = candidate["bbox"]
- matches.append(
- (
- _bbox_center_y(candidate_bbox) - _bbox_center_y(seed_bbox),
- abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(seed_bbox)),
- seed_index,
- )
- )
- if matches:
- assignments[min(matches)[2]].append(candidate_index)
-
- merged_indices: set[int] = set()
- replacements: dict[int, dict[str, Any]] = {}
- for seed_index, tail_indices in assignments.items():
- if not tail_indices:
- continue
- group_indices = [seed_index, *tail_indices]
- replacements[seed_index] = _merge_internal_text_block_group(
- blocks,
- group_indices,
- )
- merged_indices.update(tail_indices)
- return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in merged_indices]
-
-
-def _caption_image_group_bboxes(
- image_bboxes: list[BBox],
- median_height: float,
-) -> list[BBox]:
- """合并同一视觉行的并排图片 bbox,使跨多图的统一图注也能建立邻接。"""
-
- remaining = list(image_bboxes)
- grouped_bboxes = list(image_bboxes)
- while remaining:
- group = [remaining.pop(0)]
- changed = True
- while changed:
- changed = False
- for candidate in list(remaining):
- aligned = False
- for member in group:
- overlap = max(
- 0.0,
- min(candidate[3], member[3]) - max(candidate[1], member[1]),
- )
- minimum_height = max(
- 0.1,
- min(
- candidate[3] - candidate[1],
- member[3] - member[1],
- ),
- )
- horizontal_gap = max(
- 0.0,
- max(candidate[0], member[0]) - min(candidate[2], member[2]),
- )
- if overlap / minimum_height >= 0.7 and horizontal_gap <= 2.0 * median_height:
- aligned = True
- break
- if aligned:
- group.append(candidate)
- remaining.remove(candidate)
- changed = True
- if len(group) >= 2:
- grouped_bboxes.append(_bbox_union_many(group))
- return grouped_bboxes
-
-
-def _caption_seed_matches_image(
- block: dict[str, Any],
- image_bbox: BBox,
- median_height: float,
-) -> bool:
- """用上下位置、水平投影和居中关系确认图像下方的图注空间候选。"""
-
- bbox = block["bbox"]
- image_width = max(0.1, image_bbox[2] - image_bbox[0])
- block_width = max(0.1, bbox[2] - bbox[0])
- vertical_gap = max(0.0, bbox[1] - image_bbox[3])
- return (
- _bbox_center_y(bbox) >= image_bbox[3] - 0.25 * median_height
- and vertical_gap <= 2.5 * median_height
- and _bbox_axis_overlap_ratio(bbox, image_bbox, axis="x") >= 0.35
- and abs(_bbox_center_x(bbox) - _bbox_center_x(image_bbox)) <= 0.35 * max(image_width, block_width)
- and block_width <= 1.75 * image_width
- )
-
-
-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],
- median_height: float,
-) -> bool:
- """只用同栏角色、字体、邻接和投影把无标记的图注续行接回锚点。"""
-
- seed_bbox = seed["bbox"]
- candidate_bbox = candidate["bbox"]
- if not _components_share_lane_role(seed, candidate, median_height) and (
- _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.75
- or abs(seed_bbox[0] - candidate_bbox[0]) > median_height
- ):
- return False
- if _bbox_center_y(candidate_bbox) <= _bbox_center_y(seed_bbox):
- return False
- if _caption_body_has_structural_gap(seed, candidate):
- return False
- vertical_gap = max(0.0, candidate_bbox[1] - seed_bbox[3])
- if vertical_gap > 0.5 * median_height or _bbox_axis_overlap_ratio(seed_bbox, candidate_bbox, axis="x") < 0.35:
- return False
- seed_fonts = seed.get("_font_signatures")
- candidate_fonts = candidate.get("_font_signatures")
- return not (
- isinstance(seed_fonts, set)
- and seed_fonts
- and isinstance(candidate_fonts, set)
- and candidate_fonts
- and seed_fonts.isdisjoint(candidate_fonts)
- )
-
-
-def _merge_multiline_title_blocks(
- blocks: list[dict[str, Any]],
-) -> list[dict[str, Any]]:
- """跨错误栏带合并紧贴且字体兼容的多行文档标题和段落标题。"""
-
- replacements: dict[int, dict[str, Any]] = {}
- consumed: set[int] = set()
- for block_type in ("doc_title", "paragraph_title"):
- indices = [
- index
- for index, block in enumerate(blocks)
- if block.get("type") == block_type and isinstance(block.get("bbox"), (list, tuple))
- ]
- indices.sort(
- key=lambda index: (
- blocks[index]["bbox"][1],
- blocks[index]["bbox"][0],
- )
- )
- groups: list[list[int]] = []
- for index in indices:
- if not groups:
- groups.append([index])
- continue
- previous_index = groups[-1][-1]
- previous = blocks[previous_index]
- current = blocks[index]
- previous_bbox = previous["bbox"]
- current_bbox = current["bbox"]
- previous_heights = previous.get("_line_heights", [])
- current_heights = current.get("_line_heights", [])
- previous_height = (
- statistics.median(previous_heights)
- if isinstance(previous_heights, list) and previous_heights
- else previous_bbox[3] - previous_bbox[1]
- )
- current_height = (
- statistics.median(current_heights)
- if isinstance(current_heights, list) and current_heights
- else current_bbox[3] - current_bbox[1]
- )
- vertical_gap = current_bbox[1] - previous_bbox[3]
- previous_fonts = previous.get("_font_signatures")
- current_fonts = current.get("_font_signatures")
- fonts_conflict = (
- isinstance(previous_fonts, set)
- and previous_fonts
- and isinstance(current_fonts, set)
- and current_fonts
- and previous_fonts.isdisjoint(current_fonts)
- )
- if (
- -0.2 * max(previous_height, current_height) <= vertical_gap <= 0.4 * max(previous_height, current_height)
- and _bbox_axis_overlap_ratio(
- previous_bbox,
- current_bbox,
- axis="x",
- )
- >= 0.2
- and not fonts_conflict
- ):
- groups[-1].append(index)
- else:
- groups.append([index])
- for group in groups:
- if len(group) < 2:
- continue
- replacements[group[0]] = _merge_internal_text_block_group(
- blocks,
- group,
- )
- consumed.update(group[1:])
- return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
-
-
-def _merge_fragmented_header_blocks(
- blocks: list[dict[str, Any]],
-) -> list[dict[str, Any]]:
- """聚合同一视觉行中等距分散的页眉页脚片段。"""
-
- grouped: dict[tuple[int, int], list[int]] = {}
- for index, block in enumerate(blocks):
- row_id = block.get("_single_run_row_id")
- angle = int(block.get("angle", 0) or 0) % 360
- if block.get("type") in {"header", "footer"} and isinstance(row_id, int):
- grouped.setdefault((angle, row_id), []).append(index)
-
- replacements: dict[int, dict[str, Any]] = {}
- consumed: set[int] = set()
- for indices in grouped.values():
- ordered = sorted(indices, key=lambda index: blocks[index]["bbox"][0])
- components: list[list[int]] = []
- for index in ordered:
- bbox = blocks[index]["bbox"]
- heights = blocks[index].get("_line_heights", [])
- effective_height = (
- statistics.median(heights) if isinstance(heights, list) and heights else max(0.1, bbox[3] - bbox[1])
- )
- if blocks[index].get("type") == "header" and bbox[2] - bbox[0] > 1.25 * effective_height:
- continue
- if not components:
- components.append([index])
- continue
- previous_index = components[-1][-1]
- previous_bbox = blocks[previous_index]["bbox"]
- previous_heights = blocks[previous_index].get("_line_heights", [])
- previous_height = (
- statistics.median(previous_heights)
- if isinstance(previous_heights, list) and previous_heights
- else max(0.1, previous_bbox[3] - previous_bbox[1])
- )
- if (
- bbox[0] - previous_bbox[2] <= 4.0 * max(effective_height, previous_height)
- and _bbox_axis_overlap_ratio(previous_bbox, bbox, axis="y") >= 0.5
- ):
- components[-1].append(index)
- else:
- components.append([index])
- for component in components:
- if len(component) < 2:
- continue
- replacement = _merge_internal_text_block_group(
- blocks,
- component,
- preserve_visual_spaces=True,
- )
- replacement["_single_run_row_id"] = None
- replacements[component[0]] = replacement
- consumed.update(component[1:])
- return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
-
-
-def _merge_front_matter_column_blocks(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
- *,
- page_index: int,
-) -> list[dict[str, Any]]:
- """把首页标题下方规则排列的多列作者信息按列聚合。"""
-
- if page_index != 0:
- return blocks
- page_width, page_height = page_size
- if page_width <= 0 or page_height <= 0:
- return blocks
- title_blocks = [
- block for block in blocks if block.get("type") == "doc_title" and isinstance(block.get("bbox"), (list, tuple))
- ]
- if not title_blocks:
- return blocks
- title_bottom = max(block["bbox"][3] for block in title_blocks)
- candidates = [
- index
- for index, block in enumerate(blocks)
- if block.get("type") == "text"
- and isinstance(block.get("bbox"), (list, tuple))
- and title_bottom < block["bbox"][1]
- and block["bbox"][3]
- <= min(
- 0.4 * page_height,
- title_bottom + 0.22 * page_height,
- )
- and block["bbox"][2] - block["bbox"][0] <= 0.32 * page_width
- and block["bbox"][3] - block["bbox"][1] <= 0.035 * page_height
- ]
- if len(candidates) < 9:
- return blocks
- median_height = statistics.median(blocks[index]["bbox"][3] - blocks[index]["bbox"][1] for index in candidates)
- row_groups: list[list[int]] = []
- for index in sorted(
- candidates,
- key=lambda item: (
- _bbox_center_y(blocks[item]["bbox"]),
- blocks[item]["bbox"][0],
- ),
- ):
- center_y = _bbox_center_y(blocks[index]["bbox"])
- target = next(
- (
- row
- for row in row_groups
- if abs(center_y - statistics.median(_bbox_center_y(blocks[member]["bbox"]) for member in row))
- <= 0.6 * median_height
- ),
- None,
- )
- if target is None:
- row_groups.append([index])
- else:
- target.append(index)
- dense_rows = [
- row
- for row in row_groups
- if 3 <= len(row) <= 6
- and (
- max(blocks[index]["bbox"][2] for index in row) - min(blocks[index]["bbox"][0] for index in row) >= 0.55 * page_width
- )
- ]
- if len(dense_rows) < 2:
- return blocks
- anchor_row = min(
- dense_rows,
- key=lambda row: (
- -len(row),
- statistics.median(_bbox_center_y(blocks[index]["bbox"]) for index in row),
- ),
- )
- anchor_centers = sorted(_bbox_center_x(blocks[index]["bbox"]) for index in anchor_row)
- if len(anchor_centers) != 4:
- return blocks
- boundaries = [0.5 * (left + right) for left, right in zip(anchor_centers, anchor_centers[1:])]
- band_top = min(min(blocks[index]["bbox"][1] for index in row) for row in dense_rows) - median_height
- band_bottom = max(max(blocks[index]["bbox"][3] for index in row) for row in dense_rows) + median_height
- column_groups: list[list[int]] = [[] for _center in anchor_centers]
- for index in candidates:
- bbox = blocks[index]["bbox"]
- if not band_top <= _bbox_center_y(bbox) <= band_bottom:
- continue
- center_x = _bbox_center_x(bbox)
- column_index = sum(center_x > boundary for boundary in boundaries)
- if column_index >= len(column_groups):
- continue
- column_groups[column_index].append(index)
- if any(len(group) < 3 for group in column_groups):
- return blocks
-
- replacements: dict[int, dict[str, Any]] = {}
- consumed: set[int] = set()
- for group in column_groups:
- ordered = sorted(
- group,
- key=lambda index: (
- blocks[index]["bbox"][1],
- blocks[index]["bbox"][0],
- ),
- )
- replacements[ordered[0]] = _merge_internal_text_block_group(
- blocks,
- ordered,
- )
- consumed.update(ordered[1:])
- return [replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed]
-
-
-def _merge_repeated_compact_title_continuations(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """把重复出现的两行弱标题与紧邻异字体续行恢复为普通文本块。"""
-
- candidate_pairs: list[tuple[int, int, float]] = []
- for title_index, title in enumerate(blocks):
- title_lines = title.get("_local_line_bboxes")
- title_fonts = title.get("_font_signatures")
- title_bbox = title.get("bbox")
- if (
- title.get("type") != "paragraph_title"
- or not isinstance(title_bbox, (list, tuple))
- or not isinstance(title_lines, list)
- or len(title_lines) < 2
- or not isinstance(title_fonts, set)
- or not title_fonts
- ):
- continue
- angle = int(title.get("angle", 0) or 0) % 360
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- line_heights = [
- float(height) for height in title.get("_line_heights", []) if isinstance(height, (int, float)) and height > 0
- ]
- title_height = statistics.median(line_heights) if line_heights else 0.0
- if title_height <= 0 or title_bbox[2] - title_bbox[0] > 0.55 * local_page_width:
- continue
-
- continuations: list[tuple[float, int]] = []
- for text_index, text_block in enumerate(blocks):
- text_bbox = text_block.get("bbox")
- text_fonts = text_block.get("_font_signatures")
- if (
- text_block.get("type") != "text"
- or int(text_block.get("angle", 0) or 0) % 360 != angle
- or not isinstance(text_bbox, (list, tuple))
- or not isinstance(text_fonts, set)
- or not text_fonts
- or not title_fonts.isdisjoint(text_fonts)
- or text_bbox[2] - text_bbox[0] > 0.6 * local_page_width
- ):
- continue
- gap = text_bbox[1] - title_bbox[3]
- if -0.25 * title_height <= gap <= 0.6 * title_height and abs(text_bbox[0] - title_bbox[0]) <= 0.75 * title_height:
- continuations.append((max(0.0, gap), text_index))
- if continuations:
- _gap, text_index = min(continuations)
- candidate_pairs.append((title_index, text_index, title_height))
-
- supported_pairs: list[tuple[int, int]] = []
- for title_index, text_index, title_height in candidate_pairs:
- title_bbox = blocks[title_index]["bbox"]
- support_count = sum(
- abs(blocks[other_title]["bbox"][0] - title_bbox[0]) <= max(title_height, other_height)
- and 0.75 <= other_height / title_height <= 1.25
- for other_title, _other_text, other_height in candidate_pairs
- )
- if support_count >= 2:
- supported_pairs.append((title_index, text_index))
- if not supported_pairs:
- return blocks
-
- replacements: dict[int, dict[str, Any]] = {}
- consumed: set[int] = set()
- for title_index, text_index in supported_pairs:
- if title_index in consumed or text_index in consumed:
- continue
- merged = _merge_internal_text_block_group(
- blocks,
- [title_index, text_index],
- )
- merged["type"] = "text"
- replacements[min(title_index, text_index)] = merged
- consumed.update({title_index, text_index})
- return [
- replacements.get(index, block) for index, block in enumerate(blocks) if index not in consumed or index in replacements
- ]
-
-
-def _merge_internal_text_block_group(
- blocks: list[dict[str, Any]],
- indices: list[int],
- *,
- preserve_visual_spaces: bool = False,
-) -> dict[str, Any]:
- """合并内部文本块及其版面元数据,最终输出阶段仍会统一移除这些字段。"""
-
- ordered_indices = sorted(
- indices,
- key=(
- (lambda index: blocks[index]["bbox"][0])
- if preserve_visual_spaces
- else (lambda index: _text_component_sort_key(blocks[index]))
- ),
- )
- merged = dict(blocks[ordered_indices[0]])
- merged["bbox"] = _bbox_union_many([blocks[index]["bbox"] for index in ordered_indices])
- contents = [str(blocks[index].get("content", "")) for index in ordered_indices]
- merged["content"] = (
- " ".join(content.strip() for content in contents if content.strip())
- if preserve_visual_spaces
- else _merge_text_line_content(contents)
- )
- merged["_visual_row_ids"] = set().union(
- *[row_ids for index in ordered_indices if isinstance((row_ids := blocks[index].get("_visual_row_ids")), set)]
- )
- merged["_single_run_row_id"] = None
- merged["_local_line_bboxes"] = [bbox for index in ordered_indices for bbox in blocks[index].get("_local_line_bboxes", [])]
- merged["_local_output_line_bboxes"] = [
- bbox for index in ordered_indices for bbox in blocks[index].get("_local_output_line_bboxes", [])
- ]
- merged["_output_bbox_repaired"] = any(blocks[index].get("_output_bbox_repaired") is True for index in ordered_indices)
- merged["_line_heights"] = [height for index in ordered_indices for height in blocks[index].get("_line_heights", [])]
- merged["_font_signatures"] = set().union(
- *[
- signatures
- for index in ordered_indices
- if isinstance(
- (signatures := blocks[index].get("_font_signatures")),
- set,
- )
- ]
- )
- merged["_inline_math_regions"] = [
- region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
- ]
- merged[_PARAGRAPH_FORMULA_CONTEXT_MARKER] = any(
- blocks[index].get(_PARAGRAPH_FORMULA_CONTEXT_MARKER) is True for index in ordered_indices
- )
- return merged
-
-
-def _merge_spatial_text_components(
- blocks: list[dict[str, Any]],
- page_size: tuple[float, float],
-) -> list[dict[str, Any]]:
- """按短首行、紧邻续行和双栏递减尾行二次连接被栏带拆开的正文块。"""
-
- parents = list(range(len(blocks)))
-
- def find(index: int) -> int:
- """查找正文组件所属合并组的根节点。"""
-
- while parents[index] != index:
- parents[index] = parents[parents[index]]
- index = parents[index]
- return index
-
- def union(first_index: int, second_index: int) -> None:
- """合并两个已经通过空间连续性校验的正文组件。"""
-
- first_root = find(first_index)
- second_root = find(second_index)
- if first_root != second_root:
- parents[second_root] = first_root
-
- for angle in sorted(
- {
- int(block.get("angle", 0) or 0) % 360
- for block in blocks
- if block.get("type") == "text" and block.get("_local_line_bboxes")
- }
- ):
- candidate_indices = [
- index
- for index, block in enumerate(blocks)
- if block.get("type") == "text"
- and int(block.get("angle", 0) or 0) % 360 == angle
- and isinstance(block.get("_local_line_bboxes"), list)
- and block["_local_line_bboxes"]
- ]
- if len(candidate_indices) < 2:
- continue
- local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
- all_heights = [
- float(height)
- for index in candidate_indices
- for height in blocks[index].get("_line_heights", [])
- if isinstance(height, (int, float)) and height > 0
- ]
- median_height = statistics.median(all_heights) if all_heights else 1.0
- section_starts = {
- index
- for index in candidate_indices
- if _block_starts_with_short_wide_rows(
- blocks[index],
- local_page_width,
- )
- }
-
- opener_pairs = _find_short_opener_pairs(
- blocks,
- candidate_indices,
- local_page_width,
- median_height,
- )
- for opener_index, body_index in opener_pairs:
- section_starts.add(opener_index)
- union(opener_index, body_index)
-
- for current_index in sorted(
- candidate_indices,
- key=lambda index: _text_component_sort_key(blocks[index]),
- ):
- section_roots = {find(index) for index in section_starts}
- if find(current_index) not in section_roots:
- continue
- next_index = _nearest_following_text_component(
- blocks,
- current_index,
- candidate_indices,
- maximum_gap=0.75 * median_height,
- section_starts=section_starts,
- )
- if next_index is not None:
- union(current_index, next_index)
-
- for current_index in candidate_indices:
- if not _has_parallel_text_component(
- blocks,
- current_index,
- candidate_indices,
- ):
- continue
- next_index = _nearest_tapered_tail_component(
- blocks,
- current_index,
- candidate_indices,
- median_height,
- section_starts,
- )
- if next_index is not None:
- union(current_index, next_index)
-
- grouped_indices: dict[int, list[int]] = {}
- for index in range(len(blocks)):
- grouped_indices.setdefault(find(index), []).append(index)
-
- output: list[dict[str, Any]] = []
- for indices in grouped_indices.values():
- if len(indices) == 1:
- output.append(blocks[indices[0]])
- continue
- ordered_indices = sorted(
- indices,
- key=lambda index: _text_component_sort_key(blocks[index]),
- )
- merged = dict(blocks[ordered_indices[0]])
- merged["bbox"] = _bbox_union_many([blocks[index]["bbox"] for index in ordered_indices])
- merged["content"] = _merge_text_line_content([str(blocks[index].get("content", "")) for index in ordered_indices])
- merged["_visual_row_ids"] = set().union(
- *[
- block_ids
- for index in ordered_indices
- if isinstance(
- (block_ids := blocks[index].get("_visual_row_ids")),
- set,
- )
- ]
- )
- merged["_single_run_row_id"] = None
- merged["_local_line_bboxes"] = [
- bbox for index in ordered_indices for bbox in blocks[index].get("_local_line_bboxes", [])
- ]
- merged["_local_output_line_bboxes"] = [
- bbox for index in ordered_indices for bbox in blocks[index].get("_local_output_line_bboxes", [])
- ]
- merged["_output_bbox_repaired"] = any(blocks[index].get("_output_bbox_repaired") is True for index in ordered_indices)
- merged["_line_heights"] = [height for index in ordered_indices for height in blocks[index].get("_line_heights", [])]
- merged["_font_signatures"] = set().union(
- *[
- signatures
- for index in ordered_indices
- if isinstance(
- (signatures := blocks[index].get("_font_signatures")),
- set,
- )
- ]
- )
- merged["_inline_math_regions"] = [
- region for index in ordered_indices for region in blocks[index].get("_inline_math_regions", [])
- ]
- output.append(merged)
- 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]]:
- """合并普通栏未终止正文,以及满足严格结构约束的满宽 span 正文。"""
-
- 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_declared_interval = _component_declared_lane_interval(
- first,
- )
- second_declared_interval = _component_declared_lane_interval(
- second,
- )
- row_pair_height = statistics.median(
- [
- max(
- 0.1,
- first_rows[-1][3] - first_rows[-1][1],
- ),
- max(
- 0.1,
- second_rows[0][3] - second_rows[0][1],
- ),
- ],
- )
- span_connection_height = max(
- pair_height,
- row_pair_height,
- )
- span_tolerance = 0.75 * span_connection_height
- span_pair = (
- first.get("_lane_is_span") is True
- and second.get("_lane_is_span") is True
- and int(first.get("angle", 0) or 0) % 360 == int(second.get("angle", 0) or 0) % 360
- and first_declared_interval is not None
- and second_declared_interval is not None
- and abs(
- first_declared_interval[0] - second_declared_interval[0],
- )
- <= span_tolerance
- and abs(
- first_declared_interval[1] - second_declared_interval[1],
- )
- <= span_tolerance
- )
- 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 (reference_interval := (second_declared_interval if span_pair else second_interval)) is not None
- and second_rows[0][2] - second_rows[0][0] >= 0.5 * (reference_interval[1] - reference_interval[0])
- )
- if (
- second.get("_protected_hard_break_before") is True
- or (second.get("_hard_break_before") is True and (span_pair or not narrow_continuation))
- or second.get("_leading_emphasis_start") is True
- or (starts_wide_label and (span_pair or 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 span_pair
- and 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 span_pair:
- interval = first_declared_interval
- elif interval is None or not _components_share_lane_role(
- first,
- second,
- pair_height,
- ):
- continue
- if interval is None:
- continue
- lane_width = interval[1] - interval[0]
- vertical_gap = second_rows[0][1] - first_rows[-1][3]
- minimum_first_fill = 0.8 if span_pair else 0.5 if single_numbered_tail else 0.65
- minimum_second_fill = 0.8 if span_pair else 0.65
- connection_height = span_connection_height if span_pair else pair_height
- 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 (
- (span_pair or not narrow_continuation)
- and second_rows[0][2] - second_rows[0][0] < minimum_second_fill * lane_width
- )
- or not -connection_height <= vertical_gap <= 1.5 * connection_height
- or fonts_conflict
- or _component_connection_skips_block(
- output,
- first_index,
- second_index,
- connection_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_declared_lane_interval(
- block: dict[str, Any],
-) -> tuple[float, float] | None:
- """读取组件声明的有效栏带区间,不区分普通栏或跨栏。"""
-
- interval = block.get("_lane_interval")
- if (
- not isinstance(interval, (list, tuple))
- or len(interval) != 2
- or not all(isinstance(value, (int, float)) for value in interval)
- ):
- return None
- left, right = float(interval[0]), float(interval[1])
- return (left, right) if right > left else None
-
-
-def _component_lane_interval(
- block: dict[str, Any],
-) -> tuple[float, float] | None:
- """读取普通文本组件所属的有效非跨栏栏带区间。"""
-
- if block.get("_lane_is_span") is not False:
- return None
- return _component_declared_lane_interval(block)
-
-
-def _component_reference_width(
- block: dict[str, Any],
- local_page_width: float,
-) -> float:
- """优先返回组件的局部栏宽,缺少可靠栏带时回退页面宽度。"""
-
- interval = _component_lane_interval(block)
- return interval[1] - interval[0] if interval is not None else local_page_width
-
-
-def _compatible_component_lane_width(
- first_block: dict[str, Any],
- second_block: dict[str, Any],
- local_page_width: float,
- median_height: float,
-) -> float:
- """同一局部栏带的两个组件使用栏宽,否则继续使用页面宽度。"""
-
- first_interval = _component_lane_interval(first_block)
- second_interval = _component_lane_interval(second_block)
- if first_interval is None or second_interval is None:
- return local_page_width
- tolerance = 0.75 * median_height
- if abs(first_interval[0] - second_interval[0]) > tolerance or abs(first_interval[1] - second_interval[1]) > tolerance:
- return local_page_width
- return min(
- first_interval[1] - first_interval[0],
- second_interval[1] - second_interval[0],
- )
-
-
-def _components_share_lane_role(
- first_block: dict[str, Any],
- second_block: dict[str, Any],
- median_height: float,
-) -> bool:
- """要求二次合并组件同为跨栏或属于同一普通栏带。"""
-
- first_role = first_block.get("_lane_is_span")
- second_role = second_block.get("_lane_is_span")
- if isinstance(first_role, bool) and isinstance(second_role, bool):
- if first_role != second_role:
- return False
- if first_role:
- return True
- first_interval = _component_lane_interval(first_block)
- second_interval = _component_lane_interval(second_block)
- if first_interval is None or second_interval is None:
- return False
- tolerance = 0.75 * median_height
- return (
- abs(first_interval[0] - second_interval[0]) <= tolerance
- and abs(first_interval[1] - second_interval[1]) <= tolerance
- )
- # 兼容缺少内部栏元数据的旧调用;生产路径始终会携带该字段。
- return not isinstance(first_role, bool) and not isinstance(second_role, bool)
-
-
-def _block_starts_with_short_wide_rows(
- block: dict[str, Any],
- local_page_width: float,
-) -> bool:
- """判断组件内部是否以短首行和紧邻宽正文形成明确分组起点。"""
-
- line_bboxes = block.get("_local_line_bboxes")
- if not isinstance(line_bboxes, list) or len(line_bboxes) < 2:
- return False
- first_bbox, second_bbox = line_bboxes[:2]
- first_width = first_bbox[2] - first_bbox[0]
- second_width = second_bbox[2] - second_bbox[0]
- reference_width = _component_reference_width(block, local_page_width)
- return first_width <= 0.35 * reference_width and second_width >= max(0.25 * reference_width, 1.8 * first_width)
-
-
-def _find_short_opener_pairs(
- blocks: list[dict[str, Any]],
- candidate_indices: list[int],
- local_page_width: float,
- median_height: float,
-) -> list[tuple[int, int]]:
- """查找跨栏拆开的短首行与紧邻满宽正文组件。"""
-
- output: list[tuple[int, int]] = []
- for opener_index in candidate_indices:
- opener_bboxes = blocks[opener_index]["_local_line_bboxes"]
- if len(opener_bboxes) != 1:
- continue
- opener_bbox = opener_bboxes[0]
- opener_width = opener_bbox[2] - opener_bbox[0]
- matches: list[tuple[float, int]] = []
- for body_index in candidate_indices:
- if body_index == opener_index:
- continue
- if blocks[body_index].get("_hard_break_before") is True:
- continue
- if not _components_share_lane_role(
- blocks[opener_index],
- blocks[body_index],
- median_height,
- ):
- continue
- body_bbox = blocks[body_index]["_local_line_bboxes"][0]
- gap = body_bbox[1] - opener_bbox[3]
- body_width = body_bbox[2] - body_bbox[0]
- reference_width = _compatible_component_lane_width(
- blocks[opener_index],
- blocks[body_index],
- local_page_width,
- median_height,
- )
- if (
- not 0.0 <= gap <= 0.75 * median_height
- or abs(body_bbox[0] - opener_bbox[0]) > 0.75 * median_height
- or opener_width > 0.35 * reference_width
- or body_width < 0.6 * reference_width
- or _component_connection_skips_block(
- blocks,
- opener_index,
- body_index,
- median_height,
- )
- ):
- continue
- matches.append((gap, body_index))
- if matches:
- output.append((opener_index, min(matches)[1]))
- return output
-
-
-def _nearest_following_text_component(
- blocks: list[dict[str, Any]],
- current_index: int,
- candidate_indices: list[int],
- *,
- maximum_gap: float,
- section_starts: set[int],
-) -> int | None:
- """返回同一水平流中紧邻且不是新分组起点的下一正文组件。"""
-
- current_bbox = blocks[current_index]["_local_line_bboxes"][-1]
- matches: list[tuple[float, float, int]] = []
- for candidate_index in candidate_indices:
- if candidate_index == current_index or candidate_index in section_starts:
- continue
- if blocks[candidate_index].get("_hard_break_before") is True:
- continue
- if not _components_share_lane_role(
- blocks[current_index],
- blocks[candidate_index],
- maximum_gap / 0.75,
- ):
- continue
- candidate_bbox = blocks[candidate_index]["_local_line_bboxes"][0]
- gap = candidate_bbox[1] - current_bbox[3]
- if not -0.25 * maximum_gap <= gap <= maximum_gap:
- continue
- overlap = _bbox_axis_overlap_ratio(current_bbox, candidate_bbox, axis="x")
- left_gap = abs(candidate_bbox[0] - current_bbox[0])
- if overlap < 0.5 and left_gap > 3.0 * maximum_gap:
- continue
- if _component_connection_skips_block(
- blocks,
- current_index,
- candidate_index,
- maximum_gap / 0.75,
- ):
- continue
- matches.append((max(0.0, gap), left_gap, candidate_index))
- return min(matches)[2] if matches else None
-
-
-def _has_parallel_text_component(
- blocks: list[dict[str, Any]],
- current_index: int,
- candidate_indices: list[int],
-) -> bool:
- """检查当前组件同一纵向带内是否存在水平分离的并栏组件。"""
-
- current_bbox = blocks[current_index]["bbox"]
- for candidate_index in candidate_indices:
- if candidate_index == current_index:
- continue
- candidate_bbox = blocks[candidate_index]["bbox"]
- vertical_overlap = max(
- 0.0,
- min(current_bbox[3], candidate_bbox[3]) - max(current_bbox[1], candidate_bbox[1]),
- )
- horizontally_separate = candidate_bbox[0] >= current_bbox[2] or current_bbox[0] >= candidate_bbox[2]
- if vertical_overlap > 0 and horizontally_separate:
- return True
- return False
-
-
-def _nearest_tapered_tail_component(
- blocks: list[dict[str, Any]],
- current_index: int,
- candidate_indices: list[int],
- median_height: float,
- section_starts: set[int],
-) -> int | None:
- """查找左对齐、行宽递减且行距略大的信息组尾行组件。"""
-
- previous_bbox = blocks[current_index]["_local_line_bboxes"][-1]
- previous_width = previous_bbox[2] - previous_bbox[0]
- matches: list[tuple[float, int]] = []
- for candidate_index in candidate_indices:
- if candidate_index == current_index or candidate_index in section_starts:
- continue
- if blocks[candidate_index].get("_hard_break_before") is True:
- continue
- if not _components_share_lane_role(
- blocks[current_index],
- blocks[candidate_index],
- median_height,
- ):
- continue
- candidate_bboxes = blocks[candidate_index]["_local_line_bboxes"]
- first_bbox = candidate_bboxes[0]
- last_bbox = candidate_bboxes[-1]
- gap = first_bbox[1] - previous_bbox[3]
- first_width = first_bbox[2] - first_bbox[0]
- last_width = last_bbox[2] - last_bbox[0]
- if (
- not 0.75 * median_height < gap <= 1.5 * median_height
- or len(candidate_bboxes) > 2
- or abs(first_bbox[0] - previous_bbox[0]) > 0.75 * median_height
- or first_width > 0.85 * previous_width
- or last_width > first_width + 0.5 * median_height
- or _component_connection_skips_block(
- blocks,
- current_index,
- candidate_index,
- median_height,
- )
- ):
- continue
- matches.append((gap, candidate_index))
- return min(matches)[1] if matches else None
-
-
-def _component_connection_skips_block(
- blocks: list[dict[str, Any]],
- first_index: int,
- second_index: int,
- median_height: float,
-) -> bool:
- """检查两个正文组件之间是否已有同水平流的中间块,禁止二次合并跨越它。"""
-
- first_bbox = blocks[first_index]["_local_line_bboxes"][-1]
- second_bbox = blocks[second_index]["_local_line_bboxes"][0]
- first_center = _bbox_center_y(first_bbox)
- second_center = _bbox_center_y(second_bbox)
- corridor_top, corridor_bottom = sorted((first_center, second_center))
- corridor_bbox = (
- min(first_bbox[0], second_bbox[0]),
- corridor_top,
- max(first_bbox[2], second_bbox[2]),
- corridor_bottom,
- )
- for index, block in enumerate(blocks):
- if index in {first_index, second_index}:
- continue
- local_bboxes = block.get("_local_line_bboxes")
- if not isinstance(local_bboxes, list) or not local_bboxes:
- continue
- other_bbox = local_bboxes[0]
- other_center = _bbox_center_y(other_bbox)
- if not (corridor_top + 0.1 * median_height < other_center < corridor_bottom - 0.1 * median_height):
- continue
- if _bbox_axis_overlap_ratio(corridor_bbox, other_bbox, axis="x") >= 0.2:
- return True
- return False
-
-
-def _text_component_sort_key(block: dict[str, Any]) -> tuple[float, float]:
- """返回正文组件按局部首行位置排序的稳定键。"""
-
- first_bbox = block["_local_line_bboxes"][0]
- return first_bbox[1], first_bbox[0]
-
-
-def _merge_text_line_content(line_texts: Sequence[str]) -> str:
- """按 Hybrid 语言与行末连字规则折叠普通文本行。"""
- normalized_lines = [_normalize_native_run_text(str(text or "")) for text in line_texts]
- normalized_lines = [text for text in normalized_lines if text]
- if not normalized_lines:
- return ""
- try:
- block_language = detect_lang("".join(normalized_lines))
- except Exception:
- block_language = ""
- return merge_text_line_contents(
- normalized_lines,
- block_language=block_language,
- )
+__all__ = []
diff --git a/mineru/model/flash/pdf/title_analysis/__init__.py b/mineru/model/flash/pdf/title_analysis/__init__.py
new file mode 100644
index 00000000..b2b2d2a5
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""按职责拆分的 Flash PDF 内部实现。"""
+
+__all__: list[str] = []
diff --git a/mineru/model/flash/pdf/title_analysis/body_profile.py b/mineru/model/flash/pdf/title_analysis/body_profile.py
new file mode 100644
index 00000000..80bdbd38
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/body_profile.py
@@ -0,0 +1,227 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""统计全文和栏内正文排版基线。"""
+
+from __future__ import annotations
+
+import statistics
+
+from ..geometry import _rotate_bbox_to_upright
+from ..inline.types import PDF_FONT_FORCE_BOLD_FLAG, PDF_FONT_ITALIC_FLAG
+from ..line_layout import (
+ _estimate_lane_gap,
+ _font_signatures_share_family,
+ _line_canonical_style_scale,
+ _line_effective_height,
+)
+from ..models import (
+ _DocumentBodyProfile,
+ _LaneBodyProfile,
+ _LineItem,
+ _PreparedPage,
+ _TextLane,
+)
+
+
+def _infer_document_body_profile(
+ prepared_pages: list[_PreparedPage],
+ *,
+ use_canonical_scale: bool = False,
+) -> _DocumentBodyProfile | None:
+ """按跨页覆盖和累计行宽推断全文正文行高及常规字体集合。"""
+
+ samples: list[
+ tuple[
+ float,
+ int,
+ float,
+ tuple[str, int] | None,
+ float | None,
+ ]
+ ] = []
+ for page_index, prepared in enumerate(prepared_pages):
+ for line in prepared.remaining_lines:
+ if line.semantic_type is not None:
+ continue
+ local_bbox = _rotate_bbox_to_upright(
+ line.bbox,
+ prepared.page_size,
+ line.angle,
+ )
+ local_page_width = prepared.page_size[1] if line.angle in {90, 270} else prepared.page_size[0]
+ height = (
+ _line_canonical_style_scale(line, local_bbox)
+ if use_canonical_scale
+ else _line_effective_height(line, local_bbox)
+ )
+ normalized_width = max(0.0, local_bbox[2] - local_bbox[0]) / max(
+ 0.1,
+ local_page_width,
+ )
+ if height <= 0 or normalized_width <= 0:
+ continue
+ samples.append(
+ (
+ height,
+ page_index,
+ normalized_width,
+ line.font_signature if line.font_coverage >= 0.75 else None,
+ line.dominant_font_weight,
+ )
+ )
+ if not samples:
+ return None
+
+ height_clusters: list[list[tuple[float, int, float]]] = []
+ for height, page_index, normalized_width, _font, _weight in sorted(
+ samples,
+ key=lambda item: item[0],
+ ):
+ target = next(
+ (
+ cluster
+ for cluster in height_clusters
+ if abs(height - statistics.median(item[0] for item in cluster))
+ <= 0.1 * statistics.median(item[0] for item in cluster)
+ ),
+ None,
+ )
+ if target is None:
+ height_clusters.append([(height, page_index, normalized_width)])
+ else:
+ target.append((height, page_index, normalized_width))
+ cross_page_clusters = [cluster for cluster in height_clusters if len({item[1] for item in cluster}) >= 2]
+ eligible_clusters = cross_page_clusters or height_clusters
+ body_cluster = max(
+ eligible_clusters,
+ key=lambda cluster: (
+ sum(item[2] for item in cluster),
+ len({item[1] for item in cluster}),
+ len(cluster),
+ ),
+ )
+ body_height = statistics.median(item[0] for item in body_cluster)
+
+ body_weights = [
+ weight
+ for height, _page_index, _width, _font, weight in samples
+ if weight is not None and 0.9 <= height / body_height <= 1.1
+ ]
+ body_weight = statistics.median(body_weights) if body_weights else None
+
+ font_pages: dict[tuple[str, int], set[int]] = {}
+ font_widths: dict[tuple[str, int], float] = {}
+ font_weights: dict[tuple[str, int], list[float]] = {}
+ for height, page_index, width, font, weight in samples:
+ if font is None or not 0.9 <= height / body_height <= 1.1:
+ continue
+ # 常规字体支持必须来自正文高度带;跨页重复的大标题不能反向污染正文画像。
+ font_pages.setdefault(font, set()).add(page_index)
+ font_widths[font] = font_widths.get(font, 0.0) + width
+ if weight is not None:
+ font_weights.setdefault(font, []).append(weight)
+
+ regular_fonts = frozenset(
+ font
+ for font, pages in font_pages.items()
+ if len(pages) >= 3
+ and font_widths.get(font, 0.0) >= 2.0
+ and font_widths.get(font, 0.0) >= 0.75 * len(pages)
+ and _document_font_is_regular(
+ font,
+ font_weights.get(font, []),
+ body_weight,
+ )
+ )
+ return _DocumentBodyProfile(
+ body_height=max(0.1, body_height),
+ body_weight=body_weight,
+ regular_fonts=regular_fonts,
+ has_style_scale_repairs=any(
+ line.style_scale_repaired for prepared in prepared_pages for line in prepared.remaining_lines
+ ),
+ )
+
+
+def _document_font_is_regular(
+ font: tuple[str, int],
+ weights: list[float],
+ body_weight: float | None,
+) -> bool:
+ """用字体样式位和全文正文基准过滤斜体、粗体等强调字体。"""
+
+ if font[1] & (PDF_FONT_ITALIC_FLAG | PDF_FONT_FORCE_BOLD_FLAG):
+ return False
+ if not weights or body_weight is None:
+ return True
+ median_weight = statistics.median(weights)
+ return median_weight < max(body_weight + 100.0, 1.15 * body_weight)
+
+
+def _infer_lane_body_profile(lane: _TextLane) -> _LaneBodyProfile:
+ """从栏带的长行主体估计正文行高、主字体、字重、常规行距和样式占比。"""
+
+ available = [item for item in lane.lines if item[0].semantic_type is None]
+ if not available:
+ return _LaneBodyProfile(1.0, None, None, 0.35, {})
+ lane_width = max(0.1, lane.right - lane.left)
+ long_lines = [item for item in available if item[1][2] - item[1][0] >= 0.45 * lane_width]
+ body_rows = long_lines or available
+ body_line_ids = {id(line) for line, _bbox in body_rows}
+ body_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in body_rows)
+
+ font_support: dict[tuple[str, int], float] = {}
+ style_support: dict[tuple[str, int], float] = {}
+ total_style_width = 0.0
+ for line, bbox in available:
+ if line.font_signature is None or line.font_coverage < 0.75:
+ continue
+ line_width = max(0.1, bbox[2] - bbox[0])
+ style_support[line.font_signature] = style_support.get(line.font_signature, 0.0) + line_width
+ total_style_width += line_width
+ if id(line) in body_line_ids and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35:
+ font_support[line.font_signature] = font_support.get(line.font_signature, 0.0) + line_width
+ body_font = max(font_support, key=font_support.get) if font_support else None
+ if total_style_width > 0:
+ style_support = {signature: width / total_style_width for signature, width in style_support.items()}
+
+ body_weights = [
+ line.dominant_font_weight
+ for line, bbox in body_rows
+ if line.dominant_font_weight is not None
+ and (body_font is None or line.font_signature == body_font)
+ and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35
+ ]
+ regular_gap, _gap_mad = _estimate_lane_gap(lane)
+ return _LaneBodyProfile(
+ body_height=max(0.1, body_height),
+ body_font=body_font,
+ body_weight=statistics.median(body_weights) if body_weights else None,
+ regular_gap=regular_gap,
+ style_support=style_support,
+ body_row_count=len(body_rows),
+ )
+
+
+def _line_uses_document_regular_font(
+ line: _LineItem,
+ document_body_profile: _DocumentBodyProfile | None,
+) -> bool:
+ """判断当前行是否使用跨页反复出现且未加粗的常规字体。"""
+
+ return (
+ document_body_profile is not None
+ and line.font_signature is not None
+ and line.font_coverage >= 0.5
+ and any(
+ _font_signatures_share_family(line.font_signature, regular_font)
+ for regular_font in document_body_profile.regular_fonts
+ )
+ )
+
+
+__all__ = [
+ "_infer_document_body_profile",
+ "_document_font_is_regular",
+ "_infer_lane_body_profile",
+ "_line_uses_document_regular_font",
+]
diff --git a/mineru/model/flash/pdf/title_analysis/common.py b/mineru/model/flash/pdf/title_analysis/common.py
new file mode 100644
index 00000000..aa8cfc95
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/common.py
@@ -0,0 +1,122 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""提供标题分类共享的几何与文本规则。"""
+
+from __future__ import annotations
+
+import re
+
+from .....types import BBox
+from ..geometry import _bbox_axis_overlap_ratio, _bbox_center_x, _bbox_center_y
+from ..line_layout import (
+ _effective_text_row_gap,
+)
+from ..models import (
+ _LineItem,
+)
+
+_NUMBERED_SECTION_TITLE_RE = re.compile(
+ r"^(?P<number>\d+(?:\s*\.\s*\d+)*)\s+(?P<label>\S.*)$",
+)
+
+
+_SECTION_NUMBER_ONLY_RE = re.compile(
+ r"^\d+(?:\s*\.\s*\d+)*\.?$",
+)
+
+
+_SECTION_TITLE_TERMINAL_RE = re.compile(
+ r"[.!?。!?::;;,,]$",
+)
+
+
+_UNNUMBERED_SECTION_HEADING_RE = re.compile(
+ r"^(?:introduction|references?|bibliography|acknowledg(?:e)?ments?|引言|绪论|参考文献|参考资料)$",
+ re.IGNORECASE,
+)
+
+
+def _build_physical_title_gap_map(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> dict[int, tuple[float | None, float | None]]:
+ """为每行记录同方向且水平投影相交的最近上、下物理行净空。"""
+
+ output: dict[int, tuple[float | None, float | None]] = {}
+ for line, bbox in line_geometry:
+ line_center = _bbox_center_y(bbox)
+ above_gaps: list[float] = []
+ below_gaps: list[float] = []
+ for other_line, other_bbox in line_geometry:
+ if other_line is line:
+ continue
+ if _bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") < 0.1:
+ # 双栏同高度正文并非当前行的物理上下文,不能抹掉真实标题留白。
+ continue
+ if line.visual_row_id is not None and other_line.visual_row_id == line.visual_row_id:
+ continue
+ other_center = _bbox_center_y(other_bbox)
+ if other_center < line_center:
+ above_gaps.append(
+ max(
+ 0.0,
+ _effective_text_row_gap(
+ (other_line, other_bbox),
+ (line, bbox),
+ ),
+ )
+ )
+ elif other_center > line_center:
+ below_gaps.append(
+ max(
+ 0.0,
+ _effective_text_row_gap(
+ (line, bbox),
+ (other_line, other_bbox),
+ ),
+ )
+ )
+ output[line.source_index] = (
+ min(above_gaps) if above_gaps else None,
+ min(below_gaps) if below_gaps else None,
+ )
+ return output
+
+
+def _line_inside_visual_container(
+ line_bbox: BBox,
+ container_bboxes: list[BBox],
+) -> bool:
+ """检查文本行中心是否落入视觉容器,容器内标签不得借标题原型晋升。"""
+
+ center_x = _bbox_center_x(line_bbox)
+ center_y = _bbox_center_y(line_bbox)
+ return any(bbox[0] <= center_x <= bbox[2] and bbox[1] <= center_y <= bbox[3] for bbox in container_bboxes)
+
+
+def _line_near_visual_container(
+ line_bbox: BBox,
+ container_bboxes: list[BBox],
+ body_height: float,
+) -> bool:
+ """检查短行是否紧邻图、表等容器,以纯几何方式抑制 caption 误判。"""
+
+ for container_bbox in container_bboxes:
+ if _bbox_axis_overlap_ratio(line_bbox, container_bbox, axis="x") < 0.35:
+ continue
+ container_width = max(0.1, container_bbox[2] - container_bbox[0])
+ if line_bbox[2] - line_bbox[0] > 0.8 * container_width:
+ continue
+ vertical_gap = max(line_bbox[1] - container_bbox[3], container_bbox[1] - line_bbox[3], 0.0)
+ if vertical_gap <= 2.0 * body_height:
+ return True
+ return False
+
+
+__all__ = [
+ "_NUMBERED_SECTION_TITLE_RE",
+ "_SECTION_NUMBER_ONLY_RE",
+ "_SECTION_TITLE_TERMINAL_RE",
+ "_UNNUMBERED_SECTION_HEADING_RE",
+ "_build_physical_title_gap_map",
+ "_line_inside_visual_container",
+ "_line_near_visual_container",
+]
diff --git a/mineru/model/flash/pdf/title_analysis/document_profile.py b/mineru/model/flash/pdf/title_analysis/document_profile.py
new file mode 100644
index 00000000..f11262e1
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/document_profile.py
@@ -0,0 +1,174 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""使用既有页面分类探测构建全文标题原型。"""
+
+from __future__ import annotations
+
+import statistics
+from dataclasses import replace
+from typing import Literal
+
+from ..geometry import _rotate_bbox_to_upright
+from ..line_layout import (
+ _infer_text_lanes,
+ _line_effective_height,
+ _normalized_font_family,
+)
+from ..models import (
+ _DocumentBodyProfile,
+ _DocumentTitleProfile,
+ _PreparedPage,
+ _TitleStylePrototype,
+)
+from .common import _line_inside_visual_container
+from .page_titles import _classify_page_titles
+from .prototype import _title_profile_alignment, _title_profile_seed_matches_cluster
+
+
+def _infer_document_title_profile(
+ prepared_pages: list[_PreparedPage],
+ document_body_profile: _DocumentBodyProfile | None,
+) -> _DocumentTitleProfile | None:
+ """在副本上复用现有标题判定,并把跨页稳定样式聚成标题原型。"""
+
+ if document_body_profile is None:
+ return None
+ seeds: list[
+ tuple[
+ str,
+ int,
+ float,
+ float | None,
+ Literal["left", "center"],
+ float,
+ int,
+ ]
+ ] = []
+ for page_index, prepared in enumerate(prepared_pages):
+ probe_lines = [replace(line) for line in prepared.remaining_lines]
+ container_bboxes = [
+ block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
+ ]
+ _classify_page_titles(
+ probe_lines,
+ prepared.page_size,
+ page_index=page_index,
+ container_bboxes=container_bboxes,
+ document_body_profile=document_body_profile,
+ )
+ seen_rows: set[tuple[int, int]] = set()
+ for angle in sorted({line.angle for line in probe_lines}):
+ geometry = [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ prepared.page_size,
+ angle,
+ ),
+ )
+ for line in probe_lines
+ if line.angle == angle
+ ]
+ if not geometry:
+ continue
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in geometry)
+ local_page_width = prepared.page_size[1] if angle in {90, 270} else prepared.page_size[0]
+ lanes = _infer_text_lanes(
+ geometry,
+ local_page_width,
+ median_height,
+ )
+ local_container_bboxes = [
+ _rotate_bbox_to_upright(
+ bbox,
+ prepared.page_size,
+ angle,
+ )
+ for bbox in container_bboxes
+ ]
+ for lane in lanes:
+ for line, bbox in lane.lines:
+ line_height_ratio = _line_effective_height(line, bbox) / document_body_profile.body_height
+ large_unresolved_seed = (
+ page_index > 0
+ and line.semantic_type is None
+ and line_height_ratio >= 1.3
+ and bbox[2] - bbox[0] <= 0.8 * local_page_width
+ and not _line_inside_visual_container(
+ bbox,
+ local_container_bboxes,
+ )
+ )
+ if (
+ (line.semantic_type != "paragraph_title" and not large_unresolved_seed)
+ or line.font_signature is None
+ or line.font_coverage < 0.75
+ ):
+ continue
+ row_identity = line.visual_row_id if line.visual_row_id is not None else line.source_index
+ row_key = (angle, row_identity)
+ if row_key in seen_rows:
+ continue
+ alignment = _title_profile_alignment(
+ bbox,
+ lane,
+ document_body_profile.body_height,
+ )
+ if alignment is None:
+ continue
+ font_family = _normalized_font_family(line.font_signature)
+ if font_family is None:
+ continue
+ mode, anchor_offset = alignment
+ seeds.append(
+ (
+ font_family,
+ line.font_signature[1],
+ line_height_ratio,
+ line.dominant_font_weight,
+ mode,
+ anchor_offset,
+ page_index,
+ )
+ )
+ seen_rows.add(row_key)
+
+ clusters: list[list[tuple[str, int, float, float | None, Literal["left", "center"], float, int]]] = []
+ for seed in sorted(seeds, key=lambda item: (item[0], item[1], item[4], item[2])):
+ target = next(
+ (cluster for cluster in clusters if _title_profile_seed_matches_cluster(seed, cluster)),
+ None,
+ )
+ if target is None:
+ clusters.append([seed])
+ else:
+ target.append(seed)
+
+ prototypes: list[_TitleStylePrototype] = []
+ for cluster in clusters:
+ support_pages = len({seed[6] for seed in cluster})
+ if len(cluster) < 3 and support_pages < 2:
+ continue
+ weights = [seed[3] for seed in cluster if seed[3] is not None]
+ prototypes.append(
+ _TitleStylePrototype(
+ font_family=cluster[0][0],
+ font_flags=cluster[0][1],
+ height_ratio=statistics.median(seed[2] for seed in cluster),
+ weight=statistics.median(weights) if weights else None,
+ alignment=cluster[0][4],
+ anchor_offset=statistics.median(seed[5] for seed in cluster),
+ support_count=len(cluster),
+ support_pages=support_pages,
+ )
+ )
+ if not prototypes:
+ return None
+ prototypes.sort(
+ key=lambda item: (item.support_pages, item.support_count),
+ reverse=True,
+ )
+ return _DocumentTitleProfile(tuple(prototypes))
+
+
+__all__ = ["_infer_document_title_profile"]
diff --git a/mineru/model/flash/pdf/title_analysis/lane_titles.py b/mineru/model/flash/pdf/title_analysis/lane_titles.py
new file mode 100644
index 00000000..57bcfbe7
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/lane_titles.py
@@ -0,0 +1,765 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""在既有正文统计和结构证据下分类栏内标题。"""
+
+from __future__ import annotations
+
+import statistics
+from typing import Literal
+
+from .....types import BBox
+from ..geometry import _bbox_axis_overlap_ratio, _bbox_center_x, _bbox_center_y, _bbox_union_many
+from ..line_layout import (
+ _effective_text_row_gap,
+ _font_signatures_share_family,
+ _font_weights_conflict,
+ _line_effective_height,
+ _should_connect_semantic_rows,
+ _title_fonts_compatible,
+)
+from ..models import (
+ _DocumentBodyProfile,
+ _DocumentTitleProfile,
+ _LaneBodyProfile,
+ _LineItem,
+ _TextLane,
+)
+from .body_profile import _line_uses_document_regular_font
+from .common import _line_inside_visual_container, _line_near_visual_container
+from .prototype import _line_conflicts_document_title_profile, _matching_document_title_prototype
+
+
+def _classify_paragraph_titles_in_lane(
+ lane: _TextLane,
+ profile: _LaneBodyProfile,
+ local_page_width: float,
+ local_page_height: float,
+ container_bboxes: list[BBox],
+ *,
+ document_title_bottom: float | None,
+ preserve_front_matter_boundaries: bool,
+ physical_gaps: dict[int, tuple[float | None, float | None]],
+ grid_title_suppressions: set[int],
+ document_body_profile: _DocumentBodyProfile | None,
+ document_title_profile: _DocumentTitleProfile | None,
+ page_index: int,
+) -> None:
+ """以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""
+
+ lane_width = max(0.1, lane.right - lane.left)
+ rows = lane.lines
+ selected_indices: set[int] = set()
+ front_matter_boundary = _infer_front_matter_boundary(
+ lane,
+ profile,
+ local_page_height,
+ document_title_bottom=document_title_bottom,
+ )
+ for index, (line, bbox) in enumerate(rows):
+ if line.semantic_type is not None:
+ continue
+ if line.source_index in grid_title_suppressions:
+ continue
+ if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
+ continue
+ inside_front_matter = front_matter_boundary is not None and _bbox_center_y(bbox) <= front_matter_boundary
+ if inside_front_matter and not preserve_front_matter_boundaries:
+ continue
+ if (
+ document_title_bottom is not None
+ and document_title_bottom <= 0.6 * local_page_height
+ and _bbox_center_y(bbox) >= 0.84 * local_page_height
+ ):
+ # 首页底部短行通常是版本、日期等封面元数据,不属于正文标题层级。
+ continue
+ line_height = _line_effective_height(line, bbox)
+ title_prototype = _matching_document_title_prototype(
+ line,
+ bbox,
+ lane,
+ document_body_profile,
+ document_title_profile,
+ )
+ title_profile_size_conflict = title_prototype is None and _line_conflicts_document_title_profile(
+ line,
+ bbox,
+ lane,
+ document_body_profile,
+ document_title_profile,
+ )
+ inside_visual_container = _line_inside_visual_container(
+ bbox,
+ container_bboxes,
+ )
+ near_visual_container = _line_near_visual_container(
+ bbox,
+ container_bboxes,
+ profile.body_height,
+ )
+ if inside_visual_container or (near_visual_container and title_prototype is None):
+ continue
+
+ recurrent_regular_font = _line_uses_document_regular_font(
+ line,
+ document_body_profile,
+ )
+ document_regular_body_candidate = (
+ recurrent_regular_font
+ and document_body_profile is not None
+ and line_height >= 0.9 * document_body_profile.body_height
+ )
+ reference_body_height = profile.body_height
+ if profile.body_row_count < 3 and document_body_profile is not None:
+ reference_body_height = document_body_profile.body_height
+ if document_regular_body_candidate and document_body_profile is not None:
+ reference_body_height = max(
+ reference_body_height,
+ document_body_profile.body_height,
+ )
+ height_ratio = line_height / reference_body_height
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_width
+ left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height
+ if line.median_glyph_width is not None and bbox[2] - bbox[0] <= 1.25 * line.median_glyph_width and height_ratio < 1.18:
+ continue
+ style_differs = (
+ not recurrent_regular_font
+ and profile.body_font is not None
+ and line.font_signature is not None
+ and line.font_coverage >= 0.75
+ 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 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 = (
+ profile.body_weight is not None
+ and line.dominant_font_weight is not None
+ and line.dominant_font_weight >= max(profile.body_weight + 100.0, 1.15 * profile.body_weight)
+ )
+ gap_above = _normalized_title_gap(
+ rows,
+ index,
+ direction=-1,
+ body_height=profile.body_height,
+ physical_gaps=physical_gaps,
+ )
+ gap_below = _normalized_title_gap(
+ rows,
+ index,
+ direction=1,
+ body_height=profile.body_height,
+ physical_gaps=physical_gaps,
+ )
+ regular_gap_ratio = profile.regular_gap / max(0.1, profile.body_height)
+ gap_above_excess = max(0.0, gap_above - regular_gap_ratio)
+ gap_below_excess = max(0.0, gap_below - regular_gap_ratio)
+ has_spacing_signal = gap_above >= 0.35
+
+ if _visual_row_has_body_style_sibling(rows, index):
+ continue
+ if _is_near_full_mixed_inline_row(
+ rows,
+ index,
+ lane_width,
+ profile,
+ ):
+ continue
+ if (
+ index > 0
+ and rows[index - 1][0].semantic_type == "paragraph_title"
+ and width_ratio >= 0.85
+ and gap_above < 1.0
+ and not _title_fonts_compatible(rows[index - 1][0], line)
+ ):
+ continue
+ if _continues_local_body_row(
+ rows,
+ index,
+ lane_width,
+ 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
+ )
+ compact_text_section = (
+ height_ratio < 0.9
+ and centered
+ and width_ratio <= 0.7
+ and gap_above >= 0.35
+ and gap_below >= 0.2
+ and (page_index != 0 or style_differs or weight_emphasized or title_prototype is not None)
+ and _has_following_compact_text_section(
+ rows,
+ index,
+ lane_width,
+ )
+ )
+ weak_regular_pitch_body_candidate = (
+ document_body_profile is not None
+ and 0.9 <= line_height / document_body_profile.body_height <= 1.1
+ and title_prototype is None
+ and (not centered or width_ratio >= 0.75)
+ and not weight_emphasized
+ and gap_above_excess < 0.1
+ and gap_below_excess < 0.1
+ )
+ if weak_regular_pitch_body_candidate:
+ continue
+ if (
+ title_profile_size_conflict
+ and document_body_profile is not None
+ and line_height <= 1.18 * document_body_profile.body_height
+ and not weight_emphasized
+ ):
+ continue
+ prototype_promotion = (
+ title_prototype is not None
+ and (width_ratio <= 0.9 or (bbox[2] - bbox[0]) / max(0.1, local_page_width) <= 0.8)
+ and (centered or left_aligned)
+ and (
+ (document_body_profile is not None and line_height >= 1.18 * document_body_profile.body_height)
+ or near_visual_container
+ or (has_following_body_row and gap_above_excess >= 0.1)
+ or gap_above_excess >= 0.35
+ )
+ )
+ prototype_inline_heading = (
+ document_body_profile is not None
+ and line_height <= 1.15 * document_body_profile.body_height
+ and _is_full_width_inline_heading(
+ rows,
+ index,
+ lane_width,
+ profile,
+ )
+ )
+ if prototype_promotion and not prototype_inline_heading:
+ line.semantic_type = "paragraph_title"
+ selected_indices.add(index)
+ continue
+ if (
+ document_body_profile is not None
+ and 0.9 <= line_height / document_body_profile.body_height <= 1.1
+ and title_prototype is None
+ and centered
+ and not has_following_body_row
+ and not compact_text_section
+ ):
+ continue
+ if height_ratio < 0.9 and not inside_front_matter and not has_following_body_row and not compact_text_section:
+ continue
+ if width_ratio >= 0.9 and height_ratio < 1.15 and not (style_differs and gap_above >= 0.65):
+ continue
+ score = 0.0
+ if style_differs or compact_local_transition:
+ score += 2.0
+ if compact_local_transition or style_support <= 0.2:
+ score += 0.75
+ if weight_emphasized:
+ score += 1.0
+ if height_ratio >= 1.18:
+ score += 2.0
+ elif height_ratio <= 0.9 and centered:
+ score += 0.75
+ if width_ratio <= 0.78:
+ score += 0.75
+ if centered and width_ratio <= 0.85:
+ score += 1.25
+ if gap_above >= 0.65:
+ score += 1.25
+ elif gap_above >= 0.35:
+ score += 0.5
+ if gap_below >= 0.35:
+ score += 0.75
+ 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_structural_fallback
+ or compact_text_section
+ )
+ if score >= 4.0 and (has_spacing_signal or compact_local_transition) and strong_layout_signal:
+ if _is_full_width_inline_heading(
+ rows,
+ index,
+ lane_width,
+ profile,
+ ):
+ continue
+ line.semantic_type = "paragraph_title"
+ selected_indices.add(index)
+
+ _unify_visual_row_title_types(
+ lane,
+ selected_indices,
+ )
+ _expand_paragraph_title_neighbors(
+ lane,
+ selected_indices,
+ profile,
+ )
+ if front_matter_boundary is not None and preserve_front_matter_boundaries:
+ _protect_front_matter_title_types(
+ lane,
+ profile,
+ front_matter_boundary,
+ )
+
+
+def _protect_front_matter_title_types(
+ lane: _TextLane,
+ profile: _LaneBodyProfile,
+ front_matter_boundary: float,
+) -> None:
+ """把作者区误命中的标题降为正文,并仅保留原本需要跨行聚合的内部标记。"""
+
+ front_title_indices = [
+ index
+ for index, (line, bbox) in enumerate(lane.lines)
+ if line.semantic_type == "paragraph_title" and _bbox_center_y(bbox) <= front_matter_boundary
+ ]
+ connected_indices: set[int] = set()
+ for position, first_index in enumerate(front_title_indices):
+ for second_index in front_title_indices[position + 1 :]:
+ if _should_connect_semantic_rows(
+ lane.lines[first_index],
+ lane.lines[second_index],
+ lane,
+ profile.regular_gap,
+ [],
+ [],
+ ):
+ connected_indices.update((first_index, second_index))
+ for index in front_title_indices:
+ lane.lines[index][0].semantic_type = "text" if index in connected_indices else None
+
+
+def _visual_row_has_body_style_sibling(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+) -> bool:
+ """检查同一完整视觉行是否同时包含标题样式与正文样式 run。"""
+
+ line, _bbox = rows[index]
+ if line.visual_row_id is None:
+ return False
+ siblings = [
+ sibling for sibling, _sibling_bbox in rows if sibling is not line and sibling.visual_row_id == line.visual_row_id
+ ]
+ return any(not _title_fonts_compatible(line, sibling) for sibling in siblings)
+
+
+def _is_near_full_mixed_inline_row(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+ lane_width: float,
+ profile: _LaneBodyProfile,
+) -> bool:
+ """识别近满栏混合字体行内强调,避免把粗体条目头单独标成标题。"""
+
+ line, bbox = rows[index]
+ line_height = _line_effective_height(line, bbox)
+ if (
+ line.font_coverage >= 0.95
+ or (bbox[2] - bbox[0]) < 0.85 * lane_width
+ or not 0.85 <= line_height / profile.body_height <= 1.15
+ or index + 1 >= len(rows)
+ ):
+ return False
+ next_line, next_bbox = rows[index + 1]
+ next_height = _line_effective_height(next_line, next_bbox)
+ gap_below = _effective_text_row_gap(rows[index], rows[index + 1])
+ return (
+ next_line.semantic_type is None
+ and 0.8 <= next_height / profile.body_height <= 1.2
+ and gap_below <= profile.regular_gap + 0.25 * profile.body_height
+ )
+
+
+def _continues_local_body_row(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+ lane_width: float,
+ profile: _LaneBodyProfile,
+) -> bool:
+ """识别紧随同字体满行的正文尾行,阻止全局小字号基线造成标题误判。"""
+
+ if index <= 0:
+ return False
+ previous_line, previous_bbox = rows[index - 1]
+ 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 (
+ 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_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(
+ (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
+ and abs(bbox[0] - previous_bbox[0]) <= 2.0 * pair_height
+ and -0.25 * pair_height <= gap <= profile.regular_gap + pair_height
+ )
+
+
+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,
+ lane_width: float,
+ profile: _LaneBodyProfile,
+) -> bool:
+ """识别后接常规正文续行的满栏正常字号行内标题。"""
+
+ line, bbox = rows[index]
+ line_height = _line_effective_height(line, bbox)
+ if (
+ not 0.85 <= line_height / profile.body_height <= 1.15
+ or (bbox[2] - bbox[0]) < 0.9 * lane_width
+ or index + 1 >= len(rows)
+ ):
+ return False
+
+ next_line, next_bbox = rows[index + 1]
+ next_height = _line_effective_height(next_line, next_bbox)
+ next_uses_body_font = (
+ profile.body_font is None
+ or next_line.font_signature is None
+ or next_line.font_coverage < 0.75
+ or _font_signatures_share_family(
+ next_line.font_signature,
+ profile.body_font,
+ )
+ )
+ return (
+ next_line.semantic_type is None
+ and next_uses_body_font
+ and 0.75 <= next_height / profile.body_height <= 1.15
+ and (next_bbox[2] - next_bbox[0]) >= 0.75 * lane_width
+ and _effective_text_row_gap(rows[index], rows[index + 1]) <= profile.regular_gap + 0.25 * profile.body_height
+ )
+
+
+def _has_following_body_row(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+ lane_width: float,
+ lane_left: float,
+ profile: _LaneBodyProfile,
+) -> bool:
+ """只检查紧邻且空间相关的下一行,禁止用远处正文支撑小字号标题。"""
+
+ if index + 1 >= len(rows):
+ return False
+ current = rows[index]
+ line, bbox = rows[index + 1]
+ gap = _effective_text_row_gap(current, (line, bbox))
+ horizontally_related = (
+ _bbox_axis_overlap_ratio(current[1], bbox, axis="x") >= 0.35
+ or abs(current[1][0] - bbox[0]) <= 0.75 * profile.body_height
+ )
+ current_centered = abs(_bbox_center_x(current[1]) - (lane_left + lane_width / 2.0)) <= 0.12 * lane_width
+ compact_left_aligned = (
+ current[1][2] - current[1][0] <= 0.35 * lane_width and abs(current[1][0] - lane_left) <= 0.65 * profile.body_height
+ )
+ maximum_gap = (1.5 if current_centered else 1.25 if compact_left_aligned else 0.75) * profile.body_height
+ height_ratio = _line_effective_height(line, bbox) / profile.body_height
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ return (
+ line.semantic_type is None
+ and horizontally_related
+ and -0.25 * profile.body_height <= gap <= maximum_gap
+ and 0.9 <= height_ratio <= 1.2
+ and width_ratio >= 0.45
+ )
+
+
+def _has_following_compact_text_section(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+ lane_width: float,
+) -> bool:
+ """检查小字号候选后是否紧接三行同尺度的宽文本区段。"""
+
+ candidate = rows[index]
+ candidate_height = _line_effective_height(*candidate)
+ following_rows = rows[index + 1 : index + 4]
+ if len(following_rows) < 3:
+ return False
+
+ previous = candidate
+ for current in following_rows:
+ line, bbox = current
+ height_ratio = _line_effective_height(line, bbox) / candidate_height
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ gap = _effective_text_row_gap(previous, current)
+ if (
+ line.semantic_type is not None
+ or not 0.75 <= height_ratio <= 1.25
+ or width_ratio < 0.45
+ or not -0.25 * candidate_height <= gap <= 0.75 * candidate_height
+ ):
+ return False
+ previous = current
+ return True
+
+
+def _unify_visual_row_title_types(
+ lane: _TextLane,
+ selected_indices: set[int],
+) -> None:
+ """按完整 visual_row_id 统一标题类型:同样式整行晋升,混合样式整行降级。"""
+
+ row_indices: dict[int, list[int]] = {}
+ for index, (line, _bbox) in enumerate(lane.lines):
+ if line.visual_row_id is not None:
+ row_indices.setdefault(line.visual_row_id, []).append(index)
+ for indices in row_indices.values():
+ title_indices = [index for index in indices if lane.lines[index][0].semantic_type == "paragraph_title"]
+ if not title_indices:
+ continue
+ anchor_line, anchor_bbox = lane.lines[title_indices[0]]
+ anchor_height = _line_effective_height(anchor_line, anchor_bbox)
+ compatible = all(
+ 0.75 <= _line_effective_height(lane.lines[index][0], lane.lines[index][1]) / anchor_height <= 1.25
+ and _title_fonts_compatible(anchor_line, lane.lines[index][0])
+ for index in indices
+ )
+ if compatible:
+ for index in indices:
+ lane.lines[index][0].semantic_type = "paragraph_title"
+ selected_indices.add(index)
+ continue
+ for index in title_indices:
+ lane.lines[index][0].semantic_type = None
+ selected_indices.discard(index)
+
+
+def _infer_front_matter_boundary(
+ lane: _TextLane,
+ profile: _LaneBodyProfile,
+ local_page_height: float,
+ *,
+ document_title_bottom: float | None,
+) -> float | None:
+ """用短行后衔接满栏正文的几何转折点界定首页作者等前置信息。"""
+
+ if document_title_bottom is None:
+ return None
+ default_boundary = max(
+ document_title_bottom + 2.5 * profile.body_height,
+ 0.39 * local_page_height,
+ )
+ lane_width = max(0.1, lane.right - lane.left)
+ for index, (line, bbox) in enumerate(lane.lines[:-1]):
+ if bbox[1] <= document_title_bottom:
+ continue
+ next_line, next_bbox = lane.lines[index + 1]
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ next_width_ratio = (next_bbox[2] - next_bbox[0]) / lane_width
+ left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height
+ centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_width
+ next_height_ratio = _line_effective_height(next_line, next_bbox) / profile.body_height
+ gap_below = max(0.0, _effective_text_row_gap((line, bbox), (next_line, next_bbox)))
+ if (
+ width_ratio <= 0.35
+ and next_width_ratio >= 0.75
+ and (left_aligned or centered)
+ and 0.75 <= next_height_ratio <= 1.35
+ and gap_below <= 1.5 * profile.body_height
+ ):
+ return min(default_boundary, bbox[1] - 0.1)
+ return default_boundary
+
+
+def _normalized_title_gap(
+ rows: list[tuple[_LineItem, BBox]],
+ index: int,
+ *,
+ direction: Literal[-1, 1],
+ body_height: float,
+ physical_gaps: dict[int, tuple[float | None, float | None]],
+) -> float:
+ """返回栏内邻行和页面最近物理邻行中较小的归一化净空。"""
+
+ neighbor_index = index + direction
+ if 0 <= neighbor_index < len(rows):
+ if direction < 0:
+ lane_gap = _effective_text_row_gap(rows[neighbor_index], rows[index])
+ else:
+ lane_gap = _effective_text_row_gap(rows[index], rows[neighbor_index])
+ else:
+ lane_gap = 0.5 * body_height
+ physical_pair = physical_gaps.get(rows[index][0].source_index, (None, None))
+ physical_gap = physical_pair[0 if direction < 0 else 1]
+ gap = lane_gap if physical_gap is None else min(lane_gap, physical_gap)
+ return max(0.0, gap) / max(0.1, body_height)
+
+
+def _expand_paragraph_title_neighbors(
+ lane: _TextLane,
+ selected_indices: set[int],
+ profile: _LaneBodyProfile,
+) -> None:
+ """用相邻行的字体、尺寸、对齐和紧凑净空补齐折行段落标题。"""
+
+ if not selected_indices:
+ return
+ rows = lane.lines
+ lane_width = max(0.1, lane.right - lane.left)
+ pending = list(selected_indices)
+ while pending:
+ selected_index = pending.pop()
+ selected_line, selected_bbox = rows[selected_index]
+ selected_height = _line_effective_height(selected_line, selected_bbox)
+ for candidate_index in (selected_index - 1, selected_index + 1):
+ if not 0 <= candidate_index < len(rows) or candidate_index in selected_indices:
+ continue
+ candidate_line, candidate_bbox = rows[candidate_index]
+ if candidate_line.semantic_type is not None:
+ continue
+ candidate_height = _line_effective_height(candidate_line, candidate_bbox)
+ if not 0.75 <= candidate_height / selected_height <= 1.25:
+ continue
+ if candidate_bbox[2] - candidate_bbox[0] > 0.8 * lane_width:
+ continue
+ if (
+ selected_line.font_signature is not None
+ and candidate_line.font_signature is not None
+ and selected_line.font_signature != candidate_line.font_signature
+ ):
+ continue
+ if not _title_fonts_compatible(selected_line, candidate_line):
+ continue
+ vertical_gap = max(
+ candidate_bbox[1] - selected_bbox[3],
+ selected_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ centers_align = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(selected_bbox)) <= 0.15 * lane_width
+ left_edges_align = abs(candidate_bbox[0] - selected_bbox[0]) <= 0.75 * profile.body_height
+ wrapped_indent = abs(candidate_bbox[0] - selected_bbox[0]) <= 2.0 * profile.body_height
+ if vertical_gap > 0.65 * profile.body_height or not (centers_align or left_edges_align or wrapped_indent):
+ continue
+ candidate_line.semantic_type = "paragraph_title"
+ selected_indices.add(candidate_index)
+ pending.append(candidate_index)
+
+
+__all__ = [
+ "_classify_paragraph_titles_in_lane",
+ "_protect_front_matter_title_types",
+ "_visual_row_has_body_style_sibling",
+ "_is_near_full_mixed_inline_row",
+ "_continues_local_body_row",
+ "_is_continuous_field_row",
+ "_is_full_width_inline_heading",
+ "_has_following_body_row",
+ "_has_following_compact_text_section",
+ "_unify_visual_row_title_types",
+ "_infer_front_matter_boundary",
+ "_normalized_title_gap",
+ "_expand_paragraph_title_neighbors",
+]
diff --git a/mineru/model/flash/pdf/title_analysis/page_titles.py b/mineru/model/flash/pdf/title_analysis/page_titles.py
new file mode 100644
index 00000000..a2c64330
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/page_titles.py
@@ -0,0 +1,1030 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""编排页面文档标题、跨栏标题及误判回退。"""
+
+from __future__ import annotations
+
+import re
+import statistics
+
+from .....types import BBox
+from ..geometry import _bbox_axis_overlap_ratio, _bbox_center_x, _bbox_center_y, _bbox_union_many, _rotate_bbox_to_upright
+from ..inline.types import PDF_FONT_ITALIC_FLAG
+from ..line_layout import (
+ _effective_text_row_gap,
+ _font_signatures_share_family,
+ _infer_text_lanes,
+ _line_effective_height,
+ _title_fonts_compatible,
+)
+from ..models import (
+ _DocumentBodyProfile,
+ _DocumentTitleProfile,
+ _LineItem,
+ _TextLane,
+)
+from .body_profile import _infer_lane_body_profile, _line_uses_document_regular_font
+from .common import _build_physical_title_gap_map, _line_inside_visual_container, _line_near_visual_container
+from .lane_titles import _classify_paragraph_titles_in_lane
+
+
+def _classify_page_titles(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ *,
+ page_index: int,
+ container_bboxes: list[BBox],
+ caption_container_bboxes: list[BBox] | None = None,
+ document_body_profile: _DocumentBodyProfile | None = None,
+ document_title_profile: _DocumentTitleProfile | None = None,
+) -> None:
+ """只用页面几何与字体排版标注首页文档标题和各页段落标题。"""
+
+ for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
+ line_geometry = [
+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
+ for line in lines
+ if line.angle == angle and (line.semantic_type is None or line.explicit_section_title) and not line.title_suppressed
+ ]
+ if not line_geometry:
+ continue
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
+ 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)
+ for lane in lanes:
+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ physical_gaps = _build_physical_title_gap_map(line_geometry)
+ grid_title_suppressions = _find_repeated_grid_title_suppressions(
+ lanes,
+ median_height,
+ )
+ local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
+ grid_title_suppressions.update(
+ _find_container_visual_row_title_suppressions(
+ line_geometry,
+ local_container_bboxes,
+ median_height,
+ )
+ )
+
+ document_title_bottom: float | None = None
+ if page_index == 0:
+ document_title_bottom = _classify_document_title(
+ lanes,
+ local_page_height,
+ local_page_width,
+ document_body_profile=document_body_profile,
+ )
+ document_title_bottom = _expand_document_title_across_lanes(
+ line_geometry,
+ local_page_width,
+ local_page_height,
+ document_title_bottom,
+ )
+ document_title_bottom = _classify_additional_document_title_bands(
+ line_geometry,
+ local_page_width,
+ local_page_height,
+ document_title_bottom,
+ document_body_profile=document_body_profile,
+ )
+ preserve_front_matter_boundaries = _document_title_uses_page_fallback(
+ lanes,
+ document_body_profile=document_body_profile,
+ )
+
+ _classify_cross_lane_centered_section_titles(
+ line_geometry,
+ lanes,
+ local_page_width,
+ local_page_height,
+ local_container_bboxes,
+ page_index=page_index,
+ document_title_bottom=document_title_bottom,
+ )
+ _classify_cross_lane_emphasized_section_titles(
+ line_geometry,
+ lanes,
+ local_page_width,
+ local_page_height,
+ local_container_bboxes,
+ document_title_bottom=document_title_bottom,
+ document_body_profile=document_body_profile,
+ )
+
+ for lane in lanes:
+ profile = _infer_lane_body_profile(lane)
+ _classify_paragraph_titles_in_lane(
+ lane,
+ profile,
+ local_page_width,
+ local_page_height,
+ local_container_bboxes,
+ document_title_bottom=document_title_bottom,
+ preserve_front_matter_boundaries=preserve_front_matter_boundaries,
+ physical_gaps=physical_gaps,
+ grid_title_suppressions=grid_title_suppressions,
+ document_body_profile=document_body_profile,
+ document_title_profile=document_title_profile,
+ page_index=page_index,
+ )
+ _expand_cross_lane_paragraph_title_neighbors(
+ line_geometry,
+ )
+ _demote_hanging_multiline_text_titles(
+ lanes,
+ document_body_profile,
+ page_index=page_index,
+ )
+ _demote_cross_lane_body_continuation_titles(
+ line_geometry,
+ lanes,
+ )
+ _demote_visual_container_caption_titles(
+ line_geometry,
+ [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in (caption_container_bboxes or [])],
+ )
+ _demote_sentence_tail_titles(
+ [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ angle,
+ ),
+ )
+ for line in lines
+ if line.angle == angle and line.semantic_type in {None, "paragraph_title"} and not line.title_suppressed
+ ],
+ )
+ if document_body_profile is not None and document_body_profile.has_style_scale_repairs:
+ _demote_non_structural_anomaly_titles(line_geometry)
+
+
+def _demote_non_structural_anomaly_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> None:
+ """在 loose 高度异常文档中只保留预先通过结构转折校验的段落标题。"""
+
+ for line, _bbox in line_geometry:
+ if line.semantic_type == "paragraph_title" and not line.structural_title:
+ line.semantic_type = None
+
+
+def _find_repeated_grid_title_suppressions(
+ lanes: list[_TextLane],
+ median_height: float,
+) -> set[int]:
+ """识别重复双栏信息网格中的短首行,避免把城市等记录头标成标题。"""
+
+ candidates: list[tuple[int, int, float]] = []
+ for lane_index, lane in enumerate(lanes):
+ if lane.is_span:
+ continue
+ lane_width = max(0.1, lane.right - lane.left)
+ for row_index, (line, bbox) in enumerate(lane.lines[:-1]):
+ next_line, next_bbox = lane.lines[row_index + 1]
+ width = bbox[2] - bbox[0]
+ next_width = next_bbox[2] - next_bbox[0]
+ gap = _effective_text_row_gap(
+ (line, bbox),
+ (next_line, next_bbox),
+ )
+ if (
+ line.semantic_type is not None
+ or next_line.semantic_type is not None
+ or width > 0.35 * lane_width
+ or next_width < max(0.6 * lane_width, 1.8 * width)
+ or abs(next_bbox[0] - bbox[0]) > 0.75 * median_height
+ or not -0.25 * median_height <= gap <= 0.75 * median_height
+ ):
+ continue
+ candidates.append((lane_index, line.source_index, _bbox_center_y(bbox)))
+
+ bands: list[list[tuple[int, int, float]]] = []
+ for candidate in sorted(candidates, key=lambda item: item[2]):
+ target = next(
+ (band for band in bands if abs(candidate[2] - statistics.median(item[2] for item in band)) <= 0.5 * median_height),
+ None,
+ )
+ if target is None:
+ bands.append([candidate])
+ else:
+ target.append(candidate)
+ paired_bands = [
+ {source_index for _lane_index, source_index, _center_y in band}
+ for band in bands
+ if len({lane_index for lane_index, _source_index, _center_y in band}) >= 2
+ ]
+ if len(paired_bands) < 2:
+ return set()
+ return set().union(*paired_bands)
+
+
+def _find_container_visual_row_title_suppressions(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ container_bboxes: list[BBox],
+ median_height: float,
+) -> set[int]:
+ """用完整视觉行与图表容器的邻接关系抑制拆分 caption 标题误报。"""
+
+ visual_rows: dict[int, list[tuple[_LineItem, BBox]]] = {}
+ for item in line_geometry:
+ row_id = item[0].visual_row_id
+ if row_id is not None:
+ visual_rows.setdefault(row_id, []).append(item)
+ suppressed: set[int] = set()
+ for members in visual_rows.values():
+ if len(members) < 2:
+ continue
+ row_bbox = _bbox_union_many([bbox for _line, bbox in members])
+ if any(
+ _bbox_axis_overlap_ratio(row_bbox, container_bbox, axis="x") >= 0.35
+ and max(
+ row_bbox[1] - container_bbox[3],
+ container_bbox[1] - row_bbox[3],
+ 0.0,
+ )
+ <= 1.5 * median_height
+ for container_bbox in container_bboxes
+ ):
+ suppressed.update(line.source_index for line, _bbox in members)
+ return suppressed
+
+
+def _classify_document_title(
+ lanes: list[_TextLane],
+ local_page_height: float,
+ local_page_width: float,
+ *,
+ document_body_profile: _DocumentBodyProfile | None = None,
+) -> float | None:
+ """从首页上部选取显著大字号锚点,并用同版式邻行扩展多行文档标题。"""
+
+ candidates: list[tuple[float, _TextLane, int, tuple[_LineItem, BBox]]] = []
+ lane_profiles = [(lane, _infer_lane_body_profile(lane)) for lane in lanes]
+ column_body_heights = [profile.body_height for lane, profile in lane_profiles if not lane.is_span]
+ if document_body_profile is not None:
+ document_body_height = document_body_profile.body_height
+ else:
+ document_body_height = (
+ statistics.median(column_body_heights)
+ if column_body_heights
+ else min(
+ (profile.body_height for _lane, profile in lane_profiles),
+ default=1.0,
+ )
+ )
+ for lane, profile in lane_profiles:
+ lane_width = max(0.1, lane.right - lane.left)
+ available = [item for item in lane.lines if item[0].semantic_type is None]
+ for row_index, item in enumerate(available):
+ line, bbox = item
+ reference_height = min(profile.body_height, 1.25 * document_body_height)
+ height_ratio = _line_effective_height(line, bbox) / max(0.1, reference_height)
+ document_height_ratio = _line_effective_height(line, bbox) / max(
+ 0.1,
+ document_body_height,
+ )
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.15 * lane_width
+ page_centered = abs(_bbox_center_x(bbox) - 0.5 * local_page_width) <= 0.15 * local_page_width
+ page_width_ratio = (bbox[2] - bbox[0]) / max(0.1, local_page_width)
+ spans_columns_fallback = lane.is_span and centered and width_ratio >= 0.65 and document_height_ratio >= 1.3
+ if (
+ _bbox_center_y(bbox) > 0.45 * local_page_height
+ or (height_ratio < 1.4 and not spans_columns_fallback)
+ or width_ratio < 0.2
+ or (not centered and height_ratio < 1.7)
+ or (not page_centered and page_width_ratio < 0.45 and height_ratio < 1.8)
+ ):
+ continue
+ top_preference = max(0.0, 0.45 - _bbox_center_y(bbox) / local_page_height)
+ top_preference_weight = (
+ 4.0 if document_body_profile is not None and document_body_profile.has_style_scale_repairs else 1.0
+ )
+ score = (
+ height_ratio
+ + (0.75 if centered else 0.0)
+ + (1.25 if page_centered else 0.0)
+ + (0.75 if page_width_ratio >= 0.55 else 0.0)
+ + top_preference_weight * top_preference
+ - 0.02 * row_index
+ )
+ candidates.append((score, lane, row_index, item))
+ if not candidates:
+ return None
+
+ _score, lane, _row_index, anchor = max(candidates, key=lambda item: item[0])
+ anchor_line, anchor_bbox = anchor
+ anchor_height = _line_effective_height(anchor_line, anchor_bbox)
+ anchor_line.semantic_type = "doc_title"
+ selected = [anchor]
+ ordered = lane.lines
+ anchor_index = ordered.index(anchor)
+ for direction in (-1, 1):
+ index = anchor_index + direction
+ previous_bbox = anchor_bbox
+ while 0 <= index < len(ordered):
+ candidate_line, candidate_bbox = ordered[index]
+ if candidate_line.semantic_type is not None:
+ break
+ candidate_height = _line_effective_height(candidate_line, candidate_bbox)
+ if not 0.8 <= candidate_height / anchor_height <= 1.25:
+ break
+ if not _document_title_fonts_compatible(anchor_line, candidate_line):
+ break
+ vertical_gap = max(candidate_bbox[1] - previous_bbox[3], previous_bbox[1] - candidate_bbox[3], 0.0)
+ lane_width = max(0.1, lane.right - lane.left)
+ centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(anchor_bbox)) <= 0.18 * lane_width
+ aligned = abs(candidate_bbox[0] - anchor_bbox[0]) <= 0.75 * anchor_height
+ if vertical_gap > 1.1 * anchor_height or not (centered or aligned):
+ break
+ candidate_line.semantic_type = "doc_title"
+ selected.append((candidate_line, candidate_bbox))
+ previous_bbox = candidate_bbox
+ index += direction
+ return max(bbox[3] for _line, bbox in selected)
+
+
+def _expand_document_title_across_lanes(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ local_page_width: float,
+ local_page_height: float,
+ document_title_bottom: float | None,
+) -> float | None:
+ """跨错误推断栏扩展紧邻、同字号且对齐的多行文档标题。"""
+
+ title_items = [item for item in line_geometry if item[0].semantic_type == "doc_title"]
+ if not title_items:
+ return document_title_bottom
+ selected_ids = {id(line) for line, _bbox in title_items}
+ changed = True
+ while changed:
+ changed = False
+ title_bbox = _bbox_union_many([bbox for _line, bbox in title_items])
+ title_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in title_items)
+ anchors = [line for line, _bbox in title_items]
+ candidates = [
+ item
+ for item in line_geometry
+ if id(item[0]) not in selected_ids
+ and item[0].semantic_type is None
+ and _bbox_center_y(item[1]) <= 0.45 * local_page_height
+ ]
+ candidates.sort(
+ key=lambda item: min(
+ abs(item[1][1] - title_bbox[3]),
+ abs(title_bbox[1] - item[1][3]),
+ )
+ )
+ for candidate_line, candidate_bbox in candidates:
+ candidate_height = _line_effective_height(
+ candidate_line,
+ candidate_bbox,
+ )
+ if not 0.8 <= candidate_height / max(0.1, title_height) <= 1.25:
+ continue
+ if not any(_document_title_fonts_compatible(anchor, candidate_line) for anchor in anchors):
+ continue
+ vertical_gap = max(
+ candidate_bbox[1] - title_bbox[3],
+ title_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox)) <= 0.18 * local_page_width
+ aligned = abs(candidate_bbox[0] - title_bbox[0]) <= 0.75 * title_height
+ title_width = max(0.1, title_bbox[2] - title_bbox[0])
+ candidate_width = candidate_bbox[2] - candidate_bbox[0]
+ aligned_continuation = aligned and candidate_width >= 0.25 * title_width
+ centered_continuation = centered and candidate_width >= 0.45 * title_width
+ if vertical_gap > 1.1 * title_height or not (aligned_continuation or centered_continuation):
+ continue
+ candidate_line.semantic_type = "doc_title"
+ title_items.append((candidate_line, candidate_bbox))
+ selected_ids.add(id(candidate_line))
+ changed = True
+ break
+ return max(bbox[3] for _line, bbox in title_items)
+
+
+def _classify_additional_document_title_bands(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ local_page_width: float,
+ local_page_height: float,
+ document_title_bottom: float | None,
+ *,
+ document_body_profile: _DocumentBodyProfile | None,
+) -> float | None:
+ """用居中译题与后续作者行结构补充首页第二文档标题带。"""
+
+ if document_title_bottom is None or document_body_profile is None or not document_body_profile.has_style_scale_repairs:
+ return document_title_bottom
+ body_height = max(0.1, document_body_profile.body_height)
+ ordered = sorted(
+ line_geometry,
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ selected_bottoms = [bbox[3] for line, bbox in ordered if line.semantic_type == "doc_title"]
+ for index, (line, bbox) in enumerate(ordered):
+ if line.semantic_type is not None:
+ continue
+ center_y = _bbox_center_y(bbox)
+ width_ratio = (bbox[2] - bbox[0]) / max(0.1, local_page_width)
+ if not (document_title_bottom + 4.0 * body_height <= center_y <= 0.58 * local_page_height):
+ continue
+ if not 0.4 <= width_ratio <= 0.8:
+ continue
+ if abs(_bbox_center_x(bbox) - 0.5 * local_page_width) > 0.08 * local_page_width:
+ continue
+ if _line_uses_document_regular_font(line, document_body_profile):
+ continue
+ following = [
+ item for item in ordered[index + 1 :] if item[0].semantic_type is None and _bbox_center_y(item[1]) > center_y
+ ]
+ if not following:
+ continue
+ _next_line, next_bbox = following[0]
+ next_width_ratio = (next_bbox[2] - next_bbox[0]) / max(0.1, local_page_width)
+ next_centered = abs(_bbox_center_x(next_bbox) - 0.5 * local_page_width) <= 0.12 * local_page_width
+ vertical_gap = max(0.0, next_bbox[1] - bbox[3])
+ if not next_centered or next_width_ratio > 0.45 or vertical_gap > 2.0 * body_height:
+ continue
+ line.semantic_type = "doc_title"
+ selected_bottoms.append(bbox[3])
+ return max(selected_bottoms, default=document_title_bottom)
+
+
+def _classify_cross_lane_centered_section_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+ local_page_width: float,
+ local_page_height: float,
+ container_bboxes: list[BBox],
+ *,
+ page_index: int,
+ document_title_bottom: float | None,
+) -> None:
+ """用正文栏中心、上下留白和正文邻行补标被单独推成窄栏的标题。"""
+
+ stable_lanes = [
+ lane for lane in lanes if not lane.is_span and len(lane.lines) >= 5 and lane.right - lane.left >= 0.2 * local_page_width
+ ]
+ for line, bbox in line_geometry:
+ if line.semantic_type is not None:
+ continue
+ if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
+ continue
+ candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
+ if not candidate_lanes:
+ continue
+ lane = min(
+ candidate_lanes,
+ key=lambda candidate: abs(_bbox_center_x(bbox) - 0.5 * (candidate.left + candidate.right)),
+ )
+ profile = _infer_lane_body_profile(lane)
+ lane_width = max(0.1, lane.right - lane.left)
+ line_width = bbox[2] - bbox[0]
+ line_height = _line_effective_height(line, bbox)
+ if not 0.08 * lane_width <= line_width <= 0.7 * lane_width:
+ continue
+ if abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)) > 0.05 * lane_width:
+ continue
+ if not 0.75 <= line_height / max(0.1, profile.body_height) <= 1.3:
+ continue
+ uses_regular_font = (
+ profile.body_font is not None
+ and line.font_signature is not None
+ and line.font_coverage >= 0.75
+ and _font_signatures_share_family(
+ line.font_signature,
+ profile.body_font,
+ )
+ )
+ weight_emphasized = (
+ profile.body_weight is not None
+ and line.dominant_font_weight is not None
+ and line.dominant_font_weight
+ >= max(
+ profile.body_weight + 100.0,
+ 1.15 * profile.body_weight,
+ )
+ )
+ if page_index == 0 and line_height < 0.9 * profile.body_height and uses_regular_font and not weight_emphasized:
+ continue
+ if document_title_bottom is not None and bbox[1] <= document_title_bottom + profile.body_height:
+ continue
+ if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
+ bbox,
+ container_bboxes,
+ profile.body_height,
+ ):
+ continue
+ body_rows = [
+ item
+ for item in lane.lines
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[1][2] - item[1][0] >= 0.5 * lane_width
+ and 0.75 <= _line_effective_height(*item) / max(0.1, profile.body_height) <= 1.3
+ ]
+ rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < _bbox_center_y(bbox)]
+ rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > _bbox_center_y(bbox)]
+ if not rows_above or not rows_below:
+ continue
+ previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
+ following_rows = sorted(
+ rows_below,
+ key=lambda item: _bbox_center_y(item[1]),
+ )
+ if len(following_rows) < 3 or any(
+ _effective_text_row_gap(previous_row, current_row) > profile.regular_gap + 0.75 * profile.body_height
+ for previous_row, current_row in zip(
+ following_rows[:3],
+ following_rows[1:3],
+ )
+ ):
+ continue
+ following = following_rows[0]
+ gap_above = bbox[1] - previous[1][3]
+ gap_below = following[1][1] - bbox[3]
+ if (
+ gap_above < 0.3 * profile.body_height
+ or gap_below < -0.1 * profile.body_height
+ or max(gap_above, gap_below) < profile.regular_gap + 0.2 * profile.body_height
+ ):
+ continue
+ line.semantic_type = "paragraph_title"
+
+
+def _demote_cross_lane_body_continuation_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+) -> None:
+ """把紧接上一正文行、同字号同字体的短续行从标题降回正文。"""
+
+ stable_lanes = [lane for lane in lanes if not lane.is_span and len(lane.lines) >= 4]
+ for line, bbox in line_geometry:
+ if line.semantic_type != "paragraph_title":
+ continue
+ line_height = _line_effective_height(line, bbox)
+ global_preceding = [
+ item
+ for item in line_geometry
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[0].angle == line.angle
+ and _bbox_center_y(item[1]) < _bbox_center_y(bbox)
+ and abs(item[1][0] - bbox[0]) <= line_height
+ ]
+ if global_preceding:
+ previous_line, previous_bbox = max(
+ global_preceding,
+ key=lambda item: _bbox_center_y(item[1]),
+ )
+ previous_height = _line_effective_height(
+ previous_line,
+ previous_bbox,
+ )
+ same_family = (
+ previous_line.font_signature is None
+ or line.font_signature is None
+ or _font_signatures_share_family(
+ previous_line.font_signature,
+ line.font_signature,
+ )
+ )
+ if (
+ same_family
+ and 0.9 <= line_height / max(0.1, previous_height) <= 1.1
+ and bbox[1] - previous_bbox[3] <= 0.2 * max(line_height, previous_height)
+ and abs(bbox[0] - previous_bbox[0]) <= 0.75 * max(line_height, previous_height)
+ and previous_bbox[2] - previous_bbox[0] >= 2.0 * (bbox[2] - bbox[0])
+ ):
+ line.semantic_type = None
+ continue
+ candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
+ if not candidate_lanes:
+ continue
+ lane = min(
+ candidate_lanes,
+ key=lambda candidate: abs(_bbox_center_x(bbox) - 0.5 * (candidate.left + candidate.right)),
+ )
+ lane_width = max(0.1, lane.right - lane.left)
+ lane_profile = _infer_lane_body_profile(lane)
+ if bbox[2] - bbox[0] > 0.55 * lane_width:
+ continue
+ preceding = [
+ item
+ for item in line_geometry
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and _bbox_center_y(item[1]) < _bbox_center_y(bbox)
+ and lane.left <= _bbox_center_x(item[1]) <= lane.right
+ ]
+ if not preceding:
+ continue
+ previous_line, previous_bbox = max(
+ preceding,
+ key=lambda item: _bbox_center_y(item[1]),
+ )
+ previous_height = _line_effective_height(
+ previous_line,
+ previous_bbox,
+ )
+ line_height = _line_effective_height(line, bbox)
+ if not 0.9 <= line_height / max(0.1, previous_height) <= 1.1:
+ continue
+ if (
+ previous_line.font_signature is not None
+ and line.font_signature is not None
+ and not _font_signatures_share_family(
+ previous_line.font_signature,
+ line.font_signature,
+ )
+ ):
+ continue
+ if previous_bbox[2] - previous_bbox[0] < 0.5 * lane_width:
+ continue
+ maximum_gap = 0.15 * max(line_height, previous_height)
+ if (
+ re.search(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ line.text.rstrip(),
+ )
+ is not None
+ ):
+ maximum_gap = max(
+ maximum_gap,
+ lane_profile.regular_gap + 0.35 * lane_profile.body_height,
+ )
+ if bbox[1] - previous_bbox[3] > maximum_gap:
+ continue
+ if abs(bbox[0] - lane.left) > max(1.0, 0.75 * line_height):
+ continue
+ line.semantic_type = None
+
+
+def _classify_cross_lane_emphasized_section_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lanes: list[_TextLane],
+ local_page_width: float,
+ local_page_height: float,
+ container_bboxes: list[BBox],
+ *,
+ document_title_bottom: float | None,
+ document_body_profile: _DocumentBodyProfile | None,
+) -> None:
+ """用正文栏左缘、强调字体和段间留白补标跨栏推断失败的小节标题。"""
+
+ stable_lanes = [
+ lane for lane in lanes if not lane.is_span and len(lane.lines) >= 5 and lane.right - lane.left >= 0.2 * local_page_width
+ ]
+ for line, bbox in line_geometry:
+ if line.semantic_type is not None or line.font_signature is None:
+ continue
+ if not line.font_signature[1] & PDF_FONT_ITALIC_FLAG:
+ continue
+ if _line_uses_document_regular_font(line, document_body_profile):
+ continue
+ if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
+ continue
+ candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
+ if not candidate_lanes:
+ continue
+ lane = min(
+ candidate_lanes,
+ key=lambda candidate: abs(bbox[0] - candidate.left),
+ )
+ profile = _infer_lane_body_profile(lane)
+ if profile.body_font is None or line.font_signature == profile.body_font or line.font_coverage < 0.75:
+ continue
+ lane_width = max(0.1, lane.right - lane.left)
+ line_height = _line_effective_height(line, bbox)
+ if bbox[2] - bbox[0] > 0.9 * lane_width:
+ continue
+ if abs(bbox[0] - lane.left) > 2.0 * profile.body_height:
+ continue
+ if not 0.8 <= line_height / max(0.1, profile.body_height) <= 1.35:
+ continue
+ if document_title_bottom is not None and bbox[1] <= document_title_bottom + 2.0 * profile.body_height:
+ continue
+ if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
+ bbox,
+ container_bboxes,
+ profile.body_height,
+ ):
+ continue
+ body_rows = [
+ item
+ for item in lane.lines
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[0].font_signature == profile.body_font
+ and item[1][2] - item[1][0] >= 0.45 * lane_width
+ ]
+ rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < _bbox_center_y(bbox)]
+ rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > _bbox_center_y(bbox)]
+ if not rows_above or not rows_below:
+ continue
+ previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
+ following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
+ gap_above = bbox[1] - previous[1][3]
+ gap_below = following[1][1] - bbox[3]
+ if (
+ gap_above < 0.35 * profile.body_height
+ or gap_below > 3.0 * profile.body_height
+ or gap_below < -0.1 * profile.body_height
+ ):
+ continue
+ line.semantic_type = "paragraph_title"
+
+
+def _is_wide_leading_title_continuation(
+ title_bbox: BBox,
+ candidate_bbox: BBox,
+ title_height: float,
+ candidate_height: float,
+) -> bool:
+ """识别紧贴在窄标题锚点上方、同中心的较宽首行。"""
+
+ pair_height = max(0.1, title_height, candidate_height)
+ title_width = max(0.1, title_bbox[2] - title_bbox[0])
+ width_ratio = (candidate_bbox[2] - candidate_bbox[0]) / title_width
+ vertical_gap = title_bbox[1] - candidate_bbox[3]
+ return (
+ 2.0 < width_ratio <= 2.5
+ and _bbox_center_y(candidate_bbox) < _bbox_center_y(title_bbox)
+ and -0.1 * pair_height <= vertical_gap <= 0.15 * pair_height
+ and _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") >= 0.8
+ and abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox)) <= 0.5 * pair_height
+ )
+
+
+def _expand_cross_lane_paragraph_title_neighbors(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> None:
+ """把紧贴标题锚点的同字体相邻行跨栏补标为同一标题。"""
+
+ changed = True
+ while changed:
+ changed = False
+ title_items = [
+ item for item in line_geometry if item[0].semantic_type == "paragraph_title" and not item[0].explicit_section_title
+ ]
+ for title_line, title_bbox in title_items:
+ title_height = _line_effective_height(title_line, title_bbox)
+ for candidate_line, candidate_bbox in line_geometry:
+ if candidate_line.semantic_type is not None:
+ continue
+ candidate_height = _line_effective_height(
+ candidate_line,
+ candidate_bbox,
+ )
+ if not 0.85 <= candidate_height / max(0.1, title_height) <= 1.2:
+ continue
+ title_width = max(0.1, title_bbox[2] - title_bbox[0])
+ candidate_width = candidate_bbox[2] - candidate_bbox[0]
+ if not (
+ 0.25 <= candidate_width / title_width <= 2.0
+ or _is_wide_leading_title_continuation(
+ title_bbox,
+ candidate_bbox,
+ title_height,
+ candidate_height,
+ )
+ ):
+ continue
+ if (
+ title_line.font_signature is not None
+ and candidate_line.font_signature is not None
+ and title_line.font_signature != candidate_line.font_signature
+ ):
+ continue
+ vertical_gap = max(
+ candidate_bbox[1] - title_bbox[3],
+ title_bbox[1] - candidate_bbox[3],
+ 0.0,
+ )
+ if vertical_gap > 0.35 * max(title_height, candidate_height):
+ continue
+ if (
+ _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") < 0.2
+ and abs(candidate_bbox[0] - title_bbox[0]) > 2.0 * title_height
+ ):
+ continue
+ candidate_line.semantic_type = "paragraph_title"
+ changed = True
+ break
+ if changed:
+ break
+
+
+def _demote_hanging_multiline_text_titles(
+ lanes: list[_TextLane],
+ document_body_profile: _DocumentBodyProfile | None,
+ *,
+ page_index: int,
+) -> None:
+ """把缩进满行后回到栏左缘的紧邻标题行组降回正文。"""
+
+ if page_index != 0 or document_body_profile is None:
+ return
+ body_height = max(0.1, document_body_profile.body_height)
+ for lane in lanes:
+ 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)
+ for first, second in zip(rows, rows[1:]):
+ first_line, first_bbox = first
+ second_line, second_bbox = second
+ if (
+ first_line.semantic_type != "paragraph_title"
+ or second_line.semantic_type != "paragraph_title"
+ or first_line.font_signature is None
+ or second_line.font_signature is None
+ or first_line.font_coverage < 0.75
+ or second_line.font_coverage < 0.75
+ or not _font_signatures_share_family(
+ first_line.font_signature,
+ second_line.font_signature,
+ )
+ ):
+ continue
+ first_height = _line_effective_height(*first)
+ second_height = _line_effective_height(*second)
+ pair_height = max(first_height, second_height)
+ if not (
+ max(first_height, second_height) <= 1.1 * body_height
+ and min(first_height, second_height) >= 0.85 * pair_height
+ and first_bbox[2] - first_bbox[0] >= 0.9 * lane_width
+ and first_bbox[0] - lane.left >= 0.75 * pair_height
+ and abs(second_bbox[0] - lane.left) <= 0.5 * pair_height
+ and -0.25 * pair_height <= _effective_text_row_gap(first, second) <= 0.5 * pair_height
+ ):
+ continue
+ first_line.semantic_type = None
+ second_line.semantic_type = None
+ first_line.title_suppressed = True
+ second_line.title_suppressed = True
+
+
+def _demote_visual_container_caption_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ container_bboxes: list[BBox],
+) -> None:
+ """把紧贴视觉容器下缘且水平居中的标题候选降回普通图注文本。"""
+
+ for line, bbox in line_geometry:
+ if line.semantic_type != "paragraph_title":
+ continue
+ line_height = _line_effective_height(line, bbox)
+ for container_bbox in container_bboxes:
+ vertical_gap = bbox[1] - container_bbox[3]
+ if not -0.25 * line_height <= vertical_gap <= 1.5 * line_height:
+ continue
+ if _bbox_axis_overlap_ratio(bbox, container_bbox, axis="x") < 0.35:
+ continue
+ if abs(_bbox_center_x(bbox) - _bbox_center_x(container_bbox)) > 0.35 * max(
+ container_bbox[2] - container_bbox[0],
+ bbox[2] - bbox[0],
+ ):
+ continue
+ line.semantic_type = None
+ break
+
+
+def _demote_sentence_tail_titles(
+ line_geometry: list[tuple[_LineItem, BBox]],
+) -> None:
+ """把紧接未完正文、以句末标点结束的短行标题降回正文。"""
+
+ for line, bbox in line_geometry:
+ if (
+ line.semantic_type != "paragraph_title"
+ or re.search(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ line.text.rstrip(),
+ )
+ is None
+ ):
+ continue
+ line_height = _line_effective_height(line, bbox)
+ preceding = [
+ item
+ for item in line_geometry
+ if item[0] is not line
+ and item[0].semantic_type is None
+ and item[1][3] <= bbox[1]
+ and abs(item[1][0] - bbox[0]) <= 0.75 * line_height
+ ]
+ if not preceding:
+ continue
+ previous_line, previous_bbox = max(
+ preceding,
+ key=lambda item: item[1][3],
+ )
+ previous_height = _line_effective_height(
+ previous_line,
+ previous_bbox,
+ )
+ same_family = (
+ previous_line.font_signature is None
+ or line.font_signature is None
+ or _font_signatures_share_family(
+ previous_line.font_signature,
+ line.font_signature,
+ )
+ )
+ bbox_height = max(0.1, bbox[3] - bbox[1])
+ previous_bbox_height = max(
+ 0.1,
+ previous_bbox[3] - previous_bbox[1],
+ )
+ compatible_height = (same_family and 0.75 <= line_height / max(0.1, previous_height) <= 1.25) or (
+ 0.8 <= bbox_height / previous_bbox_height <= 1.2
+ )
+ if (
+ compatible_height
+ and bbox[1] - previous_bbox[3]
+ <= 0.9
+ * max(
+ line_height,
+ previous_height,
+ bbox_height,
+ previous_bbox_height,
+ )
+ and previous_bbox[2] - previous_bbox[0] >= 1.5 * (bbox[2] - bbox[0])
+ and re.search(
+ r"[.!?。!?][\]\)})】》”’'\"]*$",
+ previous_line.text.rstrip(),
+ )
+ is None
+ ):
+ line.semantic_type = None
+
+
+def _document_title_fonts_compatible(
+ first: _LineItem,
+ second: _LineItem,
+) -> bool:
+ """允许混排标题因主字体覆盖不足而切换字体,同时保留可靠字重屏障。"""
+
+ if _title_fonts_compatible(first, second):
+ return True
+ uncertain_dominant_font = min(first.font_coverage, second.font_coverage) < 0.85
+ weights_compatible = (
+ first.dominant_font_weight is None
+ or second.dominant_font_weight is None
+ or abs(first.dominant_font_weight - second.dominant_font_weight) < 100.0
+ or max(first.dominant_font_weight, second.dominant_font_weight)
+ < 1.15 * min(first.dominant_font_weight, second.dominant_font_weight)
+ )
+ return uncertain_dominant_font and weights_compatible
+
+
+def _document_title_uses_page_fallback(
+ lanes: list[_TextLane],
+ *,
+ document_body_profile: _DocumentBodyProfile | None = None,
+) -> bool:
+ """判断首页标题是否依赖跨栏 1.30 倍全文正文行高兜底。"""
+
+ title_heights = [
+ _line_effective_height(line, bbox) for lane in lanes for line, bbox in lane.lines if line.semantic_type == "doc_title"
+ ]
+ column_body_heights = [_infer_lane_body_profile(lane).body_height for lane in lanes if not lane.is_span]
+ if not title_heights or not column_body_heights:
+ return False
+ document_body_height = (
+ document_body_profile.body_height if document_body_profile is not None else statistics.median(column_body_heights)
+ )
+ return any(1.3 <= title_height / max(0.1, document_body_height) < 1.4 for title_height in title_heights)
+
+
+__all__ = [
+ "_classify_page_titles",
+ "_demote_non_structural_anomaly_titles",
+ "_find_repeated_grid_title_suppressions",
+ "_find_container_visual_row_title_suppressions",
+ "_classify_document_title",
+ "_expand_document_title_across_lanes",
+ "_classify_additional_document_title_bands",
+ "_classify_cross_lane_centered_section_titles",
+ "_demote_cross_lane_body_continuation_titles",
+ "_classify_cross_lane_emphasized_section_titles",
+ "_is_wide_leading_title_continuation",
+ "_expand_cross_lane_paragraph_title_neighbors",
+ "_demote_hanging_multiline_text_titles",
+ "_demote_visual_container_caption_titles",
+ "_demote_sentence_tail_titles",
+ "_document_title_fonts_compatible",
+ "_document_title_uses_page_fallback",
+]
diff --git a/mineru/model/flash/pdf/title_analysis/prototype.py b/mineru/model/flash/pdf/title_analysis/prototype.py
new file mode 100644
index 00000000..be5c41c1
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/prototype.py
@@ -0,0 +1,204 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""匹配标题原型的字体、尺度和对齐特征。"""
+
+from __future__ import annotations
+
+import statistics
+from typing import Literal
+
+from .....types import BBox
+from ..geometry import _bbox_center_x
+from ..line_layout import (
+ _line_effective_height,
+ _normalized_font_family,
+)
+from ..models import (
+ _DocumentBodyProfile,
+ _DocumentTitleProfile,
+ _LineItem,
+ _TextLane,
+ _TitleStylePrototype,
+)
+
+
+def _title_profile_seed_matches_cluster(
+ seed: tuple[
+ str,
+ int,
+ float,
+ float | None,
+ Literal["left", "center"],
+ float,
+ int,
+ ],
+ cluster: list[
+ tuple[
+ str,
+ int,
+ float,
+ float | None,
+ Literal["left", "center"],
+ float,
+ int,
+ ]
+ ],
+) -> bool:
+ """判断标题种子是否与已有字体、尺度和对齐簇兼容。"""
+
+ reference = cluster[0]
+ median_ratio = statistics.median(item[2] for item in cluster)
+ median_anchor = statistics.median(item[5] for item in cluster)
+ weights = [item[3] for item in cluster if item[3] is not None]
+ weight_compatible = (
+ seed[3] is None
+ or not weights
+ or abs(seed[3] - statistics.median(weights)) < 100.0
+ or max(seed[3], statistics.median(weights)) < 1.15 * min(seed[3], statistics.median(weights))
+ )
+ return (
+ seed[0] == reference[0]
+ and seed[1] == reference[1]
+ and seed[4] == reference[4]
+ and abs(seed[2] - median_ratio) <= 0.1 * median_ratio
+ and abs(seed[5] - median_anchor) <= 0.12
+ and weight_compatible
+ )
+
+
+def _title_profile_alignment(
+ bbox: BBox,
+ lane: _TextLane,
+ body_height: float,
+) -> tuple[Literal["left", "center"], float] | None:
+ """返回标题行的栏内对齐模式及归一化锚点偏移。"""
+
+ lane_width = max(0.1, lane.right - lane.left)
+ center_offset = (_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) / lane_width
+ left_offset = (bbox[0] - lane.left) / lane_width
+ if abs(center_offset) <= 0.12 and bbox[2] - bbox[0] <= 0.85 * lane_width:
+ return "center", center_offset
+ if abs(bbox[0] - lane.left) <= 3.0 * body_height:
+ return "left", left_offset
+ return None
+
+
+def _matching_document_title_prototype(
+ line: _LineItem,
+ bbox: BBox,
+ lane: _TextLane,
+ document_body_profile: _DocumentBodyProfile | None,
+ document_title_profile: _DocumentTitleProfile | None,
+) -> _TitleStylePrototype | None:
+ """返回与当前行字体、字号、字重和栏内锚点兼容的最强标题原型。"""
+
+ if (
+ document_body_profile is None
+ or document_title_profile is None
+ or line.font_signature is None
+ or line.font_coverage < 0.75
+ ):
+ return None
+ font_family = _normalized_font_family(line.font_signature)
+ if font_family is None:
+ return None
+ height_ratio = _line_effective_height(line, bbox) / max(
+ 0.1,
+ document_body_profile.body_height,
+ )
+ candidates: list[_TitleStylePrototype] = []
+ for prototype in document_title_profile.prototypes:
+ if (
+ prototype.font_family != font_family
+ or prototype.font_flags != line.font_signature[1]
+ or abs(height_ratio - prototype.height_ratio) > 0.1 * prototype.height_ratio
+ ):
+ continue
+ if (
+ prototype.weight is not None
+ and line.dominant_font_weight is not None
+ and abs(prototype.weight - line.dominant_font_weight) >= 100.0
+ and max(prototype.weight, line.dominant_font_weight) >= 1.15 * min(prototype.weight, line.dominant_font_weight)
+ ):
+ continue
+ alignment = _title_profile_alignment(
+ bbox,
+ lane,
+ document_body_profile.body_height,
+ )
+ if alignment is None or alignment[0] != prototype.alignment or abs(alignment[1] - prototype.anchor_offset) > 0.15:
+ continue
+ candidates.append(prototype)
+ return max(
+ candidates,
+ key=lambda item: (item.support_pages, item.support_count),
+ default=None,
+ )
+
+
+def _line_conflicts_document_title_profile(
+ line: _LineItem,
+ bbox: BBox,
+ lane: _TextLane,
+ document_body_profile: _DocumentBodyProfile | None,
+ document_title_profile: _DocumentTitleProfile | None,
+) -> bool:
+ """识别字体与标题原型一致、但字号明显落入正文带的弱标题候选。"""
+
+ if (
+ document_body_profile is None
+ or document_title_profile is None
+ or line.font_signature is None
+ or line.font_coverage < 0.75
+ ):
+ return False
+ font_family = _normalized_font_family(line.font_signature)
+ alignment = _title_profile_alignment(
+ bbox,
+ lane,
+ document_body_profile.body_height,
+ )
+ if font_family is None or alignment is None:
+ return False
+ height_ratio = _line_effective_height(line, bbox) / max(
+ 0.1,
+ document_body_profile.body_height,
+ )
+ for prototype in document_title_profile.prototypes:
+ if (
+ not _title_font_families_compatible(
+ prototype.font_family,
+ font_family,
+ )
+ or prototype.font_flags != line.font_signature[1]
+ or prototype.alignment != alignment[0]
+ or abs(prototype.anchor_offset - alignment[1]) > 0.15
+ ):
+ continue
+ if (
+ prototype.weight is not None
+ and line.dominant_font_weight is not None
+ and abs(prototype.weight - line.dominant_font_weight) >= 100.0
+ and max(prototype.weight, line.dominant_font_weight) >= 1.15 * min(prototype.weight, line.dominant_font_weight)
+ ):
+ continue
+ if abs(height_ratio - prototype.height_ratio) > 0.15 * prototype.height_ratio:
+ return True
+ return False
+
+
+def _title_font_families_compatible(first: str, second: str) -> bool:
+ """忽略已由 flags 和字重单独约束的常见字体样式后缀。"""
+
+ if first == second:
+ return True
+ style_suffixes = (",bold", "bold", ",regular", "regular", ",medium", "medium")
+ return any(first.removesuffix(suffix) == second or second.removesuffix(suffix) == first for suffix in style_suffixes)
+
+
+__all__ = [
+ "_title_profile_seed_matches_cluster",
+ "_title_profile_alignment",
+ "_matching_document_title_prototype",
+ "_line_conflicts_document_title_profile",
+ "_title_font_families_compatible",
+]
diff --git a/mineru/model/flash/pdf/title_analysis/structural.py b/mineru/model/flash/pdf/title_analysis/structural.py
new file mode 100644
index 00000000..f7a1577b
--- /dev/null
+++ b/mineru/model/flash/pdf/title_analysis/structural.py
@@ -0,0 +1,1088 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""识别编号、排版重置及跨页一致的结构标题。"""
+
+from __future__ import annotations
+
+import re
+import statistics
+import unicodedata
+from collections import Counter
+from dataclasses import replace
+
+from .....types import BBox
+from ..geometry import _bbox_axis_overlap_ratio, _bbox_center_x, _bbox_center_y, _bbox_union_many, _rotate_bbox_to_upright
+from ..line_layout import (
+ _effective_text_row_gap,
+ _estimate_lane_gap,
+ _font_signatures_share_family,
+ _infer_text_lanes,
+ _line_canonical_style_scale,
+ _line_effective_height,
+ _normalized_font_family,
+ _title_fonts_compatible,
+)
+from ..models import (
+ _DocumentBodyProfile,
+ _DocumentTitleProfile,
+ _LineItem,
+ _PreparedPage,
+ _TextLane,
+)
+from .body_profile import _line_uses_document_regular_font
+from .common import (
+ _NUMBERED_SECTION_TITLE_RE,
+ _SECTION_NUMBER_ONLY_RE,
+ _SECTION_TITLE_TERMINAL_RE,
+ _UNNUMBERED_SECTION_HEADING_RE,
+ _build_physical_title_gap_map,
+ _line_inside_visual_container,
+)
+from .page_titles import _classify_page_titles
+
+
+def _normalized_section_title_text(text: str) -> str:
+ """规范全半角编号和空白,仅用于结构标题规则判断。"""
+
+ return re.sub(
+ r"\s+",
+ " ",
+ unicodedata.normalize("NFKC", text),
+ ).strip()
+
+
+def _is_plausible_section_number(
+ number: str,
+ label: str = "",
+) -> bool:
+ """排除年代、小数值和整句正文冒充的章节编号。"""
+
+ parts = [int(part) for part in re.findall(r"\d+", number)]
+ if not parts or any(part > 99 for part in parts):
+ return False
+ if len(parts) > 1 and parts[0] == 0:
+ return False
+ if len(parts) == 1 and parts[0] > 12:
+ return False
+ stripped_label = label.lstrip()
+ if stripped_label and not stripped_label[0].isalpha():
+ return False
+ if stripped_label and stripped_label[0].isascii() and stripped_label[0].isalpha() and not stripped_label[0].isupper():
+ return False
+ if len(re.findall(r"\d+(?:\.\d+)?", label)) >= 2:
+ return False
+ return not any(char in label for char in ",,;;::。!?!?")
+
+
+def _section_title_has_body_followers(
+ title_bbox: BBox,
+ geometry: list[tuple[_LineItem, BBox]],
+ body_height: float,
+ local_page_width: float,
+ *,
+ minimum_count: int,
+) -> bool:
+ """检查紧随标题的同栏常规正文行,避免把页码和数值标成标题。"""
+
+ followers = 0
+ for line, bbox in sorted(
+ geometry,
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ ):
+ if bbox[1] <= title_bbox[1] + 0.4 * body_height:
+ continue
+ if bbox[1] - title_bbox[3] > 8.0 * body_height:
+ break
+ line_height = _line_effective_height(line, bbox)
+ horizontally_related = (
+ _bbox_axis_overlap_ratio(title_bbox, bbox, axis="x") >= 0.15 or abs(bbox[0] - title_bbox[0]) <= 2.5 * body_height
+ )
+ if (
+ line.semantic_type is None
+ and horizontally_related
+ and bbox[2] - bbox[0] >= 0.25 * local_page_width
+ and 0.7 <= line_height / body_height <= 1.4
+ ):
+ followers += 1
+ if followers >= minimum_count:
+ return True
+ return False
+
+
+def _classify_explicit_section_titles(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ *,
+ container_bboxes: list[BBox],
+ document_body_profile: _DocumentBodyProfile | None,
+) -> None:
+ """以通用编号行和紧凑结构转折补齐正文同字号章节标题。"""
+
+ if document_body_profile is None or document_body_profile.body_height <= 0:
+ return
+ body_height = document_body_profile.body_height
+ for angle in sorted(
+ {
+ line.angle
+ for line in lines
+ if (line.semantic_type is None or line.explicit_section_title) and not line.title_suppressed
+ }
+ ):
+ geometry = sorted(
+ [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ angle,
+ ),
+ )
+ for line in lines
+ if line.angle == angle and line.semantic_type is None and not line.title_suppressed
+ ],
+ key=lambda item: (
+ item[1][1],
+ item[1][0],
+ item[0].source_index,
+ ),
+ )
+ if not geometry:
+ continue
+ 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]
+ local_containers = [
+ _rotate_bbox_to_upright(
+ bbox,
+ page_size,
+ angle,
+ )
+ for bbox in container_bboxes
+ ]
+ numbered_groups: list[list[tuple[_LineItem, BBox]]] = []
+ grouped_sources: set[int] = set()
+ for line, bbox in geometry:
+ normalized = _normalized_section_title_text(line.text)
+ numbered_match = _NUMBERED_SECTION_TITLE_RE.match(
+ normalized,
+ )
+ if numbered_match is not None and _is_plausible_section_number(
+ numbered_match.group("number"),
+ numbered_match.group("label"),
+ ):
+ numbered_groups.append([(line, bbox)])
+ grouped_sources.add(line.source_index)
+ continue
+ if _SECTION_NUMBER_ONLY_RE.match(normalized) is None or not _is_plausible_section_number(normalized):
+ continue
+ marker_height = _line_effective_height(line, bbox)
+ companions = [
+ (candidate, candidate_bbox)
+ for candidate, candidate_bbox in geometry
+ if candidate is not line
+ and candidate.source_index not in grouped_sources
+ and candidate_bbox[0] >= bbox[2]
+ and candidate_bbox[0] - bbox[2] <= 4.0 * max(body_height, marker_height)
+ and _bbox_axis_overlap_ratio(
+ bbox,
+ candidate_bbox,
+ axis="y",
+ )
+ >= 0.5
+ and candidate_bbox[2] - candidate_bbox[0] <= 0.55 * local_page_width
+ and _SECTION_TITLE_TERMINAL_RE.search(
+ _normalized_section_title_text(candidate.text),
+ )
+ is None
+ ]
+ if not companions:
+ continue
+ companion = min(
+ companions,
+ key=lambda item: (
+ item[1][0] - bbox[2],
+ item[1][1],
+ ),
+ )
+ numbered_groups.append([(line, bbox), companion])
+ grouped_sources.update({line.source_index, companion[0].source_index})
+
+ for group in numbered_groups:
+ title_bbox = _bbox_union_many(
+ [bbox for _line, bbox in group],
+ )
+ group_line_ids = {id(line) for line, _bbox in group}
+ preceding = [
+ previous_bbox
+ for previous_line, previous_bbox in geometry
+ if id(previous_line) not in group_line_ids
+ and previous_bbox[3] <= title_bbox[1]
+ and (
+ _bbox_axis_overlap_ratio(
+ previous_bbox,
+ title_bbox,
+ axis="x",
+ )
+ >= 0.15
+ or abs(previous_bbox[0] - title_bbox[0]) <= 2.5 * body_height
+ )
+ ]
+ gap_above = title_bbox[1] - max(previous_bbox[3] for previous_bbox in preceding) if preceding else body_height
+ if (
+ title_bbox[2] - title_bbox[0] > 0.7 * local_page_width
+ or not 0.1 * local_page_height <= _bbox_center_y(title_bbox) <= 0.93 * local_page_height
+ or any(
+ _bbox_axis_overlap_ratio(
+ title_bbox,
+ container_bbox,
+ axis="x",
+ )
+ >= 0.8
+ and _bbox_axis_overlap_ratio(
+ title_bbox,
+ container_bbox,
+ axis="y",
+ )
+ >= 0.8
+ for container_bbox in local_containers
+ )
+ or not _section_title_has_body_followers(
+ title_bbox,
+ geometry,
+ body_height,
+ local_page_width,
+ minimum_count=1,
+ )
+ or gap_above < 0.4 * body_height
+ ):
+ continue
+ for line, _bbox in group:
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+ line.explicit_section_title = True
+
+ for line, bbox in geometry:
+ if line.semantic_type is not None:
+ continue
+ normalized = _normalized_section_title_text(line.text)
+ canonical_heading = normalized.strip(
+ "[][]【】()()",
+ ).replace(" ", "")
+ if (
+ _UNNUMBERED_SECTION_HEADING_RE.fullmatch(
+ canonical_heading,
+ )
+ is None
+ or not 2 <= len(normalized) <= 24
+ or _SECTION_TITLE_TERMINAL_RE.search(normalized) is not None
+ or any(char in normalized for char in "[][]")
+ or bbox[2] - bbox[0] > 0.3 * local_page_width
+ or _bbox_center_y(bbox) < 0.35 * local_page_height
+ or not 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.4
+ or any(
+ _bbox_axis_overlap_ratio(
+ bbox,
+ container_bbox,
+ axis="x",
+ )
+ >= 0.8
+ and _bbox_axis_overlap_ratio(
+ bbox,
+ container_bbox,
+ axis="y",
+ )
+ >= 0.8
+ for container_bbox in local_containers
+ )
+ or not _section_title_has_body_followers(
+ bbox,
+ geometry,
+ body_height,
+ local_page_width,
+ minimum_count=2,
+ )
+ ):
+ continue
+ preceding = [
+ previous_bbox
+ for previous_line, previous_bbox in geometry
+ if previous_line is not line
+ and previous_bbox[3] <= bbox[1]
+ and (
+ _bbox_axis_overlap_ratio(
+ previous_bbox,
+ bbox,
+ axis="x",
+ )
+ >= 0.15
+ or abs(previous_bbox[0] - bbox[0]) <= 2.5 * body_height
+ )
+ ]
+ gap_above = bbox[1] - max(previous_bbox[3] for previous_bbox in preceding) if preceding else body_height
+ if gap_above >= 0.5 * body_height:
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+ line.explicit_section_title = True
+
+
+def _classify_document_structural_titles(
+ prepared_pages: list[_PreparedPage],
+ document_body_profile: _DocumentBodyProfile | None,
+ *,
+ legacy_body_profile: _DocumentBodyProfile | None,
+ document_title_profile: _DocumentTitleProfile | None,
+) -> None:
+ """用跨页稳定栏带和段前后转折补齐正文同字号标题。"""
+
+ if document_body_profile is None or not document_body_profile.has_style_scale_repairs:
+ return
+ probe_pages = [
+ replace(
+ prepared,
+ remaining_lines=[
+ replace(
+ line,
+ style_scale_repaired=True,
+ structural_title=False,
+ )
+ for line in prepared.remaining_lines
+ ],
+ )
+ for prepared in prepared_pages
+ ]
+ _classify_document_structural_title_candidates(
+ probe_pages,
+ document_body_profile,
+ )
+ canonical_candidate_sources = {
+ (page_index, line.source_index)
+ for page_index, prepared in enumerate(probe_pages)
+ for line in prepared.remaining_lines
+ if line.structural_title
+ }
+ legacy_title_sources = _collect_legacy_paragraph_title_sources(
+ prepared_pages,
+ legacy_body_profile,
+ document_title_profile,
+ )
+ body_height = max(0.1, document_body_profile.body_height)
+ canonical_style_candidate_pages: dict[
+ tuple[str, int, float, int],
+ list[int],
+ ] = {}
+ for page_index, prepared in enumerate(prepared_pages):
+ for line in prepared.remaining_lines:
+ line_key = (page_index, line.source_index)
+ if line_key not in canonical_candidate_sources:
+ continue
+ local_bbox = _rotate_bbox_to_upright(
+ line.source_bbox or line.bbox,
+ prepared.page_size,
+ line.angle,
+ )
+ layout_ratio = (local_bbox[3] - local_bbox[1]) / body_height
+ if (
+ line_key in legacy_title_sources
+ or layout_ratio >= 1.8
+ or not _line_uses_document_regular_font(
+ line,
+ document_body_profile,
+ )
+ ):
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+ if (
+ line_key not in legacy_title_sources
+ and layout_ratio >= 1.8
+ and (
+ style_key := _canonical_title_style_key(
+ line,
+ )
+ )
+ is not None
+ ):
+ canonical_style_candidate_pages.setdefault(
+ style_key,
+ [],
+ ).append(page_index)
+ canonical_style_prototypes = {
+ style_key
+ for style_key, page_indices in canonical_style_candidate_pages.items()
+ if len(set(page_indices)) >= 2 or max(Counter(page_indices).values(), default=0) >= 3
+ }
+ if canonical_style_prototypes:
+ for prepared in prepared_pages:
+ prepared.canonical_formula_geometry = True
+ for line in prepared.remaining_lines:
+ style_key = _canonical_title_style_key(line)
+ if style_key in canonical_style_prototypes:
+ line.style_scale_repaired = True
+
+
+def _promote_noninitial_document_title_band(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ *,
+ page_index: int,
+ container_bboxes: list[BBox],
+ document_body_profile: _DocumentBodyProfile | None,
+ title_candidate_source_indices: set[int],
+) -> None:
+ """把非首页中已确认且显著大于正文的最强段落标题带升为文档标题。"""
+
+ if page_index == 0 or document_body_profile is None:
+ return
+ body_height = max(0.1, document_body_profile.body_height)
+ page_candidates: list[
+ tuple[
+ tuple[float, float, int, float],
+ list[tuple[_LineItem, BBox]],
+ ]
+ ] = []
+ for angle in sorted(
+ {
+ line.angle
+ for line in lines
+ if line.source_index in title_candidate_source_indices
+ and line.semantic_type in {None, "paragraph_title"}
+ and not line.title_suppressed
+ }
+ ):
+ geometry = sorted(
+ [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ page_size,
+ angle,
+ ),
+ )
+ for line in lines
+ if line.angle == angle
+ and line.source_index in title_candidate_source_indices
+ and line.semantic_type in {None, "paragraph_title"}
+ and not line.title_suppressed
+ ],
+ key=lambda item: (
+ item[1][1],
+ item[1][0],
+ item[0].source_index,
+ ),
+ )
+ if not geometry:
+ continue
+ 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]
+ local_containers = [
+ _rotate_bbox_to_upright(
+ bbox,
+ page_size,
+ angle,
+ )
+ for bbox in container_bboxes
+ ]
+ for index, (line, bbox) in enumerate(geometry):
+ 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.25 * 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.2 * 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 _line_inside_visual_container(
+ candidate_bbox,
+ local_containers,
+ )
+ or not _title_fonts_compatible(
+ title_members[-1][0],
+ candidate_line,
+ )
+ ):
+ break
+ title_members.append(
+ (candidate_line, candidate_bbox),
+ )
+ cursor += 1
+
+ title_scales = [_line_effective_height(title_line, title_bbox) for title_line, title_bbox in title_members]
+ title_bbox = _bbox_union_many(
+ [member_bbox for _member_line, member_bbox in title_members],
+ )
+ page_candidates.append(
+ (
+ (
+ statistics.median(title_scales) / body_height,
+ sum(member_bbox[2] - member_bbox[0] for _member_line, member_bbox in title_members) / local_page_width,
+ len(title_members),
+ -_bbox_center_y(title_bbox) / local_page_height,
+ ),
+ title_members,
+ )
+ )
+
+ if not page_candidates:
+ return
+ _score, title_members = max(
+ page_candidates,
+ key=lambda item: item[0],
+ )
+ for title_line, _title_bbox in title_members:
+ title_line.semantic_type = "doc_title"
+
+
+def _canonical_title_style_key(
+ line: _LineItem,
+) -> tuple[str, int, float, int] | None:
+ """返回 canonical-only 标题向同样式正文传播时使用的稳定键。"""
+
+ if line.font_signature is None or line.em_height <= 0:
+ return None
+ font_family = _normalized_font_family(line.font_signature)
+ if font_family is None:
+ return None
+ return (
+ font_family,
+ line.font_signature[1],
+ round(line.em_height * 4.0) / 4.0,
+ line.angle,
+ )
+
+
+def _classify_document_structural_title_candidates(
+ prepared_pages: list[_PreparedPage],
+ document_body_profile: _DocumentBodyProfile,
+) -> None:
+ """在 canonical 行副本上收集所有满足结构转折的标题候选。"""
+
+ body_height = max(0.1, document_body_profile.body_height)
+ strong_candidates: list[tuple[int, _LineItem, tuple[str, int] | None, float]] = []
+ start_candidates: list[tuple[int, _LineItem, tuple[str, int] | None, float]] = []
+ accepted_anchor_positions: list[tuple[int, int, float, float]] = []
+ for page_index, prepared in enumerate(prepared_pages):
+ container_bboxes = [
+ block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
+ ]
+ for angle in sorted({line.angle for line in prepared.remaining_lines if line.semantic_type is None}):
+ geometry = sorted(
+ [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.source_bbox or line.bbox,
+ prepared.page_size,
+ angle,
+ ),
+ )
+ for line in prepared.remaining_lines
+ if line.angle == angle and line.semantic_type is None
+ ],
+ key=lambda item: (
+ item[1][1],
+ item[1][0],
+ item[0].source_index,
+ ),
+ )
+ if len(geometry) < 4:
+ 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]
+ median_height = statistics.median(_line_canonical_style_scale(line, bbox) for line, bbox in geometry)
+ lanes = _infer_text_lanes(
+ geometry,
+ local_page_width,
+ median_height,
+ )
+ physical_gaps = _build_physical_title_gap_map(geometry)
+ local_containers = [
+ _rotate_bbox_to_upright(
+ bbox,
+ prepared.page_size,
+ angle,
+ )
+ for bbox in container_bboxes
+ ]
+ for line, bbox in geometry:
+ if page_index == 0 and _bbox_center_y(bbox) < 0.64 * local_page_height:
+ continue
+ related_lanes = [
+ lane
+ for lane in lanes
+ if not lane.is_span
+ and len(lane.lines) >= 3
+ and lane.left - body_height <= _bbox_center_x(bbox) <= lane.right + body_height
+ ]
+ if not related_lanes:
+ continue
+ lane = max(
+ related_lanes,
+ key=lambda item: (
+ len(item.lines),
+ item.right - item.left,
+ ),
+ )
+ lane_width = max(0.1, lane.right - lane.left)
+ width_ratio = (bbox[2] - bbox[0]) / lane_width
+ style_ratio = _line_canonical_style_scale(line, bbox) / body_height
+ left_offset = (bbox[0] - lane.left) / body_height
+ regular_font = _line_uses_document_regular_font(
+ line,
+ document_body_profile,
+ )
+ if (
+ not 0.75 <= style_ratio <= 1.35
+ or width_ratio > 0.8
+ or left_offset > 0.75
+ or left_offset < (-0.75 if regular_font else -3.0)
+ or _line_inside_visual_container(
+ bbox,
+ local_containers,
+ )
+ ):
+ continue
+ followers = [
+ (other_line, other_bbox)
+ for other_line, other_bbox in geometry
+ if other_line is not line
+ and bbox[1] < other_bbox[1]
+ and other_bbox[1] - bbox[3] <= 3.0 * body_height
+ and lane.left - body_height <= other_bbox[0] <= lane.left + 3.5 * body_height
+ and other_bbox[2] - other_bbox[0] >= 0.4 * lane_width
+ ]
+ if not followers:
+ continue
+ gap_above, gap_below = physical_gaps.get(
+ line.source_index,
+ (None, None),
+ )
+ layout_ratio = (bbox[3] - bbox[1]) / body_height
+ if regular_font and layout_ratio < 1.3 and line.font_coverage < 0.75:
+ continue
+ standard_transition = (
+ gap_above is not None
+ and gap_below is not None
+ and gap_above >= 0.65 * body_height
+ and gap_below >= 0.35 * body_height
+ and (not regular_font or gap_below <= 1.5 * body_height)
+ )
+ low_coverage_wide_transition = (
+ gap_above is not None
+ and gap_below is not None
+ and gap_above >= 0.5 * body_height
+ and gap_below >= 0.45 * body_height
+ and gap_below <= 0.7 * body_height
+ and width_ratio >= 0.75
+ and line.font_coverage <= 0.7
+ and layout_ratio >= 1.8
+ )
+ if low_coverage_wide_transition and any(
+ anchor_page_index == page_index
+ and anchor_angle == angle
+ and abs(anchor_left - lane.left) <= body_height
+ and 0 < _bbox_center_y(bbox) - anchor_center_y <= 12.0 * body_height
+ for (
+ anchor_page_index,
+ anchor_angle,
+ anchor_left,
+ anchor_center_y,
+ ) in accepted_anchor_positions
+ ):
+ low_coverage_wide_transition = False
+ compact_regular_transition = (
+ gap_above is not None
+ and gap_below is not None
+ and gap_above >= 0.65 * body_height
+ and gap_below >= 0.15 * body_height
+ and width_ratio <= 0.45
+ and line.font_coverage >= 0.75
+ and layout_ratio <= 1.3
+ )
+ family_key = (
+ (
+ _normalized_font_family(line.font_signature),
+ line.font_signature[1],
+ )
+ if line.font_signature is not None
+ else None
+ )
+ if (
+ standard_transition
+ or low_coverage_wide_transition
+ or compact_regular_transition
+ or (gap_above is None and gap_below is not None and gap_below >= 0.6 * body_height and not regular_font)
+ ):
+ strong_candidates.append(
+ (
+ page_index,
+ line,
+ family_key,
+ layout_ratio,
+ ),
+ )
+ accepted_anchor_positions.append(
+ (
+ page_index,
+ angle,
+ lane.left,
+ _bbox_center_y(bbox),
+ )
+ )
+ continue
+ if (
+ gap_above is None
+ and bbox[1] <= 0.18 * local_page_height
+ and width_ratio <= 0.6
+ and (line.font_coverage >= 0.75 or (not regular_font and line.font_coverage >= 0.5))
+ ):
+ start_candidates.append(
+ (
+ page_index,
+ line,
+ family_key,
+ layout_ratio,
+ ),
+ )
+
+ for _page_index, line, _family_key, _layout_ratio in strong_candidates:
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+ strong_families_by_page = {
+ (page_index, family_key) for page_index, _line, family_key, _layout_ratio in strong_candidates if family_key is not None
+ }
+ for page_index, line, family_key, _layout_ratio in start_candidates:
+ if not _line_uses_document_regular_font(
+ line,
+ document_body_profile,
+ ) or (family_key is not None and (page_index, family_key) in strong_families_by_page):
+ line.semantic_type = "paragraph_title"
+ line.structural_title = True
+
+
+def _collect_legacy_paragraph_title_sources(
+ prepared_pages: list[_PreparedPage],
+ document_body_profile: _DocumentBodyProfile | None,
+ document_title_profile: _DocumentTitleProfile | None,
+) -> set[tuple[int, int]]:
+ """在行副本上使用 legacy 尺度收集原本成立的段落标题身份。"""
+
+ if document_body_profile is None:
+ return set()
+ legacy_profile = replace(
+ document_body_profile,
+ has_style_scale_repairs=False,
+ )
+ output: set[tuple[int, int]] = set()
+ for page_index, prepared in enumerate(prepared_pages):
+ probe_lines = [
+ replace(
+ line,
+ style_scale_repaired=False,
+ structural_title=False,
+ )
+ for line in prepared.remaining_lines
+ ]
+ container_bboxes = [
+ block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
+ ]
+ caption_container_bboxes = [block["bbox"] for block in prepared.fixed_blocks if block.get("type") in {"image", "code"}]
+ _classify_page_titles(
+ probe_lines,
+ prepared.page_size,
+ page_index=page_index,
+ container_bboxes=container_bboxes,
+ caption_container_bboxes=caption_container_bboxes,
+ document_body_profile=legacy_profile,
+ document_title_profile=document_title_profile,
+ )
+ output.update((page_index, line.source_index) for line in probe_lines if line.semantic_type == "paragraph_title")
+ return output
+
+
+def _classify_inline_typography_reset_titles(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ *,
+ container_bboxes: list[BBox],
+ document_body_profile: _DocumentBodyProfile | None,
+) -> None:
+ """用短段尾、字体切换和缩进正文识别行内结构标题。"""
+
+ if document_body_profile is None:
+ return
+ for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
+ line_geometry = [
+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
+ for line in lines
+ if line.angle == angle and line.semantic_type is None and not line.title_suppressed
+ ]
+ if len(line_geometry) < 3:
+ continue
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ lanes = _infer_text_lanes(
+ line_geometry,
+ local_page_width,
+ median_height,
+ )
+ local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
+ for lane in lanes:
+ 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)
+ for previous, current, following in zip(
+ rows,
+ rows[1:],
+ rows[2:],
+ ):
+ previous_line, previous_bbox = previous
+ current_line, current_bbox = current
+ following_line, following_bbox = following
+ if any(
+ line.semantic_type is not None
+ for line in (
+ previous_line,
+ current_line,
+ following_line,
+ )
+ ):
+ continue
+ if (
+ previous_line.font_signature is None
+ or current_line.font_signature is None
+ or following_line.font_signature is None
+ or previous_line.font_coverage < 0.65
+ or current_line.font_coverage < 0.65
+ or following_line.font_coverage < 0.65
+ ):
+ continue
+ if not _font_signatures_share_family(
+ previous_line.font_signature,
+ following_line.font_signature,
+ ) or _font_signatures_share_family(
+ current_line.font_signature,
+ previous_line.font_signature,
+ ):
+ continue
+ previous_height = _line_effective_height(*previous)
+ current_height = _line_effective_height(*current)
+ following_height = _line_effective_height(*following)
+ neighbor_height = statistics.median(
+ (previous_height, following_height),
+ )
+ pair_height = max(
+ previous_height,
+ current_height,
+ following_height,
+ )
+ previous_width = previous_bbox[2] - previous_bbox[0]
+ current_width = current_bbox[2] - current_bbox[0]
+ following_width = following_bbox[2] - following_bbox[0]
+ following_indent = following_bbox[0] - current_bbox[0]
+ if not (
+ previous_width <= 0.45 * lane_width
+ and 0.2 * lane_width <= current_width <= 0.65 * lane_width
+ and following_width >= 0.75 * lane_width
+ and abs(current_bbox[0] - lane.left) <= 0.75 * pair_height
+ and 0.75 * pair_height <= following_indent <= 3.0 * pair_height
+ and 0.85 <= current_height / max(0.1, neighbor_height) <= 1.15
+ and -0.25 * pair_height <= _effective_text_row_gap(previous, current) <= 0.5 * pair_height
+ and -0.25 * pair_height <= _effective_text_row_gap(current, following) <= 0.5 * pair_height
+ and not _line_inside_visual_container(
+ current_bbox,
+ local_container_bboxes,
+ )
+ ):
+ continue
+ current_line.semantic_type = "paragraph_title"
+ current_line.structural_title = True
+
+
+def _classify_body_height_section_titles(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ *,
+ container_bboxes: list[BBox],
+ document_body_profile: _DocumentBodyProfile | None,
+ page_index: int = 1,
+) -> None:
+ """用重复的短行加正文组结构识别与正文同字号的独立章节标题。"""
+
+ if document_body_profile is None:
+ return
+ body_height = document_body_profile.body_height
+ if body_height <= 0:
+ return
+
+ for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
+ line_geometry = sorted(
+ [
+ (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
+ for line in lines
+ if line.angle == angle and line.semantic_type is None and not line.title_suppressed
+ ],
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ if len(line_geometry) < 8:
+ continue
+ median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
+ 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,
+ )
+ lane_by_source: dict[int, _TextLane] = {}
+ regular_gaps: list[float] = []
+ for lane in lanes:
+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ regular_gap, _gap_mad = _estimate_lane_gap(lane)
+ regular_gaps.append(regular_gap)
+ for line, _bbox in lane.lines:
+ lane_by_source[line.source_index] = lane
+ if not lane_by_source:
+ continue
+
+ page_regular_gap = statistics.median(regular_gaps) if regular_gaps else 0.2 * body_height
+ physical_gaps = _build_physical_title_gap_map(line_geometry)
+ local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
+ candidates: list[tuple[_LineItem, BBox, _TextLane]] = []
+ for line, bbox in line_geometry:
+ lane = lane_by_source.get(line.source_index)
+ if lane is None:
+ continue
+ line_height = _line_effective_height(line, bbox)
+ lane_width = max(0.1, lane.right - lane.left)
+ if not 0.9 <= line_height / body_height <= 1.1:
+ continue
+ if bbox[2] - bbox[0] > 0.22 * lane_width:
+ continue
+ if abs(bbox[0] - lane.left) > 0.75 * body_height:
+ continue
+ if _line_inside_visual_container(bbox, local_container_bboxes):
+ continue
+
+ followers = _body_height_section_followers(
+ line,
+ bbox,
+ line_geometry,
+ lane_by_source,
+ body_height,
+ )
+ if len(followers) < 3:
+ continue
+ gap_above = physical_gaps.get(line.source_index, (None, None))[0]
+ if gap_above is not None and gap_above <= 0.25 * body_height:
+ continue
+ starts_body = gap_above is None and bbox[1] <= 0.2 * local_page_height
+ has_extra_gap = gap_above is not None and gap_above - page_regular_gap >= 0.75 * body_height
+ has_full_width_follower = any(
+ follower_bbox[2] - follower_bbox[0]
+ >= 0.75
+ * max(
+ 0.1,
+ lane_by_source[follower_line.source_index].right - lane_by_source[follower_line.source_index].left,
+ )
+ for follower_line, follower_bbox in followers
+ if follower_line.source_index in lane_by_source
+ )
+ if starts_body or has_extra_gap or has_full_width_follower:
+ candidates.append((line, bbox, lane))
+
+ for line, bbox, _lane in candidates:
+ compatible_count = sum(
+ 1
+ for peer_line, peer_bbox, _peer_lane in candidates
+ if abs(peer_bbox[0] - bbox[0]) <= body_height
+ and 0.9 <= _line_effective_height(peer_line, peer_bbox) / _line_effective_height(line, bbox) <= 1.1
+ and _title_fonts_compatible(line, peer_line)
+ )
+ if compatible_count >= 2:
+ # 只标记结构锚点本身,避免普通正文被标题邻行扩展再次吞入。
+ line.semantic_type = "paragraph_title"
+
+
+def _body_height_section_followers(
+ candidate_line: _LineItem,
+ candidate_bbox: BBox,
+ line_geometry: list[tuple[_LineItem, BBox]],
+ lane_by_source: dict[int, _TextLane],
+ body_height: float,
+) -> list[tuple[_LineItem, BBox]]:
+ """返回短标题后方同锚点、同正文尺度且行距稳定的前三行。"""
+
+ followers: list[tuple[_LineItem, BBox]] = []
+ previous_top = candidate_bbox[1]
+ for line, bbox in line_geometry:
+ if line is candidate_line or bbox[1] <= candidate_bbox[1] + 0.4 * body_height:
+ continue
+ if not (candidate_bbox[0] - 0.75 * body_height <= bbox[0] <= candidate_bbox[0] + 1.5 * body_height):
+ continue
+ top_pitch = bbox[1] - previous_top
+ if top_pitch < 0.5 * body_height:
+ continue
+ if top_pitch > 1.8 * body_height:
+ break
+ if not 0.9 <= _line_effective_height(line, bbox) / body_height <= 1.1:
+ break
+ if line.source_index not in lane_by_source:
+ break
+ followers.append((line, bbox))
+ previous_top = bbox[1]
+ if len(followers) == 3:
+ break
+ return followers
+
+
+__all__ = [
+ "_normalized_section_title_text",
+ "_is_plausible_section_number",
+ "_section_title_has_body_followers",
+ "_classify_explicit_section_titles",
+ "_classify_document_structural_titles",
+ "_promote_noninitial_document_title_band",
+ "_canonical_title_style_key",
+ "_classify_document_structural_title_candidates",
+ "_collect_legacy_paragraph_title_sources",
+ "_classify_inline_typography_reset_titles",
+ "_classify_body_height_section_titles",
+ "_body_height_section_followers",
+]
diff --git a/mineru/model/flash/pdf/titles.py b/mineru/model/flash/pdf/titles.py
index 124eaf12..1f902b7a 100644
--- a/mineru/model/flash/pdf/titles.py
+++ b/mineru/model/flash/pdf/titles.py
@@ -1,3447 +1,76 @@
# Copyright (c) Opendatalab. All rights reserved.
+"""保留既有入口的 Flash PDF 门面,内部实现按职责显式组织。"""
-"""基于排版差异分类文档标题和段落标题。"""
-
-from __future__ import annotations
-
-import re
-import statistics
-import unicodedata
-from collections import Counter
-from dataclasses import replace
-from typing import Literal
-
-
-from ....types import BBox
-from .inline.types import (
- PDF_FONT_FORCE_BOLD_FLAG,
- PDF_FONT_ITALIC_FLAG,
+from .title_analysis.body_profile import (
+ _infer_document_body_profile as _infer_document_body_profile,
+ _document_font_is_regular as _document_font_is_regular,
+ _infer_lane_body_profile as _infer_lane_body_profile,
+ _line_uses_document_regular_font as _line_uses_document_regular_font,
)
-
-from .models import (
- _DocumentBodyProfile,
- _DocumentTitleProfile,
- _LaneBodyProfile,
- _LineItem,
- _PreparedPage,
- _TextLane,
- _TitleStylePrototype,
+from .title_analysis.common import (
+ _NUMBERED_SECTION_TITLE_RE as _NUMBERED_SECTION_TITLE_RE,
+ _SECTION_NUMBER_ONLY_RE as _SECTION_NUMBER_ONLY_RE,
+ _SECTION_TITLE_TERMINAL_RE as _SECTION_TITLE_TERMINAL_RE,
+ _UNNUMBERED_SECTION_HEADING_RE as _UNNUMBERED_SECTION_HEADING_RE,
+ _build_physical_title_gap_map as _build_physical_title_gap_map,
+ _line_inside_visual_container as _line_inside_visual_container,
+ _line_near_visual_container as _line_near_visual_container,
)
-from .geometry import (
- _bbox_axis_overlap_ratio,
- _bbox_center_x,
- _bbox_center_y,
- _bbox_union_many,
- _rotate_bbox_to_upright,
+from .title_analysis.document_profile import _infer_document_title_profile as _infer_document_title_profile
+from .title_analysis.lane_titles import (
+ _classify_paragraph_titles_in_lane as _classify_paragraph_titles_in_lane,
+ _protect_front_matter_title_types as _protect_front_matter_title_types,
+ _visual_row_has_body_style_sibling as _visual_row_has_body_style_sibling,
+ _is_near_full_mixed_inline_row as _is_near_full_mixed_inline_row,
+ _continues_local_body_row as _continues_local_body_row,
+ _is_continuous_field_row as _is_continuous_field_row,
+ _is_full_width_inline_heading as _is_full_width_inline_heading,
+ _has_following_body_row as _has_following_body_row,
+ _has_following_compact_text_section as _has_following_compact_text_section,
+ _unify_visual_row_title_types as _unify_visual_row_title_types,
+ _infer_front_matter_boundary as _infer_front_matter_boundary,
+ _normalized_title_gap as _normalized_title_gap,
+ _expand_paragraph_title_neighbors as _expand_paragraph_title_neighbors,
)
-from .line_layout import (
- _effective_text_row_gap,
- _estimate_lane_gap,
- _font_signatures_share_family,
- _font_weights_conflict,
- _infer_text_lanes,
- _line_canonical_style_scale,
- _line_effective_height,
- _normalized_font_family,
- _should_connect_semantic_rows,
- _title_fonts_compatible,
+from .title_analysis.page_titles import (
+ _classify_page_titles as _classify_page_titles,
+ _demote_non_structural_anomaly_titles as _demote_non_structural_anomaly_titles,
+ _find_repeated_grid_title_suppressions as _find_repeated_grid_title_suppressions,
+ _find_container_visual_row_title_suppressions as _find_container_visual_row_title_suppressions,
+ _classify_document_title as _classify_document_title,
+ _expand_document_title_across_lanes as _expand_document_title_across_lanes,
+ _classify_additional_document_title_bands as _classify_additional_document_title_bands,
+ _classify_cross_lane_centered_section_titles as _classify_cross_lane_centered_section_titles,
+ _demote_cross_lane_body_continuation_titles as _demote_cross_lane_body_continuation_titles,
+ _classify_cross_lane_emphasized_section_titles as _classify_cross_lane_emphasized_section_titles,
+ _is_wide_leading_title_continuation as _is_wide_leading_title_continuation,
+ _expand_cross_lane_paragraph_title_neighbors as _expand_cross_lane_paragraph_title_neighbors,
+ _demote_hanging_multiline_text_titles as _demote_hanging_multiline_text_titles,
+ _demote_visual_container_caption_titles as _demote_visual_container_caption_titles,
+ _demote_sentence_tail_titles as _demote_sentence_tail_titles,
+ _document_title_fonts_compatible as _document_title_fonts_compatible,
+ _document_title_uses_page_fallback as _document_title_uses_page_fallback,
)
-
-
-_NUMBERED_SECTION_TITLE_RE = re.compile(
- r"^(?P<number>\d+(?:\s*\.\s*\d+)*)\s+(?P<label>\S.*)$",
+from .title_analysis.prototype import (
+ _title_profile_seed_matches_cluster as _title_profile_seed_matches_cluster,
+ _title_profile_alignment as _title_profile_alignment,
+ _matching_document_title_prototype as _matching_document_title_prototype,
+ _line_conflicts_document_title_profile as _line_conflicts_document_title_profile,
+ _title_font_families_compatible as _title_font_families_compatible,
)
-_SECTION_NUMBER_ONLY_RE = re.compile(
- r"^\d+(?:\s*\.\s*\d+)*\.?$",
+from .title_analysis.structural import (
+ _normalized_section_title_text as _normalized_section_title_text,
+ _is_plausible_section_number as _is_plausible_section_number,
+ _section_title_has_body_followers as _section_title_has_body_followers,
+ _classify_explicit_section_titles as _classify_explicit_section_titles,
+ _classify_document_structural_titles as _classify_document_structural_titles,
+ _promote_noninitial_document_title_band as _promote_noninitial_document_title_band,
+ _canonical_title_style_key as _canonical_title_style_key,
+ _classify_document_structural_title_candidates as _classify_document_structural_title_candidates,
+ _collect_legacy_paragraph_title_sources as _collect_legacy_paragraph_title_sources,
+ _classify_inline_typography_reset_titles as _classify_inline_typography_reset_titles,
+ _classify_body_height_section_titles as _classify_body_height_section_titles,
+ _body_height_section_followers as _body_height_section_followers,
)
-_SECTION_TITLE_TERMINAL_RE = re.compile(
- r"[.!?。!?::;;,,]$",
-)
-_UNNUMBERED_SECTION_HEADING_RE = re.compile(
- r"^(?:introduction|references?|bibliography|acknowledg(?:e)?ments?|引言|绪论|参考文献|参考资料)$",
- re.IGNORECASE,
-)
-
-
-def _normalized_section_title_text(text: str) -> str:
- """规范全半角编号和空白,仅用于结构标题规则判断。"""
-
- return re.sub(
- r"\s+",
- " ",
- unicodedata.normalize("NFKC", text),
- ).strip()
-
-
-def _is_plausible_section_number(
- number: str,
- label: str = "",
-) -> bool:
- """排除年代、小数值和整句正文冒充的章节编号。"""
-
- parts = [int(part) for part in re.findall(r"\d+", number)]
- if not parts or any(part > 99 for part in parts):
- return False
- if len(parts) > 1 and parts[0] == 0:
- return False
- if len(parts) == 1 and parts[0] > 12:
- return False
- stripped_label = label.lstrip()
- if stripped_label and not stripped_label[0].isalpha():
- return False
- if stripped_label and stripped_label[0].isascii() and stripped_label[0].isalpha() and not stripped_label[0].isupper():
- return False
- if len(re.findall(r"\d+(?:\.\d+)?", label)) >= 2:
- return False
- return not any(char in label for char in ",,;;::。!?!?")
-
-
-def _section_title_has_body_followers(
- title_bbox: BBox,
- geometry: list[tuple[_LineItem, BBox]],
- body_height: float,
- local_page_width: float,
- *,
- minimum_count: int,
-) -> bool:
- """检查紧随标题的同栏常规正文行,避免把页码和数值标成标题。"""
-
- followers = 0
- for line, bbox in sorted(
- geometry,
- key=lambda item: (item[1][1], item[1][0], item[0].source_index),
- ):
- if bbox[1] <= title_bbox[1] + 0.4 * body_height:
- continue
- if bbox[1] - title_bbox[3] > 8.0 * body_height:
- break
- line_height = _line_effective_height(line, bbox)
- horizontally_related = (
- _bbox_axis_overlap_ratio(title_bbox, bbox, axis="x") >= 0.15 or abs(bbox[0] - title_bbox[0]) <= 2.5 * body_height
- )
- if (
- line.semantic_type is None
- and horizontally_related
- and bbox[2] - bbox[0] >= 0.25 * local_page_width
- and 0.7 <= line_height / body_height <= 1.4
- ):
- followers += 1
- if followers >= minimum_count:
- return True
- return False
-
-
-def _classify_explicit_section_titles(
- lines: list[_LineItem],
- page_size: tuple[float, float],
- *,
- container_bboxes: list[BBox],
- document_body_profile: _DocumentBodyProfile | None,
-) -> None:
- """以通用编号行和紧凑结构转折补齐正文同字号章节标题。"""
-
- if document_body_profile is None or document_body_profile.body_height <= 0:
- return
- body_height = document_body_profile.body_height
- for angle in sorted(
- {
- line.angle
- for line in lines
- if (
- line.semantic_type is None
- or line.explicit_section_title
- )
- and not line.title_suppressed
- }
- ):
- geometry = sorted(
- [
- (
- line,
- _rotate_bbox_to_upright(
- line.bbox,
- page_size,
- angle,
- ),
- )
- for line in lines
- if line.angle == angle and line.semantic_type is None and not line.title_suppressed
- ],
- key=lambda item: (
- item[1][1],
- item[1][0],
- item[0].source_index,
- ),
- )
- if not geometry:
- continue
- 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]
- local_containers = [
- _rotate_bbox_to_upright(
- bbox,
- page_size,
- angle,
- )
- for bbox in container_bboxes
- ]
- numbered_groups: list[list[tuple[_LineItem, BBox]]] = []
- grouped_sources: set[int] = set()
- for line, bbox in geometry:
- normalized = _normalized_section_title_text(line.text)
- numbered_match = _NUMBERED_SECTION_TITLE_RE.match(
- normalized,
- )
- if numbered_match is not None and _is_plausible_section_number(
- numbered_match.group("number"),
- numbered_match.group("label"),
- ):
- numbered_groups.append([(line, bbox)])
- grouped_sources.add(line.source_index)
- continue
- if _SECTION_NUMBER_ONLY_RE.match(normalized) is None or not _is_plausible_section_number(normalized):
- continue
- marker_height = _line_effective_height(line, bbox)
- companions = [
- (candidate, candidate_bbox)
- for candidate, candidate_bbox in geometry
- if candidate is not line
- and candidate.source_index not in grouped_sources
- and candidate_bbox[0] >= bbox[2]
- and candidate_bbox[0] - bbox[2] <= 4.0 * max(body_height, marker_height)
- and _bbox_axis_overlap_ratio(
- bbox,
- candidate_bbox,
- axis="y",
- )
- >= 0.5
- and candidate_bbox[2] - candidate_bbox[0] <= 0.55 * local_page_width
- and _SECTION_TITLE_TERMINAL_RE.search(
- _normalized_section_title_text(candidate.text),
- )
- is None
- ]
- if not companions:
- continue
- companion = min(
- companions,
- key=lambda item: (
- item[1][0] - bbox[2],
- item[1][1],
- ),
- )
- numbered_groups.append([(line, bbox), companion])
- grouped_sources.update({line.source_index, companion[0].source_index})
-
- for group in numbered_groups:
- title_bbox = _bbox_union_many(
- [bbox for _line, bbox in group],
- )
- group_line_ids = {id(line) for line, _bbox in group}
- preceding = [
- previous_bbox
- for previous_line, previous_bbox in geometry
- if id(previous_line) not in group_line_ids
- and previous_bbox[3] <= title_bbox[1]
- and (
- _bbox_axis_overlap_ratio(
- previous_bbox,
- title_bbox,
- axis="x",
- )
- >= 0.15
- or abs(previous_bbox[0] - title_bbox[0]) <= 2.5 * body_height
- )
- ]
- gap_above = title_bbox[1] - max(previous_bbox[3] for previous_bbox in preceding) if preceding else body_height
- if (
- title_bbox[2] - title_bbox[0] > 0.7 * local_page_width
- or not 0.1 * local_page_height <= _bbox_center_y(title_bbox) <= 0.93 * local_page_height
- or any(
- _bbox_axis_overlap_ratio(
- title_bbox,
- container_bbox,
- axis="x",
- )
- >= 0.8
- and _bbox_axis_overlap_ratio(
- title_bbox,
- container_bbox,
- axis="y",
- )
- >= 0.8
- for container_bbox in local_containers
- )
- or not _section_title_has_body_followers(
- title_bbox,
- geometry,
- body_height,
- local_page_width,
- minimum_count=1,
- )
- or gap_above < 0.4 * body_height
- ):
- continue
- for line, _bbox in group:
- line.semantic_type = "paragraph_title"
- line.structural_title = True
- line.explicit_section_title = True
-
- for line, bbox in geometry:
- if line.semantic_type is not None:
- continue
- normalized = _normalized_section_title_text(line.text)
- canonical_heading = normalized.strip(
- "[][]【】()()",
- ).replace(" ", "")
- if (
- _UNNUMBERED_SECTION_HEADING_RE.fullmatch(
- canonical_heading,
- )
- is None
- or not 2 <= len(normalized) <= 24
- or _SECTION_TITLE_TERMINAL_RE.search(normalized) is not None
- or any(char in normalized for char in "[][]")
- or bbox[2] - bbox[0] > 0.3 * local_page_width
- or _bbox_center_y(bbox) < 0.35 * local_page_height
- or not 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.4
- or any(
- _bbox_axis_overlap_ratio(
- bbox,
- container_bbox,
- axis="x",
- )
- >= 0.8
- and _bbox_axis_overlap_ratio(
- bbox,
- container_bbox,
- axis="y",
- )
- >= 0.8
- for container_bbox in local_containers
- )
- or not _section_title_has_body_followers(
- bbox,
- geometry,
- body_height,
- local_page_width,
- minimum_count=2,
- )
- ):
- continue
- preceding = [
- previous_bbox
- for previous_line, previous_bbox in geometry
- if previous_line is not line
- and previous_bbox[3] <= bbox[1]
- and (
- _bbox_axis_overlap_ratio(
- previous_bbox,
- bbox,
- axis="x",
- )
- >= 0.15
- or abs(previous_bbox[0] - bbox[0]) <= 2.5 * body_height
- )
- ]
- gap_above = bbox[1] - max(previous_bbox[3] for previous_bbox in preceding) if preceding else body_height
- if gap_above >= 0.5 * body_height:
- line.semantic_type = "paragraph_title"
- line.structural_title = True
- line.explicit_section_title = True
-
-
-def _classify_page_titles(
- lines: list[_LineItem],
- page_size: tuple[float, float],
- *,
- page_index: int,
- container_bboxes: list[BBox],
- caption_container_bboxes: list[BBox] | None = None,
- document_body_profile: _DocumentBodyProfile | None = None,
- document_title_profile: _DocumentTitleProfile | None = None,
-) -> None:
- """只用页面几何与字体排版标注首页文档标题和各页段落标题。"""
-
- for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
- line_geometry = [
- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
- for line in lines
- if line.angle == angle
- and (
- line.semantic_type is None
- or line.explicit_section_title
- )
- and not line.title_suppressed
- ]
- if not line_geometry:
- continue
- median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
- 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)
- for lane in lanes:
- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
- physical_gaps = _build_physical_title_gap_map(line_geometry)
- grid_title_suppressions = _find_repeated_grid_title_suppressions(
- lanes,
- median_height,
- )
- local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
- grid_title_suppressions.update(
- _find_container_visual_row_title_suppressions(
- line_geometry,
- local_container_bboxes,
- median_height,
- )
- )
-
- document_title_bottom: float | None = None
- if page_index == 0:
- document_title_bottom = _classify_document_title(
- lanes,
- local_page_height,
- local_page_width,
- document_body_profile=document_body_profile,
- )
- document_title_bottom = _expand_document_title_across_lanes(
- line_geometry,
- local_page_width,
- local_page_height,
- document_title_bottom,
- )
- document_title_bottom = _classify_additional_document_title_bands(
- line_geometry,
- local_page_width,
- local_page_height,
- document_title_bottom,
- document_body_profile=document_body_profile,
- )
- preserve_front_matter_boundaries = _document_title_uses_page_fallback(
- lanes,
- document_body_profile=document_body_profile,
- )
-
- _classify_cross_lane_centered_section_titles(
- line_geometry,
- lanes,
- local_page_width,
- local_page_height,
- local_container_bboxes,
- page_index=page_index,
- document_title_bottom=document_title_bottom,
- )
- _classify_cross_lane_emphasized_section_titles(
- line_geometry,
- lanes,
- local_page_width,
- local_page_height,
- local_container_bboxes,
- document_title_bottom=document_title_bottom,
- document_body_profile=document_body_profile,
- )
-
- for lane in lanes:
- profile = _infer_lane_body_profile(lane)
- _classify_paragraph_titles_in_lane(
- lane,
- profile,
- local_page_width,
- local_page_height,
- local_container_bboxes,
- document_title_bottom=document_title_bottom,
- preserve_front_matter_boundaries=preserve_front_matter_boundaries,
- physical_gaps=physical_gaps,
- grid_title_suppressions=grid_title_suppressions,
- document_body_profile=document_body_profile,
- document_title_profile=document_title_profile,
- page_index=page_index,
- )
- _expand_cross_lane_paragraph_title_neighbors(
- line_geometry,
- )
- _demote_hanging_multiline_text_titles(
- lanes,
- document_body_profile,
- page_index=page_index,
- )
- _demote_cross_lane_body_continuation_titles(
- line_geometry,
- lanes,
- )
- _demote_visual_container_caption_titles(
- line_geometry,
- [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in (caption_container_bboxes or [])],
- )
- _demote_sentence_tail_titles(
- [
- (
- line,
- _rotate_bbox_to_upright(
- line.bbox,
- page_size,
- angle,
- ),
- )
- for line in lines
- if line.angle == angle and line.semantic_type in {None, "paragraph_title"} and not line.title_suppressed
- ],
- )
- if document_body_profile is not None and document_body_profile.has_style_scale_repairs:
- _demote_non_structural_anomaly_titles(line_geometry)
-
-
-def _demote_non_structural_anomaly_titles(
- line_geometry: list[tuple[_LineItem, BBox]],
-) -> None:
- """在 loose 高度异常文档中只保留预先通过结构转折校验的段落标题。"""
-
- for line, _bbox in line_geometry:
- if line.semantic_type == "paragraph_title" and not line.structural_title:
- line.semantic_type = None
-
-
-def _infer_document_body_profile(
- prepared_pages: list[_PreparedPage],
- *,
- use_canonical_scale: bool = False,
-) -> _DocumentBodyProfile | None:
- """按跨页覆盖和累计行宽推断全文正文行高及常规字体集合。"""
-
- samples: list[
- tuple[
- float,
- int,
- float,
- tuple[str, int] | None,
- float | None,
- ]
- ] = []
- for page_index, prepared in enumerate(prepared_pages):
- for line in prepared.remaining_lines:
- if line.semantic_type is not None:
- continue
- local_bbox = _rotate_bbox_to_upright(
- line.bbox,
- prepared.page_size,
- line.angle,
- )
- local_page_width = prepared.page_size[1] if line.angle in {90, 270} else prepared.page_size[0]
- height = (
- _line_canonical_style_scale(line, local_bbox)
- if use_canonical_scale
- else _line_effective_height(line, local_bbox)
- )
- normalized_width = max(0.0, local_bbox[2] - local_bbox[0]) / max(
- 0.1,
- local_page_width,
- )
- if height <= 0 or normalized_width <= 0:
- continue
- samples.append(
- (
- height,
- page_index,
- normalized_width,
- line.font_signature if line.font_coverage >= 0.75 else None,
- line.dominant_font_weight,
- )
- )
- if not samples:
- return None
-
- height_clusters: list[list[tuple[float, int, float]]] = []
- for height, page_index, normalized_width, _font, _weight in sorted(
- samples,
- key=lambda item: item[0],
- ):
- target = next(
- (
- cluster
- for cluster in height_clusters
- if abs(height - statistics.median(item[0] for item in cluster))
- <= 0.1 * statistics.median(item[0] for item in cluster)
- ),
- None,
- )
- if target is None:
- height_clusters.append([(height, page_index, normalized_width)])
- else:
- target.append((height, page_index, normalized_width))
- cross_page_clusters = [cluster for cluster in height_clusters if len({item[1] for item in cluster}) >= 2]
- eligible_clusters = cross_page_clusters or height_clusters
- body_cluster = max(
- eligible_clusters,
- key=lambda cluster: (
- sum(item[2] for item in cluster),
- len({item[1] for item in cluster}),
- len(cluster),
- ),
- )
- body_height = statistics.median(item[0] for item in body_cluster)
-
- body_weights = [
- weight
- for height, _page_index, _width, _font, weight in samples
- if weight is not None and 0.9 <= height / body_height <= 1.1
- ]
- body_weight = statistics.median(body_weights) if body_weights else None
-
- font_pages: dict[tuple[str, int], set[int]] = {}
- font_widths: dict[tuple[str, int], float] = {}
- font_weights: dict[tuple[str, int], list[float]] = {}
- for height, page_index, width, font, weight in samples:
- if font is None or not 0.9 <= height / body_height <= 1.1:
- continue
- # 常规字体支持必须来自正文高度带;跨页重复的大标题不能反向污染正文画像。
- font_pages.setdefault(font, set()).add(page_index)
- font_widths[font] = font_widths.get(font, 0.0) + width
- if weight is not None:
- font_weights.setdefault(font, []).append(weight)
-
- regular_fonts = frozenset(
- font
- for font, pages in font_pages.items()
- if len(pages) >= 3
- and font_widths.get(font, 0.0) >= 2.0
- and font_widths.get(font, 0.0) >= 0.75 * len(pages)
- and _document_font_is_regular(
- font,
- font_weights.get(font, []),
- body_weight,
- )
- )
- return _DocumentBodyProfile(
- body_height=max(0.1, body_height),
- body_weight=body_weight,
- regular_fonts=regular_fonts,
- has_style_scale_repairs=any(
- line.style_scale_repaired for prepared in prepared_pages for line in prepared.remaining_lines
- ),
- )
-
-
-def _classify_document_structural_titles(
- prepared_pages: list[_PreparedPage],
- document_body_profile: _DocumentBodyProfile | None,
- *,
- legacy_body_profile: _DocumentBodyProfile | None,
- document_title_profile: _DocumentTitleProfile | None,
-) -> None:
- """用跨页稳定栏带和段前后转折补齐正文同字号标题。"""
-
- if document_body_profile is None or not document_body_profile.has_style_scale_repairs:
- return
- probe_pages = [
- replace(
- prepared,
- remaining_lines=[
- replace(
- line,
- style_scale_repaired=True,
- structural_title=False,
- )
- for line in prepared.remaining_lines
- ],
- )
- for prepared in prepared_pages
- ]
- _classify_document_structural_title_candidates(
- probe_pages,
- document_body_profile,
- )
- canonical_candidate_sources = {
- (page_index, line.source_index)
- for page_index, prepared in enumerate(probe_pages)
- for line in prepared.remaining_lines
- if line.structural_title
- }
- legacy_title_sources = _collect_legacy_paragraph_title_sources(
- prepared_pages,
- legacy_body_profile,
- document_title_profile,
- )
- body_height = max(0.1, document_body_profile.body_height)
- canonical_style_candidate_pages: dict[
- tuple[str, int, float, int],
- list[int],
- ] = {}
- for page_index, prepared in enumerate(prepared_pages):
- for line in prepared.remaining_lines:
- line_key = (page_index, line.source_index)
- if line_key not in canonical_candidate_sources:
- continue
- local_bbox = _rotate_bbox_to_upright(
- line.source_bbox or line.bbox,
- prepared.page_size,
- line.angle,
- )
- layout_ratio = (local_bbox[3] - local_bbox[1]) / body_height
- if (
- line_key in legacy_title_sources
- or layout_ratio >= 1.8
- or not _line_uses_document_regular_font(
- line,
- document_body_profile,
- )
- ):
- line.semantic_type = "paragraph_title"
- line.structural_title = True
- if (
- line_key not in legacy_title_sources
- and layout_ratio >= 1.8
- and (
- style_key := _canonical_title_style_key(
- line,
- )
- )
- is not None
- ):
- canonical_style_candidate_pages.setdefault(
- style_key,
- [],
- ).append(page_index)
- canonical_style_prototypes = {
- style_key
- for style_key, page_indices in canonical_style_candidate_pages.items()
- if len(set(page_indices)) >= 2 or max(Counter(page_indices).values(), default=0) >= 3
- }
- if canonical_style_prototypes:
- for prepared in prepared_pages:
- prepared.canonical_formula_geometry = True
- for line in prepared.remaining_lines:
- style_key = _canonical_title_style_key(line)
- if style_key in canonical_style_prototypes:
- line.style_scale_repaired = True
-
-
-def _promote_noninitial_document_title_band(
- lines: list[_LineItem],
- page_size: tuple[float, float],
- *,
- page_index: int,
- container_bboxes: list[BBox],
- document_body_profile: _DocumentBodyProfile | None,
- title_candidate_source_indices: set[int],
-) -> None:
- """把非首页中已确认且显著大于正文的最强段落标题带升为文档标题。"""
-
- if page_index == 0 or document_body_profile is None:
- return
- body_height = max(0.1, document_body_profile.body_height)
- page_candidates: list[
- tuple[
- tuple[float, float, int, float],
- list[tuple[_LineItem, BBox]],
- ]
- ] = []
- for angle in sorted(
- {
- line.angle
- for line in lines
- if line.source_index in title_candidate_source_indices
- and line.semantic_type in {None, "paragraph_title"}
- and not line.title_suppressed
- }
- ):
- geometry = sorted(
- [
- (
- line,
- _rotate_bbox_to_upright(
- line.bbox,
- page_size,
- angle,
- ),
- )
- for line in lines
- if line.angle == angle
- and line.source_index in title_candidate_source_indices
- and line.semantic_type in {None, "paragraph_title"}
- and not line.title_suppressed
- ],
- key=lambda item: (
- item[1][1],
- item[1][0],
- item[0].source_index,
- ),
- )
- if not geometry:
- continue
- 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]
- local_containers = [
- _rotate_bbox_to_upright(
- bbox,
- page_size,
- angle,
- )
- for bbox in container_bboxes
- ]
- for index, (line, bbox) in enumerate(geometry):
- 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.25 * 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.2 * 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 _line_inside_visual_container(
- candidate_bbox,
- local_containers,
- )
- or not _title_fonts_compatible(
- title_members[-1][0],
- candidate_line,
- )
- ):
- break
- title_members.append(
- (candidate_line, candidate_bbox),
- )
- cursor += 1
-
- title_scales = [
- _line_effective_height(title_line, title_bbox)
- for title_line, title_bbox in title_members
- ]
- title_bbox = _bbox_union_many(
- [member_bbox for _member_line, member_bbox in title_members],
- )
- page_candidates.append(
- (
- (
- statistics.median(title_scales) / body_height,
- sum(member_bbox[2] - member_bbox[0] for _member_line, member_bbox in title_members)
- / local_page_width,
- len(title_members),
- -_bbox_center_y(title_bbox) / local_page_height,
- ),
- title_members,
- )
- )
-
- if not page_candidates:
- return
- _score, title_members = max(
- page_candidates,
- key=lambda item: item[0],
- )
- for title_line, _title_bbox in title_members:
- title_line.semantic_type = "doc_title"
-
-
-def _canonical_title_style_key(
- line: _LineItem,
-) -> tuple[str, int, float, int] | None:
- """返回 canonical-only 标题向同样式正文传播时使用的稳定键。"""
-
- if line.font_signature is None or line.em_height <= 0:
- return None
- font_family = _normalized_font_family(line.font_signature)
- if font_family is None:
- return None
- return (
- font_family,
- line.font_signature[1],
- round(line.em_height * 4.0) / 4.0,
- line.angle,
- )
-
-
-def _classify_document_structural_title_candidates(
- prepared_pages: list[_PreparedPage],
- document_body_profile: _DocumentBodyProfile,
-) -> None:
- """在 canonical 行副本上收集所有满足结构转折的标题候选。"""
-
- body_height = max(0.1, document_body_profile.body_height)
- strong_candidates: list[tuple[int, _LineItem, tuple[str, int] | None, float]] = []
- start_candidates: list[tuple[int, _LineItem, tuple[str, int] | None, float]] = []
- accepted_anchor_positions: list[tuple[int, int, float, float]] = []
- for page_index, prepared in enumerate(prepared_pages):
- container_bboxes = [
- block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
- ]
- for angle in sorted({line.angle for line in prepared.remaining_lines if line.semantic_type is None}):
- geometry = sorted(
- [
- (
- line,
- _rotate_bbox_to_upright(
- line.source_bbox or line.bbox,
- prepared.page_size,
- angle,
- ),
- )
- for line in prepared.remaining_lines
- if line.angle == angle and line.semantic_type is None
- ],
- key=lambda item: (
- item[1][1],
- item[1][0],
- item[0].source_index,
- ),
- )
- if len(geometry) < 4:
- 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]
- median_height = statistics.median(_line_canonical_style_scale(line, bbox) for line, bbox in geometry)
- lanes = _infer_text_lanes(
- geometry,
- local_page_width,
- median_height,
- )
- physical_gaps = _build_physical_title_gap_map(geometry)
- local_containers = [
- _rotate_bbox_to_upright(
- bbox,
- prepared.page_size,
- angle,
- )
- for bbox in container_bboxes
- ]
- for line, bbox in geometry:
- if page_index == 0 and _bbox_center_y(bbox) < 0.64 * local_page_height:
- continue
- related_lanes = [
- lane
- for lane in lanes
- if not lane.is_span
- and len(lane.lines) >= 3
- and lane.left - body_height <= _bbox_center_x(bbox) <= lane.right + body_height
- ]
- if not related_lanes:
- continue
- lane = max(
- related_lanes,
- key=lambda item: (
- len(item.lines),
- item.right - item.left,
- ),
- )
- lane_width = max(0.1, lane.right - lane.left)
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- style_ratio = _line_canonical_style_scale(line, bbox) / body_height
- left_offset = (bbox[0] - lane.left) / body_height
- regular_font = _line_uses_document_regular_font(
- line,
- document_body_profile,
- )
- if (
- not 0.75 <= style_ratio <= 1.35
- or width_ratio > 0.8
- or left_offset > 0.75
- or left_offset < (-0.75 if regular_font else -3.0)
- or _line_inside_visual_container(
- bbox,
- local_containers,
- )
- ):
- continue
- followers = [
- (other_line, other_bbox)
- for other_line, other_bbox in geometry
- if other_line is not line
- and bbox[1] < other_bbox[1]
- and other_bbox[1] - bbox[3] <= 3.0 * body_height
- and lane.left - body_height <= other_bbox[0] <= lane.left + 3.5 * body_height
- and other_bbox[2] - other_bbox[0] >= 0.4 * lane_width
- ]
- if not followers:
- continue
- gap_above, gap_below = physical_gaps.get(
- line.source_index,
- (None, None),
- )
- layout_ratio = (bbox[3] - bbox[1]) / body_height
- if regular_font and layout_ratio < 1.3 and line.font_coverage < 0.75:
- continue
- standard_transition = (
- gap_above is not None
- and gap_below is not None
- and gap_above >= 0.65 * body_height
- and gap_below >= 0.35 * body_height
- and (not regular_font or gap_below <= 1.5 * body_height)
- )
- low_coverage_wide_transition = (
- gap_above is not None
- and gap_below is not None
- and gap_above >= 0.5 * body_height
- and gap_below >= 0.45 * body_height
- and gap_below <= 0.7 * body_height
- and width_ratio >= 0.75
- and line.font_coverage <= 0.7
- and layout_ratio >= 1.8
- )
- if low_coverage_wide_transition and any(
- anchor_page_index == page_index
- and anchor_angle == angle
- and abs(anchor_left - lane.left) <= body_height
- and 0 < _bbox_center_y(bbox) - anchor_center_y <= 12.0 * body_height
- for (
- anchor_page_index,
- anchor_angle,
- anchor_left,
- anchor_center_y,
- ) in accepted_anchor_positions
- ):
- low_coverage_wide_transition = False
- compact_regular_transition = (
- gap_above is not None
- and gap_below is not None
- and gap_above >= 0.65 * body_height
- and gap_below >= 0.15 * body_height
- and width_ratio <= 0.45
- and line.font_coverage >= 0.75
- and layout_ratio <= 1.3
- )
- family_key = (
- (
- _normalized_font_family(line.font_signature),
- line.font_signature[1],
- )
- if line.font_signature is not None
- else None
- )
- if (
- standard_transition
- or low_coverage_wide_transition
- or compact_regular_transition
- or (gap_above is None and gap_below is not None and gap_below >= 0.6 * body_height and not regular_font)
- ):
- strong_candidates.append(
- (
- page_index,
- line,
- family_key,
- layout_ratio,
- ),
- )
- accepted_anchor_positions.append(
- (
- page_index,
- angle,
- lane.left,
- _bbox_center_y(bbox),
- )
- )
- continue
- if (
- gap_above is None
- and bbox[1] <= 0.18 * local_page_height
- and width_ratio <= 0.6
- and (line.font_coverage >= 0.75 or (not regular_font and line.font_coverage >= 0.5))
- ):
- start_candidates.append(
- (
- page_index,
- line,
- family_key,
- layout_ratio,
- ),
- )
-
- for _page_index, line, _family_key, _layout_ratio in strong_candidates:
- line.semantic_type = "paragraph_title"
- line.structural_title = True
- strong_families_by_page = {
- (page_index, family_key) for page_index, _line, family_key, _layout_ratio in strong_candidates if family_key is not None
- }
- for page_index, line, family_key, _layout_ratio in start_candidates:
- if not _line_uses_document_regular_font(
- line,
- document_body_profile,
- ) or (family_key is not None and (page_index, family_key) in strong_families_by_page):
- line.semantic_type = "paragraph_title"
- line.structural_title = True
-
-
-def _collect_legacy_paragraph_title_sources(
- prepared_pages: list[_PreparedPage],
- document_body_profile: _DocumentBodyProfile | None,
- document_title_profile: _DocumentTitleProfile | None,
-) -> set[tuple[int, int]]:
- """在行副本上使用 legacy 尺度收集原本成立的段落标题身份。"""
-
- if document_body_profile is None:
- return set()
- legacy_profile = replace(
- document_body_profile,
- has_style_scale_repairs=False,
- )
- output: set[tuple[int, int]] = set()
- for page_index, prepared in enumerate(prepared_pages):
- probe_lines = [
- replace(
- line,
- style_scale_repaired=False,
- structural_title=False,
- )
- for line in prepared.remaining_lines
- ]
- container_bboxes = [
- block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
- ]
- caption_container_bboxes = [block["bbox"] for block in prepared.fixed_blocks if block.get("type") in {"image", "code"}]
- _classify_page_titles(
- probe_lines,
- prepared.page_size,
- page_index=page_index,
- container_bboxes=container_bboxes,
- caption_container_bboxes=caption_container_bboxes,
- document_body_profile=legacy_profile,
- document_title_profile=document_title_profile,
- )
- output.update((page_index, line.source_index) for line in probe_lines if line.semantic_type == "paragraph_title")
- return output
-
-
-def _classify_inline_typography_reset_titles(
- lines: list[_LineItem],
- page_size: tuple[float, float],
- *,
- container_bboxes: list[BBox],
- document_body_profile: _DocumentBodyProfile | None,
-) -> None:
- """用短段尾、字体切换和缩进正文识别行内结构标题。"""
-
- if document_body_profile is None:
- return
- for angle in sorted(
- {
- line.angle
- for line in lines
- if line.semantic_type is None and not line.title_suppressed
- }
- ):
- line_geometry = [
- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
- for line in lines
- if line.angle == angle
- and line.semantic_type is None
- and not line.title_suppressed
- ]
- if len(line_geometry) < 3:
- continue
- median_height = statistics.median(
- _line_effective_height(line, bbox)
- for line, bbox in line_geometry
- )
- local_page_width = (
- page_size[1] if angle in {90, 270} else page_size[0]
- )
- lanes = _infer_text_lanes(
- line_geometry,
- local_page_width,
- median_height,
- )
- local_container_bboxes = [
- _rotate_bbox_to_upright(bbox, page_size, angle)
- for bbox in container_bboxes
- ]
- for lane in lanes:
- 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)
- for previous, current, following in zip(
- rows,
- rows[1:],
- rows[2:],
- ):
- previous_line, previous_bbox = previous
- current_line, current_bbox = current
- following_line, following_bbox = following
- if any(
- line.semantic_type is not None
- for line in (
- previous_line,
- current_line,
- following_line,
- )
- ):
- continue
- if (
- previous_line.font_signature is None
- or current_line.font_signature is None
- or following_line.font_signature is None
- or previous_line.font_coverage < 0.65
- or current_line.font_coverage < 0.65
- or following_line.font_coverage < 0.65
- ):
- continue
- if not _font_signatures_share_family(
- previous_line.font_signature,
- following_line.font_signature,
- ) or _font_signatures_share_family(
- current_line.font_signature,
- previous_line.font_signature,
- ):
- continue
- previous_height = _line_effective_height(*previous)
- current_height = _line_effective_height(*current)
- following_height = _line_effective_height(*following)
- neighbor_height = statistics.median(
- (previous_height, following_height),
- )
- pair_height = max(
- previous_height,
- current_height,
- following_height,
- )
- previous_width = previous_bbox[2] - previous_bbox[0]
- current_width = current_bbox[2] - current_bbox[0]
- following_width = following_bbox[2] - following_bbox[0]
- following_indent = following_bbox[0] - current_bbox[0]
- if not (
- previous_width <= 0.45 * lane_width
- and 0.2 * lane_width
- <= current_width
- <= 0.65 * lane_width
- and following_width >= 0.75 * lane_width
- and abs(current_bbox[0] - lane.left)
- <= 0.75 * pair_height
- and 0.75 * pair_height
- <= following_indent
- <= 3.0 * pair_height
- and 0.85
- <= current_height / max(0.1, neighbor_height)
- <= 1.15
- and -0.25 * pair_height
- <= _effective_text_row_gap(previous, current)
- <= 0.5 * pair_height
- and -0.25 * pair_height
- <= _effective_text_row_gap(current, following)
- <= 0.5 * pair_height
- and not _line_inside_visual_container(
- current_bbox,
- local_container_bboxes,
- )
- ):
- continue
- current_line.semantic_type = "paragraph_title"
- current_line.structural_title = True
-
-
-def _classify_body_height_section_titles(
- lines: list[_LineItem],
- page_size: tuple[float, float],
- *,
- container_bboxes: list[BBox],
- document_body_profile: _DocumentBodyProfile | None,
- page_index: int = 1,
-) -> None:
- """用重复的短行加正文组结构识别与正文同字号的独立章节标题。"""
-
- if document_body_profile is None:
- return
- body_height = document_body_profile.body_height
- if body_height <= 0:
- return
-
- for angle in sorted({line.angle for line in lines if line.semantic_type is None and not line.title_suppressed}):
- line_geometry = sorted(
- [
- (line, _rotate_bbox_to_upright(line.bbox, page_size, angle))
- for line in lines
- if line.angle == angle and line.semantic_type is None and not line.title_suppressed
- ],
- key=lambda item: (item[1][1], item[1][0], item[0].source_index),
- )
- if len(line_geometry) < 8:
- continue
- median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in line_geometry)
- 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,
- )
- lane_by_source: dict[int, _TextLane] = {}
- regular_gaps: list[float] = []
- for lane in lanes:
- lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
- regular_gap, _gap_mad = _estimate_lane_gap(lane)
- regular_gaps.append(regular_gap)
- for line, _bbox in lane.lines:
- lane_by_source[line.source_index] = lane
- if not lane_by_source:
- continue
-
- page_regular_gap = statistics.median(regular_gaps) if regular_gaps else 0.2 * body_height
- physical_gaps = _build_physical_title_gap_map(line_geometry)
- local_container_bboxes = [_rotate_bbox_to_upright(bbox, page_size, angle) for bbox in container_bboxes]
- candidates: list[tuple[_LineItem, BBox, _TextLane]] = []
- for line, bbox in line_geometry:
- lane = lane_by_source.get(line.source_index)
- if lane is None:
- continue
- line_height = _line_effective_height(line, bbox)
- lane_width = max(0.1, lane.right - lane.left)
- if not 0.9 <= line_height / body_height <= 1.1:
- continue
- if bbox[2] - bbox[0] > 0.22 * lane_width:
- continue
- if abs(bbox[0] - lane.left) > 0.75 * body_height:
- continue
- if _line_inside_visual_container(bbox, local_container_bboxes):
- continue
-
- followers = _body_height_section_followers(
- line,
- bbox,
- line_geometry,
- lane_by_source,
- body_height,
- )
- if len(followers) < 3:
- continue
- gap_above = physical_gaps.get(line.source_index, (None, None))[0]
- if gap_above is not None and gap_above <= 0.25 * body_height:
- continue
- starts_body = gap_above is None and bbox[1] <= 0.2 * local_page_height
- has_extra_gap = gap_above is not None and gap_above - page_regular_gap >= 0.75 * body_height
- has_full_width_follower = any(
- follower_bbox[2] - follower_bbox[0]
- >= 0.75
- * max(
- 0.1,
- lane_by_source[follower_line.source_index].right - lane_by_source[follower_line.source_index].left,
- )
- for follower_line, follower_bbox in followers
- if follower_line.source_index in lane_by_source
- )
- if starts_body or has_extra_gap or has_full_width_follower:
- candidates.append((line, bbox, lane))
-
- for line, bbox, _lane in candidates:
- compatible_count = sum(
- 1
- for peer_line, peer_bbox, _peer_lane in candidates
- if abs(peer_bbox[0] - bbox[0]) <= body_height
- and 0.9 <= _line_effective_height(peer_line, peer_bbox) / _line_effective_height(line, bbox) <= 1.1
- and _title_fonts_compatible(line, peer_line)
- )
- if compatible_count >= 2:
- # 只标记结构锚点本身,避免普通正文被标题邻行扩展再次吞入。
- line.semantic_type = "paragraph_title"
-
-
-def _body_height_section_followers(
- candidate_line: _LineItem,
- candidate_bbox: BBox,
- line_geometry: list[tuple[_LineItem, BBox]],
- lane_by_source: dict[int, _TextLane],
- body_height: float,
-) -> list[tuple[_LineItem, BBox]]:
- """返回短标题后方同锚点、同正文尺度且行距稳定的前三行。"""
-
- followers: list[tuple[_LineItem, BBox]] = []
- previous_top = candidate_bbox[1]
- for line, bbox in line_geometry:
- if line is candidate_line or bbox[1] <= candidate_bbox[1] + 0.4 * body_height:
- continue
- if not (candidate_bbox[0] - 0.75 * body_height <= bbox[0] <= candidate_bbox[0] + 1.5 * body_height):
- continue
- top_pitch = bbox[1] - previous_top
- if top_pitch < 0.5 * body_height:
- continue
- if top_pitch > 1.8 * body_height:
- break
- if not 0.9 <= _line_effective_height(line, bbox) / body_height <= 1.1:
- break
- if line.source_index not in lane_by_source:
- break
- followers.append((line, bbox))
- previous_top = bbox[1]
- if len(followers) == 3:
- break
- return followers
-
-
-def _infer_document_title_profile(
- prepared_pages: list[_PreparedPage],
- document_body_profile: _DocumentBodyProfile | None,
-) -> _DocumentTitleProfile | None:
- """在副本上复用现有标题判定,并把跨页稳定样式聚成标题原型。"""
-
- if document_body_profile is None:
- return None
- seeds: list[
- tuple[
- str,
- int,
- float,
- float | None,
- Literal["left", "center"],
- float,
- int,
- ]
- ] = []
- for page_index, prepared in enumerate(prepared_pages):
- probe_lines = [replace(line) for line in prepared.remaining_lines]
- container_bboxes = [
- block["bbox"] for block in prepared.fixed_blocks if not isinstance(block.get("_inline_visual_row_id"), int)
- ]
- _classify_page_titles(
- probe_lines,
- prepared.page_size,
- page_index=page_index,
- container_bboxes=container_bboxes,
- document_body_profile=document_body_profile,
- )
- seen_rows: set[tuple[int, int]] = set()
- for angle in sorted({line.angle for line in probe_lines}):
- geometry = [
- (
- line,
- _rotate_bbox_to_upright(
- line.bbox,
- prepared.page_size,
- angle,
- ),
- )
- for line in probe_lines
- if line.angle == angle
- ]
- if not geometry:
- continue
- median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in geometry)
- local_page_width = prepared.page_size[1] if angle in {90, 270} else prepared.page_size[0]
- lanes = _infer_text_lanes(
- geometry,
- local_page_width,
- median_height,
- )
- local_container_bboxes = [
- _rotate_bbox_to_upright(
- bbox,
- prepared.page_size,
- angle,
- )
- for bbox in container_bboxes
- ]
- for lane in lanes:
- for line, bbox in lane.lines:
- line_height_ratio = _line_effective_height(line, bbox) / document_body_profile.body_height
- large_unresolved_seed = (
- page_index > 0
- and line.semantic_type is None
- and line_height_ratio >= 1.3
- and bbox[2] - bbox[0] <= 0.8 * local_page_width
- and not _line_inside_visual_container(
- bbox,
- local_container_bboxes,
- )
- )
- if (
- (line.semantic_type != "paragraph_title" and not large_unresolved_seed)
- or line.font_signature is None
- or line.font_coverage < 0.75
- ):
- continue
- row_identity = line.visual_row_id if line.visual_row_id is not None else line.source_index
- row_key = (angle, row_identity)
- if row_key in seen_rows:
- continue
- alignment = _title_profile_alignment(
- bbox,
- lane,
- document_body_profile.body_height,
- )
- if alignment is None:
- continue
- font_family = _normalized_font_family(line.font_signature)
- if font_family is None:
- continue
- mode, anchor_offset = alignment
- seeds.append(
- (
- font_family,
- line.font_signature[1],
- line_height_ratio,
- line.dominant_font_weight,
- mode,
- anchor_offset,
- page_index,
- )
- )
- seen_rows.add(row_key)
-
- clusters: list[list[tuple[str, int, float, float | None, Literal["left", "center"], float, int]]] = []
- for seed in sorted(seeds, key=lambda item: (item[0], item[1], item[4], item[2])):
- target = next(
- (cluster for cluster in clusters if _title_profile_seed_matches_cluster(seed, cluster)),
- None,
- )
- if target is None:
- clusters.append([seed])
- else:
- target.append(seed)
-
- prototypes: list[_TitleStylePrototype] = []
- for cluster in clusters:
- support_pages = len({seed[6] for seed in cluster})
- if len(cluster) < 3 and support_pages < 2:
- continue
- weights = [seed[3] for seed in cluster if seed[3] is not None]
- prototypes.append(
- _TitleStylePrototype(
- font_family=cluster[0][0],
- font_flags=cluster[0][1],
- height_ratio=statistics.median(seed[2] for seed in cluster),
- weight=statistics.median(weights) if weights else None,
- alignment=cluster[0][4],
- anchor_offset=statistics.median(seed[5] for seed in cluster),
- support_count=len(cluster),
- support_pages=support_pages,
- )
- )
- if not prototypes:
- return None
- prototypes.sort(
- key=lambda item: (item.support_pages, item.support_count),
- reverse=True,
- )
- return _DocumentTitleProfile(tuple(prototypes))
-
-
-def _title_profile_seed_matches_cluster(
- seed: tuple[
- str,
- int,
- float,
- float | None,
- Literal["left", "center"],
- float,
- int,
- ],
- cluster: list[
- tuple[
- str,
- int,
- float,
- float | None,
- Literal["left", "center"],
- float,
- int,
- ]
- ],
-) -> bool:
- """判断标题种子是否与已有字体、尺度和对齐簇兼容。"""
-
- reference = cluster[0]
- median_ratio = statistics.median(item[2] for item in cluster)
- median_anchor = statistics.median(item[5] for item in cluster)
- weights = [item[3] for item in cluster if item[3] is not None]
- weight_compatible = (
- seed[3] is None
- or not weights
- or abs(seed[3] - statistics.median(weights)) < 100.0
- or max(seed[3], statistics.median(weights)) < 1.15 * min(seed[3], statistics.median(weights))
- )
- return (
- seed[0] == reference[0]
- and seed[1] == reference[1]
- and seed[4] == reference[4]
- and abs(seed[2] - median_ratio) <= 0.1 * median_ratio
- and abs(seed[5] - median_anchor) <= 0.12
- and weight_compatible
- )
-
-
-def _title_profile_alignment(
- bbox: BBox,
- lane: _TextLane,
- body_height: float,
-) -> tuple[Literal["left", "center"], float] | None:
- """返回标题行的栏内对齐模式及归一化锚点偏移。"""
-
- lane_width = max(0.1, lane.right - lane.left)
- center_offset = (_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) / lane_width
- left_offset = (bbox[0] - lane.left) / lane_width
- if abs(center_offset) <= 0.12 and bbox[2] - bbox[0] <= 0.85 * lane_width:
- return "center", center_offset
- if abs(bbox[0] - lane.left) <= 3.0 * body_height:
- return "left", left_offset
- return None
-
-
-def _document_font_is_regular(
- font: tuple[str, int],
- weights: list[float],
- body_weight: float | None,
-) -> bool:
- """用字体样式位和全文正文基准过滤斜体、粗体等强调字体。"""
-
- if font[1] & (PDF_FONT_ITALIC_FLAG | PDF_FONT_FORCE_BOLD_FLAG):
- return False
- if not weights or body_weight is None:
- return True
- median_weight = statistics.median(weights)
- return median_weight < max(body_weight + 100.0, 1.15 * body_weight)
-
-
-def _build_physical_title_gap_map(
- line_geometry: list[tuple[_LineItem, BBox]],
-) -> dict[int, tuple[float | None, float | None]]:
- """为每行记录同方向且水平投影相交的最近上、下物理行净空。"""
-
- output: dict[int, tuple[float | None, float | None]] = {}
- for line, bbox in line_geometry:
- line_center = _bbox_center_y(bbox)
- above_gaps: list[float] = []
- below_gaps: list[float] = []
- for other_line, other_bbox in line_geometry:
- if other_line is line:
- continue
- if _bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") < 0.1:
- # 双栏同高度正文并非当前行的物理上下文,不能抹掉真实标题留白。
- continue
- if line.visual_row_id is not None and other_line.visual_row_id == line.visual_row_id:
- continue
- other_center = _bbox_center_y(other_bbox)
- if other_center < line_center:
- above_gaps.append(
- max(
- 0.0,
- _effective_text_row_gap(
- (other_line, other_bbox),
- (line, bbox),
- ),
- )
- )
- elif other_center > line_center:
- below_gaps.append(
- max(
- 0.0,
- _effective_text_row_gap(
- (line, bbox),
- (other_line, other_bbox),
- ),
- )
- )
- output[line.source_index] = (
- min(above_gaps) if above_gaps else None,
- min(below_gaps) if below_gaps else None,
- )
- return output
-
-
-def _find_repeated_grid_title_suppressions(
- lanes: list[_TextLane],
- median_height: float,
-) -> set[int]:
- """识别重复双栏信息网格中的短首行,避免把城市等记录头标成标题。"""
-
- candidates: list[tuple[int, int, float]] = []
- for lane_index, lane in enumerate(lanes):
- if lane.is_span:
- continue
- lane_width = max(0.1, lane.right - lane.left)
- for row_index, (line, bbox) in enumerate(lane.lines[:-1]):
- next_line, next_bbox = lane.lines[row_index + 1]
- width = bbox[2] - bbox[0]
- next_width = next_bbox[2] - next_bbox[0]
- gap = _effective_text_row_gap(
- (line, bbox),
- (next_line, next_bbox),
- )
- if (
- line.semantic_type is not None
- or next_line.semantic_type is not None
- or width > 0.35 * lane_width
- or next_width < max(0.6 * lane_width, 1.8 * width)
- or abs(next_bbox[0] - bbox[0]) > 0.75 * median_height
- or not -0.25 * median_height <= gap <= 0.75 * median_height
- ):
- continue
- candidates.append((lane_index, line.source_index, _bbox_center_y(bbox)))
-
- bands: list[list[tuple[int, int, float]]] = []
- for candidate in sorted(candidates, key=lambda item: item[2]):
- target = next(
- (band for band in bands if abs(candidate[2] - statistics.median(item[2] for item in band)) <= 0.5 * median_height),
- None,
- )
- if target is None:
- bands.append([candidate])
- else:
- target.append(candidate)
- paired_bands = [
- {source_index for _lane_index, source_index, _center_y in band}
- for band in bands
- if len({lane_index for lane_index, _source_index, _center_y in band}) >= 2
- ]
- if len(paired_bands) < 2:
- return set()
- return set().union(*paired_bands)
-
-
-def _find_container_visual_row_title_suppressions(
- line_geometry: list[tuple[_LineItem, BBox]],
- container_bboxes: list[BBox],
- median_height: float,
-) -> set[int]:
- """用完整视觉行与图表容器的邻接关系抑制拆分 caption 标题误报。"""
-
- visual_rows: dict[int, list[tuple[_LineItem, BBox]]] = {}
- for item in line_geometry:
- row_id = item[0].visual_row_id
- if row_id is not None:
- visual_rows.setdefault(row_id, []).append(item)
- suppressed: set[int] = set()
- for members in visual_rows.values():
- if len(members) < 2:
- continue
- row_bbox = _bbox_union_many([bbox for _line, bbox in members])
- if any(
- _bbox_axis_overlap_ratio(row_bbox, container_bbox, axis="x") >= 0.35
- and max(
- row_bbox[1] - container_bbox[3],
- container_bbox[1] - row_bbox[3],
- 0.0,
- )
- <= 1.5 * median_height
- for container_bbox in container_bboxes
- ):
- suppressed.update(line.source_index for line, _bbox in members)
- return suppressed
-
-
-def _infer_lane_body_profile(lane: _TextLane) -> _LaneBodyProfile:
- """从栏带的长行主体估计正文行高、主字体、字重、常规行距和样式占比。"""
-
- available = [item for item in lane.lines if item[0].semantic_type is None]
- if not available:
- return _LaneBodyProfile(1.0, None, None, 0.35, {})
- lane_width = max(0.1, lane.right - lane.left)
- long_lines = [item for item in available if item[1][2] - item[1][0] >= 0.45 * lane_width]
- body_rows = long_lines or available
- body_line_ids = {id(line) for line, _bbox in body_rows}
- body_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in body_rows)
-
- font_support: dict[tuple[str, int], float] = {}
- style_support: dict[tuple[str, int], float] = {}
- total_style_width = 0.0
- for line, bbox in available:
- if line.font_signature is None or line.font_coverage < 0.75:
- continue
- line_width = max(0.1, bbox[2] - bbox[0])
- style_support[line.font_signature] = style_support.get(line.font_signature, 0.0) + line_width
- total_style_width += line_width
- if id(line) in body_line_ids and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35:
- font_support[line.font_signature] = font_support.get(line.font_signature, 0.0) + line_width
- body_font = max(font_support, key=font_support.get) if font_support else None
- if total_style_width > 0:
- style_support = {signature: width / total_style_width for signature, width in style_support.items()}
-
- body_weights = [
- line.dominant_font_weight
- for line, bbox in body_rows
- if line.dominant_font_weight is not None
- and (body_font is None or line.font_signature == body_font)
- and 0.75 <= _line_effective_height(line, bbox) / body_height <= 1.35
- ]
- regular_gap, _gap_mad = _estimate_lane_gap(lane)
- return _LaneBodyProfile(
- body_height=max(0.1, body_height),
- body_font=body_font,
- body_weight=statistics.median(body_weights) if body_weights else None,
- regular_gap=regular_gap,
- style_support=style_support,
- body_row_count=len(body_rows),
- )
-
-
-def _classify_document_title(
- lanes: list[_TextLane],
- local_page_height: float,
- local_page_width: float,
- *,
- document_body_profile: _DocumentBodyProfile | None = None,
-) -> float | None:
- """从首页上部选取显著大字号锚点,并用同版式邻行扩展多行文档标题。"""
-
- candidates: list[tuple[float, _TextLane, int, tuple[_LineItem, BBox]]] = []
- lane_profiles = [(lane, _infer_lane_body_profile(lane)) for lane in lanes]
- column_body_heights = [profile.body_height for lane, profile in lane_profiles if not lane.is_span]
- if document_body_profile is not None:
- document_body_height = document_body_profile.body_height
- else:
- document_body_height = (
- statistics.median(column_body_heights)
- if column_body_heights
- else min(
- (profile.body_height for _lane, profile in lane_profiles),
- default=1.0,
- )
- )
- for lane, profile in lane_profiles:
- lane_width = max(0.1, lane.right - lane.left)
- available = [item for item in lane.lines if item[0].semantic_type is None]
- for row_index, item in enumerate(available):
- line, bbox = item
- reference_height = min(profile.body_height, 1.25 * document_body_height)
- height_ratio = _line_effective_height(line, bbox) / max(0.1, reference_height)
- document_height_ratio = _line_effective_height(line, bbox) / max(
- 0.1,
- document_body_height,
- )
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.15 * lane_width
- page_centered = abs(_bbox_center_x(bbox) - 0.5 * local_page_width) <= 0.15 * local_page_width
- page_width_ratio = (bbox[2] - bbox[0]) / max(0.1, local_page_width)
- spans_columns_fallback = lane.is_span and centered and width_ratio >= 0.65 and document_height_ratio >= 1.3
- if (
- _bbox_center_y(bbox) > 0.45 * local_page_height
- or (height_ratio < 1.4 and not spans_columns_fallback)
- or width_ratio < 0.2
- or (not centered and height_ratio < 1.7)
- or (not page_centered and page_width_ratio < 0.45 and height_ratio < 1.8)
- ):
- continue
- top_preference = max(0.0, 0.45 - _bbox_center_y(bbox) / local_page_height)
- top_preference_weight = (
- 4.0 if document_body_profile is not None and document_body_profile.has_style_scale_repairs else 1.0
- )
- score = (
- height_ratio
- + (0.75 if centered else 0.0)
- + (1.25 if page_centered else 0.0)
- + (0.75 if page_width_ratio >= 0.55 else 0.0)
- + top_preference_weight * top_preference
- - 0.02 * row_index
- )
- candidates.append((score, lane, row_index, item))
- if not candidates:
- return None
-
- _score, lane, _row_index, anchor = max(candidates, key=lambda item: item[0])
- anchor_line, anchor_bbox = anchor
- anchor_height = _line_effective_height(anchor_line, anchor_bbox)
- anchor_line.semantic_type = "doc_title"
- selected = [anchor]
- ordered = lane.lines
- anchor_index = ordered.index(anchor)
- for direction in (-1, 1):
- index = anchor_index + direction
- previous_bbox = anchor_bbox
- while 0 <= index < len(ordered):
- candidate_line, candidate_bbox = ordered[index]
- if candidate_line.semantic_type is not None:
- break
- candidate_height = _line_effective_height(candidate_line, candidate_bbox)
- if not 0.8 <= candidate_height / anchor_height <= 1.25:
- break
- if not _document_title_fonts_compatible(anchor_line, candidate_line):
- break
- vertical_gap = max(candidate_bbox[1] - previous_bbox[3], previous_bbox[1] - candidate_bbox[3], 0.0)
- lane_width = max(0.1, lane.right - lane.left)
- centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(anchor_bbox)) <= 0.18 * lane_width
- aligned = abs(candidate_bbox[0] - anchor_bbox[0]) <= 0.75 * anchor_height
- if vertical_gap > 1.1 * anchor_height or not (centered or aligned):
- break
- candidate_line.semantic_type = "doc_title"
- selected.append((candidate_line, candidate_bbox))
- previous_bbox = candidate_bbox
- index += direction
- return max(bbox[3] for _line, bbox in selected)
-
-
-def _expand_document_title_across_lanes(
- line_geometry: list[tuple[_LineItem, BBox]],
- local_page_width: float,
- local_page_height: float,
- document_title_bottom: float | None,
-) -> float | None:
- """跨错误推断栏扩展紧邻、同字号且对齐的多行文档标题。"""
-
- title_items = [item for item in line_geometry if item[0].semantic_type == "doc_title"]
- if not title_items:
- return document_title_bottom
- selected_ids = {id(line) for line, _bbox in title_items}
- changed = True
- while changed:
- changed = False
- title_bbox = _bbox_union_many([bbox for _line, bbox in title_items])
- title_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in title_items)
- anchors = [line for line, _bbox in title_items]
- candidates = [
- item
- for item in line_geometry
- if id(item[0]) not in selected_ids
- and item[0].semantic_type is None
- and _bbox_center_y(item[1]) <= 0.45 * local_page_height
- ]
- candidates.sort(
- key=lambda item: min(
- abs(item[1][1] - title_bbox[3]),
- abs(title_bbox[1] - item[1][3]),
- )
- )
- for candidate_line, candidate_bbox in candidates:
- candidate_height = _line_effective_height(
- candidate_line,
- candidate_bbox,
- )
- if not 0.8 <= candidate_height / max(0.1, title_height) <= 1.25:
- continue
- if not any(_document_title_fonts_compatible(anchor, candidate_line) for anchor in anchors):
- continue
- vertical_gap = max(
- candidate_bbox[1] - title_bbox[3],
- title_bbox[1] - candidate_bbox[3],
- 0.0,
- )
- centered = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox)) <= 0.18 * local_page_width
- aligned = abs(candidate_bbox[0] - title_bbox[0]) <= 0.75 * title_height
- title_width = max(0.1, title_bbox[2] - title_bbox[0])
- candidate_width = candidate_bbox[2] - candidate_bbox[0]
- aligned_continuation = aligned and candidate_width >= 0.25 * title_width
- centered_continuation = centered and candidate_width >= 0.45 * title_width
- if vertical_gap > 1.1 * title_height or not (aligned_continuation or centered_continuation):
- continue
- candidate_line.semantic_type = "doc_title"
- title_items.append((candidate_line, candidate_bbox))
- selected_ids.add(id(candidate_line))
- changed = True
- break
- return max(bbox[3] for _line, bbox in title_items)
-
-
-def _classify_additional_document_title_bands(
- line_geometry: list[tuple[_LineItem, BBox]],
- local_page_width: float,
- local_page_height: float,
- document_title_bottom: float | None,
- *,
- document_body_profile: _DocumentBodyProfile | None,
-) -> float | None:
- """用居中译题与后续作者行结构补充首页第二文档标题带。"""
-
- if document_title_bottom is None or document_body_profile is None or not document_body_profile.has_style_scale_repairs:
- return document_title_bottom
- body_height = max(0.1, document_body_profile.body_height)
- ordered = sorted(
- line_geometry,
- key=lambda item: (item[1][1], item[1][0], item[0].source_index),
- )
- selected_bottoms = [bbox[3] for line, bbox in ordered if line.semantic_type == "doc_title"]
- for index, (line, bbox) in enumerate(ordered):
- if line.semantic_type is not None:
- continue
- center_y = _bbox_center_y(bbox)
- width_ratio = (bbox[2] - bbox[0]) / max(0.1, local_page_width)
- if not (document_title_bottom + 4.0 * body_height <= center_y <= 0.58 * local_page_height):
- continue
- if not 0.4 <= width_ratio <= 0.8:
- continue
- if abs(_bbox_center_x(bbox) - 0.5 * local_page_width) > 0.08 * local_page_width:
- continue
- if _line_uses_document_regular_font(line, document_body_profile):
- continue
- following = [
- item for item in ordered[index + 1 :] if item[0].semantic_type is None and _bbox_center_y(item[1]) > center_y
- ]
- if not following:
- continue
- _next_line, next_bbox = following[0]
- next_width_ratio = (next_bbox[2] - next_bbox[0]) / max(0.1, local_page_width)
- next_centered = abs(_bbox_center_x(next_bbox) - 0.5 * local_page_width) <= 0.12 * local_page_width
- vertical_gap = max(0.0, next_bbox[1] - bbox[3])
- if not next_centered or next_width_ratio > 0.45 or vertical_gap > 2.0 * body_height:
- continue
- line.semantic_type = "doc_title"
- selected_bottoms.append(bbox[3])
- return max(selected_bottoms, default=document_title_bottom)
-
-
-def _classify_cross_lane_centered_section_titles(
- line_geometry: list[tuple[_LineItem, BBox]],
- lanes: list[_TextLane],
- local_page_width: float,
- local_page_height: float,
- container_bboxes: list[BBox],
- *,
- page_index: int,
- document_title_bottom: float | None,
-) -> None:
- """用正文栏中心、上下留白和正文邻行补标被单独推成窄栏的标题。"""
-
- stable_lanes = [
- lane for lane in lanes if not lane.is_span and len(lane.lines) >= 5 and lane.right - lane.left >= 0.2 * local_page_width
- ]
- for line, bbox in line_geometry:
- if line.semantic_type is not None:
- continue
- if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
- continue
- candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
- if not candidate_lanes:
- continue
- lane = min(
- candidate_lanes,
- key=lambda candidate: abs(_bbox_center_x(bbox) - 0.5 * (candidate.left + candidate.right)),
- )
- profile = _infer_lane_body_profile(lane)
- lane_width = max(0.1, lane.right - lane.left)
- line_width = bbox[2] - bbox[0]
- line_height = _line_effective_height(line, bbox)
- if not 0.08 * lane_width <= line_width <= 0.7 * lane_width:
- continue
- if abs(_bbox_center_x(bbox) - 0.5 * (lane.left + lane.right)) > 0.05 * lane_width:
- continue
- if not 0.75 <= line_height / max(0.1, profile.body_height) <= 1.3:
- continue
- uses_regular_font = (
- profile.body_font is not None
- and line.font_signature is not None
- and line.font_coverage >= 0.75
- and _font_signatures_share_family(
- line.font_signature,
- profile.body_font,
- )
- )
- weight_emphasized = (
- profile.body_weight is not None
- and line.dominant_font_weight is not None
- and line.dominant_font_weight
- >= max(
- profile.body_weight + 100.0,
- 1.15 * profile.body_weight,
- )
- )
- if (
- page_index == 0
- and line_height < 0.9 * profile.body_height
- and uses_regular_font
- and not weight_emphasized
- ):
- continue
- if document_title_bottom is not None and bbox[1] <= document_title_bottom + profile.body_height:
- continue
- if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
- bbox,
- container_bboxes,
- profile.body_height,
- ):
- continue
- body_rows = [
- item
- for item in lane.lines
- if item[0] is not line
- and item[0].semantic_type is None
- and item[1][2] - item[1][0] >= 0.5 * lane_width
- and 0.75 <= _line_effective_height(*item) / max(0.1, profile.body_height) <= 1.3
- ]
- rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < _bbox_center_y(bbox)]
- rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > _bbox_center_y(bbox)]
- if not rows_above or not rows_below:
- continue
- previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
- following_rows = sorted(
- rows_below,
- key=lambda item: _bbox_center_y(item[1]),
- )
- if len(following_rows) < 3 or any(
- _effective_text_row_gap(previous_row, current_row) > profile.regular_gap + 0.75 * profile.body_height
- for previous_row, current_row in zip(
- following_rows[:3],
- following_rows[1:3],
- )
- ):
- continue
- following = following_rows[0]
- gap_above = bbox[1] - previous[1][3]
- gap_below = following[1][1] - bbox[3]
- if (
- gap_above < 0.3 * profile.body_height
- or gap_below < -0.1 * profile.body_height
- or max(gap_above, gap_below) < profile.regular_gap + 0.2 * profile.body_height
- ):
- continue
- line.semantic_type = "paragraph_title"
-
-
-def _demote_cross_lane_body_continuation_titles(
- line_geometry: list[tuple[_LineItem, BBox]],
- lanes: list[_TextLane],
-) -> None:
- """把紧接上一正文行、同字号同字体的短续行从标题降回正文。"""
-
- stable_lanes = [lane for lane in lanes if not lane.is_span and len(lane.lines) >= 4]
- for line, bbox in line_geometry:
- if line.semantic_type != "paragraph_title":
- continue
- line_height = _line_effective_height(line, bbox)
- global_preceding = [
- item
- for item in line_geometry
- if item[0] is not line
- and item[0].semantic_type is None
- and item[0].angle == line.angle
- and _bbox_center_y(item[1]) < _bbox_center_y(bbox)
- and abs(item[1][0] - bbox[0]) <= line_height
- ]
- if global_preceding:
- previous_line, previous_bbox = max(
- global_preceding,
- key=lambda item: _bbox_center_y(item[1]),
- )
- previous_height = _line_effective_height(
- previous_line,
- previous_bbox,
- )
- same_family = (
- previous_line.font_signature is None
- or line.font_signature is None
- or _font_signatures_share_family(
- previous_line.font_signature,
- line.font_signature,
- )
- )
- if (
- same_family
- and 0.9 <= line_height / max(0.1, previous_height) <= 1.1
- and bbox[1] - previous_bbox[3] <= 0.2 * max(line_height, previous_height)
- and abs(bbox[0] - previous_bbox[0]) <= 0.75 * max(line_height, previous_height)
- and previous_bbox[2] - previous_bbox[0] >= 2.0 * (bbox[2] - bbox[0])
- ):
- line.semantic_type = None
- continue
- candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
- if not candidate_lanes:
- continue
- lane = min(
- candidate_lanes,
- key=lambda candidate: abs(_bbox_center_x(bbox) - 0.5 * (candidate.left + candidate.right)),
- )
- lane_width = max(0.1, lane.right - lane.left)
- lane_profile = _infer_lane_body_profile(lane)
- if bbox[2] - bbox[0] > 0.55 * lane_width:
- continue
- preceding = [
- item
- for item in line_geometry
- if item[0] is not line
- and item[0].semantic_type is None
- and _bbox_center_y(item[1]) < _bbox_center_y(bbox)
- and lane.left <= _bbox_center_x(item[1]) <= lane.right
- ]
- if not preceding:
- continue
- previous_line, previous_bbox = max(
- preceding,
- key=lambda item: _bbox_center_y(item[1]),
- )
- previous_height = _line_effective_height(
- previous_line,
- previous_bbox,
- )
- line_height = _line_effective_height(line, bbox)
- if not 0.9 <= line_height / max(0.1, previous_height) <= 1.1:
- continue
- if (
- previous_line.font_signature is not None
- and line.font_signature is not None
- and not _font_signatures_share_family(
- previous_line.font_signature,
- line.font_signature,
- )
- ):
- continue
- if previous_bbox[2] - previous_bbox[0] < 0.5 * lane_width:
- continue
- maximum_gap = 0.15 * max(line_height, previous_height)
- if (
- re.search(
- r"[.!?。!?][\]\)})】》”’'\"]*$",
- line.text.rstrip(),
- )
- is not None
- ):
- maximum_gap = max(
- maximum_gap,
- lane_profile.regular_gap + 0.35 * lane_profile.body_height,
- )
- if bbox[1] - previous_bbox[3] > maximum_gap:
- continue
- if abs(bbox[0] - lane.left) > max(1.0, 0.75 * line_height):
- continue
- line.semantic_type = None
-
-
-def _classify_cross_lane_emphasized_section_titles(
- line_geometry: list[tuple[_LineItem, BBox]],
- lanes: list[_TextLane],
- local_page_width: float,
- local_page_height: float,
- container_bboxes: list[BBox],
- *,
- document_title_bottom: float | None,
- document_body_profile: _DocumentBodyProfile | None,
-) -> None:
- """用正文栏左缘、强调字体和段间留白补标跨栏推断失败的小节标题。"""
-
- stable_lanes = [
- lane for lane in lanes if not lane.is_span and len(lane.lines) >= 5 and lane.right - lane.left >= 0.2 * local_page_width
- ]
- for line, bbox in line_geometry:
- if line.semantic_type is not None or line.font_signature is None:
- continue
- if not line.font_signature[1] & PDF_FONT_ITALIC_FLAG:
- continue
- if _line_uses_document_regular_font(line, document_body_profile):
- continue
- if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
- continue
- candidate_lanes = [lane for lane in stable_lanes if lane.left <= _bbox_center_x(bbox) <= lane.right]
- if not candidate_lanes:
- continue
- lane = min(
- candidate_lanes,
- key=lambda candidate: abs(bbox[0] - candidate.left),
- )
- profile = _infer_lane_body_profile(lane)
- if profile.body_font is None or line.font_signature == profile.body_font or line.font_coverage < 0.75:
- continue
- lane_width = max(0.1, lane.right - lane.left)
- line_height = _line_effective_height(line, bbox)
- if bbox[2] - bbox[0] > 0.9 * lane_width:
- continue
- if abs(bbox[0] - lane.left) > 2.0 * profile.body_height:
- continue
- if not 0.8 <= line_height / max(0.1, profile.body_height) <= 1.35:
- continue
- if document_title_bottom is not None and bbox[1] <= document_title_bottom + 2.0 * profile.body_height:
- continue
- if _line_inside_visual_container(bbox, container_bboxes) or _line_near_visual_container(
- bbox,
- container_bboxes,
- profile.body_height,
- ):
- continue
- body_rows = [
- item
- for item in lane.lines
- if item[0] is not line
- and item[0].semantic_type is None
- and item[0].font_signature == profile.body_font
- and item[1][2] - item[1][0] >= 0.45 * lane_width
- ]
- rows_above = [item for item in body_rows if _bbox_center_y(item[1]) < _bbox_center_y(bbox)]
- rows_below = [item for item in body_rows if _bbox_center_y(item[1]) > _bbox_center_y(bbox)]
- if not rows_above or not rows_below:
- continue
- previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))
- following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))
- gap_above = bbox[1] - previous[1][3]
- gap_below = following[1][1] - bbox[3]
- if (
- gap_above < 0.35 * profile.body_height
- or gap_below > 3.0 * profile.body_height
- or gap_below < -0.1 * profile.body_height
- ):
- continue
- line.semantic_type = "paragraph_title"
-
-
-def _is_wide_leading_title_continuation(
- title_bbox: BBox,
- candidate_bbox: BBox,
- title_height: float,
- candidate_height: float,
-) -> bool:
- """识别紧贴在窄标题锚点上方、同中心的较宽首行。"""
-
- pair_height = max(0.1, title_height, candidate_height)
- title_width = max(0.1, title_bbox[2] - title_bbox[0])
- width_ratio = (candidate_bbox[2] - candidate_bbox[0]) / title_width
- vertical_gap = title_bbox[1] - candidate_bbox[3]
- return (
- 2.0 < width_ratio <= 2.5
- and _bbox_center_y(candidate_bbox) < _bbox_center_y(title_bbox)
- and -0.1 * pair_height <= vertical_gap <= 0.15 * pair_height
- and _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") >= 0.8
- and abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(title_bbox)) <= 0.5 * pair_height
- )
-
-
-def _expand_cross_lane_paragraph_title_neighbors(
- line_geometry: list[tuple[_LineItem, BBox]],
-) -> None:
- """把紧贴标题锚点的同字体相邻行跨栏补标为同一标题。"""
-
- changed = True
- while changed:
- changed = False
- title_items = [
- item for item in line_geometry if item[0].semantic_type == "paragraph_title" and not item[0].explicit_section_title
- ]
- for title_line, title_bbox in title_items:
- title_height = _line_effective_height(title_line, title_bbox)
- for candidate_line, candidate_bbox in line_geometry:
- if candidate_line.semantic_type is not None:
- continue
- candidate_height = _line_effective_height(
- candidate_line,
- candidate_bbox,
- )
- if not 0.85 <= candidate_height / max(0.1, title_height) <= 1.2:
- continue
- title_width = max(0.1, title_bbox[2] - title_bbox[0])
- candidate_width = candidate_bbox[2] - candidate_bbox[0]
- if not (
- 0.25 <= candidate_width / title_width <= 2.0
- or _is_wide_leading_title_continuation(
- title_bbox,
- candidate_bbox,
- title_height,
- candidate_height,
- )
- ):
- continue
- if (
- title_line.font_signature is not None
- and candidate_line.font_signature is not None
- and title_line.font_signature != candidate_line.font_signature
- ):
- continue
- vertical_gap = max(
- candidate_bbox[1] - title_bbox[3],
- title_bbox[1] - candidate_bbox[3],
- 0.0,
- )
- if vertical_gap > 0.35 * max(title_height, candidate_height):
- continue
- if (
- _bbox_axis_overlap_ratio(title_bbox, candidate_bbox, axis="x") < 0.2
- and abs(candidate_bbox[0] - title_bbox[0]) > 2.0 * title_height
- ):
- continue
- candidate_line.semantic_type = "paragraph_title"
- changed = True
- break
- if changed:
- break
-
-
-def _demote_hanging_multiline_text_titles(
- lanes: list[_TextLane],
- document_body_profile: _DocumentBodyProfile | None,
- *,
- page_index: int,
-) -> None:
- """把缩进满行后回到栏左缘的紧邻标题行组降回正文。"""
-
- if page_index != 0 or document_body_profile is None:
- return
- body_height = max(0.1, document_body_profile.body_height)
- for lane in lanes:
- 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)
- for first, second in zip(rows, rows[1:]):
- first_line, first_bbox = first
- second_line, second_bbox = second
- if (
- first_line.semantic_type != "paragraph_title"
- or second_line.semantic_type != "paragraph_title"
- or first_line.font_signature is None
- or second_line.font_signature is None
- or first_line.font_coverage < 0.75
- or second_line.font_coverage < 0.75
- or not _font_signatures_share_family(
- first_line.font_signature,
- second_line.font_signature,
- )
- ):
- continue
- first_height = _line_effective_height(*first)
- second_height = _line_effective_height(*second)
- pair_height = max(first_height, second_height)
- if not (
- max(first_height, second_height) <= 1.1 * body_height
- and min(first_height, second_height)
- >= 0.85 * pair_height
- and first_bbox[2] - first_bbox[0]
- >= 0.9 * lane_width
- and first_bbox[0] - lane.left
- >= 0.75 * pair_height
- and abs(second_bbox[0] - lane.left)
- <= 0.5 * pair_height
- and -0.25 * pair_height
- <= _effective_text_row_gap(first, second)
- <= 0.5 * pair_height
- ):
- continue
- first_line.semantic_type = None
- second_line.semantic_type = None
- first_line.title_suppressed = True
- second_line.title_suppressed = True
-
-
-def _demote_visual_container_caption_titles(
- line_geometry: list[tuple[_LineItem, BBox]],
- container_bboxes: list[BBox],
-) -> None:
- """把紧贴视觉容器下缘且水平居中的标题候选降回普通图注文本。"""
-
- for line, bbox in line_geometry:
- if line.semantic_type != "paragraph_title":
- continue
- line_height = _line_effective_height(line, bbox)
- for container_bbox in container_bboxes:
- vertical_gap = bbox[1] - container_bbox[3]
- if not -0.25 * line_height <= vertical_gap <= 1.5 * line_height:
- continue
- if _bbox_axis_overlap_ratio(bbox, container_bbox, axis="x") < 0.35:
- continue
- if abs(_bbox_center_x(bbox) - _bbox_center_x(container_bbox)) > 0.35 * max(
- container_bbox[2] - container_bbox[0],
- bbox[2] - bbox[0],
- ):
- continue
- line.semantic_type = None
- break
-
-
-def _demote_sentence_tail_titles(
- line_geometry: list[tuple[_LineItem, BBox]],
-) -> None:
- """把紧接未完正文、以句末标点结束的短行标题降回正文。"""
-
- for line, bbox in line_geometry:
- if (
- line.semantic_type != "paragraph_title"
- or re.search(
- r"[.!?。!?][\]\)})】》”’'\"]*$",
- line.text.rstrip(),
- )
- is None
- ):
- continue
- line_height = _line_effective_height(line, bbox)
- preceding = [
- item
- for item in line_geometry
- if item[0] is not line
- and item[0].semantic_type is None
- and item[1][3] <= bbox[1]
- and abs(item[1][0] - bbox[0]) <= 0.75 * line_height
- ]
- if not preceding:
- continue
- previous_line, previous_bbox = max(
- preceding,
- key=lambda item: item[1][3],
- )
- previous_height = _line_effective_height(
- previous_line,
- previous_bbox,
- )
- same_family = (
- previous_line.font_signature is None
- or line.font_signature is None
- or _font_signatures_share_family(
- previous_line.font_signature,
- line.font_signature,
- )
- )
- bbox_height = max(0.1, bbox[3] - bbox[1])
- previous_bbox_height = max(
- 0.1,
- previous_bbox[3] - previous_bbox[1],
- )
- compatible_height = (same_family and 0.75 <= line_height / max(0.1, previous_height) <= 1.25) or (
- 0.8 <= bbox_height / previous_bbox_height <= 1.2
- )
- if (
- compatible_height
- and bbox[1] - previous_bbox[3]
- <= 0.9
- * max(
- line_height,
- previous_height,
- bbox_height,
- previous_bbox_height,
- )
- and previous_bbox[2] - previous_bbox[0] >= 1.5 * (bbox[2] - bbox[0])
- and re.search(
- r"[.!?。!?][\]\)})】》”’'\"]*$",
- previous_line.text.rstrip(),
- )
- is None
- ):
- line.semantic_type = None
-
-
-def _document_title_fonts_compatible(
- first: _LineItem,
- second: _LineItem,
-) -> bool:
- """允许混排标题因主字体覆盖不足而切换字体,同时保留可靠字重屏障。"""
-
- if _title_fonts_compatible(first, second):
- return True
- uncertain_dominant_font = min(first.font_coverage, second.font_coverage) < 0.85
- weights_compatible = (
- first.dominant_font_weight is None
- or second.dominant_font_weight is None
- or abs(first.dominant_font_weight - second.dominant_font_weight) < 100.0
- or max(first.dominant_font_weight, second.dominant_font_weight)
- < 1.15 * min(first.dominant_font_weight, second.dominant_font_weight)
- )
- return uncertain_dominant_font and weights_compatible
-
-
-def _document_title_uses_page_fallback(
- lanes: list[_TextLane],
- *,
- document_body_profile: _DocumentBodyProfile | None = None,
-) -> bool:
- """判断首页标题是否依赖跨栏 1.30 倍全文正文行高兜底。"""
-
- title_heights = [
- _line_effective_height(line, bbox) for lane in lanes for line, bbox in lane.lines if line.semantic_type == "doc_title"
- ]
- column_body_heights = [_infer_lane_body_profile(lane).body_height for lane in lanes if not lane.is_span]
- if not title_heights or not column_body_heights:
- return False
- document_body_height = (
- document_body_profile.body_height if document_body_profile is not None else statistics.median(column_body_heights)
- )
- return any(1.3 <= title_height / max(0.1, document_body_height) < 1.4 for title_height in title_heights)
-
-
-def _classify_paragraph_titles_in_lane(
- lane: _TextLane,
- profile: _LaneBodyProfile,
- local_page_width: float,
- local_page_height: float,
- container_bboxes: list[BBox],
- *,
- document_title_bottom: float | None,
- preserve_front_matter_boundaries: bool,
- physical_gaps: dict[int, tuple[float | None, float | None]],
- grid_title_suppressions: set[int],
- document_body_profile: _DocumentBodyProfile | None,
- document_title_profile: _DocumentTitleProfile | None,
- page_index: int,
-) -> None:
- """以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""
-
- lane_width = max(0.1, lane.right - lane.left)
- rows = lane.lines
- selected_indices: set[int] = set()
- front_matter_boundary = _infer_front_matter_boundary(
- lane,
- profile,
- local_page_height,
- document_title_bottom=document_title_bottom,
- )
- for index, (line, bbox) in enumerate(rows):
- if line.semantic_type is not None:
- continue
- if line.source_index in grid_title_suppressions:
- continue
- if not 0.07 * local_page_height <= _bbox_center_y(bbox) <= 0.93 * local_page_height:
- continue
- inside_front_matter = front_matter_boundary is not None and _bbox_center_y(bbox) <= front_matter_boundary
- if inside_front_matter and not preserve_front_matter_boundaries:
- continue
- if (
- document_title_bottom is not None
- and document_title_bottom <= 0.6 * local_page_height
- and _bbox_center_y(bbox) >= 0.84 * local_page_height
- ):
- # 首页底部短行通常是版本、日期等封面元数据,不属于正文标题层级。
- continue
- line_height = _line_effective_height(line, bbox)
- title_prototype = _matching_document_title_prototype(
- line,
- bbox,
- lane,
- document_body_profile,
- document_title_profile,
- )
- title_profile_size_conflict = title_prototype is None and _line_conflicts_document_title_profile(
- line,
- bbox,
- lane,
- document_body_profile,
- document_title_profile,
- )
- inside_visual_container = _line_inside_visual_container(
- bbox,
- container_bboxes,
- )
- near_visual_container = _line_near_visual_container(
- bbox,
- container_bboxes,
- profile.body_height,
- )
- if inside_visual_container or (near_visual_container and title_prototype is None):
- continue
-
- recurrent_regular_font = _line_uses_document_regular_font(
- line,
- document_body_profile,
- )
- document_regular_body_candidate = (
- recurrent_regular_font
- and document_body_profile is not None
- and line_height >= 0.9 * document_body_profile.body_height
- )
- reference_body_height = profile.body_height
- if profile.body_row_count < 3 and document_body_profile is not None:
- reference_body_height = document_body_profile.body_height
- if document_regular_body_candidate and document_body_profile is not None:
- reference_body_height = max(
- reference_body_height,
- document_body_profile.body_height,
- )
- height_ratio = line_height / reference_body_height
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_width
- left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height
- if line.median_glyph_width is not None and bbox[2] - bbox[0] <= 1.25 * line.median_glyph_width and height_ratio < 1.18:
- continue
- style_differs = (
- not recurrent_regular_font
- and profile.body_font is not None
- and line.font_signature is not None
- and line.font_coverage >= 0.75
- 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 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 = (
- profile.body_weight is not None
- and line.dominant_font_weight is not None
- and line.dominant_font_weight >= max(profile.body_weight + 100.0, 1.15 * profile.body_weight)
- )
- gap_above = _normalized_title_gap(
- rows,
- index,
- direction=-1,
- body_height=profile.body_height,
- physical_gaps=physical_gaps,
- )
- gap_below = _normalized_title_gap(
- rows,
- index,
- direction=1,
- body_height=profile.body_height,
- physical_gaps=physical_gaps,
- )
- regular_gap_ratio = profile.regular_gap / max(0.1, profile.body_height)
- gap_above_excess = max(0.0, gap_above - regular_gap_ratio)
- gap_below_excess = max(0.0, gap_below - regular_gap_ratio)
- has_spacing_signal = gap_above >= 0.35
-
- if _visual_row_has_body_style_sibling(rows, index):
- continue
- if _is_near_full_mixed_inline_row(
- rows,
- index,
- lane_width,
- profile,
- ):
- continue
- if (
- index > 0
- and rows[index - 1][0].semantic_type == "paragraph_title"
- and width_ratio >= 0.85
- and gap_above < 1.0
- and not _title_fonts_compatible(rows[index - 1][0], line)
- ):
- continue
- if _continues_local_body_row(
- rows,
- index,
- lane_width,
- 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
- )
- compact_text_section = (
- height_ratio < 0.9
- and centered
- and width_ratio <= 0.7
- and gap_above >= 0.35
- and gap_below >= 0.2
- and (
- page_index != 0
- or style_differs
- or weight_emphasized
- or title_prototype is not None
- )
- and _has_following_compact_text_section(
- rows,
- index,
- lane_width,
- )
- )
- weak_regular_pitch_body_candidate = (
- document_body_profile is not None
- and 0.9 <= line_height / document_body_profile.body_height <= 1.1
- and title_prototype is None
- and (not centered or width_ratio >= 0.75)
- and not weight_emphasized
- and gap_above_excess < 0.1
- and gap_below_excess < 0.1
- )
- if weak_regular_pitch_body_candidate:
- continue
- if (
- title_profile_size_conflict
- and document_body_profile is not None
- and line_height <= 1.18 * document_body_profile.body_height
- and not weight_emphasized
- ):
- continue
- prototype_promotion = (
- title_prototype is not None
- and (width_ratio <= 0.9 or (bbox[2] - bbox[0]) / max(0.1, local_page_width) <= 0.8)
- and (centered or left_aligned)
- and (
- (document_body_profile is not None and line_height >= 1.18 * document_body_profile.body_height)
- or near_visual_container
- or (has_following_body_row and gap_above_excess >= 0.1)
- or gap_above_excess >= 0.35
- )
- )
- prototype_inline_heading = (
- document_body_profile is not None
- and line_height <= 1.15 * document_body_profile.body_height
- and _is_full_width_inline_heading(
- rows,
- index,
- lane_width,
- profile,
- )
- )
- if prototype_promotion and not prototype_inline_heading:
- line.semantic_type = "paragraph_title"
- selected_indices.add(index)
- continue
- if (
- document_body_profile is not None
- and 0.9 <= line_height / document_body_profile.body_height <= 1.1
- and title_prototype is None
- and centered
- and not has_following_body_row
- and not compact_text_section
- ):
- continue
- if height_ratio < 0.9 and not inside_front_matter and not has_following_body_row and not compact_text_section:
- continue
- if width_ratio >= 0.9 and height_ratio < 1.15 and not (style_differs and gap_above >= 0.65):
- continue
- score = 0.0
- if style_differs or compact_local_transition:
- score += 2.0
- if compact_local_transition or style_support <= 0.2:
- score += 0.75
- if weight_emphasized:
- score += 1.0
- if height_ratio >= 1.18:
- score += 2.0
- elif height_ratio <= 0.9 and centered:
- score += 0.75
- if width_ratio <= 0.78:
- score += 0.75
- if centered and width_ratio <= 0.85:
- score += 1.25
- if gap_above >= 0.65:
- score += 1.25
- elif gap_above >= 0.35:
- score += 0.5
- if gap_below >= 0.35:
- score += 0.75
- 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_structural_fallback
- or compact_text_section
- )
- if score >= 4.0 and (has_spacing_signal or compact_local_transition) and strong_layout_signal:
- if _is_full_width_inline_heading(
- rows,
- index,
- lane_width,
- profile,
- ):
- continue
- line.semantic_type = "paragraph_title"
- selected_indices.add(index)
-
- _unify_visual_row_title_types(
- lane,
- selected_indices,
- )
- _expand_paragraph_title_neighbors(
- lane,
- selected_indices,
- profile,
- )
- if front_matter_boundary is not None and preserve_front_matter_boundaries:
- _protect_front_matter_title_types(
- lane,
- profile,
- front_matter_boundary,
- )
-
-
-def _line_uses_document_regular_font(
- line: _LineItem,
- document_body_profile: _DocumentBodyProfile | None,
-) -> bool:
- """判断当前行是否使用跨页反复出现且未加粗的常规字体。"""
-
- return (
- document_body_profile is not None
- and line.font_signature is not None
- and line.font_coverage >= 0.5
- and any(
- _font_signatures_share_family(line.font_signature, regular_font)
- for regular_font in document_body_profile.regular_fonts
- )
- )
-
-
-def _matching_document_title_prototype(
- line: _LineItem,
- bbox: BBox,
- lane: _TextLane,
- document_body_profile: _DocumentBodyProfile | None,
- document_title_profile: _DocumentTitleProfile | None,
-) -> _TitleStylePrototype | None:
- """返回与当前行字体、字号、字重和栏内锚点兼容的最强标题原型。"""
-
- if (
- document_body_profile is None
- or document_title_profile is None
- or line.font_signature is None
- or line.font_coverage < 0.75
- ):
- return None
- font_family = _normalized_font_family(line.font_signature)
- if font_family is None:
- return None
- height_ratio = _line_effective_height(line, bbox) / max(
- 0.1,
- document_body_profile.body_height,
- )
- candidates: list[_TitleStylePrototype] = []
- for prototype in document_title_profile.prototypes:
- if (
- prototype.font_family != font_family
- or prototype.font_flags != line.font_signature[1]
- or abs(height_ratio - prototype.height_ratio) > 0.1 * prototype.height_ratio
- ):
- continue
- if (
- prototype.weight is not None
- and line.dominant_font_weight is not None
- and abs(prototype.weight - line.dominant_font_weight) >= 100.0
- and max(prototype.weight, line.dominant_font_weight) >= 1.15 * min(prototype.weight, line.dominant_font_weight)
- ):
- continue
- alignment = _title_profile_alignment(
- bbox,
- lane,
- document_body_profile.body_height,
- )
- if alignment is None or alignment[0] != prototype.alignment or abs(alignment[1] - prototype.anchor_offset) > 0.15:
- continue
- candidates.append(prototype)
- return max(
- candidates,
- key=lambda item: (item.support_pages, item.support_count),
- default=None,
- )
-
-
-def _line_inside_visual_container(
- line_bbox: BBox,
- container_bboxes: list[BBox],
-) -> bool:
- """检查文本行中心是否落入视觉容器,容器内标签不得借标题原型晋升。"""
-
- center_x = _bbox_center_x(line_bbox)
- center_y = _bbox_center_y(line_bbox)
- return any(bbox[0] <= center_x <= bbox[2] and bbox[1] <= center_y <= bbox[3] for bbox in container_bboxes)
-
-
-def _line_conflicts_document_title_profile(
- line: _LineItem,
- bbox: BBox,
- lane: _TextLane,
- document_body_profile: _DocumentBodyProfile | None,
- document_title_profile: _DocumentTitleProfile | None,
-) -> bool:
- """识别字体与标题原型一致、但字号明显落入正文带的弱标题候选。"""
-
- if (
- document_body_profile is None
- or document_title_profile is None
- or line.font_signature is None
- or line.font_coverage < 0.75
- ):
- return False
- font_family = _normalized_font_family(line.font_signature)
- alignment = _title_profile_alignment(
- bbox,
- lane,
- document_body_profile.body_height,
- )
- if font_family is None or alignment is None:
- return False
- height_ratio = _line_effective_height(line, bbox) / max(
- 0.1,
- document_body_profile.body_height,
- )
- for prototype in document_title_profile.prototypes:
- if (
- not _title_font_families_compatible(
- prototype.font_family,
- font_family,
- )
- or prototype.font_flags != line.font_signature[1]
- or prototype.alignment != alignment[0]
- or abs(prototype.anchor_offset - alignment[1]) > 0.15
- ):
- continue
- if (
- prototype.weight is not None
- and line.dominant_font_weight is not None
- and abs(prototype.weight - line.dominant_font_weight) >= 100.0
- and max(prototype.weight, line.dominant_font_weight) >= 1.15 * min(prototype.weight, line.dominant_font_weight)
- ):
- continue
- if abs(height_ratio - prototype.height_ratio) > 0.15 * prototype.height_ratio:
- return True
- return False
-
-
-def _title_font_families_compatible(first: str, second: str) -> bool:
- """忽略已由 flags 和字重单独约束的常见字体样式后缀。"""
-
- if first == second:
- return True
- style_suffixes = (",bold", "bold", ",regular", "regular", ",medium", "medium")
- return any(first.removesuffix(suffix) == second or second.removesuffix(suffix) == first for suffix in style_suffixes)
-
-
-def _protect_front_matter_title_types(
- lane: _TextLane,
- profile: _LaneBodyProfile,
- front_matter_boundary: float,
-) -> None:
- """把作者区误命中的标题降为正文,并仅保留原本需要跨行聚合的内部标记。"""
-
- front_title_indices = [
- index
- for index, (line, bbox) in enumerate(lane.lines)
- if line.semantic_type == "paragraph_title" and _bbox_center_y(bbox) <= front_matter_boundary
- ]
- connected_indices: set[int] = set()
- for position, first_index in enumerate(front_title_indices):
- for second_index in front_title_indices[position + 1 :]:
- if _should_connect_semantic_rows(
- lane.lines[first_index],
- lane.lines[second_index],
- lane,
- profile.regular_gap,
- [],
- [],
- ):
- connected_indices.update((first_index, second_index))
- for index in front_title_indices:
- lane.lines[index][0].semantic_type = "text" if index in connected_indices else None
-
-
-def _visual_row_has_body_style_sibling(
- rows: list[tuple[_LineItem, BBox]],
- index: int,
-) -> bool:
- """检查同一完整视觉行是否同时包含标题样式与正文样式 run。"""
-
- line, _bbox = rows[index]
- if line.visual_row_id is None:
- return False
- siblings = [
- sibling for sibling, _sibling_bbox in rows if sibling is not line and sibling.visual_row_id == line.visual_row_id
- ]
- return any(not _title_fonts_compatible(line, sibling) for sibling in siblings)
-
-
-def _is_near_full_mixed_inline_row(
- rows: list[tuple[_LineItem, BBox]],
- index: int,
- lane_width: float,
- profile: _LaneBodyProfile,
-) -> bool:
- """识别近满栏混合字体行内强调,避免把粗体条目头单独标成标题。"""
-
- line, bbox = rows[index]
- line_height = _line_effective_height(line, bbox)
- if (
- line.font_coverage >= 0.95
- or (bbox[2] - bbox[0]) < 0.85 * lane_width
- or not 0.85 <= line_height / profile.body_height <= 1.15
- or index + 1 >= len(rows)
- ):
- return False
- next_line, next_bbox = rows[index + 1]
- next_height = _line_effective_height(next_line, next_bbox)
- gap_below = _effective_text_row_gap(rows[index], rows[index + 1])
- return (
- next_line.semantic_type is None
- and 0.8 <= next_height / profile.body_height <= 1.2
- and gap_below <= profile.regular_gap + 0.25 * profile.body_height
- )
-
-
-def _continues_local_body_row(
- rows: list[tuple[_LineItem, BBox]],
- index: int,
- lane_width: float,
- profile: _LaneBodyProfile,
-) -> bool:
- """识别紧随同字体满行的正文尾行,阻止全局小字号基线造成标题误判。"""
-
- if index <= 0:
- return False
- previous_line, previous_bbox = rows[index - 1]
- 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 (
- 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_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(
- (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
- and abs(bbox[0] - previous_bbox[0]) <= 2.0 * pair_height
- and -0.25 * pair_height <= gap <= profile.regular_gap + pair_height
- )
-
-
-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,
- lane_width: float,
- profile: _LaneBodyProfile,
-) -> bool:
- """识别后接常规正文续行的满栏正常字号行内标题。"""
-
- line, bbox = rows[index]
- line_height = _line_effective_height(line, bbox)
- if (
- not 0.85 <= line_height / profile.body_height <= 1.15
- or (bbox[2] - bbox[0]) < 0.9 * lane_width
- or index + 1 >= len(rows)
- ):
- return False
-
- next_line, next_bbox = rows[index + 1]
- next_height = _line_effective_height(next_line, next_bbox)
- next_uses_body_font = (
- profile.body_font is None
- or next_line.font_signature is None
- or next_line.font_coverage < 0.75
- or _font_signatures_share_family(
- next_line.font_signature,
- profile.body_font,
- )
- )
- return (
- next_line.semantic_type is None
- and next_uses_body_font
- and 0.75 <= next_height / profile.body_height <= 1.15
- and (next_bbox[2] - next_bbox[0]) >= 0.75 * lane_width
- and _effective_text_row_gap(rows[index], rows[index + 1]) <= profile.regular_gap + 0.25 * profile.body_height
- )
-
-
-def _has_following_body_row(
- rows: list[tuple[_LineItem, BBox]],
- index: int,
- lane_width: float,
- lane_left: float,
- profile: _LaneBodyProfile,
-) -> bool:
- """只检查紧邻且空间相关的下一行,禁止用远处正文支撑小字号标题。"""
-
- if index + 1 >= len(rows):
- return False
- current = rows[index]
- line, bbox = rows[index + 1]
- gap = _effective_text_row_gap(current, (line, bbox))
- horizontally_related = (
- _bbox_axis_overlap_ratio(current[1], bbox, axis="x") >= 0.35
- or abs(current[1][0] - bbox[0]) <= 0.75 * profile.body_height
- )
- current_centered = abs(_bbox_center_x(current[1]) - (lane_left + lane_width / 2.0)) <= 0.12 * lane_width
- compact_left_aligned = (
- current[1][2] - current[1][0] <= 0.35 * lane_width and abs(current[1][0] - lane_left) <= 0.65 * profile.body_height
- )
- maximum_gap = (1.5 if current_centered else 1.25 if compact_left_aligned else 0.75) * profile.body_height
- height_ratio = _line_effective_height(line, bbox) / profile.body_height
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- return (
- line.semantic_type is None
- and horizontally_related
- and -0.25 * profile.body_height <= gap <= maximum_gap
- and 0.9 <= height_ratio <= 1.2
- and width_ratio >= 0.45
- )
-
-
-def _has_following_compact_text_section(
- rows: list[tuple[_LineItem, BBox]],
- index: int,
- lane_width: float,
-) -> bool:
- """检查小字号候选后是否紧接三行同尺度的宽文本区段。"""
-
- candidate = rows[index]
- candidate_height = _line_effective_height(*candidate)
- following_rows = rows[index + 1 : index + 4]
- if len(following_rows) < 3:
- return False
-
- previous = candidate
- for current in following_rows:
- line, bbox = current
- height_ratio = _line_effective_height(line, bbox) / candidate_height
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- gap = _effective_text_row_gap(previous, current)
- if (
- line.semantic_type is not None
- or not 0.75 <= height_ratio <= 1.25
- or width_ratio < 0.45
- or not -0.25 * candidate_height <= gap <= 0.75 * candidate_height
- ):
- return False
- previous = current
- return True
-
-
-def _unify_visual_row_title_types(
- lane: _TextLane,
- selected_indices: set[int],
-) -> None:
- """按完整 visual_row_id 统一标题类型:同样式整行晋升,混合样式整行降级。"""
-
- row_indices: dict[int, list[int]] = {}
- for index, (line, _bbox) in enumerate(lane.lines):
- if line.visual_row_id is not None:
- row_indices.setdefault(line.visual_row_id, []).append(index)
- for indices in row_indices.values():
- title_indices = [index for index in indices if lane.lines[index][0].semantic_type == "paragraph_title"]
- if not title_indices:
- continue
- anchor_line, anchor_bbox = lane.lines[title_indices[0]]
- anchor_height = _line_effective_height(anchor_line, anchor_bbox)
- compatible = all(
- 0.75 <= _line_effective_height(lane.lines[index][0], lane.lines[index][1]) / anchor_height <= 1.25
- and _title_fonts_compatible(anchor_line, lane.lines[index][0])
- for index in indices
- )
- if compatible:
- for index in indices:
- lane.lines[index][0].semantic_type = "paragraph_title"
- selected_indices.add(index)
- continue
- for index in title_indices:
- lane.lines[index][0].semantic_type = None
- selected_indices.discard(index)
-
-
-def _infer_front_matter_boundary(
- lane: _TextLane,
- profile: _LaneBodyProfile,
- local_page_height: float,
- *,
- document_title_bottom: float | None,
-) -> float | None:
- """用短行后衔接满栏正文的几何转折点界定首页作者等前置信息。"""
-
- if document_title_bottom is None:
- return None
- default_boundary = max(
- document_title_bottom + 2.5 * profile.body_height,
- 0.39 * local_page_height,
- )
- lane_width = max(0.1, lane.right - lane.left)
- for index, (line, bbox) in enumerate(lane.lines[:-1]):
- if bbox[1] <= document_title_bottom:
- continue
- next_line, next_bbox = lane.lines[index + 1]
- width_ratio = (bbox[2] - bbox[0]) / lane_width
- next_width_ratio = (next_bbox[2] - next_bbox[0]) / lane_width
- left_aligned = abs(bbox[0] - lane.left) <= 0.65 * profile.body_height
- centered = abs(_bbox_center_x(bbox) - (lane.left + lane.right) / 2.0) <= 0.12 * lane_width
- next_height_ratio = _line_effective_height(next_line, next_bbox) / profile.body_height
- gap_below = max(0.0, _effective_text_row_gap((line, bbox), (next_line, next_bbox)))
- if (
- width_ratio <= 0.35
- and next_width_ratio >= 0.75
- and (left_aligned or centered)
- and 0.75 <= next_height_ratio <= 1.35
- and gap_below <= 1.5 * profile.body_height
- ):
- return min(default_boundary, bbox[1] - 0.1)
- return default_boundary
-
-
-def _normalized_title_gap(
- rows: list[tuple[_LineItem, BBox]],
- index: int,
- *,
- direction: Literal[-1, 1],
- body_height: float,
- physical_gaps: dict[int, tuple[float | None, float | None]],
-) -> float:
- """返回栏内邻行和页面最近物理邻行中较小的归一化净空。"""
-
- neighbor_index = index + direction
- if 0 <= neighbor_index < len(rows):
- if direction < 0:
- lane_gap = _effective_text_row_gap(rows[neighbor_index], rows[index])
- else:
- lane_gap = _effective_text_row_gap(rows[index], rows[neighbor_index])
- else:
- lane_gap = 0.5 * body_height
- physical_pair = physical_gaps.get(rows[index][0].source_index, (None, None))
- physical_gap = physical_pair[0 if direction < 0 else 1]
- gap = lane_gap if physical_gap is None else min(lane_gap, physical_gap)
- return max(0.0, gap) / max(0.1, body_height)
-
-
-def _line_near_visual_container(
- line_bbox: BBox,
- container_bboxes: list[BBox],
- body_height: float,
-) -> bool:
- """检查短行是否紧邻图、表等容器,以纯几何方式抑制 caption 误判。"""
-
- for container_bbox in container_bboxes:
- if _bbox_axis_overlap_ratio(line_bbox, container_bbox, axis="x") < 0.35:
- continue
- container_width = max(0.1, container_bbox[2] - container_bbox[0])
- if line_bbox[2] - line_bbox[0] > 0.8 * container_width:
- continue
- vertical_gap = max(line_bbox[1] - container_bbox[3], container_bbox[1] - line_bbox[3], 0.0)
- if vertical_gap <= 2.0 * body_height:
- return True
- return False
-
-
-def _expand_paragraph_title_neighbors(
- lane: _TextLane,
- selected_indices: set[int],
- profile: _LaneBodyProfile,
-) -> None:
- """用相邻行的字体、尺寸、对齐和紧凑净空补齐折行段落标题。"""
- if not selected_indices:
- return
- rows = lane.lines
- lane_width = max(0.1, lane.right - lane.left)
- pending = list(selected_indices)
- while pending:
- selected_index = pending.pop()
- selected_line, selected_bbox = rows[selected_index]
- selected_height = _line_effective_height(selected_line, selected_bbox)
- for candidate_index in (selected_index - 1, selected_index + 1):
- if not 0 <= candidate_index < len(rows) or candidate_index in selected_indices:
- continue
- candidate_line, candidate_bbox = rows[candidate_index]
- if candidate_line.semantic_type is not None:
- continue
- candidate_height = _line_effective_height(candidate_line, candidate_bbox)
- if not 0.75 <= candidate_height / selected_height <= 1.25:
- continue
- if candidate_bbox[2] - candidate_bbox[0] > 0.8 * lane_width:
- continue
- if (
- selected_line.font_signature is not None
- and candidate_line.font_signature is not None
- and selected_line.font_signature != candidate_line.font_signature
- ):
- continue
- if not _title_fonts_compatible(selected_line, candidate_line):
- continue
- vertical_gap = max(
- candidate_bbox[1] - selected_bbox[3],
- selected_bbox[1] - candidate_bbox[3],
- 0.0,
- )
- centers_align = abs(_bbox_center_x(candidate_bbox) - _bbox_center_x(selected_bbox)) <= 0.15 * lane_width
- left_edges_align = abs(candidate_bbox[0] - selected_bbox[0]) <= 0.75 * profile.body_height
- wrapped_indent = abs(candidate_bbox[0] - selected_bbox[0]) <= 2.0 * profile.body_height
- if vertical_gap > 0.65 * profile.body_height or not (centers_align or left_edges_align or wrapped_indent):
- continue
- candidate_line.semantic_type = "paragraph_title"
- selected_indices.add(candidate_index)
- pending.append(candidate_index)
+__all__ = []
diff --git a/tests/unittest/test_flash_pdf_document_profile.py b/tests/unittest/test_flash_pdf_document_profile.py
index df2647b7..aa6b2c2d 100644
--- a/tests/unittest/test_flash_pdf_document_profile.py
+++ b/tests/unittest/test_flash_pdf_document_profile.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from mineru.model.flash.pdf import titles
+from mineru.model.flash.pdf import models, titles
from _flash_pdf_test_utils import _prepared_text_page, _text_line
@@ -173,7 +173,7 @@ def test_document_regular_font_suppresses_code_page_false_title() -> None:
dominant_font_weight=400.0,
),
]
- profile = titles._DocumentBodyProfile(
+ profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({mono_font, regular_font}),
@@ -213,14 +213,14 @@ def test_document_title_profile_promotes_table_adjacent_style_but_not_container_
font_coverage=1.0,
dominant_font_weight=600.0,
)
- body_profile = titles._DocumentBodyProfile(
+ body_profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({("Body", 0)}),
)
- title_profile = titles._DocumentTitleProfile(
+ title_profile = models._DocumentTitleProfile(
(
- titles._TitleStylePrototype(
+ models._TitleStylePrototype(
font_family="heading",
font_flags=0,
height_ratio=1.4,
@@ -268,14 +268,14 @@ def test_document_title_profile_promotes_body_height_centered_section() -> None:
font_coverage=1.0,
dominant_font_weight=400.0,
)
- body_profile = titles._DocumentBodyProfile(
+ body_profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({regular_font}),
)
- title_profile = titles._DocumentTitleProfile(
+ title_profile = models._DocumentTitleProfile(
(
- titles._TitleStylePrototype(
+ models._TitleStylePrototype(
font_family="body",
font_flags=0,
height_ratio=1.0,
@@ -343,7 +343,7 @@ def test_document_title_profile_infers_repeated_large_left_aligned_style() -> No
page_size=(100.0, 100.0),
)
)
- body_profile = titles._DocumentBodyProfile(
+ body_profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({body_font}),
@@ -385,7 +385,7 @@ def test_regular_pitch_style_change_does_not_become_title() -> None:
font_coverage=1.0,
),
]
- profile = titles._DocumentBodyProfile(
+ profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({body_font}),
@@ -431,14 +431,14 @@ def test_title_font_at_body_size_does_not_override_document_size_profile() -> No
font_coverage=1.0,
),
]
- body_profile = titles._DocumentBodyProfile(
+ body_profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({("Body", 0)}),
)
- title_profile = titles._DocumentTitleProfile(
+ title_profile = models._DocumentTitleProfile(
(
- titles._TitleStylePrototype(
+ models._TitleStylePrototype(
font_family="heading",
font_flags=0,
height_ratio=1.4,
@@ -515,7 +515,7 @@ def test_smaller_recurrent_regular_font_does_not_gain_title_style_signal() -> No
dominant_font_weight=400.0,
),
]
- profile = titles._DocumentBodyProfile(
+ profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({body_font, mono_font}),
@@ -575,7 +575,7 @@ def test_document_profile_finds_cover_title_without_promoting_bottom_metadata()
dominant_font_weight=800.0,
),
]
- profile = titles._DocumentBodyProfile(10.0, 400.0, frozenset())
+ profile = models._DocumentBodyProfile(10.0, 400.0, frozenset())
titles._classify_page_titles(
lines,
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index b94233c9..e2d20b4a 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -73,7 +73,7 @@ def test_explicit_section_number_rejects_century_and_decimal_sentence() -> None:
_text_line("0.26 value, continues", (0.0, 96.0, 100.0, 106.0), 5, font_signature=body_font),
_text_line("ordinary body four", (0.0, 108.0, 100.0, 118.0), 6, font_signature=body_font),
]
- profile = titles._DocumentBodyProfile(
+ profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({body_font}),
@@ -172,7 +172,7 @@ def test_noninitial_document_title_requires_paragraph_title_candidate() -> None:
font_signature=body_font,
font_coverage=1.0,
)
- profile = titles._DocumentBodyProfile(
+ profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({body_font}),
@@ -290,7 +290,7 @@ def test_noninitial_document_titles_support_multiple_articles_without_metadata()
page_size=(100.0, 150.0),
),
]
- profile = titles._DocumentBodyProfile(
+ profile = models._DocumentBodyProfile(
body_height=10.0,
body_weight=400.0,
regular_fonts=frozenset({body_font}),
@@ -389,7 +389,7 @@ def test_body_height_section_titles_mark_only_repeated_short_anchors() -> None:
lines,
(100.0, 280.0),
container_bboxes=[(0.0, 128.0, 100.0, 180.0)],
- document_body_profile=titles._DocumentBodyProfile(
+ document_body_profile=models._DocumentBodyProfile(
body_height=10.0,
body_weight=250.0,
regular_fonts=frozenset({body_font}),
@@ -437,7 +437,7 @@ def test_grid_title_suppression_requires_two_distinct_parallel_bands() -> None:
)
source_index += 1
lanes.append(
- titles._TextLane(
+ models._TextLane(
left=left,
right=left + 100.0,
lines=[
@@ -792,7 +792,7 @@ def test_subset_font_visual_row_continues_into_short_body_tail() -> None:
font_coverage=1.0,
)
rows = [(line, line.bbox) for line in (first, second, tail)]
- profile = titles._LaneBodyProfile(
+ profile = models._LaneBodyProfile(
body_height=10.0,
body_font=("ABCDEF+SimSun", 0),
body_weight=400.0,