From 876faf3ede0c07aa199aa77b145ee072d9d509b8 Mon Sep 17 00:00:00 2001 From: Vibe Date: Mon, 16 Nov 2026 11:05:11 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20registre=20de=20sources=20personnalis?= =?UTF-8?q?=C3=A9es=20(sources.toml)=20+=20commande=20fetch-url=20(SCAL-14?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - --config sources.toml: domaine + license OBLIGATOIRE, robots.txt vérifié - liste de blocage inviolable (test: keiyoushi/mangas-origines restent blocked même déclarés) - scalper fetch-url : lien direct soumis au gate légal, produit raw/meta/chapter.json - 33 tests OK --- README.md | 7 +++++- docs/add-a-source.md | 37 ++++++++++++++++++++++++----- sources.example.toml | 14 +++++++++++ src/scalper/cli.py | 33 +++++++++++++++++++++++++- src/scalper/legal.py | 32 ++++++++++++++++++++++--- tests/test_registry.py | 54 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 166 insertions(+), 11 deletions(-) create mode 100644 sources.example.toml create mode 100644 tests/test_registry.py diff --git a/README.md b/README.md index 11d8c0a..0ce76eb 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | `scalper check-source ` | verdict légal (allowed/blocked + raisons) | | `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 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 | @@ -53,7 +54,11 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out ## Ajouter une source légale -Voir [docs/add-a-source.md](docs/add-a-source.md) et la politique des sources légales : +Voir [docs/add-a-source.md](docs/add-a-source.md) : registre déclaratif `sources.toml` +(licence obligatoire par domaine) ou lien direct `fetch-url`, plus adaptateur dédié. +La liste de blocage (mangas-origines, keiyoushi.github.io…) n'est **pas contournable**. + +## Politique des sources légales [docs/legal-sources.md](docs/legal-sources.md). ## Tests & CI diff --git a/docs/add-a-source.md b/docs/add-a-source.md index 38991d3..513b6a0 100644 --- a/docs/add-a-source.md +++ b/docs/add-a-source.md @@ -1,10 +1,32 @@ -# Ajouter une source légale +## Deux façons d'ajouter une source -1. **Vérification manuelle** : licence (API officielle / CC / domaine public / contenu propre), - CGU (pas d'interdiction de scraping), `robots.txt` autorisant les chemins ciblés. -2. **Enregistrement** : ajouter le domaine dans `TRUSTED_SOURCES` (`src/scalper/legal.py`) - avec sa licence. Sans cet enregistrement, la source est **bloquée** par défaut. -3. **Adaptateur** : implémenter le contrat `SourceAdapter` (`src/scalper/sources/base.py`) : +### 1. Registre déclaratif (recommandé) — `sources.toml` + +Déclare le domaine avec sa **licence obligatoire** (le pipeline refuse toute source sans licence) : + +```toml +[source."exemple-domaine-public.fr"] +license = "Domaine public (œuvres tombées dans le domaine public)" +kind = "html" +``` + +Utilisation : `scalper --config sources.toml check-source https://exemple-domaine-public.fr/...` + +Règles inviolables : robots.txt vérifié, liste de blocage prioritaire (aucune config ne peut +autoriser mangas-origines.fr / keiyoushi.github.io), aucun contournement de paywall. + +### 2. Lien direct — `fetch-url` + +```bash +scalper --config sources.toml fetch-url "https://exemple-domaine-public.fr/manga/x/chapitre-1" --out data +``` + +Le lien passe par `legal-source-check` (licence déclarée + robots.txt + liste de blocage) : +s'il est bloqué, rien n'est téléchargé. Produit `raw.html` + `meta.json` + `chapter.json`. + +## Adaptateur dédié + +Pour une source récurrente, implémenter le contrat `SourceAdapter` (`src/scalper/sources/base.py`) : - `list_series() -> list[Series]` - `list_chapters(series_id) -> list[ChapterRef]` - `fetch_chapter(chapter, dest_dir)` : écrit le brut dans `dest_dir` (raw.html + images + meta.json) @@ -13,4 +35,7 @@ 5. **Tests** : ajouter un test hors ligne (fixtures mockées, aucun appel réseau en test). 6. **PR** : ouvrir une PR liée au ticket Jira correspondant (projet SCAL). +> ⚠️ Les index d'extensions de scanlation (keiyoushi.github.io) et les sites de scanlation +> non autorisés (mangas-origines.fr) sont **bloqués** et ne peuvent pas être autorisés via la config. + Exemple d'adaptateur légal existant : `src/scalper/sources/mangadex.py` (API officielle). diff --git a/sources.example.toml b/sources.example.toml new file mode 100644 index 0000000..27fb2ba --- /dev/null +++ b/sources.example.toml @@ -0,0 +1,14 @@ +# Registre de sources personnalisées pour Scalper. +# Chaque domaine DOIT déclarer sa licence (obligatoire) et passe toujours +# par robots.txt + liste de blocage (non contournable). +# +# Exemple : +# [source."exemple-domaine-public.fr"] +# license = "Domaine public (œuvres tombées dans le domaine public)" +# kind = "html" +# +# [source."api.oeuvres-cc.example"] +# license = "API officielle — contenus Creative Commons CC BY 4.0" +# kind = "api" + +[source] diff --git a/src/scalper/cli.py b/src/scalper/cli.py index 6c74622..b892c15 100644 --- a/src/scalper/cli.py +++ b/src/scalper/cli.py @@ -5,11 +5,12 @@ from __future__ import annotations import argparse import json import sys +import time from pathlib import Path from . import legal, pipeline from .cleaner import clean_chapter -from .exporter import export_chapter +from .exporter import export_chapter, slugify from .models import Chapter from .qa import qa_chapter from .scraper import RespectfulFetcher, chapter_dir @@ -23,6 +24,7 @@ def _print(data: dict) -> None: def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="scalper", description="Pipeline légal de scraping + traduction de chapitres manga/webtoon") + p.add_argument("--config", default=None, help="registre de sources personnalisées (TOML, ex. sources.example.toml)") sub = p.add_subparsers(dest="cmd", required=True) c = sub.add_parser("check-source", help="valide une source (robots.txt, licence, liste de blocage)") @@ -71,6 +73,10 @@ def main(argv: list[str] | None = None) -> int: c.add_argument("--format", choices=["md", "json", "html"], required=True) c.add_argument("--out", required=True) + c = sub.add_parser("fetch-url", help="récupère un lien direct (soumis à legal-source-check : licence déclarée + robots.txt + liste de blocage)") + c.add_argument("url") + c.add_argument("--out", default="data") + c = sub.add_parser("run", help="pipeline complet end-to-end") c.add_argument("--source", required=True) c.add_argument("--series", required=True) @@ -82,6 +88,9 @@ def main(argv: list[str] | None = None) -> int: args = p.parse_args(argv) + if getattr(args, "config", None): + legal.load_config(args.config) + if args.cmd == "check-source": _print(legal.check_source(args.source).to_dict()) return 0 @@ -149,6 +158,28 @@ def main(argv: list[str] | None = None) -> int: path = export_chapter(chapter, args.format, Path(args.out)) _print({"exported": str(path)}) return 0 + if args.cmd == "fetch-url": + verdict = legal.check_source(args.url) + if not verdict.allowed: + _print({"status": "blocked", "verdict": verdict.to_dict()}) + return 3 + fetcher = RespectfulFetcher() + html = fetcher.get(args.url).decode("utf-8", errors="replace") + domain = legal.domain_of(args.url) + dest = Path(args.out) / "raw" / domain / slugify(args.url) + dest.mkdir(parents=True, exist_ok=True) + (dest / "raw.html").write_text(html, encoding="utf-8") + meta = { + "source": domain, + "license": verdict.license, + "url": args.url, + "fetched_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + (dest / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8") + chapter = clean_chapter(html, meta) + (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 == "run": summary = pipeline.run_pipeline( args.source, args.series, args.lang, diff --git a/src/scalper/legal.py b/src/scalper/legal.py index d881e29..60412ab 100644 --- a/src/scalper/legal.py +++ b/src/scalper/legal.py @@ -35,6 +35,32 @@ TRUSTED_SOURCES: dict[str, dict[str, str]] = { }, } +# Sources personnalisées déclarées par l'utilisateur (sources.toml). +# La liste de blocage a TOUJOURS priorité sur ce registre : aucune config ne +# peut autoriser un domaine bloqué. +CUSTOM_SOURCES: dict[str, dict[str, str]] = {} + + +def register_custom_sources(entries: dict[str, dict]) -> None: + """Enregistre des sources personnalisées. Champ 'license' obligatoire.""" + for domain, cfg in entries.items(): + lic = str(cfg.get("license", "")).strip() + if not lic: + raise ValueError( + f"source '{domain}': le champ 'license' est obligatoire " + "(API officielle, CC, domaine public ou contenu propre)" + ) + CUSTOM_SOURCES[domain.lower()] = {"license": lic, "kind": str(cfg.get("kind", "html"))} + + +def load_config(path: str) -> None: + """Charge un registre de sources TOML : [source."domaine"] license = "..." kind = "...".""" + import tomllib + from pathlib import Path + + data = tomllib.loads(Path(path).read_text(encoding="utf-8")) + register_custom_sources(data.get("source", {})) + @dataclass class Verdict: @@ -92,14 +118,14 @@ def check_source(source: str, path: str = "/") -> Verdict: license="", ) - trusted = TRUSTED_SOURCES.get(domain) + trusted = TRUSTED_SOURCES.get(domain) or CUSTOM_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)" + "source non enregistrée : déclarez-la dans sources.toml (champ 'license' obligatoire) " + "après vérification manuelle (robots.txt, CGU, licence CC/domaine public/API officielle)" ], license="", ) diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 0000000..c4f4679 --- /dev/null +++ b/tests/test_registry.py @@ -0,0 +1,54 @@ +import unittest +from unittest import mock + +from scalper import legal + +ALLOW_ALL = "User-agent: *\nAllow: /\n" + + +class TestCustomSourceRegistry(unittest.TestCase): + def setUp(self): + legal.CUSTOM_SOURCES.clear() + + def tearDown(self): + legal.CUSTOM_SOURCES.clear() + + def test_custom_source_with_license_allowed(self): + with mock.patch.object(legal, "_fetch_robots_txt", return_value=ALLOW_ALL): + legal.register_custom_sources({"exemple-cc.fr": {"license": "CC BY 4.0", "kind": "html"}}) + v = legal.check_source("https://exemple-cc.fr/manga/x") + self.assertTrue(v.allowed) + self.assertEqual(v.license, "CC BY 4.0") + + def test_custom_source_without_license_rejected(self): + with self.assertRaises(ValueError): + legal.register_custom_sources({"pirate.example": {"kind": "html"}}) + self.assertNotIn("pirate.example", legal.CUSTOM_SOURCES) + + def test_blocklist_wins_over_config(self): + with mock.patch.object(legal, "_fetch_robots_txt", return_value=ALLOW_ALL): + legal.register_custom_sources( + {"mangas-origines.fr": {"license": "CC BY 4.0"}, "keiyoushi.github.io": {"license": "CC BY 4.0"}} + ) + for url in ("https://mangas-origines.fr/", "https://keiyoushi.github.io/"): + v = legal.check_source(url) + self.assertFalse(v.allowed, url) + + def test_unknown_source_still_blocked(self): + v = legal.check_source("https://inconnu.example/") + self.assertFalse(v.allowed) + + def test_robots_disallow_blocks_custom_source(self): + robots = "User-agent: *\nDisallow: /manga/\n" + with mock.patch.object(legal, "_fetch_robots_txt", return_value=robots): + legal.register_custom_sources({"exemple.fr": {"license": "Domaine public"}}) + v = legal.check_source("https://exemple.fr/manga/x", path="/manga/x") + self.assertFalse(v.allowed) + self.assertIn("robots.txt interdit", v.reasons[-1]) + + def test_demo_still_allowed(self): + self.assertTrue(legal.check_source("demo").allowed) + + +if __name__ == "__main__": + unittest.main()