feat: registre de sources personnalisées (sources.toml) + commande fetch-url (SCAL-14)
- --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 <url>: lien direct soumis au gate légal, produit raw/meta/chapter.json - 33 tests OK
This commit is contained in:
1 parent
5177ddedc5
commit
876faf3ede
6 files changed
+166
-11
No files matched your search
@@ -34,6 +34,7 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
||||
| `scalper check-source <url>` | verdict légal (allowed/blocked + raisons) |
|
||||
| `scalper list-series <source>` / `list-chapters <source> <series> [--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 <url>` | lien direct (gate légal : licence déclarée + robots.txt + blocage) |
|
||||
| `scalper fetch <source> <series> <chapitre>` | téléchargement brut + `state.json` (reprise) |
|
||||
| `scalper clean <raw.html> --out chapter.json` | nettoyage/structuration en blocs typés |
|
||||
| `scalper translate <chapter.json> --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
|
||||
|
||||
+31
-6
@@ -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).
|
||||
@@ -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]
|
||||
+32
-1
@@ -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,
|
||||
|
||||
+29
-3
@@ -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="",
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user