feat: init Scalper — pipeline légal scrape+traduction (SCAL-1..SCAL-12)

- legal-source-check (liste de blocage scanlation, robots.txt, rate limiting)
- sources: demo (fixture) + mangadex (API officielle)
- cleaner, translator (LLM Mistral + glossaire), QA, exporter (md/json/html)
- CLI + pipeline resumable (state.json), 22 tests unitaires
- sous-agents Mistral Agents SDK: orchestrator + scraper/translator/qa
- skills/ (6 SKILL.md), docs légales, CI GitHub Actions

Refs: Jira SCAL-1 (Epic CDC), SCAL-2..SCAL-12 (backlog Scrum)
This commit is contained in:
Vibe committed 2026-11-16 10:07:28 +00:00
commit f38a1d630b
38 files changed
+1733

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
"""Scalper — pipeline légal de scraping et traduction de chapitres manga/webtoon."""
__version__ = "0.1.0"
+3
View File
@@ -0,0 +1,3 @@
from .cli import main
raise SystemExit(main())
View File
Whitespace-only changes.
+64
View File
@@ -0,0 +1,64 @@
"""Scalper multi-agents (Mistral Agents SDK 1.1).
Architecture : un orchestrateur délègue à des subagents (chacun sa propre
session), comme les subagents de Claude Code côté Mistral Studio.
Lancement : pip install -e ".[agents]" puis `agents chat` (entrypoint déclaré
dans pyproject.toml : scalper.agents.main:agent).
"""
from __future__ import annotations
from mistralai import agents
from .tools import check_source, qa_translation, run_chapter_pipeline, translate_text
scraper_agent = agents.Agent(
name="scraper-agent",
model="mistral-small-latest",
instructions=(
"Tu es l'agent scraper de Scalper. Tu valides toujours la source avec "
"check_source avant toute requête (aucune source non autorisée, ex. sites "
"de scanlation : robots.txt, rate limiting, pas de contournement). Tu "
"exécutes ensuite le scraping via run_chapter_pipeline ou list/fetch."
),
tools=[check_source, run_chapter_pipeline],
)
translator_agent = agents.Agent(
name="translator-agent",
model="mistral-large-latest",
instructions=(
"Tu es l'agent traducteur de Scalper. Tu traduis avec translate_text en "
"respectant strictement le glossaire (noms propres, termes récurrents), tu "
"ne traduis jamais les placeholders [IMG:n], et tu fais valider le résultat "
"par qa_translation (score >= 80 requis)."
),
tools=[translate_text, qa_translation],
)
qa_agent = agents.Agent(
name="qa-agent",
model="mistral-small-latest",
instructions=(
"Tu es l'agent QA de Scalper. Tu compares source et traduction avec "
"qa_translation, tu signales toute incohérence de glossaire, bloc vide, "
"placeholder altéré ou mauvaise langue, et tu rends un verdict pass/fail."
),
tools=[qa_translation],
)
agent = agents.Agent(
name="scalper-orchestrator",
model="mistral-large-latest",
instructions=(
"Tu es l'orchestrateur du pipeline Scalper (scraping légal + traduction de "
"chapitres manga/webtoon). Règle absolue : seules les sources légales sont "
"traitées (API officielles, Creative Commons, domaine public, contenus "
"propres) ; check_source doit retourner allowed avant toute action. "
"Délègue le scraping à scraper-agent, la traduction à translator-agent et "
"le contrôle qualité à qa-agent, puis consolide les résultats."
),
tools=[check_source, run_chapter_pipeline],
subagents=[scraper_agent, translator_agent, qa_agent],
)
+53
View File
@@ -0,0 +1,53 @@
"""Outils Python exposés aux agents Scalper (Mistral Agents SDK).
Chaque fonction = un @agents.tool : nom depuis la fonction, schéma depuis les
paramètres typés, description depuis le docstring.
"""
from __future__ import annotations
import json
from pathlib import Path
from mistralai import agents
from .. import legal, pipeline
from ..cleaner import clean_chapter
from ..models import Chapter
from ..qa import qa_chapter
from ..translator import FakeLLM, MistralChatClient, load_glossary, translate_chapter
@agents.tool
def check_source(source: str) -> dict:
"""Valide qu'une source de mangas/webtoons est légale (robots.txt, CGU, licence, liste de blocage). Retourne {verdict: allowed|blocked, reasons, license}."""
return legal.check_source(source).to_dict()
@agents.tool
def run_chapter_pipeline(source: str, series: str, lang: str, mock_llm: bool = False) -> dict:
"""Exécute le pipeline complet (check légal -> scrape -> clean -> translate -> QA -> export) pour une série. mock_llm=True pour une démo hors ligne."""
return pipeline.run_pipeline(source, series, lang, mock_llm=mock_llm)
@agents.tool
def translate_text(text: str, target_lang: str, glossary_json: str = "{}") -> str:
"""Traduit un texte vers target_lang via le LLM Mistral, en respectant le glossaire JSON {terme: traduction}."""
client = MistralChatClient()
glossary = json.loads(glossary_json or "{}")
meta = {"language": "unknown"}
chapter = Chapter(meta=meta, blocks=[])
from ..models import Block
chapter.blocks = [Block(index=0, type="narration", text=text)]
out = translate_chapter(chapter, target_lang, glossary, client)
return out.blocks[0].text
@agents.tool
def qa_translation(source_json: str, translated_json: str, target_lang: str, glossary_json: str = "{}") -> dict:
"""Contrôle qualité : compare un chapitre source et sa traduction (JSON), retourne {score, issues, pass}."""
src = Chapter.from_dict(json.loads(source_json))
tr = Chapter.from_dict(json.loads(translated_json))
glossary = json.loads(glossary_json or "{}")
return qa_chapter(src, tr, glossary, target_lang)
+129
View File
@@ -0,0 +1,129 @@
"""chapter-cleaner : HTML brut -> chapter.json structuré (blocs typés)."""
from __future__ import annotations
import re
from html.parser import HTMLParser
from typing import Any
from .models import Block, Chapter
BOILERPLATE_HINTS = (
"nav", "menu", "advert", "ads", "pub", "footer", "header", "sidebar",
"comment", "watermark", "scan", "credit", "prev", "next", "previous",
"suivant", "précédent", "chapitre", "télécharger", "download",
)
SKIP_TAGS = {"script", "style", "noscript", "iframe", "form", "button"}
BLOCK_TAGS = {"p", "div", "li", "h1", "h2", "h3", "h4", "blockquote", "figcaption", "td", "section", "article"}
_DIALOGUE_RE = re.compile(r"[«»“”\"']|^-\s")
_JP_RE = re.compile(r"[぀-ヿ一-鿿]")
_ONO_RE = re.compile(r"^[A-Za-zÀ-ÿ*!?·.]+$")
def _is_boilerplate(text: str) -> bool:
t = text.strip().lower()
if not t:
return True
if len(t) < 2:
return True
return any(h in t for h in BOILERPLATE_HINTS) and len(t) < 120
def classify(text: str) -> str:
t = text.strip()
if _DIALOGUE_RE.search(t):
return "dialogue"
if _ONO_RE.match(t) and len(t) <= 16 and not t.endswith("."):
return "onomatopoeia"
return "narration"
def detect_language(text: str) -> str:
if _JP_RE.search(text):
return "ja"
words = re.findall(r"[a-zàâäéèêëîïôöùûüç']+", text.lower())
if not words:
return "unknown"
fr_words = {"le", "la", "les", "un", "une", "des", "est", "dans", "pour", "avec", "sur", "et", "de", "du", "en", "que", "qui", "pas", "au", "aux", "ce", "cette", "son", "sa", "ses", "il", "elle", "nous", "vous", "à", "était", "décide"}
en_words = {"the", "and", "is", "are", "of", "to", "in", "that", "it", "for", "on", "with", "as", "was", "this", "his", "her"}
fr = sum(1 for w in words if w in fr_words)
en = sum(1 for w in words if w in en_words)
if fr > en:
return "fr"
if en:
return "en"
return "unknown"
class _Extractor(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.chunks: list[tuple[str, str | None]] = [] # (text, img_src)
self._skip_depth = 0
self._current: list[str] = []
self._in_block = False
self._attrs: dict[str, str] = {}
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
a = {k: (v or "") for k, v in attrs}
if tag in SKIP_TAGS:
self._skip_depth += 1
return
if self._skip_depth:
return
if tag == "img":
self.chunks.append(("", a.get("src")))
return
if tag in BLOCK_TAGS:
self._flush()
self._in_block = True
self._current = []
self._attrs = a
def handle_endtag(self, tag: str) -> None:
if tag in SKIP_TAGS and self._skip_depth:
self._skip_depth -= 1
return
if self._skip_depth:
return
if tag in BLOCK_TAGS and self._in_block:
self._flush()
self._in_block = False
def handle_data(self, data: str) -> None:
if self._skip_depth:
return
if data.strip():
self._current.append(data.strip())
def _flush(self) -> None:
text = " ".join(self._current).strip()
self._current = []
if not text:
return
cls_id = (self._attrs.get("class", "") + " " + self._attrs.get("id", "")).lower()
if any(h in cls_id for h in BOILERPLATE_HINTS):
return
if _is_boilerplate(text):
return
self.chunks.append((text, None))
def close(self) -> None:
super().close()
self._flush()
def clean_chapter(raw_html: str, meta: dict[str, Any]) -> Chapter:
parser = _Extractor()
parser.feed(raw_html)
parser.close()
blocks: list[Block] = []
for text, img in parser.chunks:
if img is not None and not text:
blocks.append(Block(index=len(blocks), type="image", image=img))
elif text:
blocks.append(Block(index=len(blocks), type=classify(text), text=text))
meta = dict(meta)
meta["language"] = detect_language(" ".join(b.text for b in blocks if b.type != "image"))
return Chapter(meta=meta, blocks=blocks)
+135
View File
@@ -0,0 +1,135 @@
"""CLI Scalper : check-source, list-series, list-chapters, fetch, clean, translate, qa, export, run."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from . import legal, pipeline
from .cleaner import clean_chapter
from .exporter import export_chapter
from .models import Chapter
from .qa import qa_chapter
from .scraper import RespectfulFetcher, chapter_dir
from .sources import get_adapter
from .translator import FakeLLM, MistralChatClient, load_glossary, save_glossary, translate_chapter
def _print(data: dict) -> None:
print(json.dumps(data, ensure_ascii=False, indent=2))
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="scalper", description="Pipeline légal de scraping + traduction de chapitres manga/webtoon")
sub = p.add_subparsers(dest="cmd", required=True)
c = sub.add_parser("check-source", help="valide une source (robots.txt, licence, liste de blocage)")
c.add_argument("source")
c = sub.add_parser("list-series", help="liste les séries d'une source")
c.add_argument("source")
c = sub.add_parser("list-chapters", help="liste les chapitres d'une série")
c.add_argument("source")
c.add_argument("series")
c = sub.add_parser("fetch", help="télécharge un chapitre brut")
c.add_argument("source")
c.add_argument("series")
c.add_argument("chapter")
c.add_argument("--out", default="data")
c = sub.add_parser("clean", help="nettoie un raw.html en chapter.json")
c.add_argument("raw_html")
c.add_argument("--meta", default=None)
c.add_argument("--out", required=True)
c = sub.add_parser("translate", help="traduit un chapter.json")
c.add_argument("chapter_json")
c.add_argument("--lang", required=True)
c.add_argument("--glossary", default=None)
c.add_argument("--mock-llm", action="store_true")
c.add_argument("--out", required=True)
c = sub.add_parser("qa", help="contrôle qualité d'une traduction")
c.add_argument("source_json")
c.add_argument("translated_json")
c.add_argument("--lang", required=True)
c.add_argument("--glossary", default=None)
c = sub.add_parser("export", help="exporte un chapitre traduit")
c.add_argument("chapter_json")
c.add_argument("--format", choices=["md", "json", "html"], required=True)
c.add_argument("--out", required=True)
c = sub.add_parser("run", help="pipeline complet end-to-end")
c.add_argument("--source", required=True)
c.add_argument("--series", required=True)
c.add_argument("--lang", required=True)
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)")
args = p.parse_args(argv)
if args.cmd == "check-source":
_print(legal.check_source(args.source).to_dict())
return 0
if args.cmd == "list-series":
adapter = get_adapter(args.source)
series = adapter.list_series() if args.source == "demo" else adapter.list_series(query="")
_print([s.to_dict() for s in series])
return 0
if args.cmd == "list-chapters":
_print([c.to_dict() for c in get_adapter(args.source).list_chapters(args.series)])
return 0
if args.cmd == "fetch":
adapter = get_adapter(args.source, fetcher=RespectfulFetcher())
refs = adapter.list_chapters(args.series)
ref = next((r for r in refs if r.id == args.chapter or r.number == args.chapter), None)
if ref is None:
print(f"chapitre introuvable: {args.chapter}", file=sys.stderr)
return 1
dest = chapter_dir(Path(args.out), args.source, args.series, ref.id)
adapter.fetch_chapter(ref, dest)
_print({"fetched": ref.to_dict(), "dest": str(dest)})
return 0
if args.cmd == "clean":
meta = json.loads(Path(args.meta).read_text(encoding="utf-8")) if args.meta else {}
chapter = clean_chapter(Path(args.raw_html).read_text(encoding="utf-8"), meta)
Path(args.out).write_text(json.dumps(chapter.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
_print({"out": args.out, "blocks": len(chapter.blocks), "language": chapter.meta.get("language")})
return 0
if args.cmd == "translate":
chapter = Chapter.from_dict(json.loads(Path(args.chapter_json).read_text(encoding="utf-8")))
glossary = load_glossary(Path(args.glossary) if args.glossary else None)
client = FakeLLM() if args.mock_llm else MistralChatClient()
translated = translate_chapter(chapter, args.lang, glossary, client)
Path(args.out).write_text(json.dumps(translated.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
if args.glossary:
save_glossary(Path(args.glossary), glossary)
_print({"out": args.out, "lang": args.lang})
return 0
if args.cmd == "qa":
src = Chapter.from_dict(json.loads(Path(args.source_json).read_text(encoding="utf-8")))
tr = Chapter.from_dict(json.loads(Path(args.translated_json).read_text(encoding="utf-8")))
glossary = load_glossary(Path(args.glossary) if args.glossary else None)
report = qa_chapter(src, tr, glossary, args.lang)
_print(report)
return 0 if report["pass"] else 2
if args.cmd == "export":
chapter = Chapter.from_dict(json.loads(Path(args.chapter_json).read_text(encoding="utf-8")))
path = export_chapter(chapter, args.format, Path(args.out))
_print({"exported": str(path)})
return 0
if args.cmd == "run":
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)
_print(summary)
return 0 if summary.get("status") == "done" else 3
return 1
if __name__ == "__main__":
raise SystemExit(main())
+16
View File
@@ -0,0 +1,16 @@
<html><head><title>Demo Aventures - Chapitre 1</title></head>
<body>
<nav class="menu">Accueil | Liste des chapitres | Suivant</nav>
<div class="advert">Soutenez-nous, cliquez ici !</div>
<article>
<h1>Chapter 1 - The beginning</h1>
<p>One morning, the hero starts a new life in a small village.</p>
<p>"I will leave this place," he says.</p>
<p>He decides to find the treasure with his friends.</p>
<p>They travel through mountains and rivers.</p>
<p>BAM!</p>
<img src="images/page-1.png" alt="page 1">
<p>And so the journey begins, full of wonders, to the end.</p>
</article>
<footer>Scanlation team - chapitre précédent / chapitre suivant</footer>
</body></html>
+12
View File
@@ -0,0 +1,12 @@
<html><head><title>Demo Aventures - Chapitre 2</title></head>
<body>
<nav class="menu">Accueil | Liste des chapitres | Précédent</nav>
<article>
<h1>Chapter 2 - The mountain</h1>
<p>Every day, the hero climbs the high mountain.</p>
<p>POW! A rock falls near his friends.</p>
<p>"We are almost there," she says.</p>
<img src="images/page-2.png" alt="page 2">
</article>
<footer>Scanlation team - chapitre précédent / chapitre suivant</footer>
</body></html>
+11
View File
@@ -0,0 +1,11 @@
{
"series": [
{"id": "demo-1", "title": "Demo Aventures", "url": "demo://demo-1"}
],
"chapters": {
"demo-1": [
{"id": "demo-1-ch1", "number": "1", "title": "Le départ", "file": "chapter-1.html"},
{"id": "demo-1-ch2", "number": "2", "title": "La montagne", "file": "chapter-2.html"}
]
}
}
+86
View File
@@ -0,0 +1,86 @@
"""manga-exporter : exports Markdown / JSON / HTML avec page « source & licence »."""
from __future__ import annotations
import html
import json
import re
from pathlib import Path
from typing import Any
from .models import Chapter
def slugify(text: str) -> str:
text = re.sub(r"[^a-zA-Z0-9]+", "-", text).strip("-").lower()
return text or "chapter"
def license_block(meta: dict[str, Any]) -> str:
return (
f"> **Source et licence** — source : {meta.get('source', '?')} | "
f"licence : {meta.get('license', '?')} | "
f"récupéré le : {meta.get('fetched_at', '?')} | url : {meta.get('url', '?')}"
)
def export_markdown(chapter: Chapter, out_path: Path) -> Path:
meta = chapter.meta
lines = [
f"# {meta.get('title', 'Chapitre')}",
"",
license_block(meta),
"",
]
for b in chapter.blocks:
if b.type == "image":
lines.append(f"![{b.placeholder}]({b.image})")
elif b.type == "dialogue":
lines.append(f"> {b.text}")
else:
lines.append(b.text)
lines.append("")
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text("\n".join(lines), encoding="utf-8")
return out_path
def export_json(chapter: Chapter, out_path: Path) -> Path:
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(chapter.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
return out_path
def export_html(chapter: Chapter, out_path: Path) -> Path:
meta = chapter.meta
parts = [
"<!doctype html><html lang=\"{lang}\"><head><meta charset=\"utf-8\">",
f"<title>{html.escape(str(meta.get('title', 'Chapitre')))}</title>",
"<style>body{font-family:serif;max-width:42rem;margin:2rem auto;line-height:1.6}blockquote{border-left:3px solid #888;padding-left:1rem;color:#333}img{max-width:100%}.lic{font-size:.8rem;color:#666}</style>",
"</head><body>",
f"<h1>{html.escape(str(meta.get('title', 'Chapitre')))}</h1>",
f"<p class=\"lic\">{html.escape(license_block(meta))}</p>",
]
for b in chapter.blocks:
if b.type == "image":
parts.append(f"<p><img src=\"{html.escape(b.image or '')}\" alt=\"{b.placeholder}\"></p>")
elif b.type == "dialogue":
parts.append(f"<blockquote>{html.escape(b.text)}</blockquote>")
else:
parts.append(f"<p>{html.escape(b.text)}</p>")
parts.append("</body></html>")
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text("\n".join(parts), encoding="utf-8")
return out_path
def export_chapter(chapter: Chapter, fmt: str, out_dir: Path) -> Path:
meta = chapter.meta
base = slugify(f"{meta.get('series', '')}-{meta.get('number', '')}-{meta.get('language', '')}")
if fmt == "md":
return export_markdown(chapter, out_dir / f"{base}.md")
if fmt == "json":
return export_json(chapter, out_dir / f"{base}.json")
if fmt == "html":
return export_html(chapter, out_dir / f"{base}.html")
raise ValueError(f"format inconnu: {fmt} (md|json|html)")
+117
View File
@@ -0,0 +1,117 @@
"""legal-source-check : valide qu'une source est légale avant tout scraping.
Règles bloquantes :
- domaine dans la liste de blocage (sites de scanlation non autorisés) -> blocked
- domaine non enregistré comme source de confiance -> blocked (ajout manuel requis)
- robots.txt interdit les chemins ciblés -> blocked
- aucun contournement de paywall/captcha/authentification n'est jamais tenté
"""
from __future__ import annotations
import urllib.robotparser
import urllib.request
from dataclasses import asdict, dataclass
from typing import Any
from urllib.parse import urlparse
USER_AGENT = "Scalper/1.0 (+https://github.com/Orionis312050/Scalper)"
BLOCKED_DOMAINS: dict[str, str] = {
"mangas-origines.fr": "site de scanlation non autorisé (contrefaçon de mangas commerciaux)",
}
BLOCKED_SUBSTRINGS = ("mangas-origines",)
TRUSTED_SOURCES: dict[str, dict[str, str]] = {
"api.mangadex.org": {
"license": "API officielle MangaDex (données publiques ; images selon licence de l'œuvre)",
"kind": "official-api",
},
"demo": {
"license": "fixture de test interne (texte inventé, domaine public)",
"kind": "local-fixture",
},
}
@dataclass
class Verdict:
source: str
verdict: str # "allowed" | "blocked"
reasons: list[str]
license: str
@property
def allowed(self) -> bool:
return self.verdict == "allowed"
def to_dict(self) -> dict[str, Any]:
return asdict(self)
def domain_of(url_or_id: str) -> str:
if "://" not in url_or_id:
return url_or_id.lower()
return (urlparse(url_or_id).netloc or url_or_id).lower()
def _fetch_robots_txt(domain: str) -> str | None:
url = f"https://{domain}/robots.txt"
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.read().decode("utf-8", errors="replace")
except Exception:
return None
def robots_allow(domain: str, path: str = "/") -> tuple[bool, str]:
"""Retourne (autorisé, note). Si robots.txt est inaccessible, le défaut du
standard robots.txt s'applique : autorisé, avec une note."""
content = _fetch_robots_txt(domain)
if content is None:
return True, "robots.txt inaccessible : défaut autorisé (standard robots.txt)"
rp = urllib.robotparser.RobotFileParser()
rp.parse(content.splitlines())
ok = rp.can_fetch(USER_AGENT, f"https://{domain}{path}")
return ok, "robots.txt vérifié" if ok else f"robots.txt interdit le chemin {path}"
def check_source(source: str, path: str = "/") -> Verdict:
"""Vérifie une source (id local 'demo' ou URL/domaine)."""
domain = domain_of(source)
for sub in BLOCKED_SUBSTRINGS:
if sub in domain:
return Verdict(
source=source,
verdict="blocked",
reasons=[f"liste de blocage : {BLOCKED_DOMAINS.get(domain, sub)}"],
license="",
)
trusted = TRUSTED_SOURCES.get(domain)
if trusted is None:
return Verdict(
source=source,
verdict="blocked",
reasons=[
"source non enregistrée : ajoutez-la manuellement dans TRUSTED_SOURCES "
"avec sa licence après vérification (robots.txt, CGU, licence CC/domaine public/API officielle)"
],
license="",
)
reasons: list[str] = []
if trusted["kind"] != "local-fixture":
ok, note = robots_allow(domain, path)
reasons.append(note)
if not ok:
return Verdict(source=source, verdict="blocked", reasons=reasons, license=trusted["license"])
return Verdict(
source=source,
verdict="allowed",
reasons=reasons or ["source de confiance enregistrée"],
license=trusted["license"],
)
+79
View File
@@ -0,0 +1,79 @@
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from typing import Any
BLOCK_TYPES = ("dialogue", "narration", "caption", "onomatopoeia", "image")
@dataclass
class Series:
id: str
title: str
url: str
license: str
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass
class ChapterRef:
id: str
number: str
title: str
url: str
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass
class Block:
index: int
type: str
text: str = ""
image: str | None = None
@property
def placeholder(self) -> str | None:
if self.type == "image":
return f"[IMG:{self.index}]"
return None
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "Block":
return cls(
index=int(d["index"]),
type=d["type"],
text=d.get("text", ""),
image=d.get("image"),
)
@dataclass
class Chapter:
meta: dict[str, Any] = field(default_factory=dict)
blocks: list[Block] = field(default_factory=list)
def text_blocks(self) -> list[Block]:
return [b for b in self.blocks if b.type != "image"]
def placeholders(self) -> list[str]:
return [b.placeholder for b in self.blocks if b.placeholder]
def full_text(self) -> str:
return "\n".join(b.text for b in self.text_blocks())
def to_dict(self) -> dict[str, Any]:
return {"meta": self.meta, "blocks": [b.to_dict() for b in self.blocks]}
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "Chapter":
return cls(
meta=dict(d.get("meta", {})),
blocks=[Block.from_dict(b) for b in d.get("blocks", [])],
)
+82
View File
@@ -0,0 +1,82 @@
"""Orchestration : legal-source-check -> scrape -> clean -> translate -> QA -> export."""
from __future__ import annotations
import json
import time
from pathlib import Path
from typing import Any
from . import legal
from .cleaner import clean_chapter
from .exporter import export_chapter
from .models import Chapter
from .qa import qa_chapter
from .scraper import RespectfulFetcher, RunState, chapter_dir
from .sources import get_adapter
from .translator import FakeLLM, LLMClient, MistralChatClient, load_glossary, save_glossary, translate_chapter
def run_pipeline(
source_id: str,
series_id: str,
lang: str,
out_root: Path | str = Path("out"),
mock_llm: bool = False,
fetcher: RespectfulFetcher | None = None,
max_chapters: int | None = None,
) -> dict[str, Any]:
out_root = Path(out_root)
verdict = legal.check_source(source_id)
if not verdict.allowed:
return {"status": "blocked", "verdict": verdict.to_dict()}
fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
adapter = get_adapter(source_id, fetcher=fetcher)
chapters = adapter.list_chapters(series_id)
if max_chapters is not None:
chapters = chapters[:max_chapters]
glossary_path = out_root / "glossary.json"
glossary = load_glossary(glossary_path)
client: LLMClient = FakeLLM() if mock_llm else MistralChatClient()
state = RunState(out_root / "state.json")
results: list[dict[str, Any]] = []
for ref in chapters:
entry: dict[str, Any] = {"chapter": ref.to_dict()}
if state.is_fetched(ref.id):
entry["skipped"] = "déjà récupéré (state.json)"
else:
dest = chapter_dir(out_root, source_id, series_id, ref.id)
adapter.fetch_chapter(ref, dest)
meta = json.loads((dest / "meta.json").read_text(encoding="utf-8"))
meta["fetched_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
meta["series"] = series_id
meta["number"] = ref.number
meta["title"] = ref.title
meta["url"] = ref.url
raw = (dest / "raw.html").read_text(encoding="utf-8")
chapter = clean_chapter(raw, meta)
(dest / "chapter.json").write_text(json.dumps(chapter.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
state.mark_fetched(ref.id)
entry["blocks"] = len(chapter.blocks)
translated = translate_chapter(chapter, lang, glossary, client)
(dest / f"chapter.{lang}.json").write_text(
json.dumps(translated.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8"
)
report = qa_chapter(chapter, translated, glossary, lang)
(dest / f"qa.{lang}.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
entry["qa"] = {"score": report["score"], "pass": report["pass"], "issues": len(report["issues"])}
if report["pass"]:
for fmt in ("md", "json", "html"):
export_chapter(translated, fmt, dest / "export")
state.mark_done(ref.id)
entry["status"] = "ok"
else:
entry["status"] = "qa_failed"
results.append(entry)
save_glossary(glossary_path, glossary)
return {"status": "done", "source": source_id, "series": series_id, "lang": lang, "chapters": results}
+52
View File
@@ -0,0 +1,52 @@
"""translation-qa : contrôles qualité et score d'une traduction."""
from __future__ import annotations
from typing import Any
from .cleaner import detect_language
from .models import Chapter
MIN_RATIO = 0.5
MAX_RATIO = 2.5
def qa_chapter(source: Chapter, translated: Chapter, glossary: dict[str, str], target_lang: str) -> dict[str, Any]:
issues: list[dict[str, Any]] = []
critical = False
if len(source.blocks) != len(translated.blocks):
issues.append({"type": "block_count", "critical": True, "detail": f"{len(source.blocks)} blocs source vs {len(translated.blocks)} traduits"})
critical = True
src_ph = source.placeholders()
tr_ph = translated.placeholders()
if src_ph != tr_ph:
issues.append({"type": "placeholders", "critical": True, "detail": f"placeholders source {src_ph} != traduits {tr_ph}"})
critical = True
for b in translated.text_blocks():
if not b.text.strip():
issues.append({"type": "empty_block", "critical": True, "block": b.index, "detail": "bloc traduit vide"})
critical = True
src_text = source.full_text()
tr_text = translated.full_text()
for term, trad in glossary.items():
if term in src_text and trad not in tr_text:
issues.append({"type": "glossary", "critical": True, "block": None, "detail": f"'{term}' devrait être traduit par '{trad}'"})
ratio = (len(tr_text) / len(src_text)) if src_text else 1.0
if not (MIN_RATIO <= ratio <= MAX_RATIO):
issues.append({"type": "length_ratio", "critical": False, "detail": f"ratio {ratio:.2f} hors [{MIN_RATIO}, {MAX_RATIO}]"})
detected = detect_language(tr_text)
if detected not in (target_lang, "unknown"):
issues.append({"type": "wrong_language", "critical": True, "detail": f"langue détectée '{detected}' != cible '{target_lang}'"})
critical = True
score = 100
for i in issues:
score -= 25 if i.get("critical") else 8
score = max(0, score)
return {"score": score, "issues": issues, "pass": score >= 80 and not critical, "target_lang": target_lang}
+81
View File
@@ -0,0 +1,81 @@
"""manga-scraper : récupération respectueuse (rate limiting, backoff, reprise)."""
from __future__ import annotations
import json
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any
from .legal import USER_AGENT
class FetchError(Exception):
pass
class RespectfulFetcher:
"""HTTP GET avec >= min_delay entre requêtes, 1 concurrence, backoff sur 429/5xx."""
def __init__(self, min_delay: float = 1.0, max_retries: int = 3, timeout: float = 30.0) -> None:
self.min_delay = min_delay
self.max_retries = max_retries
self.timeout = timeout
self._last_request = 0.0
def _wait(self) -> None:
elapsed = time.monotonic() - self._last_request
if elapsed < self.min_delay:
time.sleep(self.min_delay - elapsed)
self._last_request = time.monotonic()
def get(self, url: str) -> bytes:
last_err: Exception | None = None
for attempt in range(self.max_retries):
self._wait()
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
try:
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
return resp.read()
except urllib.error.HTTPError as e:
last_err = e
if e.code in (429, 500, 502, 503, 504) and attempt < self.max_retries - 1:
time.sleep(2**attempt)
continue
raise FetchError(f"HTTP {e.code} pour {url}") from e
except urllib.error.URLError as e:
raise FetchError(f"erreur réseau pour {url}: {e}") from e
raise FetchError(f"échec après {self.max_retries} tentatives pour {url}: {last_err}")
class RunState:
"""État resumable d'un run (state.json)."""
def __init__(self, path: Path) -> None:
self.path = path
self.data: dict[str, Any] = {"fetched": [], "done": []}
if path.exists():
self.data = json.loads(path.read_text(encoding="utf-8"))
def is_fetched(self, chapter_id: str) -> bool:
return chapter_id in self.data["fetched"]
def mark_fetched(self, chapter_id: str) -> None:
if chapter_id not in self.data["fetched"]:
self.data["fetched"].append(chapter_id)
self.save()
def mark_done(self, chapter_id: str) -> None:
if chapter_id not in self.data["done"]:
self.data["done"].append(chapter_id)
self.save()
def save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8")
def chapter_dir(out_root: Path, source: str, series: str, chapter_id: str) -> Path:
return out_root / "raw" / source / series / chapter_id
+20
View File
@@ -0,0 +1,20 @@
from __future__ import annotations
from ..scraper import RespectfulFetcher
from .base import SourceAdapter
from .demo import DemoAdapter
from .mangadex import MangaDexAdapter
def get_adapter(source_id: str, fetcher: RespectfulFetcher | None = None) -> SourceAdapter:
if source_id == "demo":
return DemoAdapter()
if source_id == "mangadex":
return MangaDexAdapter(fetcher=fetcher)
raise KeyError(
f"adaptateur inconnu: {source_id}. Sources disponibles : demo, mangadex. "
"Pour ajouter une source légale, voir docs/add-a-source.md."
)
__all__ = ["SourceAdapter", "get_adapter", "DemoAdapter", "MangaDexAdapter"]
+21
View File
@@ -0,0 +1,21 @@
from __future__ import annotations
from pathlib import Path
from typing import Protocol
from ..models import ChapterRef, Series
class SourceAdapter(Protocol):
"""Contrat d'un adaptateur de source légale."""
id: str
license: str
def list_series(self) -> list[Series]: ...
def list_chapters(self, series_id: str) -> list[ChapterRef]: ...
def fetch_chapter(self, chapter: ChapterRef, dest_dir: Path) -> None:
"""Télécharge le chapitre brut (HTML + images) dans dest_dir."""
...
+60
View File
@@ -0,0 +1,60 @@
"""Adaptateur 'demo' : fixture locale (texte inventé, domaine public).
Permet de faire tourner le pipeline de bout en bout hors ligne.
"""
from __future__ import annotations
import json
import shutil
from importlib import resources
from pathlib import Path
from ..models import ChapterRef, Series
class DemoAdapter:
id = "demo"
license = "fixture de test interne (texte inventé, domaine public)"
def _data_dir(self) -> Path:
return Path(str(resources.files("scalper") / "data" / "demo"))
def _index(self) -> dict:
return json.loads((self._data_dir() / "series.json").read_text(encoding="utf-8"))
def list_series(self) -> list[Series]:
idx = self._index()
return [Series(id=s["id"], title=s["title"], url=s["url"], license=self.license) for s in idx["series"]]
def list_chapters(self, series_id: str) -> list[ChapterRef]:
idx = self._index()
chapters = idx["chapters"].get(series_id, [])
return [
ChapterRef(id=c["id"], number=c["number"], title=c["title"], url=f"demo://{series_id}/{c['id']}")
for c in chapters
]
def fetch_chapter(self, chapter: ChapterRef, dest_dir: Path) -> None:
idx = self._index()
src_file = None
for c in idx["chapters"].get(chapter.id.rsplit("-ch", 1)[0] if "-ch" in chapter.id else "", []):
if c["id"] == chapter.id:
src_file = self._data_dir() / c["file"]
if src_file is None:
for chapters in idx["chapters"].values():
for c in chapters:
if c["id"] == chapter.id:
src_file = self._data_dir() / c["file"]
if src_file is None or not src_file.exists():
raise FileNotFoundError(f"chapitre de démo introuvable: {chapter.id}")
dest_dir.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src_file, dest_dir / "raw.html")
(dest_dir / "meta.json").write_text(
json.dumps(
{"source": self.id, "license": self.license, "chapter": chapter.to_dict()},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
+96
View File
@@ -0,0 +1,96 @@
"""Adaptateur API officielle MangaDex (https://api.mangadex.org) — source légale.
L'API publique ne nécessite pas de clé pour la lecture. Rate limiting appliqué.
"""
from __future__ import annotations
import json
from pathlib import Path
from ..models import ChapterRef, Series
from ..scraper import RespectfulFetcher
API = "https://api.mangadex.org"
class MangaDexAdapter:
id = "mangadex"
license = "API officielle MangaDex (données publiques ; images selon licence de l'œuvre)"
def __init__(self, fetcher: RespectfulFetcher | None = None) -> None:
self.fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
def _get_json(self, path: str, params: dict[str, str] | None = None) -> dict:
url = API + path
if params:
from urllib.parse import urlencode
url += "?" + urlencode(params)
return json.loads(self.fetcher.get(url).decode("utf-8"))
def list_series(self, query: str = "", limit: int = 20) -> list[Series]:
params = {"limit": str(limit), "order[relevance]": "desc", "includes[]": "cover_art"}
if query:
params["title"] = query
data = self._get_json("/manga", params)
return [
Series(
id=m["id"],
title=m["attributes"]["title"].get("en") or next(iter(m["attributes"]["title"].values())),
url=f"https://mangadex.org/title/{m['id']}",
license=self.license,
)
for m in data.get("data", [])
]
def list_chapters(self, series_id: str, limit: int = 100) -> list[ChapterRef]:
data = self._get_json(
f"/manga/{series_id}/feed",
{
"limit": str(limit),
"translatedLanguage[]": "en",
"order[chapter]": "asc",
"contentRating[]": "safe",
"contentRating[]": "suggestive",
},
)
refs = []
for c in data.get("data", []):
attrs = c["attributes"]
refs.append(
ChapterRef(
id=c["id"],
number=attrs.get("chapter") or "?",
title=attrs.get("title") or f"Chapter {attrs.get('chapter', '?')}",
url=f"https://mangadex.org/chapter/{c['id']}",
)
)
return refs
def fetch_chapter(self, chapter: ChapterRef, dest_dir: Path) -> None:
dest_dir.mkdir(parents=True, exist_ok=True)
at_home = self._get_json(f"/at-home/server/{chapter.id}")
base = at_home["baseUrl"]
data = self._get_json(f"/chapter/{chapter.id}")
attrs = data["data"]["attributes"]
chapter_hash = attrs["hash"]
pages = attrs.get("pages", 0)
files = attrs.get("data", []) + attrs.get("dataSaver", [])
lines = [f"# raw chapter {chapter.id} ({chapter.title})", ""]
img_dir = dest_dir / "images"
img_dir.mkdir(exist_ok=True)
quality = "data-saver" if attrs.get("dataSaver") else "data"
for i, fname in enumerate(files, start=1):
url = f"{base}/{quality}/{chapter_hash}/{fname}"
(img_dir / fname).write_bytes(self.fetcher.get(url))
lines.append(f"![page {i}](images/{fname})")
(dest_dir / "raw.html").write_text("\n".join(lines), encoding="utf-8")
(dest_dir / "meta.json").write_text(
json.dumps(
{"source": self.id, "license": self.license, "chapter": chapter.to_dict(), "pages": pages},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
+143
View File
@@ -0,0 +1,143 @@
"""llm-translator : traduction via LLM avec glossaire et chunking."""
from __future__ import annotations
import json
import os
import urllib.request
from pathlib import Path
from typing import Any, Protocol
from .models import Block, Chapter
DEFAULT_MODEL = "mistral-small-latest"
MAX_CHUNK_CHARS = 6000
SYSTEM_PROMPT = """Tu es un traducteur littéraire professionnel de mangas/webtoons.
Traduis le texte vers {target_lang}. Règles :
1. Ne traduis jamais les placeholders [IMG:n] ni les URLs.
2. Respecte strictement le glossaire fourni pour les noms propres, lieux et termes récurrents.
3. Conserve le ton et le registre (dialogue vs narration).
4. Ne rajoute aucune explication ni commentaire : uniquement le texte traduit, un bloc par ligne.
5. Conserve la ponctuation et la casse des onomatopées autant que possible."""
class LLMClient(Protocol):
def complete(self, system: str, user: str) -> str: ...
class MistralChatClient:
"""Client API Mistral (clé via MISTRAL_API_KEY, jamais écrite dans le code)."""
def __init__(self, model: str | None = None, api_key: str | None = None, api_url: str = "https://api.mistral.ai/v1") -> None:
self.model = model or os.environ.get("MISTRAL_MODEL", DEFAULT_MODEL)
self.api_key = api_key or os.environ.get("MISTRAL_API_KEY")
if not self.api_key:
raise RuntimeError("MISTRAL_API_KEY manquante (variable d'environnement requise)")
self.api_url = api_url.rstrip("/")
def complete(self, system: str, user: str) -> str:
payload = {
"model": self.model,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": user},
],
"temperature": 0.3,
}
req = urllib.request.Request(
f"{self.api_url}/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
data = json.loads(resp.read().decode("utf-8"))
return data["choices"][0]["message"]["content"].strip()
class FakeLLM:
"""LLM déterministe hors ligne pour tests et démo (--mock-llm)."""
DICT = {
"the": "le", "a": "un", "an": "un", "and": "et", "is": "est", "was": "était",
"of": "de", "to": "à", "in": "dans", "on": "sur", "with": "avec", "his": "son",
"her": "sa", "he": "il", "she": "elle", "they": "ils", "it": "il", "his friends": "ses amis",
"hero": "héros", "starts": "commence", "journey": "voyage", "chapter": "chapitre",
"one": "un", "new": "nouveau", "life": "vie", "decides": "décide", "leave": "quitter",
"village": "village", "find": "trouver", "treasure": "trésor", "travel": "voyagent",
"through": "à travers", "mountains": "montagnes", "rivers": "rivières", "end": "fin",
"day": "jour", "every": "chaque", "morning": "matin", "world": "monde", "full": "plein",
"of wonders": "de merveilles", "bang": "BAM", "pow": "POW",
}
def complete(self, system: str, user: str) -> str:
out_lines = []
for line in user.splitlines():
words = line.split(" ")
out_lines.append(" ".join(self.DICT.get(w.lower().strip(".,!?"), w) for w in words))
return "\n".join(out_lines)
def load_glossary(path: Path | None) -> dict[str, str]:
if path and path.exists():
return json.loads(path.read_text(encoding="utf-8"))
return {}
def save_glossary(path: Path, glossary: dict[str, str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(glossary, ensure_ascii=False, indent=2), encoding="utf-8")
def chunk_blocks(blocks: list[Block], max_chars: int = MAX_CHUNK_CHARS) -> list[list[Block]]:
chunks: list[list[Block]] = []
current: list[Block] = []
size = 0
for b in blocks:
n = len(b.text) + 1
if current and size + n > max_chars:
chunks.append(current)
current, size = [], 0
current.append(b)
size += n
if current:
chunks.append(current)
return chunks
def translate_chapter(
chapter: Chapter,
target_lang: str,
glossary: dict[str, str],
client: LLMClient,
) -> Chapter:
text_blocks = chapter.text_blocks()
image_blocks = [b for b in chapter.blocks if b.type == "image"]
glossary_str = "\n".join(f"- {k} -> {v}" for k, v in sorted(glossary.items())) or "(vide)"
system = SYSTEM_PROMPT.format(target_lang=target_lang)
translated: dict[int, str] = {}
for chunk in chunk_blocks(text_blocks):
user = (
f"Glossaire:\n{glossary_str}\n\nTexte à traduire ({len(chunk)} blocs, un par ligne) :\n"
+ "\n".join(b.text for b in chunk)
)
reply = client.complete(system, user)
lines = [ln for ln in reply.splitlines() if ln.strip()]
if len(lines) != len(chunk):
lines = (lines + [""] * len(chunk))[: len(chunk)]
for b, ln in zip(chunk, lines):
translated[b.index] = ln.strip()
new_blocks: list[Block] = []
for b in chapter.blocks:
if b.type == "image":
new_blocks.append(Block(index=b.index, type="image", image=b.image))
else:
new_blocks.append(Block(index=b.index, type=b.type, text=translated.get(b.index, b.text)))
meta = dict(chapter.meta)
meta["language"] = target_lang
meta["translated_from"] = chapter.meta.get("language", "unknown")
return Chapter(meta=meta, blocks=new_blocks)