🐛 Correction du texte

This commit is contained in:
Orionis committed 2026-11-17 00:39:34 +01:00
1 parent 05d5cc43b0
commit c669f65c6b
3 files changed
+73 -16

No files matched your search

+6 -1
View File
@@ -39,7 +39,12 @@ class TesseractOCR:
r["box"][2] = max(r["box"][2], data["left"][i] + data["width"][i]) 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["box"][3] = max(r["box"][3], data["top"][i] + data["height"][i])
r["text"] = (r["text"] + " " + text).strip() 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: class FakeOCR:
+26 -15
View File
@@ -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]: 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 """Inpainting : la boîte (légèrement élargie pour couvrir les bords du texte) est
de pixels juste autour de la boîte (donc hors du texte), et non par la moyenne de remplie par la couleur de fond estimée sur l'anneau de pixels juste autour (donc hors
la boîte elle-même (qui serait assombrie par le texte). Retourne la couleur RGB du texte), et non par la moyenne de la boîte elle-même (assombrie par le texte).
de remplissage. Repli : moyenne de la boîte si l'anneau est vide (bord d'image).""" Retourne la couleur RGB de remplissage. Repli : moyenne de la boîte si l'anneau est
vide (bord d'image)."""
from PIL import Image from PIL import Image
x, y, w, h = box x, y, w, h = box
x, y = max(0, x), max(0, y) pad = max(1, min(w, h) // 10)
w, h = min(max(1, w), img.width - x), min(max(1, h), img.height - y) x0, y0 = max(0, x - pad), max(0, y - pad)
if w <= 0 or h <= 0: 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) return (255, 255, 255)
margin = max(2, min(w, h) // 8) margin = max(2, min(w2, h2) // 8)
rx0, ry0 = max(0, x - margin), max(0, y - margin) rx0, ry0 = max(0, x0 - margin), max(0, y0 - margin)
rx1, ry1 = min(img.width, x + w + margin), min(img.height, y + h + margin) rx1, ry1 = min(img.width, x1 + margin), min(img.height, y1 + margin)
ring = img.crop((rx0, ry0, rx1, ry1)) ring = img.crop((rx0, ry0, rx1, ry1))
rw, rh = ring.size rw, rh = ring.size
if rw > 2 and rh > 2: 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, sum(p[2] for p in samples) // n,
) )
else: else:
fill_rgb = img.crop((x, y, x + w, y + h)).resize((1, 1)).getpixel((0, 0))[:3] fill_rgb = img.crop((x0, y0, x1, y1)).resize((1, 1)).getpixel((0, 0))[:3]
img.paste(Image.new("RGB", (w, h), fill_rgb), (x, y)) img.paste(Image.new("RGB", (w2, h2), fill_rgb), (x0, y0))
return fill_rgb 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(): if not text or text == r.get("text", "").strip():
continue continue
x, y, w, h = r["box"] 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]) fill_rgb = _inpaint(img, [x, y, w, h])
text_fill, stroke_fill = _text_colors(fill_rgb) text_fill, stroke_fill = _text_colors(fill_rgb)
draw = ImageDraw.Draw(img) 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) font = _load_font(font_size)
lines = wrap_text(draw, text, font, max(10, w - 8)) lines = wrap_text(draw, text, font, max(10, w - 8))
while font_size > 8 and (font_size + 2) * len(lines) > h: # on réduit jusqu'à tenir dans la boîte, en largeur ET en hauteur
font_size -= 2 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) font = _load_font(font_size)
lines = wrap_text(draw, text, font, max(10, w - 8)) lines = wrap_text(draw, text, font, max(10, w - 8))
line_h = font_size + 2 line_h = font_size + 2
+41
View File
@@ -17,6 +17,22 @@ except ImportError:
HAS_PIL = False 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") @unittest.skipUnless(HAS_PIL, "Pillow requis")
class TestOCRTypeset(unittest.TestCase): class TestOCRTypeset(unittest.TestCase):
def _make_image(self, path: Path, size=(300, 120)) -> None: def _make_image(self, path: Path, size=(300, 120)) -> None:
@@ -103,6 +119,31 @@ class TestOCRTypeset(unittest.TestCase):
px = img.getpixel((150, 35)) px = img.getpixel((150, 35))
self.assertGreater(px[0], 150) 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): def test_pipeline_ocr_typeset_end_to_end(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
d = Path(tmp) d = Path(tmp)