fix(ocr): ne plus utiliser sur dt_polys/rec_boxes (ndarray -> truth value ambigu)
rec_boxes est un np.ndarray : sur une page sans texte, dt_polys=[] (falsy) donc evaluait bool(ndarray vide) -> ValueError 'truth value of an empty array is ambiguous' -> chapitre OCR en erreur -> export/images-<lang>/ jamais cree. Remplace par des tests None/len + _as_list(). Reproduit et valide avec le vrai moteur (paddle 3.2.2 + paddleocr 3.7.0) : image vide -> [], image 5 lignes -> 5 regions xywh correctes. Test de regression avec champs array-like (bool() qui raise). Co-authored-by: Orionis312050 <Orionis312050@users.noreply.github.com>
This commit is contained in:
1 parent
b7a8881692
commit
0a1389c9ad
2 files changed
+53
-5
No files matched your search
+18
-5
@@ -14,6 +14,13 @@ from pathlib import Path
|
|||||||
from typing import Any, Protocol
|
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):
|
class OCRClient(Protocol):
|
||||||
def recognize(self, image_path: Path, lang: str = "eng") -> list[dict[str, Any]]: ...
|
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")
|
paddle_lang = _PADDLE_LANGS.get((lang or self.lang), "en")
|
||||||
self._engine = _PaddleEngine(lang=paddle_lang, use_textline_orientation=True)
|
self._engine = _PaddleEngine(lang=paddle_lang, use_textline_orientation=True)
|
||||||
results = self._engine.predict(str(image_path))
|
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]] = []
|
regions: list[dict[str, Any]] = []
|
||||||
for res in results or []:
|
for res in results:
|
||||||
texts = res.get("rec_texts") or []
|
texts = _as_list(res.get("rec_texts"))
|
||||||
scores = res.get("rec_scores") or []
|
scores = _as_list(res.get("rec_scores"))
|
||||||
polys = res.get("dt_polys") or res.get("rec_boxes") or []
|
polys = res.get("dt_polys")
|
||||||
for text, score, poly in zip(texts, scores, 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()
|
text = (text or "").strip()
|
||||||
try:
|
try:
|
||||||
score = float(score)
|
score = float(score)
|
||||||
|
|||||||
@@ -61,6 +61,41 @@ class TestPaddleOCRMapping(unittest.TestCase):
|
|||||||
self.assertEqual(regions[0]["text"], "Hello")
|
self.assertEqual(regions[0]["text"], "Hello")
|
||||||
self.assertEqual(regions[0]["index"], 0)
|
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):
|
def test_missing_paddle_raises_clear_error(self):
|
||||||
from scalper.ocr import PaddleOCR
|
from scalper.ocr import PaddleOCR
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user