Flux images en 4 etapes explicites + refonte du front façon Aceternity UI

- typeset : flux en deux phases — 3/4 inpainting du texte original sur les
  images BRUTES -> export/images-clean/ (inpaint_image_file, toutes les
  regions valides effacees), puis 4/4 retypographie de la traduction sur
  l'image nettoyee -> export/images-<lang>/ ; replace_texts garde son
  comportement (inpainter=None -> default_inpainter()), sentinel _DRAW_ONLY
  pour la retypographie seule ; _fit_font (merge fc3211b) conservé : taille
  = plus grande police tenant dans la boîte OCR (hauteur de boîte)
- inpaint (LaMa) : dilatation du masque (MaxFilter, mask_dilate=2) pour une
  suppression complète du texte, style pinceau magique (bords des glyphes
  inclus) ; composite toujours limité aux pixels masqués
- pipeline : logs 1/4 OCR -> 2/4 traduction -> 3/4 inpainting -> 4/4
  retypographie ; inpainter résolu une fois et passé à typeset_chapter
- front : INDEX_HTML/SETUP_HTML entierement refondus façon Aceternity UI
  (fond sombre #030303, grille + aurora animée, logo dégradé animé, cartes
  à bord conique animé, toggles, selects ocr_engine/inpaint_engine, barre de
  progression dégradée) en vanilla CSS/JS sans build ni CDN ; ids et
  fonctions JS conservés, case zip export toujours cochee par défaut
- tests : dilatation du masque LaMa, images-clean + images-fr, _DRAW_ONLY,
  _fit_font (merge). Vérifié en reel (page 1 du out/, vrai modèle LaMa) :
  0 pixel modifié hors masques+1px de dilatation, texte effacé dans les
  bulles, traduction réinsérée. Suite : 90 passed, 1 skipped.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
Orionis committed 2026-11-18 23:18:02 +01:00
1 parent 1c843c223e
commit 5c2c102518
7 files changed
+309 -94

No files matched your search

+22 -10
View File
@@ -40,12 +40,20 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
## OCR & remplacement du texte dans les images (automatique) ## OCR & remplacement du texte dans les images (automatique)
Dans `scalper run` (et `POST /run`), l'OCR + typesetting s'exécute **automatiquement** dès qu'un 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`) : chapitre contient des images (désactivable avec `--no-ocr` / `"with_ocr": false`), en **4 étapes**
l'OCR extrait les régions texte des images (`ocr.json`, avec le quadrilatère `poly` quand le moteur (loguées `1/4`…`4/4`) :
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, 1. **OCR** : extraction du texte brut des bulles (`ocr.json`, avec le quadrilatère `poly` quand le
centrée, à la taille du texte d'origine (hauteur de la boîte OCR), avec une couleur contrastée moteur le fournit — PaddleOCR) ;
avec le fond (Pillow). Résultat : `export/images-<lang>/`. 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
masqués sont remplacés, le reste de la page est inchangé) → `export/images-clean/` ;
4. **retypographie** : la traduction est redessinée au même endroit, centrée dans la boîte
d'origine, **à la taille du texte d'origine** (plus grande police tenant dans la boîte OCR,
hauteur = hauteur de boîte), avec une couleur contrastée avec le fond (Pillow)
→ `export/images-<lang>/` (les images nettoyées avant retypographie sont aussi gardées dans
`export/images-clean/`).
La langue source de l'OCR est déduite de la langue détectée du chapitre (`en→eng`, `fr→fra`, 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`) : `ja→jpn`…). L'image Docker n'embarque que `eng` (`tesseract-ocr` inclut `tesseract-ocr-eng`) :
@@ -152,10 +160,14 @@ cp .env.example .env # MISTRAL_API_KEY (jamais committer)
docker compose up -d # API sur http://localhost:8000 + interface web sur http://localhost:8000/ docker compose up -d # API sur http://localhost:8000 + interface web sur http://localhost:8000/
``` ```
L'interface web (`GET /`) affiche une **barre de progression** pendant le run (via `POST /run` L'interface web (`GET /`) — refondue dans un style **Aceternity UI** (thème sombre, aurora/grid
avec `"background": true` + polling de `GET /jobs/<id>`), puis une **preview par chapitre** : animée, cartes à bord dégradé, toggles, barre de progression dégradée ; 100 % vanilla CSS/JS,
blocs du chapitre récupéré (source) et du chapitre traduit complet, avec les images servies sans build ni CDN, servie en un seul fichier par le serveur stdlib) — affiche une **barre de
via `GET /file` (et les images re-traduites `export/images-<lang>/` quand l'OCR/typeset a tourné). progression** pendant le run (via `POST /run` avec `"background": true` + polling de
`GET /jobs/<id>`), permet de choisir les moteurs (`ocr_engine`, `inpaint_engine`) et coche par
défaut le **zip export** ; puis une **preview par chapitre** : blocs du chapitre récupéré
(source) et du chapitre traduit complet, avec les images servies via `GET /file` (et les images
re-traduites `export/images-<lang>/` quand l'OCR/typeset a tourné).
Déploiement pas à pas sur Coolify : [docs/deploy-coolify.md](docs/deploy-coolify.md). Déploiement pas à pas sur Coolify : [docs/deploy-coolify.md](docs/deploy-coolify.md).
+10 -4
View File
@@ -166,10 +166,11 @@ class LamaInpainter:
""" """
def __init__(self, model_path: str | Path | None = None, input_size: int = LAMA_INPUT_SIZE, def __init__(self, model_path: str | Path | None = None, input_size: int = LAMA_INPUT_SIZE,
min_context: int = LAMA_MIN_CONTEXT) -> None: min_context: int = LAMA_MIN_CONTEXT, mask_dilate: int = 2) -> None:
self._model_path = Path(model_path) if model_path else None self._model_path = Path(model_path) if model_path else None
self._input_size = input_size self._input_size = input_size
self._min_context = min_context self._min_context = min_context
self._mask_dilate = mask_dilate # dilatation du masque (px) : suppression complète du texte
self._session = None self._session = None
def _resolve_model_path(self) -> Path: def _resolve_model_path(self) -> Path:
@@ -233,7 +234,7 @@ class LamaInpainter:
def inpaint_image(self, img, regions: list[dict[str, Any]]): def inpaint_image(self, img, regions: list[dict[str, Any]]):
import numpy as np import numpy as np
from PIL import Image, ImageDraw from PIL import Image, ImageDraw, ImageFilter
sess = self._get_session() sess = self._get_session()
size = self._input_size size = self._input_size
@@ -248,13 +249,18 @@ class LamaInpainter:
sx, sy = size / cw, size / ch sx, sy = size / cw, size / ch
mask512 = Image.new("L", (size, size), 0) mask512 = Image.new("L", (size, size), 0)
self._draw_region_mask(ImageDraw.Draw(mask512), r, box, cx0, cy0, sx, sy) self._draw_region_mask(ImageDraw.Draw(mask512), r, box, cx0, cy0, sx, sy)
mask_crop = Image.new("L", (cw, ch), 0)
self._draw_region_mask(ImageDraw.Draw(mask_crop), r, box, cx0, cy0, 1.0, 1.0)
if self._mask_dilate > 0:
# dilatation du masque (style « pinceau magique ») : on efface le texte
# ENTIÈREMENT, y compris les bords anti-crénelés des glyphes
mask512 = mask512.filter(ImageFilter.MaxFilter(2 * self._mask_dilate + 1))
mask_crop = mask_crop.filter(ImageFilter.MaxFilter(3))
x_in = (np.asarray(crop, dtype=np.float32) / 255.0).transpose(2, 0, 1)[None] 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] 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 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 = np.clip(out.transpose(1, 2, 0), 0, 255).astype(np.uint8)
pred_crop = Image.fromarray(pred).resize((cw, ch), Image.LANCZOS) 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 m = np.asarray(mask_crop) > 0
sub = arr[cy0:cy1, cx0:cx1] sub = arr[cy0:cy1, cx0:cx1]
sub[m] = np.asarray(pred_crop)[m] sub[m] = np.asarray(pred_crop)[m]
+9 -1
View File
@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import json import json
import os
import sys import sys
import time import time
from pathlib import Path from pathlib import Path
@@ -124,18 +125,25 @@ def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMCli
return msg return msg
try: try:
src_lang = _TESSERACT_LANGS.get(str(meta.get("language") or "en")[:2].lower(), "eng") src_lang = _TESSERACT_LANGS.get(str(meta.get("language") or "en")[:2].lower(), "eng")
ocr_engine_name = ocr_engine or os.environ.get("SCALPER_OCR_ENGINE", "tesseract")
inpainter = default_inpainter(inpaint_engine)
inpaint_name = type(inpainter).__name__
print(f"[scalper][ocr] {dest.name}: 1/4 OCR ({ocr_engine_name}) du texte brut des bulles...", file=sys.stderr)
regions = ocr_chapter(dest, default_ocr_client(src_lang, engine=ocr_engine), lang=src_lang) regions = ocr_chapter(dest, default_ocr_client(src_lang, engine=ocr_engine), lang=src_lang)
if not regions: if not regions:
msg = "skipped : aucun texte détecté dans les images" msg = "skipped : aucun texte détecté dans les images"
print(f"[scalper][ocr] {dest.name}: {msg}", file=sys.stderr) print(f"[scalper][ocr] {dest.name}: {msg}", file=sys.stderr)
return msg return msg
print(f"[scalper][ocr] {dest.name}: 2/4 traduction de {len(regions)} textes -> {lang}...", file=sys.stderr)
ocr_chapter_src = Chapter( ocr_chapter_src = Chapter(
meta={"language": src_lang}, meta={"language": src_lang},
blocks=[Block(index=i, type="narration", text=r.get("text", "")) for i, r in enumerate(regions)], 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) translated = translate_chapter(ocr_chapter_src, lang, glossary, client)
print(f"[scalper][ocr] {dest.name}: 3/4 inpainting ({inpaint_name}) du texte original sur les images brutes -> export/images-clean/", file=sys.stderr)
print(f"[scalper][ocr] {dest.name}: 4/4 retypographie des traductions (taille ajustée par bulle) -> export/images-{lang}/", file=sys.stderr)
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)) inpainter=inpainter)
return f"ok ({len(outs)} images reconstituées, {len(regions)} textes remplacés)" return f"ok ({len(outs)} images reconstituées, {len(regions)} textes remplacés)"
except Exception as e: except Exception as e:
print(f"[scalper][ocr] {dest.name} ERREUR: {e}", file=sys.stderr) print(f"[scalper][ocr] {dest.name} ERREUR: {e}", file=sys.stderr)
+115 -43
View File
@@ -131,48 +131,99 @@ INDEX_HTML = """<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> <html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Scalper</title> <title>Scalper</title>
<style> <style>
body{font-family:system-ui,sans-serif;max-width:60rem;margin:2rem auto;padding:0 1rem;color:#222} @property --a{syntax:'<angle>';initial-value:0deg;inherits:false}
input,button{padding:.45rem;margin:.2rem}input{width:100%;box-sizing:border-box} :root{--bg:#030303;--card:rgba(255,255,255,.04);--border:rgba(255,255,255,.1);--txt:#e4e4e7;--muted:#a1a1aa;--indigo:#6366f1;--fuchsia:#d946ef;--cyan:#22d3ee}
fieldset{border:1px solid #ccc;border-radius:8px;margin-bottom:1rem}legend{font-weight:600} *{box-sizing:border-box}
button{cursor:pointer;background:#222;color:#fff;border:0;border-radius:6px} html,body{margin:0;padding:0}
pre{background:#f4f4f4;padding:1rem;border-radius:8px;overflow:auto;white-space:pre-wrap} body{background:var(--bg);color:var(--txt);font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;min-height:100vh}
#progress-wrap{display:none;height:1.2rem;background:#e5e5e5;border-radius:6px;overflow:hidden;margin:.6rem 0} /* fond façon Aceternity : grille + aurora dégradée */
#bar{height:100%;width:0%;background:#2a7d4f;transition:width .3s} .bg-grid{position:fixed;inset:0;z-index:-2;background-image:linear-gradient(rgba(255,255,255,.045) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.045) 1px,transparent 1px);background-size:44px 44px;-webkit-mask-image:radial-gradient(ellipse 90% 65% at 50% 0%,#000 55%,transparent 100%);mask-image:radial-gradient(ellipse 90% 65% at 50% 0%,#000 55%,transparent 100%)}
#bar-label{font-size:.8rem;color:#555;margin-bottom:1rem} .bg-aurora{position:fixed;inset:0;z-index:-3;overflow:hidden;background:var(--bg)}
.chapter{border:1px solid #ddd;border-radius:8px;padding:1rem;margin:1rem 0} .bg-aurora::before,.bg-aurora::after{content:"";position:absolute;width:55vmax;height:55vmax;border-radius:50%;filter:blur(130px);opacity:.22;animation:drift 28s ease-in-out infinite alternate}
.cols{display:flex;gap:1rem;flex-wrap:wrap} .bg-aurora::before{background:radial-gradient(circle,#6366f1,transparent 62%);top:-22vmax;left:-12vmax}
.bg-aurora::after{background:radial-gradient(circle,#d946ef,transparent 62%);bottom:-26vmax;right:-14vmax;animation-delay:-14s}
@keyframes drift{from{transform:translate(0,0) scale(1)}to{transform:translate(7vmax,4vmax) scale(1.18)}}
.wrap{max-width:62rem;margin:0 auto;padding:2rem 1rem 4rem}
header.top{text-align:center;margin-bottom:2rem}
h1.logo{margin:0;font-size:2.4rem;font-weight:800;letter-spacing:-.03em;background:linear-gradient(90deg,#fff,#a5b4fc,#e879f9,#67e8f9,#fff);background-size:300% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shine 9s linear infinite}
@keyframes shine{to{background-position:300% 0}}
header.top p{margin:.4rem 0 0;color:var(--muted);font-size:.9rem}
/* carte + bord dégradé animé (style Aceternity moving-border) */
.gborder{border-radius:1.1rem;padding:1px;background:conic-gradient(from var(--a),#6366f1,#d946ef,#22d3ee,#6366f1);animation:spin 5s linear infinite;box-shadow:0 0 40px rgba(99,102,241,.15)}
@keyframes spin{to{--a:360deg}}
.card{border:1px solid var(--border);border-radius:1rem;background:var(--card);backdrop-filter:blur(10px);padding:1.2rem 1.4rem}
.gborder .card{border:0;background:rgba(10,10,10,.92);border-radius:1rem}
#login{display:none;max-width:24rem;margin:5rem auto 0}
#login h2{margin:.2rem 0 1rem;font-size:1.2rem}
#l-err{color:#f87171;font-size:.85rem;min-height:1.2em;margin-top:.5rem}
label.f{display:block;font-size:.78rem;color:var(--muted);margin:.6rem 0 .25rem}
input[type=text],input:not([type]),select{width:100%;padding:.55rem .75rem;border-radius:.6rem;border:1px solid var(--border);background:rgba(0,0,0,.55);color:var(--txt);font-size:.9rem;outline:none;transition:border-color .15s,box-shadow .15s}
input:focus,select:focus{border-color:var(--indigo);box-shadow:0 0 0 3px rgba(99,102,241,.25)}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:0 1rem}
@media(max-width:40rem){.grid2{grid-template-columns:1fr}}
.switch{display:inline-flex;align-items:center;gap:.55rem;cursor:pointer;font-size:.84rem;color:var(--muted);margin:.35rem 1.2rem .35rem 0;user-select:none}
.switch input{position:absolute;opacity:0;width:0;height:0}
.switch .track{flex:none;width:36px;height:20px;border-radius:999px;background:rgba(255,255,255,.12);border:1px solid var(--border);position:relative;transition:.2s}
.switch .track::after{content:"";position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:#fff;transition:.2s}
.switch input:checked + .track{background:linear-gradient(90deg,var(--indigo),var(--fuchsia));border-color:transparent;box-shadow:0 0 10px rgba(217,70,239,.5)}
.switch input:checked + .track::after{left:18px}
.btn{border:0;cursor:pointer;border-radius:.65rem;padding:.65rem 1.3rem;font-weight:700;font-size:.92rem;color:#fff;background:linear-gradient(90deg,var(--indigo),var(--fuchsia));box-shadow:0 0 26px rgba(99,102,241,.45);transition:transform .15s,box-shadow .2s;margin-top:1rem}
.btn:hover{transform:translateY(-1px);box-shadow:0 0 38px rgba(217,70,239,.55)}
.btn:active{transform:translateY(0)}
#progress-wrap{display:none;height:.85rem;border-radius:999px;background:rgba(255,255,255,.08);border:1px solid var(--border);overflow:hidden;margin:1rem 0 .35rem}
#bar{height:100%;width:0%;border-radius:999px;background:linear-gradient(90deg,var(--indigo),var(--fuchsia),var(--cyan));box-shadow:0 0 14px rgba(99,102,241,.9);transition:width .3s}
#bar-label{font-size:.8rem;color:var(--muted);margin-bottom:1rem;min-height:1.1em}
pre#out{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.78rem;line-height:1.45;background:rgba(0,0,0,.65);border:1px solid var(--border);border-radius:.9rem;padding:1rem;overflow:auto;white-space:pre-wrap;max-height:26rem;margin:0}
#previews{margin-top:1.4rem}
.chapter{border:1px solid var(--border);border-radius:1rem;background:var(--card);backdrop-filter:blur(8px);padding:1.1rem 1.2rem;margin:1rem 0;transition:border-color .2s}
.chapter:hover{border-color:rgba(255,255,255,.25)}
.chapter h3{margin:.1rem 0 .6rem;font-size:1.02rem}
.chapter .lang{color:var(--muted);font-size:.8rem;margin:.2rem 0}
.cols{display:flex;gap:1.1rem;flex-wrap:wrap}
.col{flex:1;min-width:16rem} .col{flex:1;min-width:16rem}
.col img{max-width:100%;display:block;margin:.3rem 0;border:1px solid #eee} .col h4{margin:.2rem 0 .5rem;font-size:.85rem;color:var(--muted);font-weight:600;text-transform:uppercase;letter-spacing:.06em}
blockquote{margin:.3rem 0;padding:.2rem .6rem;border-left:3px solid #888;color:#333} .col img{max-width:100%;display:block;margin:.35rem 0;border-radius:.6rem;border:1px solid var(--border)}
blockquote{margin:.3rem 0;padding:.25rem .7rem;border-left:3px solid var(--indigo);color:#d4d4d8;background:rgba(255,255,255,.03);border-radius:0 .4rem .4rem 0}
.col p{margin:.3rem 0;color:#d4d4d8}
</style> </style>
</head><body> </head><body>
<div id="login" style="display:none;max-width:22rem;margin:3rem auto;padding:1rem;border:1px solid #ccc;border-radius:8px"> <div class="bg-aurora"></div><div class="bg-grid"></div>
<div id="login"><div class="gborder"><div class="card">
<h2>Connexion</h2> <h2>Connexion</h2>
<input id="l-user" placeholder="identifiant"> <label class="f" for="l-user">identifiant</label>
<input id="l-pass" type="password" placeholder="mot de passe"> <input id="l-user" type="text" placeholder="identifiant" autocomplete="username">
<button onclick="doLogin()">Se connecter</button> <label class="f" for="l-pass">mot de passe</label>
<div id="l-err" style="color:#b00;margin-top:.5rem"></div> <input id="l-pass" type="password" placeholder="mot de passe" autocomplete="current-password">
<button class="btn" onclick="doLogin()">Se connecter</button>
<div id="l-err"></div>
</div></div></div>
<div id="app" class="wrap">
<header class="top"><h1 class="logo">Scalper</h1><p>Pipeline de scraping + traduction de chapitres manga/webtoon</p></header>
<div class="card">
<h3 style="margin:.1rem 0 .4rem">Lancer un pipeline <span style="color:var(--muted);font-weight:400;font-size:.8rem">scrape → clean → translate → QA → OCR/inpainting → export</span></h3>
<div class="grid2">
<div><label class="f" for="r-source">source (demo, mangadex)</label><input id="r-source" type="text" value="demo"></div>
<div><label class="f" for="r-series">id série</label><input id="r-series" type="text" value="demo-1"></div>
<div><label class="f" for="r-lang">langue cible (fr, en…)</label><input id="r-lang" type="text" value="fr"></div>
<div><label class="f" for="r-srclang">langue d'entrée du chapitre (en, ja, fr…)</label><input id="r-srclang" type="text" value=""></div>
<div><label class="f" for="r-group">groupe optionnel (mangadex uniquement)</label><input id="r-group" type="text"></div>
<div><label class="f" for="r-max">max chapitres (optionnel)</label><input id="r-max" type="text"></div>
<div><label class="f" for="r-ocrengine">moteur OCR</label><select id="r-ocrengine"><option value="">par défaut (env)</option><option value="paddle">paddle (PP-OCRv6)</option><option value="tesseract">tesseract</option></select></div>
<div><label class="f" for="r-inpaint">moteur d'inpainting</label><select id="r-inpaint"><option value="">par défaut (env)</option><option value="lama">lama (big-lama)</option><option value="simple">simple</option><option value="auto">auto</option></select></div>
</div>
<div style="margin-top:.6rem">
<label class="switch"><input type="checkbox" id="r-mock"><span class="track"></span>mock-llm (démo hors ligne)</label>
<label class="switch"><input type="checkbox" id="r-force"><span class="track"></span>forcer l'export même si la QA échoue</label>
<label class="switch"><input type="checkbox" id="r-ocr" checked><span class="track"></span>OCR + remplacement du texte dans les images</label>
<label class="switch"><input type="checkbox" id="r-zip" checked><span class="track"></span>zip export-&lt;date&gt;-&lt;heure&gt;-&lt;minutes&gt;.zip à la fin (images + PDF, le reste de out/ est supprimé)</label>
</div>
<button class="btn" onclick="runPipeline()">Lancer le pipeline</button>
</div> </div>
<div id="app">
<h1>Scalper</h1>
<p>Pipeline de scraping + traduction de chapitres.</p>
<fieldset><legend>Lancer un pipeline (scrape → clean → translate → QA → export)</legend>
<input id="r-source" placeholder="source (demo, mangadex)" value="demo">
<input id="r-series" placeholder="id série" value="demo-1">
<input id="r-lang" placeholder="langue cible (fr, en, ...)" value="fr">
<input id="r-srclang" placeholder="langue d'entrée du chapitre (en, ja, fr…)" value="">
<input id="r-group" placeholder="groupe optionnel (mangadex uniquement)">
<input id="r-max" placeholder="max chapitres (optionnel)">
<label><input type="checkbox" id="r-mock" style="width:auto"> mock-llm (démo hors ligne)</label>
<label><input type="checkbox" id="r-force" style="width:auto"> forcer l'export même si la QA échoue</label>
<label><input type="checkbox" id="r-ocr" checked style="width:auto"> OCR + remplacement du texte dans les images (auto)</label>
<label><input type="checkbox" id="r-zip" checked style="width:auto"> zip export-<date>-<heure>-<minutes>.zip à la fin (images + PDF, le reste de out/ est supprimé)</label><br>
<button onclick="runPipeline()">Lancer le pipeline</button>
</fieldset>
<div id="progress-wrap"><div id="bar"></div></div> <div id="progress-wrap"><div id="bar"></div></div>
<div id="bar-label"></div> <div id="bar-label"></div>
<pre id="out">résultats ici…</pre> <div class="card" style="margin-top:1rem"><pre id="out">résultats ici…</pre></div>
<div id="previews"></div> <div id="previews"></div>
</div>
<script> <script>
const enc = encodeURIComponent; const enc = encodeURIComponent;
let TOKEN = localStorage.getItem('scalper_token') || ''; let TOKEN = localStorage.getItem('scalper_token') || '';
@@ -183,8 +234,9 @@ async function doLogin(){ const r=await fetch('/login',{method:'POST',headers:{'
if(TOKEN) hideLogin(); else showLogin(); if(TOKEN) hideLogin(); else showLogin();
async function runPipeline(){ async function runPipeline(){
const g=document.getElementById('r-group').value, m=document.getElementById('r-max').value, sl=document.getElementById('r-srclang').value; const g=document.getElementById('r-group').value, m=document.getElementById('r-max').value, sl=document.getElementById('r-srclang').value;
const oe=document.getElementById('r-ocrengine').value, ie=document.getElementById('r-inpaint').value;
const body={source:document.getElementById('r-source').value, series:document.getElementById('r-series').value, lang:document.getElementById('r-lang').value, mock_llm:document.getElementById('r-mock').checked, force:document.getElementById('r-force').checked, with_ocr:document.getElementById('r-ocr').checked, zip_export:document.getElementById('r-zip').checked, background:true}; const body={source:document.getElementById('r-source').value, series:document.getElementById('r-series').value, lang:document.getElementById('r-lang').value, mock_llm:document.getElementById('r-mock').checked, force:document.getElementById('r-force').checked, with_ocr:document.getElementById('r-ocr').checked, zip_export:document.getElementById('r-zip').checked, background:true};
if(g) body.group=g; if(m) body.max_chapters=Number(m); if(sl) body.src_lang=sl; if(g) body.group=g; if(m) body.max_chapters=Number(m); if(sl) body.src_lang=sl; if(oe) body.ocr_engine=oe; if(ie) body.inpaint_engine=ie;
document.getElementById('out').textContent='en cours…'; document.getElementById('out').textContent='en cours…';
document.getElementById('previews').innerHTML=''; document.getElementById('previews').innerHTML='';
const r=await api('/run',{method:'POST',body:JSON.stringify(body)}); const r=await api('/run',{method:'POST',body:JSON.stringify(body)});
@@ -230,7 +282,7 @@ function blockEl(b,dir,out,imgSub){
function chapterPanel(data,out,lang){ function chapterPanel(data,out,lang){
const panel=document.createElement('div'); panel.className='chapter'; const panel=document.createElement('div'); panel.className='chapter';
const h=document.createElement('h3'); h.textContent='Chapitre '+((data.meta&&data.meta.number)||'')+' — '+(data.dir||''); panel.appendChild(h); const h=document.createElement('h3'); h.textContent='Chapitre '+((data.meta&&data.meta.number)||'')+' — '+(data.dir||''); panel.appendChild(h);
if(data.meta&&data.meta.language){ const lp=document.createElement('p'); lp.style.cssText='margin:.2rem 0;color:#555'; lp.textContent="Langue d'entrée : "+data.meta.language; panel.appendChild(lp); } if(data.meta&&data.meta.language){ const lp=document.createElement('p'); lp.className='lang'; lp.textContent="Langue d'entrée : "+data.meta.language; panel.appendChild(lp); }
const cols=document.createElement('div'); cols.className='cols'; const cols=document.createElement('div'); cols.className='cols';
const c1=document.createElement('div'); c1.className='col'; const c1=document.createElement('div'); c1.className='col';
const h1=document.createElement('h4'); h1.textContent='Récupéré (source)'; c1.appendChild(h1); const h1=document.createElement('h4'); h1.textContent='Récupéré (source)'; c1.appendChild(h1);
@@ -245,25 +297,45 @@ function chapterPanel(data,out,lang){
return panel; return panel;
} }
</script> </script>
</div>
</body></html> </body></html>
""" """
SETUP_HTML = """<!doctype html><html lang="fr"><head><meta charset="utf-8"><title>Scalper — premier démarrage</title> SETUP_HTML = """<!doctype html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Scalper — premier démarrage</title>
<style>body{font-family:system-ui,sans-serif;max-width:24rem;margin:3rem auto;padding:0 1rem;color:#222}input{padding:.45rem;margin:.2rem 0;width:100%;box-sizing:border-box}button{padding:.5rem 1rem;background:#222;color:#fff;border:0;border-radius:6px;cursor:pointer}#err{color:#b00;margin-top:.6rem}</style> <style>
</head><body><h1>Scalper — création du compte</h1> @property --a{syntax:'<angle>';initial-value:0deg;inherits:false}
:root{--bg:#030303;--border:rgba(255,255,255,.1);--txt:#e4e4e7;--muted:#a1a1aa;--indigo:#6366f1;--fuchsia:#d946ef}
*{box-sizing:border-box}
body{margin:0;min-height:100vh;background:var(--bg);color:var(--txt);font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;display:flex;align-items:center;justify-content:center}
.bg-grid{position:fixed;inset:0;z-index:-2;background-image:linear-gradient(rgba(255,255,255,.045) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.045) 1px,transparent 1px);background-size:44px 44px;-webkit-mask-image:radial-gradient(ellipse 90% 65% at 50% 0%,#000 55%,transparent 100%);mask-image:radial-gradient(ellipse 90% 65% at 50% 0%,#000 55%,transparent 100%)}
.bg-aurora{position:fixed;inset:0;z-index:-3;overflow:hidden;background:var(--bg)}
.bg-aurora::before{content:"";position:absolute;width:55vmax;height:55vmax;border-radius:50%;filter:blur(130px);opacity:.22;background:radial-gradient(circle,#6366f1,transparent 62%);top:-22vmax;left:-12vmax}
.gborder{max-width:24rem;width:calc(100% - 2rem);border-radius:1.1rem;padding:1px;background:conic-gradient(from var(--a),#6366f1,#d946ef,#22d3ee,#6366f1);animation:spin 5s linear infinite;box-shadow:0 0 40px rgba(99,102,241,.15)}
@keyframes spin{to{--a:360deg}}
.card{border-radius:1rem;background:rgba(10,10,10,.92);padding:1.4rem}
h1{margin:.1rem 0 .3rem;font-size:1.3rem;font-weight:800;background:linear-gradient(90deg,#fff,#a5b4fc,#e879f9);-webkit-background-clip:text;background-clip:text;color:transparent}
p{color:var(--muted);font-size:.85rem;margin:.2rem 0 1rem}
input{width:100%;padding:.55rem .75rem;margin:.35rem 0;border-radius:.6rem;border:1px solid var(--border);background:rgba(0,0,0,.55);color:var(--txt);font-size:.9rem;outline:none}
input:focus{border-color:var(--indigo);box-shadow:0 0 0 3px rgba(99,102,241,.25)}
button{width:100%;margin-top:.8rem;border:0;cursor:pointer;border-radius:.65rem;padding:.65rem;font-weight:700;color:#fff;background:linear-gradient(90deg,var(--indigo),var(--fuchsia));box-shadow:0 0 26px rgba(99,102,241,.45)}
#err{color:#f87171;font-size:.85rem;min-height:1.2em;margin-top:.5rem}
</style>
</head><body>
<div class="bg-aurora"></div><div class="bg-grid"></div>
<div class="gborder"><div class="card">
<h1>Scalper — création du compte</h1>
<p>Lien de premier démarrage valide.</p> <p>Lien de premier démarrage valide.</p>
<input id="u" placeholder="identifiant"> <input id="u" type="text" placeholder="identifiant" autocomplete="username">
<input id="p" type="password" placeholder="mot de passe (8 caractères min.)"> <input id="p" type="password" placeholder="mot de passe (8 caractères min.)" autocomplete="new-password">
<button onclick="go()">Créer le compte</button> <button onclick="go()">Créer le compte</button>
<div id="err"></div> <div id="err"></div>
</div></div>
<script> <script>
async function go(){ async function go(){
const r=await fetch('/setup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:new URLSearchParams(location.search).get('token'),username:document.getElementById('u').value,password:document.getElementById('p').value})}); const r=await fetch('/setup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:new URLSearchParams(location.search).get('token'),username:document.getElementById('u').value,password:document.getElementById('p').value})});
const j=await r.json(); const j=await r.json();
if(r.ok){ document.body.innerHTML='<h1>Compte créé</h1><p>Connectez-vous : <a href="/">/</a></p>'; } if(r.ok){ document.body.innerHTML='<div class="gborder"><div class="card"><h1>Compte créé</h1><p>Connectez-vous : <a style="color:#a5b4fc" href="/">/</a></p></div></div>'; }
else document.getElementById('err').textContent=j.error||('erreur '+r.status); else document.getElementById('err').textContent=j.error||('erreur '+r.status);
} }
</script></body></html> </script></body></html>
+79 -35
View File
@@ -1,5 +1,9 @@
"""Remplacement du texte dans les images : inpainting de la bulle (voir inpaint.py : """Remplacement du texte dans les images, en deux étapes :
remplissage simple ou LaMa) + retypographie de la traduction (Pillow).
3. inpainting (voir inpaint.py : remplissage simple ou LaMa) du texte original sur
l'image brute → `export/images-clean/` ;
4. retypographie de la traduction (Pillow) par-dessus, centrée dans la boîte
d'origine, à la taille du texte d'origine (hauteur de boîte OCR) → `export/images-<lang>/`.
""" """
from __future__ import annotations from __future__ import annotations
@@ -9,6 +13,9 @@ import shutil
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
# sentinel interne : replace_texts sans inpainting (image déjà nettoyée, ex. images-clean)
_DRAW_ONLY = object()
def _load_font(size: int): def _load_font(size: int):
from PIL import ImageFont from PIL import ImageFont
@@ -43,7 +50,7 @@ def wrap_text(draw, text: str, font, max_width: int) -> list[str]:
def _fit_font(draw, text: str, max_w: int, max_h: int) -> tuple[Any, int, list[str]]: def _fit_font(draw, text: str, max_w: int, max_h: int) -> tuple[Any, int, list[str]]:
"""Plus grande police (>= 8) tenant dans max_w x max_h : renvoie (font, taille, lignes). """Plus grande police (>= 8) tenant dans max_w x max_h : renvoie (font, taille, lignes).
On part de la hauteur max (la boîte OCR ≈ la hauteur du texte d'origine), puis on On part de la hauteur max (la boîte OCR ≈ la hauteur du texte d'origine), puis on
réduit jusqu'à tenir en largeur ET en hauteur.""" réduit jusqu'à tenir en largeur ET en hauteur → la bonne taille pour chaque bulle."""
font_size = max(8, max_h - 2) font_size = max(8, max_h - 2)
font = _load_font(font_size) font = _load_font(font_size)
lines = wrap_text(draw, text, font, max(10, max_w - 8)) lines = wrap_text(draw, text, font, max(10, max_w - 8))
@@ -66,28 +73,9 @@ 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 replace_texts( def _todo_regions(regions: list[dict[str, Any]], translations: list[str]) -> list[tuple[dict[str, Any], str]]:
image_path: Path, """Régions à retyper : index valide, traduction non vide et différente du texte
regions: list[dict[str, Any]], original, boîte assez grande (sinon c'est du bruit OCR)."""
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]] = [] todo: list[tuple[dict[str, Any], str]] = []
for r in regions: for r in regions:
i = r.get("index") i = r.get("index")
@@ -100,7 +88,51 @@ def replace_texts(
if w < 8 or h < 8: if w < 8 or h < 8:
continue # mini-région = bruit OCR continue # mini-région = bruit OCR
todo.append((r, text)) todo.append((r, text))
if todo: return todo
def inpaint_image_file(image_path: Path, regions: list[dict[str, Any]], out_path: Path, inpainter) -> Path:
"""Étape 3 : efface le texte original de `regions` sur l'image brute via `inpainter`
(LaMa...) et sauve l'image « nettoyée ». Toutes les régions valides sont effacées,
même sans traduction (le texte d'origine doit disparaître entièrement)."""
from PIL import Image
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]
if valid:
img = inpainter.inpaint_image(img, valid).convert("RGB")
out_path.parent.mkdir(parents=True, exist_ok=True)
img.save(out_path)
return out_path
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, à la
taille du texte d'origine (hauteur de boîte OCR). `inpainter=_DRAW_ONLY` : retypographie
seule (l'image est déjà nettoyée)."""
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")
if inpainter is None:
inpainter = default_inpainter()
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") img = inpainter.inpaint_image(img, [r for r, _ in todo]).convert("RGB")
draw = ImageDraw.Draw(img) draw = ImageDraw.Draw(img)
for r, text in todo: for r, text in todo:
@@ -127,22 +159,28 @@ def typeset_chapter(
ocr_file: str = "ocr.json", ocr_file: str = "ocr.json",
translations: list[str] | None = None, translations: list[str] | None = None,
inpainter=None, inpainter=None,
clean_subdir: str = "export/images-clean",
) -> list[str]: ) -> list[str]:
"""Recrée les images avec le texte traduit → `export/images-<lang>/`. """Étapes 3+4 sur tout le chapitre → `export/images-<lang>/`.
Si `translations` est fourni (une traduction par région OCR, dans l'ordre), il est Étape 3 : le texte original est effacé sur les images brutes (inpainting) dans
utilisé directement ; sinon les blocs texte de `chapter.<lang>.json` servent de `clean_subdir` (défaut `export/images-clean/`) ; étape 4 : la traduction est
traductions (indexés par ordre des régions). `inpainter` (défaut redessinée par-dessus. Si `translations` est fourni (une traduction par région
`default_inpainter()`) gère la suppression du texte original avant retypographie. 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).
""" """
from .inpaint import default_inpainter
ocr = json.loads((chapter_dir / ocr_file).read_text(encoding="utf-8")) ocr = json.loads((chapter_dir / ocr_file).read_text(encoding="utf-8"))
if translations is None: if translations is None:
from .models import Chapter from .models import Chapter
chapter = Chapter.from_dict(json.loads((chapter_dir / f"chapter.{lang}.json").read_text(encoding="utf-8"))) chapter = Chapter.from_dict(json.loads((chapter_dir / f"chapter.{lang}.json").read_text(encoding="utf-8")))
translations = [b.text for b in chapter.text_blocks()] translations = [b.text for b in chapter.text_blocks()]
inpainter = inpainter if inpainter is not None else default_inpainter()
images_dir = chapter_dir / "images" images_dir = chapter_dir / "images"
out_dir = chapter_dir / "export" / f"images-{lang}" out_dir = chapter_dir / "export" / f"images-{lang}"
clean_dir = chapter_dir / clean_subdir
outputs: list[str] = [] outputs: list[str] = []
if not images_dir.exists(): if not images_dir.exists():
return outputs return outputs
@@ -152,13 +190,19 @@ def typeset_chapter(
for name, regions in sorted(by_image.items()): for name, regions in sorted(by_image.items()):
src = images_dir / name src = images_dir / name
if src.exists(): if src.exists():
outputs.append(str(replace_texts(src, regions, translations, out_dir / name, inpainter=inpainter))) # étape 3 : effacement du texte original sur l'image brute
# pages sans texte détecté : copiées telles quelles pour un export complet clean_path = inpaint_image_file(src, regions, clean_dir / name, inpainter)
# étape 4 : retypographie de la traduction sur l'image nettoyée
outputs.append(str(replace_texts(clean_path, regions, translations, out_dir / name, inpainter=_DRAW_ONLY)))
# pages sans texte détecté : copiées telles quelles (clean + export) pour un export complet
for p in sorted(images_dir.iterdir()): 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: if p.is_file() and p.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp") and p.name not in by_image:
out = out_dir / p.name for dest_dir in (clean_dir, out_dir):
out = dest_dir / p.name
if not out.exists(): if not out.exists():
out_dir.mkdir(parents=True, exist_ok=True) dest_dir.mkdir(parents=True, exist_ok=True)
shutil.copyfile(p, out) shutil.copyfile(p, out)
out = out_dir / p.name
if out.exists():
outputs.append(str(out)) outputs.append(str(out))
return outputs return outputs
+21
View File
@@ -271,6 +271,27 @@ class TestLamaInpainter(unittest.TestCase):
self.assertEqual(tuple(out_arr[250, 350]), (240, 240, 245)) self.assertEqual(tuple(out_arr[250, 350]), (240, 240, 245))
self.assertEqual(tuple(out_arr[10, 10]), (240, 240, 245)) self.assertEqual(tuple(out_arr[10, 10]), (240, 240, 245))
def test_mask_is_dilated_for_full_text_removal(self):
"""Le masque doit être dilaté (style pinceau magique) : le texte est effacé
entièrement, y compris ses bords anti-crénelés."""
with tempfile.TemporaryDirectory() as tmp:
model = Path(tmp) / "lama_fp32.onnx"
model.write_bytes(b"fake")
img = Image.new("RGB", (512, 512), (240, 240, 245))
fake_mod, fake_session_cls = _fake_onnxruntime_module(fill_value=200.0)
region = [{"index": 0, "box": [100, 100, 50, 30], "text": "x"}]
with mock.patch.dict(sys.modules, {"onnxruntime": fake_mod}):
LamaInpainter(model_path=model).inpaint_image(img, region) # mask_dilate=2 par défaut
mask = fake_session_cls.instances[-1].calls[0]["mask"][0, 0]
# crop 256x256 en (0,0), échelle x2 -> rect 512 : [194,194]..[306,266]
self.assertEqual(mask[230, 250], 1.0) # centre de la boîte
self.assertEqual(mask[192, 192], 1.0) # dilaté de 2 px (hors rectangle strict)
self.assertEqual(mask[190, 190], 0.0) # au-delà de la dilatation
LamaInpainter(model_path=model, mask_dilate=0).inpaint_image(img, region)
mask0 = fake_session_cls.instances[-1].calls[0]["mask"][0, 0]
self.assertEqual(mask0[230, 250], 1.0)
self.assertEqual(mask0[192, 192], 0.0, "sans dilatation, le bord reste à 0")
def test_inpaint_image_uses_poly_when_present(self): def test_inpaint_image_uses_poly_when_present(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
model = Path(tmp) / "lama_fp32.onnx" model = Path(tmp) / "lama_fp32.onnx"
+53 -1
View File
@@ -228,6 +228,57 @@ class TestOCRTypeset(unittest.TestCase):
self.assertEqual(len(outputs), 1) self.assertEqual(len(outputs), 1)
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists()) self.assertTrue((d / "export" / "images-fr" / "p1.png").exists())
def test_typeset_chapter_ecrit_images_clean_puis_traduites(self):
"""Flux en deux étapes : 3/4 inpainting -> export/images-clean, 4/4 retypographie
-> export/images-<lang>."""
from scalper.inpaint import SimpleInpainter
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=SimpleInpainter())
self.assertEqual(len(outputs), 1)
clean = d / "export" / "images-clean" / "p1.png"
trad = d / "export" / "images-fr" / "p1.png"
self.assertTrue(clean.exists(), "étape 3 : image nettoyée (inpainting)")
self.assertTrue(trad.exists(), "étape 4 : image re-traduite")
c = Image.open(clean).convert("RGB")
dark = any(c.getpixel((px, py))[0] < 100 for px in range(10, 290) for py in range(10, 70))
self.assertFalse(dark, "le texte original doit être entièrement effacé dans images-clean")
t = Image.open(trad).convert("RGB")
dark_t = any(t.getpixel((px, py))[0] < 100 for px in range(10, 290) for py in range(10, 70))
self.assertTrue(dark_t, "la traduction doit être redessinée dans images-<lang>")
def test_replace_texts_draw_only_ne_inpaint_pas(self):
"""inpainter=_DRAW_ONLY : retypographie seule, l'image d'entrée n'est pas inpaintée
(utilisé sur les images déjà nettoyées d'export/images-clean)."""
from scalper.typeset import _DRAW_ONLY
class RedInpainter:
def inpaint_image(self, img, 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, 0, 0))
return img
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "p.png"
out1, out2 = Path(tmp) / "o1.png", Path(tmp) / "o2.png"
self._make_image(src)
regions = [{"index": 0, "box": [10, 10, 280, 60], "text": "Hello world"}]
replace_texts(src, regions, ["x"], out1, inpainter=RedInpainter())
replace_texts(src, regions, ["x"], out2, inpainter=_DRAW_ONLY)
r1 = Image.open(out1).convert("RGB")
r2 = Image.open(out2).convert("RGB")
self.assertEqual(r1.getpixel((12, 12)), (255, 0, 0), "inpainter explicite : boîte remplie")
self.assertEqual(r2.getpixel((12, 12)), (200, 220, 255), "_DRAW_ONLY : boîte non inpaintée")
def test_typeset_chapter_explicit_translations(self): def test_typeset_chapter_explicit_translations(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
d = Path(tmp) d = Path(tmp)
@@ -297,7 +348,8 @@ class TestOCRTypeset(unittest.TestCase):
with mock.patch("scalper.ocr.ocr_chapter", side_effect=fake_ocr): with mock.patch("scalper.ocr.ocr_chapter", side_effect=fake_ocr):
out = pipeline._run_ocr_typeset(d, {"language": "en"}, "fr", FakeLLM(), {}) out = pipeline._run_ocr_typeset(d, {"language": "en"}, "fr", FakeLLM(), {})
self.assertTrue(out.startswith("ok"), out) self.assertTrue(out.startswith("ok"), out)
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists()) self.assertTrue((d / "export" / "images-clean" / "p1.png").exists(), "étape 3 : inpainting -> images-clean")
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists(), "étape 4 : retypographie -> images-fr")
if __name__ == "__main__": if __name__ == "__main__":