diff --git a/src/scalper/ocr.py b/src/scalper/ocr.py index fd81548..1d20109 100644 --- a/src/scalper/ocr.py +++ b/src/scalper/ocr.py @@ -14,6 +14,13 @@ from pathlib import Path from typing import Any, Protocol +def _as_list(value: Any) -> list: + """Normalise list/ndarray/None en list (évite `or` sur un ndarray : truth value ambigu).""" + if value is None: + return [] + return list(value) + + class OCRClient(Protocol): def recognize(self, image_path: Path, lang: str = "eng") -> list[dict[str, Any]]: ... @@ -83,12 +90,18 @@ class PaddleOCR: paddle_lang = _PADDLE_LANGS.get((lang or self.lang), "en") self._engine = _PaddleEngine(lang=paddle_lang, use_textline_orientation=True) results = self._engine.predict(str(image_path)) + if results is None: + return [] + if not isinstance(results, (list, tuple)): + results = [results] regions: list[dict[str, Any]] = [] - for res in results or []: - texts = res.get("rec_texts") or [] - scores = res.get("rec_scores") or [] - polys = res.get("dt_polys") or res.get("rec_boxes") or [] - for text, score, poly in zip(texts, scores, polys): + for res in results: + texts = _as_list(res.get("rec_texts")) + scores = _as_list(res.get("rec_scores")) + polys = res.get("dt_polys") + if polys is None or len(polys) == 0: + polys = res.get("rec_boxes") + for text, score, poly in zip(texts, scores, _as_list(polys)): text = (text or "").strip() try: score = float(score) diff --git a/tests/test_ocr_typeset.py b/tests/test_ocr_typeset.py index 556b60f..68647b9 100644 --- a/tests/test_ocr_typeset.py +++ b/tests/test_ocr_typeset.py @@ -61,6 +61,41 @@ class TestPaddleOCRMapping(unittest.TestCase): self.assertEqual(regions[0]["text"], "Hello") self.assertEqual(regions[0]["index"], 0) + def test_recognize_tolerates_array_like_fields(self): + """rec_boxes/dt_polys peuvent être des ndarray : `x or y` crashe (truth value ambigu).""" + from scalper.ocr import PaddleOCR + + class FakeArray(list): + def __bool__(self): + raise ValueError("The truth value of an empty array is ambiguous") + + class FakeEngine: + def __init__(self, **kw): + pass + + def predict(self, path): + if path == "empty.png": + return [{"rec_texts": [], "rec_scores": [], "dt_polys": FakeArray(), "rec_boxes": FakeArray()}] + return [{ + "rec_texts": ["Hello", "World"], + "rec_scores": [0.95, 0.9], + "dt_polys": FakeArray([ + [[100, 50], [130, 50], [130, 70], [100, 70]], + [[10, 10], [40, 10], [40, 30], [10, 30]], + ]), + "rec_boxes": FakeArray(), + }] + + fake_mod = types.ModuleType("paddleocr") + fake_mod.PaddleOCR = FakeEngine + with mock.patch.dict(sys.modules, {"paddleocr": fake_mod}): + client = PaddleOCR() + empty = client.recognize(Path("empty.png")) + full = client.recognize(Path("multi.png")) + self.assertEqual(empty, []) + self.assertEqual([r["text"] for r in full], ["Hello", "World"]) + self.assertEqual(full[0]["box"], [100, 50, 30, 20]) + def test_missing_paddle_raises_clear_error(self): from scalper.ocr import PaddleOCR