Skip to content

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

feat: enhance PDF image processing by adding support for image fingerprint extraction and filtering repeated raster watermarks

myhloli4d7ff95c4d6a
diff --git a/mineru/backend/flash/native_pdf/native_text.py b/mineru/backend/flash/native_pdf/native_text.py
index cb7db219..7734afb7 100644
--- a/mineru/backend/flash/native_pdf/native_text.py
+++ b/mineru/backend/flash/native_pdf/native_text.py
@@ -30,6 +30,9 @@ from .geometry import (
_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)
def _build_native_line_items(
@@ -41,7 +44,16 @@ def _build_native_line_items(
"""将 pdftext 粗行按字符间隙精修成 Flash 视觉 run。"""
items: list[_LineItem] = []
- for visual_row_id, pdf_line in enumerate(pdf_lines):
+ supported_lines = [
+ child_line
+ 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,
+ )
+ ]
+ for visual_row_id, pdf_line in enumerate(supported_lines):
bbox = _clip_bbox(_coerce_bbox(pdf_line.get("bbox")), page_size)
if bbox is None:
continue
@@ -64,6 +76,91 @@ def _build_native_line_items(
return merged_items
+def _pdftext_angle_degrees(value: Any) -> float:
+ """把 pdftext 弧度方向转换为 0 到 360 度,非法值按 0 度处理。"""
+
+ try:
+ angle_radians = float(value or 0.0)
+ except (TypeError, ValueError):
+ return 0.0
+ if not math.isfinite(angle_radians):
+ return 0.0
+ return math.degrees(angle_radians) % 360.0
+
+
+def _circular_angle_distance(first: float, second: float) -> float:
+ """返回两个方向之间不超过 180 度的最短圆周角差。"""
+
+ return abs((first - second + 180.0) % 360.0 - 180.0)
+
+
+def _span_has_visible_text(span: dict[str, Any]) -> bool:
+ """判断 span 是否包含可见的非空白字符,换行与占位空格不参与方向拆分。"""
+
+ return any(
+ char.isprintable() and not char.isspace()
+ for char in str(span.get("text") or "")
+ )
+
+
+def _build_pdftext_child_line(
+ pdf_line: dict[str, Any],
+ spans: list[dict[str, Any]],
+ angle_degrees: float,
+) -> dict[str, Any]:
+ """使用同方向 span 重建子行,并收缩原粗行被异向内容扩大的 bbox。"""
+
+ span_bboxes = [
+ bbox
+ for span in spans
+ if (bbox := _coerce_bbox(span.get("bbox"))) is not None
+ ]
+ child_line = dict(pdf_line)
+ child_line["spans"] = spans
+ child_line["bbox"] = _bbox_union_many(span_bboxes) if span_bboxes else pdf_line.get("bbox")
+ child_line["rotation"] = math.radians(angle_degrees)
+ return child_line
+
+
+def _split_pdftext_line_by_rotation(pdf_line: dict[str, Any]) -> list[dict[str, Any]]:
+ """按 45 度边界拆开 pdftext 误合并的异向 span,并保留小角度仿斜体。"""
+
+ spans = [span for span in (pdf_line.get("spans") or []) if isinstance(span, dict)]
+ if not spans:
+ return [pdf_line]
+
+ output: list[dict[str, Any]] = []
+ current_spans: list[dict[str, Any]] = []
+ current_angle = _pdftext_angle_degrees(pdf_line.get("rotation"))
+ for span in spans:
+ span_angle = _pdftext_angle_degrees(span.get("rotation"))
+ if (
+ current_spans
+ and _span_has_visible_text(span)
+ and _circular_angle_distance(span_angle, current_angle)
+ >= _PDFTEXT_ROTATION_SPLIT_THRESHOLD_DEGREES
+ ):
+ output.append(_build_pdftext_child_line(pdf_line, current_spans, current_angle))
+ current_spans = []
+ current_angle = span_angle
+ current_spans.append(span)
+
+ if current_spans:
+ output.append(_build_pdftext_child_line(pdf_line, current_spans, current_angle))
+ return output
+
+
+def _is_supported_pdftext_line_rotation(value: Any, *, page_rotation: int) -> bool:
+ """应用页面旋转后只允许 0、90、270 度行,避免异向水印被归一成正文。"""
+
+ visual_angle = (_pdftext_angle_degrees(value) + int(page_rotation or 0)) % 360.0
+ return any(
+ _circular_angle_distance(visual_angle, supported_angle)
+ <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
+ for supported_angle in _SUPPORTED_PDFTEXT_LINE_ANGLES
+ )
+
+
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 50c3513c..a10df44c 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -8,7 +8,7 @@ from typing import Any
from mineru.backend.utils.xycut_pp_sorter import sort_entries
-from mineru.utils.pdf_document import PDFDocument, get_lines_from_chars
+from mineru.utils.pdf_document import PDFDocument, PDFImageInfo, get_lines_from_chars
from .models import (
_LineItem,
@@ -16,6 +16,7 @@ from .models import (
_PreparedPage,
)
from .geometry import (
+ _bbox_area,
_bbox_axis_overlap_ratio,
_bbox_center_y,
_bbox_overlap_in_smaller,
@@ -80,14 +81,83 @@ _TEXT_SEMANTIC_TYPES = {
_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation"} | _TEXT_SEMANTIC_TYPES
+_REPEATED_RASTER_IMAGE_MIN_PAGE_AREA_RATIO = 0.08
+_REPEATED_RASTER_IMAGE_MIN_DISTINCT_PAGES = 3
+
+
+def _is_large_raster_image(
+ image_info: PDFImageInfo,
+ page_size: tuple[float, float],
+) -> bool:
+ """判断点阵图裁剪后面积是否达到页面面积的 8%。"""
+
+ bbox = _coerce_bbox(image_info.bbox)
+ page_area = max(0.0, page_size[0]) * max(0.0, page_size[1])
+ return (
+ bbox is not None
+ and page_area > 0
+ and _bbox_area(bbox) / page_area
+ >= _REPEATED_RASTER_IMAGE_MIN_PAGE_AREA_RATIO
+ )
+
+
+def _detect_repeated_raster_watermark_fingerprints(
+ page_image_infos: list[list[PDFImageInfo]],
+ page_sizes: list[tuple[float, float]],
+) -> set[str]:
+ """按大图指纹统计不同页号,出现至少三页时判为跨页图片水印。"""
+
+ page_indices_by_fingerprint: dict[str, set[int]] = {}
+ for page_idx, (image_infos, page_size) in enumerate(
+ zip(page_image_infos, page_sizes, strict=True)
+ ):
+ for image_info in image_infos:
+ if image_info.fingerprint is None or not _is_large_raster_image(image_info, page_size):
+ continue
+ page_indices_by_fingerprint.setdefault(image_info.fingerprint, set()).add(page_idx)
+ return {
+ fingerprint
+ for fingerprint, page_indices in page_indices_by_fingerprint.items()
+ if len(page_indices) >= _REPEATED_RASTER_IMAGE_MIN_DISTINCT_PAGES
+ }
+
+
+def _filter_repeated_raster_watermark_bboxes(
+ image_infos: list[PDFImageInfo],
+ page_size: tuple[float, float],
+ watermark_fingerprints: set[str],
+) -> list[tuple[float, float, float, float]]:
+ """仅删除命中跨页水印指纹且面积达标的 bbox,小尺寸同图继续保留。"""
+
+ return [
+ image_info.bbox
+ for image_info in image_infos
+ if not (
+ image_info.fingerprint in watermark_fingerprints
+ and _is_large_raster_image(image_info, page_size)
+ )
+ ]
def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]:
"""逐页读取数字 PDF,并在轻量页面上完成跨页文本类型判定。"""
+ page_sizes = [
+ pdf_doc.page_size(page_idx)
+ for page_idx in range(pdf_doc.page_count)
+ ]
+ page_image_infos = [
+ pdf_doc.get_page_image_infos(page_idx)
+ for page_idx in range(pdf_doc.page_count)
+ ]
+ watermark_fingerprints = _detect_repeated_raster_watermark_fingerprints(
+ page_image_infos,
+ page_sizes,
+ )
+
prepared_pages: list[_PreparedPage] = []
for page_idx in range(pdf_doc.page_count):
- page_size = pdf_doc.page_size(page_idx)
+ page_size = page_sizes[page_idx]
chars = pdf_doc.get_page_chars(page_idx)
lines = _build_native_line_items(
get_lines_from_chars(chars),
@@ -100,7 +170,11 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]
lines=lines,
chars=chars,
drawing_lines=drawing_lines,
- image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),
+ image_bboxes=_filter_repeated_raster_watermark_bboxes(
+ page_image_infos[page_idx],
+ page_size,
+ watermark_fingerprints,
+ ),
form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),
path_infos=pdf_doc.get_page_path_infos(page_idx),
)
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 3a0915f2..265480d5 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import ctypes
+import hashlib
import math
import os
from contextlib import contextmanager
@@ -40,6 +41,7 @@ DRAWING_LINE_AXIS_RATIO_TOLERANCE = 0.02
DRAWING_LINE_MIN_LENGTH = 1.0
DRAWING_THIN_RECT_MAX_THICKNESS = 2.0
DRAWING_THIN_RECT_MIN_ASPECT_RATIO = 4.0
+PDF_IMAGE_FINGERPRINT_MAX_RAW_BYTES = 16 * 1024 * 1024
try:
from pdftext.pdf.chars import PageChars
@@ -88,6 +90,14 @@ class PDFPathInfo:
source_index: int
+@dataclass(frozen=True)
+class PDFImageInfo:
+ """PDF 点阵图的页面几何与稳定内容指纹,指纹读取失败时为 None。"""
+
+ bbox: BBox
+ fingerprint: str | None
+
+
@dataclass
class _PathSubpath:
"""保存一个 PDF Path 子路径的点、直线段和闭合状态。"""
@@ -353,6 +363,17 @@ class PDFDocument:
page_rotation = 0
return _extract_page_image_bboxes(page, page_bbox, page_rotation)
+ def get_page_image_infos(self, page_idx: int) -> list[PDFImageInfo]:
+ """提取点阵图 bbox 与内容指纹,供 Flash 在认领正文前识别跨页重复图。"""
+
+ 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_image_infos(page, page_bbox, page_rotation)
+
def get_page_form_bboxes(self, page_idx: int) -> list[BBox]:
"""提取页面顶层 Form XObject bbox,并转换为页面左上原点坐标。"""
with self._open_page(page_idx) as page:
@@ -1183,6 +1204,75 @@ def _extract_page_image_bboxes(
return sorted(image_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))
+def _get_raw_image_fingerprint(raw_obj: Any, page: pdfium.PdfPage) -> str | None:
+ """读取受限大小的图片原始流,并结合像素宽高生成 SHA-256 指纹。"""
+
+ metadata = pdfium_c.FPDF_IMAGEOBJ_METADATA()
+ try:
+ if not pdfium_c.FPDFImageObj_GetImageMetadata(
+ raw_obj,
+ page.raw,
+ ctypes.byref(metadata),
+ ):
+ return None
+ width = int(metadata.width)
+ height = int(metadata.height)
+ raw_size = int(pdfium_c.FPDFImageObj_GetImageDataRaw(raw_obj, None, 0))
+ except Exception:
+ return None
+ if (
+ width <= 0
+ or height <= 0
+ or raw_size <= 0
+ or raw_size > PDF_IMAGE_FINGERPRINT_MAX_RAW_BYTES
+ ):
+ return None
+
+ try:
+ buffer = ctypes.create_string_buffer(raw_size)
+ except (MemoryError, OverflowError):
+ return None
+ try:
+ bytes_read = int(pdfium_c.FPDFImageObj_GetImageDataRaw(raw_obj, buffer, raw_size))
+ except Exception:
+ return None
+ if bytes_read <= 0 or bytes_read > raw_size:
+ return None
+
+ digest = hashlib.sha256()
+ digest.update(f"{width}:{height}:".encode("ascii"))
+ digest.update(buffer.raw[:bytes_read])
+ return digest.hexdigest()
+
+
+def _extract_page_image_infos(
+ page: pdfium.PdfPage,
+ page_bbox: BBox,
+ page_rotation: int,
+) -> list[PDFImageInfo]:
+ """提取全部有效点阵图几何;单图指纹失败时保留 bbox 并按放行处理。"""
+
+ image_infos: list[PDFImageInfo] = []
+ for raw_obj, matrix in _iter_raw_image_objects(page):
+ try:
+ image_bbox = _image_bbox_from_matrix(matrix, page_bbox, page_rotation)
+ except Exception:
+ # 单个损坏 Image 对象不能中断同页其他点阵图提取。
+ continue
+ if image_bbox is None:
+ continue
+ image_infos.append(
+ PDFImageInfo(
+ bbox=image_bbox,
+ fingerprint=_get_raw_image_fingerprint(raw_obj, page),
+ )
+ )
+ return sorted(
+ image_infos,
+ key=lambda info: (info.bbox[1], info.bbox[0], info.bbox[3], info.bbox[2]),
+ )
+
+
def _extract_page_form_bboxes(
page: pdfium.PdfPage,
page_bbox: BBox,
diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.py
new file mode 100644
index 00000000..61ab4247
--- /dev/null
+++ b/tests/unittest/test_flash_pdf_native_text.py
@@ -0,0 +1,109 @@
+from __future__ import annotations
+
+import math
+from typing import Any
+
+import pytest
+
+from mineru.backend.flash.native_pdf import native_text
+
+
+def _span(
+ text: str,
+ bbox: tuple[float, float, float, float],
+ angle_degrees: float,
+) -> dict[str, Any]:
+ """构造只包含方向、文本和 bbox 的最小 pdftext span。"""
+
+ return {
+ "text": text,
+ "bbox": bbox,
+ "rotation": math.radians(angle_degrees),
+ "chars": [],
+ }
+
+
+def _line(
+ spans: list[dict[str, Any]],
+ angle_degrees: float,
+ bbox: tuple[float, float, float, float] = (0.0, 0.0, 100.0, 100.0),
+) -> dict[str, Any]:
+ """构造测试混合方向拆分使用的最小 pdftext line。"""
+
+ return {
+ "spans": spans,
+ "bbox": bbox,
+ "rotation": math.radians(angle_degrees),
+ }
+
+
+def test_mixed_footer_and_315_degree_watermark_are_split_before_filtering() -> None:
+ """验证接近 315 度的 span 不会继续借用父行 0 度方向与巨型 bbox。"""
+
+ pdf_line = _line(
+ [
+ _span("文档问题反馈: [email protected]", (30.0, 90.0, 80.0, 98.0), 0.0),
+ _span("深圳TCL智能家庭科技有限公司raynL", (5.0, 10.0, 25.0, 95.0), 315.000019),
+ _span("\r\n", (26.0, 20.0, 26.0, 20.0), 0.0),
+ ],
+ 0.0,
+ )
+
+ children = native_text._split_pdftext_line_by_rotation(pdf_line)
+ items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))
+
+ assert [round(math.degrees(child["rotation"]), 6) for child in children] == [0.0, 315.000019]
+ assert children[0]["bbox"] == (30.0, 90.0, 80.0, 98.0)
+ assert children[1]["bbox"] == (5.0, 10.0, 25.0, 95.0)
+ assert [(item.text, item.bbox, item.angle) for item in items] == [
+ ("文档问题反馈: [email protected]", (30.0, 90.0, 80.0, 98.0), 0)
+ ]
+
+
+def test_small_oblique_span_stays_inside_standard_direction_line() -> None:
+ """验证约 19 度的仿斜体 span 不触发方向拆分且沿用父行 0 度。"""
+
+ pdf_line = _line(
+ [
+ _span("normal ", (10.0, 20.0, 40.0, 30.0), 0.0),
+ _span("oblique", (40.0, 18.0, 75.0, 30.0), 19.0),
+ ],
+ 0.0,
+ )
+
+ children = native_text._split_pdftext_line_by_rotation(pdf_line)
+ items = native_text._build_native_line_items([pdf_line], (100.0, 100.0))
+
+ assert len(children) == 1
+ assert math.degrees(children[0]["rotation"]) == pytest.approx(0.0)
+ assert [(item.text, item.angle) for item in items] == [("normal oblique", 0)]
+
+
+ ("line_angle", "page_rotation", "expected_angle"),
+ [
+ (0.0, 0, 0),
+ (90.0, 0, 90),
+ (270.0, 0, 270),
+ (180.0, 0, None),
+ (315.000019, 0, None),
+ (180.0, 90, 270),
+ (90.0, 90, None),
+ ],
+)
+def test_only_supported_visual_line_directions_are_retained(
+ line_angle: float,
+ page_rotation: int,
+ expected_angle: int | None,
+) -> None:
+ """验证方向白名单在页面旋转后生效,且不会先把斜向行归一为 0 度。"""
+
+ pdf_line = _line([_span("value", (10.0, 20.0, 40.0, 30.0), line_angle)], line_angle)
+
+ items = native_text._build_native_line_items(
+ [pdf_line],
+ (100.0, 100.0),
+ page_rotation=page_rotation,
+ )
+
+ assert [item.angle for item in items] == ([] if expected_angle is None else [expected_angle])
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index 7ede448b..bb7a91da 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -20,6 +20,62 @@ from mineru.backend.flash.native_pdf import (
text_blocks,
titles,
)
+from mineru.utils.pdf_document import PDFImageInfo
+
+
+def _image_info(
+ fingerprint: str | None,
+ bbox: tuple[float, float, float, float],
+) -> PDFImageInfo:
+ """构造跨页图片水印规则使用的轻量图片信息。"""
+
+ return PDFImageInfo(bbox=bbox, fingerprint=fingerprint)
+
+
+def test_repeated_large_image_requires_three_distinct_pages() -> None:
+ """验证同页重复只计一次,面积恰好 8% 且跨三页时才命中水印。"""
+
+ page_sizes = [(100.0, 100.0)] * 4
+ page_image_infos = [
+ [
+ _image_info("watermark", (0.0, 0.0, 40.0, 20.0)),
+ _image_info("watermark", (0.0, 0.0, 40.0, 20.0)),
+ _image_info("two-pages", (0.0, 0.0, 50.0, 20.0)),
+ ],
+ [_image_info("watermark", (10.0, 10.0, 50.0, 30.0))],
+ [_image_info("watermark", (20.0, 20.0, 60.0, 40.0))],
+ [_image_info("two-pages", (0.0, 0.0, 50.0, 20.0))],
+ ]
+
+ fingerprints = pipeline._detect_repeated_raster_watermark_fingerprints(
+ page_image_infos,
+ page_sizes,
+ )
+
+ assert fingerprints == {"watermark"}
+
+
+def test_repeated_watermark_filter_keeps_small_or_unfingerprinted_images() -> None:
+ """验证已命中指纹也只删除大图,小图和指纹读取失败的图片继续进入现有流程。"""
+
+ image_infos = [
+ _image_info("watermark", (0.0, 0.0, 40.0, 20.0)),
+ _image_info("watermark", (0.0, 0.0, 39.9, 20.0)),
+ _image_info(None, (0.0, 0.0, 80.0, 80.0)),
+ _image_info("ordinary", (0.0, 0.0, 80.0, 80.0)),
+ ]
+
+ filtered = pipeline._filter_repeated_raster_watermark_bboxes(
+ image_infos,
+ (100.0, 100.0),
+ {"watermark"},
+ )
+
+ assert filtered == [
+ (0.0, 0.0, 39.9, 20.0),
+ (0.0, 0.0, 80.0, 80.0),
+ (0.0, 0.0, 80.0, 80.0),
+ ]
def test_flash_extractor_has_no_local_ocr_runtime_logic() -> None:
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index 8f177d9f..fee48500 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -204,6 +204,16 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
events.append(f"image_bboxes:{lock.depth}:{page_bbox}:{page_rotation}")
return []
+ def fake_extract_page_image_infos(
+ page: _FakePage,
+ page_bbox: tuple[float, float, float, float],
+ page_rotation: int,
+ ) -> list[pdf_document.PDFImageInfo]:
+ """记录图片指纹元数据遍历时仍由 PDFDocument 持有 PDFium 锁。"""
+
+ events.append(f"image_infos:{lock.depth}:{page_bbox}:{page_rotation}")
+ return []
+
def fake_extract_page_path_infos(
page: _FakePage,
page_bbox: tuple[float, float, float, float],
@@ -228,6 +238,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
monkeypatch.setattr(pdf_document, "_extract_page_drawing_lines", fake_extract_page_drawing_lines)
monkeypatch.setattr(pdf_document, "_extract_page_path_infos", fake_extract_page_path_infos)
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)
doc = pdf_document.PDFDocument(b"%PDF")
@@ -240,6 +251,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
assert doc.get_page_drawing_lines(0) == []
assert doc.get_page_path_infos(0) == []
assert doc.get_page_image_bboxes(0) == []
+ assert doc.get_page_image_infos(0) == []
assert doc.get_page_form_bboxes(0) == []
assert any(event.startswith("doc.open:") and not event.startswith("doc.open:0:") for event in events)
@@ -255,6 +267,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: p
assert "drawing_lines:1:(0.0, 0.0, 20.0, 10.0):0" in events
assert "path_infos:1:(0.0, 0.0, 20.0, 10.0):0" in events
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
@@ -357,6 +370,55 @@ def test_get_page_image_bboxes_applies_forms_crop_box_rotation_and_clipping() ->
)
+def test_get_page_image_infos_preserves_bboxes_and_fingerprints_reused_images() -> None:
+ """验证图片信息保持既有几何,并为普通与 Form 复用图生成相同内容指纹。"""
+
+ with pdf_document.PDFDocument(_build_rotated_cropped_image_pdf()) as doc:
+ image_infos = doc.get_page_image_infos(0)
+
+ assert [info.bbox for info in image_infos] == pytest.approx(
+ [
+ (160.0, 0.0, 180.0, 15.0),
+ (10.0, 5.0, 50.0, 35.0),
+ (76.0, 47.0, 88.0, 53.0),
+ ]
+ )
+ assert len({info.fingerprint for info in image_infos}) == 1
+ assert image_infos[0].fingerprint is not None
+
+
+def test_image_fingerprint_fails_open_when_raw_stream_exceeds_limit(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证超大图片流不分配缓冲区且返回空指纹,后续按普通图片放行。"""
+
+ raw_data_calls: list[tuple[object | None, int]] = []
+
+ def fake_metadata(raw_obj: object, raw_page: object, metadata_pointer: Any) -> int:
+ """填入有效像素宽高,使测试只命中原始流大小上限。"""
+
+ metadata_pointer._obj.width = 100
+ metadata_pointer._obj.height = 200
+ return 1
+
+ def fake_raw_data(raw_obj: object, buffer: object | None, buffer_length: int) -> int:
+ """声明超过上限的流,并记录是否发生第二次缓冲区读取。"""
+
+ raw_data_calls.append((buffer, buffer_length))
+ return pdf_document.PDF_IMAGE_FINGERPRINT_MAX_RAW_BYTES + 1
+
+ class _FakePage:
+ """提供 PDFium 元数据接口所需的最小 raw 页面句柄。"""
+
+ raw = object()
+
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFImageObj_GetImageMetadata", fake_metadata)
+ monkeypatch.setattr(pdf_document.pdfium_c, "FPDFImageObj_GetImageDataRaw", fake_raw_data)
+
+ assert pdf_document._get_raw_image_fingerprint(object(), _FakePage()) is None
+ assert raw_data_calls == [(None, 0)]
+
+
def test_get_page_form_bboxes_reads_root_forms_and_nested_content_bounds() -> None:
"""验证顶层 Form bbox 覆盖其嵌套绘图内容,且不重复输出内部对象。"""
with pdf_document.PDFDocument(_build_drawing_pdf()) as doc: