From d0a95adeb97f76c621c395b1156dfc8632e4fc72 Mon Sep 17 00:00:00 2001 From: Orionis Date: Mon, 16 Nov 2026 21:42:28 +0100 Subject: [PATCH] =?UTF-8?q?:sparkles:=20Suppression=20de=20la=20partie=20l?= =?UTF-8?q?=C3=A9gal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 1 - .env.example | 3 - .github/PULL_REQUEST_TEMPLATE.md | 6 +- README.md | 40 ++------ docker-compose.yml | 10 +- docs/add-a-source.md | 35 ++----- docs/deploy-coolify.md | 15 +-- docs/legal-sources.md | 36 ------- pyproject.toml | 2 +- skills/legal-source-check/SKILL.md | 18 ---- skills/manga-exporter/SKILL.md | 4 +- skills/manga-scraper/SKILL.md | 4 +- sources.example.toml | 14 --- src/scalper/__init__.py | 2 +- src/scalper/agents/main.py | 18 ++-- src/scalper/agents/tools.py | 10 +- src/scalper/cli.py | 42 ++------ src/scalper/exporter.py | 16 +-- src/scalper/legal.py | 158 ----------------------------- src/scalper/models.py | 1 - src/scalper/ocr.py | 6 +- src/scalper/pipeline.py | 9 +- src/scalper/scraper.py | 2 +- src/scalper/server.py | 33 +----- src/scalper/sources/__init__.py | 2 +- src/scalper/sources/base.py | 3 +- src/scalper/sources/demo.py | 7 +- src/scalper/sources/mangadex.py | 11 +- src/scalper/typeset.py | 2 - tests/test_cleaner.py | 2 +- tests/test_legal.py | 38 ------- tests/test_ocr_typeset.py | 12 --- tests/test_pipeline_exporter.py | 11 +- tests/test_registry.py | 54 ---------- tests/test_server.py | 16 --- tests/test_translator_qa.py | 2 +- 36 files changed, 73 insertions(+), 572 deletions(-) delete mode 100644 docs/legal-sources.md delete mode 100644 skills/legal-source-check/SKILL.md delete mode 100644 sources.example.toml delete mode 100644 src/scalper/legal.py delete mode 100644 tests/test_legal.py delete mode 100644 tests/test_registry.py diff --git a/.dockerignore b/.dockerignore index 57d9923..7aba69d 100644 --- a/.dockerignore +++ b/.dockerignore @@ -7,7 +7,6 @@ venv out data .env -sources.toml tests docs skills diff --git a/.env.example b/.env.example index 5fe7255..78646e8 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,3 @@ MISTRAL_API_KEY= MISTRAL_MODEL=mistral-small-latest - -# Registre de sources personnalisées monté dans le conteneur (optionnel) : -# SCALPER_CONFIG=/app/sources.toml diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index f0797bc..8f97fb9 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -7,12 +7,8 @@ ## Type - [ ] Feature (Story) [ ] Bug [ ] Task / chore -## Conformité légale (obligatoire) -- [ ] Aucune source non autorisée ajoutée (legal-source-check inchangé ou élargi avec licence justifiée) -- [ ] robots.txt / rate limiting / pas de contournement respectés -- [ ] Pas de secret committé (clés API hors du code) - ## Vérification +- [ ] Pas de secret committé (clés API hors du code) - [ ] `python -m pytest -q` passe localement - [ ] CI verte sur la PR - [ ] Doc à jour si comportement change diff --git a/README.md b/README.md index 82a2ec6..5cb2a77 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,7 @@ # Scalper -Pipeline **légal** de scraping et de traduction de chapitres de mangas/webtoons : -`legal-source-check → scrape → clean → translate (LLM) → QA → export` (Markdown / JSON / HTML). - -> ⚠️ **Conformité** : Scalper ne traite que des **sources légales** (API officielles comme -> MangaDex, contenus Creative Commons, domaine public, vos propres contenus). Les sites de -> scanlation non autorisés (ex. **mangas-origines**) sont **bloqués** par `legal-source-check` : -> scraper et traduire des mangas commerciaux sans autorisation est de la contrefaçon. -> Respect de `robots.txt`, rate limiting (≥ 1 s entre requêtes), aucun contournement de -> paywall/captcha. Chaque export embarque une page « Source et licence ». +Pipeline de scraping et de traduction de chapitres de mangas/webtoons : +`scrape → clean → translate (LLM) → QA → export` (Markdown / JSON / HTML). ## Installation @@ -21,7 +14,6 @@ export MISTRAL_API_KEY=... # traduction réelle (jamais committée) ## Démarrage rapide (démo hors ligne, source fixture « demo ») ```bash -scalper check-source demo scalper list-series demo scalper list-chapters demo demo-1 scalper run --source demo --series demo-1 --lang fr --mock-llm --out out @@ -31,32 +23,28 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | Commande | Description | |---|---| -| `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 ocr [--mock-ocr]` | OCR des images (tesseract) → `ocr.json` — **licences dérivables uniquement** | +| `scalper list-groups mangadex --query Keiyoushi` | recherche de groupes de traduction (API MangaDex) | +| `scalper fetch-url ` | lien direct → `raw.html` + `meta.json` + `chapter.json` | +| `scalper ocr [--mock-ocr]` | OCR des images (tesseract) → `ocr.json` | | `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 run ... --with-ocr` | pipeline + OCR/typeset (si 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 | | `scalper qa --lang fr` | score 0-100, pass si ≥ 80 | -| `scalper export --format md\|json\|html` | export avec page licence | +| `scalper export --format md\|json\|html` | export Markdown / JSON / HTML | | `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. +moyenne floutée) et redessine la traduction (Pillow). ## Architecture -- **Skills Mistral** (workspace, v1) : `legal-source-check`, `manga-scraper`, `chapter-cleaner`, +- **Skills Mistral** (workspace, v1) : `manga-scraper`, `chapter-cleaner`, `llm-translator`, `translation-qa`, `manga-exporter` (miroirs dans `skills/`). - **Sous-agents** (`src/scalper/agents/`, Mistral Agents SDK 1.1) : `scalper-orchestrator` délègue à `scraper-agent`, `translator-agent`, `qa-agent` (chacun sa propre session). @@ -64,14 +52,9 @@ licence de l'œuvre) et toute source bloquée sont refusées. - **Gestion de projet** : Jira **SCAL** (méthodologie Scrum) — Epic `SCAL-1` (cahier des charges), stories US1–US10 (`SCAL-2`…`SCAL-12`), sprints de 2 semaines. -## Ajouter une source légale +## Ajouter une source -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). +Voir [docs/add-a-source.md](docs/add-a-source.md) : lien direct `fetch-url` ou adaptateur dédié. ## Tests & CI @@ -89,7 +72,6 @@ docker compose up -d # API sur http://localhost:8000 + interface web sur h ``` Déploiement pas à pas sur Coolify : [docs/deploy-coolify.md](docs/deploy-coolify.md). -Le conteneur applique le même gate légal que la CLI (sources non déclarées/bloquées refusées). ## Licence diff --git a/docker-compose.yml b/docker-compose.yml index 2070126..9785593 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,11 +1,7 @@ # Déploiement Scalper — prêt pour Coolify (New Resource → Docker Compose depuis ce repo). # # 1) cp .env.example .env et renseigne MISTRAL_API_KEY (jamais committer .env) -# 2) (optionnel) cp sources.example.toml sources.toml et déclare tes sources légales -# 3) docker compose up -d (ou déploiement Coolify) -# -# Le conteneur applique le gate légal : sources non déclarées / bloquées -# (mangas-origines, keiyoushi.github.io) -> jamais traitées. +# 2) docker compose up -d (ou déploiement Coolify) services: scalper: build: . @@ -16,13 +12,9 @@ services: - .env environment: - PYTHONUNBUFFERED=1 - # Décommente si tu montes un registre de sources personnalisé : - # - SCALPER_CONFIG=/app/sources.toml volumes: - ./data:/app/data - ./out:/app/out - # Décommente si tu as un sources.toml personnalisé : - # - ./sources.toml:/app/sources.toml:ro restart: unless-stopped healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz')"] diff --git a/docs/add-a-source.md b/docs/add-a-source.md index 513b6a0..1486a47 100644 --- a/docs/add-a-source.md +++ b/docs/add-a-source.md @@ -1,28 +1,10 @@ -## Deux façons d'ajouter une source - -### 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` +## Lien direct — `fetch-url` ```bash -scalper --config sources.toml fetch-url "https://exemple-domaine-public.fr/manga/x/chapitre-1" --out data +scalper fetch-url "https://exemple.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`. +Produit `raw.html` + `meta.json` + `chapter.json`. ## Adaptateur dédié @@ -31,11 +13,8 @@ Pour une source récurrente, implémenter le contrat `SourceAdapter` (`src/scalp - `list_chapters(series_id) -> list[ChapterRef]` - `fetch_chapter(chapter, dest_dir)` : écrit le brut dans `dest_dir` (raw.html + images + meta.json) puis l'enregistrer dans `get_adapter()` (`src/scalper/sources/__init__.py`). -4. **Crawl respectueux** : passer par `RespectfulFetcher` (rate limiting ≥ 1 s, backoff, UA identifiable). -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). +1. **Crawl** : passer par `RespectfulFetcher` (rate limiting ≥ 1 s, backoff, UA identifiable). +2. **Tests** : ajouter un test hors ligne (fixtures mockées, aucun appel réseau en test). +3. **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). +Exemple d'adaptateur existant : `src/scalper/sources/mangadex.py` (API MangaDex). diff --git a/docs/deploy-coolify.md b/docs/deploy-coolify.md index c4519a2..eb23952 100644 --- a/docs/deploy-coolify.md +++ b/docs/deploy-coolify.md @@ -3,21 +3,17 @@ ## 1. Préparer le dépôt ```bash cp .env.example .env # renseigne MISTRAL_API_KEY (jamais committer .env) -# optionnel : cp sources.example.toml sources.toml et déclare tes sources légales -# (chaque domaine avec sa licence — obligatoire) ``` ## 2. Créer la ressource Coolify 1. Coolify → **New Resource** → **Docker Compose** → sélectionne le repo `Orionis312050/Scalper`. 2. Coolify détecte `docker-compose.yml` (service `scalper`, port **8000**). -3. Dans l'onglet **Environment**, ajoute `MISTRAL_API_KEY` (secret) et éventuellement `SCALPER_CONFIG=/app/sources.toml`. -4. (Optionnel) **Volumes** : monte `./sources.toml` en lecture seule si tu déclares des sources personnalisées. -5. Déploie, puis attache un domaine. Coolify gère le reverse proxy HTTPS. +3. Dans l'onglet **Environment**, ajoute `MISTRAL_API_KEY` (secret). +4. Déploie, puis attache un domaine. Coolify gère le reverse proxy HTTPS. ## 3. Vérifier ```bash curl https:///healthz -curl "https:///check-source?source=demo" ``` ## 4. Lancer un pipeline @@ -31,14 +27,11 @@ Les résultats sont écrits dans le volume `./out` (monté dans le compose). ## Endpoints | Méthode | Chemin | Rôle | |---|---|---| -| GET | `/` | **interface web** (formulaires check-source + run) | +| GET | `/` | **interface web** (formulaire run) | | GET | `/healthz` | sonde de santé | -| GET | `/check-source?source=...` | verdict légal (allowed/blocked) | -| POST | `/run` | pipeline complet (check → scrape → clean → translate → QA → export) | +| POST | `/run` | pipeline complet (scrape → clean → translate → QA → export) | ## Sécurité -- Le serveur n'accepte que les sources **déclarées et légales** : domaine inconnu = bloqué, - `mangas-origines` / `keiyoushi.github.io` = bloqués (liste inviolable), robots.txt vérifié. - Rate limiting ≥ 1 s entre requêtes vers les sources. - **Conseil** : restreins l'accès à `/run` (authentification Coolify / IP allowlist), car il déclenche du scraping et des appels LLM (coût API) sur ton instance. diff --git a/docs/legal-sources.md b/docs/legal-sources.md deleted file mode 100644 index 6a808b3..0000000 --- a/docs/legal-sources.md +++ /dev/null @@ -1,36 +0,0 @@ -# Politique des sources légales - -Scalper ne doit traiter que des contenus pour lesquels une autorisation existe. - -## Autorisé -- **API officielles** : ex. API MangaDex (`api.mangadex.org`), enregistrée dans `TRUSTED_SOURCES`. -- **Creative Commons** : œuvres publiées sous licence CC (vérifier la licence exacte). -- **Domaine public** : œuvres dont les droits patrimoniaux sont éteints. -- **Contenus propres** : vos propres webtoons/mangas. -- **Fixture de test** : `demo` (texte inventé, hors ligne). - -## Interdit (bloqué par `legal-source-check`) -- Sites de scanlation non autorisés hébergeant des mangas commerciaux sans licence - (ex. **mangas-origines**) : contrefaçon + violation des CGU. -- **keiyoushi.github.io / keiyoushi.com** : index d'extensions de lecteurs pointant vers des - sites de scanlation non autorisés — bloqué. Pour suivre un groupe de scanlation (ex. - Keiyoushi), utiliser la voie légale : l'API officielle MangaDex avec le filtre par groupe - (`scalper list-chapters mangadex --group Keiyoushi`, `scalper list-groups mangadex --query Keiyoushi`). -- 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. -- Backoff exponentiel sur 429/5xx. -- Chaque export embarque une page « Source et licence » (URL, licence, date de récupération). - -## Ajouter une source -Voir [add-a-source.md](add-a-source.md). diff --git a/pyproject.toml b/pyproject.toml index bf74fb5..10befef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "scalper" version = "0.1.0" -description = "Pipeline de scraping légal et de traduction de chapitres manga/webtoon (sources autorisées uniquement)" +description = "Pipeline de scraping et de traduction de chapitres manga/webtoon" readme = "README.md" requires-python = ">=3.11" license = { text = "MIT" } diff --git a/skills/legal-source-check/SKILL.md b/skills/legal-source-check/SKILL.md deleted file mode 100644 index 24afc20..0000000 --- a/skills/legal-source-check/SKILL.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: legal-source-check -description: Valide qu'une source manga/webtoon est légale (robots.txt, CGU, licence, liste de blocage) avant tout scraping. Bloqué si un critère échoue. ---- - -# legal-source-check - -Checklist (toutes doivent passer) : -1. robots.txt : chemins ciblés non interdits. -2. CGU : pas d'interdiction de scraping/réutilisation. -3. Licence : API officielle, Creative Commons, domaine public ou contenu propre. -4. Aucun contournement de paywall/captcha/authentification. -5. Liste de blocage : sites de scanlation non autorisés refusés (ex. mangas-origines). - -Politique de crawl : UA identifiable, >= 1s entre requêtes, 1 concurrence, backoff sur 429/5xx. - -Sortie : verdict JSON `{source, verdict: allowed|blocked, reasons, license}`. -Implémentation : `src/scalper/legal.py`. diff --git a/skills/manga-exporter/SKILL.md b/skills/manga-exporter/SKILL.md index 67e93b2..557323b 100644 --- a/skills/manga-exporter/SKILL.md +++ b/skills/manga-exporter/SKILL.md @@ -1,10 +1,10 @@ --- name: manga-exporter -description: Exporte un chapitre traduit en Markdown, JSON ou HTML, avec images relatives, page « Source et licence » obligatoire et noms de fichiers assainis. +description: Exporte un chapitre traduit en Markdown, JSON ou HTML, avec images relatives et noms de fichiers assainis. --- # manga-exporter -Formats : `md`, `json`, `html` (EPUB en V2). Noms : `--.`. Page « Source et licence » (URL, licence, date) incluse dans chaque export. Jamais d'export depuis une source bloquée. +Formats : `md`, `json`, `html` (EPUB en V2). Noms : `--.`. Implémentation : `src/scalper/exporter.py`. diff --git a/skills/manga-scraper/SKILL.md b/skills/manga-scraper/SKILL.md index f58afd6..0148850 100644 --- a/skills/manga-scraper/SKILL.md +++ b/skills/manga-scraper/SKILL.md @@ -7,6 +7,6 @@ description: Scraping générique et respectueux via un SourceAdapter, avec rate Contrat `SourceAdapter` : `list_series()`, `list_chapters(series_id)`, `fetch_chapter(chapter, dest_dir)`. -Règles : passer par legal-source-check d'abord ; >= 1s entre requêtes, 1 thread, UA identifiable, backoff ; stockage `out/raw////` + `state.json` resumable ; jamais de contournement d'auth/paywall. +Règles : >= 1s entre requêtes, 1 thread, UA identifiable, backoff ; stockage `out/raw////` + `state.json` resumable. -Implémentations : `src/scalper/sources/demo.py` (fixture), `src/scalper/sources/mangadex.py` (API officielle). +Implémentations : `src/scalper/sources/demo.py` (fixture), `src/scalper/sources/mangadex.py` (API MangaDex). diff --git a/sources.example.toml b/sources.example.toml deleted file mode 100644 index 27fb2ba..0000000 --- a/sources.example.toml +++ /dev/null @@ -1,14 +0,0 @@ -# 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/__init__.py b/src/scalper/__init__.py index b7e4b72..4af84be 100644 --- a/src/scalper/__init__.py +++ b/src/scalper/__init__.py @@ -1,3 +1,3 @@ -"""Scalper — pipeline légal de scraping et traduction de chapitres manga/webtoon.""" +"""Scalper — pipeline de scraping et traduction de chapitres manga/webtoon.""" __version__ = "0.1.0" diff --git a/src/scalper/agents/main.py b/src/scalper/agents/main.py index 8253494..19c2df4 100644 --- a/src/scalper/agents/main.py +++ b/src/scalper/agents/main.py @@ -11,18 +11,16 @@ from __future__ import annotations from mistralai import agents -from .tools import check_source, qa_translation, run_chapter_pipeline, translate_text +from .tools import 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." + "Tu es l'agent scraper de Scalper. Tu " + "exécutes le scraping via run_chapter_pipeline ou list/fetch (rate limiting, UA identifiable)." ), - tools=[check_source, run_chapter_pipeline], + tools=[run_chapter_pipeline], ) translator_agent = agents.Agent( @@ -52,13 +50,11 @@ 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. " + "Tu es l'orchestrateur du pipeline Scalper (scraping + traduction de " + "chapitres manga/webtoon). " "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], + tools=[run_chapter_pipeline], subagents=[scraper_agent, translator_agent, qa_agent], ) diff --git a/src/scalper/agents/tools.py b/src/scalper/agents/tools.py index fe60682..3b73276 100644 --- a/src/scalper/agents/tools.py +++ b/src/scalper/agents/tools.py @@ -11,22 +11,16 @@ from pathlib import Path from mistralai import agents -from .. import legal, pipeline +from .. import 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.""" + """Exécute le pipeline complet (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) diff --git a/src/scalper/cli.py b/src/scalper/cli.py index 1d41166..78a7a9f 100644 --- a/src/scalper/cli.py +++ b/src/scalper/cli.py @@ -1,4 +1,4 @@ -"""CLI Scalper : check-source, list-series, list-groups, list-chapters, fetch, clean, translate, qa, export, run.""" +"""CLI Scalper : list-series, list-groups, list-chapters, fetch, fetch-url, clean, translate, qa, export, ocr, typeset, serve, run.""" from __future__ import annotations @@ -7,8 +7,9 @@ import json import sys import time from pathlib import Path +from urllib.parse import urlparse -from . import legal, pipeline +from . import pipeline from .cleaner import clean_chapter from .exporter import export_chapter, slugify from .models import Chapter @@ -23,18 +24,14 @@ 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)") + p = argparse.ArgumentParser(prog="scalper", description="Pipeline 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.add_argument("--query", default="") - c = sub.add_parser("list-groups", help="liste les groupes de scanlation (source mangadex uniquement)") + c = sub.add_parser("list-groups", help="liste les groupes de traduction (source mangadex uniquement)") c.add_argument("source") c.add_argument("--query", default="") @@ -73,16 +70,16 @@ 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 = sub.add_parser("fetch-url", help="récupère un lien direct") 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 = sub.add_parser("ocr", help="OCR des images d'un chapitre (tesseract)") 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 = sub.add_parser("typeset", help="remplace le texte des images par la traduction") c.add_argument("chapter_dir") c.add_argument("--lang", required=True) @@ -98,16 +95,10 @@ 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)") + c.add_argument("--with-ocr", action="store_true", help="OCR + remplacement du texte dans les images") 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 if args.cmd == "list-series": adapter = get_adapter(args.source) series = adapter.list_series(query=args.query) if args.source == "mangadex" else adapter.list_series() @@ -173,19 +164,14 @@ def main(argv: list[str] | None = None) -> int: _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) + domain = (urlparse(args.url).netloc or args.url).lower() 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()), } @@ -197,10 +183,6 @@ def main(argv: list[str] | None = None) -> int: 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")}) @@ -208,10 +190,6 @@ def main(argv: list[str] | None = None) -> int: 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 diff --git a/src/scalper/exporter.py b/src/scalper/exporter.py index 2ca9e29..ce05bd4 100644 --- a/src/scalper/exporter.py +++ b/src/scalper/exporter.py @@ -1,4 +1,4 @@ -"""manga-exporter : exports Markdown / JSON / HTML avec page « source & licence ».""" +"""manga-exporter : exports Markdown / JSON / HTML.""" from __future__ import annotations @@ -6,7 +6,6 @@ import html import json import re from pathlib import Path -from typing import Any from .models import Chapter @@ -16,21 +15,11 @@ def slugify(text: str) -> str: 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": @@ -56,10 +45,9 @@ def export_html(chapter: Chapter, out_path: Path) -> Path: parts = [ "", f"{html.escape(str(meta.get('title', 'Chapitre')))}", - "", + "", "", f"

{html.escape(str(meta.get('title', 'Chapitre')))}

", - f"

{html.escape(license_block(meta))}

", ] for b in chapter.blocks: if b.type == "image": diff --git a/src/scalper/legal.py b/src/scalper/legal.py deleted file mode 100644 index 0dd81d4..0000000 --- a/src/scalper/legal.py +++ /dev/null @@ -1,158 +0,0 @@ -"""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)", - "keiyoushi.github.io": "index d'extensions Keiyoushi pointant vers des sites de scanlation non autorisés", - "keiyoushi.com": "dépôt d'extensions Keiyoushi pointant vers des sites de scanlation non autorisés", -} -BLOCKED_SUBSTRINGS = ("mangas-origines", "keiyoushi.github.io", "keiyoushi.com") - -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", - }, -} - -# 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: - 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}" - - -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) - - 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) or CUSTOM_SOURCES.get(domain) - if trusted is None: - return Verdict( - source=source, - verdict="blocked", - reasons=[ - "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="", - ) - - 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"], - ) diff --git a/src/scalper/models.py b/src/scalper/models.py index bf2c828..ae1bb8f 100644 --- a/src/scalper/models.py +++ b/src/scalper/models.py @@ -11,7 +11,6 @@ class Series: id: str title: str url: str - license: str def to_dict(self) -> dict[str, Any]: return asdict(self) diff --git a/src/scalper/ocr.py b/src/scalper/ocr.py index 22f6ecb..111d090 100644 --- a/src/scalper/ocr.py +++ b/src/scalper/ocr.py @@ -1,8 +1,4 @@ -"""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. -""" +"""OCR des images d'un chapitre (texte dans les bulles).""" from __future__ import annotations diff --git a/src/scalper/pipeline.py b/src/scalper/pipeline.py index 25ea6bc..b088475 100644 --- a/src/scalper/pipeline.py +++ b/src/scalper/pipeline.py @@ -1,4 +1,4 @@ -"""Orchestration : legal-source-check -> scrape -> clean -> translate -> QA -> export.""" +"""Orchestration : scrape -> clean -> translate -> QA -> export.""" from __future__ import annotations @@ -7,7 +7,6 @@ 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 @@ -29,10 +28,6 @@ def run_pipeline( with_ocr: bool = False, ) -> 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, **({"group": group} if group else {})) @@ -90,8 +85,6 @@ 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: diff --git a/src/scalper/scraper.py b/src/scalper/scraper.py index fadf70a..deaba32 100644 --- a/src/scalper/scraper.py +++ b/src/scalper/scraper.py @@ -9,7 +9,7 @@ import urllib.request from pathlib import Path from typing import Any -from .legal import USER_AGENT +USER_AGENT = "Scalper/1.0 (+https://github.com/Orionis312050/Scalper)" class FetchError(Exception): diff --git a/src/scalper/server.py b/src/scalper/server.py index da06346..f2e4297 100644 --- a/src/scalper/server.py +++ b/src/scalper/server.py @@ -2,22 +2,16 @@ Endpoints : - GET /healthz -- GET /check-source?source= - 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. """ from __future__ import annotations import json -import os from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, urlparse +from urllib.parse import urlparse -from . import legal, pipeline +from . import pipeline INDEX_HTML = """ @@ -25,12 +19,8 @@ INDEX_HTML = """

Scalper

-

Pipeline légal de scraping + traduction de chapitres. Sources non déclarées ou bloquées (mangas-origines, keiyoushi.github.io) refusées.

-
1. Vérifier une source -
- -
-
2. Lancer un pipeline (check → scrape → clean → translate → QA → export) +

Pipeline de scraping + traduction de chapitres.

+
Lancer un pipeline (scrape → clean → translate → QA → export) @@ -41,7 +31,6 @@ INDEX_HTML = """
résultats ici…
@@ -74,11 +63,6 @@ class Handler(BaseHTTPRequestHandler): return self._html(200, INDEX_HTML) if u.path == "/healthz": return self._json(200, {"status": "ok"}) - if u.path == "/check-source": - source = parse_qs(u.query).get("source", [""])[0] - if not source: - return self._json(400, {"error": "paramètre 'source' requis"}) - return self._json(200, legal.check_source(source).to_dict()) return self._json(404, {"error": "not found"}) def do_POST(self) -> None: @@ -107,15 +91,8 @@ class Handler(BaseHTTPRequestHandler): def serve(host: str = "127.0.0.1", port: int = 8000) -> None: - cfg = os.environ.get("SCALPER_CONFIG") - if cfg: - if Path(cfg).exists(): - legal.load_config(cfg) - print(f"registre de sources chargé: {cfg}") - else: - print(f"attention: SCALPER_CONFIG={cfg} introuvable, ignoré") server = ThreadingHTTPServer((host, port), Handler) - print(f"scalper serve sur http://{host}:{port} (GET /healthz, GET /check-source, POST /run)") + print(f"scalper serve sur http://{host}:{port} (GET /healthz, POST /run)") try: server.serve_forever() except KeyboardInterrupt: diff --git a/src/scalper/sources/__init__.py b/src/scalper/sources/__init__.py index 14f2d8d..21c5081 100644 --- a/src/scalper/sources/__init__.py +++ b/src/scalper/sources/__init__.py @@ -13,7 +13,7 @@ def get_adapter(source_id: str, fetcher: RespectfulFetcher | None = None) -> Sou 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." + "Pour ajouter une source, voir docs/add-a-source.md." ) diff --git a/src/scalper/sources/base.py b/src/scalper/sources/base.py index e8fd991..60d60de 100644 --- a/src/scalper/sources/base.py +++ b/src/scalper/sources/base.py @@ -7,10 +7,9 @@ from ..models import ChapterRef, Series class SourceAdapter(Protocol): - """Contrat d'un adaptateur de source légale.""" + """Contrat d'un adaptateur de source.""" id: str - license: str def list_series(self) -> list[Series]: ... diff --git a/src/scalper/sources/demo.py b/src/scalper/sources/demo.py index b4c0ba9..ccb0553 100644 --- a/src/scalper/sources/demo.py +++ b/src/scalper/sources/demo.py @@ -1,4 +1,4 @@ -"""Adaptateur 'demo' : fixture locale (texte inventé, domaine public). +"""Adaptateur 'demo' : fixture locale. Permet de faire tourner le pipeline de bout en bout hors ligne. """ @@ -15,7 +15,6 @@ 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")) @@ -25,7 +24,7 @@ class DemoAdapter: 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"]] + return [Series(id=s["id"], title=s["title"], url=s["url"]) for s in idx["series"]] def list_chapters(self, series_id: str, **kwargs) -> list[ChapterRef]: idx = self._index() @@ -52,7 +51,7 @@ class DemoAdapter: 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()}, + {"source": self.id, "chapter": chapter.to_dict()}, ensure_ascii=False, indent=2, ), diff --git a/src/scalper/sources/mangadex.py b/src/scalper/sources/mangadex.py index 4f360f4..5563e26 100644 --- a/src/scalper/sources/mangadex.py +++ b/src/scalper/sources/mangadex.py @@ -1,8 +1,7 @@ -"""Adaptateur API officielle MangaDex (https://api.mangadex.org) — source légale. +"""Adaptateur API MangaDex (https://api.mangadex.org). L'API publique ne nécessite pas de clé pour la lecture. Rate limiting appliqué. -Permet de filtrer les chapitres par groupe de scanlation (ex. Keiyoushi) via le -paramètre groups[] — la voie légale pour suivre un groupe donné. +Permet de filtrer les chapitres par groupe (ex. Keiyoushi) via le paramètre groups[]. """ from __future__ import annotations @@ -22,7 +21,6 @@ _UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F 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) @@ -43,13 +41,12 @@ class MangaDexAdapter: 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_groups(self, query: str = "", limit: int = 20) -> list[dict]: - """Recherche des groupes de scanlation par nom (ex. 'Keiyoushi').""" + """Recherche des groupes de traduction par nom (ex. 'Keiyoushi').""" params: dict[str, object] = {"limit": limit, "order[name]": "asc"} if query: params["name"] = query @@ -109,7 +106,7 @@ class MangaDexAdapter: (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}, + {"source": self.id, "chapter": chapter.to_dict(), "pages": pages}, ensure_ascii=False, indent=2, ), diff --git a/src/scalper/typeset.py b/src/scalper/typeset.py index dd9e44e..9772a90 100644 --- a/src/scalper/typeset.py +++ b/src/scalper/typeset.py @@ -1,7 +1,5 @@ """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 diff --git a/tests/test_cleaner.py b/tests/test_cleaner.py index 6599cee..f80c0c4 100644 --- a/tests/test_cleaner.py +++ b/tests/test_cleaner.py @@ -7,7 +7,7 @@ from scalper.cleaner import clean_chapter, detect_language class TestCleaner(unittest.TestCase): def setUp(self): raw = (resources.files("scalper") / "data" / "demo" / "chapter-1.html").read_text(encoding="utf-8") - self.chapter = clean_chapter(raw, {"source": "demo", "license": "fixture"}) + self.chapter = clean_chapter(raw, {"source": "demo"}) def test_boilerplate_removed(self): text = self.chapter.full_text().lower() diff --git a/tests/test_legal.py b/tests/test_legal.py deleted file mode 100644 index 4da848d..0000000 --- a/tests/test_legal.py +++ /dev/null @@ -1,38 +0,0 @@ -import unittest - -from scalper import legal - - -class TestLegal(unittest.TestCase): - def test_demo_allowed(self): - v = legal.check_source("demo") - self.assertTrue(v.allowed) - - def test_mangas_origines_blocked(self): - for url in ("https://mangas-origines.fr/", "https://www.mangas-origines.fr/manga/x", "mangas-origines.fr"): - v = legal.check_source(url) - self.assertFalse(v.allowed, url) - self.assertIn("blocage", v.reasons[0]) - - def test_keiyoushi_extensions_blocked(self): - for url in ("https://keiyoushi.github.io", "https://keiyoushi.github.io/extensions", "keiyoushi.com"): - v = legal.check_source(url) - self.assertFalse(v.allowed, url) - self.assertIn("blocage", v.reasons[0]) - - def test_unknown_domain_blocked(self): - v = legal.check_source("https://site-inconnu.example/manga") - self.assertFalse(v.allowed) - - def test_mangadex_trusted(self): - v = legal.check_source("api.mangadex.org") - self.assertTrue(v.allowed) - self.assertIn("MangaDex", v.license) - - def test_domain_of(self): - self.assertEqual(legal.domain_of("https://WWW.Example.COM/x"), "www.example.com") - self.assertEqual(legal.domain_of("demo"), "demo") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ocr_typeset.py b/tests/test_ocr_typeset.py index 91fae4b..c6df39a 100644 --- a/tests/test_ocr_typeset.py +++ b/tests/test_ocr_typeset.py @@ -3,7 +3,6 @@ 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 @@ -15,17 +14,6 @@ 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: diff --git a/tests/test_pipeline_exporter.py b/tests/test_pipeline_exporter.py index 5bdc892..002266b 100644 --- a/tests/test_pipeline_exporter.py +++ b/tests/test_pipeline_exporter.py @@ -10,11 +10,6 @@ from scalper.sources import get_adapter class TestPipeline(unittest.TestCase): - def test_blocked_source(self): - with tempfile.TemporaryDirectory() as tmp: - res = pipeline.run_pipeline("https://mangas-origines.fr", "x", "fr", out_root=tmp, mock_llm=True) - self.assertEqual(res["status"], "blocked") - def test_demo_end_to_end_mock_llm(self): with tempfile.TemporaryDirectory() as tmp: res = pipeline.run_pipeline("demo", "demo-1", "fr", out_root=tmp, mock_llm=True) @@ -37,14 +32,14 @@ class TestPipeline(unittest.TestCase): class TestExporter(unittest.TestCase): - def test_exports_contain_license(self): + def test_exports(self): ch = Chapter( - meta={"source": "demo", "license": "fixture test", "fetched_at": "2026-01-01", "url": "demo://x", "title": "T", "language": "fr"}, + meta={"source": "demo", "fetched_at": "2026-01-01", "url": "demo://x", "title": "T", "language": "fr"}, blocks=[Block(index=0, type="narration", text="Bonjour"), Block(index=1, type="image", image="images/p.png")], ) with tempfile.TemporaryDirectory() as tmp: md = export_chapter(ch, "md", Path(tmp)) - self.assertIn("Source et licence", md.read_text(encoding="utf-8")) + self.assertIn("Bonjour", md.read_text(encoding="utf-8")) self.assertIn("[IMG:1]", md.read_text(encoding="utf-8")) js = export_chapter(ch, "json", Path(tmp)) self.assertEqual(json.loads(js.read_text(encoding="utf-8"))["blocks"][1]["image"], "images/p.png") diff --git a/tests/test_registry.py b/tests/test_registry.py deleted file mode 100644 index c4f4679..0000000 --- a/tests/test_registry.py +++ /dev/null @@ -1,54 +0,0 @@ -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() diff --git a/tests/test_server.py b/tests/test_server.py index 45f20d6..a87baf4 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -51,17 +51,6 @@ class TestServer(unittest.TestCase): self.assertIn("text/html", r.headers.get("Content-Type", "")) self.assertIn("Scalper", body) self.assertIn("/run", body) - self.assertIn("/check-source", body) - - def test_check_source_demo_allowed(self): - status, body = self._get("/check-source?source=demo") - self.assertEqual(status, 200) - self.assertEqual(body["verdict"], "allowed") - - def test_check_source_blocked(self): - status, body = self._get("/check-source?source=https://mangas-origines.fr") - self.assertEqual(status, 200) - self.assertEqual(body["verdict"], "blocked") def test_run_demo_mock_llm(self): with tempfile.TemporaryDirectory() as tmp: @@ -70,11 +59,6 @@ class TestServer(unittest.TestCase): self.assertEqual(body["status"], "done") self.assertEqual(len(body["chapters"]), 2) - def test_run_blocked_source_returns_403(self): - status, body = self._post("/run", {"source": "https://keiyoushi.github.io", "series": "x", "lang": "fr", "mock_llm": True}) - self.assertEqual(status, 403) - self.assertEqual(body["status"], "blocked") - def test_run_missing_field_400(self): status, body = self._post("/run", {"source": "demo"}) self.assertEqual(status, 400) diff --git a/tests/test_translator_qa.py b/tests/test_translator_qa.py index ffceeda..ebc4655 100644 --- a/tests/test_translator_qa.py +++ b/tests/test_translator_qa.py @@ -9,7 +9,7 @@ from scalper.translator import FakeLLM, chunk_blocks, translate_chapter def demo_chapter(): raw = (resources.files("scalper") / "data" / "demo" / "chapter-1.html").read_text(encoding="utf-8") - return clean_chapter(raw, {"source": "demo", "license": "fixture", "language": "en"}) + return clean_chapter(raw, {"source": "demo", "language": "en"}) class TestTranslator(unittest.TestCase):