fix(ocr): normaliser les coordonnées PaddleOCR dans le référentiel de l'image
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 <vibe@mistral.ai>
This commit is contained in:
1 parent
a1b01946cc
commit
99559b58a1
4 files changed
+130
-3
No files matched your search
@@ -44,7 +44,9 @@ chapitre contient des images (désactivable avec `--no-ocr` / `"with_ocr": false
|
|||||||
(loguées `1/4`…`4/4`) :
|
(loguées `1/4`…`4/4`) :
|
||||||
|
|
||||||
1. **OCR** : extraction du texte brut des bulles (`ocr.json`, avec le quadrilatère `poly` quand le
|
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 ;
|
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
|
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
|
le texte entièrement, masque = polygone OCR dilaté, style « pinceau magique » ; seuls les pixels
|
||||||
|
|||||||
+47
-1
@@ -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:
|
class PaddleOCR:
|
||||||
"""OCR via PaddleOCR (gratuit, 100 % local, meilleur sur texte stylisé/bulles).
|
"""OCR via PaddleOCR (gratuit, 100 % local, meilleur sur texte stylisé/bulles).
|
||||||
|
|
||||||
@@ -94,7 +135,7 @@ class PaddleOCR:
|
|||||||
return []
|
return []
|
||||||
if not isinstance(results, (list, tuple)):
|
if not isinstance(results, (list, tuple)):
|
||||||
results = [results]
|
results = [results]
|
||||||
regions: list[dict[str, Any]] = []
|
raw: list[tuple[str, float, list]] = []
|
||||||
for res in results:
|
for res in results:
|
||||||
texts = _as_list(res.get("rec_texts"))
|
texts = _as_list(res.get("rec_texts"))
|
||||||
scores = _as_list(res.get("rec_scores"))
|
scores = _as_list(res.get("rec_scores"))
|
||||||
@@ -109,6 +150,11 @@ class PaddleOCR:
|
|||||||
score = -1.0
|
score = -1.0
|
||||||
if not text or score < 0.6:
|
if not text or score < 0.6:
|
||||||
continue
|
continue
|
||||||
|
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]
|
xs = [p[0] for p in poly]
|
||||||
ys = [p[1] for p in poly]
|
ys = [p[1] for p in poly]
|
||||||
x0, y0, x1, y1 = min(xs), min(ys), max(xs), max(ys)
|
x0, y0, x1, y1 = min(xs), min(ys), max(xs), max(ys)
|
||||||
|
|||||||
+24
-1
@@ -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)
|
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]]:
|
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
|
"""Régions à retyper : index valide, traduction non vide et différente du texte
|
||||||
original, boîte assez grande (sinon c'est du bruit OCR)."""
|
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
|
Image.MAX_IMAGE_PIXELS = None
|
||||||
img = Image.open(image_path).convert("RGB")
|
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:
|
if valid:
|
||||||
img = inpainter.inpaint_image(img, valid).convert("RGB")
|
img = inpainter.inpaint_image(img, valid).convert("RGB")
|
||||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -131,6 +153,7 @@ def replace_texts(
|
|||||||
img = Image.open(image_path).convert("RGB")
|
img = Image.open(image_path).convert("RGB")
|
||||||
if inpainter is None:
|
if inpainter is None:
|
||||||
inpainter = default_inpainter()
|
inpainter = default_inpainter()
|
||||||
|
regions = _clamp_regions(regions, img.width, img.height)
|
||||||
todo = _todo_regions(regions, translations)
|
todo = _todo_regions(regions, translations)
|
||||||
if todo and inpainter is not _DRAW_ONLY:
|
if todo and inpainter is not _DRAW_ONLY:
|
||||||
img = inpainter.inpaint_image(img, [r for r, _ in todo]).convert("RGB")
|
img = inpainter.inpaint_image(img, [r for r, _ in todo]).convert("RGB")
|
||||||
|
|||||||
@@ -107,6 +107,62 @@ class TestPaddleOCRMapping(unittest.TestCase):
|
|||||||
self.assertEqual([r["text"] for r in full], ["Hello", "World"])
|
self.assertEqual([r["text"] for r in full], ["Hello", "World"])
|
||||||
self.assertEqual(full[0]["box"], [100, 50, 30, 20])
|
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):
|
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