Barre de progression en etapes (7 étapes) dans l'UI
- pipeline : nouveau callback on_step emis par run_pipeline (fetch, translate, zip, clean) et _run_ocr_typeset (ocr, translate) ; typeset_chapter emet inpaint/typeset par image - server : STEP_LABELS (libelles FR), le job background remonte progress.step via GET /jobs/<id> - UI : barre d'étapes en pastilles (done=vert, active=degradé pulsant) au-dessus de la barre globale % chapitres ; libellé de l'étape courante dans le label - tests : séquence d'étapes OCR (ocr->translate->inpaint->typeset), étapes run_pipeline (fetch/translate/zip/clean), step dans /jobs, labels dans la page Suite : 94 passed, 1 skipped. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
1 parent
5c2c102518
commit
a1b01946cc
7 files changed
+131
-10
No files matched your search
@@ -164,7 +164,10 @@ L'interface web (`GET /`) — refondue dans un style **Aceternity UI** (thème s
|
|||||||
animée, cartes à bord dégradé, toggles, barre de progression dégradée ; 100 % vanilla CSS/JS,
|
animée, cartes à bord dégradé, toggles, barre de progression dégradée ; 100 % vanilla CSS/JS,
|
||||||
sans build ni CDN, servie en un seul fichier par le serveur stdlib) — affiche une **barre de
|
sans build ni CDN, servie en un seul fichier par le serveur stdlib) — affiche une **barre de
|
||||||
progression** pendant le run (via `POST /run` avec `"background": true` + polling de
|
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
|
`GET /jobs/<id>`) — affichée **en étapes** : téléchargement des images → récupération des textes
|
||||||
|
(OCR) → traduction des textes → effacement des bulles sur les images (LaMa) → mise en place du
|
||||||
|
texte traduit sur les images cleaned → compression du rendu (zip) → suppression du reste de `out/`.
|
||||||
|
L'UI 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é
|
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
|
(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é).
|
re-traduites `export/images-<lang>/` quand l'OCR/typeset a tourné).
|
||||||
|
|||||||
+22
-4
@@ -30,6 +30,7 @@ def run_pipeline(
|
|||||||
with_ocr: bool = True,
|
with_ocr: bool = True,
|
||||||
force: bool = False,
|
force: bool = False,
|
||||||
on_progress: Callable[[int, int, Any], None] | None = None,
|
on_progress: Callable[[int, int, Any], None] | None = None,
|
||||||
|
on_step: Callable[[str], None] | None = None,
|
||||||
src_lang: str | None = None,
|
src_lang: str | None = None,
|
||||||
inpaint_engine: str | None = None,
|
inpaint_engine: str | None = None,
|
||||||
ocr_engine: str | None = None,
|
ocr_engine: str | None = None,
|
||||||
@@ -47,6 +48,10 @@ def run_pipeline(
|
|||||||
client: LLMClient = FakeLLM() if mock_llm else MistralChatClient()
|
client: LLMClient = FakeLLM() if mock_llm else MistralChatClient()
|
||||||
state = RunState(out_root / "state.json")
|
state = RunState(out_root / "state.json")
|
||||||
|
|
||||||
|
def _fire(step: str) -> None:
|
||||||
|
if on_step is not None:
|
||||||
|
on_step(step)
|
||||||
|
|
||||||
results: list[dict[str, Any]] = []
|
results: list[dict[str, Any]] = []
|
||||||
for ref in chapters:
|
for ref in chapters:
|
||||||
entry: dict[str, Any] = {"chapter": ref.to_dict()}
|
entry: dict[str, Any] = {"chapter": ref.to_dict()}
|
||||||
@@ -54,6 +59,7 @@ def run_pipeline(
|
|||||||
entry["skipped"] = "déjà récupéré (state.json)"
|
entry["skipped"] = "déjà récupéré (state.json)"
|
||||||
else:
|
else:
|
||||||
dest = chapter_dir(out_root, source_id, series_id, ref.id)
|
dest = chapter_dir(out_root, source_id, series_id, ref.id)
|
||||||
|
_fire("fetch")
|
||||||
adapter.fetch_chapter(ref, dest)
|
adapter.fetch_chapter(ref, dest)
|
||||||
meta = json.loads((dest / "meta.json").read_text(encoding="utf-8"))
|
meta = json.loads((dest / "meta.json").read_text(encoding="utf-8"))
|
||||||
meta["fetched_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
meta["fetched_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||||
@@ -69,6 +75,7 @@ def run_pipeline(
|
|||||||
state.mark_fetched(ref.id)
|
state.mark_fetched(ref.id)
|
||||||
entry["blocks"] = len(chapter.blocks)
|
entry["blocks"] = len(chapter.blocks)
|
||||||
|
|
||||||
|
_fire("translate")
|
||||||
translated = translate_chapter(chapter, lang, glossary, client)
|
translated = translate_chapter(chapter, lang, glossary, client)
|
||||||
(dest / f"chapter.{lang}.json").write_text(
|
(dest / f"chapter.{lang}.json").write_text(
|
||||||
json.dumps(translated.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8"
|
json.dumps(translated.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8"
|
||||||
@@ -81,7 +88,8 @@ def run_pipeline(
|
|||||||
export_chapter(translated, fmt, dest / "export")
|
export_chapter(translated, fmt, dest / "export")
|
||||||
if with_ocr:
|
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, ocr_engine=ocr_engine)
|
inpaint_engine=inpaint_engine, ocr_engine=ocr_engine,
|
||||||
|
on_step=on_step)
|
||||||
state.mark_done(ref.id)
|
state.mark_done(ref.id)
|
||||||
entry["status"] = "ok"
|
entry["status"] = "ok"
|
||||||
if not report["pass"]:
|
if not report["pass"]:
|
||||||
@@ -98,7 +106,9 @@ def run_pipeline(
|
|||||||
from .packager import zip_run_export
|
from .packager import zip_run_export
|
||||||
|
|
||||||
chapter_ids = [r["chapter"]["id"] for r in results if "chapter" in r]
|
chapter_ids = [r["chapter"]["id"] for r in results if "chapter" in r]
|
||||||
|
_fire("zip")
|
||||||
summary["export_zip"] = str(zip_run_export(out_root, source_id, series_id, lang, chapter_ids))
|
summary["export_zip"] = str(zip_run_export(out_root, source_id, series_id, lang, chapter_ids))
|
||||||
|
_fire("clean")
|
||||||
return summary
|
return summary
|
||||||
|
|
||||||
|
|
||||||
@@ -110,11 +120,17 @@ _TESSERACT_LANGS = {
|
|||||||
|
|
||||||
|
|
||||||
def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMClient, glossary: dict[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, ocr_engine: str | None = None) -> str:
|
inpaint_engine: str | None = None, ocr_engine: str | None = None,
|
||||||
|
on_step: Callable[[str], None] | None = None) -> str:
|
||||||
"""OCR des images du chapitre, traduction des textes détectés via le LLM, puis
|
"""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) ;
|
`inpaint_engine` : moteur d'inpainting (simple|lama|auto, défaut SCALPER_INPAINT_ENGINE) ;
|
||||||
`ocr_engine` : moteur OCR (tesseract|paddle, défaut SCALPER_OCR_ENGINE)."""
|
`ocr_engine` : moteur OCR (tesseract|paddle, défaut SCALPER_OCR_ENGINE).
|
||||||
|
`on_step` : callback d'étape ("ocr", "translate", "inpaint", "typeset") pour la barre de progression."""
|
||||||
|
|
||||||
|
def _fire(step: str) -> None:
|
||||||
|
if on_step is not None:
|
||||||
|
on_step(step)
|
||||||
from .inpaint import default_inpainter
|
from .inpaint import default_inpainter
|
||||||
from .ocr import default_ocr_client, ocr_chapter
|
from .ocr import default_ocr_client, ocr_chapter
|
||||||
from .typeset import typeset_chapter
|
from .typeset import typeset_chapter
|
||||||
@@ -129,12 +145,14 @@ def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMCli
|
|||||||
inpainter = default_inpainter(inpaint_engine)
|
inpainter = default_inpainter(inpaint_engine)
|
||||||
inpaint_name = type(inpainter).__name__
|
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)
|
print(f"[scalper][ocr] {dest.name}: 1/4 OCR ({ocr_engine_name}) du texte brut des bulles...", file=sys.stderr)
|
||||||
|
_fire("ocr")
|
||||||
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)
|
print(f"[scalper][ocr] {dest.name}: 2/4 traduction de {len(regions)} textes -> {lang}...", file=sys.stderr)
|
||||||
|
_fire("translate")
|
||||||
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)],
|
||||||
@@ -143,7 +161,7 @@ def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMCli
|
|||||||
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}: 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)
|
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=inpainter)
|
inpainter=inpainter, on_step=on_step)
|
||||||
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)
|
||||||
|
|||||||
+44
-5
@@ -34,6 +34,18 @@ from . import pipeline
|
|||||||
JOBS: dict[str, dict] = {}
|
JOBS: dict[str, dict] = {}
|
||||||
JOBS_LOCK = threading.Lock()
|
JOBS_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
# Étapes du pipeline affichées dans la barre de progression de l'UI (clé -> libellé)
|
||||||
|
STEP_LABELS = {
|
||||||
|
"fetch": "Téléchargement des images",
|
||||||
|
"ocr": "Récupération des textes (OCR)",
|
||||||
|
"translate": "Traduction des textes",
|
||||||
|
"inpaint": "Effacement des bulles de texte sur les images (LaMa)",
|
||||||
|
"typeset": "Mise en place du texte traduit sur les images cleaned",
|
||||||
|
"zip": "Compression du rendu (zip)",
|
||||||
|
"clean": "Suppression du reste de out/",
|
||||||
|
}
|
||||||
|
STEP_ORDER = list(STEP_LABELS)
|
||||||
|
|
||||||
AUTH_FILE = Path(os.environ.get("SCALPER_AUTH_FILE", "data/auth.json"))
|
AUTH_FILE = Path(os.environ.get("SCALPER_AUTH_FILE", "data/auth.json"))
|
||||||
SETUP_TOKEN: str | None = None
|
SETUP_TOKEN: str | None = None
|
||||||
SESSIONS: dict[str, float] = {}
|
SESSIONS: dict[str, float] = {}
|
||||||
@@ -86,14 +98,17 @@ def _authorized(headers) -> bool:
|
|||||||
def _start_job(body: dict) -> str:
|
def _start_job(body: dict) -> str:
|
||||||
"""Lance run_pipeline dans un thread et retourne l'id du job."""
|
"""Lance run_pipeline dans un thread et retourne l'id du job."""
|
||||||
job_id = uuid.uuid4().hex[:12]
|
job_id = uuid.uuid4().hex[:12]
|
||||||
job = {"status": "running", "progress": {"done": 0, "total": 0, "current": None}, "result": None, "error": None}
|
job = {"status": "running", "progress": {"done": 0, "total": 0, "current": None, "step": None}, "result": None, "error": None}
|
||||||
with JOBS_LOCK:
|
with JOBS_LOCK:
|
||||||
JOBS[job_id] = job
|
JOBS[job_id] = job
|
||||||
|
|
||||||
def work() -> None:
|
def work() -> None:
|
||||||
try:
|
try:
|
||||||
def on_progress(done: int, total: int, ref) -> None:
|
def on_progress(done: int, total: int, ref) -> None:
|
||||||
job["progress"] = {"done": done, "total": total, "current": ref.id}
|
job["progress"].update({"done": done, "total": total, "current": ref.id})
|
||||||
|
|
||||||
|
def on_step(step: str) -> None:
|
||||||
|
job["progress"].update({"step": step})
|
||||||
|
|
||||||
summary = pipeline.run_pipeline(
|
summary = pipeline.run_pipeline(
|
||||||
body["source"], body["series"], body["lang"],
|
body["source"], body["series"], body["lang"],
|
||||||
@@ -108,6 +123,7 @@ def _start_job(body: dict) -> str:
|
|||||||
ocr_engine=body.get("ocr_engine"),
|
ocr_engine=body.get("ocr_engine"),
|
||||||
zip_export=bool(body.get("zip_export", False)),
|
zip_export=bool(body.get("zip_export", False)),
|
||||||
on_progress=on_progress,
|
on_progress=on_progress,
|
||||||
|
on_step=on_step,
|
||||||
)
|
)
|
||||||
job["result"] = summary
|
job["result"] = summary
|
||||||
job["status"] = "done"
|
job["status"] = "done"
|
||||||
@@ -173,6 +189,14 @@ input:focus,select:focus{border-color:var(--indigo);box-shadow:0 0 0 3px rgba(99
|
|||||||
#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}
|
#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{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}
|
#bar-label{font-size:.8rem;color:var(--muted);margin-bottom:1rem;min-height:1.1em}
|
||||||
|
.steps{display:flex;gap:.4rem;flex-wrap:wrap;margin:.9rem 0 .4rem}
|
||||||
|
.step{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .65rem;border-radius:999px;border:1px solid var(--border);font-size:.72rem;color:var(--muted);background:rgba(255,255,255,.03);transition:.2s}
|
||||||
|
.step .dot{width:.55rem;height:.55rem;border-radius:50%;background:rgba(255,255,255,.18);flex:none}
|
||||||
|
.step.active{color:#fff;border-color:transparent;background:linear-gradient(90deg,rgba(99,102,241,.3),rgba(217,70,239,.3));box-shadow:0 0 16px rgba(99,102,241,.4)}
|
||||||
|
.step.active .dot{background:linear-gradient(90deg,var(--indigo),var(--fuchsia));box-shadow:0 0 8px var(--fuchsia);animation:pulse 1s ease-in-out infinite alternate}
|
||||||
|
.step.done{color:#a7f3d0;border-color:rgba(52,211,153,.35)}
|
||||||
|
.step.done .dot{background:#34d399}
|
||||||
|
@keyframes pulse{from{transform:scale(1)}to{transform:scale(1.35)}}
|
||||||
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}
|
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}
|
#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{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}
|
||||||
@@ -219,6 +243,7 @@ blockquote{margin:.3rem 0;padding:.25rem .7rem;border-left:3px solid var(--indig
|
|||||||
</div>
|
</div>
|
||||||
<button class="btn" onclick="runPipeline()">Lancer le pipeline</button>
|
<button class="btn" onclick="runPipeline()">Lancer le pipeline</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="steps" class="steps"></div>
|
||||||
<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>
|
||||||
<div class="card" style="margin-top:1rem"><pre id="out">résultats ici…</pre></div>
|
<div class="card" style="margin-top:1rem"><pre id="out">résultats ici…</pre></div>
|
||||||
@@ -244,15 +269,29 @@ async function runPipeline(){
|
|||||||
if(!j.job){ document.getElementById('out').textContent=r.status+' '+JSON.stringify(j,null,2); return; }
|
if(!j.job){ document.getElementById('out').textContent=r.status+' '+JSON.stringify(j,null,2); return; }
|
||||||
poll(j.job, body.out||'out');
|
poll(j.job, body.out||'out');
|
||||||
}
|
}
|
||||||
|
const STEPS=[["fetch","Téléchargement des images"],["ocr","Récupération des textes (OCR)"],["translate","Traduction des textes"],["inpaint","Effacement des bulles (LaMa)"],["typeset","Texte traduit sur images cleaned"],["zip","Compression (zip)"],["clean","Suppression du reste"]];
|
||||||
|
function renderSteps(cur){
|
||||||
|
const el=document.getElementById('steps'); if(!el) return; el.innerHTML='';
|
||||||
|
const idx=STEPS.findIndex(s=>s[0]===cur);
|
||||||
|
STEPS.forEach(([k,label],i)=>{
|
||||||
|
const d=document.createElement('div');
|
||||||
|
d.className='step'+(cur?(i<idx?' done':(i===idx?' active':'')):'');
|
||||||
|
const dot=document.createElement('span'); dot.className='dot'; d.appendChild(dot);
|
||||||
|
d.appendChild(document.createTextNode((cur&&i<idx?'✓ ':'')+label));
|
||||||
|
el.appendChild(d);
|
||||||
|
});
|
||||||
|
}
|
||||||
function poll(jobId,out){
|
function poll(jobId,out){
|
||||||
const wrap=document.getElementById('progress-wrap'), bar=document.getElementById('bar'), label=document.getElementById('bar-label');
|
const wrap=document.getElementById('progress-wrap'), bar=document.getElementById('bar'), label=document.getElementById('bar-label');
|
||||||
wrap.style.display='block'; bar.style.width='0%';
|
wrap.style.display='block'; bar.style.width='0%'; renderSteps(null);
|
||||||
const t=setInterval(async ()=>{
|
const t=setInterval(async ()=>{
|
||||||
const r=await api('/jobs/'+jobId); const j=await r.json();
|
const r=await api('/jobs/'+jobId); const j=await r.json();
|
||||||
const p=j.progress||{done:0,total:0,current:''};
|
const p=j.progress||{done:0,total:0,current:'',step:null};
|
||||||
const pct=p.total?Math.round(100*p.done/Math.max(1,p.total)):0;
|
const pct=p.total?Math.round(100*p.done/Math.max(1,p.total)):0;
|
||||||
bar.style.width=pct+'%';
|
bar.style.width=pct+'%';
|
||||||
label.textContent=pct+'% — chapitre '+p.done+'/'+p.total+(p.current?' ('+p.current+')':'');
|
renderSteps(p.step||null);
|
||||||
|
const sl=p.step?(((STEPS.find(s=>s[0]===p.step)||[])[1])||p.step)+' — ':'';
|
||||||
|
label.textContent=sl+pct+'% — chapitre '+p.done+'/'+p.total+(p.current?' ('+p.current+')':'');
|
||||||
if(j.status!=='running'){ clearInterval(t); setTimeout(()=>{wrap.style.display='none';},1500); render(j,out); }
|
if(j.status!=='running'){ clearInterval(t); setTimeout(()=>{wrap.style.display='none';},1500); render(j,out); }
|
||||||
},800);
|
},800);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -160,6 +160,7 @@ def typeset_chapter(
|
|||||||
translations: list[str] | None = None,
|
translations: list[str] | None = None,
|
||||||
inpainter=None,
|
inpainter=None,
|
||||||
clean_subdir: str = "export/images-clean",
|
clean_subdir: str = "export/images-clean",
|
||||||
|
on_step=None,
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
"""Étapes 3+4 sur tout le chapitre → `export/images-<lang>/`.
|
"""Étapes 3+4 sur tout le chapitre → `export/images-<lang>/`.
|
||||||
|
|
||||||
@@ -191,8 +192,12 @@ def typeset_chapter(
|
|||||||
src = images_dir / name
|
src = images_dir / name
|
||||||
if src.exists():
|
if src.exists():
|
||||||
# étape 3 : effacement du texte original sur l'image brute
|
# étape 3 : effacement du texte original sur l'image brute
|
||||||
|
if on_step is not None:
|
||||||
|
on_step("inpaint")
|
||||||
clean_path = inpaint_image_file(src, regions, clean_dir / name, inpainter)
|
clean_path = inpaint_image_file(src, regions, clean_dir / name, inpainter)
|
||||||
# étape 4 : retypographie de la traduction sur l'image nettoyée
|
# étape 4 : retypographie de la traduction sur l'image nettoyée
|
||||||
|
if on_step is not None:
|
||||||
|
on_step("typeset")
|
||||||
outputs.append(str(replace_texts(clean_path, regions, translations, out_dir / name, inpainter=_DRAW_ONLY)))
|
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
|
# 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()):
|
||||||
|
|||||||
@@ -351,6 +351,26 @@ class TestOCRTypeset(unittest.TestCase):
|
|||||||
self.assertTrue((d / "export" / "images-clean" / "p1.png").exists(), "étape 3 : inpainting -> images-clean")
|
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")
|
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists(), "étape 4 : retypographie -> images-fr")
|
||||||
|
|
||||||
|
def test_pipeline_ocr_typeset_reports_steps_in_order(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
d = Path(tmp)
|
||||||
|
(d / "images").mkdir()
|
||||||
|
self._make_image(d / "images" / "p1.png")
|
||||||
|
regions = [{"index": 0, "image": "p1.png", "box": [10, 10, 280, 60], "text": "Hello world"}]
|
||||||
|
|
||||||
|
def fake_ocr(chapter_dir, client, lang="eng"):
|
||||||
|
(Path(chapter_dir) / "ocr.json").write_text(
|
||||||
|
json.dumps({"lang": lang, "regions": regions}), encoding="utf-8"
|
||||||
|
)
|
||||||
|
return regions
|
||||||
|
|
||||||
|
steps = []
|
||||||
|
with mock.patch("scalper.ocr.ocr_chapter", side_effect=fake_ocr):
|
||||||
|
out = pipeline._run_ocr_typeset(d, {"language": "en"}, "fr", FakeLLM(), {},
|
||||||
|
inpaint_engine="simple", on_step=steps.append)
|
||||||
|
self.assertTrue(out.startswith("ok"), out)
|
||||||
|
self.assertEqual(steps, ["ocr", "translate", "inpaint", "typeset"], steps)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -93,6 +93,17 @@ class TestExporter(unittest.TestCase):
|
|||||||
with self.assertRaises(KeyError):
|
with self.assertRaises(KeyError):
|
||||||
get_adapter("inconnu")
|
get_adapter("inconnu")
|
||||||
|
|
||||||
|
def test_run_pipeline_reports_steps(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
steps = []
|
||||||
|
res = pipeline.run_pipeline("demo", "demo-1", "fr", out_root=tmp, mock_llm=True,
|
||||||
|
zip_export=True, on_step=steps.append)
|
||||||
|
self.assertEqual(res["status"], "done")
|
||||||
|
self.assertIn("fetch", steps)
|
||||||
|
self.assertIn("translate", steps)
|
||||||
|
self.assertEqual(steps[-2:], ["zip", "clean"], steps)
|
||||||
|
self.assertIn("export_zip", res)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -116,6 +116,31 @@ class TestServer(unittest.TestCase):
|
|||||||
self.assertIn("Scalper", body)
|
self.assertIn("Scalper", body)
|
||||||
self.assertIn("/run", body)
|
self.assertIn("/run", body)
|
||||||
|
|
||||||
|
def test_web_ui_has_step_bar(self):
|
||||||
|
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/") as r:
|
||||||
|
body = r.read().decode("utf-8")
|
||||||
|
self.assertIn('id="steps"', body)
|
||||||
|
for label in ("Téléchargement des images", "Récupération des textes (OCR)", "Traduction des textes",
|
||||||
|
"Effacement des bulles", "images cleaned", "Compression (zip)", "Suppression du reste"):
|
||||||
|
self.assertIn(label, body)
|
||||||
|
|
||||||
|
def test_background_job_progress_has_step(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
status, body = self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr",
|
||||||
|
"mock_llm": True, "out": tmp, "background": True,
|
||||||
|
"zip_export": True})
|
||||||
|
self.assertEqual(status, 202)
|
||||||
|
job = body["job"]
|
||||||
|
j = {}
|
||||||
|
for _ in range(200):
|
||||||
|
s, j = self._get(f"/jobs/{job}")
|
||||||
|
if j["status"] != "running":
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
self.assertEqual(j["status"], "done")
|
||||||
|
self.assertIn("step", j["progress"])
|
||||||
|
self.assertEqual(j["progress"]["step"], "clean", j["progress"]) # zip_export -> zip puis clean
|
||||||
|
|
||||||
def test_run_demo_mock_llm(self):
|
def test_run_demo_mock_llm(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
status, body = self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr", "mock_llm": True, "out": tmp})
|
status, body = self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr", "mock_llm": True, "out": tmp})
|
||||||
|
|||||||
Reference in new issue
Block a user