Ajout de l'export zip (images + PDF par chapitre) dans out/
- nouveau module src/scalper/packager.py : zip_run_export cree out/export-<AAAA-MM-JJ-HH-MM>.zip contenant images/<chapitre>/<page> (pages re-traduites export/images-<lang>/ si presentes, sinon originales, tri naturel des pages) et pdf/<chapitre>.pdf (Pillow, save_all, pages RGB reduites a 1600 px max) ; puis supprime tout le reste de out/ (clean=True, state.json/glossary.json compris -> pas de reprise apres un export zippe) - pipeline : parametre zip_export, le zip est renvoye dans le resume (export_zip) - CLI : scalper run --zip-export, et commande scalper pack pour zipper un out/ existant (--no-clean pour garder le reste) - server : POST /run accepte "zip_export": true + case a cocher dans l'UI - tests : tests/test_packager.py (tri naturel, preference images traduites, PDF multi-pages, contenu/nom du zip, clean/no-clean, pipeline, CLI pack) Verifie en reel sur une copie du out/ mangadex : export-2026-11-18-20-29.zip (14,7 Mo) = 28 images traduites + 1 PDF de 28 pages. Suite : 84 passed, 1 skipped. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
1 parent
74f47096cd
commit
3a1bc0b131
6 files changed
+327
-8
No files matched your search
@@ -34,7 +34,8 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
||||
| `scalper translate <chapter.json> --lang fr [--mock-llm]` | traduction LLM + glossaire |
|
||||
| `scalper qa <source.json> <traduit.json> --lang fr` | score 0-100, pass si ≥ 80 |
|
||||
| `scalper export <traduit.json> --format md\|json\|html` | export Markdown / JSON / HTML |
|
||||
| `scalper run --source ... --series ... --lang fr [--force] [--src-lang ja]` | pipeline complet end-to-end (`--force` = exporte même si la QA échoue ; `--src-lang` = langue d'entrée du chapitre : enregistrée dans `meta.json`, affichée dans l'UI et utilisée comme langue source de l'OCR) |
|
||||
| `scalper run --source ... --series ... --lang fr [--force] [--src-lang ja] [--zip-export]` | pipeline complet end-to-end (`--force` = exporte même si la QA échoue ; `--src-lang` = langue d'entrée du chapitre : enregistrée dans `meta.json`, affichée dans l'UI et utilisée comme langue source de l'OCR ; `--zip-export` = zip final dans `out/`, voir ci-dessous) |
|
||||
| `scalper pack --out out --source mangadex --series <id> --lang fr [--no-clean]` | zippe un `out/` existant (même contenu qu'avec `--zip-export`) |
|
||||
|
||||
## OCR & remplacement du texte dans les images (automatique)
|
||||
|
||||
@@ -66,6 +67,22 @@ vérifié localement : 3.3.1 crashe, 3.2.2 fonctionne.
|
||||
|
||||
Commandes manuelles : `scalper ocr <chapter_dir> [--mock-ocr]` et `scalper typeset <chapter_dir> --lang fr [--inpaint-engine lama]`.
|
||||
|
||||
## Export zip (images + PDF)
|
||||
|
||||
Avec `scalper run ... --zip-export` (ou `"zip_export": true` dans `POST /run`, case à cocher dans
|
||||
l'UI), ou à tout moment avec `scalper pack --out out --source <src> --series <id> --lang fr`,
|
||||
Scalper crée à la fin dans le dossier `out/` un **seul zip** nommé
|
||||
`export-<AAAA-MM-JJ-HH-MM>.zip` (date/heure/minutes locales) contenant :
|
||||
|
||||
- `images/<chapitre>/<page>` : les pages du résultat — re-traduites (`export/images-<lang>/`)
|
||||
quand l'OCR/typeset a tourné, sinon les images d'origine — dans l'ordre des pages (tri naturel) ;
|
||||
- `pdf/<chapitre>.pdf` : un PDF par chapitre (Pillow, sans dépendance externe ; pages en RGB
|
||||
redimensionnées à 1600 px max).
|
||||
|
||||
Puis **tout le reste du dossier `out/` est supprimé** (zip excepté — y compris `state.json` et
|
||||
`glossary.json` : pas de reprise après un export zippé). `scalper pack --no-clean` garde le reste.
|
||||
Le chemin du zip est renvoyé dans le résumé du run (`export_zip`).
|
||||
|
||||
**Moteurs d'inpainting** (protocol `Inpainter` dans `src/scalper/inpaint.py`, sélection par
|
||||
`SCALPER_INPAINT_ENGINE` ou `--inpaint-engine`, et `"inpaint_engine"` dans `POST /run`) :
|
||||
|
||||
@@ -99,8 +116,9 @@ temp) est redirigé vers `/app/data/.paddlex` via `PADDLE_PDX_CACHE_HOME` dans `
|
||||
et celui du modèle LaMa vers `/app/data/.lama` via `SCALPER_LAMA_CACHE` :
|
||||
les modèles ne sont téléchargés qu'une fois, dans le volume monté.
|
||||
|
||||
`POST /run` accepte en plus `"src_lang": "ja"` (langue d'entrée du chapitre) et
|
||||
`"inpaint_engine": "lama"` (moteur d'inpainting : `simple` | `lama` | `auto`).
|
||||
`POST /run` accepte en plus `"src_lang": "ja"` (langue d'entrée du chapitre),
|
||||
`"inpaint_engine": "lama"` (moteur d'inpainting : `simple` | `lama` | `auto`) et
|
||||
`"zip_export": true` (zip `export-<date>-<heure>-<minutes>.zip` à la fin, puis supprime le reste de `out/`).
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
+19
-1
@@ -1,4 +1,4 @@
|
||||
"""CLI Scalper : list-series, list-groups, list-chapters, fetch, fetch-url, clean, translate, qa, export, ocr, typeset, serve, run."""
|
||||
"""CLI Scalper : list-series, list-groups, list-chapters, fetch, fetch-url, clean, translate, qa, export, ocr, typeset, pack, serve, run."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -88,6 +88,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
c.add_argument("--inpaint-engine", choices=["simple", "lama", "auto"], default=None,
|
||||
help="moteur d'inpainting pour la suppression du texte (défaut: SCALPER_INPAINT_ENGINE ou auto)")
|
||||
|
||||
c = sub.add_parser("pack", help="zippe un out/ existant : export-<date>-<heure>-<minutes>.zip (images + PDF), puis supprime le reste de out/ sauf --no-clean")
|
||||
c.add_argument("--out", default="out")
|
||||
c.add_argument("--source", required=True)
|
||||
c.add_argument("--series", required=True)
|
||||
c.add_argument("--lang", required=True)
|
||||
c.add_argument("--chapters", default=None, help="ids de chapitres séparés par des virgules (défaut: tous les chapitres de la série)")
|
||||
c.add_argument("--no-clean", action="store_true", help="garde le reste du dossier out/ (seul le zip est ajouté)")
|
||||
|
||||
c = sub.add_parser("serve", help="démarre le serveur HTTP (déploiement Docker/Coolify)")
|
||||
c.add_argument("--host", default="127.0.0.1")
|
||||
c.add_argument("--port", type=int, default=8000)
|
||||
@@ -106,6 +114,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
help="moteur OCR (défaut: SCALPER_OCR_ENGINE ou tesseract)")
|
||||
c.add_argument("--inpaint-engine", choices=["simple", "lama", "auto"], default=None,
|
||||
help="moteur d'inpainting pour la suppression du texte (défaut: SCALPER_INPAINT_ENGINE ou auto)")
|
||||
c.add_argument("--zip-export", action="store_true",
|
||||
help="à la fin du run : zip export-<date>-<heure>-<minutes>.zip dans out/ (images + PDF par chapitre), puis supprime le reste de out/")
|
||||
c.add_argument("--force", action="store_true", help="exporte même si la QA échoue (bypass vérification)")
|
||||
c.add_argument("--src-lang", default=None, help="langue d'entrée du chapitre (en, ja, fr…) : enregistrée dans meta.json et utilisée pour l'OCR")
|
||||
|
||||
@@ -211,6 +221,13 @@ def main(argv: list[str] | None = None) -> int:
|
||||
inpainter=default_inpainter(args.inpaint_engine))
|
||||
_print({"status": "ok", "images": outputs})
|
||||
return 0
|
||||
if args.cmd == "pack":
|
||||
from .packager import zip_run_export
|
||||
|
||||
ids = [c.strip() for c in args.chapters.split(",") if c.strip()] if args.chapters else None
|
||||
zip_path = zip_run_export(args.out, args.source, args.series, args.lang, chapter_ids=ids, clean=not args.no_clean)
|
||||
_print({"status": "ok", "zip": str(zip_path), "clean": not args.no_clean})
|
||||
return 0
|
||||
if args.cmd == "serve":
|
||||
from .server import serve
|
||||
|
||||
@@ -226,6 +243,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
out_root=Path(args.out), mock_llm=args.mock_llm,
|
||||
max_chapters=args.max_chapters, group=args.group, with_ocr=args.with_ocr,
|
||||
force=args.force, src_lang=args.src_lang, inpaint_engine=args.inpaint_engine,
|
||||
zip_export=args.zip_export,
|
||||
)
|
||||
_print(summary)
|
||||
return 0 if summary.get("status") == "done" else 3
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Empaquetage du résultat d'un run en un seul zip.
|
||||
|
||||
`zip_run_export` crée dans le dossier `out` un zip nommé
|
||||
`export-<AAAA-MM-JJ-HH-MM>.zip` (date/heure/minutes locales) contenant :
|
||||
|
||||
- `images/<chapitre>/<page>` : les images du résultat — les pages re-traduites
|
||||
`export/images-<lang>/` quand l'OCR/typeset a tourné, sinon les images d'origine ;
|
||||
- `pdf/<chapitre>.pdf` : un PDF par chapitre, pages dans l'ordre (tri naturel :
|
||||
1, 2, …, 10), redimensionnées à PDF_MAX_SIDE px max pour alléger le PDF.
|
||||
|
||||
Ensuite, sauf `clean=False`, **tout le reste du dossier `out` est supprimé**
|
||||
(y compris `state.json` et `glossary.json` : pas de reprise après un export zippé).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
PDF_MAX_SIDE = 1600 # les pages du PDF sont redimensionnées à cette taille max (lecture, pas print)
|
||||
IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp")
|
||||
|
||||
|
||||
def page_sort_key(name: str) -> tuple:
|
||||
"""Tri naturel des pages : « 1-… », « 2-… », « 10-… » → 1, 2, 10 (et non 1, 10, 2)."""
|
||||
m = re.match(r"\s*(\d+)", name)
|
||||
return (int(m.group(1)) if m else 1 << 30, name)
|
||||
|
||||
|
||||
def chapter_images(chapter_dir: Path, lang: str) -> list[Path]:
|
||||
"""Pages du chapitre à embarquer : `export/images-<lang>/` si présent (résultat
|
||||
traduit), sinon `images/` (original). Triées dans l'ordre des pages."""
|
||||
for candidate in (chapter_dir / "export" / f"images-{lang}", chapter_dir / "images"):
|
||||
if candidate.is_dir():
|
||||
pages = [p for p in candidate.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES]
|
||||
return sorted(pages, key=lambda p: page_sort_key(p.name))
|
||||
return []
|
||||
|
||||
|
||||
def build_chapter_pdf(pages: list[Path], pdf_path: Path) -> Path:
|
||||
"""Construit un PDF multi-pages (Pillow, aucune dépendance externe) à partir des
|
||||
images, en RGB et redimensionnées à PDF_MAX_SIDE px max."""
|
||||
from PIL import Image
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
imgs = []
|
||||
for p in pages:
|
||||
im = Image.open(p).convert("RGB")
|
||||
side = max(im.size)
|
||||
if side > PDF_MAX_SIDE:
|
||||
im = im.resize((int(im.width * PDF_MAX_SIDE / side), int(im.height * PDF_MAX_SIDE / side)), Image.LANCZOS)
|
||||
imgs.append(im)
|
||||
pdf_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
imgs[0].save(pdf_path, "PDF", save_all=True, append_images=imgs[1:], resolution=100.0)
|
||||
for im in imgs:
|
||||
im.close()
|
||||
return pdf_path
|
||||
|
||||
|
||||
def zip_run_export(
|
||||
out_root: Path | str,
|
||||
source_id: str,
|
||||
series_id: str,
|
||||
lang: str,
|
||||
chapter_ids: list[str] | None = None,
|
||||
clean: bool = True,
|
||||
when: datetime | None = None,
|
||||
) -> Path:
|
||||
"""Crée `out_root/export-<AAAA-MM-JJ-HH-MM>.zip` avec les images + PDF des chapitres
|
||||
du run, puis (clean=True) supprime tout le reste du dossier `out_root`."""
|
||||
from .scraper import chapter_dir
|
||||
|
||||
out_root = Path(out_root)
|
||||
if chapter_ids is None:
|
||||
base = out_root / "raw" / source_id / series_id
|
||||
chapter_ids = sorted(p.name for p in base.iterdir() if p.is_dir()) if base.is_dir() else []
|
||||
when = when or datetime.now()
|
||||
zip_path = out_root / f"export-{when:%Y-%m-%d-%H-%M}.zip"
|
||||
out_root.mkdir(parents=True, exist_ok=True)
|
||||
if zip_path.exists():
|
||||
zip_path.unlink()
|
||||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
for cid in chapter_ids:
|
||||
cdir = chapter_dir(out_root, source_id, series_id, cid)
|
||||
pages = chapter_images(cdir, lang)
|
||||
if not pages:
|
||||
continue
|
||||
for p in pages:
|
||||
z.write(p, f"images/{cid}/{p.name}")
|
||||
pdf_tmp = out_root / ".packager-tmp" / f"{cid}.pdf"
|
||||
build_chapter_pdf(pages, pdf_tmp)
|
||||
z.write(pdf_tmp, f"pdf/{cid}.pdf")
|
||||
shutil.rmtree(pdf_tmp.parent, ignore_errors=True)
|
||||
if clean:
|
||||
for p in out_root.iterdir():
|
||||
if p == zip_path:
|
||||
continue
|
||||
if p.is_dir():
|
||||
shutil.rmtree(p, ignore_errors=True)
|
||||
else:
|
||||
p.unlink(missing_ok=True)
|
||||
return zip_path
|
||||
@@ -31,6 +31,7 @@ def run_pipeline(
|
||||
on_progress: Callable[[int, int, Any], None] | None = None,
|
||||
src_lang: str | None = None,
|
||||
inpaint_engine: str | None = None,
|
||||
zip_export: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
out_root = Path(out_root)
|
||||
fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
|
||||
@@ -89,7 +90,13 @@ def run_pipeline(
|
||||
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}
|
||||
summary: dict[str, Any] = {"status": "done", "source": source_id, "series": series_id, "lang": lang, "chapters": results}
|
||||
if zip_export:
|
||||
from .packager import zip_run_export
|
||||
|
||||
chapter_ids = [r["chapter"]["id"] for r in results if "chapter" in r]
|
||||
summary["export_zip"] = str(zip_run_export(out_root, source_id, series_id, lang, chapter_ids))
|
||||
return summary
|
||||
|
||||
|
||||
# Langue détectée (2 lettres) -> code langue Tesseract
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Endpoints :
|
||||
- GET /healthz
|
||||
- GET / interface web (barre de progression + previews source/traduit)
|
||||
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"inpaint_engine"?,"force"?,"out"?,"background"?}
|
||||
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"inpaint_engine"?,"zip_export"?,"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)
|
||||
@@ -105,6 +105,7 @@ def _start_job(body: dict) -> str:
|
||||
force=bool(body.get("force", False)),
|
||||
src_lang=body.get("src_lang"),
|
||||
inpaint_engine=body.get("inpaint_engine"),
|
||||
zip_export=bool(body.get("zip_export", False)),
|
||||
on_progress=on_progress,
|
||||
)
|
||||
job["result"] = summary
|
||||
@@ -163,7 +164,8 @@ blockquote{margin:.3rem 0;padding:.2rem .6rem;border-left:3px solid #888;color:#
|
||||
<input id="r-max" placeholder="max chapitres (optionnel)">
|
||||
<label><input type="checkbox" id="r-mock" style="width:auto"> mock-llm (démo hors ligne)</label>
|
||||
<label><input type="checkbox" id="r-force" style="width:auto"> forcer l'export même si la QA échoue</label>
|
||||
<label><input type="checkbox" id="r-ocr" checked style="width:auto"> OCR + remplacement du texte dans les images (auto)</label><br>
|
||||
<label><input type="checkbox" id="r-ocr" checked style="width:auto"> OCR + remplacement du texte dans les images (auto)</label>
|
||||
<label><input type="checkbox" id="r-zip" style="width:auto"> zip export-<date>-<heure>-<minutes>.zip à la fin (images + PDF, le reste de out/ est supprimé)</label><br>
|
||||
<button onclick="runPipeline()">Lancer le pipeline</button>
|
||||
</fieldset>
|
||||
<div id="progress-wrap"><div id="bar"></div></div>
|
||||
@@ -180,7 +182,7 @@ async function doLogin(){ const r=await fetch('/login',{method:'POST',headers:{'
|
||||
if(TOKEN) hideLogin(); else showLogin();
|
||||
async function runPipeline(){
|
||||
const g=document.getElementById('r-group').value, m=document.getElementById('r-max').value, sl=document.getElementById('r-srclang').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};
|
||||
const body={source:document.getElementById('r-source').value, series:document.getElementById('r-series').value, lang:document.getElementById('r-lang').value, mock_llm:document.getElementById('r-mock').checked, force:document.getElementById('r-force').checked, with_ocr:document.getElementById('r-ocr').checked, zip_export:document.getElementById('r-zip').checked, background:true};
|
||||
if(g) body.group=g; if(m) body.max_chapters=Number(m); if(sl) body.src_lang=sl;
|
||||
document.getElementById('out').textContent='en cours…';
|
||||
document.getElementById('previews').innerHTML='';
|
||||
@@ -414,6 +416,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
force=bool(body.get("force", False)),
|
||||
src_lang=body.get("src_lang"),
|
||||
inpaint_engine=body.get("inpaint_engine"),
|
||||
zip_export=bool(body.get("zip_export", False)),
|
||||
)
|
||||
except KeyError as e:
|
||||
return self._json(400, {"error": f"champ requis manquant: {e}"})
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import json
|
||||
import re
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from scalper.packager import build_chapter_pdf, chapter_images, page_sort_key, zip_run_export
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
HAS_PIL = True
|
||||
except ImportError:
|
||||
HAS_PIL = False
|
||||
|
||||
|
||||
def _png(path: Path, color=(200, 220, 255), size=(60, 80)) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
Image.new("RGB", size, color).save(path)
|
||||
|
||||
|
||||
def _make_out(tmp: Path) -> Path:
|
||||
"""out/ factice : 2 chapitres (ch1 avec images traduites, ch2 avec images seules)."""
|
||||
out = tmp / "out"
|
||||
out.mkdir(parents=True)
|
||||
(out / "state.json").write_text(json.dumps({"done": ["ch1", "ch2"]}), encoding="utf-8")
|
||||
(out / "glossary.json").write_text("{}", encoding="utf-8")
|
||||
ch1 = out / "raw" / "mangadex" / "ser1" / "ch1"
|
||||
for name in ("1-a.png", "2-b.png", "10-c.png"):
|
||||
_png(ch1 / "images" / name, color=(255, 255, 255)) # originales
|
||||
_png(ch1 / "export" / "images-fr" / name, color=(200, 220, 255)) # traduites
|
||||
ch2 = out / "raw" / "mangadex" / "ser1" / "ch2"
|
||||
_png(ch2 / "images" / "1.png")
|
||||
return out
|
||||
|
||||
|
||||
class TestPageSortKey(unittest.TestCase):
|
||||
def test_natural_order(self):
|
||||
names = ["10-c.png", "2-b.png", "1-a.png"]
|
||||
self.assertEqual(sorted(names, key=page_sort_key), ["1-a.png", "2-b.png", "10-c.png"])
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL, "Pillow requis")
|
||||
class TestChapterImages(unittest.TestCase):
|
||||
def test_prefers_translated_and_sorts_naturally(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = _make_out(Path(tmp))
|
||||
pages = chapter_images(out / "raw" / "mangadex" / "ser1" / "ch1", "fr")
|
||||
self.assertEqual([p.name for p in pages], ["1-a.png", "2-b.png", "10-c.png"])
|
||||
self.assertIn("images-fr", str(pages[0]))
|
||||
# sans export traduit : repli sur les images d'origine
|
||||
pages2 = chapter_images(out / "raw" / "mangadex" / "ser1" / "ch2", "fr")
|
||||
self.assertEqual([p.name for p in pages2], ["1.png"])
|
||||
self.assertIn(f"{Path('images')}", str(pages2[0]))
|
||||
self.assertNotIn("images-fr", str(pages2[0]))
|
||||
|
||||
def test_no_images(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
d = Path(tmp) / "ch"
|
||||
d.mkdir()
|
||||
self.assertEqual(chapter_images(d, "fr"), [])
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL, "Pillow requis")
|
||||
class TestBuildPdf(unittest.TestCase):
|
||||
def test_pdf_multipage(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
pages = []
|
||||
for i in range(3):
|
||||
p = Path(tmp) / f"{i + 1}-p.png"
|
||||
_png(p, size=(100 + i, 50))
|
||||
pages.append(p)
|
||||
pdf = build_chapter_pdf(pages, Path(tmp) / "ch.pdf")
|
||||
data = pdf.read_bytes()
|
||||
self.assertTrue(data.startswith(b"%PDF"))
|
||||
n_pages = len(re.findall(rb"/Type\s*/Page(?![s])", data))
|
||||
self.assertEqual(n_pages, 3, f"3 pages attendues, trouvé {n_pages}")
|
||||
|
||||
def test_pdf_downscales_big_pages(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = Path(tmp) / "1-big.png"
|
||||
_png(p, size=(4000, 3000))
|
||||
pdf = build_chapter_pdf([p], Path(tmp) / "big.pdf")
|
||||
data = pdf.read_bytes()
|
||||
self.assertIn(b"%PDF", data[:8])
|
||||
# MediaBox en points (resolution=100 -> 4000px = 2880pt) : la page doit être réduite
|
||||
m = re.search(rb"/MediaBox\s*\[\s*0\s+0\s+([\d.]+)\s+([\d.]+)\s*\]", data)
|
||||
self.assertIsNotNone(m)
|
||||
w_pt = float(m.group(1))
|
||||
self.assertLessEqual(w_pt, 4000 * 72 / 100 + 1, "page redimensionnée à PDF_MAX_SIDE")
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PIL, "Pillow requis")
|
||||
class TestZipRunExport(unittest.TestCase):
|
||||
def test_zip_name_contents_and_clean(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = _make_out(Path(tmp))
|
||||
when = datetime(2026, 11, 17, 19, 30)
|
||||
z = zip_run_export(out, "mangadex", "ser1", "fr", ["ch1", "ch2"], when=when)
|
||||
self.assertEqual(z.name, "export-2026-11-17-19-30.zip")
|
||||
self.assertTrue(z.exists())
|
||||
with zipfile.ZipFile(z) as zf:
|
||||
names = zf.namelist()
|
||||
# images traduites de ch1 dans l'ordre naturel + pdf par chapitre
|
||||
self.assertEqual(
|
||||
[n for n in names if n.startswith("images/ch1/")],
|
||||
["images/ch1/1-a.png", "images/ch1/2-b.png", "images/ch1/10-c.png"],
|
||||
)
|
||||
self.assertIn("images/ch2/1.png", names) # ch2 : pas de traduction -> originales
|
||||
self.assertIn("pdf/ch1.pdf", names)
|
||||
self.assertIn("pdf/ch2.pdf", names)
|
||||
self.assertNotIn("state.json", names)
|
||||
self.assertNotIn("glossary.json", names)
|
||||
with zipfile.ZipFile(z) as zf:
|
||||
pdf_data = zf.read("pdf/ch1.pdf")
|
||||
self.assertEqual(len(re.findall(rb"/Type\s*/Page(?![s])", pdf_data)), 3)
|
||||
# clean : il ne reste que le zip dans out/
|
||||
self.assertEqual([p.name for p in out.iterdir()], [z.name])
|
||||
|
||||
def test_no_clean_keeps_rest(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = _make_out(Path(tmp))
|
||||
z = zip_run_export(out, "mangadex", "ser1", "fr", ["ch1"], clean=False, when=datetime(2026, 1, 2, 3, 4))
|
||||
self.assertEqual(z.name, "export-2026-01-02-03-04.zip")
|
||||
remaining = {p.name for p in out.iterdir()}
|
||||
self.assertIn(z.name, remaining)
|
||||
self.assertIn("state.json", remaining)
|
||||
self.assertIn("raw", remaining)
|
||||
|
||||
def test_chapter_ids_default_scan(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = _make_out(Path(tmp))
|
||||
z = zip_run_export(out, "mangadex", "ser1", "fr", when=datetime(2026, 5, 6, 7, 8))
|
||||
with zipfile.ZipFile(z) as zf:
|
||||
names = zf.namelist()
|
||||
self.assertTrue(any(n.startswith("images/ch1/") for n in names))
|
||||
self.assertTrue(any(n.startswith("images/ch2/") for n in names))
|
||||
|
||||
def test_pipeline_zip_export(self):
|
||||
from scalper import pipeline
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
res = pipeline.run_pipeline("demo", "demo-1", "fr", out_root=tmp, mock_llm=True, zip_export=True)
|
||||
self.assertEqual(res["status"], "done")
|
||||
self.assertIn("export_zip", res)
|
||||
z = Path(res["export_zip"])
|
||||
self.assertTrue(z.exists())
|
||||
self.assertRegex(z.name, r"^export-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}\.zip$")
|
||||
# le reste de out/ a été supprimé
|
||||
self.assertEqual([p.name for p in Path(tmp).iterdir()], [z.name])
|
||||
|
||||
def test_cli_pack(self):
|
||||
from scalper.cli import main
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = _make_out(Path(tmp))
|
||||
rc = main(["pack", "--out", str(out), "--source", "mangadex", "--series", "ser1", "--lang", "fr"])
|
||||
self.assertEqual(rc, 0)
|
||||
zips = list(out.glob("export-*.zip"))
|
||||
self.assertEqual(len(zips), 1)
|
||||
self.assertEqual([p.name for p in out.iterdir()], [zips[0].name])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user