diff --git a/Dockerfile b/Dockerfile index 89d9710..3b30fd9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,15 @@ FROM python:3.12-slim +RUN apt-get update && apt-get install -y --no-install-recommends \ + tesseract-ocr fonts-dejavu-core \ + && rm -rf /var/lib/apt/lists/* + WORKDIR /app COPY pyproject.toml README.md ./ COPY src ./src -RUN pip install --no-cache-dir . +RUN pip install --no-cache-dir ".[ocr]" RUN useradd -m scalper && mkdir -p /app/data /app/out && chown -R scalper:scalper /app USER scalper diff --git a/README.md b/README.md index 5883762..82a2ec6 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,9 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | `scalper list-series ` / `list-chapters [--group Keiyoushi]` | catalogage (filtre par groupe via API MangaDex) | | `scalper list-groups mangadex --query Keiyoushi` | recherche de groupes de scanlation (API officielle) | | `scalper --config sources.toml fetch-url ` | lien direct (gate légal : licence déclarée + robots.txt + blocage) | +| `scalper ocr [--mock-ocr]` | OCR des images (tesseract) → `ocr.json` — **licences dérivables uniquement** | +| `scalper typeset --lang fr` | remplace le texte des images par la traduction → `export/images-fr/` | +| `scalper run ... --with-ocr` | pipeline + OCR/typeset (si licence dérivable et 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 | @@ -42,6 +45,15 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | `scalper export --format md\|json\|html` | export avec page licence | | `scalper run --source ... --series ... --lang fr` | pipeline complet end-to-end | +## OCR & remplacement du texte dans les images (V2) + +`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). **Restriction légale** : ce traitement crée +une œuvre dérivée des images, donc il est réservé aux sources en **domaine public / Creative +Commons / contenu propre** (`legal.allows_derivatives`) — la source `mangadex` (images selon +licence de l'œuvre) et toute source bloquée sont refusées. + ## Architecture - **Skills Mistral** (workspace, v1) : `legal-source-check`, `manga-scraper`, `chapter-cleaner`, diff --git a/docs/legal-sources.md b/docs/legal-sources.md index ab62237..6a808b3 100644 --- a/docs/legal-sources.md +++ b/docs/legal-sources.md @@ -19,6 +19,13 @@ Scalper ne doit traiter que des contenus pour lesquels une autorisation existe. - Toute source dont `robots.txt` interdit le chemin ciblé. - Tout contournement de paywall, captcha, authentification ou DRM. +## Œuvres dérivées (OCR + remplacement du texte dans les images) +Modifier les images d'un chapitre (effacer le texte, redessiner la traduction) crée une **œuvre +dérivée des images** : réservé aux licences qui l'autorisent — **domaine public, Creative Commons, +contenus propres** (`legal.allows_derivatives`). La source `mangadex` (images selon la licence +de chaque œuvre) est **exclue** du traitement d'images. Les commandes `scalper ocr` / `typeset` +et le flag `--with-ocr` refusent toute source non dérivable. + ## Règles de crawl obligatoires - `User-Agent` identifiable (nom du projet + contact). - ≥ 1 seconde entre deux requêtes, 1 seule requête concurrente. diff --git a/pyproject.toml b/pyproject.toml index ed4672a..bf74fb5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [] [project.optional-dependencies] dev = ["pytest>=8"] agents = ["mistralai-agents>=1.1"] +ocr = ["pillow>=10.1", "pytesseract>=0.3.10"] [project.scripts] scalper = "scalper.cli:main" diff --git a/src/scalper/cli.py b/src/scalper/cli.py index 7b03e07..1d41166 100644 --- a/src/scalper/cli.py +++ b/src/scalper/cli.py @@ -77,6 +77,15 @@ def main(argv: list[str] | None = None) -> int: c.add_argument("url") c.add_argument("--out", default="data") + c = sub.add_parser("ocr", help="OCR des images d'un chapitre (réservé aux licences dérivables : domaine public/CC/propre)") + c.add_argument("chapter_dir") + c.add_argument("--lang", default="eng", help="langue OCR (tesseract)") + c.add_argument("--mock-ocr", action="store_true") + + c = sub.add_parser("typeset", help="remplace le texte des images par la traduction (licences dérivables uniquement)") + c.add_argument("chapter_dir") + c.add_argument("--lang", required=True) + 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) @@ -89,6 +98,7 @@ 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 (licences dérivables uniquement)") args = p.parse_args(argv) @@ -184,6 +194,27 @@ def main(argv: list[str] | None = None) -> int: (dest / "chapter.json").write_text(json.dumps(chapter.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8") _print({"status": "ok", "dest": str(dest), "blocks": len(chapter.blocks), "language": chapter.meta.get("language")}) return 0 + if args.cmd == "ocr": + from .ocr import FakeOCR, TesseractOCR, ocr_chapter + + meta = json.loads((Path(args.chapter_dir) / "meta.json").read_text(encoding="utf-8")) + if not legal.allows_derivatives(meta.get("license", "")): + _print({"status": "blocked", "reason": "licence non dérivable : OCR/typeset réservé domaine public/CC/contenu propre"}) + return 3 + client = FakeOCR() if args.mock_ocr else TesseractOCR(lang=args.lang) + regions = ocr_chapter(Path(args.chapter_dir), client, lang=args.lang) + _print({"status": "ok", "regions": len(regions), "out": str(Path(args.chapter_dir) / "ocr.json")}) + return 0 + if args.cmd == "typeset": + from .typeset import typeset_chapter + + meta = json.loads((Path(args.chapter_dir) / "meta.json").read_text(encoding="utf-8")) + if not legal.allows_derivatives(meta.get("license", "")): + _print({"status": "blocked", "reason": "licence non dérivable : OCR/typeset réservé domaine public/CC/contenu propre"}) + return 3 + outputs = typeset_chapter(Path(args.chapter_dir), args.lang) + _print({"status": "ok", "images": outputs}) + return 0 if args.cmd == "serve": from .server import serve @@ -193,7 +224,7 @@ def main(argv: list[str] | None = None) -> int: summary = pipeline.run_pipeline( args.source, args.series, args.lang, out_root=Path(args.out), mock_llm=args.mock_llm, - max_chapters=args.max_chapters, group=args.group, + max_chapters=args.max_chapters, group=args.group, with_ocr=args.with_ocr, ) _print(summary) return 0 if summary.get("status") == "done" else 3 diff --git a/src/scalper/legal.py b/src/scalper/legal.py index 60412ab..0dd81d4 100644 --- a/src/scalper/legal.py +++ b/src/scalper/legal.py @@ -105,6 +105,19 @@ def robots_allow(domain: str, path: str = "/") -> tuple[bool, str]: return ok, "robots.txt vérifié" if ok else f"robots.txt interdit le chemin {path}" +DERIVATIVE_LICENSE_MARKERS = ( + "domaine public", "public domain", "creative commons", "cc by", "cc0", + "contenu propre", "own content", +) + + +def allows_derivatives(license_str: str) -> bool: + """True si la licence autorise les œuvres dérivées (ex. modifier les images : + OCR + remplacement du texte = image modifiée). Réservé domaine public / CC / contenu propre.""" + l = (license_str or "").lower() + return any(m in l for m in DERIVATIVE_LICENSE_MARKERS) + + def check_source(source: str, path: str = "/") -> Verdict: """Vérifie une source (id local 'demo' ou URL/domaine).""" domain = domain_of(source) diff --git a/src/scalper/ocr.py b/src/scalper/ocr.py new file mode 100644 index 0000000..22f6ecb --- /dev/null +++ b/src/scalper/ocr.py @@ -0,0 +1,73 @@ +"""OCR des images d'un chapitre (texte dans les bulles). + +Réservé aux sources dont la licence autorise les œuvres dérivées +(domaine public / Creative Commons / contenu propre) — voir legal.allows_derivatives. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Protocol + + +class OCRClient(Protocol): + def recognize(self, image_path: Path, lang: str = "eng") -> list[dict[str, Any]]: ... + + +class TesseractOCR: + """OCR via Tesseract (pytesseract). Nécessite le binaire tesseract (voir Dockerfile).""" + + def __init__(self, lang: str = "eng") -> None: + self.lang = lang + + def recognize(self, image_path: Path, lang: str | None = None) -> list[dict[str, Any]]: + import pytesseract + from pytesseract import Output + + data = pytesseract.image_to_data(str(image_path), lang=lang or self.lang, output_type=Output.DICT) + regions: dict[tuple, dict[str, Any]] = {} + for i in range(len(data["text"])): + text = (data["text"][i] or "").strip() + try: + conf = float(data["conf"][i]) + except (TypeError, ValueError): + conf = -1.0 + if not text or conf < 60: + continue + key = (data["block_num"][i], data["par_num"][i], data["line_num"][i]) + r = regions.setdefault( + key, + {"image": image_path.name, "box": [data["left"][i], data["top"][i], 0, 0], "text": ""}, + ) + r["box"][2] = max(r["box"][2], data["left"][i] + data["width"][i]) + r["box"][3] = max(r["box"][3], data["top"][i] + data["height"][i]) + r["text"] = (r["text"] + " " + text).strip() + return [dict(v, index=i) for i, v in enumerate(regions.values())] + + +class FakeOCR: + """OCR factice hors ligne (tests / démo).""" + + def __init__(self, regions_by_image: dict[str, list[dict]] | None = None) -> None: + self.regions_by_image = regions_by_image or {} + + def recognize(self, image_path: Path, lang: str | None = None) -> list[dict[str, Any]]: + return [ + dict(r, image=image_path.name, index=i) + for i, r in enumerate(self.regions_by_image.get(image_path.name, [])) + ] + + +def ocr_chapter(chapter_dir: Path, client: OCRClient, lang: str = "eng") -> list[dict[str, Any]]: + """OCR de toutes les images de `chapter_dir/images` → `chapter_dir/ocr.json`.""" + images_dir = chapter_dir / "images" + images = sorted(p for p in images_dir.glob("*") if p.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp")) if images_dir.exists() else [] + regions: list[dict[str, Any]] = [] + for img in images: + regions.extend(client.recognize(img, lang)) + for i, r in enumerate(regions): + r["index"] = i + out = chapter_dir / "ocr.json" + out.write_text(json.dumps({"lang": lang, "regions": regions}, ensure_ascii=False, indent=2), encoding="utf-8") + return regions diff --git a/src/scalper/pipeline.py b/src/scalper/pipeline.py index 3f37da9..25ea6bc 100644 --- a/src/scalper/pipeline.py +++ b/src/scalper/pipeline.py @@ -26,6 +26,7 @@ def run_pipeline( fetcher: RespectfulFetcher | None = None, max_chapters: int | None = None, group: str | None = None, + with_ocr: bool = False, ) -> dict[str, Any]: out_root = Path(out_root) verdict = legal.check_source(source_id) @@ -73,6 +74,8 @@ def run_pipeline( if report["pass"]: for fmt in ("md", "json", "html"): export_chapter(translated, fmt, dest / "export") + if with_ocr: + entry["ocr"] = _run_ocr_typeset(dest, meta, lang) state.mark_done(ref.id) entry["status"] = "ok" else: @@ -81,3 +84,19 @@ def run_pipeline( 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: + from .ocr import TesseractOCR, ocr_chapter + from .typeset import typeset_chapter + + if not legal.allows_derivatives(meta.get("license", "")): + return "skipped : licence non dérivable (OCR/typeset réservé domaine public/CC/contenu propre)" + 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)" + except Exception as e: + return f"erreur: {e}" diff --git a/src/scalper/server.py b/src/scalper/server.py index 1fe326e..da06346 100644 --- a/src/scalper/server.py +++ b/src/scalper/server.py @@ -3,7 +3,7 @@ Endpoints : - GET /healthz - GET /check-source?source= -- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"out"?} +- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"with_ocr"?,"out"?} Toutes les requêtes passent par legal-source-check : une source bloquée (mangas-origines, keiyoushi.github.io, domaine non déclaré) n'est jamais traitée. @@ -96,6 +96,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)), ) except KeyError as e: return self._json(400, {"error": f"champ requis manquant: {e}"}) diff --git a/src/scalper/typeset.py b/src/scalper/typeset.py new file mode 100644 index 0000000..dd9e44e --- /dev/null +++ b/src/scalper/typeset.py @@ -0,0 +1,109 @@ +"""Remplacement du texte dans les images : inpainting de la bulle + retypographie +de la traduction (Pillow uniquement). + +Réservé aux sources dont la licence autorise les œuvres dérivées — voir legal.allows_derivatives. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + + +def _load_font(size: int): + from PIL import ImageFont + + for name in ("DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"): + try: + return ImageFont.truetype(name, size) + except Exception: + pass + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + +def wrap_text(draw, text: str, font, max_width: int) -> list[str]: + words = text.split() + lines: list[str] = [] + cur = "" + for w in words: + t = (cur + " " + w).strip() + if not cur or draw.textlength(t, font=font) <= max_width: + cur = t + else: + lines.append(cur) + cur = w + if cur: + lines.append(cur) + 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 + + 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)) + + +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 + + img = Image.open(image_path).convert("RGB") + for r in regions: + i = r.get("index") + if i is None or i >= len(translations): + continue + text = translations[i].strip() + if not text or text == r.get("text", "").strip(): + continue + x, y, w, h = r["box"] + _inpaint(img, [x, y, w, h]) + draw = ImageDraw.Draw(img) + font_size = max(10, int(h * 0.8)) + font = _load_font(font_size) + lines = wrap_text(draw, text, font, max(10, w - 8)) + while font_size > 8 and (font_size + 2) * len(lines) > h: + font_size -= 2 + font = _load_font(font_size) + lines = wrap_text(draw, text, font, max(10, w - 8)) + line_h = font_size + 2 + ty = y + max(0, (h - line_h * len(lines)) // 2) + 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)) + 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 + + 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()] + images_dir = chapter_dir / "images" + out_dir = chapter_dir / "export" / f"images-{lang}" + outputs: list[str] = [] + if not images_dir.exists(): + return outputs + by_image: dict[str, list[dict[str, Any]]] = {} + for r in ocr.get("regions", []): + by_image.setdefault(r["image"], []).append(r) + for name, regions in sorted(by_image.items()): + src = images_dir / name + if src.exists(): + outputs.append(str(replace_texts(src, regions, translations, out_dir / name))) + return outputs diff --git a/tests/test_ocr_typeset.py b/tests/test_ocr_typeset.py new file mode 100644 index 0000000..91fae4b --- /dev/null +++ b/tests/test_ocr_typeset.py @@ -0,0 +1,91 @@ +import json +import tempfile +import unittest +from pathlib import Path + +from scalper import legal +from scalper.ocr import FakeOCR, ocr_chapter +from scalper.typeset import replace_texts, typeset_chapter, wrap_text + +try: + from PIL import Image, ImageDraw + + HAS_PIL = True +except ImportError: + HAS_PIL = False + + +class TestDerivativeGate(unittest.TestCase): + def test_demo_license_allows_derivatives(self): + self.assertTrue(legal.allows_derivatives("fixture de test interne (texte inventé, domaine public)")) + + def test_mangadex_license_refuses_derivatives(self): + self.assertFalse(legal.allows_derivatives("API officielle MangaDex (données publiques ; images selon licence de l'œuvre)")) + + def test_cc_license_allows_derivatives(self): + self.assertTrue(legal.allows_derivatives("Creative Commons CC BY 4.0")) + + +@unittest.skipUnless(HAS_PIL, "Pillow requis") +class TestOCRTypeset(unittest.TestCase): + def _make_image(self, path: Path, size=(300, 120)) -> None: + img = Image.new("RGB", size, (255, 255, 255)) + d = ImageDraw.Draw(img) + d.rectangle([10, 10, 290, 70], fill=(200, 220, 255)) + d.text((20, 20), "Hello world", fill=(0, 0, 0)) + img.save(path) + + def test_ocr_chapter_writes_ocr_json(self): + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + (d / "images").mkdir() + self._make_image(d / "images" / "p1.png") + fake = FakeOCR({"p1.png": [{"box": [10, 10, 280, 60], "text": "Hello world"}]}) + regions = ocr_chapter(d, fake, lang="eng") + self.assertEqual(len(regions), 1) + self.assertEqual(regions[0]["index"], 0) + data = json.loads((d / "ocr.json").read_text(encoding="utf-8")) + self.assertEqual(data["regions"][0]["text"], "Hello world") + + def test_replace_texts_draws_translation(self): + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "p1.png" + out = Path(tmp) / "out.png" + self._make_image(src) + regions = [{"index": 0, "box": [10, 10, 280, 60], "text": "Hello world"}] + replace_texts(src, regions, ["Bonjour le monde"], out) + self.assertTrue(out.exists()) + img = Image.open(out) + self.assertEqual(img.size, (300, 120)) + colors = img.getcolors(maxcolors=100000) + self.assertGreater(len(colors), 2, "le texte redessiné doit modifier des pixels") + + def test_wrap_text(self): + img = Image.new("RGB", (10, 10)) + d = ImageDraw.Draw(img) + from scalper.typeset import _load_font + + lines = wrap_text(d, "un deux trois quatre cinq", _load_font(10), 40) + self.assertGreater(len(lines), 1) + self.assertEqual(" ".join(lines).split(), "un deux trois quatre cinq".split()) + + def test_typeset_chapter(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", + ) + (d / "chapter.fr.json").write_text( + json.dumps({"meta": {"language": "fr"}, "blocks": [{"index": 0, "type": "dialogue", "text": "Bonjour le monde"}]}), + encoding="utf-8", + ) + outputs = typeset_chapter(d, "fr") + self.assertEqual(len(outputs), 1) + self.assertTrue((d / "export" / "images-fr" / "p1.png").exists()) + + +if __name__ == "__main__": + unittest.main()