Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix(ocr): skip zero-sized seal crops without misaligning results
myhloli1b2be98968d8
diff --git a/mineru/model/ocr/pp_ocr_v6_onnx.py b/mineru/model/ocr/pp_ocr_v6_onnx.pyindex c4418621..0694fe46 100644--- a/mineru/model/ocr/pp_ocr_v6_onnx.py+++ b/mineru/model/ocr/pp_ocr_v6_onnx.py@@ -28,7 +28,7 @@ from ..runtime.onnx import ort_sessionfrom .._internal.pytorchocr.data.imaug.operators import DetResizeForTest, NormalizeImagefrom .db_postprocess import DBPostProcessfrom .resources import PPOCRV6_DICT_PATH-from .seal_crop import CropByPolys, SortPolyBoxes+from .seal_crop import CropByPolys, SortPolyBoxes, filter_valid_seal_cropsfrom .geometry import merge_det_boxes, sorted_boxes, update_det_boxesfrom .image import check_img, get_rotate_crop_image_for_text_rec, preprocess_image, resize_text_recognition_image@@ -496,6 +496,7 @@ class PPOCRv6ONNX:if self.is_seal:dt_boxes = self._seal_sort_boxes(dt_boxes)img_crop_list = self._seal_crop_by_polys(ori_im, dt_boxes)+ dt_boxes, img_crop_list = filter_valid_seal_crops(dt_boxes, img_crop_list)else:dt_boxes = sorted_boxes(dt_boxes)if self.enable_merge_det_boxes:diff --git a/mineru/model/ocr/pytorch_paddle.py b/mineru/model/ocr/pytorch_paddle.pyindex 1beba38c..5d214c4f 100644--- a/mineru/model/ocr/pytorch_paddle.py+++ b/mineru/model/ocr/pytorch_paddle.py@@ -17,7 +17,7 @@ from .._internal.pytorchocr.infer.predict_system import TextSystemfrom .geometry import merge_det_boxes, sorted_boxes, update_det_boxesfrom .image import check_img, get_rotate_crop_image_for_text_rec, preprocess_imagefrom .language import normalize_ocr_model_lang-from .seal_crop import CropByPolys, SortPolyBoxes+from .seal_crop import CropByPolys, SortPolyBoxes, filter_valid_seal_cropsfrom .resources import PPOCRV6_DICT_PATHimport argparsefrom typing import Any@@ -155,15 +155,17 @@ class PytorchPaddleOCR(TextSystem):with open(os.path.join(sample_dir, "meta.json"), "w", encoding="utf-8") as f:json.dump(records, f, ensure_ascii=False, indent=2)- def ocr(self,- img,- det=True,- rec=True,- mfd_res=None,- tqdm_enable=False,- tqdm_desc="OCR-rec Predict",- tqdm_progress_bar=None,- ):+ def ocr(+ self,+ img: np.ndarray | list[np.ndarray] | str | bytes,+ det: bool = True,+ rec: bool = True,+ mfd_res: list[dict[str, Any]] | None = None,+ tqdm_enable: bool = False,+ tqdm_desc: str = "OCR-rec Predict",+ tqdm_progress_bar: Any = None,+ ) -> list[list[Any] | None] | None:+ """按模式执行 OCR,印章裁剪同步过滤无效轮廓并保持调试数据对应。"""assert isinstance(img, (np.ndarray, list, str, bytes))if isinstance(img, list) and det:logger.error('When input a list of images, det must be false')@@ -195,6 +197,7 @@ class PytorchPaddleOCR(TextSystem):if self.is_seal:dt_boxes = self._seal_sort_boxes(dt_boxes)img_crop_list = self._seal_crop_by_polys(img, dt_boxes)+ dt_boxes, img_crop_list = filter_valid_seal_crops(dt_boxes, img_crop_list)self._dump_seal_debug_artifacts(img, dt_boxes, img_crop_list)else:dt_boxes = sorted_boxes(dt_boxes)@@ -222,8 +225,10 @@ class PytorchPaddleOCR(TextSystem):ocr_res.append(rec_res)return ocr_res- def __call__(self, img, mfd_res=None):-+ def __call__(+ self, img: np.ndarray | None, mfd_res: list[dict[str, Any]] | None = None+ ) -> tuple[list[np.ndarray] | None, list[tuple[str, float]] | None]:+ """执行检测与识别,跳过无效印章裁片时同步移除检测框,避免文字错配。"""if img is None:logger.debug("no valid image provided")return None, None@@ -240,6 +245,9 @@ class PytorchPaddleOCR(TextSystem):if self.is_seal:dt_boxes = self._seal_sort_boxes(dt_boxes)img_crop_list = self._seal_crop_by_polys(ori_im, dt_boxes)+ dt_boxes, img_crop_list = filter_valid_seal_crops(dt_boxes, img_crop_list)+ if not img_crop_list:+ return [], []else:img_crop_list = []diff --git a/mineru/model/ocr/seal_crop.py b/mineru/model/ocr/seal_crop.pyindex cc178fe3..c4a73a45 100644--- a/mineru/model/ocr/seal_crop.py+++ b/mineru/model/ocr/seal_crop.py@@ -15,7 +15,7 @@from docvortex.image import minimum_rectangle, perspective_matrix, rectangle_corners, warp_imageimport copy-from typing import List, Tuple+from typing import List, Tuple, castimport numpy as npfrom numpy.linalg import norm@@ -24,6 +24,21 @@ from shapely.geometry import Polygonfrom .seal_det_warp import AutoRectifier+def filter_valid_seal_crops(+ dt_polys: list[np.ndarray], crops: list[np.ndarray | None]+) -> tuple[list[np.ndarray], list[np.ndarray]]:+ """同步过滤无效印章裁片和对应检测框,保持有效轮廓的识别顺序。"""+ valid_polys = []+ valid_crops = []+ for poly, crop in zip(dt_polys, crops, strict=True):+ if crop is not None and crop.size > 0:+ valid_polys.append(poly)+ valid_crops.append(crop)+ if len(valid_crops) == len(crops):+ return dt_polys, cast(list[np.ndarray], crops)+ return valid_polys, valid_crops++class SortPolyBoxes:def __call__(self, dt_polys: List[np.ndarray]) -> np.ndarray:num_boxes = len(dt_polys)@@ -44,7 +59,8 @@ class CropByPolys:def __init__(self, det_box_type: str = "quad") -> None:self.det_box_type = det_box_type- def __call__(self, img: np.ndarray, dt_polys: List[list]) -> List[np.ndarray]:+ def __call__(self, img: np.ndarray, dt_polys: list[np.ndarray]) -> list[np.ndarray | None]:+ """逐个裁剪印章轮廓,以原位置的 None 标记无法形成有效裁片的轮廓。"""if self.det_box_type == "quad":dt_boxes = np.array(dt_polys)output_list = []@@ -64,7 +80,8 @@ class CropByPolys:return output_list- def get_minarea_rect_crop(self, img: np.ndarray, points: np.ndarray) -> np.ndarray:+ def get_minarea_rect_crop(self, img: np.ndarray, points: np.ndarray) -> np.ndarray | None:+ """按最小外接矩形裁剪四边形,向调用方传递零尺寸裁片标记。"""bounding_box = minimum_rectangle(np.array(points).astype(np.int32))points = sorted(list(rectangle_corners(bounding_box)), key=lambda x: x[0])@@ -86,7 +103,8 @@ class CropByPolys:crop_img = self.get_rotate_crop_image(img, np.array(box))return crop_img- def get_rotate_crop_image(self, img: np.ndarray, points: list) -> np.ndarray:+ def get_rotate_crop_image(self, img: np.ndarray, points: np.ndarray) -> np.ndarray | None:+ """沿用透视裁剪和转正规则,在生成矩阵前跳过取整后零宽或零高的轮廓。"""assert len(points) == 4, "shape of points must be 4*2"img_crop_width = int(max(@@ -100,6 +118,8 @@ class CropByPolys:np.linalg.norm(points[1] - points[2]),))+ if img_crop_width < 1 or img_crop_height < 1:+ return Nonepts_std = np.float32([[0, 0],@@ -225,7 +245,8 @@ class CropByPolys:unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8)return np.arccos(np.clip(np.sum(unit_vec1 * unit_vec2, axis=-1), -1.0, 1.0))- def get_minarea_rect(self, img: np.ndarray, points: np.ndarray) -> Tuple[np.ndarray, list]:+ def get_minarea_rect(self, img: np.ndarray, points: np.ndarray) -> tuple[np.ndarray | None, list[np.ndarray]]:+ """返回多边形的外接矩形和可选裁片,保留无效轮廓的几何信息。"""bounding_box = minimum_rectangle(points)points = sorted(list(rectangle_corners(bounding_box)), key=lambda x: x[0])@@ -316,17 +337,23 @@ class CropByPolys:resampled_line = np.array(mean_positions)return resampled_line- def get_poly_rect_crop(self, img, points):+ def get_poly_rect_crop(self, img: np.ndarray, points: np.ndarray) -> np.ndarray | None:+ """对有效多边形执行既有曲线展开,外接矩形无有效像素时直接跳过。"""points = np.array(points).astype(np.int32).reshape(-1, 2)temp_crop_img, temp_box = self.get_minarea_rect(img, points)+ if temp_crop_img is None:+ return None- def get_union(pD, pG):+ def get_union(pD: np.ndarray, pG: list[np.ndarray]) -> float:+ """计算检测多边形与外接矩形的并集面积。"""return Polygon(pD).union(Polygon(pG)).area- def get_intersection_over_union(pD, pG):+ def get_intersection_over_union(pD: np.ndarray, pG: list[np.ndarray]) -> float:+ """沿用交并比判断是否需要曲线展开。"""return get_intersection(pD, pG) / (get_union(pD, pG) + 1e-10)- def get_intersection(pD, pG):+ def get_intersection(pD: np.ndarray, pG: list[np.ndarray]) -> float:+ """计算检测多边形与外接矩形的交集面积。"""return Polygon(pD).intersection(Polygon(pG)).areaif not Polygon(points).is_valid:diff --git a/tests/fixtures/seal_crop_degenerate.json b/tests/fixtures/seal_crop_degenerate.jsonnew file mode 100644index 00000000..16eb86e2--- /dev/null+++ b/tests/fixtures/seal_crop_degenerate.json@@ -0,0 +1,20 @@+{+ "source_page": 8,+ "seal_bbox": [0.722, 0.905, 0.822, 0.974],+ "image_shape": [163, 166, 3],+ "image_seed": 53,+ "degenerate_polygon": [[88, 25], [88, 26], [88, 26], [89, 26], [89, 26], [88, 26], [88, 25]],+ "degenerate_quad": [[88.00001, 25.000006], [89.00001, 26.000006], [88.50001, 26.500006], [87.50001, 25.500006]],+ "valid_cases": [+ {+ "points": [[10, 10], [40, 10], [40, 20], [10, 20]],+ "shape": [10, 30, 3],+ "sha256": "c218bbe983c48877b6a38dfde56255010589c870b8952050b146a732661b0bc0"+ },+ {+ "points": [[30, 40], [65, 45], [60, 60], [25, 55]],+ "shape": [15, 38, 3],+ "sha256": "1ecff08e6b4213f58f05adf33322db49917b64522d388142bab589ab46c5225e"+ }+ ]+}diff --git a/tests/unittest/test_seal_crop_degenerate.py b/tests/unittest/test_seal_crop_degenerate.pynew file mode 100644index 00000000..4e7262e8--- /dev/null+++ b/tests/unittest/test_seal_crop_degenerate.py@@ -0,0 +1,166 @@+"""印章零尺寸裁片及检测框、识别结果和调试产物对应关系回归。"""++from __future__ import annotations++import hashlib+import json+from collections.abc import Iterator+from pathlib import Path+from typing import Any+from unittest.mock import Mock++import numpy as np+import pytest+from PIL import Image++from mineru.model.ocr import seal_crop+from mineru.model.ocr.seal_crop import CropByPolys, SortPolyBoxes++_REFERENCE = json.loads((Path(__file__).parents[1] / "fixtures/seal_crop_degenerate.json").read_text())++[email protected](params=["python", "rust"])+def image_backend(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ """两种共享图像后端均检查无效轮廓和有效裁片的像素契约。"""+ from docvortex._compute_backend import get_native++ monkeypatch.setenv("DOCVORTEX_COMPUTE_BACKEND", request.param)+ get_native.cache_clear()+ try:+ yield+ finally:+ get_native.cache_clear()+++def seal_image() -> np.ndarray:+ """构造与真实失败印章尺寸一致的确定性图像。"""+ return np.random.default_rng(_REFERENCE["image_seed"]).integers(0, 256, _REFERENCE["image_shape"], dtype=np.uint8)++[email protected]("mode", ["poly", "quad"])+ "points",+ [+ _REFERENCE["degenerate_polygon"],+ [[20, 10], [20, 10], [20, 30], [20, 30]],+ [[10, 20], [30, 20], [30, 20], [10, 20]],+ [[10, 20]] * 4,+ ],+ ids=["real-repeated-points", "zero-width", "zero-height", "single-point"],+)+def test_invalid_seal_crop_keeps_original_position(+ image_backend: None, seal_image: np.ndarray, mode: str, points: list[list[int]]+) -> None:+ """真实重复点、线段和单点均保留无效裁片标记,且不影响前后有效轮廓。"""+ valid = np.asarray(_REFERENCE["valid_cases"][0]["points"])+ invalid = np.asarray(points)+ if mode == "quad":+ invalid = invalid[:4]+ crops = CropByPolys(mode)(seal_image, [valid, invalid, valid + 70])+ assert len(crops) == 3+ assert crops[0] is not None and crops[0].size > 0+ assert crops[1] is None+ assert crops[2] is not None and crops[2].size > 0+++def test_zero_target_size_is_rejected_before_matrix_creation(+ image_backend: None, seal_image: np.ndarray, monkeypatch: pytest.MonkeyPatch+) -> None:+ """真实四点裁片高度取整为零时,不再调用透视矩阵或共享采样内核。"""+ matrix = Mock(side_effect=AssertionError("zero-size target must not reach perspective_matrix"))+ warp = Mock(side_effect=AssertionError("zero-size target must not reach warp_image"))+ monkeypatch.setattr(seal_crop, "perspective_matrix", matrix)+ monkeypatch.setattr(seal_crop, "warp_image", warp)+ assert CropByPolys().get_rotate_crop_image(seal_image, np.asarray(_REFERENCE["degenerate_quad"], dtype=np.float32)) is None+ matrix.assert_not_called()+ warp.assert_not_called()++[email protected]("mode", ["poly", "quad"])[email protected]("case", _REFERENCE["valid_cases"], ids=["aligned", "inclined"])+def test_valid_seal_crop_keeps_frozen_pixels(+ image_backend: None, seal_image: np.ndarray, mode: str, case: dict[str, Any]+) -> None:+ """有效裁片保持修改前冻结的尺寸、全部像素和独立存储。"""+ original = seal_image.copy()+ crop = CropByPolys(mode)(seal_image, [np.asarray(case["points"])])[0]+ assert crop is not None+ assert list(crop.shape) == case["shape"]+ assert hashlib.sha256(crop.tobytes()).hexdigest() == case["sha256"]+ np.testing.assert_array_equal(seal_image, original)+ assert not np.shares_memory(crop, seal_image)+++def test_valid_crop_does_not_hide_unrelated_warp_errors(seal_image: np.ndarray, monkeypatch: pytest.MonkeyPatch) -> None:+ """尺寸有效时共享内核的其他错误继续抛出,避免宽泛回退掩盖真实故障。"""+ monkeypatch.setattr(seal_crop, "warp_image", Mock(side_effect=ValueError("unexpected warp error")))+ with pytest.raises(ValueError, match="unexpected warp error"):+ CropByPolys().get_rotate_crop_image(seal_image, np.asarray(_REFERENCE["valid_cases"][0]["points"], dtype=np.float32))+++def _build_seal_model(engine: str, boxes: list[np.ndarray], recognizer: Mock, debug_dir: Path) -> Any:+ """只替换检测和识别推理,保留两个引擎的真实裁剪、过滤与结果封装。"""+ if engine == "torch":+ from mineru.model.ocr.pytorch_paddle import PytorchPaddleOCR++ model = PytorchPaddleOCR.__new__(PytorchPaddleOCR)+ model._seal_debug_counter = 0+ model._seal_debug_dir = str(debug_dir)+ else:+ from mineru.model.ocr.pp_ocr_v6_onnx import PPOCRv6ONNX++ model = PPOCRv6ONNX.__new__(PPOCRv6ONNX)+ model.is_seal = True+ model.enable_merge_det_boxes = False+ model.drop_score = 0+ model.text_detector = Mock(return_value=(boxes, 0.0))+ model.text_recognizer = recognizer+ model._seal_sort_boxes = SortPolyBoxes()+ model._seal_crop_by_polys = CropByPolys("poly")+ return model++[email protected]("engine", ["torch", "onnx"])+def test_seal_recognition_keeps_boxes_and_debug_outputs_aligned(seal_image: np.ndarray, engine: str, tmp_path: Path) -> None:+ """跳过中间真实无效轮廓后,后一个识别文字和调试裁片仍对应最后的检测框。"""+ first = np.asarray(_REFERENCE["valid_cases"][0]["points"])+ last = first + 70+ invalid = np.asarray(_REFERENCE["degenerate_polygon"])+ texts = [("第一段", 0.8), ("第二段", 0.7)]+ recognizer = Mock(return_value=(texts, 0.0))+ model = _build_seal_model(engine, [first, invalid, last], recognizer, tmp_path)+ assert model.ocr(seal_image) == [[[first.tolist(), texts[0]], [last.tolist(), texts[1]]]]+ crops = recognizer.call_args.args[0]+ assert len(crops) == 2 and all(crop.size > 0 for crop in crops)+ if engine == "torch":+ sample_dir = tmp_path / "sample_0000"+ records = json.loads((sample_dir / "meta.json").read_text())+ assert [(record["index"], record["text"]) for record in records] == [(0, "第一段"), (1, "第二段")]+ for record, crop in zip(records, crops, strict=True):+ with Image.open(sample_dir / record["crop_path"]) as saved:+ np.testing.assert_array_equal(np.asarray(saved), crop[:, :, ::-1])++[email protected]("engine", ["torch", "onnx"])+def test_all_invalid_seal_crops_skip_recognition(seal_image: np.ndarray, engine: str, tmp_path: Path) -> None:+ """全部轮廓无效时外层 OCR 返回既有空结果,并且不执行识别模型。"""+ invalid = np.asarray(_REFERENCE["degenerate_polygon"])+ recognizer = Mock(side_effect=AssertionError("recognizer must not receive invalid crops"))+ model = _build_seal_model(engine, [invalid, invalid.copy()], recognizer, tmp_path)+ assert model.ocr(seal_image) == [None]+ recognizer.assert_not_called()++[email protected]("all_invalid", [False, True])+def test_torch_detection_only_keeps_debug_crops_aligned(seal_image: np.ndarray, tmp_path: Path, all_invalid: bool) -> None:+ """Torch 仅检测入口实际执行裁剪时,同步过滤返回框及调试图,空裁片也能安全输出。"""+ invalid = np.asarray(_REFERENCE["degenerate_polygon"])+ valid = np.asarray(_REFERENCE["valid_cases"][0]["points"])+ boxes = [invalid] if all_invalid else [valid, invalid]+ recognizer = Mock(side_effect=AssertionError("detection-only must not call recognizer"))+ model = _build_seal_model("torch", boxes, recognizer, tmp_path)+ assert model.ocr(seal_image, rec=False) == ([[]] if all_invalid else [[valid.tolist()]])+ recognizer.assert_not_called()+ records = json.loads((tmp_path / "sample_0000/meta.json").read_text())+ assert len(records) == (0 if all_invalid else 1)