Skip to content

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

feat: add support for extracting signature bounding boxes and enhance raster image processing for signatures

myhloli5a1d999dc579
diff --git a/mineru/backend/flash/native_pdf/auxiliary_text.py b/mineru/backend/flash/native_pdf/auxiliary_text.py
index f819dcbc..61b52393 100644
--- a/mineru/backend/flash/native_pdf/auxiliary_text.py
+++ b/mineru/backend/flash/native_pdf/auxiliary_text.py
@@ -672,6 +672,137 @@ def _classify_repeated_page_marginals(pages: list[_PreparedPage]) -> None:
right.line.semantic_type = right.region
+def _classify_single_page_compound_headers(pages: list[_PreparedPage]) -> None:
+ """以拆分同行、字号收缩和正文栏右缘共同确认单页复合页眉。"""
+
+ if len(pages) != 1:
+ return
+ page = pages[0]
+ page_width, page_height = page.page_size
+ if page_width <= 0 or page_height <= 0:
+ return
+
+ row_groups: dict[tuple[int, int], list[_LineItem]] = {}
+ for line in page.remaining_lines:
+ if (
+ line.semantic_type is None
+ and line.visual_row_id is not None
+ and line.split_from_row
+ ):
+ row_groups.setdefault((line.angle, line.visual_row_id), []).append(line)
+
+ for (angle, _row_id), members in row_groups.items():
+ if len(members) < 2:
+ continue
+ local_page_width = page_height if angle in {90, 270} else page_width
+ local_page_height = page_width if angle in {90, 270} else page_height
+ local_members = [
+ (line, _rotate_bbox_to_upright(line.bbox, page.page_size, angle))
+ for line in members
+ ]
+ row_top = min(bbox[1] for _line, bbox in local_members)
+ row_bottom = max(bbox[3] for _line, bbox in local_members)
+ if row_top < 0 or row_bottom > 0.05 * local_page_height:
+ continue
+
+ row_left = min(bbox[0] for _line, bbox in local_members)
+ row_right = max(bbox[2] for _line, bbox in local_members)
+ related_body = [
+ (line, local_bbox)
+ for line in page.remaining_lines
+ if line.semantic_type is None
+ and line.angle == angle
+ and line not in members
+ and (
+ local_bbox := _rotate_bbox_to_upright(
+ line.bbox,
+ page.page_size,
+ angle,
+ )
+ )[1]
+ >= 0.05 * local_page_height
+ and local_bbox[2] - local_bbox[0] >= 0.3 * local_page_width
+ and _bbox_axis_overlap_ratio(
+ (row_left, row_top, row_right, row_bottom),
+ local_bbox,
+ axis="x",
+ )
+ >= 0.2
+ ]
+ if len(related_body) < 3:
+ continue
+ body_height = statistics.median(
+ _line_effective_height(line, bbox)
+ for line, bbox in related_body
+ )
+ row_height = max(
+ _line_effective_height(line, bbox)
+ for line, bbox in local_members
+ )
+ if row_height > 0.85 * body_height:
+ continue
+ body_right = statistics.median(bbox[2] for _line, bbox in related_body)
+ has_right_sidecar = any(
+ bbox[2] - bbox[0] <= max(4.0 * row_height, 0.12 * local_page_width)
+ and abs(bbox[2] - body_right) <= max(3.0, 0.02 * local_page_width)
+ for _line, bbox in local_members
+ )
+ if has_right_sidecar:
+ for line, _bbox in local_members:
+ line.semantic_type = "header"
+
+
+def _classify_isolated_first_page_footer(pages: list[_PreparedPage]) -> None:
+ """用多页首页的极底位置、正文尺度和孤立净空补标唯一页脚。"""
+
+ if len(pages) < 2:
+ return
+ page = pages[0]
+ page_width, page_height = page.page_size
+ if page_width <= 0 or page_height <= 0:
+ return
+
+ body_lines = [
+ line
+ for line in page.remaining_lines
+ if line.semantic_type is None
+ and line.angle == 0
+ and line.bbox[2] - line.bbox[0] >= 0.3 * page_width
+ and 0.1 * page_height <= _bbox_center_y(line.bbox) <= 0.94 * page_height
+ ]
+ if len(body_lines) < 4:
+ return
+ body_height = statistics.median(
+ _line_effective_height(line, line.bbox)
+ for line in body_lines
+ )
+ body_bottom = max(line.bbox[3] for line in body_lines)
+ if body_bottom < 0.7 * page_height:
+ return
+ container_bboxes = [
+ bbox
+ for block in page.fixed_blocks
+ if (bbox := _coerce_bbox(block.get("bbox"))) is not None
+ ]
+ candidates = [
+ line
+ for line in page.remaining_lines
+ if line.semantic_type is None
+ and line.angle == 0
+ and line.bbox[1] >= 0.94 * page_height
+ and line.bbox[2] - line.bbox[0] <= 0.6 * page_width
+ and abs(_bbox_center_x(line.bbox) - 0.5 * page_width) <= 0.08 * page_width
+ and _line_effective_height(line, line.bbox) <= 0.95 * body_height
+ and line.bbox[1] - body_bottom >= 1.5 * body_height
+ and not any(
+ _bbox_intersects(line.bbox, container_bbox)
+ for container_bbox in container_bboxes
+ )
+ ]
+ if len(candidates) == 1:
+ candidates[0].semantic_type = "footer"
+
+
def _classify_repeated_visual_headers(pages: list[_PreparedPage]) -> None:
"""仅按页首位置与跨页重复几何,把整体图片重标为视觉页眉。"""
@@ -778,7 +909,7 @@ def _build_marginal_candidate(
) -> _MarginalCandidate | None:
"""把页面上下百分之十五内的常规小行转换成跨页比较候选。"""
- if line.semantic_type is not None:
+ if line.semantic_type not in {None, "page_footnote"}:
return None
local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, line.angle)
local_page_size = (page_size[1], page_size[0]) if line.angle in {90, 270} else page_size
@@ -787,6 +918,9 @@ def _build_marginal_candidate(
return None
normalized_center_y = _bbox_center_y(local_bbox) / local_page_height
normalized_center_x = _bbox_center_x(local_bbox) / local_page_width
+ if line.semantic_type == "page_footnote" and normalized_center_y < 0.94:
+ # 只允许极底部脚注重新参加跨页强证据匹配,正文脚注继续保留原类型。
+ return None
if normalized_center_y <= 0.15:
region: Literal["header", "footer", "side"] = "header"
elif normalized_center_y >= 0.85:
diff --git a/mineru/backend/flash/native_pdf/formulas.py b/mineru/backend/flash/native_pdf/formulas.py
index bfc91d54..21f79a20 100644
--- a/mineru/backend/flash/native_pdf/formulas.py
+++ b/mineru/backend/flash/native_pdf/formulas.py
@@ -48,6 +48,7 @@ _FORMULA_NUMBER_SUFFIX_RE = re.compile(
)
+_FORMULA_PAGE_MARGIN_RATIO = 0.05
_VECTOR_FORMULA_COMPLEX_SEGMENTS = 8
_VECTOR_FORMULA_MIN_PATHS = 5
_VECTOR_FORMULA_MIN_COMPLEX_PATHS = 5
@@ -335,8 +336,7 @@ def _is_vector_formula_core(
and width >= 1.4 * height
):
return False
- page_height = page_size[1]
- if bbox[3] <= 0.05 * page_height or bbox[1] >= 0.95 * page_height:
+ if _is_formula_component_in_page_margin(bbox, page_size[1]):
return False
if any(
_bbox_overlap_in_smaller(bbox, container_bbox) >= 0.5
@@ -349,6 +349,13 @@ def _is_vector_formula_core(
)
+def _is_formula_component_in_page_margin(bbox: BBox, page_height: float) -> bool:
+ """仅当公式组件完全落在页面顶部或底部边缘带时排除。"""
+
+ margin = _FORMULA_PAGE_MARGIN_RATIO * page_height
+ return bbox[3] <= margin or bbox[1] >= page_height - margin
+
+
def _vector_formula_collides_with_text(
formula_bbox: BBox,
line: _LineItem,
@@ -563,6 +570,7 @@ def _build_formula_like_blocks(
effective_heights = [_line_effective_height(line, bbox) for line, bbox in angle_geometry]
median_height = statistics.median(effective_heights) if effective_heights else 1.0
local_page_width = page_size[1] if angle in {90, 270} else page_size[0]
+ local_page_height = page_size[0] if angle in {90, 270} else page_size[1]
lanes = _infer_text_lanes(angle_geometry, local_page_width, median_height)
for lane in lanes:
if lane.is_span:
@@ -571,6 +579,10 @@ def _build_formula_like_blocks(
for line, bbox in list(lane.lines):
if (
line.compact_formula_cluster
+ and not _is_formula_component_in_page_margin(
+ bbox,
+ local_page_height,
+ )
and _is_isolated_compact_formula_cluster(
(line, bbox),
lane,
@@ -644,6 +656,14 @@ def _build_formula_like_blocks(
axis="y",
) < 0.2:
continue
+ component_bbox = _bbox_union_many(
+ [member_bbox for _member_line, member_bbox in members]
+ )
+ if _is_formula_component_in_page_margin(
+ component_bbox,
+ local_page_height,
+ ):
+ continue
block = _formula_members_to_block(
members,
page_size,
diff --git a/mineru/backend/flash/native_pdf/graphics.py b/mineru/backend/flash/native_pdf/graphics.py
index efd0c681..2d1c61cb 100644
--- a/mineru/backend/flash/native_pdf/graphics.py
+++ b/mineru/backend/flash/native_pdf/graphics.py
@@ -45,6 +45,9 @@ from .line_merging import _join_formula_visual_row
_MIN_RASTER_IMAGE_PAGE_AREA_RATIO = 0.0038
+_SIGNATURE_IMAGE_BBOX_DEDUP_TOLERANCE = 0.5
+
+
_MIN_FORM_IMAGE_PAGE_AREA_RATIO = 0.01
@@ -871,12 +874,21 @@ def _merge_inline_raster_image_candidates(
return merged_specs
+def _image_bboxes_are_near_equal(first: BBox, second: BBox) -> bool:
+ """用亚 point 边界容差识别同一图片框,避免签名与点阵来源重复输出。"""
+
+ return all(
+ abs(first_value - second_value) <= _SIGNATURE_IMAGE_BBOX_DEDUP_TOLERANCE
+ for first_value, second_value in zip(first, second, strict=True)
+ )
+
+
def _build_raster_image_blocks(
source: _PageSource,
container_blocks: list[dict[str, Any]],
claimed_line_indices: set[int],
) -> tuple[list[dict[str, Any]], set[int]]:
- """过滤点阵图、避让高优先级容器,并唯一认领图片内部的原生文本。"""
+ """过滤点阵图并接纳签名框,避让高优先级容器后唯一认领内部文本。"""
page_area = max(0.0, source.page_size[0]) * max(0.0, source.page_size[1])
if page_area <= 0:
@@ -887,7 +899,25 @@ def _build_raster_image_blocks(
for block in container_blocks
if (bbox := _coerce_bbox(block.get("bbox"))) is not None
]
- candidate_bboxes: list[BBox] = []
+ signature_bboxes: list[BBox] = []
+ for raw_bbox in source.signature_bboxes:
+ bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)
+ if bbox is None:
+ continue
+ if any(
+ _bbox_overlap_in_smaller(bbox, container_bbox)
+ >= _IMAGE_CONTAINER_OVERLAP_THRESHOLD
+ for container_bbox in container_bboxes
+ ):
+ continue
+ if not any(
+ _image_bboxes_are_near_equal(bbox, existing_bbox)
+ for existing_bbox in signature_bboxes
+ ):
+ # 已由注释可见性和 /AP 严格确认的签名不再套用普通点阵图面积门槛。
+ signature_bboxes.append(bbox)
+
+ raster_bboxes: list[BBox] = []
for raw_bbox in source.image_bboxes:
bbox = _clip_bbox(_coerce_bbox(raw_bbox), source.page_size)
if bbox is None or _bbox_area(bbox) / page_area < _MIN_RASTER_IMAGE_PAGE_AREA_RATIO:
@@ -897,15 +927,28 @@ def _build_raster_image_blocks(
for container_bbox in container_bboxes
):
continue
- candidate_bboxes.append(bbox)
- if not candidate_bboxes:
+ if any(
+ _image_bboxes_are_near_equal(bbox, signature_bbox)
+ for signature_bbox in signature_bboxes
+ ):
+ continue
+ raster_bboxes.append(bbox)
+ if not raster_bboxes and not signature_bboxes:
return [], set()
- candidate_specs = _merge_inline_raster_image_candidates(
- source,
- candidate_bboxes,
- container_bboxes,
- claimed_line_indices,
+ candidate_specs = (
+ _merge_inline_raster_image_candidates(
+ source,
+ raster_bboxes,
+ container_bboxes,
+ claimed_line_indices,
+ )
+ if raster_bboxes
+ else []
+ )
+ candidate_specs.extend((bbox, None) for bbox in signature_bboxes)
+ candidate_specs.sort(
+ key=lambda item: (item[0][1], item[0][0], item[0][3], item[0][2])
)
candidate_bboxes = [bbox for bbox, _row_id in candidate_specs]
diff --git a/mineru/backend/flash/native_pdf/index_blocks.py b/mineru/backend/flash/native_pdf/index_blocks.py
index daa80d6d..c6cd494e 100644
--- a/mineru/backend/flash/native_pdf/index_blocks.py
+++ b/mineru/backend/flash/native_pdf/index_blocks.py
@@ -46,8 +46,10 @@ def _extract_index_blocks(
lines: list[_LineItem],
page_size: tuple[float, float],
container_bboxes: list[BBox],
+ *,
+ require_heading: bool = False,
) -> tuple[list[dict[str, object]], list[_LineItem]]:
- """用页码行尾和稳定版式识别目录区域,并返回独立 index 块。"""
+ """用页码行尾和稳定版式识别目录;预判阶段可强制要求几何目录标题。"""
claimed_line_ids: set[int] = set()
blocks: list[dict[str, object]] = []
@@ -71,6 +73,8 @@ def _extract_index_blocks(
candidate,
local_page_width,
)
+ if require_heading and heading_row is None:
+ continue
if heading_row is not None:
for line in heading_row.members:
line.semantic_type = "paragraph_title"
diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.py
index a8d674ee..c3ede64f 100644
--- a/mineru/backend/flash/native_pdf/models.py
+++ b/mineru/backend/flash/native_pdf/models.py
@@ -127,6 +127,7 @@ class _PageSource:
chars: list[Char]
drawing_lines: list[_AxisLine]
image_bboxes: list[BBox] = field(default_factory=list)
+ signature_bboxes: list[BBox] = field(default_factory=list)
form_bboxes: list[BBox] = field(default_factory=list)
path_infos: list[PDFPathInfo] = field(default_factory=list)
diff --git a/mineru/backend/flash/native_pdf/native_text.py b/mineru/backend/flash/native_pdf/native_text.py
index ab0981f5..68b6d134 100644
--- a/mineru/backend/flash/native_pdf/native_text.py
+++ b/mineru/backend/flash/native_pdf/native_text.py
@@ -33,6 +33,9 @@ _PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
_PDFTEXT_ROTATION_SPLIT_THRESHOLD_DEGREES = 44.9
_PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES = 0.1
_SUPPORTED_PDFTEXT_LINE_ANGLES = (0.0, 90.0, 270.0)
+_PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES = 30.0
+_PDFTEXT_HORIZONTAL_BASELINE_MAX_ANGLE_DEGREES = 2.0
+_PDFTEXT_HORIZONTAL_BASELINE_MAX_DISPERSION_RATIO = 0.75
def _build_native_line_items(
@@ -45,15 +48,18 @@ def _build_native_line_items(
items: list[_LineItem] = []
supported_lines = [
- child_line
+ (child_line, visual_angle)
for pdf_line in pdf_lines
for child_line in _split_pdftext_line_by_rotation(pdf_line)
- if _is_supported_pdftext_line_rotation(
- child_line.get("rotation"),
- page_rotation=page_rotation,
+ if (
+ visual_angle := _resolve_pdftext_line_angle(
+ child_line,
+ page_rotation=page_rotation,
+ )
)
+ is not None
]
- for visual_row_id, pdf_line in enumerate(supported_lines):
+ for visual_row_id, (pdf_line, visual_angle) in enumerate(supported_lines):
bbox = _clip_bbox(_coerce_bbox(pdf_line.get("bbox")), page_size)
if bbox is None:
continue
@@ -62,7 +68,7 @@ def _build_native_line_items(
coarse_item = _LineItem(
text="".join(str(span.get("text") or "") for span in spans),
bbox=bbox,
- angle=(_normalize_pdftext_angle(pdf_line.get("rotation")) + int(page_rotation or 0)) % 360,
+ angle=visual_angle,
source_index=-1,
chars=chars,
visual_row_id=visual_row_id,
@@ -161,6 +167,95 @@ def _is_supported_pdftext_line_rotation(value: Any, *, page_rotation: int) -> bo
)
+def _resolve_pdftext_line_angle(
+ pdf_line: dict[str, Any],
+ *,
+ page_rotation: int,
+) -> int | None:
+ """解析视觉文字方向,并用字符基线纠正字体 shear 造成的伪斜向行。"""
+
+ visual_angle = (
+ _pdftext_angle_degrees(pdf_line.get("rotation"))
+ + int(page_rotation or 0)
+ ) % 360.0
+ for supported_angle in _SUPPORTED_PDFTEXT_LINE_ANGLES:
+ if (
+ _circular_angle_distance(visual_angle, supported_angle)
+ <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
+ ):
+ return int(supported_angle)
+ if (
+ _circular_angle_distance(visual_angle, 0.0)
+ <= _PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES
+ and _pdftext_line_has_horizontal_char_baseline(pdf_line)
+ ):
+ return 0
+ return None
+
+
+def _pdftext_line_has_horizontal_char_baseline(
+ pdf_line: dict[str, Any],
+) -> bool:
+ """用字符中心的水平基线确认小角度只来自仿斜体变换,而非真实旋转。"""
+
+ visible_bboxes: list[BBox] = []
+ for span in pdf_line.get("spans") or []:
+ if not isinstance(span, dict):
+ continue
+ for char in span.get("chars") or []:
+ if not isinstance(char, dict):
+ continue
+ raw_char = str(char.get("char") or "")
+ bbox = _coerce_bbox(char.get("bbox"))
+ if (
+ bbox is not None
+ and raw_char.isprintable()
+ and not raw_char.isspace()
+ ):
+ visible_bboxes.append(bbox)
+ if len(visible_bboxes) < 4:
+ return False
+
+ line_bbox = _bbox_union_many(visible_bboxes)
+ line_width = line_bbox[2] - line_bbox[0]
+ line_height = line_bbox[3] - line_bbox[1]
+ glyph_heights = [bbox[3] - bbox[1] for bbox in visible_bboxes]
+ median_height = statistics.median(glyph_heights)
+ if (
+ line_height <= 0
+ or median_height <= 0
+ or line_width / line_height < 3.0
+ ):
+ return False
+
+ ordered = sorted(
+ visible_bboxes,
+ key=lambda bbox: ((bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0),
+ )
+ first_center = (
+ (ordered[0][0] + ordered[0][2]) / 2.0,
+ (ordered[0][1] + ordered[0][3]) / 2.0,
+ )
+ last_center = (
+ (ordered[-1][0] + ordered[-1][2]) / 2.0,
+ (ordered[-1][1] + ordered[-1][3]) / 2.0,
+ )
+ baseline_width = last_center[0] - first_center[0]
+ if baseline_width <= 0:
+ return False
+ baseline_angle = abs(
+ math.degrees(
+ math.atan2(last_center[1] - first_center[1], baseline_width)
+ )
+ )
+ centers_y = [(bbox[1] + bbox[3]) / 2.0 for bbox in ordered]
+ return (
+ baseline_angle <= _PDFTEXT_HORIZONTAL_BASELINE_MAX_ANGLE_DEGREES
+ and max(centers_y) - min(centers_y)
+ <= _PDFTEXT_HORIZONTAL_BASELINE_MAX_DISPERSION_RATIO * median_height
+ )
+
+
def _split_native_visual_runs(
line: _LineItem,
page_size: tuple[float, float],
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 23c746d7..0d4cbc46 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -59,11 +59,13 @@ from .formulas import (
_build_vector_formula_blocks,
)
from .auxiliary_text import (
+ _classify_isolated_first_page_footer,
_classify_page_number_outer_companions,
_classify_page_auxiliary_text,
_classify_rule_delimited_headers,
_classify_repeated_page_marginals,
_classify_repeated_visual_headers,
+ _classify_single_page_compound_headers,
)
from .titles import (
_classify_page_titles,
@@ -158,6 +160,10 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
pdf_doc.get_page_image_infos(page_idx)
for page_idx in range(pdf_doc.page_count)
]
+ page_signature_bboxes = [
+ pdf_doc.get_page_signature_bboxes(page_idx)
+ for page_idx in range(pdf_doc.page_count)
+ ]
watermark_fingerprints = _detect_repeated_raster_watermark_fingerprints(
page_image_infos,
page_sizes,
@@ -183,6 +189,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
page_size,
watermark_fingerprints,
),
+ signature_bboxes=page_signature_bboxes[page_idx],
form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),
path_infos=pdf_doc.get_page_path_infos(page_idx),
)
@@ -190,8 +197,10 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
_classify_repeated_visual_headers(prepared_pages)
_classify_repeated_page_marginals(prepared_pages)
+ _classify_single_page_compound_headers(prepared_pages)
_classify_rule_delimited_headers(prepared_pages)
_classify_page_number_outer_companions(prepared_pages)
+ _classify_isolated_first_page_footer(prepared_pages)
document_body_profile = _infer_document_body_profile(prepared_pages)
return [
_finalize_prepared_page(
@@ -313,7 +322,20 @@ def _finalize_prepared_page(
"""按预分类语义、公式、标题、正文的优先级完成单页文本并排序。"""
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]
+ unresolved_lines = [line for line in prepared.remaining_lines if line.semantic_type is None]
+ container_bboxes = [block["bbox"] for block in prepared.fixed_blocks]
+ index_blocks, unresolved_lines = _extract_index_blocks(
+ unresolved_lines,
+ prepared.page_size,
+ container_bboxes,
+ require_heading=True,
+ )
+ semantic_lines.extend(
+ line
+ for line in unresolved_lines
+ if line.semantic_type is not None
+ )
+ formula_input = [line for line in unresolved_lines if line.semantic_type is None]
formula_blocks, remaining_lines = _build_formula_like_blocks(
formula_input,
prepared.table_bboxes,
@@ -324,12 +346,22 @@ def _finalize_prepared_page(
prepared.page_size,
prepared.table_bboxes,
)
- container_bboxes = [block["bbox"] for block in prepared.fixed_blocks]
- index_blocks, remaining_lines = _extract_index_blocks(
+ fallback_index_blocks, remaining_lines = _extract_index_blocks(
remaining_lines,
prepared.page_size,
container_bboxes,
)
+ index_blocks.extend(fallback_index_blocks)
+ semantic_lines.extend(
+ line
+ for line in remaining_lines
+ if line.semantic_type is not None
+ )
+ remaining_lines = [
+ line
+ for line in remaining_lines
+ if line.semantic_type is None
+ ]
title_container_bboxes = [
block["bbox"]
for block in prepared.fixed_blocks
@@ -381,7 +413,7 @@ def _finalize_prepared_page(
def _analyze_page_source(source: _PageSource) -> list[dict[str, Any]]:
"""兼容单页测试入口;单页不凭边缘位置猜测页眉、页脚或页码。"""
- if not source.lines and not source.image_bboxes:
+ if not source.lines and not source.image_bboxes and not source.signature_bboxes:
return []
return _finalize_prepared_page(_prepare_page_source(source), page_index=0)
diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.py
index 52b46916..4e509e34 100644
--- a/mineru/backend/flash/native_pdf/tables.py
+++ b/mineru/backend/flash/native_pdf/tables.py
@@ -109,6 +109,13 @@ def _detect_table_candidates(
)
for bbox in [*excluded_bboxes, *filled_grid_bboxes]
]
+ local_closed_grid_excluded_bboxes = [
+ *local_excluded_bboxes,
+ *[
+ _rotate_bbox_to_upright(bbox, source.page_size, angle)
+ for bbox in source.form_bboxes
+ ],
+ ]
rule_candidates.extend(
_build_rule_table_candidates(
rows,
@@ -121,6 +128,17 @@ def _detect_table_candidates(
excluded_bboxes=local_excluded_bboxes,
)
)
+ rule_candidates.extend(
+ _build_closed_rule_grid_candidates(
+ rows,
+ angle_lines,
+ source.page_size,
+ angle,
+ median_height,
+ local_axis_lines,
+ local_closed_grid_excluded_bboxes,
+ )
+ )
merged_rule_candidates = [
candidate
for candidate in _merge_table_candidates(rule_candidates)
@@ -690,13 +708,167 @@ def _expand_candidates_to_connected_rule_grids(
return candidates
+def _build_closed_rule_grid_candidates(
+ rows: list[_VisualRow],
+ lines: list[_LineItem],
+ page_size: tuple[float, float],
+ angle: int,
+ median_height: float,
+ axis_lines: list[_LocalAxisLine],
+ excluded_bboxes: list[BBox],
+) -> list[_TableCandidate]:
+ """用闭合物理网格接纳含空行或仅有表头文本的稀疏表格。"""
+
+ candidates: list[_TableCandidate] = []
+ for component in _connected_rule_grid_components(axis_lines, median_height):
+ grid_bbox = _bbox_union_many([rule.bbox for rule in component])
+ if any(
+ _bbox_overlap_in_smaller(grid_bbox, excluded_bbox) >= 0.5
+ for excluded_bbox in excluded_bboxes
+ ):
+ continue
+ core_rows = _rows_inside_rule_interval(
+ rows,
+ grid_bbox,
+ excluded_bboxes,
+ )
+ if not core_rows:
+ continue
+
+ vertical_positions = _closed_grid_vertical_track_positions(
+ component,
+ axis_lines,
+ median_height,
+ )
+ if len(vertical_positions) < 2:
+ continue
+ edge_tolerance = max(2.0, 0.25 * median_height)
+ if (
+ abs(vertical_positions[0] - grid_bbox[0]) > edge_tolerance
+ or abs(vertical_positions[-1] - grid_bbox[2]) > edge_tolerance
+ ):
+ continue
+
+ if len(component) == 2:
+ if len(vertical_positions) < 3:
+ continue
+ occupied_columns = _count_occupied_closed_grid_columns(
+ core_rows,
+ vertical_positions,
+ )
+ if occupied_columns < 2:
+ continue
+
+ caption_line = _find_table_caption(
+ lines,
+ grid_bbox,
+ page_size,
+ angle,
+ median_height,
+ )
+ candidate = _expand_rule_table_candidate(
+ [component[0], component[-1]],
+ core_rows,
+ rows,
+ lines,
+ page_size,
+ angle,
+ median_height,
+ caption_line,
+ )
+ candidate.score = float(
+ 100 + len(component) + len(vertical_positions)
+ )
+ candidates.append(candidate)
+ return candidates
+
+
+def _closed_grid_vertical_track_positions(
+ horizontal_rules: list[_LocalAxisLine],
+ axis_lines: list[_LocalAxisLine],
+ median_height: float,
+) -> list[float]:
+ """收集覆盖首末横边界中心跨度至少九成的竖轨并合并重复路径。"""
+
+ top = _bbox_center_y(horizontal_rules[0].bbox)
+ bottom = _bbox_center_y(horizontal_rules[-1].bbox)
+ grid_height = max(0.1, bottom - top)
+ left = min(rule.bbox[0] for rule in horizontal_rules)
+ right = max(rule.bbox[2] for rule in horizontal_rules)
+ edge_tolerance = max(2.0, 0.25 * median_height)
+ raw_positions = []
+ for line in axis_lines:
+ if line.orientation != "vertical":
+ continue
+ overlap = max(
+ 0.0,
+ min(line.bbox[3], bottom) - max(line.bbox[1], top),
+ )
+ position = _bbox_center_x(line.bbox)
+ if (
+ overlap / grid_height >= 0.9
+ and left - edge_tolerance <= position <= right + edge_tolerance
+ ):
+ raw_positions.append(position)
+
+ position_tolerance = max(1.0, 0.1 * median_height)
+ position_groups: list[list[float]] = []
+ for position in sorted(raw_positions):
+ if (
+ position_groups
+ and abs(position - statistics.mean(position_groups[-1]))
+ <= position_tolerance
+ ):
+ position_groups[-1].append(position)
+ else:
+ position_groups.append([position])
+ return [statistics.mean(group) for group in position_groups]
+
+
+def _count_occupied_closed_grid_columns(
+ rows: list[_VisualRow],
+ vertical_positions: list[float],
+) -> int:
+ """按文本片段中心统计闭合网格中实际有文字的物理列数。"""
+
+ occupied_columns: set[int] = set()
+ for row in rows:
+ for fragment in row.fragments:
+ center_x = _bbox_center_x(fragment.local_bbox)
+ matching_columns = [
+ index
+ for index, (left, right) in enumerate(
+ zip(vertical_positions, vertical_positions[1:])
+ )
+ if left < center_x < right
+ ]
+ if len(matching_columns) == 1:
+ occupied_columns.add(matching_columns[0])
+ return len(occupied_columns)
+
+
def _connected_rule_grid_bboxes(
axis_lines: list[_LocalAxisLine],
median_height: float,
) -> list[BBox]:
"""把端点一致且由外轨或至少两条列轨贯穿的相邻横线组成网格框。"""
- output: list[BBox] = []
+ return [
+ _bbox_union_many([rule.bbox for rule in component])
+ for component in _connected_rule_grid_components(
+ axis_lines,
+ median_height,
+ )
+ ]
+
+
+def _connected_rule_grid_components(
+ axis_lines: list[_LocalAxisLine],
+ median_height: float,
+) -> list[list[_LocalAxisLine]]:
+ """保留连续网格的横边界成员,供精确外轨和横边界数量校验。"""
+
+ output: list[list[_LocalAxisLine]] = []
for rule_group in _group_long_horizontal_rules(axis_lines, median_height):
components: list[list[_LocalAxisLine]] = []
for rule in rule_group:
@@ -709,11 +881,7 @@ def _connected_rule_grid_bboxes(
components.append([rule])
else:
components[-1].append(rule)
- output.extend(
- _bbox_union_many([rule.bbox for rule in component])
- for component in components
- if len(component) >= 2
- )
+ output.extend(component for component in components if len(component) >= 2)
return output
diff --git a/mineru/backend/flash/native_pdf/titles.py b/mineru/backend/flash/native_pdf/titles.py
index 502c8bc4..35befe99 100644
--- a/mineru/backend/flash/native_pdf/titles.py
+++ b/mineru/backend/flash/native_pdf/titles.py
@@ -197,9 +197,10 @@ def _infer_document_body_profile(
font_pages: dict[tuple[str, int], set[int]] = {}
font_widths: dict[tuple[str, int], float] = {}
font_weights: dict[tuple[str, int], list[float]] = {}
- for _height, page_index, width, font, weight in samples:
- if font is None:
+ for height, page_index, width, font, weight in samples:
+ if font is None or not 0.9 <= height / body_height <= 1.1:
continue
+ # 常规字体支持必须来自正文高度带;跨页重复的大标题不能反向污染正文画像。
font_pages.setdefault(font, set()).add(page_index)
font_widths[font] = font_widths.get(font, 0.0) + width
if weight is not None:
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 265480d5..c78c3b71 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -384,6 +384,22 @@ class PDFDocument:
page_rotation = 0
return _extract_page_form_bboxes(page, page_bbox, page_rotation)
+ def get_page_signature_bboxes(self, page_idx: int) -> list[BBox]:
+ """提取带可见正常外观的数字签名控件,并转换为页面左上原点坐标。"""
+
+ with self._open_page(page_idx) as page:
+ page_bbox = _normalize_pdf_page_bbox(page.get_bbox())
+ try:
+ page_rotation = int(page.get_rotation()) % 360
+ except Exception:
+ page_rotation = 0
+ return _extract_page_signature_bboxes(
+ page,
+ page_bbox,
+ page_rotation,
+ form_handle=getattr(self._pdf_doc, "formenv", None),
+ )
+
# ------------------------------------------------------------------ #
# Classification
# ------------------------------------------------------------------ #
@@ -444,7 +460,14 @@ class PDFDocument:
if self._pdf_doc_opened is None:
with _pdfium_lock:
if self._pdf_doc_opened is None:
- self._pdf_doc_opened = pdfium.PdfDocument(self._pdf_bytes)
+ pdf_doc = pdfium.PdfDocument(self._pdf_bytes)
+ try:
+ # 表单环境必须在打开页面前初始化,签名字段类型才能沿 Parent 正确继承。
+ pdf_doc.init_forms()
+ except Exception:
+ # 异常表单不能阻断普通文本、绘图和渲染接口。
+ pass
+ self._pdf_doc_opened = pdf_doc
return self._pdf_doc_opened
@contextmanager
@@ -1186,6 +1209,159 @@ def _form_bbox_from_object(
return visual_left, visual_top, visual_right, visual_bottom
+def _get_annotation_string(raw_annot: Any, key: bytes) -> str | None:
+ """读取 PDFium 注释字典中的 UTF-16 字符串或名称,异常和空值统一返回 None。"""
+
+ try:
+ required = int(pdfium_c.FPDFAnnot_GetStringValue(raw_annot, key, None, 0))
+ except Exception:
+ return None
+ if required <= 2:
+ return None
+ try:
+ buffer = (ctypes.c_ushort * ((required + 1) // 2))()
+ actual = int(
+ pdfium_c.FPDFAnnot_GetStringValue(
+ raw_annot,
+ key,
+ buffer,
+ ctypes.sizeof(buffer),
+ )
+ )
+ except Exception:
+ return None
+ if actual <= 2 or actual > ctypes.sizeof(buffer):
+ return None
+ try:
+ return bytes(buffer)[: actual - 2].decode("utf-16-le")
+ except UnicodeDecodeError:
+ return None
+
+
+def _signature_bbox_from_annotation(
+ raw_annot: Any,
+ page_bbox: BBox,
+ page_rotation: int,
+ form_handle: Any | None,
+) -> BBox | None:
+ """校验一个可见签名 Widget,并把注释矩形裁剪到视觉页面坐标。"""
+
+ try:
+ if int(pdfium_c.FPDFAnnot_GetSubtype(raw_annot)) != pdfium_c.FPDF_ANNOT_WIDGET:
+ return None
+ flags = int(pdfium_c.FPDFAnnot_GetFlags(raw_annot))
+ except Exception:
+ return None
+ hidden_flags = (
+ pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE
+ | pdfium_c.FPDF_ANNOT_FLAG_HIDDEN
+ | pdfium_c.FPDF_ANNOT_FLAG_NOVIEW
+ )
+ if flags & hidden_flags:
+ return None
+ field_type: int | None = None
+ if form_handle is not None:
+ try:
+ field_type = int(
+ pdfium_c.FPDFAnnot_GetFormFieldType(form_handle, raw_annot)
+ )
+ except Exception:
+ field_type = None
+ if field_type == pdfium_c.FPDF_FORMFIELD_SIGNATURE:
+ pass
+ elif field_type is None or field_type <= pdfium_c.FPDF_FORMFIELD_UNKNOWN:
+ if _get_annotation_string(raw_annot, b"FT") != "Sig":
+ return None
+ else:
+ return None
+
+ # 正常外观长度只有 UTF-16 终止符时等价于无 /AP /N,不能形成可见签名。
+ try:
+ appearance_length = int(
+ pdfium_c.FPDFAnnot_GetAP(
+ raw_annot,
+ pdfium_c.FPDF_ANNOT_APPEARANCEMODE_NORMAL,
+ None,
+ 0,
+ )
+ )
+ except Exception:
+ return None
+ if appearance_length <= 2:
+ return None
+
+ rect = pdfium_c.FS_RECTF()
+ try:
+ if not pdfium_c.FPDFAnnot_GetRect(raw_annot, ctypes.byref(rect)):
+ return None
+ except Exception:
+ return None
+ raw_bbox = _normalize_pdf_page_bbox(
+ (float(rect.left), float(rect.bottom), float(rect.right), float(rect.top))
+ )
+ if not all(math.isfinite(value) for value in raw_bbox):
+ return None
+ page_points = [
+ _transform_drawing_point(point, page_bbox, page_rotation)
+ for point in (
+ (raw_bbox[0], raw_bbox[1]),
+ (raw_bbox[0], raw_bbox[3]),
+ (raw_bbox[2], raw_bbox[1]),
+ (raw_bbox[2], raw_bbox[3]),
+ )
+ ]
+ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)
+ visual_bbox = (
+ max(0.0, min(point[0] for point in page_points)),
+ max(0.0, min(point[1] for point in page_points)),
+ min(page_width, max(point[0] for point in page_points)),
+ min(page_height, max(point[1] for point in page_points)),
+ )
+ if visual_bbox[2] <= visual_bbox[0] or visual_bbox[3] <= visual_bbox[1]:
+ return None
+ return visual_bbox
+
+
+def _extract_page_signature_bboxes(
+ page: pdfium.PdfPage,
+ page_bbox: BBox,
+ page_rotation: int,
+ *,
+ form_handle: Any | None = None,
+) -> list[BBox]:
+ """遍历页面签名注释;逐个关闭句柄,并隔离损坏注释造成的异常。"""
+
+ try:
+ annot_count = max(0, int(pdfium_c.FPDFPage_GetAnnotCount(page.raw)))
+ except Exception:
+ return []
+ signature_bboxes: list[BBox] = []
+ for annot_index in range(annot_count):
+ raw_annot = None
+ try:
+ raw_annot = pdfium_c.FPDFPage_GetAnnot(page.raw, annot_index)
+ if not raw_annot:
+ continue
+ signature_bbox = _signature_bbox_from_annotation(
+ raw_annot,
+ page_bbox,
+ page_rotation,
+ form_handle,
+ )
+ if signature_bbox is not None:
+ signature_bboxes.append(signature_bbox)
+ except Exception:
+ # 单个损坏注释不能影响同页其他有效签名框。
+ continue
+ finally:
+ if raw_annot:
+ try:
+ pdfium_c.FPDFPage_CloseAnnot(raw_annot)
+ except Exception:
+ pass
+ return sorted(signature_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))
+
+
def _extract_page_image_bboxes(
page: pdfium.PdfPage,
page_bbox: BBox,
diff --git a/tests/unittest/test_flash_pdf_auxiliary_text.py b/tests/unittest/test_flash_pdf_auxiliary_text.py
index e7e18594..6c1d1e84 100644
--- a/tests/unittest/test_flash_pdf_auxiliary_text.py
+++ b/tests/unittest/test_flash_pdf_auxiliary_text.py
@@ -728,6 +728,129 @@ def test_single_page_marginal_content_remains_text() -> None:
assert [line.semantic_type for line in page.remaining_lines] == [None, None]
+def test_extreme_page_footnotes_can_be_overridden_by_repeated_marginals() -> None:
+ """验证只有极底脚注可凭跨页重复和递增证据改判为页脚、页码。"""
+
+ pages = []
+ for page_index in range(3):
+ pages.append(
+ _prepared_text_page(
+ _text_line(
+ "stable footer",
+ (20.0, 95.0, 70.0, 99.0),
+ 0,
+ effective_height=4.0,
+ font_signature=("Margin", 0),
+ font_coverage=1.0,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ str(page_index + 10),
+ (90.0, 95.0, 95.0, 99.0),
+ 1,
+ effective_height=4.0,
+ font_signature=("Margin", 0),
+ font_coverage=1.0,
+ semantic_type="page_footnote",
+ ),
+ _text_line(
+ "local note",
+ (20.0, 86.0, 60.0, 90.0),
+ 2,
+ semantic_type="page_footnote",
+ ),
+ )
+ )
+
+ auxiliary_text._classify_repeated_page_marginals(pages)
+
+ assert [
+ [line.semantic_type for line in page.remaining_lines]
+ for page in pages
+ ] == [["footer", "page_number", "page_footnote"]] * 3
+
+
+def test_single_page_compound_header_requires_small_split_row_and_body_edge() -> None:
+ """验证单页顶部的小字号拆分同行可由正文栏右缘确认为页眉。"""
+
+ header_name = _text_line(
+ "journal",
+ (60.0, 2.0, 85.0, 4.0),
+ 0,
+ visual_row_id=7,
+ run_index=0,
+ split_from_row=True,
+ effective_height=2.0,
+ )
+ header_number = _text_line(
+ "5",
+ (96.0, 2.0, 98.0, 4.0),
+ 1,
+ visual_row_id=7,
+ run_index=1,
+ split_from_row=True,
+ effective_height=2.0,
+ )
+ page = _prepared_text_page(
+ header_name,
+ header_number,
+ *[
+ _text_line(
+ f"body-{index}",
+ (50.0, 10.0 + 12.0 * index, 98.0, 20.0 + 12.0 * index),
+ 2 + index,
+ effective_height=10.0,
+ )
+ for index in range(4)
+ ],
+ )
+
+ auxiliary_text._classify_single_page_compound_headers([page])
+
+ assert header_name.semantic_type == "header"
+ assert header_number.semantic_type == "header"
+
+
+def test_isolated_first_page_footer_uses_multi_page_geometry_only() -> None:
+ """验证多页首页唯一极底短行可补标页脚,而单页相同布局保持正文。"""
+
+ def build_page() -> tuple[models._PreparedPage, models._LineItem]:
+ """构造带四行下延正文和一个孤立极底候选的页面。"""
+
+ footer = _text_line(
+ "neutral notice",
+ (37.5, 98.0, 62.5, 100.0),
+ 4,
+ effective_height=2.0,
+ )
+ return (
+ _prepared_text_page(
+ *[
+ _text_line(
+ f"body-{index}",
+ (0.0, 55.0 + 10.0 * index, 100.0, 60.0 + 10.0 * index),
+ index,
+ effective_height=5.0,
+ )
+ for index in range(4)
+ ],
+ footer,
+ ),
+ footer,
+ )
+
+ multi_page, multi_footer = build_page()
+ single_page, single_footer = build_page()
+
+ auxiliary_text._classify_isolated_first_page_footer(
+ [multi_page, _prepared_text_page()]
+ )
+ auxiliary_text._classify_isolated_first_page_footer([single_page])
+
+ assert multi_footer.semantic_type == "footer"
+ assert single_footer.semantic_type is None
+
+
def test_repeated_visual_headers_use_geometry_and_skip_first_page() -> None:
"""验证重复页首图片仅按几何重标,空 content 也可保留为 header。"""
diff --git a/tests/unittest/test_flash_pdf_document_profile.py b/tests/unittest/test_flash_pdf_document_profile.py
index f58a2299..f9e6e51e 100644
--- a/tests/unittest/test_flash_pdf_document_profile.py
+++ b/tests/unittest/test_flash_pdf_document_profile.py
@@ -64,7 +64,8 @@ def test_document_body_profile_prefers_cross_page_body_and_regular_fonts() -> No
assert profile is not None
assert profile.body_height == 10.0
assert profile.body_weight == 400.0
- assert profile.regular_fonts == frozenset({body_font, mono_font})
+ # 正文字体画像只统计正文高度带,较矮的等宽和斜体样本不再进入 regular_fonts。
+ assert profile.regular_fonts == frozenset({body_font})
def test_sparse_repeated_font_is_not_document_regular_style() -> None:
diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.py
index d57d5e66..7d1b4a16 100644
--- a/tests/unittest/test_flash_pdf_formulas.py
+++ b/tests/unittest/test_flash_pdf_formulas.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+from dataclasses import replace
+
import pytest
from mineru.backend.flash.native_pdf import (
@@ -723,6 +725,237 @@ def test_compact_multiline_cluster_becomes_one_isolated_equation() -> None:
assert compact_cluster not in remaining
+def _build_compact_margin_case(
+ candidate_bbox: tuple[float, float, float, float],
+ above_bbox: tuple[float, float, float, float],
+ below_bbox: tuple[float, float, float, float],
+) -> tuple[
+ models._LineItem,
+ list[dict[str, object]],
+ list[models._LineItem],
+]:
+ """构造上下都有稳定正文行的紧凑公式页边用例。"""
+
+ body_font = ("Body", 0)
+ above = _text_line(
+ "body above",
+ above_bbox,
+ 0,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ candidate = replace(
+ _text_line(
+ "formula cluster",
+ candidate_bbox,
+ 1,
+ effective_height=10.0,
+ font_signature=("Math", 1),
+ font_coverage=0.5,
+ ),
+ compact_formula_cluster=True,
+ )
+ below = _text_line(
+ "body below",
+ below_bbox,
+ 2,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ blocks, remaining = formulas._build_formula_like_blocks(
+ [above, candidate, below],
+ [],
+ (100.0, 1000.0),
+ )
+ return candidate, blocks, remaining
+
+
+def _build_text_formula_margin_case(
+ formula_bboxes: tuple[
+ tuple[float, float, float, float],
+ tuple[float, float, float, float],
+ tuple[float, float, float, float],
+ ],
+ body_tops: tuple[float, float, float, float],
+) -> tuple[list[dict[str, object]], list[models._LineItem]]:
+ """构造带右缘编号和稳定正文栏带的文本公式页边用例。"""
+
+ body_font = ("Body", 0)
+ formula_lines = [
+ _text_line(
+ "formula numerator",
+ formula_bboxes[0],
+ 0,
+ effective_height=10.0,
+ font_signature=("Math", 0),
+ font_coverage=0.6,
+ ),
+ _text_line(
+ "formula denominator",
+ formula_bboxes[1],
+ 1,
+ effective_height=10.0,
+ font_signature=("Math", 0),
+ font_coverage=0.6,
+ ),
+ _text_line("(5)", formula_bboxes[2], 2, effective_height=10.0),
+ ]
+ body_lines = [
+ _text_line(
+ f"body-{index}",
+ (0.0, top, 100.0, top + 10.0),
+ 3 + index,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ for index, top in enumerate(body_tops)
+ ]
+ return formulas._build_formula_like_blocks(
+ [*formula_lines, *body_lines],
+ [],
+ (100.0, 1000.0),
+ )
+
+
+ ("candidate_bbox", "above_bbox", "below_bbox"),
+ [
+ ((25.0, 20.0, 65.0, 30.0), (0.0, 0.0, 100.0, 10.0), (0.0, 40.0, 100.0, 50.0)),
+ (
+ (25.0, 970.0, 65.0, 980.0),
+ (0.0, 940.0, 100.0, 950.0),
+ (0.0, 990.0, 100.0, 1000.0),
+ ),
+ ],
+ ids=["top", "bottom"],
+)
+def test_compact_formula_fully_in_page_margin_remains_text(
+ candidate_bbox: tuple[float, float, float, float],
+ above_bbox: tuple[float, float, float, float],
+ below_bbox: tuple[float, float, float, float],
+) -> None:
+ """验证紧凑公式簇整体落入顶部或底部 5% 时不升级为公式。"""
+
+ candidate, blocks, remaining = _build_compact_margin_case(
+ candidate_bbox,
+ above_bbox,
+ below_bbox,
+ )
+
+ assert blocks == []
+ assert candidate in remaining
+
+
+def test_compact_formula_crossing_page_margin_boundary_remains_equation() -> None:
+ """验证跨过顶部 5% 分界的紧凑真公式仍能输出公式块。"""
+
+ candidate, blocks, remaining = _build_compact_margin_case(
+ (25.0, 45.0, 65.0, 55.0),
+ (0.0, 30.0, 100.0, 40.0),
+ (0.0, 60.0, 100.0, 70.0),
+ )
+
+ assert blocks == [
+ {
+ "type": "equation",
+ "bbox": candidate.bbox,
+ "angle": 0,
+ "content": "formula cluster",
+ }
+ ]
+ assert candidate not in remaining
+
+
+ ("formula_bboxes", "body_tops"),
+ [
+ (
+ (
+ (20.0, 8.0, 58.0, 18.0),
+ (25.0, 19.0, 55.0, 29.0),
+ (91.0, 17.0, 100.0, 27.0),
+ ),
+ (44.0, 56.0, 68.0, 80.0),
+ ),
+ (
+ (
+ (20.0, 955.0, 58.0, 965.0),
+ (25.0, 966.0, 55.0, 976.0),
+ (91.0, 973.0, 100.0, 983.0),
+ ),
+ (900.0, 912.0, 924.0, 936.0),
+ ),
+ ],
+ ids=["top", "bottom"],
+)
+def test_text_formula_fully_in_page_margin_remains_text(
+ formula_bboxes: tuple[
+ tuple[float, float, float, float],
+ tuple[float, float, float, float],
+ tuple[float, float, float, float],
+ ],
+ body_tops: tuple[float, float, float, float],
+) -> None:
+ """验证文本公式空间分量整体落入页边 5% 时不认领原文本行。"""
+
+ blocks, remaining = _build_text_formula_margin_case(
+ formula_bboxes,
+ body_tops,
+ )
+
+ assert blocks == []
+ assert {line.source_index for line in remaining} == set(range(7))
+
+
+ ("formula_bboxes", "body_tops", "expected_bbox"),
+ [
+ (
+ (
+ (20.0, 40.0, 58.0, 50.0),
+ (25.0, 51.0, 55.0, 61.0),
+ (91.0, 49.0, 100.0, 59.0),
+ ),
+ (76.0, 88.0, 100.0, 112.0),
+ (20.0, 40.0, 100.0, 61.0),
+ ),
+ (
+ (
+ (20.0, 940.0, 58.0, 950.0),
+ (25.0, 951.0, 55.0, 961.0),
+ (91.0, 958.0, 100.0, 968.0),
+ ),
+ (885.0, 897.0, 909.0, 921.0),
+ (20.0, 940.0, 100.0, 968.0),
+ ),
+ ],
+ ids=["top", "bottom"],
+)
+def test_text_formula_crossing_page_margin_boundary_remains_equation(
+ formula_bboxes: tuple[
+ tuple[float, float, float, float],
+ tuple[float, float, float, float],
+ tuple[float, float, float, float],
+ ],
+ body_tops: tuple[float, float, float, float],
+ expected_bbox: tuple[float, float, float, float],
+) -> None:
+ """验证跨过顶部或底部 5% 分界的文本真公式仍能输出。"""
+
+ blocks, remaining = _build_text_formula_margin_case(
+ formula_bboxes,
+ body_tops,
+ )
+
+ assert len(blocks) == 1
+ assert blocks[0]["type"] == "equation"
+ assert blocks[0]["bbox"] == expected_bbox
+ assert {line.source_index for line in remaining} == {3, 4, 5, 6}
+
+
def test_justified_mixed_font_visual_row_before_body_is_not_formula_anchor() -> None:
"""验证粗体短语与常规字体混排的满栏同行不会因右缘短词误判公式。"""
diff --git a/tests/unittest/test_flash_pdf_graphics.py b/tests/unittest/test_flash_pdf_graphics.py
index c5a2265b..633a5a5c 100644
--- a/tests/unittest/test_flash_pdf_graphics.py
+++ b/tests/unittest/test_flash_pdf_graphics.py
@@ -338,6 +338,31 @@ def test_raster_image_threshold_accepts_point_38_percent_only() -> None:
assert claimed == set()
+def test_signature_images_bypass_raster_threshold_and_deduplicate_same_geometry() -> None:
+ """验证小签名仍输出,且签名间及签名与点阵图的同框候选只保留一次。"""
+
+ source = models._PageSource(
+ page_size=(1000.0, 1000.0),
+ lines=[],
+ chars=[],
+ drawing_lines=[],
+ image_bboxes=[(100.0, 100.0, 200.0, 200.0)],
+ signature_bboxes=[
+ (10.0, 10.0, 30.0, 30.0),
+ (10.2, 10.1, 30.1, 30.2),
+ (100.0, 100.0, 200.0, 200.0),
+ ],
+ )
+
+ blocks, claimed = graphics._build_raster_image_blocks(source, [], set())
+
+ assert [block["bbox"] for block in blocks] == [
+ (10.0, 10.0, 30.0, 30.0),
+ (100.0, 100.0, 200.0, 200.0),
+ ]
+ assert claimed == set()
+
+
def test_inline_raster_images_and_gap_runs_form_one_composite_image() -> None:
"""验证四张已准入图片与三个同行间隔符合成一个复合 image。"""
diff --git a/tests/unittest/test_flash_pdf_index_blocks.py b/tests/unittest/test_flash_pdf_index_blocks.py
index a23f5d57..1cb2961b 100644
--- a/tests/unittest/test_flash_pdf_index_blocks.py
+++ b/tests/unittest/test_flash_pdf_index_blocks.py
@@ -90,6 +90,29 @@ def test_index_block_merges_split_rows_and_preserves_heading() -> None:
assert all(line.semantic_type == "index" for line in lines if line is not remaining[0])
+def test_index_prepass_requires_geometric_heading_but_fallback_keeps_legacy_detection() -> None:
+ """验证公式前目录预判拒绝无标题编号行,公式后的兼容识别仍可处理无标题目录。"""
+
+ lines = _directory_lines(set(range(6)), row_count=6)[1:]
+
+ prepass_blocks, prepass_remaining = index_blocks._extract_index_blocks(
+ lines,
+ (100.0, 130.0),
+ [],
+ require_heading=True,
+ )
+ fallback_blocks, fallback_remaining = index_blocks._extract_index_blocks(
+ lines,
+ (100.0, 130.0),
+ [],
+ )
+
+ assert prepass_blocks == []
+ assert prepass_remaining == lines
+ assert len(fallback_blocks) == 1
+ assert fallback_remaining == []
+
+
@pytest.mark.parametrize(
("numeric_rows", "expected_block_count"),
[
diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.py
index 61ab4247..d15cf657 100644
--- a/tests/unittest/test_flash_pdf_native_text.py
+++ b/tests/unittest/test_flash_pdf_native_text.py
@@ -12,6 +12,8 @@ def _span(
text: str,
bbox: tuple[float, float, float, float],
angle_degrees: float,
+ *,
+ chars: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""构造只包含方向、文本和 bbox 的最小 pdftext span。"""
@@ -19,10 +21,19 @@ def _span(
"text": text,
"bbox": bbox,
"rotation": math.radians(angle_degrees),
- "chars": [],
+ "chars": chars or [],
}
+def _char(
+ value: str,
+ bbox: tuple[float, float, float, float],
+) -> dict[str, Any]:
+ """构造字符基线方向测试使用的最小 pdftext 字符。"""
+
+ return {"char": value, "bbox": bbox}
+
+
def _line(
spans: list[dict[str, Any]],
angle_degrees: float,
@@ -79,6 +90,59 @@ def test_small_oblique_span_stays_inside_standard_direction_line() -> None:
assert [(item.text, item.angle) for item in items] == [("normal oblique", 0)]
+def test_sheared_horizontal_line_uses_char_baseline_and_splits_far_sidecar() -> None:
+ """验证仿斜体粗行可由水平字符基线恢复,并继续拆开远端页码。"""
+
+ chars = [
+ _char(value, (10.0 + index * 5.0, 80.0, 14.0 + index * 5.0, 88.0))
+ for index, value in enumerate("NOTICE")
+ ]
+ chars.append(_char("2", (90.0, 80.2, 94.0, 88.2)))
+ pdf_line = _line(
+ [
+ _span(
+ "NOTICE 2",
+ (10.0, 80.0, 94.0, 88.2),
+ 18.433,
+ chars=chars,
+ )
+ ],
+ 18.433,
+ bbox=(10.0, 80.0, 94.0, 88.2),
+ )
+
+ items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))
+
+ assert [(item.text, item.angle) for item in items] == [
+ ("NOTICE", 0),
+ ("2", 0),
+ ]
+ assert all(item.split_from_row for item in items)
+
+
+def test_true_diagonal_char_baseline_is_not_recovered_as_horizontal() -> None:
+ """验证真实斜向字符中心不会因字符数量和长宽比被恢复为水平正文。"""
+
+ chars = [
+ _char(value, (10.0 + index * 8.0, 70.0 - index * 6.0, 14.0 + index * 8.0, 78.0 - index * 6.0))
+ for index, value in enumerate("WATERMARK")
+ ]
+ pdf_line = _line(
+ [
+ _span(
+ "WATERMARK",
+ (10.0, 22.0, 78.0, 78.0),
+ 315.0,
+ chars=chars,
+ )
+ ],
+ 315.0,
+ bbox=(10.0, 22.0, 78.0, 78.0),
+ )
+
+ assert native_text._build_native_line_items([pdf_line], (100.0, 100.0)) == []
+
+
@pytest.mark.parametrize(
("line_angle", "page_rotation", "expected_angle"),
[
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index 3ff9f770..f86e5265 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -23,6 +23,11 @@ from mineru.backend.flash.native_pdf import (
)
from mineru.utils.pdf_document import PDFImageInfo
+from _flash_pdf_test_utils import (
+ _prepared_text_page,
+ _text_line,
+)
+
def _image_info(
fingerprint: str | None,
@@ -195,3 +200,108 @@ def test_output_normalization_keeps_empty_equation_but_drops_empty_text() -> Non
"content": "",
}
assert text is None
+
+
+def test_index_is_claimed_before_formula_anchor_growth() -> None:
+ """验证目录右缘页码先形成完整 index,不再扩张为重叠公式。"""
+
+ heading = _text_line(
+ "contents",
+ (40.0, 5.0, 60.0, 10.0),
+ 0,
+ effective_height=5.0,
+ )
+ rows = []
+ source_index = 1
+ for row_index, top in enumerate((20.0, 30.0, 40.0, 50.0, 60.0, 70.0)):
+ visual_row_id = 10 + row_index
+ rows.extend(
+ [
+ _text_line(
+ f"entry-{row_index}",
+ (10.0, top, 80.0, top + 5.0),
+ source_index,
+ visual_row_id=visual_row_id,
+ run_index=0,
+ split_from_row=True,
+ effective_height=5.0,
+ ),
+ _text_line(
+ str(row_index + 1),
+ (90.0, top, 95.0, top + 5.0),
+ source_index + 1,
+ visual_row_id=visual_row_id,
+ run_index=1,
+ split_from_row=True,
+ effective_height=5.0,
+ ),
+ ]
+ )
+ source_index += 2
+ page = _prepared_text_page(heading, *rows)
+
+ blocks = pipeline._finalize_prepared_page(page, page_index=1)
+
+ assert [block["type"] for block in blocks].count("index") == 1
+ assert not [block for block in blocks if block["type"] == "equation"]
+ assert next(block for block in blocks if block["type"] == "index")[
+ "content"
+ ].count("entry-") == 6
+ assert next(block for block in blocks if block["content"] == "contents")[
+ "type"
+ ] == "paragraph_title"
+
+
+def test_numbered_formula_rows_are_not_claimed_as_index() -> None:
+ """验证连续编号公式先保留公式语义,不被无标题目录候选吞并。"""
+
+ body_font = ("Body", 0)
+ lines = [
+ _text_line(
+ "ordinary body row",
+ (0.0, 10.0 * index, 100.0, 10.0 * index + 7.0),
+ index,
+ effective_height=7.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ )
+ for index in range(10)
+ ]
+ source_index = 10
+ for row_index, top in enumerate(
+ (102.0, 113.0, 124.0, 135.0, 146.0, 157.0)
+ ):
+ visual_row_id = 100 + row_index
+ lines.extend(
+ [
+ _text_line(
+ f"x{row_index}=y{row_index}",
+ (20.0, top, 55.0, top + 7.0),
+ source_index,
+ visual_row_id=visual_row_id,
+ run_index=0,
+ split_from_row=True,
+ effective_height=7.0,
+ font_signature=("Math", 0),
+ font_coverage=0.6,
+ ),
+ _text_line(
+ f"({row_index + 1})",
+ (91.0, top, 100.0, top + 7.0),
+ source_index + 1,
+ visual_row_id=visual_row_id,
+ run_index=1,
+ split_from_row=True,
+ effective_height=7.0,
+ ),
+ ]
+ )
+ source_index += 2
+
+ blocks = pipeline._finalize_prepared_page(
+ _prepared_text_page(*lines, page_size=(100.0, 200.0)),
+ page_index=1,
+ )
+
+ assert sum(block["type"] == "equation" for block in blocks) == 6
+ assert not [block for block in blocks if block["type"] == "index"]
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 27649576..3639eb46 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -50,6 +50,7 @@ def _native_page_source(pdf_name: str, page_idx: int) -> models._PageSource:
chars=chars,
drawing_lines=native_text._get_pdf_drawing_lines(pdf_doc, page_idx),
image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),
+ signature_bboxes=pdf_doc.get_page_signature_bboxes(page_idx),
form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),
)
@@ -169,6 +170,12 @@ def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() ->
assert "Figure 1:" not in graphic_block["content"]
assert "Left camera" not in caption_block["content"]
assert sum(block["content"].count("Left camera") for block in page) == 1
+ copyright_block = next(
+ block
+ for block in page
+ if block["content"].startswith("978-1-4673-5208-6")
+ )
+ assert copyright_block["type"] == "footer"
def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> None:
@@ -841,6 +848,36 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:
model_list = _native_model_list("demo5.pdf")
+ sparse_table_counts = {
+ 4: 2,
+ 49: 1,
+ 55: 1,
+ 56: 2,
+ 59: 1,
+ 61: 1,
+ 83: 2,
+ 84: 3,
+ 85: 3,
+ 87: 1,
+ }
+ for page_number, expected_count in sparse_table_counts.items():
+ page = model_list[page_number - 1]
+ table_blocks = [block for block in page if block["type"] == "table"]
+ assert len(table_blocks) == expected_count
+ for table_block in table_blocks:
+ table_bbox = table_block["bbox"]
+ assert not [
+ block
+ for block in page
+ if block["type"] == "text"
+ and table_bbox[0]
+ <= (block["bbox"][0] + block["bbox"][2]) / 2
+ <= table_bbox[2]
+ and table_bbox[1]
+ <= (block["bbox"][1] + block["bbox"][3]) / 2
+ <= table_bbox[3]
+ ]
+
for page_number in (9, 10, 22, 38, 70, 77):
page = model_list[page_number - 1]
table_blocks = [block for block in page if block["type"] == "table"]
@@ -907,3 +944,12 @@ def test_demo6_default3_targeted_title_regressions() -> None:
matches = _blocks_containing(blocks, probe)
assert matches
assert {block["type"] for block in matches} == {"text"}
+
+ page7_images = [block for block in model_list[6] if block["type"] == "image"]
+ assert [block["bbox"] for block in page7_images] == [
+ [0.601, 0.106, 0.811, 0.255],
+ [0.615, 0.244, 0.839, 0.403],
+ ]
+ assert [block["content"] for block in page7_images] == ["(签名)", "(盖章)"]
+ assert sum("签名" in str(block["content"]) for block in model_list[6]) == 1
+ assert sum("盖章" in str(block["content"]) for block in model_list[6]) == 1
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index 321c4361..12337172 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -389,6 +389,190 @@ def test_disconnected_stacked_rule_grids_remain_separate() -> None:
)
+def _closed_sparse_grid_fixture(
+ *,
+ horizontal_count: int = 3,
+) -> tuple[
+ list[models._VisualRow],
+ list[models._LineItem],
+ list[models._LocalAxisLine],
+]:
+ """构造仅有少量文本、但外轨完整闭合的物理网格。"""
+
+ fragment_bboxes = (
+ (10.0, 10.0, 30.0, 15.0),
+ (75.0, 10.0, 95.0, 15.0),
+ )
+ fragments = [
+ models._Fragment(
+ text=f"cell-{index}",
+ bbox=bbox,
+ local_bbox=bbox,
+ line_index=index,
+ visual_row_id=0,
+ )
+ for index, bbox in enumerate(fragment_bboxes)
+ ]
+ rows = [
+ models._VisualRow(
+ fragments=fragments,
+ center_y=12.5,
+ bbox=geometry._bbox_union_many(fragment_bboxes),
+ visual_row_id=0,
+ )
+ ]
+ lines = [
+ models._LineItem(
+ text=fragment.text,
+ bbox=fragment.bbox,
+ angle=0,
+ source_index=fragment.line_index,
+ effective_height=5.0,
+ visual_row_id=0,
+ )
+ for fragment in fragments
+ ]
+ horizontal_tops = (
+ (0.0, 20.0, 40.0)
+ if horizontal_count == 3
+ else (0.0, 40.0)
+ )
+ axis_lines = [
+ *[
+ _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
+ for top in horizontal_tops
+ ],
+ *[
+ _axis_line("vertical", (left, 0.0, left + 0.1, 40.1))
+ for left in (0.0, 55.0, 109.9)
+ ],
+ ]
+ return rows, lines, axis_lines
+
+
+def test_closed_grid_accepts_sparse_single_column_form_with_empty_row() -> None:
+ """验证三条横边界和完整外轨可接纳有空数据行的单列表单。"""
+
+ rows, lines, axis_lines = _closed_sparse_grid_fixture()
+ rows[0].fragments = rows[0].fragments[:1]
+ rows[0].bbox = rows[0].fragments[0].bbox
+ lines = lines[:1]
+
+ candidates = tables._build_closed_rule_grid_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ [],
+ )
+
+ assert len(candidates) == 1
+ assert candidates[0].core_bbox == pytest.approx(
+ (0.0, 0.0, 110.0, 40.1)
+ )
+ assert candidates[0].line_indices == {0}
+
+
+def test_closed_two_boundary_grid_requires_text_in_two_physical_columns() -> None:
+ """验证两条横边界只有在三条贯穿竖轨且文字占两列时才接纳。"""
+
+ rows, lines, axis_lines = _closed_sparse_grid_fixture(
+ horizontal_count=2,
+ )
+
+ candidates = tables._build_closed_rule_grid_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ [],
+ )
+
+ assert len(candidates) == 1
+ assert candidates[0].line_indices == {0, 1}
+
+
+ "failure_mode",
+ [
+ "no_text",
+ "short_outer_tracks",
+ "only_two_vertical_tracks",
+ "one_occupied_column",
+ "excluded_graphic",
+ ],
+)
+def test_closed_sparse_grid_rejects_incomplete_or_excluded_geometry(
+ failure_mode: str,
+) -> None:
+ """验证空框、短外轨、单格框、单列文字和强图形区域不会误报表格。"""
+
+ rows, lines, axis_lines = _closed_sparse_grid_fixture(
+ horizontal_count=2,
+ )
+ excluded_bboxes: list[tuple[float, float, float, float]] = []
+ if failure_mode == "no_text":
+ rows = []
+ lines = []
+ elif failure_mode == "short_outer_tracks":
+ axis_lines = [
+ _axis_line("vertical", (line.bbox[0], 5.0, line.bbox[2], 35.0))
+ if line.orientation == "vertical"
+ else line
+ for line in axis_lines
+ ]
+ elif failure_mode == "only_two_vertical_tracks":
+ axis_lines = [
+ line
+ for line in axis_lines
+ if line.orientation != "vertical" or line.bbox[0] != 55.0
+ ]
+ elif failure_mode == "one_occupied_column":
+ rows[0].fragments[1].bbox = (32.0, 10.0, 48.0, 15.0)
+ rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox
+ rows[0].bbox = geometry._bbox_union_many(
+ [fragment.bbox for fragment in rows[0].fragments]
+ )
+ else:
+ excluded_bboxes = [(0.0, 0.0, 110.0, 40.1)]
+
+ assert tables._build_closed_rule_grid_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ excluded_bboxes,
+ ) == []
+
+
+def test_closed_grid_inside_form_bbox_is_not_a_table_candidate() -> None:
+ """验证 Form 容器内的闭合线框继续由图片分支处理而不生成表格。"""
+
+ rows, lines, axis_lines = _closed_sparse_grid_fixture()
+ source = models._PageSource(
+ page_size=(150.0, 100.0),
+ lines=lines,
+ chars=[],
+ drawing_lines=[
+ models._AxisLine(
+ bbox=line.bbox,
+ width=line.width,
+ orientation=line.orientation,
+ )
+ for line in axis_lines
+ ],
+ form_bboxes=[(0.0, 0.0, 110.0, 40.1)],
+ )
+
+ assert tables._detect_table_candidates(source) == []
+
+
def _rule_table_fixture(
rule_count: int = 3,
*,
diff --git a/tests/unittest/test_flash_pdf_titles.py b/tests/unittest/test_flash_pdf_titles.py
index 8475fc31..b0faa966 100644
--- a/tests/unittest/test_flash_pdf_titles.py
+++ b/tests/unittest/test_flash_pdf_titles.py
@@ -13,6 +13,7 @@ from mineru.backend.flash.native_pdf import (
from _flash_pdf_test_utils import (
+ _prepared_text_page,
_text_line,
)
@@ -58,6 +59,40 @@ def test_heading_like_content_with_body_layout_remains_text() -> None:
assert lines[2].semantic_type is None
+def test_document_regular_fonts_only_use_body_height_band() -> None:
+ """验证跨页重复的大字号标题字体不会进入全文常规正文字体集合。"""
+
+ body_font = ("Body", 0)
+ heading_font = ("RepeatedHeading", 0)
+ pages = [
+ _prepared_text_page(
+ _text_line(
+ f"heading-{page_index}",
+ (10.0, 10.0, 90.0, 28.0),
+ 0,
+ effective_height=18.0,
+ font_signature=heading_font,
+ font_coverage=1.0,
+ ),
+ _text_line(
+ f"body-{page_index}",
+ (0.0, 40.0, 100.0, 50.0),
+ 1,
+ effective_height=10.0,
+ font_signature=body_font,
+ font_coverage=1.0,
+ ),
+ )
+ for page_index in range(3)
+ ]
+
+ profile = titles._infer_document_body_profile(pages)
+
+ assert profile is not None
+ assert profile.body_height == pytest.approx(10.0)
+ assert profile.regular_fonts == frozenset({body_font})
+
+
def test_physical_title_gap_ignores_disjoint_column_and_keeps_overlapping_row() -> None:
"""验证物理邻行只在水平投影相交时参与标题留白,避免另一栏正文压缩间距。"""
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index fee48500..2745ad98 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -5,6 +5,15 @@ from typing import Any
import pytest
from pypdf import PdfReader, PdfWriter
+from pypdf.generic import (
+ ArrayObject,
+ DecodedStreamObject,
+ DictionaryObject,
+ FloatObject,
+ NameObject,
+ NumberObject,
+ TextStringObject,
+)
from pdftext.schema import Bbox
from PIL import Image
from reportlab.lib.utils import ImageReader
@@ -107,6 +116,107 @@ def _build_rotated_cropped_image_pdf() -> bytes:
return output.getvalue()
+def _build_rotated_cropped_signature_pdf() -> bytes:
+ """构造带可见签名和各类无效注释的 CropBox 旋转测试 PDF。"""
+
+ writer = PdfWriter()
+ page = writer.add_blank_page(width=100, height=200)
+ page.rotate(90)
+ page.cropbox.lower_left = (5, 10)
+ page.cropbox.upper_right = (95, 190)
+
+ def add_appearance(width: float, height: float) -> object:
+ """为测试签名创建最小正常 Form 外观流。"""
+
+ appearance = DecodedStreamObject()
+ appearance.set_data(b"q 1 0 0 rg 0 0 1 1 re f Q")
+ appearance.update(
+ {
+ NameObject("/Type"): NameObject("/XObject"),
+ NameObject("/Subtype"): NameObject("/Form"),
+ NameObject("/BBox"): ArrayObject(
+ [
+ FloatObject(0),
+ FloatObject(0),
+ FloatObject(width),
+ FloatObject(height),
+ ]
+ ),
+ NameObject("/Resources"): DictionaryObject(),
+ }
+ )
+ return writer._add_object(appearance)
+
+ annotations = ArrayObject()
+ form_fields = ArrayObject()
+
+ def add_widget(
+ rect: tuple[float, float, float, float],
+ *,
+ flags: int = 4,
+ field_type: str = "/Sig",
+ subtype: str = "/Widget",
+ with_appearance: bool = True,
+ inherited_field_type: bool = False,
+ ) -> None:
+ """追加一个可配置的测试 Widget,覆盖可见性和结构过滤分支。"""
+
+ annotation = DictionaryObject(
+ {
+ NameObject("/Type"): NameObject("/Annot"),
+ NameObject("/Subtype"): NameObject(subtype),
+ NameObject("/Rect"): ArrayObject([FloatObject(value) for value in rect]),
+ NameObject("/F"): NumberObject(flags),
+ }
+ )
+ parent_field = None
+ parent_reference = None
+ if inherited_field_type:
+ parent_field = DictionaryObject(
+ {
+ NameObject("/FT"): NameObject(field_type),
+ NameObject("/T"): TextStringObject("InheritedSignature"),
+ }
+ )
+ parent_reference = writer._add_object(parent_field)
+ annotation[NameObject("/Parent")] = parent_reference
+ else:
+ annotation[NameObject("/FT")] = NameObject(field_type)
+ if with_appearance:
+ annotation[NameObject("/AP")] = DictionaryObject(
+ {
+ NameObject("/N"): add_appearance(
+ abs(rect[2] - rect[0]),
+ abs(rect[3] - rect[1]),
+ )
+ }
+ )
+ annotation_reference = writer._add_object(annotation)
+ annotations.append(annotation_reference)
+ if parent_field is not None and parent_reference is not None:
+ parent_field[NameObject("/Kids")] = ArrayObject([annotation_reference])
+ form_fields.append(parent_reference)
+ elif subtype == "/Widget":
+ form_fields.append(annotation_reference)
+
+ add_widget((10, 20, 40, 60), inherited_field_type=True)
+ add_widget((-10, 170, 20, 210))
+ add_widget((20, 80, 40, 100), flags=pdf_document.pdfium_c.FPDF_ANNOT_FLAG_HIDDEN)
+ add_widget((20, 80, 40, 100), flags=pdf_document.pdfium_c.FPDF_ANNOT_FLAG_INVISIBLE)
+ add_widget((20, 80, 40, 100), flags=pdf_document.pdfium_c.FPDF_ANNOT_FLAG_NOVIEW)
+ add_widget((20, 80, 40, 100), with_appearance=False)
+ add_widget((20, 80, 40, 100), field_type="/Btn")
+ add_widget((20, 80, 40, 100), subtype="/Text")
+ page[NameObject("/Annots")] = annotations
+ writer._root_object[NameObject("/AcroForm")] = DictionaryObject(
+ {NameObject("/Fields"): form_fields}
+ )
+
+ output = BytesIO()
+ writer.write(output)
+ return output.getvalue()
+
+
class _TrackingLock:
def __init__(self) -> None:
self.depth = 0
@@ -232,6 +342,19 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
events.append(f"form_bboxes:{lock.depth}:{page_bbox}:{page_rotation}")
return []
+ def fake_extract_page_signature_bboxes(
+ page: _FakePage,
+ page_bbox: tuple[float, float, float, float],
+ page_rotation: int,
+ *,
+ form_handle: object | None = None,
+ ) -> list[tuple[float, float, float, float]]:
+ """记录签名注释遍历时仍由 PDFDocument 持有 PDFium 锁。"""
+
+ assert form_handle is None
+ events.append(f"signature_bboxes:{lock.depth}:{page_bbox}:{page_rotation}")
+ return []
+
monkeypatch.setattr(pdf_document.pdfium, "PdfDocument", _FakeDoc)
monkeypatch.setattr(pdf_document, "get_chars", fake_get_chars, raising=False)
monkeypatch.setattr(pdf_document, "pdftext_get_chars", fake_get_chars, raising=False)
@@ -240,6 +363,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
monkeypatch.setattr(pdf_document, "_extract_page_image_bboxes", fake_extract_page_image_bboxes)
monkeypatch.setattr(pdf_document, "_extract_page_image_infos", fake_extract_page_image_infos)
monkeypatch.setattr(pdf_document, "_extract_page_form_bboxes", fake_extract_page_form_bboxes)
+ monkeypatch.setattr(pdf_document, "_extract_page_signature_bboxes", fake_extract_page_signature_bboxes)
doc = pdf_document.PDFDocument(b"%PDF")
@@ -253,6 +377,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
assert doc.get_page_image_bboxes(0) == []
assert doc.get_page_image_infos(0) == []
assert doc.get_page_form_bboxes(0) == []
+ assert doc.get_page_signature_bboxes(0) == []
assert any(event.startswith("doc.open:") and not event.startswith("doc.open:0:") for event in events)
assert any(event.startswith("doc.__getitem__:") and not event.startswith("doc.__getitem__:0:") for event in events)
@@ -269,6 +394,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
assert "image_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in events
assert "image_infos:1:(0.0, 0.0, 20.0, 10.0):0" in events
assert "form_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in events
+ assert "signature_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in events
def test_pdf_document_does_not_expose_legacy_compat_hooks() -> None:
@@ -437,6 +563,66 @@ def test_get_page_form_bboxes_applies_crop_box_rotation_and_clipping() -> None:
assert form_bboxes == pytest.approx([(76.0, 47.0, 88.0, 53.0)])
+def test_get_page_signature_bboxes_filters_visibility_and_applies_page_geometry() -> None:
+ """验证仅输出可见正常签名,并正确应用 CropBox、旋转和页面裁剪。"""
+
+ with pdf_document.PDFDocument(_build_rotated_cropped_signature_pdf()) as doc:
+ page_size = doc.page_size(0)
+ signature_bboxes = doc.get_page_signature_bboxes(0)
+
+ assert page_size == pytest.approx((180.0, 90.0))
+ assert signature_bboxes == pytest.approx(
+ [
+ (160.0, 0.0, 180.0, 15.0),
+ (10.0, 5.0, 50.0, 35.0),
+ ]
+ )
+
+
+def test_extract_page_signature_bboxes_closes_handles_and_skips_bad_annotation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证损坏签名被隔离,且成功或失败路径都关闭注释句柄。"""
+
+ bad_annot = object()
+ good_annot = object()
+ closed: list[object] = []
+
+ class _FakePage:
+ """提供注释原始接口所需的最小页面句柄。"""
+
+ raw = object()
+
+ def fake_get_annot(_raw_page: object, index: int) -> object:
+ """按索引返回一个损坏注释和一个有效注释。"""
+
+ return (bad_annot, good_annot)[index]
+
+ def fake_signature_bbox(
+ raw_annot: object,
+ _page_bbox: tuple[float, float, float, float],
+ _page_rotation: int,
+ _form_handle: object | None,
+ ) -> tuple[float, float, float, float]:
+ """让首个注释抛错,验证第二个注释仍能被提取。"""
+
+ if raw_annot is bad_annot:
+ raise RuntimeError("broken annotation")
+ return (10.0, 20.0, 30.0, 40.0)
+
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFPage_GetAnnotCount", lambda _page: 2)
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFPage_GetAnnot", fake_get_annot)
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFPage_CloseAnnot", closed.append)
+ monkeypatch.setattr(pdf_document, "_signature_bbox_from_annotation", fake_signature_bbox)
+
+ assert pdf_document._extract_page_signature_bboxes(
+ _FakePage(),
+ (0.0, 0.0, 100.0, 200.0),
+ 0,
+ ) == [(10.0, 20.0, 30.0, 40.0)]
+ assert closed == [bad_annot, good_annot]
+
+
def test_extract_page_form_bboxes_skips_one_bad_object(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证单个损坏 Form 不会阻断同页其他有效 Form 的提取。"""
bad_object = object()