From c669f65c6b31b3fca3c3b4281840954bae5b1027 Mon Sep 17 00:00:00 2001 From: Orionis Date: Tue, 17 Nov 2026 00:39:34 +0100 Subject: [PATCH] :bug: Correction du texte --- src/scalper/ocr.py | 7 ++++++- src/scalper/typeset.py | 41 +++++++++++++++++++++++++-------------- tests/test_ocr_typeset.py | 41 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 16 deletions(-) diff --git a/src/scalper/ocr.py b/src/scalper/ocr.py index 111d090..d5892a1 100644 --- a/src/scalper/ocr.py +++ b/src/scalper/ocr.py @@ -39,7 +39,12 @@ class TesseractOCR: r["box"][2] = max(r["box"][2], data["left"][i] + data["width"][i]) r["box"][3] = max(r["box"][3], data["top"][i] + data["height"][i]) r["text"] = (r["text"] + " " + text).strip() - return [dict(v, index=i) for i, v in enumerate(regions.values())] + out = [] + for i, v in enumerate(regions.values()): + x0, y0, x1, y1 = v["box"] + # format de sortie : [x, y, w, h] (et non [x0, y0, x1, y1]) + out.append(dict(v, index=i, box=[x0, y0, max(1, x1 - x0), max(1, y1 - y0)])) + return out class FakeOCR: diff --git a/src/scalper/typeset.py b/src/scalper/typeset.py index 951e6e2..f74fc10 100644 --- a/src/scalper/typeset.py +++ b/src/scalper/typeset.py @@ -40,20 +40,23 @@ def wrap_text(draw, text: str, font, max_width: int) -> list[str]: def _inpaint(img, box: list[int]) -> tuple[int, int, int]: - """Inpainting : la boîte est remplie par la couleur de fond estimée sur l'anneau - de pixels juste autour de la boîte (donc hors du texte), et non par la moyenne de - la boîte elle-même (qui serait assombrie par le texte). Retourne la couleur RGB - de remplissage. Repli : moyenne de la boîte si l'anneau est vide (bord d'image).""" + """Inpainting : la boîte (légèrement élargie pour couvrir les bords du texte) est + remplie par la couleur de fond estimée sur l'anneau de pixels juste autour (donc hors + du texte), et non par la moyenne de la boîte elle-même (assombrie par le texte). + Retourne la couleur RGB de remplissage. Repli : moyenne de la boîte si l'anneau est + vide (bord d'image).""" from PIL import Image x, y, w, h = box - x, y = max(0, x), max(0, y) - w, h = min(max(1, w), img.width - x), min(max(1, h), img.height - y) - if w <= 0 or h <= 0: + pad = max(1, min(w, h) // 10) + x0, y0 = max(0, x - pad), max(0, y - pad) + x1, y1 = min(img.width, x + w + pad), min(img.height, y + h + pad) + w2, h2 = x1 - x0, y1 - y0 + if w2 <= 0 or h2 <= 0: return (255, 255, 255) - margin = max(2, min(w, h) // 8) - rx0, ry0 = max(0, x - margin), max(0, y - margin) - rx1, ry1 = min(img.width, x + w + margin), min(img.height, y + h + margin) + margin = max(2, min(w2, h2) // 8) + rx0, ry0 = max(0, x0 - margin), max(0, y0 - margin) + rx1, ry1 = min(img.width, x1 + margin), min(img.height, y1 + margin) ring = img.crop((rx0, ry0, rx1, ry1)) rw, rh = ring.size if rw > 2 and rh > 2: @@ -73,8 +76,8 @@ def _inpaint(img, box: list[int]) -> tuple[int, int, int]: sum(p[2] for p in samples) // n, ) else: - fill_rgb = img.crop((x, y, x + w, y + h)).resize((1, 1)).getpixel((0, 0))[:3] - img.paste(Image.new("RGB", (w, h), fill_rgb), (x, y)) + fill_rgb = img.crop((x0, y0, x1, y1)).resize((1, 1)).getpixel((0, 0))[:3] + img.paste(Image.new("RGB", (w2, h2), fill_rgb), (x0, y0)) return fill_rgb @@ -102,14 +105,22 @@ def replace_texts(image_path: Path, regions: list[dict[str, Any]], translations: if not text or text == r.get("text", "").strip(): continue x, y, w, h = r["box"] + if w < 8 or h < 8: + continue # mini-région = bruit OCR fill_rgb = _inpaint(img, [x, y, w, h]) text_fill, stroke_fill = _text_colors(fill_rgb) draw = ImageDraw.Draw(img) - font_size = max(10, int(h * 0.8)) + # taille de départ proche du texte original (hauteur de boîte ≈ hauteur de ligne) + font_size = max(8, int(h * 0.8)) font = _load_font(font_size) lines = wrap_text(draw, text, font, max(10, w - 8)) - while font_size > 8 and (font_size + 2) * len(lines) > h: - font_size -= 2 + # on réduit jusqu'à tenir dans la boîte, en largeur ET en hauteur + while font_size > 8: + too_tall = (font_size + 2) * len(lines) > h + too_wide = max(draw.textlength(ln, font=font) for ln in lines) > w - 8 + if not too_tall and not too_wide: + break + font_size -= 1 font = _load_font(font_size) lines = wrap_text(draw, text, font, max(10, w - 8)) line_h = font_size + 2 diff --git a/tests/test_ocr_typeset.py b/tests/test_ocr_typeset.py index 603946f..317a2f5 100644 --- a/tests/test_ocr_typeset.py +++ b/tests/test_ocr_typeset.py @@ -17,6 +17,22 @@ except ImportError: HAS_PIL = False +class TestTesseractBoxFormat(unittest.TestCase): + def test_box_is_xywh_not_corners(self): + from scalper.ocr import TesseractOCR + + data = { + "text": ["Hello", "world"], "conf": [90, 85], + "block_num": [1, 1], "par_num": [1, 1], "line_num": [1, 1], + "left": [100, 140], "top": [50, 52], "width": [30, 40], "height": [20, 18], + } + with mock.patch("pytesseract.image_to_data", return_value=data): + regions = TesseractOCR().recognize(Path("p.png")) + self.assertEqual(len(regions), 1) + self.assertEqual(regions[0]["box"], [100, 50, 80, 20]) # x, y, w, h + self.assertEqual(regions[0]["text"], "Hello world") + + @unittest.skipUnless(HAS_PIL, "Pillow requis") class TestOCRTypeset(unittest.TestCase): def _make_image(self, path: Path, size=(300, 120)) -> None: @@ -103,6 +119,31 @@ class TestOCRTypeset(unittest.TestCase): px = img.getpixel((150, 35)) self.assertGreater(px[0], 150) + def test_replace_texts_stays_inside_box(self): + with tempfile.TemporaryDirectory() as tmp: + src, out = Path(tmp) / "p.png", Path(tmp) / "out.png" + img = Image.new("RGB", (400, 200), (200, 220, 255)) + ImageDraw.Draw(img).text((60, 60), "Hi", fill=(0, 0, 0)) + img.save(src) + regions = [{"index": 0, "box": [50, 50, 120, 30], "text": "Hi"}] # x, y, w, h + replace_texts(src, regions, ["Une traduction beaucoup plus longue que l'original"], out) + res = Image.open(out).convert("RGB") + self.assertEqual(res.getpixel((10, 10)), (200, 220, 255)) # hors boîte : inchangé + self.assertEqual(res.getpixel((300, 150)), (200, 220, 255)) # idem + dark = any(res.getpixel((px, py))[0] < 100 for px in range(50, 170) for py in range(50, 80)) + self.assertTrue(dark, "le texte traduit doit être redessiné dans la boîte") + + def test_degenerate_region_skipped(self): + with tempfile.TemporaryDirectory() as tmp: + src, out = Path(tmp) / "p.png", Path(tmp) / "out.png" + self._make_image(src) + before = Image.open(src).convert("RGB").copy() + regions = [{"index": 0, "box": [5, 5, 4, 4], "text": "x"}] # trop petit = bruit + replace_texts(src, regions, ["y"], out) + from PIL import ImageChops + + self.assertIsNone(ImageChops.difference(before, Image.open(out).convert("RGB")).getbbox()) + def test_pipeline_ocr_typeset_end_to_end(self): with tempfile.TemporaryDirectory() as tmp: d = Path(tmp)