✨ Front ajout
This commit is contained in:
1 parent
71bd601110
commit
05d5cc43b0
9 files changed
+404
-39
No files matched your search
@@ -28,7 +28,7 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
|||||||
| `scalper fetch-url <url>` | lien direct → `raw.html` + `meta.json` + `chapter.json` |
|
| `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 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` | remplace le texte des images par la traduction → `export/images-fr/` |
|
||||||
| `scalper run ... --with-ocr` | pipeline + OCR/typeset (si images présentes) |
|
| `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 fetch <source> <series> <chapitre>` | téléchargement brut + `state.json` (reprise) |
|
||||||
| `scalper clean <raw.html> --out chapter.json` | nettoyage/structuration en blocs typés |
|
| `scalper clean <raw.html> --out chapter.json` | nettoyage/structuration en blocs typés |
|
||||||
| `scalper translate <chapter.json> --lang fr [--mock-llm]` | traduction LLM + glossaire |
|
| `scalper translate <chapter.json> --lang fr [--mock-llm]` | traduction LLM + glossaire |
|
||||||
@@ -36,11 +36,21 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
|||||||
| `scalper export <traduit.json> --format md\|json\|html` | export Markdown / JSON / HTML |
|
| `scalper export <traduit.json> --format md\|json\|html` | export Markdown / JSON / HTML |
|
||||||
| `scalper run --source ... --series ... --lang fr [--force]` | pipeline complet end-to-end (`--force` = exporte même si la QA échoue) |
|
| `scalper run --source ... --series ... --lang fr [--force]` | pipeline complet end-to-end (`--force` = exporte même si la QA échoue) |
|
||||||
|
|
||||||
## OCR & remplacement du texte dans les images (V2)
|
## OCR & remplacement du texte dans les images (automatique)
|
||||||
|
|
||||||
`scalper ocr` (Tesseract via `pytesseract`, binaire installé dans l'image Docker) extrait les
|
Dans `scalper run` (et `POST /run`), l'OCR + typesetting s'exécute **automatiquement** dès qu'un
|
||||||
régions texte des images (`ocr.json`) ; `scalper typeset` efface la bulle (inpainting par couleur
|
chapitre contient des images (désactivable avec `--no-ocr` / `"with_ocr": false`) :
|
||||||
moyenne floutée) et redessine la traduction (Pillow).
|
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>/`.
|
||||||
|
|
||||||
|
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`) :
|
||||||
|
ajoute ex. `tesseract-ocr-fra` / `tesseract-ocr-jpn` dans le `Dockerfile` pour d'autres sources.
|
||||||
|
|
||||||
|
Commandes manuelles : `scalper ocr <chapter_dir> [--mock-ocr]` et `scalper typeset <chapter_dir> --lang fr`.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -71,6 +81,11 @@ 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`
|
||||||
|
avec `"background": true` + polling de `GET /jobs/<id>`), 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).
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|||||||
@@ -33,9 +33,12 @@ Les résultats sont écrits dans le volume `./out` (monté dans le compose).
|
|||||||
## Endpoints
|
## Endpoints
|
||||||
| Méthode | Chemin | Rôle |
|
| Méthode | Chemin | Rôle |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/` | **interface web** (formulaire run) |
|
| GET | `/` | **interface web** : formulaire run + barre de progression + previews (chapitre récupéré / traduit complet) |
|
||||||
| GET | `/healthz` | sonde de santé |
|
| GET | `/healthz` | sonde de santé |
|
||||||
| POST | `/run` | pipeline complet (scrape → clean → translate → QA → export). Champ optionnel `"force": true` : exporte même si la QA échoue (les chapitres concernés sont marqués `"forced": true`) |
|
| POST | `/run` | pipeline complet (scrape → clean → translate → QA → export, + OCR/typeset auto des images). Options : `"force": true` (exporte même si la QA échoue, chapitres marqués `"forced": true`), `"with_ocr": false` (désactive l'OCR/typeset, actif par défaut), `"background": true` → répond `202 {"job": id}` et le run tourne en thread |
|
||||||
|
| GET | `/jobs/<id>` | progression du job background `{status, progress: {done, total, current}, result, error}` |
|
||||||
|
| GET | `/api/chapter?out=&source=&series=&chapter=&lang=` | données de preview : meta, blocs source (`chapter.json`) et traduits (`chapter.<lang>.json`), images, images traduites |
|
||||||
|
| GET | `/file?out=&path=` | sert un fichier sous `out` (images, exports), anti path-traversal |
|
||||||
|
|
||||||
## Sécurité
|
## Sécurité
|
||||||
- Rate limiting ≥ 1 s entre requêtes vers les sources.
|
- Rate limiting ≥ 1 s entre requêtes vers les sources.
|
||||||
|
|||||||
+2
-1
@@ -95,7 +95,8 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
c.add_argument("--out", default="out")
|
c.add_argument("--out", default="out")
|
||||||
c.add_argument("--max-chapters", type=int, default=None)
|
c.add_argument("--max-chapters", type=int, default=None)
|
||||||
c.add_argument("--mock-llm", action="store_true", help="démo hors ligne (LLM factice)")
|
c.add_argument("--mock-llm", action="store_true", help="démo hors ligne (LLM factice)")
|
||||||
c.add_argument("--with-ocr", action="store_true", help="OCR + remplacement du texte dans les images")
|
c.add_argument("--with-ocr", action=argparse.BooleanOptionalAction, default=True,
|
||||||
|
help="OCR + remplacement du texte dans les images (auto si images présentes ; --no-ocr pour désactiver)")
|
||||||
c.add_argument("--force", action="store_true", help="exporte même si la QA échoue (bypass vérification)")
|
c.add_argument("--force", action="store_true", help="exporte même si la QA échoue (bypass vérification)")
|
||||||
|
|
||||||
args = p.parse_args(argv)
|
args = p.parse_args(argv)
|
||||||
|
|||||||
+28
-8
@@ -5,11 +5,11 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any, Callable
|
||||||
|
|
||||||
from .cleaner import clean_chapter
|
from .cleaner import clean_chapter
|
||||||
from .exporter import export_chapter
|
from .exporter import export_chapter
|
||||||
from .models import Chapter
|
from .models import Block, Chapter
|
||||||
from .qa import qa_chapter
|
from .qa import qa_chapter
|
||||||
from .scraper import RespectfulFetcher, RunState, chapter_dir
|
from .scraper import RespectfulFetcher, RunState, chapter_dir
|
||||||
from .sources import get_adapter
|
from .sources import get_adapter
|
||||||
@@ -25,8 +25,9 @@ def run_pipeline(
|
|||||||
fetcher: RespectfulFetcher | None = None,
|
fetcher: RespectfulFetcher | None = None,
|
||||||
max_chapters: int | None = None,
|
max_chapters: int | None = None,
|
||||||
group: str | None = None,
|
group: str | None = None,
|
||||||
with_ocr: bool = False,
|
with_ocr: bool = True,
|
||||||
force: bool = False,
|
force: bool = False,
|
||||||
|
on_progress: Callable[[int, int, Any], None] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
out_root = Path(out_root)
|
out_root = Path(out_root)
|
||||||
fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
|
fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
|
||||||
@@ -71,7 +72,7 @@ def run_pipeline(
|
|||||||
for fmt in ("md", "json", "html"):
|
for fmt in ("md", "json", "html"):
|
||||||
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)
|
entry["ocr"] = _run_ocr_typeset(dest, meta, lang, client, glossary)
|
||||||
state.mark_done(ref.id)
|
state.mark_done(ref.id)
|
||||||
entry["status"] = "ok"
|
entry["status"] = "ok"
|
||||||
if not report["pass"]:
|
if not report["pass"]:
|
||||||
@@ -79,20 +80,39 @@ def run_pipeline(
|
|||||||
else:
|
else:
|
||||||
entry["status"] = "qa_failed"
|
entry["status"] = "qa_failed"
|
||||||
results.append(entry)
|
results.append(entry)
|
||||||
|
if on_progress is not None:
|
||||||
|
on_progress(len(results), len(chapters), ref)
|
||||||
|
|
||||||
save_glossary(glossary_path, glossary)
|
save_glossary(glossary_path, glossary)
|
||||||
return {"status": "done", "source": source_id, "series": series_id, "lang": lang, "chapters": results}
|
return {"status": "done", "source": source_id, "series": series_id, "lang": lang, "chapters": results}
|
||||||
|
|
||||||
|
|
||||||
def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str) -> str:
|
# Langue détectée (2 lettres) -> code langue Tesseract
|
||||||
|
_TESSERACT_LANGS = {
|
||||||
|
"en": "eng", "fr": "fra", "es": "spa", "de": "deu", "it": "ita", "pt": "por",
|
||||||
|
"ja": "jpn", "ko": "kor", "zh": "chi_sim",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _run_ocr_typeset(dest: Path, meta: dict[str, Any], lang: str, client: LLMClient, glossary: dict[str, str]) -> 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>/."""
|
||||||
from .ocr import TesseractOCR, ocr_chapter
|
from .ocr import TesseractOCR, ocr_chapter
|
||||||
from .typeset import typeset_chapter
|
from .typeset import typeset_chapter
|
||||||
|
|
||||||
if not (dest / "images").exists():
|
if not (dest / "images").exists():
|
||||||
return "skipped : aucune image dans ce chapitre"
|
return "skipped : aucune image dans ce chapitre"
|
||||||
try:
|
try:
|
||||||
ocr_chapter(dest, TesseractOCR(), lang="eng")
|
src_lang = _TESSERACT_LANGS.get(str(meta.get("language") or "en")[:2].lower(), "eng")
|
||||||
outs = typeset_chapter(dest, lang)
|
regions = ocr_chapter(dest, TesseractOCR(), lang=src_lang)
|
||||||
return f"ok ({len(outs)} images reconstituées)"
|
if not regions:
|
||||||
|
return "skipped : aucun texte détecté dans les images"
|
||||||
|
ocr_chapter_src = Chapter(
|
||||||
|
meta={"language": src_lang},
|
||||||
|
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])
|
||||||
|
return f"ok ({len(outs)} images reconstituées, {len(regions)} textes remplacés)"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"erreur: {e}"
|
return f"erreur: {e}"
|
||||||
+192
-8
@@ -2,21 +2,88 @@
|
|||||||
|
|
||||||
Endpoints :
|
Endpoints :
|
||||||
- GET /healthz
|
- GET /healthz
|
||||||
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"force"?,"out"?}
|
- GET / interface web (barre de progression + previews source/traduit)
|
||||||
|
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"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)
|
||||||
|
- GET /file?out=&path= sert un fichier sous le répertoire `out` (anti path-traversal)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import mimetypes
|
||||||
|
import threading
|
||||||
|
import uuid
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
from urllib.parse import urlparse
|
from pathlib import Path
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
from . import pipeline
|
from . import pipeline
|
||||||
|
|
||||||
|
JOBS: dict[str, dict] = {}
|
||||||
|
JOBS_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _start_job(body: dict) -> str:
|
||||||
|
"""Lance run_pipeline dans un thread et retourne l'id du job."""
|
||||||
|
job_id = uuid.uuid4().hex[:12]
|
||||||
|
job = {"status": "running", "progress": {"done": 0, "total": 0, "current": None}, "result": None, "error": None}
|
||||||
|
with JOBS_LOCK:
|
||||||
|
JOBS[job_id] = job
|
||||||
|
|
||||||
|
def work() -> None:
|
||||||
|
try:
|
||||||
|
def on_progress(done: int, total: int, ref) -> None:
|
||||||
|
job["progress"] = {"done": done, "total": total, "current": ref.id}
|
||||||
|
|
||||||
|
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)),
|
||||||
|
on_progress=on_progress,
|
||||||
|
)
|
||||||
|
job["result"] = summary
|
||||||
|
job["status"] = "done"
|
||||||
|
except Exception as e:
|
||||||
|
job["error"] = str(e)
|
||||||
|
job["status"] = "error"
|
||||||
|
|
||||||
|
threading.Thread(target=work, daemon=True).start()
|
||||||
|
return job_id
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_out_path(out: str, rel: str) -> Path | None:
|
||||||
|
"""Résout `rel` sous le répertoire `out` ; None si hors de `out` (path traversal)."""
|
||||||
|
base = Path(out).resolve()
|
||||||
|
p = (base / rel).resolve()
|
||||||
|
if p == base or base in p.parents:
|
||||||
|
return p
|
||||||
|
return None
|
||||||
|
|
||||||
INDEX_HTML = """<!doctype html>
|
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>body{font-family:system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;color:#222}input,button{padding:.45rem;margin:.2rem}input{width:100%;box-sizing:border-box}fieldset{border:1px solid #ccc;border-radius:8px;margin-bottom:1rem}legend{font-weight:600}button{cursor:pointer;background:#222;color:#fff;border:0;border-radius:6px}pre{background:#f4f4f4;padding:1rem;border-radius:8px;overflow:auto;white-space:pre-wrap}.warn{color:#a00;font-size:.85rem}</style>
|
<style>
|
||||||
|
body{font-family:system-ui,sans-serif;max-width:60rem;margin:2rem auto;padding:0 1rem;color:#222}
|
||||||
|
input,button{padding:.45rem;margin:.2rem}input{width:100%;box-sizing:border-box}
|
||||||
|
fieldset{border:1px solid #ccc;border-radius:8px;margin-bottom:1rem}legend{font-weight:600}
|
||||||
|
button{cursor:pointer;background:#222;color:#fff;border:0;border-radius:6px}
|
||||||
|
pre{background:#f4f4f4;padding:1rem;border-radius:8px;overflow:auto;white-space:pre-wrap}
|
||||||
|
#progress-wrap{display:none;height:1.2rem;background:#e5e5e5;border-radius:6px;overflow:hidden;margin:.6rem 0}
|
||||||
|
#bar{height:100%;width:0%;background:#2a7d4f;transition:width .3s}
|
||||||
|
#bar-label{font-size:.8rem;color:#555;margin-bottom:1rem}
|
||||||
|
.chapter{border:1px solid #ddd;border-radius:8px;padding:1rem;margin:1rem 0}
|
||||||
|
.cols{display:flex;gap:1rem;flex-wrap:wrap}
|
||||||
|
.col{flex:1;min-width:16rem}
|
||||||
|
.col img{max-width:100%;display:block;margin:.3rem 0;border:1px solid #eee}
|
||||||
|
blockquote{margin:.3rem 0;padding:.2rem .6rem;border-left:3px solid #888;color:#333}
|
||||||
|
</style>
|
||||||
</head><body>
|
</head><body>
|
||||||
<h1>Scalper</h1>
|
<h1>Scalper</h1>
|
||||||
<p>Pipeline de scraping + traduction de chapitres.</p>
|
<p>Pipeline de scraping + traduction de chapitres.</p>
|
||||||
@@ -24,20 +91,87 @@ INDEX_HTML = """<!doctype html>
|
|||||||
<input id="r-source" placeholder="source (demo, mangadex)" value="demo">
|
<input id="r-source" placeholder="source (demo, mangadex)" value="demo">
|
||||||
<input id="r-series" placeholder="id série" value="demo-1">
|
<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-lang" placeholder="langue cible (fr, en, ...)" value="fr">
|
||||||
<input id="r-group" placeholder="groupe optionnel (ex. Keiyoushi, mangadex uniquement)">
|
<input id="r-group" placeholder="groupe optionnel (mangadex uniquement)">
|
||||||
<input id="r-max" placeholder="max chapitres (optionnel)">
|
<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-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><br>
|
<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><br>
|
||||||
<button onclick="runPipeline()">Lancer le pipeline</button>
|
<button onclick="runPipeline()">Lancer le pipeline</button>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
<div id="progress-wrap"><div id="bar"></div></div>
|
||||||
|
<div id="bar-label"></div>
|
||||||
<pre id="out">résultats ici…</pre>
|
<pre id="out">résultats ici…</pre>
|
||||||
|
<div id="previews"></div>
|
||||||
<script>
|
<script>
|
||||||
async function runPipeline(){const g=document.getElementById('r-group').value;const m=document.getElementById('r-max').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};if(g)body.group=g;if(m)body.max_chapters=Number(m);document.getElementById('out').textContent='en cours…';const r=await fetch('/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});document.getElementById('out').textContent=r.status+'\\n'+JSON.stringify(await r.json(),null,2);}
|
const enc = encodeURIComponent;
|
||||||
|
async function runPipeline(){
|
||||||
|
const g=document.getElementById('r-group').value, m=document.getElementById('r-max').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, background:true};
|
||||||
|
if(g) body.group=g; if(m) body.max_chapters=Number(m);
|
||||||
|
document.getElementById('out').textContent='en cours…';
|
||||||
|
document.getElementById('previews').innerHTML='';
|
||||||
|
const r=await fetch('/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
|
||||||
|
const j=await r.json();
|
||||||
|
if(!j.job){ document.getElementById('out').textContent=r.status+' '+JSON.stringify(j,null,2); return; }
|
||||||
|
poll(j.job, body.out||'out');
|
||||||
|
}
|
||||||
|
function poll(jobId,out){
|
||||||
|
const wrap=document.getElementById('progress-wrap'), bar=document.getElementById('bar'), label=document.getElementById('bar-label');
|
||||||
|
wrap.style.display='block'; bar.style.width='0%';
|
||||||
|
const t=setInterval(async()=>{
|
||||||
|
const r=await fetch('/jobs/'+jobId); const j=await r.json();
|
||||||
|
const p=j.progress||{done:0,total:0,current:''};
|
||||||
|
const pct=p.total?Math.round(100*p.done/Math.max(1,p.total)):0;
|
||||||
|
bar.style.width=pct+'%';
|
||||||
|
label.textContent=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); }
|
||||||
|
},800);
|
||||||
|
}
|
||||||
|
async function render(j,out){
|
||||||
|
const res=j.result||{};
|
||||||
|
document.getElementById('out').textContent=(j.status==='error'?'ERREUR: '+j.error:j.status+' '+JSON.stringify(res,null,2));
|
||||||
|
const prev=document.getElementById('previews'); prev.innerHTML='';
|
||||||
|
for(const ch of (res.chapters||[])){
|
||||||
|
if(!ch.chapter||ch.skipped) continue;
|
||||||
|
const q='/api/chapter?out='+enc(out)+'&source='+enc(res.source||'')+'&series='+enc(res.series||'')+'&chapter='+enc(ch.chapter.id)+'&lang='+enc(res.lang||'');
|
||||||
|
const r=await fetch(q); if(!r.ok) continue;
|
||||||
|
prev.appendChild(chapterPanel(await r.json(), out, res.lang||''));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function blockEl(b,dir,out,imgSub){
|
||||||
|
if(b.type==='image'){
|
||||||
|
const img=document.createElement('img');
|
||||||
|
const name=(b.image||'').split('/').pop();
|
||||||
|
img.src='/file?out='+enc(out)+'&path='+enc(dir+'/'+imgSub+'/'+name);
|
||||||
|
img.alt=b.placeholder||'image';
|
||||||
|
return img;
|
||||||
|
}
|
||||||
|
const p=document.createElement(b.type==='dialogue'?'blockquote':'p');
|
||||||
|
p.textContent=b.text||'';
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
function chapterPanel(data,out,lang){
|
||||||
|
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 cols=document.createElement('div'); cols.className='cols';
|
||||||
|
const c1=document.createElement('div'); c1.className='col';
|
||||||
|
const h1=document.createElement('h4'); h1.textContent='Récupéré (source)'; c1.appendChild(h1);
|
||||||
|
if(data.source) for(const b of data.source.blocks) c1.appendChild(blockEl(b,data.dir,out,'images'));
|
||||||
|
else c1.appendChild(document.createTextNode('(pas de chapter.json)'));
|
||||||
|
const c2=document.createElement('div'); c2.className='col';
|
||||||
|
const h2=document.createElement('h4'); h2.textContent='Traduit complet ('+lang+')'; c2.appendChild(h2);
|
||||||
|
const trImg=(data.images_translated&&data.images_translated.length)?('export/images-'+lang):'images';
|
||||||
|
if(data.translated) for(const b of data.translated.blocks) c2.appendChild(blockEl(b,data.dir,out,trImg));
|
||||||
|
else c2.appendChild(document.createTextNode('(pas encore traduit)'));
|
||||||
|
cols.appendChild(c1); cols.appendChild(c2); panel.appendChild(cols);
|
||||||
|
return panel;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body></html>
|
</body></html>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class Handler(BaseHTTPRequestHandler):
|
class Handler(BaseHTTPRequestHandler):
|
||||||
def log_message(self, *args) -> None: # silence les logs par requête
|
def log_message(self, *args) -> None: # silence les logs par requête
|
||||||
pass
|
pass
|
||||||
@@ -64,6 +198,53 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return self._html(200, INDEX_HTML)
|
return self._html(200, INDEX_HTML)
|
||||||
if u.path == "/healthz":
|
if u.path == "/healthz":
|
||||||
return self._json(200, {"status": "ok"})
|
return self._json(200, {"status": "ok"})
|
||||||
|
if u.path.startswith("/jobs/"):
|
||||||
|
job_id = u.path[len("/jobs/"):]
|
||||||
|
with JOBS_LOCK:
|
||||||
|
job = JOBS.get(job_id)
|
||||||
|
if job is None:
|
||||||
|
return self._json(404, {"error": "job introuvable"})
|
||||||
|
return self._json(200, {"status": job["status"], "progress": job["progress"], "result": job["result"], "error": job["error"]})
|
||||||
|
if u.path == "/api/chapter":
|
||||||
|
q = parse_qs(u.query)
|
||||||
|
out = q.get("out", ["out"])[0]
|
||||||
|
source = q.get("source", [""])[0]
|
||||||
|
series = q.get("series", [""])[0]
|
||||||
|
chapter = q.get("chapter", [""])[0]
|
||||||
|
lang = q.get("lang", [""])[0]
|
||||||
|
d = _safe_out_path(out, f"raw/{source}/{series}/{chapter}")
|
||||||
|
if d is None or not d.is_dir():
|
||||||
|
return self._json(404, {"error": "chapitre introuvable"})
|
||||||
|
base = Path(out).resolve()
|
||||||
|
data: dict = {"dir": str(d.relative_to(base)), "meta": {}, "source": None, "translated": None, "images": [], "images_translated": []}
|
||||||
|
for name, key in (("meta.json", "meta"), ("chapter.json", "source")):
|
||||||
|
f = d / name
|
||||||
|
if f.exists():
|
||||||
|
data[key] = json.loads(f.read_text(encoding="utf-8"))
|
||||||
|
if lang:
|
||||||
|
f = d / f"chapter.{lang}.json"
|
||||||
|
if f.exists():
|
||||||
|
data["translated"] = json.loads(f.read_text(encoding="utf-8"))
|
||||||
|
img_dir = d / "images"
|
||||||
|
if img_dir.is_dir():
|
||||||
|
data["images"] = sorted(p.name for p in img_dir.iterdir() if p.is_file())
|
||||||
|
itr = d / "export" / f"images-{lang}"
|
||||||
|
if lang and itr.is_dir():
|
||||||
|
data["images_translated"] = sorted(p.name for p in itr.iterdir() if p.is_file())
|
||||||
|
return self._json(200, data)
|
||||||
|
if u.path == "/file":
|
||||||
|
q = parse_qs(u.query)
|
||||||
|
out = q.get("out", ["out"])[0]
|
||||||
|
p = _safe_out_path(out, q.get("path", [""])[0])
|
||||||
|
if p is None or not p.is_file():
|
||||||
|
return self._json(404, {"error": "fichier introuvable"})
|
||||||
|
body = p.read_bytes()
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", mimetypes.guess_type(str(p))[0] or "application/octet-stream")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
return
|
||||||
return self._json(404, {"error": "not found"})
|
return self._json(404, {"error": "not found"})
|
||||||
|
|
||||||
def do_POST(self) -> None:
|
def do_POST(self) -> None:
|
||||||
@@ -73,6 +254,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
try:
|
try:
|
||||||
length = int(self.headers.get("Content-Length", 0))
|
length = int(self.headers.get("Content-Length", 0))
|
||||||
body = json.loads(self.rfile.read(length) or b"{}")
|
body = json.loads(self.rfile.read(length) or b"{}")
|
||||||
|
if body.get("background"):
|
||||||
|
job_id = _start_job(body)
|
||||||
|
return self._json(202, {"job": job_id, "status": "running"})
|
||||||
summary = pipeline.run_pipeline(
|
summary = pipeline.run_pipeline(
|
||||||
body["source"],
|
body["source"],
|
||||||
body["series"],
|
body["series"],
|
||||||
@@ -81,7 +265,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
mock_llm=bool(body.get("mock_llm", False)),
|
mock_llm=bool(body.get("mock_llm", False)),
|
||||||
max_chapters=body.get("max_chapters"),
|
max_chapters=body.get("max_chapters"),
|
||||||
group=body.get("group"),
|
group=body.get("group"),
|
||||||
with_ocr=bool(body.get("with_ocr", False)),
|
with_ocr=bool(body.get("with_ocr", True)),
|
||||||
force=bool(body.get("force", False)),
|
force=bool(body.get("force", False)),
|
||||||
)
|
)
|
||||||
except KeyError as e:
|
except KeyError as e:
|
||||||
@@ -94,7 +278,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
def serve(host: str = "127.0.0.1", port: int = 8000) -> None:
|
def serve(host: str = "127.0.0.1", port: int = 8000) -> None:
|
||||||
server = ThreadingHTTPServer((host, port), Handler)
|
server = ThreadingHTTPServer((host, port), Handler)
|
||||||
print(f"scalper serve sur http://{host}:{port} (GET /healthz, POST /run)")
|
print(f"scalper serve sur http://{host}:{port} (GET /healthz, GET /jobs/<id>, GET /api/chapter, GET /file, POST /run)")
|
||||||
try:
|
try:
|
||||||
server.serve_forever()
|
server.serve_forever()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
|
|||||||
+58
-14
@@ -39,22 +39,60 @@ def wrap_text(draw, text: str, font, max_width: int) -> list[str]:
|
|||||||
return lines or [""]
|
return lines or [""]
|
||||||
|
|
||||||
|
|
||||||
def _inpaint(img, box: list[int]) -> None:
|
def _inpaint(img, box: list[int]) -> tuple[int, int, int]:
|
||||||
"""Approximation d'inpainting : remplissage par la couleur moyenne locale floutée."""
|
"""Inpainting : la boîte est remplie par la couleur de fond estimée sur l'anneau
|
||||||
from PIL import ImageFilter
|
de pixels juste autour de la boîte (donc hors du texte), et non par la moyenne de
|
||||||
|
la boîte elle-même (qui serait 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
|
x, y, w, h = box
|
||||||
x, y = max(0, x), max(0, y)
|
x, y = max(0, x), max(0, y)
|
||||||
w, h = max(1, w), max(1, h)
|
w, h = min(max(1, w), img.width - x), min(max(1, h), img.height - y)
|
||||||
patch = img.crop((x, y, x + w, y + h)).resize((1, 1)).resize((w, h))
|
if w <= 0 or h <= 0:
|
||||||
patch = patch.filter(ImageFilter.GaussianBlur(radius=max(1, min(w, h) // 10)))
|
return (255, 255, 255)
|
||||||
img.paste(patch, (x, y))
|
margin = max(2, min(w, h) // 8)
|
||||||
|
rx0, ry0 = max(0, x - margin), max(0, y - margin)
|
||||||
|
rx1, ry1 = min(img.width, x + w + margin), min(img.height, y + h + 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((x, y, x + w, y + h)).resize((1, 1)).getpixel((0, 0))[:3]
|
||||||
|
img.paste(Image.new("RGB", (w, h), fill_rgb), (x, y))
|
||||||
|
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]
|
||||||
|
if lum > 140:
|
||||||
|
return (0, 0, 0), (255, 255, 255)
|
||||||
|
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:
|
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."""
|
"""Remplace le texte des `regions` (index → translations[index]) dans l'image."""
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
# 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")
|
img = Image.open(image_path).convert("RGB")
|
||||||
for r in regions:
|
for r in regions:
|
||||||
i = r.get("index")
|
i = r.get("index")
|
||||||
@@ -64,7 +102,8 @@ def replace_texts(image_path: Path, regions: list[dict[str, Any]], translations:
|
|||||||
if not text or text == r.get("text", "").strip():
|
if not text or text == r.get("text", "").strip():
|
||||||
continue
|
continue
|
||||||
x, y, w, h = r["box"]
|
x, y, w, h = r["box"]
|
||||||
_inpaint(img, [x, y, w, h])
|
fill_rgb = _inpaint(img, [x, y, w, h])
|
||||||
|
text_fill, stroke_fill = _text_colors(fill_rgb)
|
||||||
draw = ImageDraw.Draw(img)
|
draw = ImageDraw.Draw(img)
|
||||||
font_size = max(10, int(h * 0.8))
|
font_size = max(10, int(h * 0.8))
|
||||||
font = _load_font(font_size)
|
font = _load_font(font_size)
|
||||||
@@ -78,20 +117,25 @@ def replace_texts(image_path: Path, regions: list[dict[str, Any]], translations:
|
|||||||
for ln in lines:
|
for ln in lines:
|
||||||
tw = draw.textlength(ln, font=font)
|
tw = draw.textlength(ln, font=font)
|
||||||
tx = x + max(0, int((w - tw) // 2))
|
tx = x + max(0, int((w - tw) // 2))
|
||||||
draw.text((tx, ty), ln, font=font, fill=(255, 255, 255), stroke_width=1, stroke_fill=(0, 0, 0))
|
draw.text((tx, ty), ln, font=font, fill=text_fill, stroke_width=1, stroke_fill=stroke_fill)
|
||||||
ty += line_h
|
ty += line_h
|
||||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
img.save(out_path)
|
img.save(out_path)
|
||||||
return out_path
|
return out_path
|
||||||
|
|
||||||
|
|
||||||
def typeset_chapter(chapter_dir: Path, lang: str, ocr_file: str = "ocr.json") -> list[str]:
|
def typeset_chapter(chapter_dir: Path, lang: str, ocr_file: str = "ocr.json", translations: list[str] | None = None) -> list[str]:
|
||||||
"""Recrée les images avec le texte traduit → `export/images-<lang>/`."""
|
"""Recrée les images avec le texte traduit → `export/images-<lang>/`.
|
||||||
from .models import Chapter
|
|
||||||
|
|
||||||
|
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)."""
|
||||||
ocr = json.loads((chapter_dir / ocr_file).read_text(encoding="utf-8"))
|
ocr = json.loads((chapter_dir / ocr_file).read_text(encoding="utf-8"))
|
||||||
chapter = Chapter.from_dict(json.loads((chapter_dir / f"chapter.{lang}.json").read_text(encoding="utf-8")))
|
if translations is None:
|
||||||
translations = [b.text for b in chapter.text_blocks()]
|
from .models import Chapter
|
||||||
|
|
||||||
|
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()]
|
||||||
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}"
|
||||||
outputs: list[str] = []
|
outputs: list[str] = []
|
||||||
|
|||||||
@@ -2,9 +2,12 @@ import json
|
|||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from scalper import pipeline
|
||||||
from scalper.ocr import FakeOCR, ocr_chapter
|
from scalper.ocr import FakeOCR, ocr_chapter
|
||||||
from scalper.typeset import replace_texts, typeset_chapter, wrap_text
|
from scalper.translator import FakeLLM
|
||||||
|
from scalper.typeset import _inpaint, replace_texts, typeset_chapter, wrap_text
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
@@ -74,6 +77,50 @@ 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_explicit_translations(self):
|
||||||
|
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"])
|
||||||
|
self.assertEqual(len(outputs), 1)
|
||||||
|
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists())
|
||||||
|
|
||||||
|
def test_inpaint_uses_background_ring_not_text(self):
|
||||||
|
img = Image.new("RGB", (300, 120), (200, 220, 255))
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
d.text((20, 20), "Texte noir sur fond clair", fill=(0, 0, 0))
|
||||||
|
box = [10, 10, 280, 60]
|
||||||
|
fill = _inpaint(img, box)
|
||||||
|
# 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)
|
||||||
|
px = img.getpixel((150, 35))
|
||||||
|
self.assertGreater(px[0], 150)
|
||||||
|
|
||||||
|
def test_pipeline_ocr_typeset_end_to_end(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
|
||||||
|
|
||||||
|
with mock.patch("scalper.ocr.ocr_chapter", side_effect=fake_ocr):
|
||||||
|
out = pipeline._run_ocr_typeset(d, {"language": "en"}, "fr", FakeLLM(), {})
|
||||||
|
self.assertTrue(out.startswith("ok"), out)
|
||||||
|
self.assertTrue((d / "export" / "images-fr" / "p1.png").exists())
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -40,6 +40,16 @@ class TestPipeline(unittest.TestCase):
|
|||||||
raw1 = Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1"
|
raw1 = Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1"
|
||||||
self.assertFalse((raw1 / "export").exists())
|
self.assertFalse((raw1 / "export").exists())
|
||||||
|
|
||||||
|
def test_on_progress_callback(self):
|
||||||
|
calls = []
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
pipeline.run_pipeline(
|
||||||
|
"demo", "demo-1", "fr", out_root=tmp, mock_llm=True,
|
||||||
|
on_progress=lambda done, total, ref: calls.append((done, total, ref.id)),
|
||||||
|
)
|
||||||
|
self.assertEqual([(d, t) for d, t, _ in calls], [(1, 2), (2, 2)])
|
||||||
|
self.assertEqual(calls[-1][2], "demo-1-ch2")
|
||||||
|
|
||||||
def test_force_exports_despite_qa_failure(self):
|
def test_force_exports_despite_qa_failure(self):
|
||||||
fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]}
|
fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]}
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
import json
|
import json
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from http.server import ThreadingHTTPServer
|
from http.server import ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
from scalper.server import Handler
|
from scalper.server import Handler
|
||||||
@@ -64,6 +67,44 @@ class TestServer(unittest.TestCase):
|
|||||||
status, body = self._post("/run", {"source": "demo"})
|
status, body = self._post("/run", {"source": "demo"})
|
||||||
self.assertEqual(status, 400)
|
self.assertEqual(status, 400)
|
||||||
|
|
||||||
|
def test_run_background_job_with_progress(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})
|
||||||
|
self.assertEqual(status, 202)
|
||||||
|
job = body["job"]
|
||||||
|
final = None
|
||||||
|
for _ in range(50):
|
||||||
|
s, j = self._get(f"/jobs/{job}")
|
||||||
|
self.assertEqual(s, 200)
|
||||||
|
if j["status"] != "running":
|
||||||
|
final = j
|
||||||
|
break
|
||||||
|
time.sleep(0.2)
|
||||||
|
self.assertIsNotNone(final, "job toujours running après 10s")
|
||||||
|
self.assertEqual(final["status"], "done")
|
||||||
|
self.assertEqual(final["result"]["status"], "done")
|
||||||
|
self.assertEqual(final["progress"]["total"], 2)
|
||||||
|
self.assertEqual(final["progress"]["done"], 2)
|
||||||
|
|
||||||
|
def test_api_chapter_and_file(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr", "mock_llm": True, "out": tmp, "max_chapters": 1})
|
||||||
|
q = urllib.parse.urlencode({"out": tmp, "source": "demo", "series": "demo-1", "chapter": "demo-1-ch1", "lang": "fr"})
|
||||||
|
status, data = self._get(f"/api/chapter?{q}")
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertTrue(data["source"]["blocks"])
|
||||||
|
self.assertEqual(data["translated"]["meta"]["language"], "fr")
|
||||||
|
self.assertEqual(Path(data["dir"]).as_posix(), "raw/demo/demo-1/demo-1-ch1")
|
||||||
|
md = next((Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1" / "export").glob("*.md"))
|
||||||
|
rel = md.relative_to(tmp).as_posix()
|
||||||
|
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/file?out={urllib.parse.quote(tmp)}&path={urllib.parse.quote(rel)}") as r:
|
||||||
|
self.assertEqual(r.status, 200)
|
||||||
|
self.assertIn("markdown", r.headers.get("Content-Type", ""))
|
||||||
|
self.assertTrue(r.read())
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as cm:
|
||||||
|
self._get(f"/file?out={urllib.parse.quote(tmp)}&path=../pyproject.toml")
|
||||||
|
self.assertEqual(cm.exception.code, 404)
|
||||||
|
|
||||||
def test_run_force_bypasses_qa_gate(self):
|
def test_run_force_bypasses_qa_gate(self):
|
||||||
fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]}
|
fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]}
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
|||||||
Reference in new issue
Block a user