Skip to content

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

feat: enhance document processing by adding title profile detection and refining image footnote classification

myhloli29ece3132d74
diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.py
index 61b52393..797bcd7a 100644
--- a/mineru/backend/flash/native_pdf/auxiliary_text.py
+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py
@@ -51,6 +51,17 @@ def _classify_page_auxiliary_text(prepared: _PreparedPage) -> None:
"""在容器认领后仅按空间关系标注侧栏文字和页脚注。"""
_classify_aside_text(prepared.remaining_lines, prepared.page_size)
+ _classify_image_footnotes(
+ prepared.remaining_lines,
+ [
+ block["bbox"]
+ for block in prepared.fixed_blocks
+ if block.get("type") == "image"
+ ],
+ prepared.table_bboxes,
+ prepared.drawing_lines,
+ prepared.page_size,
+ )
prepared.page_footnote_groups = _classify_page_footnotes(
prepared.remaining_lines,
prepared.table_bboxes,
@@ -111,6 +122,155 @@ def _geometric_text_support_by_angle(
return support_by_angle
+def _classify_image_footnotes(
+ lines: list[_LineItem],
+ image_bboxes: list[BBox],
+ table_bboxes: list[BBox],
+ drawing_lines: list[_AxisLine],
+ page_size: tuple[float, float],
+) -> None:
+ """用图片、下缘长横线和紧凑小字的联合关系识别图表脚注。"""
+
+ available = [line for line in lines if line.semantic_type is None]
+ if not available or not image_bboxes or not drawing_lines:
+ return
+ support_by_angle = _geometric_text_support_by_angle(available, page_size)
+ if not support_by_angle:
+ return
+ dominant_angle = max(
+ sorted(support_by_angle),
+ key=lambda angle: support_by_angle[angle],
+ )
+ local_page_size = (
+ (page_size[1], page_size[0])
+ if dominant_angle in {90, 270}
+ else page_size
+ )
+ local_page_width, local_page_height = local_page_size
+ if local_page_width <= 0 or local_page_height <= 0:
+ return
+
+ line_geometry = sorted(
+ [
+ (line, _rotate_bbox_to_upright(line.bbox, page_size, dominant_angle))
+ for line in available
+ if line.angle == dominant_angle
+ ],
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ if not line_geometry:
+ return
+ body_samples = [
+ _line_effective_height(line, bbox)
+ for line, bbox in line_geometry
+ if bbox[2] - bbox[0] >= 0.2 * local_page_width
+ ]
+ if not body_samples:
+ body_samples = [
+ _line_effective_height(line, bbox)
+ for line, bbox in line_geometry
+ ]
+ body_height = max(0.1, statistics.median(body_samples))
+ local_images = [
+ _rotate_bbox_to_upright(bbox, page_size, dominant_angle)
+ for bbox in image_bboxes
+ ]
+ local_axis_lines = _transform_axis_lines(
+ drawing_lines,
+ page_size,
+ dominant_angle,
+ )
+
+ matched_source_indices: set[int] = set()
+ for image_bbox in local_images:
+ image_width = max(0.1, image_bbox[2] - image_bbox[0])
+ # 同一视觉行的并排图可能高度略有差异;共享较低下缘可避免把留白误作远距。
+ row_bottom = max(
+ peer_bbox[3]
+ for peer_bbox in local_images
+ if _bbox_axis_overlap_ratio(image_bbox, peer_bbox, axis="y") >= 0.5
+ )
+ candidate_rules = [
+ axis_line
+ for axis_line in local_axis_lines
+ if axis_line.orientation == "horizontal"
+ and 0.75 * image_width
+ <= axis_line.bbox[2] - axis_line.bbox[0]
+ <= 1.3 * image_width
+ and max(
+ 0.0,
+ min(axis_line.bbox[2], image_bbox[2])
+ - max(axis_line.bbox[0], image_bbox[0]),
+ )
+ >= 0.85 * image_width
+ and -0.25 * body_height
+ <= axis_line.bbox[1] - row_bottom
+ <= max(0.01 * local_page_height, 0.75 * body_height)
+ and not _rule_belongs_to_confirmed_table(
+ axis_line,
+ local_axis_lines,
+ table_bboxes,
+ local_page_width,
+ )
+ ]
+ if not candidate_rules:
+ continue
+ rule = min(
+ candidate_rules,
+ key=lambda item: (max(0.0, item.bbox[1] - row_bottom), item.bbox[1]),
+ )
+ matched_source_indices.update(
+ _image_footnote_members(
+ line_geometry,
+ rule.bbox,
+ body_height,
+ local_page_height,
+ )
+ )
+
+ for line in available:
+ if line.source_index in matched_source_indices:
+ line.semantic_type = "footnote"
+
+
+def _image_footnote_members(
+ line_geometry: list[tuple[_LineItem, BBox]],
+ rule_bbox: BBox,
+ body_height: float,
+ local_page_height: float,
+) -> set[int]:
+ """返回长横线下方、位于同一水平走廊内的连续小字号文本行。"""
+
+ first_gap_limit = max(0.025 * local_page_height, 2.0 * body_height)
+ horizontal_tolerance = 0.5 * body_height
+ candidates = [
+ item
+ for item in line_geometry
+ if -0.25 * body_height <= item[1][1] - rule_bbox[3] <= first_gap_limit
+ and item[1][0] >= rule_bbox[0] - horizontal_tolerance
+ and item[1][2] <= rule_bbox[2] + horizontal_tolerance
+ and _line_effective_height(*item) <= 0.9 * body_height
+ ]
+ if not candidates:
+ return set()
+ first = min(candidates, key=lambda item: (item[1][1], item[1][0]))
+ members = [first]
+ continuation_gap_limit = max(1.25 * _line_effective_height(*first), 0.01 * local_page_height)
+ for current in line_geometry:
+ if current[0] is first[0] or current[1][1] < first[1][1]:
+ continue
+ if current[1][0] < rule_bbox[0] - horizontal_tolerance:
+ continue
+ if current[1][2] > rule_bbox[2] + horizontal_tolerance:
+ continue
+ if _line_effective_height(*current) > 0.95 * body_height:
+ continue
+ if _effective_text_row_gap(members[-1], current) > continuation_gap_limit:
+ break
+ members.append(current)
+ return {line.source_index for line, _bbox in members}
+
+
def _classify_page_footnotes(
lines: list[_LineItem],
table_bboxes: list[BBox],
diff --git a/mineru/backend/flash/native_pdf/code_blocks.py b/mineru/backend/flash/native_pdf/code_blocks.py
new file mode 100644
index 00000000..7b6727da
--- /dev/null
+++ b/mineru/backend/flash/native_pdf/code_blocks.py
@@ -0,0 +1,383 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""识别带填充背景的等宽代码区域并投影其空间文本。"""
+
+from __future__ import annotations
+
+import math
+import statistics
+import unicodedata
+from typing import Any
+
+from mineru.backend.hybrid.table_text import project_pdf_spatial_text
+from mineru.types import BBox
+from mineru.utils.pdf_document import PDFPathInfo
+
+from .geometry import (
+ _bbox_area,
+ _bbox_center_x,
+ _bbox_center_y,
+ _bbox_overlap_in_first,
+ _bbox_overlap_in_smaller,
+)
+from .models import _CodeCandidate, _LineItem, _PageSource
+from .native_text import _sanitize_pdf_control_text
+
+
+_MONOSPACE_FONT_HINTS = (
+ "mono",
+ "courier",
+ "consolas",
+ "menlo",
+ "typewriter",
+ "fixed",
+ "code",
+)
+
+
+def _build_code_blocks(
+ source: _PageSource,
+ excluded_bboxes: list[BBox],
+ claimed_line_indices: set[int],
+) -> tuple[list[dict[str, Any]], set[int]]:
+ """检测代码背景、唯一认领其文本,并输出页内 code block。"""
+
+ candidates = _detect_code_candidates(
+ source,
+ excluded_bboxes,
+ claimed_line_indices,
+ )
+ if not candidates:
+ return [], set()
+ lines_by_index = {line.source_index: line for line in source.lines}
+ blocks: list[dict[str, Any]] = []
+ claimed: set[int] = set()
+ for candidate in candidates:
+ members = [
+ lines_by_index[source_index]
+ for source_index in sorted(candidate.line_indices)
+ if source_index in lines_by_index
+ ]
+ if not members:
+ continue
+ content = project_pdf_spatial_text(
+ _code_member_chars(members),
+ candidate.bbox,
+ candidate.angle,
+ preserve_blank_rows=True,
+ )
+ if not content:
+ content = _fallback_code_content(members)
+ if not content:
+ continue
+ blocks.append(
+ {
+ "type": "code",
+ "bbox": candidate.bbox,
+ "angle": candidate.angle,
+ "content": content,
+ }
+ )
+ claimed.update(candidate.line_indices)
+ blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))
+ return blocks, claimed
+
+
+def _code_member_chars(lines: list[_LineItem]) -> list[dict[str, Any]]:
+ """按 char_idx 去重代码成员字符,避免区域内斜向水印混入空间投影。"""
+
+ output: list[dict[str, Any]] = []
+ seen: set[tuple[str, int]] = set()
+ for line in lines:
+ for fallback_index, char in enumerate(line.chars):
+ if not isinstance(char, dict):
+ continue
+ try:
+ identity = ("source", int(char.get("char_idx")))
+ except (TypeError, ValueError):
+ identity = ("fallback", fallback_index + line.source_index * 1_000_000)
+ if identity in seen:
+ continue
+ seen.add(identity)
+ output.append(char)
+ return output
+
+
+def _detect_code_candidates(
+ source: _PageSource,
+ excluded_bboxes: list[BBox],
+ claimed_line_indices: set[int],
+) -> list[_CodeCandidate]:
+ """以非白填充矩形、等宽字体和规则空间栅格筛选代码候选。"""
+
+ page_width, page_height = source.page_size
+ page_area = max(0.0, page_width) * max(0.0, page_height)
+ if page_area <= 0 or not source.path_infos:
+ return []
+ raw_candidates: list[_CodeCandidate] = []
+ for path_info in source.path_infos:
+ bbox = path_info.bbox
+ width = bbox[2] - bbox[0]
+ height = bbox[3] - bbox[1]
+ if (
+ path_info.form_depth != 0
+ or not path_info.fill_visible
+ or path_info.segment_count < 4
+ or not _path_has_visible_nonwhite_fill(path_info)
+ or width < 0.5 * page_width
+ or height < 0.008 * page_height
+ or _bbox_area(bbox) >= 0.8 * page_area
+ or any(
+ _bbox_overlap_in_smaller(bbox, excluded_bbox) >= 0.5
+ for excluded_bbox in excluded_bboxes
+ )
+ ):
+ continue
+ members = [
+ line
+ for line in source.lines
+ if line.source_index not in claimed_line_indices
+ and _bbox_overlap_in_first(line.bbox, bbox) >= 0.8
+ ]
+ if not members:
+ continue
+ dominant_angle = _dominant_code_angle(members)
+ angle_members = [line for line in members if line.angle == dominant_angle]
+ total_support = sum(_estimated_line_character_count(line) for line in members)
+ angle_support = sum(
+ _estimated_line_character_count(line)
+ for line in angle_members
+ )
+ if total_support <= 0 or angle_support / total_support < 0.8:
+ continue
+ monospace_ratio, cell_widths = _monospace_character_support(angle_members)
+ if monospace_ratio < 0.8 or not _monospace_advances_are_stable(cell_widths):
+ continue
+ median_cell_width = statistics.median(
+ width_value
+ for values in cell_widths.values()
+ for width_value in values
+ )
+ if not _code_rows_have_spatial_structure(
+ angle_members,
+ bbox,
+ median_cell_width,
+ ):
+ continue
+ raw_candidates.append(
+ _CodeCandidate(
+ bbox=bbox,
+ angle=dominant_angle,
+ line_indices={line.source_index for line in angle_members},
+ )
+ )
+
+ accepted: list[_CodeCandidate] = []
+ for candidate in sorted(raw_candidates, key=lambda item: _bbox_area(item.bbox)):
+ if any(
+ _bbox_overlap_in_smaller(candidate.bbox, existing.bbox) >= 0.9
+ for existing in accepted
+ ):
+ continue
+ accepted.append(candidate)
+ return sorted(accepted, key=lambda item: (item.bbox[1], item.bbox[0]))
+
+
+def _path_has_visible_nonwhite_fill(path_info: PDFPathInfo) -> bool:
+ """检查填充色是否可见且与白色背景存在最小颜色差。"""
+
+ if path_info.fill_rgba is None:
+ return False
+ red, green, blue, alpha = path_info.fill_rgba
+ return alpha > 0 and max(255 - red, 255 - green, 255 - blue) >= 5
+
+
+def _dominant_code_angle(lines: list[_LineItem]) -> int:
+ """按估算字符数选择代码区域的主文本方向。"""
+
+ support: dict[int, float] = {}
+ for line in lines:
+ support[line.angle] = support.get(line.angle, 0.0) + _estimated_line_character_count(line)
+ return max(sorted(support), key=lambda angle: support[angle])
+
+
+def _estimated_line_character_count(line: _LineItem) -> float:
+ """优先按字符对象计数,缺失时用行宽和缓存字宽估算字符支持。"""
+
+ valid_chars = [
+ char
+ for char in line.chars
+ if isinstance(char, dict) and str(char.get("char") or "").strip()
+ ]
+ if valid_chars:
+ return float(len(valid_chars))
+ line_width = max(0.1, line.bbox[2] - line.bbox[0])
+ glyph_width = max(0.1, line.median_glyph_width or line_width)
+ return max(1.0, line_width / glyph_width)
+
+
+def _font_name_looks_monospaced(name: str | None) -> bool:
+ """按字体元数据中的通用等宽提示判断字体族,不匹配文档内容。"""
+
+ normalized = (name or "").replace("-", "").replace("_", "").casefold()
+ return any(hint in normalized for hint in _MONOSPACE_FONT_HINTS)
+
+
+def _monospace_character_support(
+ lines: list[_LineItem],
+) -> tuple[float, dict[str, list[float]]]:
+ """统计等宽字体字符占比,并按东西文宽度组收集字符 advance。"""
+
+ supported = 0.0
+ total = 0.0
+ widths: dict[str, list[float]] = {"narrow": [], "wide": []}
+ for line in lines:
+ fallback_monospace = _font_name_looks_monospaced(
+ line.font_signature[0] if line.font_signature is not None else None
+ )
+ for char in line.chars:
+ if not isinstance(char, dict):
+ continue
+ value = str(char.get("char") or "")
+ if not value.strip():
+ continue
+ total += 1.0
+ font = char.get("font")
+ font_name = font.get("name") if isinstance(font, dict) else None
+ if _font_name_looks_monospaced(font_name) or fallback_monospace:
+ supported += 1.0
+ try:
+ x0, _y0, x1, _y1 = [float(item) for item in char.get("bbox", [])]
+ except (TypeError, ValueError):
+ continue
+ width = x1 - x0
+ if not math.isfinite(width) or width <= 0.1:
+ continue
+ width_group = (
+ "wide"
+ if unicodedata.east_asian_width(value[0]) in {"W", "F"}
+ else "narrow"
+ )
+ widths[width_group].append(width)
+
+ if total <= 0:
+ fallback_support = sum(_estimated_line_character_count(line) for line in lines)
+ if fallback_support <= 0:
+ return 0.0, widths
+ supported_support = sum(
+ _estimated_line_character_count(line)
+ for line in lines
+ if _font_name_looks_monospaced(
+ line.font_signature[0]
+ if line.font_signature is not None
+ else None
+ )
+ )
+ fallback_widths = [
+ line.median_glyph_width
+ for line in lines
+ if line.median_glyph_width is not None
+ and line.median_glyph_width > 0
+ ]
+ widths["narrow"].extend(fallback_widths)
+ return supported_support / fallback_support, widths
+ return supported / total, widths
+
+
+def _monospace_advances_are_stable(
+ widths: dict[str, list[float]],
+) -> bool:
+ """验证各字符宽度组的中位绝对偏差足够小,并校验中西文宽度关系。"""
+
+ populated = [values for values in widths.values() if values]
+ if not populated or sum(len(values) for values in populated) < 3:
+ return False
+ medians: dict[str, float] = {}
+ for group_name, values in widths.items():
+ if not values:
+ continue
+ median_width = statistics.median(values)
+ mad = statistics.median(abs(value - median_width) for value in values)
+ if mad / max(0.1, median_width) > 0.2:
+ return False
+ medians[group_name] = median_width
+ if "narrow" in medians and "wide" in medians:
+ ratio = medians["wide"] / medians["narrow"]
+ if not 1.25 <= ratio <= 2.25:
+ return False
+ return True
+
+
+def _code_rows_have_spatial_structure(
+ lines: list[_LineItem],
+ candidate_bbox: BBox,
+ median_cell_width: float,
+) -> bool:
+ """验证代码行具有规则基线,并且左缘落在一致的等宽字符槽。"""
+
+ rows: list[list[_LineItem]] = []
+ for line in sorted(lines, key=lambda item: (_bbox_center_y(item.bbox), item.bbox[0])):
+ target = next(
+ (
+ row
+ for row in rows
+ if any(
+ min(member.bbox[3], line.bbox[3])
+ - max(member.bbox[1], line.bbox[1])
+ >= 0.5
+ * min(
+ member.bbox[3] - member.bbox[1],
+ line.bbox[3] - line.bbox[1],
+ )
+ for member in row
+ )
+ ),
+ None,
+ )
+ if target is None:
+ rows.append([line])
+ else:
+ target.append(line)
+ if not rows:
+ return False
+
+ residuals = []
+ for line in lines:
+ slot = (line.bbox[0] - candidate_bbox[0]) / max(0.1, median_cell_width)
+ residuals.append(abs(slot - round(slot)))
+ if sum(residual <= 0.35 for residual in residuals) / len(residuals) < 0.8:
+ return False
+ if len(rows) == 1:
+ return True
+
+ row_tops = sorted(min(line.bbox[1] for line in row) for row in rows)
+ deltas = [
+ current - previous
+ for previous, current in zip(row_tops, row_tops[1:])
+ if current > previous
+ ]
+ if not deltas:
+ return False
+ lower_count = max(1, math.ceil(0.6 * len(deltas)))
+ base_pitch = statistics.median(sorted(deltas)[:lower_count])
+ if base_pitch <= 0:
+ return False
+ return all(
+ abs(delta / base_pitch - round(delta / base_pitch)) <= 0.35
+ for delta in deltas
+ )
+
+
+def _fallback_code_content(lines: list[_LineItem]) -> str:
+ """空间投影失败时按视觉行和水平位置保留代码文本的最小结构。"""
+
+ ordered = sorted(
+ lines,
+ key=lambda line: (
+ round(_bbox_center_y(line.bbox), 1),
+ _bbox_center_x(line.bbox),
+ line.source_index,
+ ),
+ )
+ content = "\n".join(line.text for line in ordered if line.text)
+ return _sanitize_pdf_control_text(content, preserve_newlines=True).strip()
diff --git a/mineru/backend/flash/native_pdf/line_layout.py b/mineru/backend/flash/native_pdf/line_layout.py
index 6bbe62d0..3a00912a 100644
--- a/mineru/backend/flash/native_pdf/line_layout.py
+++ b/mineru/backend/flash/native_pdf/line_layout.py
@@ -539,6 +539,11 @@ def _reattach_span_lane_continuations(
return
for span_lane in span_lanes:
+ _reattach_repeated_indented_span_tails(
+ span_lane,
+ regular_lanes,
+ median_height,
+ )
while True:
span_lane.lines.sort(
key=lambda item: (item[1][1], item[1][0], item[0].source_index)
@@ -623,6 +628,78 @@ def _reattach_span_lane_continuations(
)
+def _reattach_repeated_indented_span_tails(
+ span_lane: _TextLane,
+ regular_lanes: list[_TextLane],
+ median_height: float,
+) -> None:
+ """识别重复的跨栏首行与缩进短尾,并把短尾统一迁回跨栏栏带。"""
+
+ span_rows = sorted(
+ span_lane.lines,
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index),
+ )
+ matches: list[
+ tuple[_TextLane, tuple[_LineItem, BBox], tuple[_LineItem, BBox], float]
+ ] = []
+ for span_index, span_row in enumerate(span_rows):
+ span_line, span_bbox = span_row
+ next_span_top = (
+ span_rows[span_index + 1][1][1]
+ if span_index + 1 < len(span_rows)
+ else float("inf")
+ )
+ for regular_lane in regular_lanes:
+ for candidate in regular_lane.lines:
+ candidate_line, candidate_bbox = candidate
+ if candidate_line.semantic_type != span_line.semantic_type:
+ continue
+ gap = _effective_text_row_gap(span_row, candidate)
+ indent = candidate_bbox[0] - span_bbox[0]
+ span_height = _line_effective_height(*span_row)
+ candidate_height = _line_effective_height(*candidate)
+ if (
+ candidate_bbox[1] <= span_bbox[1]
+ or candidate_bbox[1] >= next_span_top
+ or not -0.25 * median_height <= gap <= 0.75 * median_height
+ or not 0.75 * median_height <= indent <= 6.0 * median_height
+ or max(span_height, candidate_height)
+ / min(span_height, candidate_height)
+ > 1.35
+ or not _title_fonts_compatible(span_line, candidate_line)
+ ):
+ continue
+ has_parallel_peer = any(
+ other_line is not candidate_line
+ and _bbox_axis_overlap_ratio(candidate_bbox, other_bbox, axis="y") >= 0.5
+ for lane in regular_lanes
+ for other_line, other_bbox in lane.lines
+ )
+ if not has_parallel_peer:
+ matches.append((regular_lane, candidate, span_row, indent))
+
+ if len(matches) < 2:
+ return
+ median_indent = statistics.median(match[3] for match in matches)
+ supported = [
+ match
+ for match in matches
+ if abs(match[3] - median_indent) <= max(0.75 * median_height, 0.25 * median_indent)
+ ]
+ if len(supported) < 2:
+ return
+ for regular_lane, candidate, _span_row, _indent in supported:
+ if candidate not in regular_lane.lines:
+ continue
+ regular_lane.lines.remove(candidate)
+ span_lane.lines.append(candidate)
+ span_lane.left = min(span_lane.left, candidate[1][0])
+ span_lane.right = max(span_lane.right, candidate[1][2])
+ span_lane.lines.sort(
+ key=lambda item: (item[1][1], item[1][0], item[0].source_index)
+ )
+
+
def _estimate_lane_gap(lane: _TextLane) -> tuple[float, float]:
"""从栏带内兼容相邻行的较小间隙簇估计常规净空和 MAD。"""
@@ -774,6 +851,27 @@ def _should_connect_text_rows(
or _font_weights_conflict(previous_line, current_line)
)
)
+ fallback_font_continuation = (
+ previous_line.font_signature is not None
+ and current_line.font_signature is not None
+ and previous_line.font_coverage >= 0.75
+ and current_line.font_coverage >= 0.75
+ and previous_line.font_signature[0] != current_line.font_signature[0]
+ and previous_line.font_signature[1] == current_line.font_signature[1]
+ and aligned_left_edges
+ and height_ratio <= 1.25
+ and not _font_weights_conflict(previous_line, current_line)
+ and -0.25 * pair_height
+ <= vertical_gap
+ <= regular_gap + max(0.35 * pair_height, 3.0 * gap_mad)
+ )
+ if (
+ font_style_changed
+ and _font_weights_conflict(previous_line, current_line)
+ and not fallback_font_continuation
+ ):
+ # 显式样式位与显著字重同时变化仍是硬边界,不能被满栏几何放宽。
+ return False
if (
not is_hyphen_at_line_end(previous_line.text)
and _is_structural_typography_gap(
@@ -784,6 +882,7 @@ def _should_connect_text_rows(
gap_mad,
reliable_style_change=reliable_style_conflict,
)
+ and not fallback_font_continuation
):
# 图注到正文等排版层级转换即使同栏满行,也不能被常规续行规则重新吸收。
return False
@@ -839,6 +938,7 @@ def _should_connect_text_rows(
and (abnormal_gap or min(previous_width, current_width) <= 0.7 * lane_width)
and not both_fill_lane
and not safe_short_tail
+ and not fallback_font_continuation
):
return False
if (
diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.py
index c3ede64f..08125fe7 100644
--- a/mineru/backend/flash/native_pdf/models.py
+++ b/mineru/backend/flash/native_pdf/models.py
@@ -98,6 +98,15 @@ class _GraphicCandidate:
line_indices: set[int] = field(default_factory=set)
+@dataclass(slots=True)
+class _CodeCandidate:
+ """保存由浅色填充背景与等宽文本共同确认的代码区域。"""
+
+ bbox: BBox
+ angle: int
+ line_indices: set[int] = field(default_factory=set)
+
+
@dataclass(slots=True)
class _TextLane:
"""保存同一文本方向下的局部栏带与已归属文本行。"""
@@ -164,6 +173,7 @@ class _LaneBodyProfile:
body_weight: float | None
regular_gap: float
style_support: dict[tuple[str, int], float]
+ body_row_count: int = 0
@dataclass(frozen=True, slots=True)
@@ -173,3 +183,24 @@ class _DocumentBodyProfile:
body_height: float
body_weight: float | None
regular_fonts: frozenset[tuple[str, int]]
+
+
+@dataclass(frozen=True, slots=True)
+class _TitleStylePrototype:
+ """保存跨页标题原型的字体、尺度、字重和栏内对齐特征。"""
+
+ font_family: str
+ font_flags: int
+ height_ratio: float
+ weight: float | None
+ alignment: Literal["left", "center"]
+ anchor_offset: float
+ support_count: int
+ support_pages: int
+
+
+@dataclass(frozen=True, slots=True)
+class _DocumentTitleProfile:
+ """保存全文中由重复高置信标题形成的排版原型集合。"""
+
+ prototypes: tuple[_TitleStylePrototype, ...]
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 0d4cbc46..d359d5af 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -12,6 +12,7 @@ from mineru.utils.pdf_document import PDFDocument, PDFImageInfo, get_lines_from_
from .models import (
_DocumentBodyProfile,
+ _DocumentTitleProfile,
_LineItem,
_PageSource,
_PreparedPage,
@@ -58,6 +59,7 @@ from .formulas import (
_build_formula_like_blocks,
_build_vector_formula_blocks,
)
+from .code_blocks import _build_code_blocks
from .auxiliary_text import (
_classify_isolated_first_page_footer,
_classify_page_number_outer_companions,
@@ -70,11 +72,13 @@ from .auxiliary_text import (
from .titles import (
_classify_page_titles,
_infer_document_body_profile,
+ _infer_document_title_profile,
)
from .text_blocks import (
_build_text_blocks,
_merge_fragmented_header_blocks,
_merge_image_caption_text_blocks,
+ _merge_repeated_compact_title_continuations,
)
@@ -84,13 +88,14 @@ _TEXT_SEMANTIC_TYPES = {
"header",
"footer",
"page_number",
+ "footnote",
"page_footnote",
"aside_text",
"index",
}
-_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation"} | _TEXT_SEMANTIC_TYPES
+_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation", "code"} | _TEXT_SEMANTIC_TYPES
_REPEATED_RASTER_IMAGE_MIN_PAGE_AREA_RATIO = 0.08
_REPEATED_RASTER_IMAGE_MIN_DISTINCT_PAGES = 3
@@ -202,11 +207,16 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
_classify_page_number_outer_companions(prepared_pages)
_classify_isolated_first_page_footer(prepared_pages)
document_body_profile = _infer_document_body_profile(prepared_pages)
+ document_title_profile = _infer_document_title_profile(
+ prepared_pages,
+ document_body_profile,
+ )
return [
_finalize_prepared_page(
prepared,
page_index,
document_body_profile=document_body_profile,
+ document_title_profile=document_title_profile,
)
for page_index, prepared in enumerate(prepared_pages)
]
@@ -242,32 +252,51 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
for table_bbox in table_bboxes
)
]
+ code_blocks, claimed_code_line_indices = _build_code_blocks(
+ source,
+ table_bboxes
+ + active_form_bboxes
+ + strong_graphic_bboxes
+ + list(source.image_bboxes)
+ + list(source.signature_bboxes),
+ claimed_line_indices,
+ )
+ code_bboxes = [block["bbox"] for block in code_blocks]
form_image_blocks, claimed_form_line_indices = _build_form_image_blocks(
source,
active_form_bboxes,
- claimed_line_indices,
+ claimed_line_indices | claimed_code_line_indices,
)
graphic_blocks, claimed_graphic_line_indices = _build_graphic_like_blocks(
source,
- table_bboxes + active_form_bboxes,
- claimed_line_indices | claimed_form_line_indices,
+ table_bboxes + active_form_bboxes + code_bboxes,
+ claimed_line_indices | claimed_code_line_indices | claimed_form_line_indices,
strong_graphic_bboxes,
)
raster_image_blocks, claimed_raster_line_indices = _build_raster_image_blocks(
source,
- table_blocks + form_image_blocks + graphic_blocks,
- claimed_line_indices | claimed_form_line_indices | claimed_graphic_line_indices,
+ table_blocks + code_blocks + form_image_blocks + graphic_blocks,
+ claimed_line_indices
+ | claimed_code_line_indices
+ | claimed_form_line_indices
+ | claimed_graphic_line_indices,
)
vector_formula_blocks, claimed_vector_number_indices = _build_vector_formula_blocks(
source,
- table_blocks + form_image_blocks + graphic_blocks + raster_image_blocks,
+ table_blocks
+ + code_blocks
+ + form_image_blocks
+ + graphic_blocks
+ + raster_image_blocks,
claimed_line_indices
+ | claimed_code_line_indices
| claimed_form_line_indices
| claimed_graphic_line_indices
| claimed_raster_line_indices,
)
claimed_line_indices = (
claimed_line_indices
+ | claimed_code_line_indices
| claimed_form_line_indices
| claimed_graphic_line_indices
| claimed_raster_line_indices
@@ -291,6 +320,7 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
drawing_lines=source.drawing_lines,
fixed_blocks=(
table_blocks
+ + code_blocks
+ form_image_blocks
+ graphic_blocks
+ raster_image_blocks
@@ -318,6 +348,7 @@ def _finalize_prepared_page(
page_index: int,
*,
document_body_profile: _DocumentBodyProfile | None = None,
+ document_title_profile: _DocumentTitleProfile | None = None,
) -> list[dict[str, Any]]:
"""按预分类语义、公式、标题、正文的优先级完成单页文本并排序。"""
@@ -373,6 +404,7 @@ def _finalize_prepared_page(
page_index=page_index,
container_bboxes=title_container_bboxes,
document_body_profile=document_body_profile,
+ document_title_profile=document_title_profile,
)
remaining_lines = _merge_title_resolved_visual_rows(
remaining_lines,
@@ -399,6 +431,10 @@ def _finalize_prepared_page(
],
)
text_blocks = _merge_fragmented_header_blocks(text_blocks)
+ text_blocks = _merge_repeated_compact_title_continuations(
+ text_blocks,
+ prepared.page_size,
+ )
absolute_blocks = (
prepared.fixed_blocks + formula_blocks + index_blocks + text_blocks
)
diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.py
index e32cf065..180614ae 100644
--- a/mineru/backend/flash/native_pdf/text_blocks.py
+++ b/mineru/backend/flash/native_pdf/text_blocks.py
@@ -78,7 +78,7 @@ def _build_hanging_indent_group_map(
) -> dict[int, int]:
"""仅按重复的左突首行和稳定续行缩进识别悬挂缩进条目。"""
- if lane.is_span or len(lane.lines) < 4:
+ if len(lane.lines) < 4:
return {}
rows = sorted(
(item for item in lane.lines if item[0].semantic_type is None),
@@ -101,7 +101,16 @@ def _build_hanging_indent_group_map(
"""检查相邻行的净空和几何障碍是否允许组成同一缩进序列。"""
effective_gap = _effective_text_row_gap(previous, current)
- if not -0.6 * median_height <= effective_gap <= 1.3 * median_height:
+ 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,
@@ -1138,6 +1147,97 @@ def _merge_fragmented_header_blocks(
]
+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],
diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.py
index 35befe99..43b883b1 100644
--- a/mineru/backend/flash/native_pdf/titles.py
+++ b/mineru/backend/flash/native_pdf/titles.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import statistics
+from dataclasses import replace
from typing import Literal
@@ -12,10 +13,12 @@ from mineru.types import BBox
from .models import (
_DocumentBodyProfile,
+ _DocumentTitleProfile,
_LaneBodyProfile,
_LineItem,
_PreparedPage,
_TextLane,
+ _TitleStylePrototype,
)
from .geometry import (
_bbox_axis_overlap_ratio,
@@ -31,6 +34,7 @@ from .line_layout import (
_font_weights_conflict,
_infer_text_lanes,
_line_effective_height,
+ _normalized_font_family,
_should_connect_semantic_rows,
_title_fonts_compatible,
)
@@ -48,6 +52,7 @@ def _classify_page_titles(
page_index: int,
container_bboxes: list[BBox],
document_body_profile: _DocumentBodyProfile | None = None,
+ document_title_profile: _DocumentTitleProfile | None = None,
) -> None:
"""只用页面几何与字体排版标注首页文档标题和各页段落标题。"""
@@ -102,6 +107,7 @@ def _classify_page_titles(
_classify_paragraph_titles_in_lane(
lane,
profile,
+ local_page_width,
local_page_height,
local_container_bboxes,
document_title_bottom=document_title_bottom,
@@ -109,6 +115,7 @@ def _classify_page_titles(
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,
)
@@ -225,6 +232,241 @@ def _infer_document_body_profile(
)
+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],
@@ -416,6 +658,7 @@ def _infer_lane_body_profile(lane: _TextLane) -> _LaneBodyProfile:
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),
)
@@ -573,6 +816,7 @@ def _document_title_uses_page_fallback(
def _classify_paragraph_titles_in_lane(
lane: _TextLane,
profile: _LaneBodyProfile,
+ local_page_width: float,
local_page_height: float,
container_bboxes: list[BBox],
*,
@@ -581,6 +825,7 @@ def _classify_paragraph_titles_in_lane(
physical_gaps: dict[int, tuple[float | None, float | None]],
grid_title_suppressions: set[int],
document_body_profile: _DocumentBodyProfile | None,
+ document_title_profile: _DocumentTitleProfile | None,
page_index: int,
) -> None:
"""以字号、样式、留白、对齐、栏宽和容器邻接判定段落标题。"""
@@ -614,10 +859,38 @@ def _classify_paragraph_titles_in_lane(
):
# 首页底部短行通常是版本、日期等封面元数据,不属于正文标题层级。
continue
- if _line_near_visual_container(bbox, container_bboxes, profile.body_height):
+ 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
- line_height = _line_effective_height(line, bbox)
recurrent_regular_font = _line_uses_document_regular_font(
line,
document_body_profile,
@@ -628,6 +901,11 @@ def _classify_paragraph_titles_in_lane(
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,
@@ -637,6 +915,12 @@ def _classify_paragraph_titles_in_lane(
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
@@ -677,6 +961,9 @@ def _classify_paragraph_titles_in_lane(
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):
@@ -730,6 +1017,69 @@ def _classify_paragraph_titles_in_lane(
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
@@ -848,6 +1198,145 @@ def _line_uses_document_regular_font(
)
+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,
@@ -1238,7 +1727,7 @@ def _line_near_visual_container(
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 <= 1.5 * body_height:
+ if vertical_gap <= 2.0 * body_height:
return True
return False
diff --git a/mineru/backend/hybrid/table_text.py b/mineru/backend/hybrid/table_text.py
index 0d7e77b1..2181eed8 100644
--- a/mineru/backend/hybrid/table_text.py
+++ b/mineru/backend/hybrid/table_text.py
@@ -351,8 +351,12 @@ def _trim_projected_lines(lines: list[str]) -> str:
return "\n".join(trimmed_lines)
-def _project_spatial_items(items: list[_SpatialTextItem]) -> str:
- """把空间文本项投影到等宽字符网格,生成保留列关系的多行纯文本。"""
+def _project_spatial_items(
+ items: list[_SpatialTextItem],
+ *,
+ preserve_blank_rows: bool = False,
+) -> str:
+ """把空间文本项投影到等宽字符网格,并按需保留明显的空白行。"""
valid_items = [
item
for item in items
@@ -362,8 +366,21 @@ def _project_spatial_items(items: list[_SpatialTextItem]) -> str:
return ""
median_width, median_height = _compute_text_grid_size(valid_items)
+ spatial_lines = _form_spatial_lines(valid_items, median_width, median_height)
projected_lines: list[str] = []
- for line in _form_spatial_lines(valid_items, median_width, median_height):
+ previous_bottom: float | None = None
+ for line in spatial_lines:
+ line_top = min(item.bbox[1] for item in line)
+ if (
+ preserve_blank_rows
+ and previous_bottom is not None
+ and line_top - previous_bottom > 1.25 * median_height
+ ):
+ blank_count = max(
+ 1,
+ round((line_top - previous_bottom) / median_height) - 1,
+ )
+ projected_lines.extend("" for _ in range(blank_count))
projected_line = ""
for item in line:
target_column = max(0, round(item.bbox[0] / median_width))
@@ -374,15 +391,32 @@ def _project_spatial_items(items: list[_SpatialTextItem]) -> str:
projected_line += " " * (target_column - len(projected_line))
projected_line += item.text
projected_lines.append(projected_line)
+ previous_bottom = max(item.bbox[3] for item in line)
return _trim_projected_lines(projected_lines)
-def project_pdf_table_text(chars: list[Char], table_bbox: BBox, angle: int = 0) -> str:
- """从 PDF 原生字符中提取指定表格,并返回空间投影纯文本。"""
- normalized_bbox = _coerce_bbox(table_bbox)
+def project_pdf_spatial_text(
+ chars: list[Char],
+ region_bbox: BBox,
+ angle: int = 0,
+ *,
+ preserve_blank_rows: bool = False,
+) -> str:
+ """从 PDF 指定区域提取字符,并返回可选保留空行的空间投影文本。"""
+
+ normalized_bbox = _coerce_bbox(region_bbox)
if normalized_bbox is None:
return ""
- return _project_spatial_items(_build_pdf_spatial_items(chars, normalized_bbox, angle))
+ return _project_spatial_items(
+ _build_pdf_spatial_items(chars, normalized_bbox, angle),
+ preserve_blank_rows=preserve_blank_rows,
+ )
+
+
+def project_pdf_table_text(chars: list[Char], table_bbox: BBox, angle: int = 0) -> str:
+ """从 PDF 原生字符中提取指定表格,并返回空间投影纯文本。"""
+
+ return project_pdf_spatial_text(chars, table_bbox, angle)
def project_ocr_table_text(ocr_result: Any, table_size: tuple[int, int]) -> str:
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index c78c3b71..6eadf818 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -88,6 +88,7 @@ class PDFPathInfo:
stroke_visible: bool
form_depth: int
source_index: int
+ fill_rgba: tuple[int, int, int, int] | None = None
@dataclass(frozen=True)
@@ -706,8 +707,12 @@ def _iter_raw_root_form_objects(page: pdfium.PdfPage) -> Iterator[Any]:
continue
-def _get_raw_object_alpha(raw_obj: Any, color_getter: Any) -> int:
- """读取对象颜色 alpha;旧 PDFium 或读取失败时按不透明处理。"""
+def _get_raw_object_rgba(
+ raw_obj: Any,
+ color_getter: Any,
+) -> tuple[int, int, int, int] | None:
+ """读取对象 RGBA;旧 PDFium、不支持的对象或读取失败时返回 None。"""
+
red = ctypes.c_uint()
green = ctypes.c_uint()
blue = ctypes.c_uint()
@@ -721,8 +726,22 @@ def _get_raw_object_alpha(raw_obj: Any, color_getter: Any) -> int:
ctypes.byref(alpha),
)
except Exception:
- return 255
- return int(alpha.value) if ok else 255
+ return None
+ if not ok:
+ return None
+ return (
+ int(red.value),
+ int(green.value),
+ int(blue.value),
+ int(alpha.value),
+ )
+
+
+def _get_raw_object_alpha(raw_obj: Any, color_getter: Any) -> int:
+ """读取对象颜色 alpha;旧 PDFium 或读取失败时按不透明处理。"""
+
+ rgba = _get_raw_object_rgba(raw_obj, color_getter)
+ return rgba[3] if rgba is not None else 255
def _get_path_visibility(raw_obj: Any) -> tuple[bool, bool]:
@@ -910,6 +929,14 @@ def _path_info_from_object(
stroke_visible=stroke_visible,
form_depth=form_depth,
source_index=source_index,
+ fill_rgba=(
+ _get_raw_object_rgba(
+ raw_obj,
+ pdfium_c.FPDFPageObj_GetFillColor,
+ )
+ if fill_visible
+ else None
+ ),
)
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index 6c1d1e84..bca3c540 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -58,6 +58,85 @@ def test_page_footnote_uses_separator_and_stops_before_distant_footer_text() ->
assert page.page_footnote_groups == [{3, 4, 5}]
+def test_image_footnote_requires_image_rule_and_smaller_text() -> None:
+ """验证图表脚注必须同时具备图片、下缘长横线和字号收缩证据。"""
+
+ lines = [
+ _text_line(
+ f"body {index}",
+ (50.0, 40.0 + 20.0 * index, 450.0, 50.0 + 20.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ]
+ note = _text_line(
+ "chart source",
+ (50.0, 325.0, 180.0, 333.0),
+ 4,
+ effective_height=8.0,
+ )
+ lines.append(note)
+ page = _prepared_text_page(*lines, page_size=(500.0, 500.0))
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (50.0, 140.0, 300.0, 315.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+ page.drawing_lines = [
+ models._AxisLine((50.0, 318.0, 300.0, 319.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_page_auxiliary_text(page)
+
+ assert note.semantic_type == "footnote"
+ assert page.page_footnote_groups == []
+
+
[email protected]("missing_evidence", ["image", "rule", "small_text"])
+def test_image_footnote_rejects_incomplete_visual_evidence(
+ missing_evidence: str,
+) -> None:
+ """验证缺少任一联合证据时普通图下文字不会晋升为图表脚注。"""
+
+ body = [
+ _text_line(
+ f"body {index}",
+ (50.0, 40.0 + 20.0 * index, 450.0, 50.0 + 20.0 * index),
+ index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ]
+ note = _text_line(
+ "candidate",
+ (50.0, 325.0, 180.0, 333.0),
+ 4,
+ effective_height=10.0 if missing_evidence == "small_text" else 8.0,
+ )
+ page = _prepared_text_page(*body, note, page_size=(500.0, 500.0))
+ if missing_evidence != "image":
+ page.fixed_blocks = [
+ {
+ "type": "image",
+ "bbox": (50.0, 140.0, 300.0, 315.0),
+ "angle": 0,
+ "content": "",
+ }
+ ]
+ if missing_evidence != "rule":
+ page.drawing_lines = [
+ models._AxisLine((50.0, 318.0, 300.0, 319.0), 1.0, "horizontal")
+ ]
+
+ auxiliary_text._classify_page_auxiliary_text(page)
+
+ assert note.semantic_type is None
+
+
def test_page_footnote_supports_independent_column_rules() -> None:
"""验证左右栏各自的短横线只认领本栏连续页脚注。"""
@@ -494,6 +573,8 @@ def test_auxiliary_text_classifiers_do_not_read_line_text() -> None:
auxiliary_text._classify_page_auxiliary_text,
auxiliary_text._classify_aside_text,
auxiliary_text._geometric_text_support_by_angle,
+ auxiliary_text._classify_image_footnotes,
+ auxiliary_text._image_footnote_members,
auxiliary_text._classify_page_footnotes,
auxiliary_text._augment_footnote_groups_with_edge_markers,
auxiliary_text._classify_rule_delimited_headers,
@@ -514,6 +595,7 @@ def test_finalize_preserves_preclassified_auxiliary_text_types() -> None:
page = _prepared_text_page(
_text_line("note", (10.0, 80.0, 40.0, 90.0), 0, semantic_type="page_footnote"),
+ _text_line("chart note", (10.0, 65.0, 40.0, 75.0), 2, semantic_type="footnote"),
_text_line(
"aside",
(2.0, 20.0, 5.0, 60.0),
@@ -526,7 +608,11 @@ def test_finalize_preserves_preclassified_auxiliary_text_types() -> None:
blocks = pipeline._finalize_prepared_page(page, page_index=0)
- assert {block["type"] for block in blocks} == {"page_footnote", "aside_text"}
+ assert {block["type"] for block in blocks} == {
+ "footnote",
+ "page_footnote",
+ "aside_text",
+ }
def test_repeated_marginals_require_cross_page_evidence_and_separate_page_numbers() -> None:
diff --git a/tests/unittest/test_flash_pdf_code_blocks.py b/tests/unittest/test_flash_pdf_code_blocks.py
new file mode 100644
index 00000000..bb5aea94
--- /dev/null
+++ b/tests/unittest/test_flash_pdf_code_blocks.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from mineru.backend.flash.native_pdf import code_blocks, models, pipeline
+from mineru.backend.hybrid.table_text import project_pdf_spatial_text
+from mineru.utils.pdf_document import PDFPathInfo
+
+from _flash_pdf_test_utils import _text_line
+
+
+def _mono_line(
+ text: str,
+ bbox: tuple[float, float, float, float],
+ source_index: int,
+ *,
+ font_name: str = "TestMono",
+ glyph_widths: list[float] | None = None,
+) -> models._LineItem:
+ """构造带原生字符框的等宽或比例字体测试行。"""
+
+ widths = glyph_widths or [5.0] * len(text)
+ line = _text_line(
+ text,
+ bbox,
+ source_index,
+ effective_height=bbox[3] - bbox[1],
+ font_signature=(font_name, 0),
+ font_coverage=1.0,
+ median_glyph_width=5.0,
+ )
+ x = bbox[0]
+ chars: list[dict[str, Any]] = []
+ for char_offset, (value, width) in enumerate(zip(text, widths, strict=True)):
+ chars.append(
+ {
+ "bbox": (x, bbox[1], x + width, bbox[3]),
+ "char": value,
+ "rotation": 0.0,
+ "font": {
+ "name": font_name,
+ "flags": 0,
+ "size": bbox[3] - bbox[1],
+ "weight": 400,
+ },
+ "char_idx": source_index * 100 + char_offset,
+ }
+ )
+ x += width
+ line.chars = chars
+ return line
+
+
+def _code_source(
+ *lines: models._LineItem,
+ fill_rgba: tuple[int, int, int, int] = (242, 242, 255, 255),
+) -> models._PageSource:
+ """构造带大幅浅色填充背景的代码页测试源。"""
+
+ return models._PageSource(
+ page_size=(200.0, 100.0),
+ lines=list(lines),
+ chars=[char for line in lines for char in line.chars],
+ drawing_lines=[],
+ path_infos=[
+ PDFPathInfo(
+ bbox=(10.0, 10.0, 190.0, 70.0),
+ segment_count=5,
+ fill_visible=True,
+ stroke_visible=False,
+ form_depth=0,
+ source_index=0,
+ fill_rgba=fill_rgba,
+ )
+ ],
+ )
+
+
+def test_colored_monospace_region_materializes_code_and_claims_text() -> None:
+ """验证浅色等宽区域输出 code,并且内部文本不再重复进入正文。"""
+
+ first = _mono_line("alpha", (15.0, 15.0, 40.0, 23.0), 0)
+ second = _mono_line("beta", (20.0, 35.0, 40.0, 43.0), 1)
+ source = _code_source(first, second)
+
+ prepared = pipeline._prepare_page_source(source)
+ blocks = pipeline._finalize_prepared_page(prepared, page_index=0)
+
+ assert prepared.remaining_lines == []
+ assert len(blocks) == 1
+ assert blocks[0]["type"] == "code"
+ assert blocks[0]["content"] == "alpha\n\n beta"
+
+
[email protected]("rejection", ["white", "proportional", "table_overlap"])
+def test_code_candidate_rejects_missing_background_or_monospace_evidence(
+ rejection: str,
+) -> None:
+ """验证白框、比例字体和已确认表格均不会被升级为代码块。"""
+
+ if rejection == "proportional":
+ first = _mono_line(
+ "alpha",
+ (15.0, 15.0, 42.0, 23.0),
+ 0,
+ font_name="Body",
+ glyph_widths=[3.0, 7.0, 4.0, 8.0, 5.0],
+ )
+ else:
+ first = _mono_line("alpha", (15.0, 15.0, 40.0, 23.0), 0)
+ second = _mono_line("beta", (15.0, 35.0, 35.0, 43.0), 1)
+ source = _code_source(
+ first,
+ second,
+ fill_rgba=(255, 255, 255, 255) if rejection == "white" else (242, 242, 255, 255),
+ )
+ excluded = [(10.0, 10.0, 190.0, 70.0)] if rejection == "table_overlap" else []
+
+ blocks, claimed = code_blocks._build_code_blocks(source, excluded, set())
+
+ assert blocks == []
+ assert claimed == set()
+
+
+def test_code_projection_preserves_columns_and_blank_rows() -> None:
+ """验证通用 PDF 空间投影保留等宽缩进、双列关系和明显空行。"""
+
+ left = _mono_line("left", (5.0, 5.0, 25.0, 13.0), 0)
+ right = _mono_line("right", (55.0, 5.0, 80.0, 13.0), 1)
+ tail = _mono_line("tail", (10.0, 30.0, 30.0, 38.0), 2)
+ chars = [char for line in (left, right, tail) for char in line.chars]
+
+ content = project_pdf_spatial_text(
+ chars,
+ (0.0, 0.0, 100.0, 50.0),
+ preserve_blank_rows=True,
+ )
+
+ assert content == "left right\n\n tail"
diff --git a/tests/unittest/test_flash_pdf_document_profile.py b/tests/unittest/test_flash_pdf_document_profile.py
index f9e6e51e..e29264a4 100644
--- a/tests/unittest/test_flash_pdf_document_profile.py
+++ b/tests/unittest/test_flash_pdf_document_profile.py
@@ -191,6 +191,278 @@ def test_document_regular_font_suppresses_code_page_false_title() -> None:
assert lines[5].semantic_type == "paragraph_title"
+def test_document_title_profile_promotes_table_adjacent_style_but_not_container_label() -> None:
+ """验证跨页标题原型可越过邻表抑制,但容器内部同样式标签仍保持正文。"""
+
+ heading_font = ("Heading", 0)
+ heading = _text_line(
+ "heading",
+ (0.0, 10.0, 40.0, 24.0),
+ 0,
+ effective_height=14.0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ dominant_font_weight=600.0,
+ )
+ container_label = _text_line(
+ "container label",
+ (0.0, 40.0, 40.0, 54.0),
+ 1,
+ effective_height=14.0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ dominant_font_weight=600.0,
+ )
+ body_profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({("Body", 0)}),
+ )
+ title_profile = titles._DocumentTitleProfile(
+ (
+ titles._TitleStylePrototype(
+ font_family="heading",
+ font_flags=0,
+ height_ratio=1.4,
+ weight=600.0,
+ alignment="left",
+ anchor_offset=0.0,
+ support_count=4,
+ support_pages=3,
+ ),
+ )
+ )
+
+ titles._classify_page_titles(
+ [heading, container_label],
+ (100.0, 100.0),
+ page_index=1,
+ container_bboxes=[(0.0, 28.0, 100.0, 90.0)],
+ document_body_profile=body_profile,
+ document_title_profile=title_profile,
+ )
+
+ assert heading.semantic_type == "paragraph_title"
+ assert container_label.semantic_type is None
+
+
+def test_document_title_profile_promotes_body_height_centered_section() -> None:
+ """验证与正文同字体字号的居中章节行可凭重复标题原型和邻表关系晋升。"""
+
+ regular_font = ("Body", 0)
+ heading = _text_line(
+ "section",
+ (30.0, 24.0, 70.0, 34.0),
+ 0,
+ effective_height=10.0,
+ font_signature=regular_font,
+ font_coverage=1.0,
+ dominant_font_weight=400.0,
+ )
+ body = _text_line(
+ "body",
+ (0.0, 40.0, 100.0, 50.0),
+ 1,
+ effective_height=10.0,
+ font_signature=regular_font,
+ font_coverage=1.0,
+ dominant_font_weight=400.0,
+ )
+ body_profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({regular_font}),
+ )
+ title_profile = titles._DocumentTitleProfile(
+ (
+ titles._TitleStylePrototype(
+ font_family="body",
+ font_flags=0,
+ height_ratio=1.0,
+ weight=400.0,
+ alignment="center",
+ anchor_offset=0.0,
+ support_count=5,
+ support_pages=3,
+ ),
+ )
+ )
+
+ titles._classify_page_titles(
+ [heading, body],
+ (100.0, 100.0),
+ page_index=1,
+ container_bboxes=[(0.0, 0.0, 100.0, 20.0)],
+ document_body_profile=body_profile,
+ document_title_profile=title_profile,
+ )
+
+ assert heading.semantic_type == "paragraph_title"
+ assert body.semantic_type is None
+
+
+def test_document_title_profile_infers_repeated_large_left_aligned_style() -> None:
+ """验证两页重复的大字号左对齐样式可形成文档级标题原型。"""
+
+ body_font = ("Body", 0)
+ heading_font = ("RepeatedHeading", 0)
+ pages = [
+ _prepared_text_page(
+ _text_line(
+ "body cover",
+ (0.0, 20.0, 100.0, 30.0),
+ 0,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ page_size=(100.0, 100.0),
+ )
+ ]
+ for page_index in range(1, 3):
+ pages.append(
+ _prepared_text_page(
+ _text_line(
+ f"heading {page_index}",
+ (0.0, 10.0, 45.0, 24.0),
+ page_index * 10,
+ effective_height=14.0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ dominant_font_weight=600.0,
+ ),
+ _text_line(
+ f"body {page_index}",
+ (0.0, 40.0, 100.0, 50.0),
+ page_index * 10 + 1,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ dominant_font_weight=400.0,
+ ),
+ page_size=(100.0, 100.0),
+ )
+ )
+ body_profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({body_font}),
+ )
+
+ profile = titles._infer_document_title_profile(pages, body_profile)
+
+ assert profile is not None
+ assert len(profile.prototypes) == 1
+ assert profile.prototypes[0].font_family == "repeatedheading"
+ assert profile.prototypes[0].support_pages == 2
+
+
+def test_regular_pitch_style_change_does_not_become_title() -> None:
+ """验证仅有字体变化、但没有额外段间净空的正文续行不会误判标题。"""
+
+ body_font = ("Body", 0)
+ alternate_font = ("Alternate", 0)
+ lines = [
+ _text_line(
+ "body one",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "continuation",
+ (0.0, 16.0, 80.0, 26.0),
+ 1,
+ font_signature=alternate_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "body two",
+ (0.0, 32.0, 100.0, 42.0),
+ 2,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ ]
+ profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({body_font}),
+ )
+
+ titles._classify_page_titles(
+ lines,
+ (100.0, 100.0),
+ page_index=1,
+ container_bboxes=[],
+ document_body_profile=profile,
+ )
+
+ assert lines[1].semantic_type is None
+
+
+def test_title_font_at_body_size_does_not_override_document_size_profile() -> None:
+ """验证标题字体落入正文字号带时不会仅凭大留白继续误判为标题。"""
+
+ heading_font = ("Heading", 0)
+ lines = [
+ _text_line(
+ "body one",
+ (0.0, 0.0, 100.0, 10.0),
+ 0,
+ font_signature=("Body", 0),
+ font_coverage=1.0,
+ ),
+ _text_line(
+ "weak heading",
+ (0.0, 35.0, 45.0, 46.0),
+ 1,
+ effective_height=11.0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ dominant_font_weight=400.0,
+ ),
+ _text_line(
+ "body two",
+ (0.0, 60.0, 100.0, 70.0),
+ 2,
+ font_signature=("Body", 0),
+ font_coverage=1.0,
+ ),
+ ]
+ body_profile = titles._DocumentBodyProfile(
+ body_height=10.0,
+ body_weight=400.0,
+ regular_fonts=frozenset({("Body", 0)}),
+ )
+ title_profile = titles._DocumentTitleProfile(
+ (
+ titles._TitleStylePrototype(
+ font_family="heading",
+ font_flags=0,
+ height_ratio=1.4,
+ weight=400.0,
+ alignment="left",
+ anchor_offset=0.0,
+ support_count=4,
+ support_pages=3,
+ ),
+ )
+ )
+
+ titles._classify_page_titles(
+ lines,
+ (100.0, 100.0),
+ page_index=1,
+ container_bboxes=[],
+ document_body_profile=body_profile,
+ document_title_profile=title_profile,
+ )
+
+ assert lines[1].semantic_type is None
+
+
def test_smaller_recurrent_regular_font_does_not_gain_title_style_signal() -> None:
"""验证较小的跨页常规代码字体即使留白较大,也不会仅凭字体切换升为标题。"""
diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.py
index dafea0e7..92e6b927 100644
--- a/tests/unittest/test_flash_pdf_text_blocks.py
+++ b/tests/unittest/test_flash_pdf_text_blocks.py
@@ -1076,6 +1076,156 @@ def test_short_span_tail_reattaches_before_later_cross_layout_region() -> None:
assert tail in [line for line, _bbox in span_lane.lines]
+def test_repeated_indented_span_tails_reattach_and_form_separate_entries() -> None:
+ """验证重复的跨栏首行与缩进尾行迁回 span 后仍逐条分组。"""
+
+ body_font = ("Body", 0)
+ first = _text_line(
+ "first wide",
+ (10.0, 0.0, 190.0, 10.0),
+ 0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ first_tail = _text_line(
+ "first tail",
+ (25.0, 10.0, 90.0, 20.0),
+ 1,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ second = _text_line(
+ "second wide",
+ (10.0, 20.0, 190.0, 30.0),
+ 2,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ second_tail = _text_line(
+ "second tail",
+ (25.0, 30.0, 80.0, 40.0),
+ 3,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ left_lane = models._TextLane(
+ left=10.0,
+ right=90.0,
+ lines=[(first_tail, first_tail.bbox), (second_tail, second_tail.bbox)],
+ )
+ right_marker = _text_line("peer", (110.0, 70.0, 190.0, 80.0), 4)
+ right_lane = models._TextLane(
+ left=110.0,
+ right=190.0,
+ lines=[(right_marker, right_marker.bbox)],
+ )
+ span_lane = models._TextLane(
+ left=10.0,
+ right=190.0,
+ lines=[(first, first.bbox), (second, second.bbox)],
+ is_span=True,
+ )
+
+ line_layout._reattach_span_lane_continuations(
+ [left_lane, right_lane, span_lane],
+ 10.0,
+ )
+ group_map = text_blocks._build_hanging_indent_group_map(span_lane, [], [])
+
+ assert not left_lane.lines
+ assert [group_map[index] for index in range(4)] == [0, 0, 1, 1]
+
+
+def test_single_indented_span_tail_does_not_reattach() -> None:
+ """验证缺少重复结构支持时单个缩进行不会被猜测为跨栏续行。"""
+
+ first = _text_line("wide", (10.0, 0.0, 190.0, 10.0), 0)
+ tail = _text_line("tail", (25.0, 10.0, 80.0, 20.0), 1)
+ peer = _text_line("peer", (110.0, 50.0, 190.0, 60.0), 2)
+ left_lane = models._TextLane(left=10.0, right=90.0, lines=[(tail, tail.bbox)])
+ right_lane = models._TextLane(left=110.0, right=190.0, lines=[(peer, peer.bbox)])
+ span_lane = models._TextLane(
+ left=10.0,
+ right=190.0,
+ lines=[(first, first.bbox)],
+ is_span=True,
+ )
+
+ line_layout._reattach_span_lane_continuations(
+ [left_lane, right_lane, span_lane],
+ 10.0,
+ )
+
+ assert tail in [line for line, _bbox in left_lane.lines]
+
+
+def test_aligned_fallback_fonts_merge_but_style_conflict_stays_separate() -> None:
+ """验证紧邻地址与联系方式可跨字体族续接,而样式位变化仍形成边界。"""
+
+ address = _text_line(
+ "address",
+ (0.0, 0.0, 70.0, 10.0),
+ 0,
+ font_signature=("CJK", 32),
+ font_coverage=1.0,
+ dominant_font_weight=250.0,
+ )
+ contact = _text_line(
+ "contact",
+ (0.0, 12.0, 80.0, 22.0),
+ 1,
+ font_signature=("Latin", 32),
+ font_coverage=1.0,
+ dominant_font_weight=220.0,
+ )
+ emphasized = _text_line(
+ "emphasized",
+ (0.0, 24.0, 80.0, 34.0),
+ 2,
+ font_signature=("LatinBold", 64),
+ font_coverage=1.0,
+ dominant_font_weight=650.0,
+ )
+
+ blocks = text_blocks._build_text_blocks(
+ [address, contact, emphasized],
+ [],
+ (100.0, 100.0),
+ )
+
+ assert [block["content"] for block in blocks] == [
+ "address contact",
+ "emphasized",
+ ]
+
+
+def test_hanging_indent_uses_top_pitch_when_terminal_glyph_height_is_abnormal() -> None:
+ """验证异常偏高末字符不会把已重复的参考文献悬挂缩进拆开。"""
+
+ lines = [
+ _text_line("entry one", (0.0, 0.0, 100.0, 10.0), 0),
+ _text_line("entry one tail", (15.0, 10.0, 90.0, 20.0), 1),
+ _text_line("entry two", (0.0, 20.0, 100.0, 30.0), 2),
+ _text_line(
+ "entry two tall tail",
+ (15.0, 30.0, 90.0, 40.0),
+ 3,
+ effective_height=18.6,
+ ),
+ _text_line("entry three", (0.0, 42.0, 100.0, 52.0), 4),
+ _text_line("entry three tail", (15.0, 52.0, 90.0, 62.0), 5),
+ ]
+ lane = models._TextLane(
+ left=0.0,
+ right=100.0,
+ lines=[(line, line.bbox) for line in lines],
+ )
+
+ group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])
+
+ assert [group_map[index] for index in range(6)] == [0, 0, 1, 1, 2, 2]
+
+
def test_spatial_post_merge_connects_short_opener_wide_body_and_tail() -> None:
"""验证跨栏拆开的短首行、满宽正文和紧邻尾行仅按空间关系重新连接。"""
@@ -1933,3 +2083,116 @@ def test_caption_post_merge_respects_typographic_gap_barrier() -> None:
"Fig. 1 caption",
"body starts",
]
+
+
+def test_repeated_compact_title_continuations_merge_across_font_switch() -> None:
+ """验证重复两行弱标题可与紧邻异字体续行合并并恢复为正文。"""
+
+ blocks: list[dict[str, object]] = []
+ for offset, label in ((0.0, "first"), (45.0, "second")):
+ blocks.extend(
+ [
+ {
+ "type": "paragraph_title",
+ "bbox": (10.0, 10.0 + offset, 65.0, 30.0 + offset),
+ "angle": 0,
+ "content": f"{label} name {label} address",
+ "_visual_row_ids": {1, 2},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [
+ (10.0, 10.0 + offset, 50.0, 20.0 + offset),
+ (10.0, 20.0 + offset, 65.0, 30.0 + offset),
+ ],
+ "_line_heights": [10.0, 10.0],
+ "_font_signatures": {("Title", 0)},
+ "_lane_interval": (10.0, 100.0),
+ "_lane_is_span": False,
+ },
+ {
+ "type": "text",
+ "bbox": (10.0, 31.0 + offset, 80.0, 41.0 + offset),
+ "angle": 0,
+ "content": f"{label} contact",
+ "_visual_row_ids": {3},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [
+ (10.0, 31.0 + offset, 80.0, 41.0 + offset),
+ ],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body", 0)},
+ "_lane_interval": (10.0, 100.0),
+ "_lane_is_span": False,
+ },
+ ]
+ )
+
+ merged = text_blocks._merge_repeated_compact_title_continuations(
+ blocks,
+ (200.0, 200.0),
+ )
+
+ assert [block["type"] for block in merged] == ["text", "text"]
+ assert [block["content"] for block in merged] == [
+ "first name first address first contact",
+ "second name second address second contact",
+ ]
+
+
+def test_compact_title_continuation_requires_repetition_and_font_switch() -> None:
+ """验证单组结构或相同字体续行不会越过真正的标题边界。"""
+
+ title = {
+ "type": "paragraph_title",
+ "bbox": (10.0, 10.0, 65.0, 30.0),
+ "angle": 0,
+ "content": "title",
+ "_visual_row_ids": {1, 2},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [
+ (10.0, 10.0, 50.0, 20.0),
+ (10.0, 20.0, 65.0, 30.0),
+ ],
+ "_line_heights": [10.0, 10.0],
+ "_font_signatures": {("Title", 0)},
+ "_lane_interval": (10.0, 100.0),
+ "_lane_is_span": False,
+ }
+ continuation = {
+ "type": "text",
+ "bbox": (10.0, 31.0, 80.0, 41.0),
+ "angle": 0,
+ "content": "body",
+ "_visual_row_ids": {3},
+ "_single_run_row_id": None,
+ "_local_line_bboxes": [(10.0, 31.0, 80.0, 41.0)],
+ "_line_heights": [10.0],
+ "_font_signatures": {("Body", 0)},
+ "_lane_interval": (10.0, 100.0),
+ "_lane_is_span": False,
+ }
+
+ unique = text_blocks._merge_repeated_compact_title_continuations(
+ [title, continuation],
+ (200.0, 200.0),
+ )
+ same_font = text_blocks._merge_repeated_compact_title_continuations(
+ [
+ title,
+ {**continuation, "_font_signatures": {("Title", 0)}},
+ {**title, "bbox": (10.0, 55.0, 65.0, 75.0)},
+ {
+ **continuation,
+ "bbox": (10.0, 76.0, 80.0, 86.0),
+ "_font_signatures": {("Title", 0)},
+ },
+ ],
+ (200.0, 200.0),
+ )
+
+ assert [block["type"] for block in unique] == ["paragraph_title", "text"]
+ assert [block["type"] for block in same_font] == [
+ "paragraph_title",
+ "text",
+ "paragraph_title",
+ "text",
+ ]
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index b0faa966..1f5b0b11 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -894,6 +894,9 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
for function in (
titles._classify_page_titles,
titles._infer_document_body_profile,
+ titles._infer_document_title_profile,
+ titles._title_profile_seed_matches_cluster,
+ titles._title_profile_alignment,
titles._document_font_is_regular,
titles._build_physical_title_gap_map,
titles._find_repeated_grid_title_suppressions,
@@ -904,6 +907,8 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
titles._document_title_uses_page_fallback,
titles._classify_paragraph_titles_in_lane,
titles._line_uses_document_regular_font,
+ titles._matching_document_title_prototype,
+ titles._line_inside_visual_container,
titles._visual_row_has_body_style_sibling,
titles._is_near_full_mixed_inline_row,
titles._continues_local_body_row,
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index 2745ad98..6fe69272 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -81,6 +81,21 @@ def _build_rotated_cropped_drawing_pdf() -> bytes:
return output.getvalue()
+def _build_colored_path_pdf() -> bytes:
+ """构造可见浅色填充与透明填充 Path,验证 RGBA 元数据。"""
+
+ output = BytesIO()
+ canvas = Canvas(output, pagesize=(100, 100))
+ canvas.setFillColorRGB(242 / 255, 255 / 255, 242 / 255)
+ canvas.rect(10, 60, 80, 20, stroke=0, fill=1)
+ canvas.saveState()
+ canvas.setFillAlpha(0)
+ canvas.rect(10, 20, 80, 20, stroke=0, fill=1)
+ canvas.restoreState()
+ canvas.save()
+ return output.getvalue()
+
+
def _build_rotated_cropped_image_pdf() -> bytes:
"""构造普通、嵌套 Form、部分页外和完全页外点阵图,并应用 CropBox 与旋转。"""
image = Image.new("RGB", (3, 4), "red")
@@ -443,6 +458,7 @@ def test_get_page_path_infos_preserves_bezier_visibility_depth_and_source_order(
assert not path_infos[0].fill_visible and path_infos[0].stroke_visible
assert path_infos[3].bbox == pytest.approx((10.0, 60.0, 90.0, 60.5))
assert path_infos[3].fill_visible and not path_infos[3].stroke_visible
+ assert path_infos[3].fill_rgba == (0, 0, 0, 255)
nested_path = next(item for item in path_infos if item.form_depth == 1)
assert nested_path.bbox == pytest.approx((29.0, 99.0, 71.0, 101.0))
bezier_path = path_infos[-1]
@@ -450,6 +466,29 @@ def test_get_page_path_infos_preserves_bezier_visibility_depth_and_source_order(
assert bezier_path.bbox == pytest.approx((10.0, 105.0, 40.0, 120.0))
+def test_get_page_path_infos_exposes_fill_rgba_and_transparency() -> None:
+ """验证可见 Path 保留填充 RGBA,透明填充不伪装成可见背景。"""
+
+ with pdf_document.PDFDocument(_build_colored_path_pdf()) as doc:
+ path_infos = doc.get_page_path_infos(0)
+
+ visible = next(item for item in path_infos if item.fill_visible)
+ transparent = next(item for item in path_infos if not item.fill_visible)
+ assert visible.fill_rgba == (242, 255, 242, 255)
+ assert transparent.fill_rgba is None
+
+
+def test_raw_object_rgba_failure_returns_none() -> None:
+ """验证旧 PDFium 或损坏对象读取颜色失败时返回 None。"""
+
+ def broken_getter(*_args: Any) -> bool:
+ """模拟底层颜色接口异常。"""
+
+ raise RuntimeError("broken color")
+
+ assert pdf_document._get_raw_object_rgba(object(), broken_getter) is None
+
+
def test_get_page_drawing_lines_applies_crop_box_and_page_rotation() -> None:
"""验证页面 CropBox 与 90 度旋转被转换为左上原点坐标。"""
with pdf_document.PDFDocument(_build_rotated_cropped_drawing_pdf()) as doc: