From 99559b58a134caab1a329d81f5d3e03f7978fbe8 Mon Sep 17 00:00:00 2001 From: Orionis Date: Thu, 19 Nov 2026 00:40:08 +0100 Subject: [PATCH] =?UTF-8?q?fix(ocr):=20normaliser=20les=20coordonn=C3=A9es?= =?UTF-8?q?=20PaddleOCR=20dans=20le=20r=C3=A9f=C3=A9rentiel=20de=20l'image?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sur les très grandes pages (ex. 690x10000), le modèle de détection de PaddleOCR redimensionne l'entrée en interne (max_side_limit=4000, UVDoc...) et les coordonnées返voyées (dt_polys/rec_boxes) peuvent dépasser l'image (jusqu'à ~2x constate dans out/ocr.json) : masques LaMa et texte traduit étaient placés hors des bulles -> texte original non effacé, traduction au mauvais endroit. - ocr.py : _normalize_polys ramène les polygones dans l'image (rescale uniforme 1/k sur le plus grand dépassement, puis clamp), appliqué dans PaddleOCR.recognize (box + poly) ; _image_size lit la taille réelle (PIL) - typeset.py : _clamp_regions clamp défensif des boîtes dans l'image avant inpainting/retypographie (protection même avec un ancien ocr.json) - tests : normalisation (dépassement 2x -> dans l'image, échelle 1/2), recognize() avec image réelle + moteur factice, inchangé si pas de dépassement Vérifié sur out/ (607 régions) : avant 146/607 boîtes dans l'image, après 607/607. Suite : 96 passed, 1 skipped. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- README.md | 4 ++- src/scalper/ocr.py | 68 ++++++++++++++++++++++++++++++++------- src/scalper/typeset.py | 25 +++++++++++++- tests/test_ocr_typeset.py | 56 ++++++++++++++++++++++++++++++++ 4 files changed, 140 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index e173be6..06c3207 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,9 @@ chapitre contient des images (désactivable avec `--no-ocr` / `"with_ocr": false (loguées `1/4`…`4/4`) : 1. **OCR** : extraction du texte brut des bulles (`ocr.json`, avec le quadrilatère `poly` quand le - moteur le fournit — PaddleOCR) ; + moteur le fournit — PaddleOCR). Les coordonnées renvoyées par PaddleOCR sont **normalisées dans le + référentiel de l'image réelle** (sur les très grandes pages, le modèle de détection redimensionne + en interne et peut renvoyer des coordonnées hors image → rescale uniforme + clamp) ; 2. **traduction** de chaque texte détecté par le LLM ; 3. **inpainting** du texte original sur les images **brutes** (voir moteurs ci-dessous — LaMa efface le texte entièrement, masque = polygone OCR dilaté, style « pinceau magique » ; seuls les pixels diff --git a/src/scalper/ocr.py b/src/scalper/ocr.py index 16a4c7d..72be769 100644 --- a/src/scalper/ocr.py +++ b/src/scalper/ocr.py @@ -68,6 +68,47 @@ _PADDLE_LANGS = { } +def _image_size(path: Path) -> tuple[int, int] | None: + """Taille (w, h) réelle de l'image, ou None si illisible (tests avec chemins factices).""" + try: + from PIL import Image + + with Image.open(path) as im: + return im.size + except Exception: + return None + + +def _normalize_polys(polys: list, img_size: tuple[int, int] | None) -> list: + """Ramène les polygones dans le référentiel de l'image. + + Sur les très grandes images, le modèle de détection de PaddleOCR redimensionne + l'entrée en interne (max_side_limit) et peut renvoyer des coordonnées dans un + espace plus grand que l'image : on rescale alors uniformément (préserve l'aspect) + par 1/k avec k = max dépassement relatif, puis on clamp dans l'image. Sans + dépassement (coordonnées déjà dans l'image), rien ne change.""" + polys = _as_list(polys) + if not img_size or not polys: + return polys + img_w, img_h = img_size + if img_w <= 0 or img_h <= 0: + return polys + try: + max_x = max(float(p[0]) for poly in polys for p in poly) + max_y = max(float(p[1]) for poly in polys for p in poly) + k = max(max_x / img_w, max_y / img_h, 1.0) + s = 1.0 / k + return [ + [ + [min(max(float(p[0]) * s, 0.0), float(img_w)), min(max(float(p[1]) * s, 0.0), float(img_h))] + for p in poly + ] + for poly in polys + ] + except (TypeError, ValueError, IndexError): + return polys # format inattendu : on ne touche à rien + + class PaddleOCR: """OCR via PaddleOCR (gratuit, 100 % local, meilleur sur texte stylisé/bulles). @@ -94,7 +135,7 @@ class PaddleOCR: return [] if not isinstance(results, (list, tuple)): results = [results] - regions: list[dict[str, Any]] = [] + raw: list[tuple[str, float, list]] = [] for res in results: texts = _as_list(res.get("rec_texts")) scores = _as_list(res.get("rec_scores")) @@ -109,16 +150,21 @@ class PaddleOCR: score = -1.0 if not text or score < 0.6: continue - xs = [p[0] for p in poly] - ys = [p[1] for p in poly] - x0, y0, x1, y1 = min(xs), min(ys), max(xs), max(ys) - regions.append({ - "image": image_path.name, - "box": [int(x0), int(y0), max(1, int(x1 - x0)), max(1, int(y1 - y0))], - "text": text, - # quadrilatère du texte : masque plus fidèle pour l'inpainting LaMa - "poly": [[int(px), int(py)] for px, py in poly], - }) + raw.append((text, score, [list(p) for p in poly])) + # coordonnées -> référentiel de l'image réelle (voir _normalize_polys) + norm = _normalize_polys([poly for _, _, poly in raw], _image_size(image_path)) + regions: list[dict[str, Any]] = [] + for (text, _score, _poly), poly in zip(raw, norm): + xs = [p[0] for p in poly] + ys = [p[1] for p in poly] + x0, y0, x1, y1 = min(xs), min(ys), max(xs), max(ys) + regions.append({ + "image": image_path.name, + "box": [int(x0), int(y0), max(1, int(x1 - x0)), max(1, int(y1 - y0))], + "text": text, + # quadrilatère du texte : masque plus fidèle pour l'inpainting LaMa + "poly": [[int(px), int(py)] for px, py in poly], + }) for i, r in enumerate(regions): r["index"] = i return regions diff --git a/src/scalper/typeset.py b/src/scalper/typeset.py index 60f30a0..6c1251e 100644 --- a/src/scalper/typeset.py +++ b/src/scalper/typeset.py @@ -73,6 +73,28 @@ def _text_colors(fill_rgb: tuple[int, int, int]) -> tuple[tuple[int, int, int], return (255, 255, 255), (0, 0, 0) +def _clamp_regions(regions: list[dict[str, Any]], width: int, height: int) -> list[dict[str, Any]]: + """Clamp défensif des boîtes dans l'image : si une boîte OCR dépasse du canvas, + on la ramène dans l'image (évite de dessiner / inpainter hors image).""" + out = [] + for r in regions: + box = r.get("box") + if not box or len(box) != 4: + continue + try: + x, y, w, h = (int(v) for v in box) + except (TypeError, ValueError): + continue + x0 = max(0, min(x, max(0, width - 1))) + y0 = max(0, min(y, max(0, height - 1))) + x1 = min(width, x + w) + y1 = min(height, y + h) + if x1 - x0 < 1 or y1 - y0 < 1: + continue + out.append({**r, "box": [x0, y0, x1 - x0, y1 - y0]}) + return out + + def _todo_regions(regions: list[dict[str, Any]], translations: list[str]) -> list[tuple[dict[str, Any], str]]: """Régions à retyper : index valide, traduction non vide et différente du texte original, boîte assez grande (sinon c'est du bruit OCR).""" @@ -99,7 +121,7 @@ def inpaint_image_file(image_path: Path, regions: list[dict[str, Any]], out_path Image.MAX_IMAGE_PIXELS = None img = Image.open(image_path).convert("RGB") - valid = [r for r in regions if r.get("box") and len(r["box"]) == 4 and r["box"][2] >= 8 and r["box"][3] >= 8] + valid = [r for r in _clamp_regions(regions, img.width, img.height) if r["box"][2] >= 8 and r["box"][3] >= 8] if valid: img = inpainter.inpaint_image(img, valid).convert("RGB") out_path.parent.mkdir(parents=True, exist_ok=True) @@ -131,6 +153,7 @@ def replace_texts( img = Image.open(image_path).convert("RGB") if inpainter is None: inpainter = default_inpainter() + regions = _clamp_regions(regions, img.width, img.height) todo = _todo_regions(regions, translations) if todo and inpainter is not _DRAW_ONLY: img = inpainter.inpaint_image(img, [r for r, _ in todo]).convert("RGB") diff --git a/tests/test_ocr_typeset.py b/tests/test_ocr_typeset.py index 27aec9b..e756d7a 100644 --- a/tests/test_ocr_typeset.py +++ b/tests/test_ocr_typeset.py @@ -107,6 +107,62 @@ class TestPaddleOCRMapping(unittest.TestCase): self.assertEqual([r["text"] for r in full], ["Hello", "World"]) self.assertEqual(full[0]["box"], [100, 50, 30, 20]) + def test_recognize_normalizes_polys_to_image_size(self): + """Sur grande image, PaddleOCR peut renvoyer des coordonnées hors image + (espace redimensionné du modèle det) : on les rescale dans l'image.""" + from scalper.ocr import PaddleOCR, _normalize_polys + + # _normalize_polys : rescale uniforme si dépassement, clamp dans l'image + img_size = (690, 10000) + polys = [[[0, 0], [1380, 0], [1380, 20000], [0, 20000]]] # espace 2x + out = _normalize_polys(polys, img_size) + max_x = max(p[0] for q in out for p in q) + max_y = max(p[1] for q in out for p in q) + self.assertAlmostEqual(max_x, 690, delta=1) # 1380 * (1/2) + self.assertAlmostEqual(max_y, 10000, delta=1) # 20000 * (1/2) + # sans dépassement : inchangé + polys2 = [[[0, 0], [100, 0], [100, 50], [0, 50]]] + self.assertEqual(_normalize_polys(polys2, (690, 10000)), polys2) + + def test_recognize_scales_boxes_back_into_image(self): + """recognize() applique la normalisation à box + poly (image réelle créée avec PIL).""" + from scalper.ocr import PaddleOCR + + try: + from PIL import Image + except ImportError: + self.skipTest("Pillow requis") + + class FakeEngine: + def __init__(self, **kw): + pass + + def predict(self, path): + # coordonnées dans un espace 2x plus grand que l'image (690x500) + return [{ + "rec_texts": ["Hello"], + "rec_scores": [0.95], + "dt_polys": [[[200, 100], [1380, 100], [1380, 1000], [200, 1000]]], + }] + + with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp) / "p.png" + Image.new("RGB", (690, 500), (255, 255, 255)).save(p) + fake_mod = types.ModuleType("paddleocr") + fake_mod.PaddleOCR = FakeEngine + with mock.patch.dict(sys.modules, {"paddleocr": fake_mod}): + regions = PaddleOCR().recognize(p) + self.assertEqual(len(regions), 1) + x, y, w, h = regions[0]["box"] + self.assertLessEqual(x + w, 690, "box dans l'image") + self.assertLessEqual(y + h, 500, "box dans l'image") + self.assertTrue(all(0 <= px <= 690 and 0 <= py <= 500 for px, py in regions[0]["poly"])) + # échelle 1/2 (espace 2x) : box ~ [100, 50, 590, 450] + self.assertAlmostEqual(x, 100, delta=5) + self.assertAlmostEqual(y, 50, delta=5) + self.assertAlmostEqual(w, 590, delta=10) + self.assertAlmostEqual(h, 450, delta=10) + def test_missing_paddle_raises_clear_error(self): from scalper.ocr import PaddleOCR