Ajout de l'inpainting LaMa (big-lama ONNX) pour la suppression intelligente du texte
- nouveau module src/scalper/inpaint.py : protocol Inpainter, SimpleInpainter (remplissage par couleur de fond, ex-comportement) et LamaInpainter (big-lama advimman/lama via port ONNX Carve/LaMa-ONNX, onnxruntime CPU) : crop carre 512x512 avec contexte par region, masque polygone OCR (poly) ou rectangle dilate, composite uniquement des pixels masques a la resolution d'origine ; modele telecharge une fois (208 Mo, sha256 verifie) dans SCALPER_LAMA_CACHE, SCALPER_LAMA_MODEL pour un fichier local - selection par SCALPER_INPAINT_ENGINE / --inpaint-engine / "inpaint_engine" (simple|lama|auto, defaut auto = lama si onnxruntime installe) - typeset.py : inpainting de toute l'image via l'Inpainter puis retypographie de la traduction (Pillow) ; ocr.py : PaddleOCR expose le quadrilatere poly - pipeline/cli/server : parametre inpaint_engine cable de bout en bout - packaging : extra .[inpaint-lama] (onnxruntime+numpy), Dockerfile, entrypoint.sh (SCALPER_LAMA_CACHE=/app/data/.lama), docker-compose (SCALPER_INPAINT_ENGINE=lama), .env.example, README - tests : tests/test_inpaint.py (moteurs, masque, crop, telechargement sha256, LaMa avec session factice + test reel optionnel SCALPER_TEST_LAMA_MODEL) Verifie en reel sur une page du out/ : 0 pixel modifie hors masques, contraste du texte efface dans les boites, traduction reinseree par-dessus (~2,2 s/region en CPU). Suite complete : 74 passed, 1 skipped. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
1 parent
bbde55e27b
commit
74f47096cd
14 files changed
+768
-69
No files matched your search
@@ -7,3 +7,9 @@ MISTRAL_MODEL=mistral-small-latest
|
||||
# Port hôte publié par docker-compose (le conteneur interne reste sur 8000).
|
||||
# Décommente et change si le port est déjà occupé sur le serveur de déploiement :
|
||||
# SCALPER_HOST_PORT=8000
|
||||
|
||||
# Moteur d'inpainting pour la suppression du texte dans les images (simple|lama|auto, défaut auto).
|
||||
# lama = big-lama (advimman/lama) en ONNX, téléchargé une fois (~208 Mo) dans SCALPER_LAMA_CACHE.
|
||||
# SCALPER_INPAINT_ENGINE=lama
|
||||
# SCALPER_LAMA_CACHE=/app/data/.lama
|
||||
# SCALPER_LAMA_MODEL=/chemin/vers/lama_fp32.onnx # modèle local, si déjà téléchargé ailleurs
|
||||
+1
-1
@@ -10,7 +10,7 @@ WORKDIR /app
|
||||
COPY pyproject.toml README.md ./
|
||||
COPY src ./src
|
||||
|
||||
RUN pip install --no-cache-dir ".[ocr,ocr-paddle]"
|
||||
RUN pip install --no-cache-dir ".[ocr,ocr-paddle,inpaint-lama]"
|
||||
|
||||
RUN useradd -m scalper && mkdir -p /app/data /app/out && chown -R scalper:scalper /app
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
||||
| `scalper list-groups mangadex --query Keiyoushi` | recherche de groupes de traduction (API MangaDex) |
|
||||
| `scalper fetch-url <url>` | lien direct → `raw.html` + `meta.json` + `chapter.json` |
|
||||
| `scalper ocr <chapter_dir> [--mock-ocr]` | OCR des images (tesseract) → `ocr.json` |
|
||||
| `scalper typeset <chapter_dir> --lang fr` | remplace le texte des images par la traduction → `export/images-fr/` |
|
||||
| `scalper typeset <chapter_dir> --lang fr [--inpaint-engine lama]` | remplace le texte des images par la traduction → `export/images-fr/` |
|
||||
| `scalper run ... --no-ocr` | désactive l'OCR/typeset (actif par défaut si images présentes) |
|
||||
| `scalper fetch <source> <series> <chapitre>` | téléchargement brut + `state.json` (reprise) |
|
||||
| `scalper clean <raw.html> --out chapter.json` | nettoyage/structuration en blocs typés |
|
||||
@@ -40,11 +40,10 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
||||
|
||||
Dans `scalper run` (et `POST /run`), l'OCR + typesetting s'exécute **automatiquement** dès qu'un
|
||||
chapitre contient des images (désactivable avec `--no-ocr` / `"with_ocr": false`) :
|
||||
Tesseract (`pytesseract`, binaire installé dans l'image Docker) extrait les régions texte des
|
||||
images (`ocr.json`), chaque texte détecté est traduit par le LLM, puis `typeset` efface le texte
|
||||
original (inpainting : remplissage par la couleur de fond estimée sur l'anneau de pixels autour de
|
||||
la bulle) et redessine la traduction au même endroit, centrée, avec une couleur contrastée avec le
|
||||
fond (Pillow). Résultat : `export/images-<lang>/`.
|
||||
l'OCR extrait les régions texte des images (`ocr.json`, avec le quadrilatère `poly` quand le moteur
|
||||
le fournit — PaddleOCR), chaque texte détecté est traduit par le LLM, puis `typeset` efface le texte
|
||||
original (**inpainting**, voir moteurs ci-dessous) et redessine la traduction au même endroit,
|
||||
centrée, avec une couleur contrastée avec le fond (Pillow). Résultat : `export/images-<lang>/`.
|
||||
|
||||
La langue source de l'OCR est déduite de la langue détectée du chapitre (`en→eng`, `fr→fra`,
|
||||
`ja→jpn`…). L'image Docker n'embarque que `eng` (`tesseract-ocr` inclut `tesseract-ocr-eng`) :
|
||||
@@ -65,7 +64,27 @@ PaddleOCR : l'image Docker embarque déjà les deux moteurs (`pip install ".[ocr
|
||||
(`ConvertPirAttribute2RuntimeAttribute ... ArrayAttribute<DoubleAttribute>`, Paddle#79749) —
|
||||
vérifié localement : 3.3.1 crashe, 3.2.2 fonctionne.
|
||||
|
||||
Commandes manuelles : `scalper ocr <chapter_dir> [--mock-ocr]` et `scalper typeset <chapter_dir> --lang fr`.
|
||||
Commandes manuelles : `scalper ocr <chapter_dir> [--mock-ocr]` et `scalper typeset <chapter_dir> --lang fr [--inpaint-engine lama]`.
|
||||
|
||||
**Moteurs d'inpainting** (protocol `Inpainter` dans `src/scalper/inpaint.py`, sélection par
|
||||
`SCALPER_INPAINT_ENGINE` ou `--inpaint-engine`, et `"inpaint_engine"` dans `POST /run`) :
|
||||
|
||||
| Moteur | Gratuit | Local | Qualité suppression texte | Install |
|
||||
|---|---|---|---|---|
|
||||
| `simple` | oui | oui | basique (remplissage par la couleur de fond estimée sur l'anneau autour de la boîte) | inclus (`[ocr]`) |
|
||||
| `lama` | oui | oui | **bien meilleure** : big-lama [advimman/lama](https://github.com/advimman/lama) (Apache-2.0), inférence ONNX CPU | `.[inpaint-lama]` (dans l'image Docker) |
|
||||
| `auto` (défaut) | — | — | `lama` si onnxruntime est installé, sinon `simple` | — |
|
||||
|
||||
LaMa : le graphe ONNX (`lama_fp32.onnx`, 208 Mo, port [Carve/LaMa-ONNX](https://huggingface.co/Carve/LaMa-ONNX)
|
||||
du modèle big-lama, entrée fixe 512×512) est téléchargé **une seule fois** au premier run, sha256
|
||||
vérifié, dans `SCALPER_LAMA_CACHE` (défaut `~/.cache/scalper/lama` ; `/app/data/.lama` dans le
|
||||
conteneur via `entrypoint.sh`, donc dans le volume monté). `SCALPER_LAMA_MODEL` permet de pointer
|
||||
directement vers un fichier `.onnx` local. Pour chaque région de texte, Scalper découpe un crop
|
||||
carré avec contexte autour de la boîte, le redimensionne en 512×512, construit le masque (polygone
|
||||
OCR `poly` si présent, sinon rectangle dilaté de 10 %), infère, puis ne recolle que les pixels
|
||||
masqués à la résolution d'origine : le reste de la page est **inchangé**. Comptez ~2 s par région
|
||||
en CPU (une page de 20 bulles ≈ 45 s). La réinsertion du texte traduit reste faite par Pillow
|
||||
(retypographie centrée dans la boîte d'origine).
|
||||
|
||||
## Serveur & authentification (`scalper serve`)
|
||||
|
||||
@@ -76,10 +95,12 @@ est invalidé. Ensuite, `POST /login` `{"username": ..., "password": ...}` renvo
|
||||
`/login`, `/setup`). Le compte est stocké dans `SCALPER_AUTH_FILE` (défaut `data/auth.json`, monté par
|
||||
docker-compose), mot de passe haché (PBKDF2). En conteneur (`--host 0.0.0.0`), le lien est
|
||||
affiché avec `<hote-du-serveur>` à remplacer par l'IP/hôte réel. Le cache PaddleX (modèles OCR,
|
||||
temp) est redirigé vers `/app/data/.paddlex` via `PADDLE_PDX_CACHE_HOME` dans `entrypoint.sh` :
|
||||
temp) est redirigé vers `/app/data/.paddlex` via `PADDLE_PDX_CACHE_HOME` dans `entrypoint.sh`,
|
||||
et celui du modèle LaMa vers `/app/data/.lama` via `SCALPER_LAMA_CACHE` :
|
||||
les modèles ne sont téléchargés qu'une fois, dans le volume monté.
|
||||
|
||||
`POST /run` accepte en plus `"src_lang": "ja"` (langue d'entrée du chapitre).
|
||||
`POST /run` accepte en plus `"src_lang": "ja"` (langue d'entrée du chapitre) et
|
||||
`"inpaint_engine": "lama"` (moteur d'inpainting : `simple` | `lama` | `auto`).
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ services:
|
||||
- MISTRAL_API_KEY=mstrl_gC0ggPOzDrlmPm9de9Co1st51TfIGScv_2eu6XV
|
||||
- MISTRAL_MODEL=mistral-small-latest
|
||||
- SCALPER_OCR_ENGINE=paddle
|
||||
- SCALPER_INPAINT_ENGINE=lama
|
||||
volumes:
|
||||
- /DATA/AppData/scalper/data:/app/data
|
||||
- /DATA/AppData/scalper/out:/app/out
|
||||
|
||||
@@ -9,4 +9,6 @@ export HOME=/home/scalper
|
||||
# Cache PaddleX (modèles OCR + temp) dans le volume monté /app/data :
|
||||
# les modèles ne sont téléchargés qu'une seule fois, même après recréation du conteneur.
|
||||
export PADDLE_PDX_CACHE_HOME=/app/data/.paddlex
|
||||
# Idem pour le modèle LaMa d'inpainting (big-lama ONNX, ~208 Mo, téléchargé au premier run).
|
||||
export SCALPER_LAMA_CACHE=/app/data/.lama
|
||||
exec setpriv --reuid scalper --regid scalper --init-groups "$@"
|
||||
@@ -16,6 +16,7 @@ dev = ["pytest>=8"]
|
||||
agents = ["mistralai-agents>=1.1"]
|
||||
ocr = ["pillow>=10.1", "pytesseract>=0.3.10"]
|
||||
ocr-paddle = ["paddlepaddle>=3.0,<3.3", "paddleocr>=3.0"] # paddlepaddle 3.3.x: bug oneDNN ConvertPirAttribute2RuntimeAttribute (Paddle#79749) -> pin <3.3
|
||||
inpaint-lama = ["onnxruntime>=1.17", "numpy>=1.24"] # inpainting LaMa (big-lama ONNX, github.com/advimman/lama) pour la suppression du texte
|
||||
|
||||
[project.scripts]
|
||||
scalper = "scalper.cli:main"
|
||||
|
||||
+12
-2
@@ -85,6 +85,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
c = sub.add_parser("typeset", help="remplace le texte des images par la traduction")
|
||||
c.add_argument("chapter_dir")
|
||||
c.add_argument("--lang", required=True)
|
||||
c.add_argument("--inpaint-engine", choices=["simple", "lama", "auto"], default=None,
|
||||
help="moteur d'inpainting pour la suppression du texte (défaut: SCALPER_INPAINT_ENGINE ou auto)")
|
||||
|
||||
c = sub.add_parser("serve", help="démarre le serveur HTTP (déploiement Docker/Coolify)")
|
||||
c.add_argument("--host", default="127.0.0.1")
|
||||
@@ -102,6 +104,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
help="OCR + remplacement du texte dans les images (auto si images présentes ; --no-ocr pour désactiver)")
|
||||
c.add_argument("--ocr-engine", choices=["tesseract", "paddle"], default=None,
|
||||
help="moteur OCR (défaut: SCALPER_OCR_ENGINE ou tesseract)")
|
||||
c.add_argument("--inpaint-engine", choices=["simple", "lama", "auto"], default=None,
|
||||
help="moteur d'inpainting pour la suppression du texte (défaut: SCALPER_INPAINT_ENGINE ou auto)")
|
||||
c.add_argument("--force", action="store_true", help="exporte même si la QA échoue (bypass vérification)")
|
||||
c.add_argument("--src-lang", default=None, help="langue d'entrée du chapitre (en, ja, fr…) : enregistrée dans meta.json et utilisée pour l'OCR")
|
||||
|
||||
@@ -198,9 +202,13 @@ def main(argv: list[str] | None = None) -> int:
|
||||
_print({"status": "ok", "regions": len(regions), "out": str(Path(args.chapter_dir) / "ocr.json")})
|
||||
return 0
|
||||
if args.cmd == "typeset":
|
||||
from .inpaint import default_inpainter
|
||||
from .typeset import typeset_chapter
|
||||
|
||||
outputs = typeset_chapter(Path(args.chapter_dir), args.lang)
|
||||
if args.inpaint_engine:
|
||||
os.environ["SCALPER_INPAINT_ENGINE"] = args.inpaint_engine
|
||||
outputs = typeset_chapter(Path(args.chapter_dir), args.lang,
|
||||
inpainter=default_inpainter(args.inpaint_engine))
|
||||
_print({"status": "ok", "images": outputs})
|
||||
return 0
|
||||
if args.cmd == "serve":
|
||||
@@ -211,11 +219,13 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if args.cmd == "run":
|
||||
if getattr(args, "ocr_engine", None):
|
||||
os.environ["SCALPER_OCR_ENGINE"] = args.ocr_engine
|
||||
if getattr(args, "inpaint_engine", None):
|
||||
os.environ["SCALPER_INPAINT_ENGINE"] = args.inpaint_engine
|
||||
summary = pipeline.run_pipeline(
|
||||
args.source, args.series, args.lang,
|
||||
out_root=Path(args.out), mock_llm=args.mock_llm,
|
||||
max_chapters=args.max_chapters, group=args.group, with_ocr=args.with_ocr,
|
||||
force=args.force, src_lang=args.src_lang,
|
||||
force=args.force, src_lang=args.src_lang, inpaint_engine=args.inpaint_engine,
|
||||
)
|
||||
_print(summary)
|
||||
return 0 if summary.get("status") == "done" else 3
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Inpainting des zones de texte avant retypographie (suppression « intelligente » du texte).
|
||||
|
||||
Deux moteurs (protocol `Inpainter`), sélection par `SCALPER_INPAINT_ENGINE` ou `--inpaint-engine` :
|
||||
|
||||
- `simple` : remplissage de la boîte (légèrement élargie) par la couleur de fond estimée sur
|
||||
l'anneau de pixels juste autour (hors texte) — l'ancien comportement du typeset ;
|
||||
- `lama` : big-lama (https://github.com/advimman/lama, licence Apache-2.0) en ONNX
|
||||
(port Carve/LaMa-ONNX, entrée fixe 512x512) via onnxruntime. Pour chaque région de texte,
|
||||
on découpe un crop carré avec contexte autour de la boîte, on le redimensionne en 512x512,
|
||||
on construit le masque (polygone OCR quand disponible, sinon rectangle dilaté), on infère,
|
||||
puis on ne recolle que les pixels masqués à la résolution d'origine : le reste de la page
|
||||
est inchangé. Le modèle (208 Mo) est téléchargé une seule fois, sha256 vérifié, dans
|
||||
`SCALPER_LAMA_CACHE` (défaut `~/.cache/scalper/lama` ; `/app/data/.lama` dans le conteneur).
|
||||
`SCALPER_LAMA_MODEL` permet de pointer directement vers un fichier .onnx local.
|
||||
- `auto` (défaut) : `lama` si onnxruntime est installé, sinon `simple`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
# big-lama en ONNX (port Carve/LaMa-ONNX de advimman/lama), révision épinglée, sha256 vérifié.
|
||||
LAMA_MODEL_URL = (
|
||||
"https://huggingface.co/gumka/lama-onnx/resolve/"
|
||||
"d979e5c755d09d8b146fc977c78ec3ea9cdc72ed/lama_fp32.onnx"
|
||||
)
|
||||
LAMA_MODEL_SHA256 = "1faef5301d78db7dda502fe59966957ec4b79dd64e16f03ed96913c7a4eb68d6"
|
||||
LAMA_MODEL_SIZE = 208_044_816
|
||||
LAMA_MODEL_NAME = "lama_fp32.onnx"
|
||||
LAMA_INPUT_SIZE = 512 # entrée fixe du graphe ONNX exporté
|
||||
LAMA_MIN_CONTEXT = 256 # fenêtre de contexte minimale (px) autour d'une petite boîte de texte
|
||||
|
||||
|
||||
class Inpainter(Protocol):
|
||||
def inpaint_image(self, img, regions: list[dict[str, Any]]):
|
||||
"""Renvoie `img` (PIL, RGB) avec les zones de texte des `regions` remplies.
|
||||
|
||||
`regions` : dicts OCR avec au moins `box` = [x, y, w, h] et optionnellement
|
||||
`poly` = [[x, y], ...] (quadrilatère PaddleOCR, masque plus fidèle que la boîte).
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
def _box_of(region: dict[str, Any]) -> tuple[int, int, int, int] | None:
|
||||
box = region.get("box")
|
||||
if not box or len(box) != 4:
|
||||
return None
|
||||
try:
|
||||
x, y, w, h = (int(v) for v in box)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if w <= 0 or h <= 0:
|
||||
return None
|
||||
return x, y, w, h
|
||||
|
||||
|
||||
def _ring_fill_color(img, x0: int, y0: int, x1: int, y1: int) -> tuple[int, int, int]:
|
||||
"""Couleur de fond estimée sur l'anneau de pixels juste autour du rectangle
|
||||
(x0, y0, x1, y1) — donc hors du texte. Repli : moyenne du rectangle si l'anneau
|
||||
est vide (bord d'image)."""
|
||||
w2, h2 = x1 - x0, y1 - y0
|
||||
if w2 <= 0 or h2 <= 0:
|
||||
return (255, 255, 255)
|
||||
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:
|
||||
px = ring.load()
|
||||
samples = []
|
||||
step = max(1, (rw + rh) // 400)
|
||||
for i in range(0, rw, step):
|
||||
samples.append(px[i, 0])
|
||||
samples.append(px[i, rh - 1])
|
||||
for j in range(0, rh, step):
|
||||
samples.append(px[0, j])
|
||||
samples.append(px[rw - 1, j])
|
||||
n = len(samples)
|
||||
return (
|
||||
sum(p[0] for p in samples) // n,
|
||||
sum(p[1] for p in samples) // n,
|
||||
sum(p[2] for p in samples) // n,
|
||||
)
|
||||
return img.crop((x0, y0, x1, y1)).resize((1, 1)).getpixel((0, 0))[:3]
|
||||
|
||||
|
||||
def estimate_bg_color(img, box: list[int]) -> tuple[int, int, int]:
|
||||
"""Couleur de fond estimée autour de la boîte [x, y, w, h] (boîte élargie d'un pad,
|
||||
puis anneau) — utilisée pour choisir une couleur de texte contrastée."""
|
||||
x, y, w, h = box
|
||||
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)
|
||||
return _ring_fill_color(img, x0, y0, x1, y1)
|
||||
|
||||
|
||||
def _inpaint(img, box: list[int]) -> tuple[int, int, int]:
|
||||
"""Inpainting « simple » : 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."""
|
||||
from PIL import Image
|
||||
|
||||
x, y, w, h = box
|
||||
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)
|
||||
fill_rgb = _ring_fill_color(img, x0, y0, x1, y1)
|
||||
img.paste(Image.new("RGB", (w2, h2), fill_rgb), (x0, y0))
|
||||
return fill_rgb
|
||||
|
||||
|
||||
class SimpleInpainter:
|
||||
"""Moteur d'inpainting par défaut (léger, sans dépendance ML) : remplissage par la
|
||||
couleur de fond estimée sur l'anneau autour de chaque boîte."""
|
||||
|
||||
def inpaint_image(self, img, regions: list[dict[str, Any]]):
|
||||
for r in regions:
|
||||
box = _box_of(r)
|
||||
if box is not None:
|
||||
_inpaint(img, list(box))
|
||||
return img
|
||||
|
||||
|
||||
def _default_cache_dir() -> Path:
|
||||
env = os.environ.get("SCALPER_LAMA_CACHE")
|
||||
if env:
|
||||
return Path(env)
|
||||
return Path.home() / ".cache" / "scalper" / "lama"
|
||||
|
||||
|
||||
def _download_model(url: str, dest: Path) -> None:
|
||||
"""Télécharge le modèle ONNX (temp .part + renommage atomique) et vérifie
|
||||
taille + sha256 avant de le valider."""
|
||||
import urllib.request
|
||||
|
||||
part = dest.with_name(dest.name + ".part")
|
||||
print(f"[scalper][lama] téléchargement du modèle big-lama ONNX ({LAMA_MODEL_SIZE // (1 << 20)} Mo) : {url} -> {dest}", file=sys.stderr)
|
||||
with urllib.request.urlopen(url) as r, open(part, "wb") as f:
|
||||
shutil.copyfileobj(r, f, length=1 << 20)
|
||||
h = hashlib.sha256()
|
||||
with open(part, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
if part.stat().st_size != LAMA_MODEL_SIZE or h.hexdigest() != LAMA_MODEL_SHA256:
|
||||
part.unlink(missing_ok=True)
|
||||
raise RuntimeError("modèle LaMa téléchargé invalide (taille ou sha256 incorrect) — réessayez")
|
||||
os.replace(part, dest)
|
||||
|
||||
|
||||
class LamaInpainter:
|
||||
"""Inpainting par big-lama (advimman/lama) en ONNX via onnxruntime (CPU).
|
||||
|
||||
Le graphe exporté a une entrée fixe 512x512 : chaque région est donc traitée par un
|
||||
crop carré (boîte + contexte) redimensionné en 512x512 ; seuls les pixels masqués du
|
||||
crop sont recollés dans l'image à la résolution d'origine.
|
||||
"""
|
||||
|
||||
def __init__(self, model_path: str | Path | None = None, input_size: int = LAMA_INPUT_SIZE,
|
||||
min_context: int = LAMA_MIN_CONTEXT) -> None:
|
||||
self._model_path = Path(model_path) if model_path else None
|
||||
self._input_size = input_size
|
||||
self._min_context = min_context
|
||||
self._session = None
|
||||
|
||||
def _resolve_model_path(self) -> Path:
|
||||
for candidate in (self._model_path, Path(os.environ["SCALPER_LAMA_MODEL"]) if os.environ.get("SCALPER_LAMA_MODEL") else None):
|
||||
if candidate is not None:
|
||||
if not candidate.exists():
|
||||
raise RuntimeError(f"modèle LaMa introuvable : {candidate} (SCALPER_LAMA_MODEL)")
|
||||
return candidate
|
||||
cache = _default_cache_dir()
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
dest = cache / LAMA_MODEL_NAME
|
||||
if not dest.exists():
|
||||
_download_model(LAMA_MODEL_URL, dest)
|
||||
return dest
|
||||
|
||||
def _get_session(self):
|
||||
if self._session is None:
|
||||
try:
|
||||
import onnxruntime as ort
|
||||
except ImportError as e:
|
||||
raise RuntimeError(
|
||||
'onnxruntime non installé : pip install -e ".[inpaint-lama]" '
|
||||
"(ou SCALPER_INPAINT_ENGINE=simple pour rester sur le remplissage simple)"
|
||||
) from e
|
||||
model = self._resolve_model_path()
|
||||
self._session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
|
||||
return self._session
|
||||
|
||||
def _crop_rect(self, box: tuple[int, int, int, int], img_w: int, img_h: int) -> tuple[int, int, int, int]:
|
||||
"""Crop carré centré sur la boîte, avec contexte (côté >= 2x la boîte et >= min_context),
|
||||
borné à l'image."""
|
||||
x, y, w, h = box
|
||||
pad = max(2, int(min(w, h) * 0.1))
|
||||
side = max(2 * max(w + 2 * pad, h + 2 * pad), self._min_context)
|
||||
cx, cy = x + w / 2, y + h / 2
|
||||
cx0 = min(max(0, round(cx - side / 2)), max(0, img_w - side))
|
||||
cy0 = min(max(0, round(cy - side / 2)), max(0, img_h - side))
|
||||
cx1 = min(img_w, cx0 + side)
|
||||
cy1 = min(img_h, cy0 + side)
|
||||
cx0, cy0 = max(0, cx1 - side), max(0, cy1 - side)
|
||||
return cx0, cy0, max(cx0 + 1, cx1), max(cy0 + 1, cy1)
|
||||
|
||||
def _draw_region_mask(self, draw, region: dict[str, Any], box: tuple[int, int, int, int],
|
||||
cx0: int, cy0: int, sx: float, sy: float) -> None:
|
||||
"""Dessine le masque d'une région dans un ImageDraw : polygone OCR si disponible,
|
||||
sinon rectangle (boîte élargie d'un pad de 10 %)."""
|
||||
poly = region.get("poly")
|
||||
if poly and len(poly) >= 3:
|
||||
try:
|
||||
pts = [((float(px) - cx0) * sx, (float(py) - cy0) * sy) for px, py in poly]
|
||||
draw.polygon(pts, fill=255)
|
||||
return
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
x, y, w, h = box
|
||||
pad = max(2, int(min(w, h) * 0.1))
|
||||
draw.rectangle(
|
||||
[(x - pad - cx0) * sx, (y - pad - cy0) * sy, (x + w + pad - cx0) * sx, (y + h + pad - cy0) * sy],
|
||||
fill=255,
|
||||
)
|
||||
|
||||
def inpaint_image(self, img, regions: list[dict[str, Any]]):
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
sess = self._get_session()
|
||||
size = self._input_size
|
||||
arr = np.array(img.convert("RGB"))
|
||||
for r in regions:
|
||||
box = _box_of(r)
|
||||
if box is None:
|
||||
continue
|
||||
cx0, cy0, cx1, cy1 = self._crop_rect(box, img.width, img.height)
|
||||
cw, ch = cx1 - cx0, cy1 - cy0
|
||||
crop = img.crop((cx0, cy0, cx1, cy1)).resize((size, size), Image.LANCZOS)
|
||||
sx, sy = size / cw, size / ch
|
||||
mask512 = Image.new("L", (size, size), 0)
|
||||
self._draw_region_mask(ImageDraw.Draw(mask512), r, box, cx0, cy0, sx, sy)
|
||||
x_in = (np.asarray(crop, dtype=np.float32) / 255.0).transpose(2, 0, 1)[None]
|
||||
m_in = ((np.asarray(mask512, dtype=np.float32) / 255.0) > 0).astype(np.float32)[None, None]
|
||||
out = sess.run(["output"], {"image": x_in, "mask": m_in})[0][0] # [3, S, S], RGB 0..255
|
||||
pred = np.clip(out.transpose(1, 2, 0), 0, 255).astype(np.uint8)
|
||||
pred_crop = Image.fromarray(pred).resize((cw, ch), Image.LANCZOS)
|
||||
mask_crop = Image.new("L", (cw, ch), 0)
|
||||
self._draw_region_mask(ImageDraw.Draw(mask_crop), r, box, cx0, cy0, 1.0, 1.0)
|
||||
m = np.asarray(mask_crop) > 0
|
||||
sub = arr[cy0:cy1, cx0:cx1]
|
||||
sub[m] = np.asarray(pred_crop)[m]
|
||||
return Image.fromarray(arr)
|
||||
|
||||
|
||||
def default_inpainter(engine: str | None = None) -> Inpainter:
|
||||
"""Moteur d'inpainting par défaut : `engine`, sinon SCALPER_INPAINT_ENGINE, sinon
|
||||
`auto` (lama si onnxruntime est installé, simple sinon)."""
|
||||
engine = (engine or os.environ.get("SCALPER_INPAINT_ENGINE", "auto")).strip().lower()
|
||||
if engine == "simple":
|
||||
return SimpleInpainter()
|
||||
if engine == "lama":
|
||||
return LamaInpainter()
|
||||
if engine == "auto":
|
||||
try:
|
||||
import onnxruntime # noqa: F401
|
||||
|
||||
return LamaInpainter()
|
||||
except ImportError:
|
||||
return SimpleInpainter()
|
||||
raise ValueError(f"moteur d'inpainting inconnu : {engine!r} (simple|lama|auto)")
|
||||
@@ -116,6 +116,8 @@ class PaddleOCR:
|
||||
"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
|
||||
|
||||
@@ -30,6 +30,7 @@ def run_pipeline(
|
||||
force: bool = False,
|
||||
on_progress: Callable[[int, int, Any], None] | None = None,
|
||||
src_lang: str | None = None,
|
||||
inpaint_engine: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
out_root = Path(out_root)
|
||||
fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
|
||||
@@ -76,7 +77,7 @@ def run_pipeline(
|
||||
for fmt in ("md", "json", "html"):
|
||||
export_chapter(translated, fmt, dest / "export")
|
||||
if with_ocr:
|
||||
entry["ocr"] = _run_ocr_typeset(dest, meta, lang, client, glossary)
|
||||
entry["ocr"] = _run_ocr_typeset(dest, meta, lang, client, glossary, inpaint_engine=inpaint_engine)
|
||||
state.mark_done(ref.id)
|
||||
entry["status"] = "ok"
|
||||
if not report["pass"]:
|
||||
@@ -98,9 +99,12 @@ _TESSERACT_LANGS = {
|
||||
}
|
||||
|
||||
|
||||
def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMClient, glossary: dict[str, str]) -> str:
|
||||
def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMClient, glossary: dict[str, str],
|
||||
inpaint_engine: str | None = None) -> str:
|
||||
"""OCR des images du chapitre, traduction des textes détectés via le LLM, puis
|
||||
remplacement dans les images (inpainting + retypographie) -> export/images-<lang>/."""
|
||||
remplacement dans les images (inpainting + retypographie) -> export/images-<lang>/.
|
||||
`inpaint_engine` : moteur d'inpainting (simple|lama|auto, défaut SCALPER_INPAINT_ENGINE)."""
|
||||
from .inpaint import default_inpainter
|
||||
from .ocr import default_ocr_client, ocr_chapter
|
||||
from .typeset import typeset_chapter
|
||||
|
||||
@@ -120,7 +124,8 @@ def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMCli
|
||||
blocks=[Block(index=i, type="narration", text=r.get("text", "")) for i, r in enumerate(regions)],
|
||||
)
|
||||
translated = translate_chapter(ocr_chapter_src, lang, glossary, client)
|
||||
outs = typeset_chapter(dest, lang, translations=[b.text for b in translated.blocks])
|
||||
outs = typeset_chapter(dest, lang, translations=[b.text for b in translated.blocks],
|
||||
inpainter=default_inpainter(inpaint_engine))
|
||||
return f"ok ({len(outs)} images reconstituées, {len(regions)} textes remplacés)"
|
||||
except Exception as e:
|
||||
print(f"[scalper][ocr] {dest.name} ERREUR: {e}", file=sys.stderr)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Endpoints :
|
||||
- GET /healthz
|
||||
- GET / interface web (barre de progression + previews source/traduit)
|
||||
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"force"?,"out"?,"background"?}
|
||||
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"inpaint_engine"?,"force"?,"out"?,"background"?}
|
||||
avec "background": true -> 202 {"job": id} et le run tourne en thread
|
||||
- GET /jobs/<id> état du job {status, progress{done,total,current}, result, error}
|
||||
- GET /api/chapter?out=&source=&series=&chapter=&lang= données de preview (meta, blocs source/traduits, images)
|
||||
@@ -104,6 +104,7 @@ def _start_job(body: dict) -> str:
|
||||
with_ocr=bool(body.get("with_ocr", True)),
|
||||
force=bool(body.get("force", False)),
|
||||
src_lang=body.get("src_lang"),
|
||||
inpaint_engine=body.get("inpaint_engine"),
|
||||
on_progress=on_progress,
|
||||
)
|
||||
job["result"] = summary
|
||||
@@ -412,6 +413,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
with_ocr=bool(body.get("with_ocr", True)),
|
||||
force=bool(body.get("force", False)),
|
||||
src_lang=body.get("src_lang"),
|
||||
inpaint_engine=body.get("inpaint_engine"),
|
||||
)
|
||||
except KeyError as e:
|
||||
return self._json(400, {"error": f"champ requis manquant: {e}"})
|
||||
|
||||
+37
-51
@@ -1,5 +1,5 @@
|
||||
"""Remplacement du texte dans les images : inpainting de la bulle + retypographie
|
||||
de la traduction (Pillow uniquement).
|
||||
"""Remplacement du texte dans les images : inpainting de la bulle (voir inpaint.py :
|
||||
remplissage simple ou LaMa) + retypographie de la traduction (Pillow).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -40,48 +40,6 @@ def wrap_text(draw, text: str, font, max_width: int) -> list[str]:
|
||||
return lines or [""]
|
||||
|
||||
|
||||
def _inpaint(img, box: list[int]) -> tuple[int, int, int]:
|
||||
"""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
|
||||
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(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:
|
||||
px = ring.load()
|
||||
samples = []
|
||||
step = max(1, (rw + rh) // 400)
|
||||
for i in range(0, rw, step):
|
||||
samples.append(px[i, 0])
|
||||
samples.append(px[i, rh - 1])
|
||||
for j in range(0, rh, step):
|
||||
samples.append(px[0, j])
|
||||
samples.append(px[rw - 1, j])
|
||||
n = len(samples)
|
||||
fill_rgb = (
|
||||
sum(p[0] for p in samples) // n,
|
||||
sum(p[1] for p in samples) // n,
|
||||
sum(p[2] for p in samples) // n,
|
||||
)
|
||||
else:
|
||||
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
|
||||
|
||||
|
||||
def _text_colors(fill_rgb: tuple[int, int, int]) -> tuple[tuple[int, int, int], tuple[int, int, int]]:
|
||||
"""Couleur de texte + contour contrastées avec le fond (luminance)."""
|
||||
lum = 0.299 * fill_rgb[0] + 0.587 * fill_rgb[1] + 0.114 * fill_rgb[2]
|
||||
@@ -90,14 +48,29 @@ def _text_colors(fill_rgb: tuple[int, int, int]) -> tuple[tuple[int, int, int],
|
||||
return (255, 255, 255), (0, 0, 0)
|
||||
|
||||
|
||||
def replace_texts(image_path: Path, regions: list[dict[str, Any]], translations: list[str], out_path: Path) -> Path:
|
||||
"""Remplace le texte des `regions` (index → translations[index]) dans l'image."""
|
||||
def replace_texts(
|
||||
image_path: Path,
|
||||
regions: list[dict[str, Any]],
|
||||
translations: list[str],
|
||||
out_path: Path,
|
||||
inpainter=None,
|
||||
) -> Path:
|
||||
"""Remplace le texte des `regions` (index → translations[index]) dans l'image.
|
||||
|
||||
Phase 1 : `inpainter` (défaut `default_inpainter()`) efface le texte original de
|
||||
toutes les régions à traduire (remplissage simple ou inpainting LaMa) ; phase 2 :
|
||||
la traduction est redessinée par-dessus, centrée dans la boîte d'origine.
|
||||
"""
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from .inpaint import default_inpainter, estimate_bg_color
|
||||
|
||||
# Les pages manga peuvent être très grandes : on désactive la limite
|
||||
# anti-decompression-bomb de PIL (les images viennent de nos propres chapitres).
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
img = Image.open(image_path).convert("RGB")
|
||||
inpainter = inpainter or default_inpainter()
|
||||
todo: list[tuple[dict[str, Any], str]] = []
|
||||
for r in regions:
|
||||
i = r.get("index")
|
||||
if i is None or i >= len(translations):
|
||||
@@ -108,9 +81,14 @@ def replace_texts(image_path: Path, regions: list[dict[str, Any]], translations:
|
||||
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])
|
||||
todo.append((r, text))
|
||||
if todo:
|
||||
img = inpainter.inpaint_image(img, [r for r, _ in todo]).convert("RGB")
|
||||
draw = ImageDraw.Draw(img)
|
||||
for r, text in todo:
|
||||
x, y, w, h = r["box"]
|
||||
fill_rgb = estimate_bg_color(img, [x, y, w, h])
|
||||
text_fill, stroke_fill = _text_colors(fill_rgb)
|
||||
draw = ImageDraw.Draw(img)
|
||||
# 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)
|
||||
@@ -136,12 +114,20 @@ def replace_texts(image_path: Path, regions: list[dict[str, Any]], translations:
|
||||
return out_path
|
||||
|
||||
|
||||
def typeset_chapter(chapter_dir: Path, lang: str, ocr_file: str = "ocr.json", translations: list[str] | None = None) -> list[str]:
|
||||
def typeset_chapter(
|
||||
chapter_dir: Path,
|
||||
lang: str,
|
||||
ocr_file: str = "ocr.json",
|
||||
translations: list[str] | None = None,
|
||||
inpainter=None,
|
||||
) -> list[str]:
|
||||
"""Recrée les images avec le texte traduit → `export/images-<lang>/`.
|
||||
|
||||
Si `translations` est fourni (une traduction par région OCR, dans l'ordre), il est
|
||||
utilisé directement ; sinon les blocs texte de `chapter.<lang>.json` servent de
|
||||
traductions (indexés par ordre des régions)."""
|
||||
traductions (indexés par ordre des régions). `inpainter` (défaut
|
||||
`default_inpainter()`) gère la suppression du texte original avant retypographie.
|
||||
"""
|
||||
ocr = json.loads((chapter_dir / ocr_file).read_text(encoding="utf-8"))
|
||||
if translations is None:
|
||||
from .models import Chapter
|
||||
@@ -159,7 +145,7 @@ def typeset_chapter(chapter_dir: Path, lang: str, ocr_file: str = "ocr.json", tr
|
||||
for name, regions in sorted(by_image.items()):
|
||||
src = images_dir / name
|
||||
if src.exists():
|
||||
outputs.append(str(replace_texts(src, regions, translations, out_dir / name)))
|
||||
outputs.append(str(replace_texts(src, regions, translations, out_dir / name, inpainter=inpainter)))
|
||||
# pages sans texte détecté : copiées telles quelles pour un export complet
|
||||
for p in sorted(images_dir.iterdir()):
|
||||
if p.is_file() and p.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp") and p.name not in by_image:
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from scalper.inpaint import (
|
||||
LAMA_INPUT_SIZE,
|
||||
LamaInpainter,
|
||||
SimpleInpainter,
|
||||
_download_model,
|
||||
default_inpainter,
|
||||
)
|
||||
|
||||
try:
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
HAS_PIL = True
|
||||
except ImportError:
|
||||
HAS_PIL = False
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
|
||||
HAS_NUMPY = True
|
||||
except ImportError:
|
||||
HAS_NUMPY = False
|
||||
|
||||
|
||||
class TestEngineSelection(unittest.TestCase):
|
||||
def test_simple_via_env(self):
|
||||
with mock.patch.dict(os.environ, {"SCALPER_INPAINT_ENGINE": "simple"}):
|
||||
self.assertIsInstance(default_inpainter(), SimpleInpainter)
|
||||
|
||||
def test_lama_via_env(self):
|
||||
with mock.patch.dict(os.environ, {"SCALPER_INPAINT_ENGINE": "lama"}):
|
||||
self.assertIsInstance(default_inpainter(), LamaInpainter)
|
||||
|
||||
def test_explicit_engine_wins_over_env(self):
|
||||
with mock.patch.dict(os.environ, {"SCALPER_INPAINT_ENGINE": "lama"}):
|
||||
self.assertIsInstance(default_inpainter("simple"), SimpleInpainter)
|
||||
|
||||
def test_auto_falls_back_to_simple_without_onnxruntime(self):
|
||||
with mock.patch.dict(os.environ, {}, clear=True):
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": None}):
|
||||
self.assertIsInstance(default_inpainter(), SimpleInpainter)
|
||||
|
||||
def test_auto_picks_lama_when_onnxruntime_available(self):
|
||||
fake_mod = types.ModuleType("onnxruntime")
|
||||
with mock.patch.dict(os.environ, {}, clear=True):
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": fake_mod}):
|
||||
self.assertIsInstance(default_inpainter(), LamaInpainter)
|
||||
|
||||
def test_unknown_engine_raises(self):
|
||||
with self.assertRaises(ValueError):
|
||||
default_inpainter("bogus")
|
||||
|
||||
|
||||
class TestModelResolution(unittest.TestCase):
|
||||
def test_explicit_model_path_must_exist(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with self.assertRaises(RuntimeError) as cm:
|
||||
LamaInpainter(model_path=Path(tmp) / "nope.onnx")._resolve_model_path()
|
||||
self.assertIn("SCALPER_LAMA_MODEL", str(cm.exception))
|
||||
|
||||
def test_env_model_path(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
model.write_bytes(b"fake")
|
||||
with mock.patch.dict(os.environ, {"SCALPER_LAMA_MODEL": str(model)}):
|
||||
self.assertEqual(LamaInpainter()._resolve_model_path(), model)
|
||||
|
||||
def test_cache_hit_does_not_download(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
cache = Path(tmp) / "cache"
|
||||
cache.mkdir()
|
||||
(cache / "lama_fp32.onnx").write_bytes(b"fake")
|
||||
with mock.patch.dict(os.environ, {"SCALPER_LAMA_CACHE": str(cache)}):
|
||||
with mock.patch("scalper.inpaint._download_model", side_effect=AssertionError("ne doit pas télécharger")):
|
||||
self.assertEqual(LamaInpainter()._resolve_model_path(), cache / "lama_fp32.onnx")
|
||||
|
||||
def test_cache_miss_downloads_once(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
cache = Path(tmp) / "cache"
|
||||
with mock.patch.dict(os.environ, {"SCALPER_LAMA_CACHE": str(cache)}):
|
||||
with mock.patch("scalper.inpaint._download_model") as dl:
|
||||
def fake_download(url, dest):
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_bytes(b"fake")
|
||||
dl.side_effect = fake_download
|
||||
p1 = LamaInpainter()._resolve_model_path()
|
||||
p2 = LamaInpainter()._resolve_model_path()
|
||||
self.assertEqual(p1, cache / "lama_fp32.onnx")
|
||||
self.assertEqual(dl.call_count, 1, "un second appel doit réutiliser le cache")
|
||||
self.assertEqual(p2, p1)
|
||||
|
||||
|
||||
class _FakeResp:
|
||||
def __init__(self, data: bytes):
|
||||
self._io = io.BytesIO(data)
|
||||
|
||||
def __enter__(self):
|
||||
return self._io
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
|
||||
class TestDownloadModel(unittest.TestCase):
|
||||
def test_download_verifies_sha256_and_renames(self):
|
||||
payload = b"x" * 1000
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
dest = Path(tmp) / "lama_fp32.onnx"
|
||||
with mock.patch("urllib.request.urlopen", return_value=_FakeResp(payload)):
|
||||
with mock.patch("scalper.inpaint.LAMA_MODEL_SIZE", 1000), \
|
||||
mock.patch("scalper.inpaint.LAMA_MODEL_SHA256", hashlib.sha256(payload).hexdigest()):
|
||||
_download_model("https://example.invalid/model.onnx", dest)
|
||||
self.assertEqual(dest.read_bytes(), payload)
|
||||
self.assertFalse((Path(tmp) / "lama_fp32.onnx.part").exists(), "le .part doit être renommé")
|
||||
|
||||
def test_download_bad_sha256_raises_and_cleans_up(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
dest = Path(tmp) / "lama_fp32.onnx"
|
||||
with mock.patch("urllib.request.urlopen", return_value=_FakeResp(b"y" * 1000)):
|
||||
with mock.patch("scalper.inpaint.LAMA_MODEL_SIZE", 1000), \
|
||||
mock.patch("scalper.inpaint.LAMA_MODEL_SHA256", "0" * 64):
|
||||
with self.assertRaises(RuntimeError):
|
||||
_download_model("https://example.invalid/model.onnx", dest)
|
||||
self.assertFalse(dest.exists())
|
||||
self.assertFalse((Path(tmp) / "lama_fp32.onnx.part").exists())
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL, "Pillow requis")
|
||||
class TestSimpleInpainter(unittest.TestCase):
|
||||
def _img(self, size=(300, 120), bg=(200, 220, 255)) -> Image.Image:
|
||||
img = Image.new("RGB", size, bg)
|
||||
ImageDraw.Draw(img).text((20, 20), "Texte noir sur fond clair", fill=(0, 0, 0))
|
||||
return img
|
||||
|
||||
def test_ring_fill_not_text_average(self):
|
||||
from scalper.inpaint import _inpaint
|
||||
|
||||
img = self._img()
|
||||
fill = _inpaint(img, [10, 10, 280, 60])
|
||||
# la couleur estimée doit rester proche du fond (200,220,255), pas assombrie par le texte
|
||||
self.assertGreater(fill[0], 150)
|
||||
self.assertGreater(fill[1], 170)
|
||||
self.assertGreater(fill[2], 200)
|
||||
self.assertGreater(img.getpixel((150, 35))[0], 150)
|
||||
|
||||
def test_inpaint_image_fills_each_box(self):
|
||||
img = self._img()
|
||||
out = SimpleInpainter().inpaint_image(img, [
|
||||
{"box": [10, 10, 280, 60]},
|
||||
{"box": [0, 0, 0, 0]}, # invalide -> ignorée
|
||||
{"box": [200, 80, 50, 20]},
|
||||
])
|
||||
self.assertIs(out, img)
|
||||
self.assertGreater(img.getpixel((150, 35))[0], 150)
|
||||
self.assertGreater(img.getpixel((220, 90))[0], 150)
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL, "Pillow requis")
|
||||
class TestCropAndMask(unittest.TestCase):
|
||||
def test_crop_rect_centered_with_context_and_clamped(self):
|
||||
inp = LamaInpainter()
|
||||
cx0, cy0, cx1, cy1 = inp._crop_rect((100, 100, 50, 30), 1000, 800)
|
||||
self.assertEqual(cx1 - cx0, cy1 - cy0) # carré
|
||||
self.assertGreaterEqual(cx1 - cx0, 256) # contexte min
|
||||
self.assertLessEqual(cx0, 100)
|
||||
self.assertGreaterEqual(cx1, 150)
|
||||
# boîte collée au bord : crop borné à l'image
|
||||
cx0, cy0, cx1, cy1 = inp._crop_rect((0, 0, 40, 40), 300, 300)
|
||||
self.assertEqual((cx0, cy0), (0, 0))
|
||||
self.assertLessEqual(cx1, 300)
|
||||
self.assertLessEqual(cy1, 300)
|
||||
|
||||
def test_draw_region_mask_rect_and_poly(self):
|
||||
inp = LamaInpainter()
|
||||
size = LAMA_INPUT_SIZE
|
||||
mask = Image.new("L", (size, size), 0)
|
||||
d = ImageDraw.Draw(mask)
|
||||
inp._draw_region_mask(d, {"box": [100, 100, 50, 30]}, (100, 100, 50, 30), 0, 0, 1.0, 1.0)
|
||||
self.assertEqual(mask.getpixel((125, 115)), 255)
|
||||
self.assertEqual(mask.getpixel((10, 10)), 0)
|
||||
# avec poly : seul le polygone est masqué
|
||||
mask2 = Image.new("L", (size, size), 0)
|
||||
d2 = ImageDraw.Draw(mask2)
|
||||
poly = [[100, 100], [200, 100], [200, 200], [100, 200]]
|
||||
inp._draw_region_mask(d2, {"box": [100, 100, 100, 100], "poly": poly}, (100, 100, 100, 100), 0, 0, 1.0, 1.0)
|
||||
self.assertEqual(mask2.getpixel((150, 150)), 255)
|
||||
self.assertEqual(mask2.getpixel((90, 90)), 0)
|
||||
|
||||
|
||||
def _fake_onnxruntime_module(fill_value=200.0):
|
||||
"""Module onnxruntime factice : session qui renvoie `fill_value` dans le masque et
|
||||
recopopie l'entrée (x255) hors masque, comme le vrai modèle."""
|
||||
mod = types.ModuleType("onnxruntime")
|
||||
|
||||
class FakeSession:
|
||||
instances = []
|
||||
|
||||
def __init__(self, path, sess_options=None, providers=None):
|
||||
self.path = path
|
||||
self.providers = providers
|
||||
self.calls = []
|
||||
FakeSession.instances.append(self)
|
||||
|
||||
def run(self, output_names, feeds):
|
||||
assert output_names == ["output"]
|
||||
self.calls.append(feeds)
|
||||
image, mask = feeds["image"], feeds["mask"]
|
||||
out = image * 255.0 * (1.0 - mask) + fill_value * mask
|
||||
return [out]
|
||||
|
||||
class SessionOptions:
|
||||
pass
|
||||
|
||||
mod.InferenceSession = FakeSession
|
||||
mod.SessionOptions = SessionOptions
|
||||
return mod, FakeSession
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL and HAS_NUMPY, "Pillow + numpy requis")
|
||||
class TestLamaInpainter(unittest.TestCase):
|
||||
def _make_page(self, path: Path, size=(400, 300)) -> None:
|
||||
img = Image.new("RGB", size, (240, 240, 245))
|
||||
d = ImageDraw.Draw(img)
|
||||
d.rectangle([50, 40, 250, 110], fill=(255, 255, 255))
|
||||
d.text((70, 60), "Texte original", fill=(0, 0, 0))
|
||||
img.save(path)
|
||||
|
||||
def test_missing_onnxruntime_raises_clear_error(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
model.write_bytes(b"fake")
|
||||
inp = LamaInpainter(model_path=model)
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": None}):
|
||||
with self.assertRaises(RuntimeError) as cm:
|
||||
inp._get_session()
|
||||
self.assertIn("inpaint-lama", str(cm.exception))
|
||||
|
||||
def test_inpaint_image_composites_only_masked_pixels(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
model.write_bytes(b"fake")
|
||||
src = Path(tmp) / "p.png"
|
||||
self._make_page(src)
|
||||
fake_mod, fake_session_cls = _fake_onnxruntime_module(fill_value=200.0)
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": fake_mod}):
|
||||
inp = LamaInpainter(model_path=model)
|
||||
img = Image.open(src).convert("RGB")
|
||||
regions = [{"index": 0, "box": [60, 50, 180, 50], "text": "Texte original"}]
|
||||
out = inp.inpaint_image(img, regions)
|
||||
sess = fake_session_cls.instances[-1]
|
||||
self.assertEqual(len(sess.calls), 1)
|
||||
feeds = sess.calls[0]
|
||||
self.assertEqual(feeds["image"].shape, (1, 3, LAMA_INPUT_SIZE, LAMA_INPUT_SIZE))
|
||||
self.assertEqual(feeds["mask"].shape, (1, 1, LAMA_INPUT_SIZE, LAMA_INPUT_SIZE))
|
||||
self.assertLessEqual(float(feeds["image"].max()), 1.0, "image normalisée en [0,1]")
|
||||
self.assertTrue(set(np.unique(feeds["mask"]).tolist()) <= {0.0, 1.0}, "masque binaire")
|
||||
out_arr = np.asarray(out)
|
||||
# zone masquée remplie par la valeur factice
|
||||
self.assertTrue(np.all(out_arr[60:90, 100:200] == 200), "pixels masqués remplacés")
|
||||
# hors masque : image d'origine inchangée
|
||||
self.assertEqual(tuple(out_arr[250, 350]), (240, 240, 245))
|
||||
self.assertEqual(tuple(out_arr[10, 10]), (240, 240, 245))
|
||||
|
||||
def test_inpaint_image_uses_poly_when_present(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
model.write_bytes(b"fake")
|
||||
src = Path(tmp) / "p.png"
|
||||
self._make_page(src)
|
||||
fake_mod, fake_session_cls = _fake_onnxruntime_module(fill_value=200.0)
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": fake_mod}):
|
||||
inp = LamaInpainter(model_path=model)
|
||||
img = Image.open(src).convert("RGB")
|
||||
poly = [[60, 50], [240, 50], [240, 100], [60, 100]]
|
||||
regions = [{"index": 0, "box": [60, 50, 180, 50], "text": "x", "poly": poly}]
|
||||
inp.inpaint_image(img, regions)
|
||||
mask = fake_session_cls.instances[-1].calls[0]["mask"][0, 0]
|
||||
self.assertGreater(mask.sum(), 0)
|
||||
# le masque doit suivre le polygone : point intérieur masqué, extérieur non
|
||||
self.assertEqual(mask[128, 200], 1.0) # (x=200, y=128) dans le poly [60..240]x[50..100]
|
||||
self.assertEqual(mask[LAMA_INPUT_SIZE // 2, LAMA_INPUT_SIZE // 2], 0.0) # (256,256) hors poly
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL, "Pillow requis")
|
||||
class TestTypesetWithInpainter(unittest.TestCase):
|
||||
def _make_image(self, path: Path, size=(300, 120)) -> None:
|
||||
img = Image.new("RGB", size, (255, 255, 255))
|
||||
d = ImageDraw.Draw(img)
|
||||
d.rectangle([10, 10, 290, 70], fill=(200, 220, 255))
|
||||
d.text((20, 20), "Hello world", fill=(0, 0, 0))
|
||||
img.save(path)
|
||||
|
||||
def test_replace_texts_uses_inpainter_then_draws(self):
|
||||
from scalper.typeset import replace_texts
|
||||
|
||||
calls = []
|
||||
|
||||
class FakeInpainter:
|
||||
def inpaint_image(self, img, regions):
|
||||
calls.append([r["index"] for r in regions])
|
||||
d = ImageDraw.Draw(img)
|
||||
for r in regions:
|
||||
x, y, w, h = r["box"]
|
||||
d.rectangle([x, y, x + w, y + h], fill=(255, 255, 255))
|
||||
return img
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src, out = Path(tmp) / "p.png", Path(tmp) / "out.png"
|
||||
self._make_image(src)
|
||||
regions = [
|
||||
{"index": 0, "box": [10, 10, 280, 60], "text": "Hello world"},
|
||||
{"index": 1, "box": [5, 5, 4, 4], "text": "x"}, # trop petit -> ignoré
|
||||
]
|
||||
replace_texts(src, regions, ["Bonjour le monde", "y"], out, inpainter=FakeInpainter())
|
||||
self.assertEqual(calls, [[0]], "seules les régions valides sont inpaintées")
|
||||
res = Image.open(out).convert("RGB")
|
||||
dark = any(res.getpixel((px, py))[0] < 100 for px in range(10, 290) for py in range(10, 70))
|
||||
self.assertTrue(dark, "la traduction doit être redessinée dans la boîte")
|
||||
|
||||
def test_typeset_chapter_forwards_inpainter(self):
|
||||
from scalper.typeset import typeset_chapter
|
||||
|
||||
seen = []
|
||||
|
||||
class FakeInpainter:
|
||||
def inpaint_image(self, img, regions):
|
||||
seen.append(len(regions))
|
||||
return img
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp)
|
||||
(d / "images").mkdir()
|
||||
self._make_image(d / "images" / "p1.png")
|
||||
(d / "ocr.json").write_text(
|
||||
json.dumps({"lang": "eng", "regions": [{"index": 0, "image": "p1.png", "box": [10, 10, 280, 60], "text": "Hello world"}]}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
outputs = typeset_chapter(d, "fr", translations=["Bonjour le monde"], inpainter=FakeInpainter())
|
||||
self.assertEqual(len(outputs), 1)
|
||||
self.assertEqual(seen, [1])
|
||||
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists())
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL and HAS_NUMPY, "Pillow + numpy requis")
|
||||
class TestLamaRealModel(unittest.TestCase):
|
||||
"""Test réel (optionnel) : lance le vrai big-lama ONNX si SCALPER_TEST_LAMA_MODEL pointe dessus."""
|
||||
|
||||
def test_real_model_inpaints_text(self):
|
||||
model = os.environ.get("SCALPER_TEST_LAMA_MODEL")
|
||||
if not model or not Path(model).exists():
|
||||
self.skipTest("SCALPER_TEST_LAMA_MODEL non renseigné")
|
||||
from scalper.inpaint import LamaInpainter
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "p.png"
|
||||
img = Image.new("RGB", (512, 512), (235, 235, 240))
|
||||
d = ImageDraw.Draw(img)
|
||||
d.text((50, 50), "Texte a supprimer", fill=(0, 0, 0))
|
||||
img.save(src)
|
||||
inp = LamaInpainter(model_path=model)
|
||||
out = inp.inpaint_image(Image.open(src).convert("RGB"),
|
||||
[{"index": 0, "box": [40, 40, 300, 40], "text": "Texte a supprimer"}])
|
||||
arr = np.asarray(out)
|
||||
before = np.asarray(Image.open(src).convert("RGB"))
|
||||
zone = arr[40:80, 40:340]
|
||||
self.assertGreater(float(zone.mean()), 150.0, "le texte noir doit être remplacé par du fond clair")
|
||||
self.assertEqual(tuple(arr[400, 400]), tuple(before[400, 400]), "hors masque : inchangé")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,9 +8,10 @@ from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from scalper import pipeline
|
||||
from scalper.inpaint import _inpaint
|
||||
from scalper.ocr import FakeOCR, ocr_chapter
|
||||
from scalper.translator import FakeLLM
|
||||
from scalper.typeset import _inpaint, replace_texts, typeset_chapter, wrap_text
|
||||
from scalper.typeset import replace_texts, typeset_chapter, wrap_text
|
||||
|
||||
try:
|
||||
from PIL import Image, ImageDraw
|
||||
@@ -60,6 +61,8 @@ class TestPaddleOCRMapping(unittest.TestCase):
|
||||
self.assertEqual(regions[0]["box"], [100, 50, 30, 20]) # x, y, w, h
|
||||
self.assertEqual(regions[0]["text"], "Hello")
|
||||
self.assertEqual(regions[0]["index"], 0)
|
||||
# quadrilatère conservé pour le masque d'inpainting LaMa
|
||||
self.assertEqual(regions[0]["poly"], [[100, 50], [130, 50], [130, 70], [100, 70]])
|
||||
|
||||
def test_recognize_tolerates_array_like_fields(self):
|
||||
"""rec_boxes/dt_polys peuvent être des ndarray : `x or y` crashe (truth value ambigu)."""
|
||||
|
||||
Reference in new issue
Block a user