✨ Suppression de la partie légal
This commit is contained in:
1 parent
0c5189d9ca
commit
d0a95adeb9
36 files changed
+73
-572
No files matched your search
@@ -7,7 +7,6 @@ venv
|
||||
out
|
||||
data
|
||||
.env
|
||||
sources.toml
|
||||
tests
|
||||
docs
|
||||
skills
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 <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 ocr <chapter_dir> [--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 <url>` | lien direct → `raw.html` + `meta.json` + `chapter.json` |
|
||||
| `scalper ocr <chapter_dir> [--mock-ocr]` | OCR des images (tesseract) → `ocr.json` |
|
||||
| `scalper typeset <chapter_dir> --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 <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 |
|
||||
| `scalper qa <source.json> <traduit.json> --lang fr` | score 0-100, pass si ≥ 80 |
|
||||
| `scalper export <traduit.json> --format md\|json\|html` | export avec page licence |
|
||||
| `scalper export <traduit.json> --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
|
||||
|
||||
|
||||
+1
-9
@@ -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')"]
|
||||
|
||||
+7
-28
@@ -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).
|
||||
+4
-11
@@ -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://<ton-domaine>/healthz
|
||||
curl "https://<ton-domaine>/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.
|
||||
|
||||
@@ -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 <series> --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).
|
||||
+1
-1
@@ -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" }
|
||||
|
||||
@@ -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`.
|
||||
@@ -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 : `<series>-<chapitre>-<lang>.<ext>`. 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 : `<series>-<chapitre>-<lang>.<ext>`.
|
||||
|
||||
Implémentation : `src/scalper/exporter.py`.
|
||||
@@ -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/<source>/<series>/<chapter>/` + `state.json` resumable ; jamais de contournement d'auth/paywall.
|
||||
Règles : >= 1s entre requêtes, 1 thread, UA identifiable, backoff ; stockage `out/raw/<source>/<series>/<chapter>/` + `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).
|
||||
@@ -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]
|
||||
@@ -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"
|
||||
@@ -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],
|
||||
)
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
+10
-32
@@ -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
|
||||
|
||||
+2
-14
@@ -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 = [
|
||||
"<!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>",
|
||||
"<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%}</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":
|
||||
|
||||
@@ -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"],
|
||||
)
|
||||
@@ -11,7 +11,6 @@ class Series:
|
||||
id: str
|
||||
title: str
|
||||
url: str
|
||||
license: str
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
+1
-5
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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):
|
||||
|
||||
+5
-28
@@ -2,22 +2,16 @@
|
||||
|
||||
Endpoints :
|
||||
- GET /healthz
|
||||
- GET /check-source?source=<url|domaine>
|
||||
- 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 = """<!doctype html>
|
||||
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
@@ -25,12 +19,8 @@ INDEX_HTML = """<!doctype html>
|
||||
<style>body{font-family:system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;color:#222}input,button{padding:.45rem;margin:.2rem}input{width:100%;box-sizing:border-box}fieldset{border:1px solid #ccc;border-radius:8px;margin-bottom:1rem}legend{font-weight:600}button{cursor:pointer;background:#222;color:#fff;border:0;border-radius:6px}pre{background:#f4f4f4;padding:1rem;border-radius:8px;overflow:auto;white-space:pre-wrap}.warn{color:#a00;font-size:.85rem}</style>
|
||||
</head><body>
|
||||
<h1>Scalper</h1>
|
||||
<p>Pipeline légal de scraping + traduction de chapitres. <span class="warn">Sources non déclarées ou bloquées (mangas-origines, keiyoushi.github.io) refusées.</span></p>
|
||||
<fieldset><legend>1. Vérifier une source</legend>
|
||||
<input id="cs-source" placeholder="https://... ou demo ou mangadex"><br>
|
||||
<button onclick="checkSource()">check-source</button>
|
||||
</fieldset>
|
||||
<fieldset><legend>2. Lancer un pipeline (check → scrape → clean → translate → QA → export)</legend>
|
||||
<p>Pipeline de scraping + traduction de chapitres.</p>
|
||||
<fieldset><legend>Lancer un pipeline (scrape → clean → translate → QA → export)</legend>
|
||||
<input id="r-source" placeholder="source (demo, mangadex)" value="demo">
|
||||
<input id="r-series" placeholder="id série" value="demo-1">
|
||||
<input id="r-lang" placeholder="langue cible (fr, en, ...)" value="fr">
|
||||
@@ -41,7 +31,6 @@ INDEX_HTML = """<!doctype html>
|
||||
</fieldset>
|
||||
<pre id="out">résultats ici…</pre>
|
||||
<script>
|
||||
async function checkSource(){const s=document.getElementById('cs-source').value;const r=await fetch('/check-source?source='+encodeURIComponent(s));document.getElementById('out').textContent=r.status+'\\n'+JSON.stringify(await r.json(),null,2);}
|
||||
async function runPipeline(){const g=document.getElementById('r-group').value;const m=document.getElementById('r-max').value;const body={source:document.getElementById('r-source').value,series:document.getElementById('r-series').value,lang:document.getElementById('r-lang').value,mock_llm:document.getElementById('r-mock').checked};if(g)body.group=g;if(m)body.max_chapters=Number(m);document.getElementById('out').textContent='en cours…';const r=await fetch('/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});document.getElementById('out').textContent=r.status+'\\n'+JSON.stringify(await r.json(),null,2);}
|
||||
</script>
|
||||
</body></html>
|
||||
@@ -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:
|
||||
|
||||
@@ -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."
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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]: ...
|
||||
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
@@ -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:
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user