diff --git a/README.md b/README.md index 017b7b5..dbf0004 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | `scalper fetch-url ` | lien direct → `raw.html` + `meta.json` + `chapter.json` | | `scalper ocr [--mock-ocr]` | OCR des images (tesseract) → `ocr.json` | | `scalper typeset --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 ` | téléchargement brut + `state.json` (reprise) | | `scalper clean --out chapter.json` | nettoyage/structuration en blocs typés | | `scalper translate --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 --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) | -## 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 -régions texte des images (`ocr.json`) ; `scalper typeset` efface la bulle (inpainting par couleur -moyenne floutée) et redessine la traduction (Pillow). +Dans `scalper run` (et `POST /run`), l'OCR + typesetting s'exécute **automatiquement** dès qu'un +chapitre contient des images (désactivable avec `--no-ocr` / `"with_ocr": false`) : +Tesseract (`pytesseract`, binaire installé dans l'image Docker) extrait les régions texte des +images (`ocr.json`), chaque texte détecté est traduit par le LLM, puis `typeset` efface le texte +original (inpainting : remplissage par la couleur de fond estimée sur l'anneau de pixels autour de +la bulle) et redessine la traduction au même endroit, centrée, avec une couleur contrastée avec le +fond (Pillow). Résultat : `export/images-/`. + +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 [--mock-ocr]` et `scalper typeset --lang fr`. ## 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/ ``` +L'interface web (`GET /`) affiche une **barre de progression** pendant le run (via `POST /run` +avec `"background": true` + polling de `GET /jobs/`), 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-/` quand l'OCR/typeset a tourné). + Déploiement pas à pas sur Coolify : [docs/deploy-coolify.md](docs/deploy-coolify.md). ## Licence diff --git a/docs/deploy-coolify.md b/docs/deploy-coolify.md index 85b188b..e32b569 100644 --- a/docs/deploy-coolify.md +++ b/docs/deploy-coolify.md @@ -33,9 +33,12 @@ Les résultats sont écrits dans le volume `./out` (monté dans le compose). ## Endpoints | 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é | -| 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/` | 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..json`), images, images traduites | +| GET | `/file?out=&path=` | sert un fichier sous `out` (images, exports), anti path-traversal | ## Sécurité - Rate limiting ≥ 1 s entre requêtes vers les sources. diff --git a/src/scalper/cli.py b/src/scalper/cli.py index a82999a..fa4ab54 100644 --- a/src/scalper/cli.py +++ b/src/scalper/cli.py @@ -95,7 +95,8 @@ def main(argv: list[str] | None = None) -> int: c.add_argument("--out", default="out") 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("--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)") args = p.parse_args(argv) diff --git a/src/scalper/pipeline.py b/src/scalper/pipeline.py index 011f8dd..0e2e9f4 100644 --- a/src/scalper/pipeline.py +++ b/src/scalper/pipeline.py @@ -5,11 +5,11 @@ from __future__ import annotations import json import time from pathlib import Path -from typing import Any +from typing import Any, Callable from .cleaner import clean_chapter from .exporter import export_chapter -from .models import Chapter +from .models import Block, Chapter from .qa import qa_chapter from .scraper import RespectfulFetcher, RunState, chapter_dir from .sources import get_adapter @@ -25,8 +25,9 @@ def run_pipeline( fetcher: RespectfulFetcher | None = None, max_chapters: int | None = None, group: str | None = None, - with_ocr: bool = False, + with_ocr: bool = True, force: bool = False, + on_progress: Callable[[int, int, Any], None] | None = None, ) -> dict[str, Any]: out_root = Path(out_root) fetcher = fetcher or RespectfulFetcher(min_delay=1.0) @@ -71,7 +72,7 @@ def run_pipeline( for fmt in ("md", "json", "html"): export_chapter(translated, fmt, dest / "export") if with_ocr: - entry["ocr"] = _run_ocr_typeset(dest, meta, lang) + entry["ocr"] = _run_ocr_typeset(dest, meta, lang, client, glossary) state.mark_done(ref.id) entry["status"] = "ok" if not report["pass"]: @@ -79,20 +80,39 @@ def run_pipeline( else: entry["status"] = "qa_failed" results.append(entry) + if on_progress is not None: + on_progress(len(results), len(chapters), ref) save_glossary(glossary_path, glossary) 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-/.""" from .ocr import TesseractOCR, ocr_chapter from .typeset import typeset_chapter if not (dest / "images").exists(): return "skipped : aucune image dans ce chapitre" try: - ocr_chapter(dest, TesseractOCR(), lang="eng") - outs = typeset_chapter(dest, lang) - return f"ok ({len(outs)} images reconstituées)" + src_lang = _TESSERACT_LANGS.get(str(meta.get("language") or "en")[:2].lower(), "eng") + regions = ocr_chapter(dest, TesseractOCR(), lang=src_lang) + 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: return f"erreur: {e}" diff --git a/src/scalper/server.py b/src/scalper/server.py index 9b63857..cda1774 100644 --- a/src/scalper/server.py +++ b/src/scalper/server.py @@ -2,21 +2,88 @@ Endpoints : - 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/ é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 import json +import mimetypes +import threading +import uuid 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 +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 = """ Scalper - +

Scalper

Pipeline de scraping + traduction de chapitres.

@@ -24,20 +91,87 @@ INDEX_HTML = """ - + -
+ +
+
+
résultats ici…
+
""" + class Handler(BaseHTTPRequestHandler): def log_message(self, *args) -> None: # silence les logs par requête pass @@ -64,6 +198,53 @@ class Handler(BaseHTTPRequestHandler): return self._html(200, INDEX_HTML) if u.path == "/healthz": 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"}) def do_POST(self) -> None: @@ -73,6 +254,9 @@ class Handler(BaseHTTPRequestHandler): try: length = int(self.headers.get("Content-Length", 0)) 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( body["source"], body["series"], @@ -81,7 +265,7 @@ class Handler(BaseHTTPRequestHandler): 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", False)), + with_ocr=bool(body.get("with_ocr", True)), force=bool(body.get("force", False)), ) except KeyError as e: @@ -94,7 +278,7 @@ class Handler(BaseHTTPRequestHandler): def serve(host: str = "127.0.0.1", port: int = 8000) -> None: 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/, GET /api/chapter, GET /file, POST /run)") try: server.serve_forever() except KeyboardInterrupt: diff --git a/src/scalper/typeset.py b/src/scalper/typeset.py index 9772a90..951e6e2 100644 --- a/src/scalper/typeset.py +++ b/src/scalper/typeset.py @@ -39,22 +39,60 @@ def wrap_text(draw, text: str, font, max_width: int) -> list[str]: return lines or [""] -def _inpaint(img, box: list[int]) -> None: - """Approximation d'inpainting : remplissage par la couleur moyenne locale floutée.""" - from PIL import ImageFilter +def _inpaint(img, box: list[int]) -> tuple[int, int, int]: + """Inpainting : la boîte est remplie par la couleur de fond estimée sur l'anneau + 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 = max(0, x), max(0, y) - w, h = max(1, w), max(1, h) - patch = img.crop((x, y, x + w, y + h)).resize((1, 1)).resize((w, h)) - patch = patch.filter(ImageFilter.GaussianBlur(radius=max(1, min(w, h) // 10))) - img.paste(patch, (x, y)) + w, h = min(max(1, w), img.width - x), min(max(1, h), img.height - y) + if w <= 0 or h <= 0: + return (255, 255, 255) + 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: """Remplace le texte des `regions` (index → translations[index]) dans l'image.""" 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") for r in regions: 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(): continue 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) font_size = max(10, int(h * 0.8)) 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: tw = draw.textlength(ln, font=font) 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 out_path.parent.mkdir(parents=True, exist_ok=True) img.save(out_path) return out_path -def typeset_chapter(chapter_dir: Path, lang: str, ocr_file: str = "ocr.json") -> list[str]: - """Recrée les images avec le texte traduit → `export/images-/`.""" - from .models import Chapter +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-/`. + Si `translations` est fourni (une traduction par région OCR, dans l'ordre), il est + utilisé directement ; sinon les blocs texte de `chapter..json` servent de + traductions (indexés par ordre des régions).""" 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"))) - translations = [b.text for b in chapter.text_blocks()] + if translations is None: + 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" out_dir = chapter_dir / "export" / f"images-{lang}" outputs: list[str] = [] diff --git a/tests/test_ocr_typeset.py b/tests/test_ocr_typeset.py index c6df39a..603946f 100644 --- a/tests/test_ocr_typeset.py +++ b/tests/test_ocr_typeset.py @@ -2,9 +2,12 @@ import json import tempfile import unittest from pathlib import Path +from unittest import mock +from scalper import pipeline 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: from PIL import Image, ImageDraw @@ -74,6 +77,50 @@ class TestOCRTypeset(unittest.TestCase): self.assertEqual(len(outputs), 1) 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__": unittest.main() diff --git a/tests/test_pipeline_exporter.py b/tests/test_pipeline_exporter.py index 0d02388..86314c4 100644 --- a/tests/test_pipeline_exporter.py +++ b/tests/test_pipeline_exporter.py @@ -40,6 +40,16 @@ class TestPipeline(unittest.TestCase): raw1 = Path(tmp) / "raw" / "demo" / "demo-1" / "demo-1-ch1" 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): fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]} with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/test_server.py b/tests/test_server.py index 18a8116..717b6f8 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,10 +1,13 @@ import json import tempfile import threading +import time import unittest import urllib.error +import urllib.parse import urllib.request from http.server import ThreadingHTTPServer +from pathlib import Path from unittest import mock from scalper.server import Handler @@ -64,6 +67,44 @@ class TestServer(unittest.TestCase): status, body = self._post("/run", {"source": "demo"}) 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): fake = {"score": 10, "pass": False, "issues": [{"type": "x", "critical": True}]} with tempfile.TemporaryDirectory() as tmp: