feat(config): valeurs par défaut du run via env (source/série/langues/moteurs/zip cleaned)

docker-compose.yml pose désormais par défaut :
  SCALPER_DEFAULT_SOURCE=mangadex
  SCALPER_DEFAULT_SERIES=6e769716-df1e-4d66-89cc-32f3b46e17dc
  SCALPER_DEFAULT_LANG=fr  SCALPER_DEFAULT_SRC_LANG=en
  SCALPER_OCR_ENGINE=paddle + SCALPER_PADDLE_OCR_TIER=medium (PP-OCRv6)
  SCALPER_INPAINT_ENGINE=lama (big-lama)
  SCALPER_ZIP_EXPORT=true + SCALPER_ZIP_INCLUDE_CLEAN=true (cleaned/ dans le zip)

Câblage :
- server.py : _run_kwargs() résout source/series/lang/src_lang/zip_export/zip_include_clean
  depuis le body sinon l'env (SCALPER_DEFAULT_*, SCALPER_ZIP_*), utilisé par POST /run
  (synchrone ET background) ; zip_include_clean était ignoré sur le /run synchrone -> fix.
  _index_html() pré-remplit le formulaire (champs + sélecteurs moteurs + cases zip).
- cli.py : scalper run --source/--series/--lang/--src-lang/--zip-export/--zip-include-clean
  prennent leur défaut dans l'env (validation si toujours absent).
- .env.example + README documentés. Tests : défauts env utilisés par /run, zip_include_clean
  transmis, page d'accueil pré-remplie.

Co-authored-by: Orionis312050 <Orionis312050@users.noreply.github.com>
This commit is contained in:
Vibe Nuage AgentandOrionis312050 committed 2026-11-24 13:22:03 +00:00
1 parent cb120c375f
commit 3155586913
6 files changed
+161 -44

No files matched your search

+10
View File
@@ -22,5 +22,15 @@ MISTRAL_MODEL=mistral-small-latest
# GPU (image Dockerfile.gpu + docker-compose.gpu.yml, hôte NVIDIA + nvidia-ctk) :
# SCALPER_PADDLE_DEVICE=gpu:0
# SCALPER_LAMA_DEVICE=gpu
# Valeurs par défaut du run (pré-remplies dans l'UI, utilisées par POST /run et `scalper run`) :
# SCALPER_DEFAULT_SOURCE=mangadex
# SCALPER_DEFAULT_SERIES=<id-série>
# SCALPER_DEFAULT_LANG=fr
# SCALPER_DEFAULT_SRC_LANG=en
# SCALPER_DEFAULT_OCR_ENGINE=paddle # moteur OCR affiché (paddle = PP-OCRv6)
# SCALPER_DEFAULT_INPAINT_ENGINE=lama # moteur d'inpainting affiché (big-lama)
# SCALPER_ZIP_EXPORT=true
# SCALPER_ZIP_INCLUDE_CLEAN=true # embarque cleaned/ (images nettoyées) dans le zip
# SCALPER_LAMA_CACHE=/app/data/.lama
# SCALPER_LAMA_MODEL=/chemin/vers/lama_fp32.onnx # modèle local, si déjà téléchargé ailleurs
+9
View File
@@ -184,6 +184,15 @@ docker compose -f docker-compose.yml -f docker-compose.gpu.yml up -d --build
`nvidia`) et pose `SCALPER_PADDLE_DEVICE=gpu:0` (PaddleOCR sur le GPU) + `SCALPER_LAMA_DEVICE=gpu`
(big-lama en CUDA). Sans ces variables, tout retombe sur le CPU automatiquement.
## Valeurs par défaut du run (env)
`POST /run`, `scalper run` et le formulaire web prennent leurs valeurs par défaut dans l'env :
`SCALPER_DEFAULT_SOURCE`, `SCALPER_DEFAULT_SERIES`, `SCALPER_DEFAULT_LANG` (cible),
`SCALPER_DEFAULT_SRC_LANG` (entrée), `SCALPER_DEFAULT_OCR_ENGINE` (paddle = PP-OCRv6),
`SCALPER_DEFAULT_INPAINT_ENGINE` (lama = big-lama), `SCALPER_ZIP_EXPORT`,
`SCALPER_ZIP_INCLUDE_CLEAN` (embarque `cleaned/` — images nettoyées avant retypographie — dans le
zip d'export). Exemple dans `docker-compose.yml` / `.env.example`.
## Architecture
- **Skills Mistral** (workspace, v1) : `manga-scraper`, `chapter-cleaner`,
+8
View File
@@ -20,6 +20,14 @@ services:
- MISTRAL_MODEL=mistral-small-latest
- SCALPER_OCR_ENGINE=paddle
- SCALPER_INPAINT_ENGINE=lama
# valeurs par défaut du run (pré-remplies dans l'UI, utilisées par POST /run et la CLI) :
- SCALPER_DEFAULT_SOURCE=mangadex
- SCALPER_DEFAULT_SERIES=6e769716-df1e-4d66-89cc-32f3b46e17dc
- SCALPER_DEFAULT_LANG=fr
- SCALPER_DEFAULT_SRC_LANG=en
- SCALPER_PADDLE_OCR_TIER=medium # PP-OCRv6_medium (défaut)
- SCALPER_ZIP_EXPORT=true
- SCALPER_ZIP_INCLUDE_CLEAN=true # embarque cleaned/ dans le zip d'export
volumes:
- /DATA/AppData/scalper/data:/app/data
- /DATA/AppData/scalper/out:/app/out
+20 -6
View File
@@ -20,6 +20,13 @@ from .sources import get_adapter
from .translator import FakeLLM, MistralChatClient, load_glossary, save_glossary, translate_chapter
def _env_bool(name: str, default: bool = False) -> bool:
v = os.environ.get(name)
if v is None:
return default
return v.strip().lower() in ("1", "true", "yes", "on")
def _print(data: dict) -> None:
print(json.dumps(data, ensure_ascii=False, indent=2))
@@ -102,9 +109,12 @@ def main(argv: list[str] | None = None) -> int:
c.add_argument("--port", type=int, default=8000)
c = sub.add_parser("run", help="pipeline complet end-to-end")
c.add_argument("--source", required=True)
c.add_argument("--series", required=True)
c.add_argument("--lang", required=True)
c.add_argument("--source", default=os.environ.get("SCALPER_DEFAULT_SOURCE"),
help="source (défaut: SCALPER_DEFAULT_SOURCE)")
c.add_argument("--series", default=os.environ.get("SCALPER_DEFAULT_SERIES"),
help="id série (défaut: SCALPER_DEFAULT_SERIES)")
c.add_argument("--lang", default=os.environ.get("SCALPER_DEFAULT_LANG"),
help="langue cible (défaut: SCALPER_DEFAULT_LANG)")
c.add_argument("--group", default=None, help="filtrer par groupe (mangadex)")
c.add_argument("--out", default="out")
c.add_argument("--max-chapters", type=int, default=None)
@@ -115,12 +125,13 @@ def main(argv: list[str] | None = None) -> int:
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("--zip-export", action="store_true",
c.add_argument("--zip-export", action=argparse.BooleanOptionalAction, default=_env_bool("SCALPER_ZIP_EXPORT", False),
help="à la fin du run : zip export-<date>-<heure>-<minutes>.zip dans out/ (images + PDF + metadata/ par chapitre), puis supprime le reste de out/")
c.add_argument("--zip-include-clean", action="store_true",
c.add_argument("--zip-include-clean", action=argparse.BooleanOptionalAction, default=_env_bool("SCALPER_ZIP_INCLUDE_CLEAN", False),
help="avec --zip-export : embarque aussi cleaned/<chapitre>/ (images nettoyées, debug inpainting) dans le zip")
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")
c.add_argument("--src-lang", default=os.environ.get("SCALPER_DEFAULT_SRC_LANG"),
help="langue d'entrée du chapitre (défaut: SCALPER_DEFAULT_SRC_LANG ; enregistrée dans meta.json et utilisée pour l'OCR)")
args = p.parse_args(argv)
@@ -238,6 +249,9 @@ def main(argv: list[str] | None = None) -> int:
serve(args.host, args.port)
return 0
if args.cmd == "run":
for _name in ("source", "series", "lang"):
if not getattr(args, _name):
p.error(f"--{_name} requis (ou variable d'env SCALPER_DEFAULT_{_name.upper()})")
if getattr(args, "ocr_engine", None):
os.environ["SCALPER_OCR_ENGINE"] = args.ocr_engine
if getattr(args, "inpaint_engine", None):
+88 -38
View File
@@ -18,6 +18,7 @@ Endpoints :
from __future__ import annotations
import hashlib
import html
import json
import mimetypes
import os
@@ -94,6 +95,58 @@ def _authorized(headers) -> bool:
return exp is not None and exp > time.time()
def _env_bool(name: str, default: bool = False) -> bool:
v = os.environ.get(name)
if v is None:
return default
return v.strip().lower() in ("1", "true", "yes", "on")
def _run_kwargs(body: dict, on_progress=None, on_step=None):
"""(source, series, lang) + kwargs pour run_pipeline : champs du body, sinon défauts
env (SCALPER_DEFAULT_SOURCE / _SERIES / _LANG / _SRC_LANG, SCALPER_ZIP_EXPORT,
SCALPER_ZIP_INCLUDE_CLEAN). source/series/lang restent requis (body ou env)."""
def field(key: str, env: str):
v = body.get(key)
if v in (None, ""):
v = os.environ.get(env)
return v
zip_export = body.get("zip_export")
if zip_export is None:
zip_export = _env_bool("SCALPER_ZIP_EXPORT", False)
zip_clean = body.get("zip_include_clean")
if zip_clean is None:
zip_clean = _env_bool("SCALPER_ZIP_INCLUDE_CLEAN", False)
kw = dict(
out_root=body.get("out", "out"),
mock_llm=bool(body.get("mock_llm", False)),
max_chapters=body.get("max_chapters"),
group=body.get("group"),
with_ocr=bool(body.get("with_ocr", True)),
force=bool(body.get("force", False)),
src_lang=field("src_lang", "SCALPER_DEFAULT_SRC_LANG"),
inpaint_engine=body.get("inpaint_engine"),
ocr_engine=body.get("ocr_engine"),
zip_export=bool(zip_export),
zip_include_clean=bool(zip_clean),
)
if on_progress is not None:
kw["on_progress"] = on_progress
if on_step is not None:
kw["on_step"] = on_step
source = field("source", "SCALPER_DEFAULT_SOURCE")
series = field("series", "SCALPER_DEFAULT_SERIES")
lang = field("lang", "SCALPER_DEFAULT_LANG")
if not source:
raise KeyError("source")
if not series:
raise KeyError("series")
if not lang:
raise KeyError("lang")
return (source, series, lang), kw
def _start_job(body: dict) -> str:
"""Lance run_pipeline dans un thread et retourne l'id du job."""
@@ -110,22 +163,8 @@ def _start_job(body: dict) -> str:
def on_step(step: str) -> None:
job["progress"].update({"step": step})
summary = pipeline.run_pipeline(
body["source"], body["series"], body["lang"],
out_root=body.get("out", "out"),
mock_llm=bool(body.get("mock_llm", False)),
max_chapters=body.get("max_chapters"),
group=body.get("group"),
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"),
ocr_engine=body.get("ocr_engine"),
zip_export=bool(body.get("zip_export", False)),
zip_include_clean=bool(body.get("zip_include_clean", False)),
on_progress=on_progress,
on_step=on_step,
)
pos, kw = _run_kwargs(body, on_progress=on_progress, on_step=on_step)
summary = pipeline.run_pipeline(*pos, **kw)
job["result"] = summary
job["status"] = "done"
except Exception as e:
@@ -227,10 +266,10 @@ blockquote{margin:.3rem 0;padding:.25rem .7rem;border-left:3px solid var(--indig
<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-source">source (demo, mangadex)</label><input id="r-source" type="text" value="__DEFAULT_SOURCE__"></div>
<div><label class="f" for="r-series">id série</label><input id="r-series" type="text" value="__DEFAULT_SERIES__"></div>
<div><label class="f" for="r-lang">langue cible (fr, en…)</label><input id="r-lang" type="text" value="__DEFAULT_LANG__"></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="__DEFAULT_SRCLANG__"></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>
@@ -240,8 +279,8 @@ blockquote{margin:.3rem 0;padding:.25rem .7rem;border-left:3px solid var(--indig
<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 + metadata/, le reste de out/ est supprimé)</label>
<label class="switch"><input type="checkbox" id="r-zip-clean"><span class="track"></span>aussi embarquer cleaned/ dans le zip (images nettoyées avant retypographie — debug inpainting)</label>
<label class="switch"><input type="checkbox" id="r-zip" __ZIP_ATTR__><span class="track"></span>zip export-&lt;date&gt;-&lt;heure&gt;-&lt;minutes&gt;.zip à la fin (images + PDF + metadata/, le reste de out/ est supprimé)</label>
<label class="switch"><input type="checkbox" id="r-zip-clean" __ZIPCLEAN_ATTR__><span class="track"></span>aussi embarquer cleaned/ dans le zip (images nettoyées avant retypographie — debug inpainting)</label>
</div>
<button class="btn" onclick="runPipeline()">Lancer le pipeline</button>
</div>
@@ -253,6 +292,7 @@ blockquote{margin:.3rem 0;padding:.25rem .7rem;border-left:3px solid var(--indig
</div>
<script>
const enc = encodeURIComponent;
__DEFAULTS_JS__
let TOKEN = localStorage.getItem('scalper_token') || '';
function showLogin(){ document.getElementById('login').style.display='block'; document.getElementById('app').style.display='none'; }
function hideLogin(){ document.getElementById('login').style.display='none'; document.getElementById('app').style.display='block'; }
@@ -383,6 +423,29 @@ async function go(){
"""
def _index_html() -> str:
"""INDEX_HTML avec les valeurs par défaut env pré-remplies (source, série, langues,
moteurs, zip)."""
def esc(v: str | None) -> str:
return html.escape(v or "", quote=True)
defaults_js = (
"document.getElementById('r-ocrengine').value="
+ json.dumps(os.environ.get("SCALPER_DEFAULT_OCR_ENGINE") or "") + ";"
+ "document.getElementById('r-inpaint').value="
+ json.dumps(os.environ.get("SCALPER_DEFAULT_INPAINT_ENGINE") or "") + ";"
)
page = INDEX_HTML
page = page.replace("__DEFAULT_SOURCE__", esc(os.environ.get("SCALPER_DEFAULT_SOURCE") or "demo"))
page = page.replace("__DEFAULT_SERIES__", esc(os.environ.get("SCALPER_DEFAULT_SERIES") or "demo-1"))
page = page.replace("__DEFAULT_LANG__", esc(os.environ.get("SCALPER_DEFAULT_LANG") or "fr"))
page = page.replace("__DEFAULT_SRCLANG__", esc(os.environ.get("SCALPER_DEFAULT_SRC_LANG") or ""))
page = page.replace("__ZIP_ATTR__", "checked" if _env_bool("SCALPER_ZIP_EXPORT", True) else "")
page = page.replace("__ZIPCLEAN_ATTR__", "checked" if _env_bool("SCALPER_ZIP_INCLUDE_CLEAN", False) else "")
page = page.replace("__DEFAULTS_JS__", defaults_js)
return page
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args) -> None: # silence les logs par requête
pass
@@ -443,7 +506,7 @@ class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
u = urlparse(self.path)
if u.path == "/":
return self._html(200, INDEX_HTML)
return self._html(200, _index_html())
if u.path == "/healthz":
return self._json(200, {"status": "ok"})
if u.path == "/setup":
@@ -518,21 +581,8 @@ class Handler(BaseHTTPRequestHandler):
if body.get("background"):
job_id = _start_job(body)
return self._json(202, {"job": job_id, "status": "running"})
summary = pipeline.run_pipeline(
body["source"],
body["series"],
body["lang"],
out_root=body.get("out", "out"),
mock_llm=bool(body.get("mock_llm", False)),
max_chapters=body.get("max_chapters"),
group=body.get("group"),
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"),
ocr_engine=body.get("ocr_engine"),
zip_export=bool(body.get("zip_export", False)),
)
pos, kw = _run_kwargs(body)
summary = pipeline.run_pipeline(*pos, **kw)
except KeyError as e:
return self._json(400, {"error": f"champ requis manquant: {e}"})
except Exception as e:
+26
View File
@@ -1,4 +1,5 @@
import json
import os
import tempfile
import threading
import time
@@ -208,5 +209,30 @@ class TestServer(unittest.TestCase):
self.assertTrue(body["chapters"][0].get("forced"))
def test_run_uses_env_defaults(self):
with tempfile.TemporaryDirectory() as tmp:
with mock.patch.dict(os.environ, {"SCALPER_DEFAULT_SOURCE": "demo", "SCALPER_DEFAULT_SERIES": "demo-1", "SCALPER_DEFAULT_LANG": "fr"}):
status, body = self._post("/run", {"mock_llm": True, "out": tmp, "max_chapters": 1})
self.assertEqual(status, 200)
self.assertEqual(body["status"], "done")
def test_zip_include_clean_default_from_env(self):
with tempfile.TemporaryDirectory() as tmp:
with mock.patch.dict(os.environ, {"SCALPER_ZIP_INCLUDE_CLEAN": "true", "SCALPER_ZIP_EXPORT": "true"}):
with mock.patch("scalper.pipeline.run_pipeline", return_value={"status": "done"}) as rp:
status, _ = self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr", "out": tmp})
self.assertEqual(status, 200)
self.assertTrue(rp.call_args.kwargs["zip_include_clean"])
self.assertTrue(rp.call_args.kwargs["zip_export"])
def test_index_prefilled_from_env(self):
with mock.patch.dict(os.environ, {"SCALPER_DEFAULT_SOURCE": "mangadex", "SCALPER_DEFAULT_SERIES": "abc-123", "SCALPER_DEFAULT_SRC_LANG": "en"}):
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/") as r:
page = r.read().decode("utf-8")
self.assertIn('value="mangadex"', page)
self.assertIn('value="abc-123"', page)
self.assertIn('value="en"', page)
if __name__ == "__main__":
unittest.main()