Skip to content

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

feat: enhance page processing by adding classification for page footnotes and aside text

myhloli068a50ffab12
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.py
index 2790c533..70064f09 100644
--- a/mineru/backend/flash/pdf_extractor.py
+++ b/mineru/backend/flash/pdf_extractor.py
@@ -53,6 +53,8 @@ _TEXT_SEMANTIC_TYPES = {
"header",
"footer",
"page_number",
+ "page_footnote",
+ "aside_text",
}
_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation"} | _TEXT_SEMANTIC_TYPES
_PAGE_NUMBER_RE = re.compile(
@@ -185,6 +187,7 @@ class _PreparedPage:
table_bboxes: list[BBox]
drawing_lines: list[_AxisLine]
fixed_blocks: list[dict[str, Any]]
+ page_footnote_groups: list[set[int]] = field(default_factory=list)
@dataclass(slots=True)
@@ -611,7 +614,7 @@ def _get_pdf_drawing_lines(pdf_doc: PDFDocument, page_idx: int) -> list[_AxisLin
def _prepare_page_source(source: _PageSource) -> _PreparedPage:
- """先完成表格、Form、图形和点阵图认领,留下可跨页比较的轻量文本行。"""
+ """先认领视觉容器,再标注辅助文本并留下可跨页比较的轻量文本行。"""
form_bboxes = _select_form_image_bboxes(source)
candidates = [
@@ -663,13 +666,15 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
table_bboxes,
)
_compact_prepared_lines(remaining_lines, source.page_size)
- return _PreparedPage(
+ prepared = _PreparedPage(
page_size=source.page_size,
remaining_lines=remaining_lines,
table_bboxes=table_bboxes,
drawing_lines=source.drawing_lines,
fixed_blocks=table_blocks + form_image_blocks + graphic_blocks + raster_image_blocks,
)
+ _classify_page_auxiliary_text(prepared)
+ return prepared
def _compact_prepared_lines(
@@ -684,13 +689,253 @@ def _compact_prepared_lines(
line.chars.clear()
+def _classify_page_auxiliary_text(prepared: _PreparedPage) -> None:
+ """在容器认领后仅按空间关系标注侧栏文字和页脚注。"""
+
+ _classify_aside_text(prepared.remaining_lines, prepared.page_size)
+ prepared.page_footnote_groups = _classify_page_footnotes(
+ prepared.remaining_lines,
+ prepared.table_bboxes,
+ prepared.drawing_lines,
+ prepared.page_size,
+ )
+
+
+def _classify_aside_text(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+) -> None:
+ """在横排正文占绝对多数时,以边缘带和物理尺寸识别垂直侧栏。"""
+
+ available = [line for line in lines if line.semantic_type is None]
+ upright_lines = [line for line in available if line.angle == 0]
+ if len(upright_lines) < 4:
+ return
+
+ support_by_angle = _geometric_text_support_by_angle(available, page_size)
+ total_support = sum(support_by_angle.values())
+ if total_support <= 0 or support_by_angle.get(0, 0.0) / total_support < 0.8:
+ return
+
+ page_width, page_height = page_size
+ if page_width <= 0 or page_height <= 0:
+ return
+ # 侧栏必须完整位于 12% 边缘带,且兼具不超过 8% 的窄宽和至少 15% 的物理高度。
+ aside_source_indices = {
+ line.source_index
+ for line in available
+ if line.angle in {90, 270}
+ and line.bbox[2] - line.bbox[0] <= 0.08 * page_width
+ and line.bbox[3] - line.bbox[1] >= 0.15 * page_height
+ and (
+ line.bbox[2] <= 0.12 * page_width
+ or line.bbox[0] >= 0.88 * page_width
+ )
+ }
+ for line in available:
+ if line.source_index in aside_source_indices:
+ line.semantic_type = "aside_text"
+
+
+def _geometric_text_support_by_angle(
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+) -> dict[int, float]:
+ """按局部行宽乘有效行高累计各文字方向的纯几何支持度。"""
+
+ support_by_angle: dict[int, float] = {}
+ for line in lines:
+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)
+ local_width = max(0.1, local_bbox[2] - local_bbox[0])
+ support_by_angle[line.angle] = support_by_angle.get(line.angle, 0.0) + (
+ local_width * _line_effective_height(line, local_bbox)
+ )
+ return support_by_angle
+
+
+def _classify_page_footnotes(
+ lines: list[_LineItem],
+ table_bboxes: list[BBox],
+ drawing_lines: list[_AxisLine],
+ page_size: tuple[float, float],
+) -> list[set[int]]:
+ """识别主方向页脚注,并按触发分隔线返回来源编号分组。"""
+
+ available = [line for line in lines if line.semantic_type is None]
+ if not available 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],
+ )
+ line_geometry = [
+ (line, _rotate_bbox_to_upright(line.bbox, page_size, dominant_angle))
+ for line in available
+ if line.angle == dominant_angle
+ ]
+ if not line_geometry:
+ return []
+
+ 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 []
+ 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
+ lanes = _infer_text_lanes(line_geometry, local_page_width, median_height)
+ local_axis_lines = _transform_axis_lines(
+ drawing_lines,
+ page_size,
+ dominant_angle,
+ )
+
+ candidate_groups: list[set[int]] = []
+ for axis_line in local_axis_lines:
+ if axis_line.orientation != "horizontal":
+ continue
+ # 分隔线中心必须进入页面下方 30%,上方的正文分隔线不参与脚注判定。
+ rule_center_y = _bbox_center_y(axis_line.bbox)
+ if rule_center_y < 0.7 * local_page_height:
+ continue
+ # 表格边界会产生断裂横线;除框内线段外,也排除与其同高且近邻的框外线段。
+ if _rule_belongs_to_confirmed_table(
+ axis_line,
+ local_axis_lines,
+ table_bboxes,
+ local_page_width,
+ ):
+ continue
+ rule_source_indices: set[int] = set()
+ for lane in lanes:
+ rule_source_indices.update(
+ _footnote_lane_members(
+ lane,
+ axis_line.bbox,
+ local_page_size,
+ )
+ )
+ if rule_source_indices:
+ candidate_groups.append(rule_source_indices)
+
+ page_footnote_groups = _merge_overlapping_source_groups(candidate_groups)
+ footnote_source_indices = set().union(*page_footnote_groups) if page_footnote_groups else set()
+ for line in available:
+ if line.source_index in footnote_source_indices:
+ line.semantic_type = "page_footnote"
+ return page_footnote_groups
+
+
+def _rule_belongs_to_confirmed_table(
+ candidate: _LocalAxisLine,
+ local_axis_lines: list[_LocalAxisLine],
+ table_bboxes: list[BBox],
+ local_page_width: float,
+) -> bool:
+ """把表格框内横线及其同高近邻断裂段一并排除,避免框外残段触发脚注。"""
+
+ if not table_bboxes:
+ return False
+ maximum_segment_gap = 0.04 * local_page_width
+ for table_line in local_axis_lines:
+ if table_line.orientation != "horizontal":
+ continue
+ table_margin = max(0.5, table_line.width)
+ if not any(
+ _bbox_intersects(
+ _expand_bbox(table_line.original_bbox, table_margin),
+ table_bbox,
+ )
+ for table_bbox in table_bboxes
+ ):
+ continue
+ center_tolerance = max(1.0, candidate.width, table_line.width)
+ if abs(_bbox_center_y(candidate.bbox) - _bbox_center_y(table_line.bbox)) > center_tolerance:
+ continue
+ if _horizontal_bbox_gap(candidate.bbox, table_line.bbox) <= maximum_segment_gap:
+ return True
+ return False
+
+
+def _merge_overlapping_source_groups(groups: list[set[int]]) -> list[set[int]]:
+ """合并共享来源行的分隔线候选组,消除重复绘图线造成的重复分组。"""
+
+ merged: list[set[int]] = []
+ for group in groups:
+ combined = set(group)
+ index = 0
+ while index < len(merged):
+ if combined & merged[index]:
+ combined.update(merged.pop(index))
+ index = 0
+ continue
+ index += 1
+ merged.append(combined)
+ return sorted(merged, key=lambda group: min(group))
+
+
+def _footnote_lane_members(
+ lane: _TextLane,
+ rule_bbox: BBox,
+ local_page_size: tuple[float, float],
+) -> set[int]:
+ """验证横线与单个栏带的对齐关系,并返回其下连续脚注行的来源编号。"""
+
+ lane_lines = [item for item in lane.lines if item[0].semantic_type is None]
+ if not lane_lines:
+ return set()
+ lane_lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))
+ local_page_width, local_page_height = local_page_size
+ lane_width = max(0.1, lane.right - lane.left)
+ lane_heights = [_line_effective_height(line, bbox) for line, bbox in lane_lines]
+ median_height = statistics.median(lane_heights) if lane_heights else 1.0
+ rule_width = max(0.0, rule_bbox[2] - rule_bbox[0])
+ # 同时限制绝对短线、相对长线和左缘偏移,排除图标、公式线及跨栏正文分隔线。
+ if rule_width < max(4.0 * median_height, 0.04 * local_page_width):
+ return set()
+ if rule_width > 0.65 * lane_width:
+ return set()
+ if abs(rule_bbox[0] - lane.left) > max(2.0 * median_height, 0.04 * lane_width):
+ return set()
+
+ # 首行采用较宽的 3.5% 页高窗口;命中后仅按紧凑的连续净空向下扩展。
+ first_gap_limit = max(3.0 * median_height, 0.035 * local_page_height)
+ first_index: int | None = None
+ for index, (_line, bbox) in enumerate(lane_lines):
+ rule_gap = bbox[1] - rule_bbox[3]
+ if rule_gap < -0.5 * median_height:
+ continue
+ if rule_gap <= first_gap_limit:
+ first_index = index
+ break
+ if first_index is None:
+ return set()
+
+ continuation_gap_limit = max(1.25 * median_height, 0.01 * local_page_height)
+ members = [lane_lines[first_index]]
+ for current in lane_lines[first_index + 1 :]:
+ if _effective_text_row_gap(members[-1], current) > continuation_gap_limit:
+ break
+ members.append(current)
+ return {line.source_index for line, _bbox in members}
+
+
def _finalize_prepared_page(
prepared: _PreparedPage,
page_index: int,
) -> list[dict[str, Any]]:
- """按边缘类型、公式、标题、正文的优先级完成单页文本并排序。"""
+ """按预分类语义、公式、标题、正文的优先级完成单页文本并排序。"""
- marginal_lines = [line for line in prepared.remaining_lines if line.semantic_type in {"header", "footer", "page_number"}]
+ semantic_lines = [line for line in prepared.remaining_lines if line.semantic_type is not None]
formula_input = [line for line in prepared.remaining_lines if line.semantic_type is None]
formula_blocks, remaining_lines = _build_formula_like_blocks(
formula_input,
@@ -718,10 +963,11 @@ def _finalize_prepared_page(
prepared.table_bboxes,
)
text_blocks = _build_text_blocks(
- marginal_lines + remaining_lines,
+ semantic_lines + remaining_lines,
prepared.table_bboxes,
prepared.page_size,
prepared.drawing_lines,
+ page_footnote_groups=prepared.page_footnote_groups,
)
absolute_blocks = prepared.fixed_blocks + formula_blocks + text_blocks
sorted_blocks = _sort_blocks_with_visual_row_groups(absolute_blocks, prepared.page_size)
@@ -4138,15 +4384,205 @@ def _build_hanging_indent_group_map(
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
+ )
+ blocks.append(
+ {
+ "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,
+ }
+ )
+ 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)
+ 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
+ # 满行后必然续接;其余行按首页观测到的首行/续行缩进模式决定边界。
+ continues_previous = previous_is_near_full 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 _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,
) -> list[dict[str, Any]]:
- """按类型屏障、局部栏带和自然段边界聚合剩余文本行。"""
+ """先构建分组脚注,再按类型屏障、栏带和自然段边界聚合其余文本。"""
- blocks: 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:
diff --git a/tests/unittest/test_flash_pdf_extractor.py b/tests/unittest/test_flash_pdf_extractor.py
index a22bc839..5ba7dc5d 100644
--- a/tests/unittest/test_flash_pdf_extractor.py
+++ b/tests/unittest/test_flash_pdf_extractor.py
@@ -686,6 +686,7 @@ def _text_line(
bbox: tuple[float, float, float, float],
source_index: int,
*,
+ angle: int = 0,
visual_row_id: int | None = None,
run_index: int = 0,
split_from_row: bool = False,
@@ -693,6 +694,7 @@ def _text_line(
font_signature: tuple[str, int] | None = None,
font_coverage: float = 0.0,
dominant_font_weight: float | None = None,
+ median_glyph_width: float | None = None,
semantic_type: str | None = None,
) -> pdf_extractor._LineItem:
"""构造栏带、排版恢复与图形标签测试使用的原生文本行。"""
@@ -700,7 +702,7 @@ def _text_line(
return pdf_extractor._LineItem(
text=text,
bbox=bbox,
- angle=0,
+ angle=angle,
source_index=source_index,
visual_row_id=visual_row_id,
run_index=run_index,
@@ -708,6 +710,7 @@ def _text_line(
font_signature=font_signature,
font_coverage=font_coverage,
dominant_font_weight=dominant_font_weight,
+ median_glyph_width=median_glyph_width,
split_from_row=split_from_row,
semantic_type=semantic_type,
)
@@ -728,6 +731,391 @@ def _prepared_text_page(
)
+def test_page_footnote_uses_separator_and_stops_before_distant_footer_text() -> None:
+ """验证单栏页脚注由页底横线触发,并在较大行间隙前停止扩展。"""
+
+ lines = [
+ _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),
+ _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),
+ _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),
+ _text_line("note one", (100.0, 770.0, 500.0, 780.0), 3),
+ _text_line("note two", (100.0, 788.0, 500.0, 798.0), 4),
+ _text_line("note three", (100.0, 806.0, 500.0, 816.0), 5),
+ _text_line("footer text", (100.0, 850.0, 600.0, 860.0), 6),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.drawing_lines = [
+ pdf_extractor._AxisLine(
+ bbox=(100.0, 750.0, 260.0, 752.0),
+ width=1.0,
+ orientation="horizontal",
+ ),
+ pdf_extractor._AxisLine(
+ bbox=(100.0, 750.5, 260.0, 752.5),
+ width=1.0,
+ orientation="horizontal",
+ ),
+ ]
+
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert [line.semantic_type for line in lines] == [
+ None,
+ None,
+ None,
+ "page_footnote",
+ "page_footnote",
+ "page_footnote",
+ None,
+ ]
+ assert page.page_footnote_groups == [{3, 4, 5}]
+
+
+def test_page_footnote_supports_independent_column_rules() -> None:
+ """验证左右栏各自的短横线只认领本栏连续页脚注。"""
+
+ lines = [
+ *[
+ _text_line(f"left body {index}", (80.0, 100.0 + 30.0 * index, 460.0, 110.0 + 30.0 * index), index)
+ for index in range(3)
+ ],
+ *[
+ _text_line(
+ f"right body {index}",
+ (540.0, 100.0 + 30.0 * index, 920.0, 110.0 + 30.0 * index),
+ index + 3,
+ )
+ for index in range(3)
+ ],
+ _text_line("left note one", (80.0, 820.0, 400.0, 830.0), 6),
+ _text_line("left note two", (80.0, 838.0, 400.0, 848.0), 7),
+ _text_line("right note one", (540.0, 820.0, 860.0, 830.0), 8),
+ _text_line("right note two", (540.0, 838.0, 860.0, 848.0), 9),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.drawing_lines = [
+ pdf_extractor._AxisLine((80.0, 800.0, 220.0, 802.0), 1.0, "horizontal"),
+ pdf_extractor._AxisLine((540.0, 800.0, 680.0, 802.0), 1.0, "horizontal"),
+ ]
+
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert all(line.semantic_type is None for line in lines[:6])
+ assert all(line.semantic_type == "page_footnote" for line in lines[6:])
+ assert page.page_footnote_groups == [{6, 7}, {8, 9}]
+
+
+def test_page_footnote_unions_aligned_regular_and_span_lanes_only() -> None:
+ """验证同左缘 regular/span 栏可联合认领,但不会吞掉右侧正文栏。"""
+
+ lines = [
+ *[
+ _text_line(f"left body {index}", (100.0, 100.0 + 30.0 * index, 480.0, 110.0 + 30.0 * index), index)
+ for index in range(3)
+ ],
+ *[
+ _text_line(
+ f"right body {index}",
+ (520.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index),
+ index + 3,
+ )
+ for index in range(3)
+ ],
+ _text_line("span note one", (100.0, 810.0, 900.0, 820.0), 6),
+ _text_line("span note two", (100.0, 830.0, 900.0, 840.0), 7),
+ _text_line("span note three", (100.0, 850.0, 900.0, 860.0), 8),
+ _text_line("left note one", (100.0, 812.0, 480.0, 822.0), 9),
+ _text_line("left note two", (100.0, 832.0, 480.0, 842.0), 10),
+ _text_line("right body below rule", (520.0, 812.0, 900.0, 822.0), 11),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.drawing_lines = [
+ pdf_extractor._AxisLine((100.0, 800.0, 305.0, 802.0), 1.0, "horizontal")
+ ]
+
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert {line.source_index for line in lines if line.semantic_type == "page_footnote"} == {
+ 6,
+ 7,
+ 8,
+ 9,
+ 10,
+ }
+ assert page.page_footnote_groups == [{6, 7, 8, 9, 10}]
+ assert lines[11].semantic_type is None
+
+
+def test_page_footnote_entries_split_first_line_indent_without_text() -> None:
+ """验证首行缩进模式把两个脚注起始行拆开,并吸收左对齐续行。"""
+
+ lines = [
+ _text_line("first", (87.0, 732.0, 245.0, 742.0), 0, effective_height=8.0, median_glyph_width=4.5),
+ _text_line("second", (83.0, 743.0, 293.0, 753.0), 1, effective_height=8.0, median_glyph_width=4.5),
+ _text_line("continuation", (70.0, 755.0, 276.0, 763.0), 2, effective_height=7.0, median_glyph_width=5.0),
+ _text_line("tail", (70.0, 766.0, 146.0, 773.0), 3, effective_height=7.0, median_glyph_width=5.0),
+ ]
+
+ entries = pdf_extractor._split_page_footnote_entries(
+ lines,
+ (595.0, 842.0),
+ )
+
+ assert [[line.source_index for line in entry] for entry in entries] == [
+ [0],
+ [1, 2, 3],
+ ]
+
+
+def test_page_footnote_entries_split_hanging_indent_and_tighten_boxes() -> None:
+ """验证 Boosting 型续行缩进拆成四条脚注,且异常高字符框不再互相覆盖。"""
+
+ page_size = (612.2833862304688, 858.8975830078125)
+ lines = [
+ _text_line(
+ "receipt",
+ (81.2767, 740.0383, 238.2958, 758.6347),
+ 66,
+ effective_height=18.5964,
+ median_glyph_width=3.92,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ "fund start",
+ (81.2767, 750.5583, 546.9993, 769.1547),
+ 67,
+ effective_height=9.0,
+ median_glyph_width=7.84,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ "fund continuation",
+ (119.6767, 761.0783, 364.8372, 779.6747),
+ 68,
+ effective_height=10.38,
+ median_glyph_width=4.78,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ "author",
+ (81.2767, 771.5983, 385.9195, 790.1947),
+ 69,
+ effective_height=9.0,
+ median_glyph_width=7.84,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ "corresponding",
+ (81.2767, 782.1183, 439.2661, 800.7147),
+ 70,
+ effective_height=9.0,
+ median_glyph_width=7.84,
+ semantic_type="page_footnote",
+ ),
+ ]
+ page = _prepared_text_page(*lines, page_size=page_size)
+ page.page_footnote_groups = [{line.source_index for line in lines}]
+
+ blocks = [
+ block
+ for block in pdf_extractor._finalize_prepared_page(page, page_index=0)
+ if block["type"] == "page_footnote"
+ ]
+
+ assert [block["content"] for block in blocks] == [
+ "receipt",
+ "fund start fund continuation",
+ "author",
+ "corresponding",
+ ]
+ assert [block["bbox"] for block in blocks] == [
+ [0.133, 0.867, 0.389, 0.878],
+ [0.133, 0.879, 0.893, 0.902],
+ [0.133, 0.904, 0.63, 0.914],
+ [0.133, 0.916, 0.717, 0.927],
+ ]
+ assert all(
+ previous["bbox"][3] < current["bbox"][1]
+ for previous, current in zip(blocks, blocks[1:])
+ )
+
+
+ ("rule_bbox", "table_bboxes"),
+ [
+ ((100.0, 750.0, 125.0, 752.0), []),
+ ((400.0, 750.0, 550.0, 752.0), []),
+ ((100.0, 750.0, 260.0, 752.0), [(90.0, 730.0, 500.0, 850.0)]),
+ (None, []),
+ ],
+)
+def test_page_footnote_rejects_decorative_formula_table_and_missing_rules(
+ rule_bbox: tuple[float, float, float, float] | None,
+ table_bboxes: list[tuple[float, float, float, float]],
+) -> None:
+ """验证装饰短线、居中公式线、表格线和无横线页底正文均不触发脚注。"""
+
+ lines = [
+ _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),
+ _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),
+ _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),
+ _text_line("bottom body", (100.0, 770.0, 500.0, 780.0), 3),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.table_bboxes = table_bboxes
+ if rule_bbox is not None:
+ page.drawing_lines = [pdf_extractor._AxisLine(rule_bbox, 1.0, "horizontal")]
+
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert all(line.semantic_type is None for line in lines)
+
+
+def test_page_footnote_rejects_collinear_rule_segment_next_to_table() -> None:
+ """验证表格框外的同高近邻断裂横线不会独立触发页脚注。"""
+
+ lines = [
+ _text_line("body one", (100.0, 100.0, 900.0, 110.0), 0),
+ _text_line("body two", (100.0, 130.0, 900.0, 140.0), 1),
+ _text_line("body three", (100.0, 160.0, 900.0, 170.0), 2),
+ _text_line("bottom table row", (100.0, 770.0, 500.0, 780.0), 3),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+ page.table_bboxes = [(280.0, 730.0, 900.0, 850.0)]
+ page.drawing_lines = [
+ pdf_extractor._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal"),
+ pdf_extractor._AxisLine((280.0, 750.0, 900.0, 752.0), 1.0, "horizontal"),
+ ]
+
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert all(line.semantic_type is None for line in lines)
+ assert page.page_footnote_groups == []
+
+
+ ("angle", "bbox"),
+ [
+ (270, (20.0, 250.0, 50.0, 650.0)),
+ (90, (930.0, 250.0, 960.0, 650.0)),
+ ],
+)
+def test_aside_text_accepts_tall_vertical_text_in_either_edge_band(
+ angle: int,
+ bbox: tuple[float, float, float, float],
+) -> None:
+ """验证横排正文占主导时,左右边缘的高占比垂直文字均标为侧栏。"""
+
+ lines = [
+ *[
+ _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index)
+ for index in range(6)
+ ],
+ _text_line("aside", bbox, 6, angle=angle, effective_height=20.0),
+ ]
+ page = _prepared_text_page(*lines, page_size=(1000.0, 1000.0))
+
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert lines[-1].semantic_type == "aside_text"
+ assert all(line.semantic_type is None for line in lines[:-1])
+
+
+def test_aside_text_rejects_short_internal_wide_and_non_dominant_rotated_text() -> None:
+ """验证短旋转行、页内旋转行、过宽边缘行及旋转正文均不误报侧栏。"""
+
+ upright_lines = [
+ _text_line(f"body {index}", (100.0, 100.0 + 30.0 * index, 900.0, 110.0 + 30.0 * index), index)
+ for index in range(10)
+ ]
+ rejected = [
+ _text_line("short", (20.0, 250.0, 50.0, 350.0), 10, angle=270, effective_height=20.0),
+ _text_line("internal", (400.0, 200.0, 430.0, 600.0), 11, angle=270, effective_height=20.0),
+ _text_line("wide", (0.0, 200.0, 100.0, 600.0), 12, angle=270, effective_height=20.0),
+ ]
+ page = _prepared_text_page(*upright_lines, *rejected, page_size=(1000.0, 1000.0))
+ pdf_extractor._classify_page_auxiliary_text(page)
+ assert all(line.semantic_type is None for line in rejected)
+
+ rotated_body = [
+ _text_line(f"upright {index}", (100.0, 100.0 + 20.0 * index, 300.0, 110.0 + 20.0 * index), index)
+ for index in range(4)
+ ]
+ rotated_body.append(
+ _text_line("edge but not aside", (20.0, 200.0, 50.0, 700.0), 4, angle=270, effective_height=20.0)
+ )
+ rotated_page = _prepared_text_page(*rotated_body, page_size=(1000.0, 1000.0))
+ pdf_extractor._classify_page_auxiliary_text(rotated_page)
+ assert rotated_body[-1].semantic_type is None
+
+
+def test_auxiliary_text_classification_is_content_independent() -> None:
+ """验证替换全部行文本不会改变页脚注空间分类结果。"""
+
+ geometries = [
+ (100.0, 100.0, 900.0, 110.0),
+ (100.0, 130.0, 900.0, 140.0),
+ (100.0, 160.0, 900.0, 170.0),
+ (100.0, 770.0, 500.0, 780.0),
+ (100.0, 788.0, 500.0, 798.0),
+ ]
+ first_lines = [_text_line(f"alpha {index}", bbox, index) for index, bbox in enumerate(geometries)]
+ second_lines = [_text_line(f"完全不同 {index}", bbox, index) for index, bbox in enumerate(geometries)]
+ first_page = _prepared_text_page(*first_lines, page_size=(1000.0, 1000.0))
+ second_page = _prepared_text_page(*second_lines, page_size=(1000.0, 1000.0))
+ for page in (first_page, second_page):
+ page.drawing_lines = [
+ pdf_extractor._AxisLine((100.0, 750.0, 260.0, 752.0), 1.0, "horizontal")
+ ]
+ pdf_extractor._classify_page_auxiliary_text(page)
+
+ assert [line.semantic_type for line in first_lines] == [
+ line.semantic_type for line in second_lines
+ ]
+ assert first_page.page_footnote_groups == second_page.page_footnote_groups
+
+
+def test_auxiliary_text_classifiers_do_not_read_line_text() -> None:
+ """静态守卫侧栏和页脚注分类函数不访问文本内容。"""
+
+ source = "\n".join(
+ inspect.getsource(function)
+ for function in (
+ pdf_extractor._classify_page_auxiliary_text,
+ pdf_extractor._classify_aside_text,
+ pdf_extractor._geometric_text_support_by_angle,
+ pdf_extractor._classify_page_footnotes,
+ pdf_extractor._rule_belongs_to_confirmed_table,
+ pdf_extractor._merge_overlapping_source_groups,
+ pdf_extractor._footnote_lane_members,
+ pdf_extractor._split_page_footnote_entries,
+ pdf_extractor._tight_page_footnote_bboxes,
+ )
+ )
+
+ assert ".text" not in source
+
+
+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(
+ "aside",
+ (2.0, 20.0, 5.0, 60.0),
+ 1,
+ angle=270,
+ effective_height=3.0,
+ semantic_type="aside_text",
+ ),
+ )
+
+ blocks = pdf_extractor._finalize_prepared_page(page, page_index=0)
+
+ assert {block["type"] for block in blocks} == {"page_footnote", "aside_text"}
+
+
def test_repeated_marginals_require_cross_page_evidence_and_separate_page_numbers() -> None:
"""验证重复页眉页脚与递增镜像页码被标注,孤立边缘行和正文不变。"""
@@ -1270,9 +1658,21 @@ def test_paragraph_title_detector_does_not_read_line_text() -> None:
assert ".text" not in source
[email protected]("block_type", ["doc_title", "paragraph_title", "header", "footer", "page_number", "equation"])
+ "block_type",
+ [
+ "doc_title",
+ "paragraph_title",
+ "header",
+ "footer",
+ "page_number",
+ "page_footnote",
+ "aside_text",
+ "equation",
+ ],
+)
def test_output_normalization_preserves_new_flash_types(block_type: str) -> None:
- """验证 Flash 新增文本类型和公式类型不会在归一化阶段退回 text。"""
+ """验证 Flash 文本语义类型和公式类型不会在归一化阶段退回 text。"""
block = pdf_extractor._normalize_output_block(
{"type": block_type, "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": "value"},
@@ -2094,11 +2494,11 @@ def _normalized_content_probe(text: str) -> str:
def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:
- """验证 demo1 参考文献逐条分块,第四页公式不误报且五个真实表格保留。"""
+ """验证 demo1 首页脚注、参考文献、公式与五个真实表格均保持正确。"""
model_list = _native_model_list("demo1.pdf")
- assert [len(page) for page in model_list] == [17, 9, 12, 18, 10, 9, 11, 8, 10, 7, 10, 26, 9]
+ assert [len(page) for page in model_list] == [16, 9, 12, 18, 10, 9, 11, 8, 10, 7, 10, 26, 9]
assert [sum(block["type"] == "table" for block in page) for page in model_list] == [
0,
0,
@@ -2118,6 +2518,14 @@ def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:
assert sum(block["type"] == "header" for page in model_list for block in page) == 12
assert sum(block["type"] == "page_number" for page in model_list for block in page) == 12
assert sum(block["type"] == "equation" for page in model_list for block in page) == 7
+ page1_footnotes = [block for block in model_list[0] if block["type"] == "page_footnote"]
+ assert len(page1_footnotes) == 1
+ assert page1_footnotes[0]["content"].startswith("* Corresponding author.")
+ copyright_block = next(
+ block for block in model_list[0] if block["content"].startswith("0022-1694/$")
+ )
+ assert copyright_block["type"] == "text"
+ assert "doi:10.1016/j.jhydrol.2005.01.006" in copyright_block["content"]
assert next(block for block in model_list[0] if block["content"] == "Abstract")["type"] == "paragraph_title"
assert next(block for block in model_list[6] if block["content"].startswith("4.2."))["type"] == "paragraph_title"
@@ -2350,7 +2758,7 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:
0,
]
assert [len(page) for page in model_list] == [
- 23,
+ 24,
15,
13,
21,
@@ -2413,6 +2821,42 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:
assert not missing_lines
+def test_demo3_auxiliary_text_types_match_real_page_geometry() -> None:
+ """验证真实 PDF 的首页侧栏及第 1、5、6、9 页脚注命中,公式页不误报。"""
+
+ model_list = _native_model_list("demo3.pdf")
+
+ assert [sum(block["type"] == "aside_text" for block in page) for page in model_list] == [
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ ]
+ assert [sum(block["type"] == "page_footnote" for block in page) for page in model_list] == [
+ 2,
+ 0,
+ 0,
+ 0,
+ 2,
+ 1,
+ 0,
+ 0,
+ 1,
+ 0,
+ ]
+ assert not [
+ block
+ for block in model_list[6]
+ if block["type"] in {"aside_text", "page_footnote"}
+ ]
+
+
def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> None:
"""验证首页标题稳定,第二页标题、公式和栏尾正文各自保持完整。"""
@@ -2433,6 +2877,7 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Non
released_code = next(
block for block in page1 if "TABLEFORMER.md" in block["content"]
)
+ aside = next(block for block in page1 if block["type"] == "aside_text")
introduction = next(
block for block in page1 if block["content"].startswith("Recently, semi-structured")
)
@@ -2450,7 +2895,9 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Non
assert len(front_matter) == len(front_matter_contents)
assert all(block["type"] == "text" for block in front_matter)
assert next(block for block in page1 if block["content"] == "Abstract")["type"] == "paragraph_title"
- assert released_code["type"] == "text"
+ assert released_code["type"] == "page_footnote"
+ assert aside["angle"] == 270
+ assert aside["bbox"][2] <= 0.12
assert introduction["content"].endswith("(Eisenschlos et al., 2021; Liu et al., 2021).")
assert nutshell["type"] == "text"
assert nutshell["content"].endswith("by serializing")
@@ -2659,5 +3106,6 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> N
final_footnote = next(
block for block in page5 if block["content"].startswith("3By perturbation")
)
- assert final_bullet["type"] == final_footnote["type"] == "text"
+ assert final_bullet["type"] == "text"
+ assert final_footnote["type"] == "page_footnote"
assert "3By perturbation" not in final_bullet["content"]