Compare commits
79
Commits
v0.16.0
...
cd54f05b78
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd54f05b78 | ||
|
|
4998ac3849 | ||
|
|
3c76762efc | ||
|
|
6c1d74f9a5 | ||
|
|
0d56f8527b | ||
|
|
3f0766ccbe | ||
|
|
b9020cb46f | ||
|
|
10574ba0c5 | ||
|
|
ace2e486fc | ||
|
|
c008c22e09 | ||
|
|
bf606c23d1 | ||
|
|
1898e8b1ae | ||
|
|
e77ad85be9 | ||
|
|
11939fe39e | ||
|
|
8958822545 | ||
|
|
007bcce8a7 | ||
|
|
a985bbd018 | ||
|
|
1c9ac524db | ||
|
|
abf66733fe | ||
|
|
763219412b | ||
|
|
cccf2b85db | ||
|
|
6ae9238fee | ||
|
|
0ef1380265 | ||
|
|
9a7e93b162 | ||
|
|
106754fd77 | ||
|
|
0c0581e894 | ||
|
|
dae0508c93 | ||
|
|
cbd59a5bd9 | ||
|
|
d759bc8131 | ||
|
|
ac7648f9fe | ||
|
|
d9a90f8412 | ||
|
|
2e9632de49 | ||
|
|
fbb1956e17 | ||
|
|
8c6b642975 | ||
|
|
d926545e3d | ||
|
|
b323c681f8 | ||
|
|
e7063b31e3 | ||
|
|
ab658f27b0 | ||
|
|
c2947cfef8 | ||
|
|
67ac4cc68f | ||
|
|
c2f162d823 | ||
|
|
ad3ea0e9e6 | ||
|
|
0c44e42a22 | ||
|
|
1c8b24c5dd | ||
|
|
177967af55 | ||
|
|
42c4b53ced | ||
|
|
3e9e828225 | ||
|
|
51eb907078 | ||
|
|
9f0359d8c0 | ||
|
|
587e0fe097 | ||
|
|
5c3c58265f | ||
|
|
f72161e41e | ||
|
|
4d05aa5118 | ||
|
|
beafbc2fa9 | ||
|
|
b2c3800bf8 | ||
|
|
268f4721ce | ||
|
|
11a33b1cf0 | ||
|
|
f670735100 | ||
|
|
c1e3a20e5a | ||
|
|
a9242ba1e1 | ||
|
|
3896c5b4cb | ||
|
|
b999aa54ad | ||
|
|
9bd66613b6 | ||
|
|
18f5a260b0 | ||
|
|
c0e1da78c8 | ||
|
|
5bc038acd8 | ||
|
|
f347dcd357 | ||
|
|
46fea8d53c | ||
|
|
e05b26563f | ||
|
|
dc66199177 | ||
|
|
b133d0f16d | ||
|
|
024d37dea6 | ||
|
|
997aadf5b5 | ||
|
|
560c07d5c3 | ||
|
|
5aa08a3a27 | ||
|
|
13f4b994ab | ||
|
|
d1653b8bea | ||
|
|
4d049274f9 | ||
|
|
eb78a75621 |
@@ -0,0 +1,86 @@
|
||||
name: Tests unitaires
|
||||
|
||||
# Gate de qualité : lance les 3 suites unitaires (Java / Python / Angular) à
|
||||
# chaque push sur main et sur chaque PR. Une suite rouge fait échouer la CI
|
||||
# (et, via la branch protection Gitea, peut bloquer le merge).
|
||||
# Le build/push des images (release.yml) dépend AUSSI de ces tests via `needs`.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
core:
|
||||
name: Core (Java · mvn test + JaCoCo)
|
||||
runs-on: ubuntu-latest
|
||||
# Les tests Core utilisent une VRAIE base PostgreSQL (cf.
|
||||
# src/test/resources/application.properties, ddl-auto=create-drop).
|
||||
# On en fournit une en service container. Sur Gitea (job en conteneur),
|
||||
# le service est joignable par son NOM d'hôte `postgres`.
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
env:
|
||||
POSTGRES_DB: loremind_test
|
||||
POSTGRES_USER: loremind_test
|
||||
POSTGRES_PASSWORD: loremind_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U loremind_test -d loremind_test"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
cache: maven
|
||||
# Maven wrapper (./mvnw) : le runner Gitea n'a pas `mvn` préinstallé et
|
||||
# setup-java n'installe que le JDK → le wrapper bootstrappe Maven lui-même.
|
||||
# `mvn test` exécute aussi jacoco:report + jacoco:check (plancher 60%).
|
||||
- name: mvn test (via wrapper)
|
||||
working-directory: core
|
||||
env:
|
||||
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/loremind_test
|
||||
SPRING_DATASOURCE_USERNAME: loremind_test
|
||||
SPRING_DATASOURCE_PASSWORD: loremind_test
|
||||
run: |
|
||||
chmod +x ./mvnw
|
||||
./mvnw -B test
|
||||
|
||||
brain:
|
||||
name: Brain (Python · pytest + couverture)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
cache: pip
|
||||
cache-dependency-path: brain/requirements-dev.txt
|
||||
- name: Install deps (test)
|
||||
working-directory: brain
|
||||
run: pip install -r requirements-dev.txt
|
||||
- name: pytest (+ plancher couverture 50%)
|
||||
working-directory: brain
|
||||
run: pytest --cov=app --cov-report=term-missing --cov-fail-under=50
|
||||
|
||||
web:
|
||||
name: Web (Angular · vitest + couverture)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
- name: npm ci
|
||||
working-directory: web
|
||||
run: npm ci --no-audit --no-fund
|
||||
# vitest run --coverage applique les seuils définis dans vitest.config.ts.
|
||||
- name: vitest (+ seuils couverture)
|
||||
working-directory: web
|
||||
run: npm run test:unit:coverage
|
||||
@@ -82,9 +82,11 @@ jobs:
|
||||
if: failure()
|
||||
run: docker compose -f docker-compose.yml -f docker-compose.e2e.yml logs --no-color
|
||||
|
||||
# v3 obligatoire : l'API artifacts v4 n'est pas supportée par Gitea
|
||||
# (GHESNotSupportedError — constaté sur le job MegaLinter).
|
||||
- name: Upload Playwright report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: playwright-report
|
||||
path: web/playwright-report/
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
name: Qualité & Sécurité
|
||||
|
||||
# Analyse statique (MegaLinter, config racine .mega-linter.yml) + CVE des
|
||||
# dépendances (Trivy). Workflow SÉPARÉ de ci.yml : un rouge qualité ne bloque
|
||||
# pas la chaîne tests → release pendant la phase de rodage. Une fois la base
|
||||
# assainie, on pourra l'ajouter aux checks requis de la branch protection.
|
||||
on:
|
||||
push:
|
||||
# beta inclus : c'est la branche de dev, le feedback qualité doit y vivre
|
||||
# (ci.yml/e2e.yml, eux, restent volontairement sur main + PR).
|
||||
branches: [main, beta]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
megalinter:
|
||||
name: MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# Historique complet : requis par gitleaks (scan de l'historique)
|
||||
# et par le mode "fichiers modifiés seulement" en PR.
|
||||
fetch-depth: 0
|
||||
# Flavor "cupcake" : image allégée couvrant les langages courants
|
||||
# (Java/Python/TS inclus). Si un linter activé manquait à la flavor,
|
||||
# MegaLinter échoue en l'indiquant → remplacer par oxsecurity/megalinter@v9
|
||||
# (image complète, plus lourde).
|
||||
- name: MegaLinter
|
||||
uses: oxsecurity/megalinter/flavors/cupcake@v9
|
||||
env:
|
||||
# main → scan complet du dépôt ; beta et PR → seulement les fichiers
|
||||
# modifiés par rapport à main (rapide, feedback ciblé).
|
||||
VALIDATE_ALL_CODEBASE: ${{ github.ref == 'refs/heads/main' }}
|
||||
# v3 obligatoire : l'API artifacts v4 (@actions/artifact 2.x) n'est pas
|
||||
# supportée par Gitea (GHESNotSupportedError constaté avec v4).
|
||||
- name: Publier les rapports
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: megalinter-reports
|
||||
path: megalinter-reports/
|
||||
|
||||
web-lint:
|
||||
name: Web (ESLint · angular-eslint + sonarjs)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
- name: npm ci
|
||||
working-directory: web
|
||||
run: npm ci --no-audit --no-fund
|
||||
# Lint via la toolchain du projet (et non via MegaLinter : ESLint a
|
||||
# besoin des plugins de web/node_modules et du contexte Angular).
|
||||
# Config + règles : web/eslint.config.js (sonarjs = règles "à la Sonar").
|
||||
- name: ng lint
|
||||
working-directory: web
|
||||
run: npm run lint
|
||||
|
||||
trivy:
|
||||
name: Trivy (CVE dépendances Maven / pip / npm)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# Pour résoudre pom.xml (versions héritées du parent Spring Boot), Trivy
|
||||
# télécharge les BOMs depuis Maven Central — qui finit par rate-limiter
|
||||
# l'IP du runner (429). Parade officielle : peupler ~/.m2 AVANT le scan,
|
||||
# Trivy lit le cache local en priorité. Le cache setup-java (clé pom.xml)
|
||||
# rend l'étape quasi gratuite d'un run à l'autre.
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
cache: maven
|
||||
- name: Précharger le cache Maven (~/.m2)
|
||||
working-directory: core
|
||||
run: |
|
||||
chmod +x ./mvnw
|
||||
./mvnw -B -q dependency:go-offline
|
||||
- name: Installer Trivy
|
||||
run: curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||
# Scanne les manifestes du dépôt (pom.xml, requirements*.txt,
|
||||
# package-lock.json) contre les bases CVE. --ignore-unfixed : on ne
|
||||
# bloque que sur les vulnérabilités qui ONT un correctif publié.
|
||||
# --offline-scan : AUCUNE requête vers Maven Central pendant la
|
||||
# résolution — Trivy allait y chercher les POMs parents même avec le
|
||||
# cache rempli, et l'IP du runner finissait rate-limitée (429, 30 min).
|
||||
# Tout est déjà dans ~/.m2 grâce au dependency:go-offline ci-dessus ;
|
||||
# contrepartie : une dépendance absente du cache serait ignorée en
|
||||
# silence (impossible ici, go-offline échouerait d'abord).
|
||||
- name: Scan des dépendances (HIGH/CRITICAL bloquants)
|
||||
run: |
|
||||
trivy fs . \
|
||||
--scanners vuln \
|
||||
--severity HIGH,CRITICAL \
|
||||
--ignore-unfixed \
|
||||
--offline-scan \
|
||||
--skip-dirs node_modules \
|
||||
--skip-dirs docusaurus \
|
||||
--exit-code 1
|
||||
@@ -12,6 +12,9 @@ env:
|
||||
GHCR_NAMESPACE: igmlcreation
|
||||
|
||||
jobs:
|
||||
# NB : pas de job de test ici. Le gate qualité vit dans ci.yml (push main + PR) ;
|
||||
# avec la branch protection Gitea (checks requis sur main), on ne tague donc que
|
||||
# du code déjà vert. release.yml ne fait que builder/pousser les images.
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
@@ -44,7 +47,7 @@ jobs:
|
||||
|
||||
# Detection du canal :
|
||||
# - tag vX.Y.Z -> stable (push :latest + :version sur les repos publics)
|
||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR prives
|
||||
# - tag vX.Y.Z-beta* -> beta (push :beta + :version sur les repos GHCR publics
|
||||
# loremind-beta-<component> ; backup Gitea avec :version)
|
||||
- name: Extract version & channel
|
||||
id: meta
|
||||
@@ -71,8 +74,8 @@ jobs:
|
||||
${{ env.GHCR_REGISTRY }}/${{ env.GHCR_NAMESPACE }}/loremind-${{ matrix.component }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
# Build & push canal BETA
|
||||
# GHCR : repos prives loremind-beta-<component> (gated par PAT distribue
|
||||
# via le relais Patreon aux tiers Compagnon).
|
||||
# GHCR : repos PUBLICS loremind-beta-<component> (canal beta libre ;
|
||||
# le switcher bascule IMAGE_NAMESPACE vers ce prefixe).
|
||||
# Gitea : backup prive avec :version uniquement (pas de :latest pour ne
|
||||
# pas faire upgrader les installs branchees sur Gitea).
|
||||
- name: Build & push ${{ matrix.component }} (beta)
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
name: Desktop installers
|
||||
|
||||
# Produit les installeurs de BUREAU (.msi Windows pour l'instant) et les publie
|
||||
# Produit les installeurs de BUREAU (.msi Windows + AppImage Linux) et les publie
|
||||
# en tant qu'assets d'une GitHub Release, sur tag `v*`.
|
||||
#
|
||||
# Complementaire au pipeline Gitea Actions (.gitea/workflows/release.yml) qui,
|
||||
# lui, build et pousse les IMAGES Docker. Ici on est sur GitHub car jpackage et
|
||||
# PyInstaller ne savent PAS cross-compiler : le .msi DOIT etre construit sur un
|
||||
# runner Windows, et GitHub en fournit gratuitement (windows-latest).
|
||||
# lui, build et pousse les IMAGES Docker. Ici on est sur GitHub car jpackage ne
|
||||
# sait PAS cross-compiler : le .msi DOIT etre construit sur un runner Windows et
|
||||
# l'AppImage sur un runner Linux — GitHub fournit les deux gratuitement.
|
||||
#
|
||||
# Prerequis : le depot Gitea doit etre mirrore vers GitHub (push mirror, tags
|
||||
# inclus) pour que le tag declenche ce workflow.
|
||||
#
|
||||
# Tag stable vX.Y.Z -> GitHub Release PUBLIQUE avec le .msi attache.
|
||||
# Tag beta vX.Y.Z-beta* -> AUCUNE publication publique. Le .msi est depose en
|
||||
# ARTEFACT PRIVE du run (telechargeable seulement par
|
||||
# toi via l'onglet Actions) ; tu le joins ensuite a un
|
||||
# post Patreon reserve a un palier. Patreon = la
|
||||
# barriere d'acces (equivalent du registry prive +
|
||||
# relais pour les images Docker beta).
|
||||
# Tag beta vX.Y.Z-beta* -> GitHub Release PUBLIQUE marquee « pre-release » : le
|
||||
# canal beta est libre. /releases/latest l'ignore, donc
|
||||
# seules les installations beta en sont prevenues
|
||||
# (cf. DesktopUpdateService).
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -35,8 +33,81 @@ permissions:
|
||||
contents: write # requis pour creer la Release et y attacher le .msi
|
||||
|
||||
jobs:
|
||||
# GATE : les 3 suites unitaires (Java / Python / Angular) doivent passer avant
|
||||
# de construire le .msi. Tourne sur ubuntu-latest (moins cher/plus rapide que
|
||||
# windows) ; le build natif lui-meme reste sur windows-latest via `needs`.
|
||||
# Auto-suffisant : ne depend PAS du resultat de Gitea (CI separee), il rejoue
|
||||
# les memes tests ici. Un test rouge => pas d'installeur publie.
|
||||
tests:
|
||||
runs-on: ubuntu-latest
|
||||
# Base PostgreSQL réelle pour les tests Core. Sur les runners GitHub (job sur
|
||||
# la VM, pas en conteneur), le service est joignable via localhost + le port mappé.
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
env:
|
||||
POSTGRES_DB: loremind_test
|
||||
POSTGRES_USER: loremind_test
|
||||
POSTGRES_PASSWORD: loremind_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U loremind_test -d loremind_test"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
cache: maven
|
||||
- name: Core — mvn test (+ JaCoCo check)
|
||||
working-directory: core
|
||||
env:
|
||||
SPRING_DATASOURCE_URL: jdbc:postgresql://localhost:5432/loremind_test
|
||||
SPRING_DATASOURCE_USERNAME: loremind_test
|
||||
SPRING_DATASOURCE_PASSWORD: loremind_test
|
||||
run: |
|
||||
chmod +x ./mvnw
|
||||
./mvnw -B test
|
||||
|
||||
- name: Set up Python 3.12
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
cache: pip
|
||||
cache-dependency-path: brain/requirements-dev.txt
|
||||
- name: Brain — pytest (+ couverture)
|
||||
working-directory: brain
|
||||
run: |
|
||||
pip install -r requirements-dev.txt
|
||||
pytest --cov=app --cov-report=term-missing --cov-fail-under=50
|
||||
|
||||
- name: Set up Node 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
- name: Web — vitest (+ couverture)
|
||||
working-directory: web
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm run test:unit:coverage
|
||||
|
||||
windows:
|
||||
needs: tests
|
||||
runs-on: windows-latest
|
||||
# Reprises par le job `publish` (tag de la release, statut pre-release).
|
||||
outputs:
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
isbeta: ${{ steps.ver.outputs.isbeta }}
|
||||
steps:
|
||||
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||
@@ -70,6 +141,13 @@ jobs:
|
||||
shell: pwsh
|
||||
run: choco install wixtoolset -y --no-progress
|
||||
|
||||
# Tesseract OCR : non preinstalle sur windows-latest. Requis pour que
|
||||
# build-windows.ps1 embarque l'OCR des PDF scannes (sinon il skip en
|
||||
# degradation gracieuse). Installe dans %ProgramFiles%\Tesseract-OCR.
|
||||
- name: Install Tesseract OCR
|
||||
shell: pwsh
|
||||
run: choco install tesseract -y --no-progress
|
||||
|
||||
# Version de l'installeur = version du tag (push) OU de l'input (manuel).
|
||||
# Sorties : version (numerique X.Y.Z pour le MSI), tag (vX.Y.Z[-beta]),
|
||||
# isbeta (true/false) — independant du nom de ref (qui est une branche en manuel).
|
||||
@@ -93,28 +171,100 @@ jobs:
|
||||
shell: pwsh
|
||||
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||
|
||||
# STABLE uniquement : Release GitHub publique avec le .msi.
|
||||
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
||||
# donc on cible le tag derive (la release est attachee au bon tag).
|
||||
- name: Publish installer to GitHub Release (stable)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'false' }}
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.ver.outputs.tag }}
|
||||
files: core/target/dist-out/*.msi
|
||||
fail_on_unmatched_files: true
|
||||
generate_release_notes: true
|
||||
|
||||
# BETA uniquement : artefact PRIVE (pas de release publique). A recuperer
|
||||
# via l'onglet Actions puis a joindre a un post Patreon gate par palier.
|
||||
- name: Upload installer as private artifact (beta)
|
||||
if: ${{ steps.ver.outputs.isbeta == 'true' }}
|
||||
# Le .msi est passe au job `publish`, seul a creer la release.
|
||||
- name: Keep installer for the release
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: loremind-beta-${{ steps.ver.outputs.version }}-msi
|
||||
name: installer-windows
|
||||
path: core/target/dist-out/*.msi
|
||||
retention-days: 90
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
# TODO (plus tard) : job `linux` sur ubuntu-latest produisant un AppImage
|
||||
# (jpackage --type app-image + appimagetool) + PyInstaller Linux du Brain,
|
||||
# attache a la MEME release. Reutilise la meme matrice / les memes etapes.
|
||||
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
||||
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
||||
# Brain empaquete via python-build-standalone (pas de Python embeddable Linux
|
||||
# officiel ; pas de PyInstaller -> pas de faux positif AV). Memes regles de
|
||||
# publication que windows : stable -> release publique ; beta -> pre-release.
|
||||
linux:
|
||||
needs: tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('v{0}', inputs.version) || github.ref }}
|
||||
|
||||
# Apporte jpackage (empaquetage natif) dans le PATH.
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
# Pas de setup-python : le Brain utilise SON python-build-standalone
|
||||
# (telecharge par le script, avec son propre pip). Le host n'en a pas besoin.
|
||||
|
||||
# Version (numerique X.Y.Z) + tag + isbeta, comme le job windows.
|
||||
- name: Derive version
|
||||
id: ver
|
||||
run: |
|
||||
if [ '${{ github.event_name }}' = 'workflow_dispatch' ]; then
|
||||
raw='${{ inputs.version }}'
|
||||
else
|
||||
raw='${{ github.ref_name }}'
|
||||
fi
|
||||
raw="${raw#v}" # 0.15.0 ou 0.15.0-beta
|
||||
num="${raw%%-*}" # 0.15.0
|
||||
case "$raw" in *-beta*) isbeta=true ;; *) isbeta=false ;; esac
|
||||
echo "version=$num" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$raw" >> "$GITHUB_OUTPUT"
|
||||
echo "isbeta=$isbeta" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build Linux AppImage
|
||||
env:
|
||||
# Authentifie l'appel API GitHub (resolution python-build-standalone) :
|
||||
# evite le rate limit 60/h anonyme des runners partages.
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
||||
|
||||
# L'AppImage est passee au job `publish`, seul a creer la release.
|
||||
- name: Keep AppImage for the release
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: installer-linux
|
||||
path: core/target/dist-out/DM_Loremind*.AppImage
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
# PUBLICATION : un seul job cree la release et y attache les deux installeurs.
|
||||
# Quand windows et linux publiaient chacun de leur cote, ils tournaient en
|
||||
# parallele et creaient DEUX releases pour le meme tag (une publiee, une en
|
||||
# brouillon), l'un echouant sur « already_exists ». Rien n'est publie si l'un
|
||||
# des deux builds echoue : une release a toujours ses deux installeurs.
|
||||
# Relancer le workflow pour une version deja publiee met la release a jour et
|
||||
# remplace les fichiers de meme nom (pas besoin de la supprimer).
|
||||
publish:
|
||||
needs: [windows, linux]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get installers
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: installer-*
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
|
||||
# tag_name explicite : en declenchement manuel, github.ref est une branche.
|
||||
# Une beta est publiee en pre-release (ignoree par /releases/latest).
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.windows.outputs.tag }}
|
||||
files: dist/*
|
||||
fail_on_unmatched_files: true
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ needs.windows.outputs.isbeta == 'true' }}
|
||||
|
||||
+8
-5
@@ -7,11 +7,6 @@
|
||||
brain/data/settings.json
|
||||
*.key
|
||||
*.pem
|
||||
# Exception : la cle PUBLIQUE JWT du relais Patreon est destinee a etre
|
||||
# embarquee dans le binaire. Pas de risque a la committer (c'est une cle
|
||||
# publique par construction). Sans cette exception, le module licensing
|
||||
# est silencieusement desactive dans les builds CI.
|
||||
!core/src/main/resources/licensing/jwt-public-key.pem
|
||||
|
||||
# ============================================================================
|
||||
# Java / Spring Boot / Maven
|
||||
@@ -123,3 +118,11 @@ brain/data/notebooks/5.json
|
||||
# ============================================================================
|
||||
docusaurus/loremind-patreon/
|
||||
installers/desktop/README.md
|
||||
|
||||
# Rapports de couverture de tests
|
||||
web/coverage/
|
||||
brain/htmlcov/
|
||||
brain/.coverage
|
||||
foundry-module/
|
||||
plan-promotion-loremind.md
|
||||
post-reddit-foundryvtt.md
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# Configuration MegaLinter — https://megalinter.io/latest/config-file/
|
||||
#
|
||||
# Périmètre volontairement resserré (liste ENABLE_LINTERS exclusive) : on
|
||||
# active les linters au fil de l'eau plutôt que de subir les ~100 par défaut.
|
||||
# Le scan CVE des dépendances n'est PAS ici : il est porté par le job Trivy
|
||||
# (cf. .gitea/workflows/quality.yml).
|
||||
|
||||
APPLY_FIXES: none
|
||||
DEFAULT_BRANCH: main
|
||||
SHOW_ELAPSED_TIME: true
|
||||
PRINT_ALPACA: false
|
||||
|
||||
# Liste EXCLUSIVE : tout linter absent d'ici est désactivé.
|
||||
ENABLE_LINTERS:
|
||||
# --- core (Java) : bugs + code smells "à la Sonar" sur les sources.
|
||||
# (Sonar for IDE reste pertinent en local pour l'analyse de flux fine.)
|
||||
- JAVA_PMD
|
||||
# --- brain (Python) ---
|
||||
- PYTHON_RUFF # remplace flake8/pylint/isort, très rapide
|
||||
- PYTHON_BANDIT # sécurité du code Python
|
||||
# - PYTHON_MYPY # à activer quand le brain aura des annotations de types
|
||||
# --- repo entier ---
|
||||
- REPOSITORY_GITLEAKS # secrets committés (tokens, mots de passe…)
|
||||
- DOCKERFILE_HADOLINT # bonnes pratiques Dockerfile
|
||||
# --- web (TypeScript) : PAS via MegaLinter. Le lint tourne avec la
|
||||
# toolchain du projet (job "web-lint" de quality.yml → ng lint,
|
||||
# config web/eslint.config.js avec angular-eslint + sonarjs).
|
||||
|
||||
# Jamais d'analyse des artefacts de build, dépendances et sites docs.
|
||||
FILTER_REGEX_EXCLUDE: '(^|/)(node_modules|target|dist|coverage|\.angular|\.mvn|docusaurus)/'
|
||||
|
||||
# Rapports déposés là où le workflow les publie en artefact CI.
|
||||
REPORT_OUTPUT_FOLDER: megalinter-reports
|
||||
|
||||
# Phase de rodage : passer temporairement à true pour rendre le job
|
||||
# informatif (rapport sans échec CI) le temps de purger l'existant.
|
||||
DISABLE_ERRORS: false
|
||||
|
||||
# PMD : ruleset projet à la racine (java-pmd-ruleset.xml, détecté
|
||||
# automatiquement) — orienté bugs réels, sans style. Non-bloquant le temps
|
||||
# de purger le backlog (~65 findings : PreserveStackTrace, EmptyCatchBlock,
|
||||
# CheckResultSet, RelianceOnDefaultCharset…). Repasser à false ensuite.
|
||||
JAVA_PMD_DISABLE_ERRORS: true
|
||||
+25
-14
@@ -1,4 +1,4 @@
|
||||
# LoreMind
|
||||
# DM Loremind
|
||||
|
||||
[English](README.md) · **Français**
|
||||
|
||||
@@ -7,36 +7,47 @@
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
## Découvrir LoreMind en vidéo
|
||||
## Découvrir DM Loremind en vidéo
|
||||
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
|
||||

|
||||
|
||||
## Ce que ça fait
|
||||
|
||||
LoreMind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
||||
DM Loremind regroupe ce qu'un MJ utilise habituellement éparpillé entre plusieurs outils. L'application s'articule autour de trois modules principaux, augmentés par un assistant IA qui exploite tout votre contenu.
|
||||
|
||||
### Lore
|
||||
|
||||
Construire votre univers avec une arborescence de pages templatées : lieux, factions, PNJ, événements, organisations... Chaque type de page suit un template configurable, ce qui garantit la cohérence et facilite la navigation dans des univers riches.
|
||||
|
||||
### Game System
|
||||
### Système de JDR
|
||||
|
||||
Stocker les règles de votre système de jeu (D&D, Nimble, créations maison...) et définir les modèles de fiches de personnages associés. Les règles indexées peuvent être injectées dans le contexte de l'IA pour des réponses fidèles à votre système.
|
||||
|
||||
### Campaign
|
||||
### Campagne
|
||||
|
||||
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du game system retenu.
|
||||
Structurer vos campagnes en Arcs → Chapitres → Scènes avec séparation claire du contenu MJ et du contenu joueurs. Gérer les PJ et PNJ via des fiches dynamiques basées sur les templates du système de JDR retenu.
|
||||
|
||||
### Assistant IA
|
||||
|
||||
Un assistant contextuel qui pioche dans votre Lore, vos règles et vos campagnes pour répondre à vos questions, suggérer du contenu cohérent, ou rebondir sur une situation improvisée en table.
|
||||
|
||||
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** ou via **[1min.ai](https://1min.ai/)**. D'autres moteurs seront supportés à l'avenir.
|
||||
L'IA s'exécute **en local via [Ollama](https://ollama.com/)** — vos données ne quittent jamais votre machine — ou dans le **cloud** avec votre propre clé API via [1min.ai](https://1min.ai/), [Mistral](https://mistral.ai/), [Google AI Studio (Gemini)](https://aistudio.google.com/) ou [OpenRouter](https://openrouter.ai/).
|
||||
|
||||
## Démarrage rapide
|
||||
|
||||
**Bureau (le plus simple)** — récupérez le dernier installeur sur la [page Releases](https://github.com/IGMLcreation/LoreMind/releases) : Windows `.msi` ou Linux `.AppImage`, puis lancez-le. Vos données restent en local.
|
||||
|
||||
**Auto-hébergement Docker** — sous Linux :
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/installers/install.sh | bash
|
||||
```
|
||||
|
||||
Sous Windows, suivez le [guide d'installation](https://loremind-docs.igmlcreation.fr/).
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -49,20 +60,20 @@ Une instance de démonstration est disponible sur **[loremind-demo.igmlcreation.
|
||||
Quelques limites à connaître :
|
||||
- 10 utilisateurs maximum simultanés (instances isolées)
|
||||
- Session limitée à 20 minutes avant réinitialisation
|
||||
- Partie IA non incluse dans la démo (nécessite Ollama ou 1min.ai côté serveur)
|
||||
- Fonctions IA non incluses dans la démo (elles nécessitent un fournisseur d'IA — Ollama en local ou une clé API cloud — configuré côté serveur)
|
||||
|
||||
## Soutenir le projet
|
||||
|
||||
LoreMind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||
DM Loremind est **et restera gratuit en auto-hébergement**. Le développement avance plus vite avec votre soutien :
|
||||
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — accès anticipé aux features, vote sur la roadmap, devlogs exclusifs
|
||||
- **Canal bêta** — les nouveautés en avant-première, gratuites pour tous : bascule depuis les Paramètres (Docker) ou pré-version GitHub (bureau)
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — annonces, support, retours utilisateurs
|
||||
|
||||
## Licence
|
||||
|
||||
LoreMind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||
DM Loremind est distribué sous licence **[GNU AGPL v3](LICENSE)**.
|
||||
|
||||
En pratique :
|
||||
- Vous pouvez l'utiliser gratuitement, l'héberger, la modifier, la redistribuer.
|
||||
- Si vous modifiez le code et que vous exposez l'application modifiée sur un réseau (même en SaaS privé), vous devez rendre vos modifications publiques sous la même licence.
|
||||
- Les univers (Lore) et campagnes que vous créez avec LoreMind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
- Les univers (Lore) et campagnes que vous créez avec DM Loremind **vous appartiennent entièrement** — la licence ne couvre que le code de l'application.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# LoreMind
|
||||
# DM Loremind
|
||||
|
||||
**English** · [Français](README.fr.md)
|
||||
|
||||
@@ -7,18 +7,17 @@
|
||||
[](LICENSE)
|
||||
[](https://loremind-docs.igmlcreation.fr/en/)
|
||||
[](https://loremind-demo.igmlcreation.fr/)
|
||||
[](https://www.patreon.com/c/IGMLCreation)
|
||||
[](https://discord.gg/cPpFzCjEzQ)
|
||||
|
||||
## See LoreMind in action
|
||||
## See DM Loremind in action
|
||||
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
[](https://www.youtube.com/watch?v=llJkmlotbB8)
|
||||
|
||||

|
||||
|
||||
## What it does
|
||||
|
||||
LoreMind brings together what a game master usually scatters across several tools. The app is built around three core modules, augmented by an AI assistant that draws on all of your content.
|
||||
DM Loremind brings together what a game master usually scatters across several tools. The app is built around three core modules, augmented by an AI assistant that draws on all of your content.
|
||||
|
||||
### Lore
|
||||
|
||||
@@ -36,7 +35,19 @@ Structure your campaigns as Arcs → Chapters → Scenes, with a clear split bet
|
||||
|
||||
A context-aware assistant that pulls from your Lore, rules and campaigns to answer your questions, suggest consistent content, or improvise around an unexpected situation at the table.
|
||||
|
||||
The AI runs **locally via [Ollama](https://ollama.com/)** or via **[1min.ai](https://1min.ai/)**. More engines will be supported in the future.
|
||||
The AI runs **locally via [Ollama](https://ollama.com/)** — your data stays on your machine — or in the **cloud** with your own API key via [1min.ai](https://1min.ai/), [Mistral](https://mistral.ai/), [Google AI Studio (Gemini)](https://aistudio.google.com/) or [OpenRouter](https://openrouter.ai/).
|
||||
|
||||
## Quick start
|
||||
|
||||
**Desktop (easiest)** — grab the latest installer from the [Releases page](https://github.com/IGMLcreation/LoreMind/releases): Windows `.msi` or Linux `.AppImage`, then run it. Your data stays local.
|
||||
|
||||
**Self-host with Docker** — on Linux:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/IGMLcreation/LoreMind/main/installers/install.sh | bash
|
||||
```
|
||||
|
||||
On Windows, follow the [installation guide](https://loremind-docs.igmlcreation.fr/en/).
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -49,20 +60,20 @@ A demo instance is available at **[loremind-demo.igmlcreation.fr](https://loremi
|
||||
A few limitations to be aware of:
|
||||
- 10 concurrent users maximum (isolated instances)
|
||||
- Sessions limited to 20 minutes before reset
|
||||
- The AI part is not included in the demo (requires Ollama or 1min.ai server-side)
|
||||
- The AI features are not included in the demo (they require an AI provider — local Ollama or a cloud API key — configured server-side)
|
||||
|
||||
## Support the project
|
||||
|
||||
LoreMind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||
DM Loremind is **and will remain free when self-hosted**. Development moves faster with your support:
|
||||
|
||||
- **[Patreon](https://www.patreon.com/c/IGMLCreation)** — early access to features, roadmap voting, exclusive devlogs
|
||||
- **Beta channel** — new features ahead of time, free for everyone: switch from Settings (Docker) or install a GitHub pre-release (desktop)
|
||||
- **[Discord](https://discord.gg/cPpFzCjEzQ)** — announcements, support, user feedback
|
||||
|
||||
## License
|
||||
|
||||
LoreMind is distributed under the **[GNU AGPL v3](LICENSE)** license.
|
||||
DM Loremind is distributed under the **[GNU AGPL v3](LICENSE)** license.
|
||||
|
||||
In practice:
|
||||
- You can use it for free, host it, modify it, and redistribute it.
|
||||
- If you modify the code and expose the modified app over a network (even as a private SaaS), you must make your changes public under the same license.
|
||||
- The worlds (Lore) and campaigns you create with LoreMind **belong entirely to you** — the license only covers the application's code.
|
||||
- The worlds (Lore) and campaigns you create with DM Loremind **belong entirely to you** — the license only covers the application's code.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Configuration de couverture (coverage.py / pytest-cov).
|
||||
# Rapport HTML (équivalent JaCoCo) : pytest --cov=app --cov-report=html → htmlcov/
|
||||
# Plancher anti-régression appliqué en CI : --cov-fail-under=50
|
||||
[run]
|
||||
source = app
|
||||
branch = false
|
||||
|
||||
[report]
|
||||
show_missing = true
|
||||
skip_covered = false
|
||||
# Lignes jamais comptées comme « à couvrir ».
|
||||
exclude_lines =
|
||||
pragma: no cover
|
||||
if __name__ == .__main__.:
|
||||
raise NotImplementedError
|
||||
@@ -2,3 +2,8 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.env
|
||||
|
||||
# Couverture de tests (pytest-cov)
|
||||
htmlcov/
|
||||
.coverage
|
||||
.pytest_cache/
|
||||
|
||||
+16
-6
@@ -111,14 +111,20 @@ def get_import_rules_use_case(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> ImportRulesUseCase:
|
||||
"""Factory du use case d'import de règles PDF (extraction + structuration)."""
|
||||
# Modèle LOCAL → mode segmentation : le LLM ne renvoie que les frontières des
|
||||
# sections (~200 tokens) et le texte original est découpé localement. Réécrire
|
||||
# tout le contenu à ~100 tokens/s prendrait des dizaines de minutes par livre.
|
||||
# Les providers cloud (rapides, grand contexte) gardent la réécriture nettoyée.
|
||||
# Les règles importées doivent correspondre au texte du PDF : l'IA ne le réécrit jamais,
|
||||
# quel que soit le fournisseur.
|
||||
# - Le livre est d'abord découpé par sa propre structure (signets du PDF, sinon titres
|
||||
# repérés), sans IA : immédiat, fidèle, identique sur toutes les machines (mesuré sur
|
||||
# 159 livres).
|
||||
# - Un PDF sans structure passe par l'IA en mode SEGMENTATION : elle ne renvoie que les
|
||||
# frontières des sections (~200 tokens) et le texte original est découpé tel quel.
|
||||
# La réécriture du contenu par un fournisseur cloud (texte « nettoyé » mais remanié)
|
||||
# n'est plus utilisée.
|
||||
return ImportRulesUseCase(
|
||||
llm=llm, extractor=_PDF_EXTRACTOR,
|
||||
chunk_target_tokens=_effective_import_chunk_tokens(settings),
|
||||
segment_only=settings.llm_provider == "ollama")
|
||||
segment_only=True,
|
||||
structure_first=True)
|
||||
|
||||
|
||||
def get_import_campaign_use_case(
|
||||
@@ -126,11 +132,15 @@ def get_import_campaign_use_case(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> ImportCampaignUseCase:
|
||||
"""Factory du use case d'import de campagne PDF (extraction + arborescence)."""
|
||||
# Comme pour les règles : le livre est d'abord rangé d'après sa propre structure, sans IA,
|
||||
# et le texte des scènes est celui du livre. Un modèle local traite les demandes l'une
|
||||
# après l'autre : lui en envoyer plusieurs ne ferait qu'allonger leur attente.
|
||||
return ImportCampaignUseCase(
|
||||
llm=llm,
|
||||
extractor=_PDF_EXTRACTOR,
|
||||
chunk_target_tokens=_effective_import_chunk_tokens(settings),
|
||||
map_concurrency=settings.llm_map_concurrency,
|
||||
map_concurrency=1 if settings.llm_provider == "ollama" else settings.llm_map_concurrency,
|
||||
structure_first=True,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Endpoint du chat contextuel (/chat/stream) : Structural Context + jauge tokens."""
|
||||
import json
|
||||
import logging
|
||||
from typing import Annotated, AsyncIterator
|
||||
|
||||
import tiktoken
|
||||
@@ -22,6 +23,8 @@ from app.core.language import get_user_language
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
||||
@@ -118,6 +121,7 @@ async def chat_stream(
|
||||
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||
yield "event: done\ndata: {}\n\n"
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Conversation : erreur du fournisseur IA : %s", exc)
|
||||
yield f"event: error\ndata: {json.dumps({'message': str(exc)})}\n\n"
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
|
||||
@@ -6,7 +6,14 @@ from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_generate_page_use_case, get_llm_provider
|
||||
from app.application.generate_page import GeneratePageUseCase
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import conversation_title as title_prompts
|
||||
from app.application.prompts import guided_answers as guided_answers_prompts
|
||||
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
||||
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
||||
from app.application.prompts import session_recap as session_recap_prompts
|
||||
from app.application.prompts import sheet_template as sheet_template_prompts
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.models import PageGenerationContext
|
||||
@@ -131,3 +138,338 @@ async def summarize_conversation_title(
|
||||
if not title:
|
||||
title = title_prompts.TITLE_FALLBACK.get(language, title_prompts.TITLE_FALLBACK["fr"])
|
||||
return SummarizeTitleResponseDTO(title=title)
|
||||
|
||||
|
||||
# --- Étoffer une entité narrative (Pilier A : co-MJ propose → l'humain valide) ----------
|
||||
|
||||
|
||||
class NarrativeFieldSpecDTO(BaseModel):
|
||||
"""Un champ autorisé : clé technique + libellé lisible (fourni par le Core)."""
|
||||
|
||||
key: str
|
||||
label: str = Field(default="")
|
||||
|
||||
|
||||
class NarrativeFieldsRequestDTO(BaseModel):
|
||||
"""Contexte envoyé par le Core pour proposer des valeurs de champs (arc/chapitre/scène)."""
|
||||
|
||||
entity_type: str = Field(default="")
|
||||
context: str = Field(default="")
|
||||
instruction: str = Field(default="")
|
||||
# Whitelist (clé + libellé) fournie par le Core, source de vérité.
|
||||
fields: list[NarrativeFieldSpecDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class NarrativeFieldsResponseDTO(BaseModel):
|
||||
"""Retour : une valeur proposée par clé (uniquement des clés autorisées, non vides)."""
|
||||
|
||||
fields: dict[str, str]
|
||||
|
||||
|
||||
@router.post("/generate/narrative-fields", response_model=NarrativeFieldsResponseDTO)
|
||||
async def generate_narrative_fields(
|
||||
body: NarrativeFieldsRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> NarrativeFieldsResponseDTO:
|
||||
"""Propose des valeurs pour ÉTOFFER une entité narrative (patch champ par champ, non appliqué).
|
||||
|
||||
Whitelist stricte : on ne retient que les clés autorisées, non vides. Un objet vide
|
||||
est une réponse VALIDE (le modèle n'a rien de pertinent à proposer — l'entité est
|
||||
peut-être déjà complète) ; seule une sortie non-JSON est une erreur.
|
||||
"""
|
||||
allowed = {f.key for f in body.fields if f.key}
|
||||
prompt = narrative_fields_prompts.narrative_fields_prompt(
|
||||
body.entity_type, body.context, body.instruction,
|
||||
[{"key": f.key, "label": f.label} for f in body.fields], language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.7)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de champs exploitables.")
|
||||
|
||||
out: dict[str, str] = {}
|
||||
raw_fields = parsed.get("fields")
|
||||
if isinstance(raw_fields, dict):
|
||||
for key, value in raw_fields.items():
|
||||
if key not in allowed:
|
||||
continue
|
||||
if not isinstance(value, (str, int, float)):
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if text:
|
||||
out[str(key)] = text
|
||||
return NarrativeFieldsResponseDTO(fields=out)
|
||||
|
||||
|
||||
# --- Peupler un chapitre en scènes (Pilier A : capacité « create ») ----------
|
||||
|
||||
|
||||
class SceneDraftsRequestDTO(BaseModel):
|
||||
"""Contexte envoyé par le Core pour ébaucher des scènes d'un chapitre."""
|
||||
|
||||
context: str = Field(default="")
|
||||
instruction: str = Field(default="")
|
||||
count: int = Field(default=4)
|
||||
|
||||
|
||||
class SceneDraftDTO(BaseModel):
|
||||
name: str
|
||||
description: str = Field(default="")
|
||||
playerNarration: str = Field(default="")
|
||||
|
||||
|
||||
class SceneDraftsResponseDTO(BaseModel):
|
||||
scenes: list[SceneDraftDTO]
|
||||
|
||||
|
||||
@router.post("/generate/scene-drafts", response_model=SceneDraftsResponseDTO)
|
||||
async def generate_scene_drafts(
|
||||
body: SceneDraftsRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> SceneDraftsResponseDTO:
|
||||
"""Propose des ébauches de scènes pour un chapitre (non créées). Un titre par scène
|
||||
est obligatoire ; on borne le nombre. Seule une sortie non-JSON est une erreur."""
|
||||
n = max(1, min(8, body.count))
|
||||
prompt = scene_drafts_prompts.scene_drafts_prompt(body.context, body.instruction, n, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de scènes exploitables.")
|
||||
|
||||
scenes: list[SceneDraftDTO] = []
|
||||
for s in (parsed.get("scenes") or [])[:n]:
|
||||
if not isinstance(s, dict):
|
||||
continue
|
||||
name = str(s.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
scenes.append(SceneDraftDTO(
|
||||
name=name[:200],
|
||||
description=str(s.get("description") or "").strip(),
|
||||
playerNarration=str(s.get("playerNarration") or "").strip(),
|
||||
))
|
||||
return SceneDraftsResponseDTO(scenes=scenes)
|
||||
|
||||
|
||||
# --- Récap « précédemment… » d'une séance (mode cockpit) ---------------------
|
||||
|
||||
|
||||
class SessionRecapRequestDTO(BaseModel):
|
||||
"""Journal chronologique de la séance précédente + méta courte."""
|
||||
|
||||
transcript: str
|
||||
context: str = Field(default="")
|
||||
|
||||
|
||||
class SessionRecapResponseDTO(BaseModel):
|
||||
recap: str
|
||||
|
||||
|
||||
@router.post("/generate/session-recap", response_model=SessionRecapResponseDTO)
|
||||
async def generate_session_recap(
|
||||
body: SessionRecapRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> SessionRecapResponseDTO:
|
||||
"""Rédige le récap « Précédemment… » à lire aux joueurs (texte libre, pas de JSON)."""
|
||||
if not body.transcript.strip():
|
||||
raise HTTPException(status_code=422, detail="Journal vide : rien à résumer.")
|
||||
prompt = session_recap_prompts.session_recap_prompt(body.transcript, body.context, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, temperature=0.7)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
recap = raw.strip()
|
||||
if not recap:
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
||||
return SessionRecapResponseDTO(recap=recap)
|
||||
|
||||
|
||||
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
|
||||
|
||||
|
||||
class GuidedOptionDTO(BaseModel):
|
||||
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
|
||||
|
||||
value: str
|
||||
label: str = Field(default="")
|
||||
|
||||
|
||||
class GuidedFieldDTO(BaseModel):
|
||||
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
|
||||
|
||||
key: str
|
||||
label: str = Field(default="")
|
||||
hint: str = Field(default="")
|
||||
step: str = Field(default="")
|
||||
options: list[GuidedOptionDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class GuidedAnswersRequestDTO(BaseModel):
|
||||
method_name: str = Field(default="")
|
||||
method_principle: str = Field(default="")
|
||||
idea: str = Field(default="")
|
||||
context: str = Field(default="")
|
||||
fields: list[GuidedFieldDTO] = Field(default_factory=list)
|
||||
existing: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class GuidedAnswersResponseDTO(BaseModel):
|
||||
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
|
||||
|
||||
answers: dict[str, str]
|
||||
|
||||
|
||||
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
|
||||
async def generate_guided_answers(
|
||||
body: GuidedAnswersRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> GuidedAnswersResponseDTO:
|
||||
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
|
||||
|
||||
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
|
||||
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
|
||||
"""
|
||||
by_key = {f.key: f for f in body.fields if f.key}
|
||||
prompt = guided_answers_prompts.guided_answers_prompt(
|
||||
body.method_name, body.method_principle, body.idea, body.context,
|
||||
[f.model_dump() for f in body.fields], body.existing, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
|
||||
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
|
||||
|
||||
|
||||
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
|
||||
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
|
||||
out: dict[str, str] = {}
|
||||
if not isinstance(raw, dict):
|
||||
return out
|
||||
for key, value in raw.items():
|
||||
field = by_key.get(str(key))
|
||||
if field is None or not isinstance(value, (str, int, float)):
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
continue
|
||||
if field.options and text not in {o.value for o in field.options}:
|
||||
continue
|
||||
out[field.key] = text
|
||||
return out
|
||||
|
||||
|
||||
# --- Modèle de fiche proposé à partir des règles (PJ, PNJ, ennemi) --------------------------
|
||||
|
||||
# Schéma de la sortie : passé tel quel aux modèles locaux (sortie structurée), traduit en
|
||||
# mode JSON par les fournisseurs cloud.
|
||||
_SHEET_TEMPLATE_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fields": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"type": {"type": "string", "enum": list(sheet_template_prompts.ALLOWED_TYPES)},
|
||||
"labels": {"type": "array", "items": {"type": "string"}},
|
||||
"source": {"type": "string"},
|
||||
},
|
||||
"required": ["name", "type"],
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": ["fields"],
|
||||
}
|
||||
|
||||
|
||||
class SheetTemplateRequestDTO(BaseModel):
|
||||
"""Sections de règles utiles (choisies et bornées par le Core) + champs déjà en place."""
|
||||
|
||||
sheet: Literal["character", "npc", "enemy"] = "character"
|
||||
system_name: str = Field(default="")
|
||||
sections: dict[str, str] = Field(default_factory=dict)
|
||||
existing_fields: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SheetFieldDTO(BaseModel):
|
||||
"""Un champ proposé. `type` est relayé tel quel : le Core écarte les types inconnus."""
|
||||
|
||||
name: str
|
||||
type: str
|
||||
labels: list[str] = Field(default_factory=list)
|
||||
source: str = Field(default="")
|
||||
|
||||
|
||||
class SheetTemplateResponseDTO(BaseModel):
|
||||
fields: list[SheetFieldDTO]
|
||||
|
||||
|
||||
@router.post("/generate/sheet-template", response_model=SheetTemplateResponseDTO)
|
||||
async def generate_sheet_template(
|
||||
body: SheetTemplateRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> SheetTemplateResponseDTO:
|
||||
"""Propose les champs d'une fiche (PJ, PNJ, ennemi) à partir des règles du système.
|
||||
|
||||
Rien n'est enregistré : le MJ coche les champs à ajouter à son modèle. Une liste vide
|
||||
signifie que les règles fournies ne décrivent pas cette fiche.
|
||||
"""
|
||||
sections = {t: c for t, c in body.sections.items() if t.strip() and c.strip()}
|
||||
if not sections:
|
||||
raise HTTPException(status_code=422, detail="Aucune règle fournie pour proposer une fiche.")
|
||||
prompt = sheet_template_prompts.sheet_template_prompt(
|
||||
body.sheet, body.system_name, sections, body.existing_fields, language)
|
||||
try:
|
||||
# Température basse : relevé fidèle de ce que disent les règles, pas de création.
|
||||
raw = await generate_with_retry(
|
||||
llm, prompt, output_format=_SHEET_TEMPLATE_SCHEMA, temperature=0.2)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de fiche exploitable.")
|
||||
return SheetTemplateResponseDTO(fields=_clean_sheet_fields(parsed.get("fields")))
|
||||
|
||||
|
||||
def _clean_sheet_fields(raw: object) -> list[SheetFieldDTO]:
|
||||
"""Garde les entrées bien formées (nom et type en texte) ; lignes et source nettoyées.
|
||||
|
||||
Le tri métier (doublons, types inconnus, listes sans lignes, plafond) est fait par le Core.
|
||||
"""
|
||||
out: list[SheetFieldDTO] = []
|
||||
if not isinstance(raw, list):
|
||||
return out
|
||||
for entry in raw:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
name, kind = entry.get("name"), entry.get("type")
|
||||
if not isinstance(name, str) or not name.strip() or not isinstance(kind, str):
|
||||
continue
|
||||
labels = entry.get("labels")
|
||||
source = entry.get("source")
|
||||
out.append(SheetFieldDTO(
|
||||
name=name.strip(),
|
||||
type=kind.strip().upper(),
|
||||
labels=[str(l).strip() for l in labels if isinstance(l, (str, int, float)) and str(l).strip()]
|
||||
if isinstance(labels, list) else [],
|
||||
source=source.strip() if isinstance(source, str) else "",
|
||||
))
|
||||
return out
|
||||
|
||||
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
|
||||
sections_by_language: dict[str, dict[str, str]] = {}
|
||||
source_language: str = ""
|
||||
|
||||
|
||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||
@@ -70,6 +73,8 @@ async def import_rules(
|
||||
sections=result.sections,
|
||||
page_count=result.page_count,
|
||||
ocr_page_count=result.ocr_page_count,
|
||||
sections_by_language=result.sections_by_language,
|
||||
source_language=result.source_language,
|
||||
)
|
||||
|
||||
|
||||
@@ -102,6 +107,7 @@ async def import_rules_stream(
|
||||
except PdfExtractionError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — filet : une erreur inattendue ne doit
|
||||
# PAS casser le flux SSE brutalement (sinon le Core n'a qu'un message générique
|
||||
@@ -115,12 +121,15 @@ async def import_rules_stream(
|
||||
@router.post("/import/campaign/stream")
|
||||
async def import_campaign_stream(
|
||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
file: UploadFile = File(...),
|
||||
) -> StreamingResponse:
|
||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
||||
|
||||
Évènements : `extracting`, `start` {page_count, ocr_page_count, total},
|
||||
`progress` {current, total, arc_count, chapter_count, scene_count},
|
||||
`extracted` {arcs:[...], npcs:[], split_method} — campagne découpée d'après la structure
|
||||
du livre, livrée avant les passes de l'IA (aides, traduction) —,
|
||||
`done` {arcs:[...], page_count, ocr_page_count}, `error` {message}.
|
||||
"""
|
||||
content = await file.read()
|
||||
@@ -131,12 +140,13 @@ async def import_campaign_stream(
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(content):
|
||||
async for ev in use_case.stream(content, language=language):
|
||||
event_type = ev.pop("type")
|
||||
yield sse_event(event_type, ev)
|
||||
except PdfExtractionError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas
|
||||
# une erreur inattendue casser le flux sans détail.
|
||||
@@ -183,6 +193,7 @@ async def adapt_campaign_stream(
|
||||
except PdfExtractionError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
|
||||
@@ -97,6 +97,7 @@ async def chat_notebook_stream(
|
||||
yield sse_event(ev_type, ev)
|
||||
yield sse_event("done", {})
|
||||
except (LLMProviderError, EmbeddingError) as exc:
|
||||
logger.warning("Atelier : erreur du fournisseur IA : %s", exc)
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux.
|
||||
logger.exception("Chat notebook : erreur inattendue.")
|
||||
@@ -125,6 +126,7 @@ async def chat_notebook_deep_stream(
|
||||
ev_type = ev.pop("type")
|
||||
yield sse_event(ev_type, ev)
|
||||
except (LLMProviderError, EmbeddingError) as exc:
|
||||
logger.warning("Atelier : erreur du fournisseur IA : %s", exc)
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale.
|
||||
logger.exception("Analyse approfondie : erreur inattendue.")
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Catalogue de sorts : relevé des sorts décrits dans un morceau de règles."""
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import spell_extraction as spell_prompts
|
||||
from app.application.spell_location import locate_spells, named_by_a_heading, unclaimed_headings
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Un petit modèle s'arrête parfois après quelques sorts. Quand les sorts du morceau sont des
|
||||
# intertitres et qu'une bonne part reste sans sort, il est relancé sur ceux qui manquent.
|
||||
MAX_PASSES = 3
|
||||
_MISSING_SHARE = 0.25
|
||||
|
||||
# Schéma de sortie : passé tel quel aux modèles locaux (sortie structurée), traduit en mode
|
||||
# JSON par les fournisseurs cloud.
|
||||
_SPELLS_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"spells": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
# Pas de description : le modèle désigne le sort, le code reprend son texte
|
||||
# dans les règles (cf. spell_location).
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"level": {"type": "string"},
|
||||
"school": {"type": "string"},
|
||||
"values": {"type": "object"},
|
||||
"start": {"type": "string"},
|
||||
},
|
||||
"required": ["name", "start"],
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": ["spells"],
|
||||
}
|
||||
|
||||
|
||||
class SpellFieldDTO(BaseModel):
|
||||
"""Un champ du modèle de sort du système. `type` : `TEXT` ou `NUMBER`."""
|
||||
|
||||
name: str = Field(default="")
|
||||
type: str = Field(default="TEXT")
|
||||
|
||||
|
||||
class SpellExtractionRequestDTO(BaseModel):
|
||||
"""Un morceau de règles (borné par le Core) et les champs à remplir pour chaque sort."""
|
||||
|
||||
system_name: str = Field(default="")
|
||||
section_title: str = Field(default="")
|
||||
text: str = Field(default="")
|
||||
fields: list[SpellFieldDTO] = Field(default_factory=list)
|
||||
avoid: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ExtractedSpellDTO(BaseModel):
|
||||
"""Un sort relevé. `description` : tranche du texte des règles, reprise telle quelle.
|
||||
`excerpt` : son début, que le Core retrouve mot pour mot dans le texte envoyé."""
|
||||
|
||||
name: str
|
||||
level: str = ""
|
||||
school: str = ""
|
||||
description: str
|
||||
values: dict[str, str] = Field(default_factory=dict)
|
||||
excerpt: str
|
||||
|
||||
|
||||
class SpellExtractionResponseDTO(BaseModel):
|
||||
spells: list[ExtractedSpellDTO]
|
||||
|
||||
|
||||
@router.post("/generate/spell-extraction", response_model=SpellExtractionResponseDTO)
|
||||
async def generate_spell_extraction(
|
||||
body: SpellExtractionRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> SpellExtractionResponseDTO:
|
||||
"""Relève les sorts décrits dans un morceau de règles. Rien n'est enregistré.
|
||||
|
||||
Le modèle désigne les sorts (nom, niveau, école, valeurs, premiers mots du bloc) ; la
|
||||
description de chacun est la tranche du texte qui suit son nom, reprise telle quelle. Le
|
||||
Core vérifie ensuite que le nom et le début de la description se retrouvent dans le texte
|
||||
envoyé ; une liste vide signifie que le morceau ne décrit aucun sort.
|
||||
"""
|
||||
if not body.text.strip():
|
||||
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
||||
fields = [f.model_dump() for f in body.fields]
|
||||
entries: list = []
|
||||
spells = []
|
||||
for attempt in range(MAX_PASSES):
|
||||
avoid = [*body.avoid, *(spell.name for spell in spells)]
|
||||
prompt = spell_prompts.spell_extraction_prompt(
|
||||
body.system_name, body.section_title, body.text, fields, avoid)
|
||||
try:
|
||||
# Température basse : on relève ce qui est écrit, on n'écrit rien.
|
||||
raw = await generate_with_retry(llm, prompt, output_format=_SPELLS_SCHEMA, temperature=0.1)
|
||||
except LLMProviderError as exc:
|
||||
if attempt == 0:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
break # une relance en échec ne retire rien à ce qui est déjà relevé
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
if attempt == 0:
|
||||
raise HTTPException(status_code=502,
|
||||
detail="Le modèle n'a pas renvoyé de liste de sorts exploitable.")
|
||||
break
|
||||
answer = parsed.get("spells")
|
||||
# D'une relance, seuls comptent les sorts que nomme un intertitre encore sans sort : le
|
||||
# modèle, poussé à en trouver d'autres, ne doit pas découper les sorts déjà relevés.
|
||||
fresh = answer if attempt == 0 else named_by_a_heading(answer, unclaimed_headings(body.text, spells))
|
||||
before = len(spells)
|
||||
entries.extend(fresh if isinstance(fresh, list) else [])
|
||||
spells = locate_spells(entries, body.text, body.section_title)
|
||||
missing = unclaimed_headings(body.text, spells)
|
||||
headings = len(missing) + len(spells)
|
||||
if not spells or len(spells) <= before and attempt > 0:
|
||||
break
|
||||
if len(missing) < 2 or len(missing) < _MISSING_SHARE * headings:
|
||||
break
|
||||
logger.info("Relevé de sorts « %s » : %s sort(s) relevé(s), %s intertitre(s) sans sort — relance.",
|
||||
body.section_title, len(spells), len(missing))
|
||||
return SpellExtractionResponseDTO(spells=[
|
||||
ExtractedSpellDTO(name=spell.name, level=spell.level, school=spell.school,
|
||||
description=spell.description, values=spell.values, excerpt=spell.excerpt)
|
||||
for spell in spells
|
||||
])
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Entraînement aux règles : série de situations à trancher, comparaison d'une réponse."""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import rule_training as rule_training_prompts
|
||||
from app.core.language import get_user_language
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Schémas de sortie : passés tels quels aux modèles locaux (sortie structurée), traduits en
|
||||
# mode JSON par les fournisseurs cloud.
|
||||
_DRILLS_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"drills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"scene": {"type": "integer"},
|
||||
"situation": {"type": "string"},
|
||||
"section": {"type": "string"},
|
||||
"excerpt": {"type": "string"},
|
||||
"ruling": {"type": "string"},
|
||||
},
|
||||
"required": ["situation", "section", "excerpt", "ruling"],
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": ["drills"],
|
||||
}
|
||||
|
||||
_REVIEW_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"verdict": {"type": "string", "enum": list(rule_training_prompts.VERDICTS)},
|
||||
"feedback": {"type": "string"},
|
||||
},
|
||||
"required": ["verdict", "feedback"],
|
||||
}
|
||||
|
||||
|
||||
class DrillSceneDTO(BaseModel):
|
||||
"""Une scène du scénario, résumée par le Core : le décor d'une situation."""
|
||||
|
||||
name: str = Field(default="")
|
||||
kind: str = Field(default="")
|
||||
text: str = Field(default="")
|
||||
|
||||
|
||||
class RuleDrillsRequestDTO(BaseModel):
|
||||
"""Sections de règles utiles (choisies et bornées par le Core) + scènes du scénario."""
|
||||
|
||||
system_name: str = Field(default="")
|
||||
sections: dict[str, str] = Field(default_factory=dict)
|
||||
scenes: list[DrillSceneDTO] = Field(default_factory=list)
|
||||
count: int = Field(default=5, ge=1, le=10)
|
||||
avoid: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class RuleDrillDTO(BaseModel):
|
||||
"""Une situation et son corrigé. `scene` : numéro de la scène (à partir de 1), 0 si aucune."""
|
||||
|
||||
scene: int = 0
|
||||
situation: str
|
||||
section: str
|
||||
excerpt: str
|
||||
ruling: str
|
||||
|
||||
|
||||
class RuleDrillsResponseDTO(BaseModel):
|
||||
drills: list[RuleDrillDTO]
|
||||
|
||||
|
||||
@router.post("/generate/rule-drills", response_model=RuleDrillsResponseDTO)
|
||||
async def generate_rule_drills(
|
||||
body: RuleDrillsRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> RuleDrillsResponseDTO:
|
||||
"""Prépare une série de situations à trancher, corrigé compris, en un seul appel.
|
||||
|
||||
Rien n'est enregistré. Le Core vérifie ensuite chaque extrait cité contre les règles
|
||||
envoyées ; une liste vide signifie que les extraits ne contiennent aucune règle de table.
|
||||
"""
|
||||
sections = {t: c for t, c in body.sections.items() if t.strip() and c.strip()}
|
||||
if not sections:
|
||||
raise HTTPException(status_code=422, detail="Aucune règle fournie pour préparer une série.")
|
||||
prompt = rule_training_prompts.rule_drills_prompt(
|
||||
body.system_name, sections, [s.model_dump() for s in body.scenes],
|
||||
body.count, body.avoid, language)
|
||||
try:
|
||||
# Température moyenne : des situations variées, mais un extrait recopié fidèlement.
|
||||
raw = await generate_with_retry(llm, prompt, output_format=_DRILLS_SCHEMA, temperature=0.5)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de série exploitable.")
|
||||
return RuleDrillsResponseDTO(drills=_clean_drills(parsed.get("drills")))
|
||||
|
||||
|
||||
def _clean_drills(raw: object) -> list[RuleDrillDTO]:
|
||||
"""Garde les situations complètes (quatre textes non vides) ; numéro de scène ramené à un entier.
|
||||
|
||||
La vérification de l'extrait contre les règles est faite par le Core.
|
||||
"""
|
||||
out: list[RuleDrillDTO] = []
|
||||
if not isinstance(raw, list):
|
||||
return out
|
||||
for entry in raw:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
texts = [entry.get(key) for key in ("situation", "section", "excerpt", "ruling")]
|
||||
if not all(isinstance(t, str) and t.strip() for t in texts):
|
||||
continue
|
||||
scene = entry.get("scene")
|
||||
if isinstance(scene, str) and scene.strip().isdigit():
|
||||
scene = int(scene.strip())
|
||||
out.append(RuleDrillDTO(
|
||||
scene=scene if isinstance(scene, int) and not isinstance(scene, bool) and scene > 0 else 0,
|
||||
situation=texts[0].strip(),
|
||||
section=texts[1].strip(),
|
||||
excerpt=texts[2].strip(),
|
||||
ruling=texts[3].strip(),
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
class RuleDrillReviewRequestDTO(BaseModel):
|
||||
"""La décision du MJ face au corrigé d'une situation."""
|
||||
|
||||
system_name: str = Field(default="")
|
||||
section_title: str = Field(default="")
|
||||
section_text: str = Field(default="")
|
||||
situation: str = Field(default="")
|
||||
excerpt: str = Field(default="")
|
||||
ruling: str = Field(default="")
|
||||
answer: str = Field(default="")
|
||||
|
||||
|
||||
class RuleDrillReviewResponseDTO(BaseModel):
|
||||
"""`verdict` : `right`, `partial` ou `off`."""
|
||||
|
||||
verdict: str
|
||||
feedback: str
|
||||
|
||||
|
||||
@router.post("/generate/rule-drill-review", response_model=RuleDrillReviewResponseDTO)
|
||||
async def generate_rule_drill_review(
|
||||
body: RuleDrillReviewRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
) -> RuleDrillReviewResponseDTO:
|
||||
"""Compare la décision écrite par le MJ aux règles et au corrigé de la situation."""
|
||||
if not body.answer.strip() or not body.situation.strip() or not body.section_text.strip():
|
||||
raise HTTPException(status_code=422, detail="Situation, règles et réponse sont nécessaires.")
|
||||
prompt = rule_training_prompts.rule_drill_review_prompt(
|
||||
body.system_name, body.section_title, body.section_text, body.situation,
|
||||
body.excerpt, body.ruling, body.answer, language)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format=_REVIEW_SCHEMA, temperature=0.2)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
parsed, _ = load_json_object(raw)
|
||||
verdict = parsed.get("verdict") if isinstance(parsed, dict) else None
|
||||
feedback = parsed.get("feedback") if isinstance(parsed, dict) else None
|
||||
if (not isinstance(verdict, str) or verdict.strip().lower() not in rule_training_prompts.VERDICTS
|
||||
or not isinstance(feedback, str) or not feedback.strip()):
|
||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de comparaison exploitable.")
|
||||
return RuleDrillReviewResponseDTO(verdict=verdict.strip().lower(), feedback=feedback.strip())
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Arbre d'un livre de campagne → arcs, aventures (chapitres), scènes et salles — sans IA.
|
||||
|
||||
Le livre dit lui-même comment il est découpé (cf. pdf_structure.book_outline). Ici on range
|
||||
cet arbre dans les entités de l'appli, sans réécrire un mot : le texte d'une scène est la
|
||||
tranche du livre qui lui correspond.
|
||||
|
||||
- Les chapitres du livre deviennent les AVENTURES (chapitres de l'appli). Si le livre est
|
||||
découpé en parties (« Part 1 », « Acte II », « Livre premier »), elles deviennent les ARCS ;
|
||||
sinon tout va dans un seul arc.
|
||||
- Les sections d'un chapitre deviennent ses SCÈNES. Une section trop longue est rendue par
|
||||
ses sous-sections ; le texte d'introduction d'un chapitre fait une scène de présentation.
|
||||
- Une section dont les sous-sections sont des lieux numérotés (« 1. Entrée », « A3. Poste
|
||||
de garde », « Area 4 ») est un lieu explorable : UNE scène, ses lieux en SALLES.
|
||||
- Couverture, crédits, sommaire, index et mentions légales ne sont pas repris.
|
||||
- Les ANNEXES (bestiaire, objets magiques, aides de jeu) ne sont pas des scènes à jouer :
|
||||
elles vont dans un arc à part, en ordre libre, regroupées en quelques scènes de lecture
|
||||
plutôt qu'en une scène par créature ou par objet.
|
||||
|
||||
Ce module ne remplit ni le synopsis d'une scène ni les fiches de PNJ : ce sont des aides
|
||||
écrites par l'IA, ajoutées ensuite (cf. import_campaign). Sans IA, le synopsis est le début du
|
||||
texte de la scène.
|
||||
|
||||
Logique pure : elle ne voit qu'un `BookOutline`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.application.pdf_structure import BookOutline, OutlineNode, outline_text
|
||||
|
||||
# Au-delà, une section qui a des sous-sections est rendue par elles : une scène se lit d'une
|
||||
# traite pendant la partie.
|
||||
MAX_SCENE_CHARS = 15_000
|
||||
# En-deçà, un texte d'introduction ne fait pas une scène à lui seul : il ouvre la suivante.
|
||||
MIN_TEXT_CHARS = 200
|
||||
SEPARATOR = " › "
|
||||
# Longueur du synopsis de repli (le début du texte de la scène).
|
||||
LEAD_CHARS = 240
|
||||
|
||||
# Titres de premier niveau qui ne sont pas de la matière de jeu.
|
||||
_SKIPPED_TITLES = {
|
||||
"cover", "couverture", "front cover", "back cover", "quatrieme de couverture", "title page",
|
||||
"page de titre", "credits", "credit", "contents", "table of contents", "table des matieres",
|
||||
"sommaire", "index", "legal", "legal appendix", "license", "licence", "open game license",
|
||||
"open game licence", "ogl", "copyright", "colophon", "mentions legales",
|
||||
}
|
||||
_SKIPPED_STARTS = ("table of contents", "table des matieres", "open game licen", "credits", "legal ")
|
||||
_FILE_NAME = re.compile(r"\.(pdf|indd|docx?|qxp)$", re.IGNORECASE)
|
||||
_COVER = re.compile(r"\b(cover|couverture)\b")
|
||||
_COVER_MAX_CHARS = 2_000
|
||||
# Un nœud est une enveloppe s'il porte au moins cette part du livre et assez de sous-sections.
|
||||
_WRAPPER_SHARE = 0.6
|
||||
_WRAPPER_CHILDREN = 3
|
||||
|
||||
# Annexes : « Appendix A », « Annexe 2 », et en fin de livre les titres de matière de référence.
|
||||
_APPENDIX = re.compile(r"^(?:appendix|appendices|appendice|annexe|annexes)\b")
|
||||
_REFERENCE_TITLES = (
|
||||
"new monsters", "new creatures", "new magic items", "new spells", "new items", "magic items",
|
||||
"monsters", "creatures", "bestiary", "handouts", "pregenerated characters", "glossary",
|
||||
"nouveaux monstres", "nouvelles creatures", "nouveaux objets", "nouveaux sorts", "objets magiques",
|
||||
"monstres", "bestiaire", "aides de jeu", "personnages pretires", "pretires", "glossaire",
|
||||
)
|
||||
_TITLE_CHARS = 40
|
||||
|
||||
# « Part 1 », « Partie II », « Act Three », « Livre premier », « Tome 2 ».
|
||||
_PART = re.compile(
|
||||
r"^(?:part|partie|act|acte|book|livre|tome|volume)\b[\s.:–—-]*"
|
||||
r"(?:\d+|[ivxlc]+|one|two|three|four|five|six|un|une|deux|trois|quatre|cinq|six|"
|
||||
r"premi[eè]re?|seconde?|deuxi[eè]me|troisi[eè]me|quatri[eè]me)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Lieu numéroté d'un donjon : « 1. Entrée », « A3. Poste de garde », « T-10. Antre »,
|
||||
# « 12 – Crypte », « Area 4: Hall », « Salle 2 ».
|
||||
_AREA = re.compile(
|
||||
r"^(?:(?:area|zone|salle|room|pi[eè]ce|location|lieu)\s+)?(?:[A-Za-z]{1,2}-?)?\d{1,3}[a-z]?\s*[.:)–—-]\s*\S"
|
||||
r"|^(?:area|zone|salle|room|pi[eè]ce)\s+[A-Za-z]?\d",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _fold(text: str) -> str:
|
||||
text = unicodedata.normalize("NFD", text)
|
||||
text = "".join(c for c in text if unicodedata.category(c) != "Mn").lower()
|
||||
return re.sub(r"[^a-z0-9]+", " ", text).strip()
|
||||
|
||||
|
||||
def is_skipped(title: str) -> bool:
|
||||
"""Le titre désigne-t-il une partie du livre qui n'est pas de la matière de jeu ?"""
|
||||
folded = _fold(title)
|
||||
return (not folded or folded in _SKIPPED_TITLES or folded.startswith(_SKIPPED_STARTS)
|
||||
or bool(_FILE_NAME.search(title.strip())))
|
||||
|
||||
|
||||
def lead(text: str, limit: int = LEAD_CHARS) -> str:
|
||||
"""Début du texte : son premier paragraphe ordinaire, coupé à la fin d'une phrase."""
|
||||
for paragraph in text.split("\n\n"):
|
||||
paragraph = " ".join(paragraph.split())
|
||||
if not paragraph or paragraph.startswith(("#", "|", "- ")):
|
||||
continue
|
||||
if len(paragraph) <= limit:
|
||||
return paragraph
|
||||
cut = max(paragraph.rfind(mark, 0, limit) for mark in (". ", "! ", "? ", "… "))
|
||||
if cut >= limit // 3:
|
||||
return paragraph[:cut + 1]
|
||||
cut = paragraph.rfind(" ", 0, limit)
|
||||
return paragraph[:cut if cut > 0 else limit] + "…"
|
||||
return ""
|
||||
|
||||
|
||||
def _content_nodes(outline: BookOutline) -> list[OutlineNode]:
|
||||
"""Nœuds de premier niveau qui portent la matière du livre.
|
||||
|
||||
Les signets d'un PDF sont souvent mal rangés : tout le livre sous un signet au nom de
|
||||
fichier (« Hall of the Rainbow Mage 5e.pdf »), ou sous « Crédits ». Un nœud qui contient
|
||||
l'essentiel du livre est donc une ENVELOPPE : ce sont ses enfants, les chapitres — même si
|
||||
son titre est de ceux qu'on ne reprend pas. Sont ensuite écartés la couverture, les
|
||||
crédits, le sommaire, l'index, les mentions légales, et les nœuds presque vides
|
||||
(légendes de cartes)."""
|
||||
nodes = list(outline.nodes)
|
||||
total = sum(node.chars for node in nodes)
|
||||
while True:
|
||||
# Un gros bestiaire en annexe n'est pas l'enveloppe du livre.
|
||||
wrapper = next((node for node in nodes
|
||||
if len(node.children) >= _WRAPPER_CHILDREN and node.chars >= _WRAPPER_SHARE * total
|
||||
and not _is_reference_title(node.title)), None)
|
||||
if wrapper is None:
|
||||
break
|
||||
position = nodes.index(wrapper)
|
||||
own: list[OutlineNode] = []
|
||||
if len(wrapper.text) >= MIN_TEXT_CHARS and not is_skipped(wrapper.title):
|
||||
own = [OutlineNode(wrapper.title, wrapper.level, wrapper.page, wrapper.text)]
|
||||
nodes[position:position + 1] = [*own, *wrapper.children]
|
||||
return [node for node in nodes if not _left_out(node)]
|
||||
|
||||
|
||||
def _left_out(node: OutlineNode) -> bool:
|
||||
if is_skipped(node.title) or node.chars < MIN_TEXT_CHARS:
|
||||
return True
|
||||
# « … Cover PDF », « Back Cover » : une couverture, tant qu'elle ne porte presque rien.
|
||||
return bool(_COVER.search(_fold(node.title))) and node.chars < _COVER_MAX_CHARS
|
||||
|
||||
|
||||
def _scene(name: str, notes: str, rooms: list[dict] | None = None) -> dict:
|
||||
return {"name": name, "description": "", "player_narration": "", "gm_notes": notes.strip(),
|
||||
"rooms": rooms or []}
|
||||
|
||||
|
||||
def _join(*parts: str) -> str:
|
||||
return "\n\n".join(part for part in parts if part and part.strip())
|
||||
|
||||
|
||||
def _areas(node: OutlineNode) -> list[OutlineNode]:
|
||||
"""Sous-sections qui sont des lieux numérotés — si elles sont au moins deux et la majorité."""
|
||||
areas = [child for child in node.children if _AREA.match(child.title)]
|
||||
return areas if len(areas) >= 2 and len(areas) * 2 >= len(node.children) else []
|
||||
|
||||
|
||||
def _explorable(node: OutlineNode, name: str, intro: str, path: list[str], out: list[dict]) -> None:
|
||||
"""Un lieu explorable : une scène, ses lieux numérotés en salles.
|
||||
|
||||
Ses autres sous-sections restent dans le texte de la scène — sauf celles qui sont
|
||||
elles-mêmes un lieu explorable, ou trop longues : elles font leurs propres scènes, à la
|
||||
suite (un donjon rangé sous la région qui y mène garde ainsi ses salles)."""
|
||||
areas = _areas(node)
|
||||
inside: list[OutlineNode] = []
|
||||
apart: list[OutlineNode] = []
|
||||
for child in node.children:
|
||||
if child in areas:
|
||||
continue
|
||||
on_its_own = bool(_areas(child)) or (bool(child.children) and child.chars > MAX_SCENE_CHARS)
|
||||
(apart if on_its_own else inside).append(child)
|
||||
notes = _join(intro, node.text, *(_join(f"### {child.title}", outline_text(child, 1)) for child in inside))
|
||||
rooms = [{"name": area.title, "description": outline_text(area), "enemies": "", "loot": ""} for area in areas]
|
||||
out.append(_scene(name, notes, rooms))
|
||||
for child in apart:
|
||||
_scenes(child, path, out)
|
||||
|
||||
|
||||
def _scenes(node: OutlineNode, path: list[str], out: list[dict], intro: str = "") -> None:
|
||||
"""Scènes que donne `node`, section d'un chapitre. `path` : ses ancêtres sous le chapitre."""
|
||||
name = SEPARATOR.join([*path, node.title][-2:])
|
||||
if _areas(node):
|
||||
_explorable(node, name, intro, [*path, node.title], out)
|
||||
return
|
||||
if node.children and node.chars > MAX_SCENE_CHARS:
|
||||
own = _join(intro, node.text)
|
||||
carry = ""
|
||||
if len(own) >= MIN_TEXT_CHARS:
|
||||
out.append(_scene(name, own))
|
||||
else:
|
||||
carry = own
|
||||
for position, child in enumerate(node.children):
|
||||
_scenes(child, [*path, node.title], out, carry if position == 0 else "")
|
||||
return
|
||||
out.append(_scene(name, _join(intro, outline_text(node))))
|
||||
|
||||
|
||||
def _reference_nodes(nodes: list[OutlineNode]) -> list[OutlineNode]:
|
||||
"""Nœuds de premier niveau qui sont des annexes : ceux qui s'appellent ainsi, et en fin de
|
||||
livre ceux dont le titre annonce de la matière de référence (« New Creatures »,
|
||||
« Bestiaire »). Aucun si tout le livre en serait : ce n'est alors pas une campagne."""
|
||||
found = [node for node in nodes if _APPENDIX.match(_fold(node.title))]
|
||||
for node in reversed(nodes):
|
||||
folded = _fold(node.title)
|
||||
if node in found:
|
||||
continue
|
||||
if folded in _REFERENCE_TITLES or folded.startswith(_REFERENCE_TITLES):
|
||||
found.append(node)
|
||||
else:
|
||||
break
|
||||
return [] if len(found) == len(nodes) else [node for node in nodes if node in found]
|
||||
|
||||
|
||||
def _is_reference_title(title: str) -> bool:
|
||||
folded = _fold(title)
|
||||
return bool(_APPENDIX.match(folded)) or folded in _REFERENCE_TITLES or folded.startswith(_REFERENCE_TITLES)
|
||||
|
||||
|
||||
def _entries(node: OutlineNode) -> list[OutlineNode]:
|
||||
"""Sous-sections d'une annexe, une trop longue étant rendue par les siennes."""
|
||||
out: list[OutlineNode] = []
|
||||
for child in node.children:
|
||||
if child.children and child.chars > MAX_SCENE_CHARS:
|
||||
if child.text.strip():
|
||||
out.append(OutlineNode(child.title, child.level, child.page, child.text))
|
||||
out.extend(_entries(child))
|
||||
else:
|
||||
out.append(child)
|
||||
return out
|
||||
|
||||
|
||||
def _reference_scene(group: list[OutlineNode], intro: str) -> dict:
|
||||
"""Une scène de lecture pour des entrées d'annexe qui se suivent."""
|
||||
if len(group) == 1:
|
||||
entry = group[0]
|
||||
scene = _scene(entry.title, _join(intro, outline_text(entry)))
|
||||
titles = [child.title for child in entry.children]
|
||||
else:
|
||||
first, last = group[0].title[:_TITLE_CHARS], group[-1].title[:_TITLE_CHARS]
|
||||
scene = _scene(f"{first} – {last}", _join(intro, *(
|
||||
_join(f"### {entry.title}", outline_text(entry, 1)) for entry in group)))
|
||||
titles = [entry.title for entry in group]
|
||||
# Synopsis : ce que la scène contient. L'IA n'en rédige pas pour une annexe.
|
||||
scene["description"] = ", ".join(titles)[:LEAD_CHARS]
|
||||
return scene
|
||||
|
||||
|
||||
def _reference_chapter(node: OutlineNode, overview_title: str) -> dict:
|
||||
"""Une annexe : ses entrées regroupées, dans l'ordre du livre, en scènes de lecture."""
|
||||
entries = _entries(node)
|
||||
scenes: list[dict] = []
|
||||
if not entries:
|
||||
scenes.append(_scene(node.title, node.text))
|
||||
else:
|
||||
intro = ""
|
||||
if len(node.text) >= MIN_TEXT_CHARS:
|
||||
scenes.append(_scene(overview_title, node.text))
|
||||
else:
|
||||
intro = node.text
|
||||
group: list[OutlineNode] = []
|
||||
size = 0
|
||||
for entry in entries:
|
||||
if group and size + entry.chars > MAX_SCENE_CHARS:
|
||||
scenes.append(_reference_scene(group, intro))
|
||||
group, size, intro = [], 0, ""
|
||||
group.append(entry)
|
||||
size += entry.chars
|
||||
scenes.append(_reference_scene(group, intro))
|
||||
return {"name": node.title, "description": "", "scenes": _unique(scenes)}
|
||||
|
||||
|
||||
def _unique(scenes: list[dict]) -> list[dict]:
|
||||
"""Scènes non vides, noms uniques dans le chapitre."""
|
||||
seen: dict[str, int] = {}
|
||||
out: list[dict] = []
|
||||
for scene in scenes:
|
||||
if not scene["gm_notes"] and not scene["rooms"]:
|
||||
continue
|
||||
count = seen.get(scene["name"], 0) + 1
|
||||
seen[scene["name"]] = count
|
||||
if count > 1:
|
||||
scene["name"] = f"{scene['name']} ({count})"
|
||||
scene["description"] = scene["description"] or lead(scene["gm_notes"])
|
||||
out.append(scene)
|
||||
return out
|
||||
|
||||
|
||||
def _chapter(node: OutlineNode, overview_title: str) -> dict:
|
||||
scenes: list[dict] = []
|
||||
if _areas(node):
|
||||
_explorable(node, node.title, "", [], scenes)
|
||||
elif not node.children:
|
||||
scenes.append(_scene(node.title, node.text))
|
||||
else:
|
||||
carry = ""
|
||||
if len(node.text) >= MIN_TEXT_CHARS:
|
||||
scenes.append(_scene(overview_title, node.text))
|
||||
else:
|
||||
carry = node.text
|
||||
for position, child in enumerate(node.children):
|
||||
_scenes(child, [], scenes, carry if position == 0 else "")
|
||||
return {"name": node.title, "description": "", "scenes": _unique(scenes)}
|
||||
|
||||
|
||||
def campaign_from_outline(
|
||||
outline: BookOutline,
|
||||
*,
|
||||
default_arc: str = "Aventure principale",
|
||||
overview_title: str = "Présentation",
|
||||
appendix_arc: str = "Annexes",
|
||||
) -> list[dict]:
|
||||
"""Arcs → chapitres → scènes → salles, au format du flux d'import (dicts).
|
||||
|
||||
Chaque scène porte son texte dans `gm_notes` (le livre, mot pour mot) et, en synopsis de
|
||||
repli, le début de ce texte dans `description`. Les annexes forment un dernier arc, marqué
|
||||
`reference` : de la lecture, pas des scènes à jouer. Liste vide si le livre n'a pas de matière."""
|
||||
nodes = _content_nodes(outline)
|
||||
reference = _reference_nodes(nodes)
|
||||
nodes = [node for node in nodes if node not in reference]
|
||||
parts = [node for node in nodes if _PART.match(node.title.strip())]
|
||||
arcs: list[dict] = []
|
||||
if len(parts) >= 2:
|
||||
# Livre découpé en parties : chacune est un arc, ses chapitres sont les aventures.
|
||||
for node in nodes:
|
||||
if node in parts and node.children:
|
||||
chapters = [_chapter(child, overview_title) for child in node.children]
|
||||
if len(node.text) >= MIN_TEXT_CHARS:
|
||||
chapters.insert(0, {"name": overview_title, "description": "",
|
||||
"scenes": _unique([_scene(overview_title, node.text)])})
|
||||
else:
|
||||
chapters = [_chapter(node, overview_title)]
|
||||
arcs.append({"name": node.title, "description": "", "type": "LINEAR", "chapters": chapters})
|
||||
else:
|
||||
arcs.append({"name": default_arc, "description": "", "type": "LINEAR",
|
||||
"chapters": [_chapter(node, overview_title) for node in nodes]})
|
||||
if reference:
|
||||
# Ordre libre : on consulte une annexe, on ne la joue pas à la suite.
|
||||
arcs.append({"name": appendix_arc, "description": "", "type": "HUB", "reference": True,
|
||||
"chapters": [_reference_chapter(node, overview_title) for node in reference]})
|
||||
|
||||
for arc in arcs:
|
||||
arc["chapters"] = [chapter for chapter in arc["chapters"] if chapter["scenes"]]
|
||||
return [arc for arc in arcs if arc["chapters"]]
|
||||
|
||||
|
||||
def counts(arcs: list[dict]) -> tuple[int, int, int, int]:
|
||||
"""(arcs, chapitres, scènes, salles)."""
|
||||
chapters = [chapter for arc in arcs for chapter in arc["chapters"]]
|
||||
scenes = [scene for chapter in chapters for scene in chapter["scenes"]]
|
||||
return len(arcs), len(chapters), len(scenes), sum(len(scene["rooms"]) for scene in scenes)
|
||||
|
||||
|
||||
def all_scenes(arcs: list[dict]) -> list[dict]:
|
||||
"""Toutes les scènes, dans l'ordre du livre."""
|
||||
return [scene for arc in arcs for chapter in arc["chapters"] for scene in chapter["scenes"]]
|
||||
|
||||
|
||||
def played_scenes(arcs: list[dict]) -> list[dict]:
|
||||
"""Scènes de l'aventure elle-même, sans celles des annexes."""
|
||||
return all_scenes([arc for arc in arcs if not arc.get("reference")])
|
||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.application.campaign_structure import all_scenes, campaign_from_outline, counts, played_scenes
|
||||
from app.application.chunking import chunk_text, split_in_half
|
||||
from app.application.import_status import (
|
||||
notify_status,
|
||||
@@ -21,8 +24,17 @@ from app.application.import_status import (
|
||||
)
|
||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.pdf_structure import BOOKMARKS, NONE, book_outline
|
||||
from app.application.prompts import import_campaign as prompts
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.application.rules_translation import (
|
||||
DEFAULT_CONCURRENCY,
|
||||
LANGUAGES,
|
||||
RulesTranslator,
|
||||
detect_language,
|
||||
translate_sections,
|
||||
)
|
||||
from app.application.streaming import HEARTBEAT_INTERVAL_SECONDS, with_heartbeat
|
||||
from app.core.language import language_name
|
||||
|
||||
# Repli anti-troncature : si la sortie d'un morceau est coupée, on le retraite en
|
||||
# 2 moitiés. Borné en profondeur (3 niveaux => jusqu'à 8 sous-blocs).
|
||||
@@ -52,6 +64,35 @@ _TEMPERATURE = 0.1
|
||||
# d'un coup et le structure de façon cohérente (1 scène par lieu) au lieu de le
|
||||
# fragmenter en dizaines de scènes. Adapté aux providers à grand contexte (1min.ai).
|
||||
_CHUNK_TARGET_TOKENS = 10000
|
||||
# Import par la structure du livre : conversion approchée tokens → caractères pour la taille
|
||||
# d'un lot d'aides, nombre de scènes par lot, longueur d'un synopsis, durée accordée aux aides.
|
||||
_CHARS_PER_TOKEN = 3
|
||||
_MAX_SCENES_PER_BATCH = 12
|
||||
_MAX_SYNOPSIS_CHARS = 400
|
||||
_ROOM_LIST_CHARS = 600
|
||||
AIDS_BUDGET_SECONDS = 30 * 60
|
||||
# Durée accordée à la traduction d'une campagne. Plus longue que pour des règles : un livre de
|
||||
# 200 pages compte des centaines de textes (50 minutes mesurées avec un petit modèle local sur
|
||||
# une carte rapide), et une campagne à moitié traduite sert peu. Reste sous la durée maximale
|
||||
# d'un import côté Core (4 heures).
|
||||
TRANSLATION_BUDGET_SECONDS = 3 * 60 * 60
|
||||
# Échantillon de texte utilisé pour reconnaître la langue du livre.
|
||||
_DETECT_CHARS = 20_000
|
||||
# Réponse attendue pour les aides : un synopsis par scène (repérée par son numéro), des PNJ.
|
||||
_AIDS_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"scenes": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"properties": {"n": {"type": "integer"}, "synopsis": {"type": "string"}},
|
||||
"required": ["n", "synopsis"]}},
|
||||
"npcs": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"properties": {"name": {"type": "string"}, "description": {"type": "string"}},
|
||||
"required": ["name"]}},
|
||||
},
|
||||
"required": ["scenes"],
|
||||
}
|
||||
|
||||
# Schéma de l'arbre attendu, passé aux providers à sorties structurées (Ollama
|
||||
# contraint la grammaire : un modèle local ne PEUT plus produire de clés
|
||||
@@ -352,18 +393,42 @@ class ImportCampaignUseCase:
|
||||
extractor: PdfTextExtractor,
|
||||
chunk_target_tokens: int = _CHUNK_TARGET_TOKENS,
|
||||
map_concurrency: int = 1,
|
||||
structure_first: bool = False,
|
||||
) -> None:
|
||||
self._llm = llm
|
||||
self._extractor = extractor
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
# `structure_first` : ranger d'abord le livre d'après SA structure (signets du PDF,
|
||||
# sinon titres repérés), sans IA. Le texte des scènes est alors celui du livre, mot
|
||||
# pour mot ; l'IA n'écrit que des aides (synopsis, fiches de PNJ) et la traduction.
|
||||
self._structure_first = structure_first
|
||||
# Taille (caractères) d'un lot de scènes confié à l'IA pour ses aides.
|
||||
self._aid_batch_chars = max(4_000, chunk_target_tokens * _CHARS_PER_TOKEN)
|
||||
self._translation_concurrency = DEFAULT_CONCURRENCY if map_concurrency > 1 else 1
|
||||
self._heartbeat_seconds = HEARTBEAT_INTERVAL_SECONDS
|
||||
self._aids_budget_seconds = AIDS_BUDGET_SECONDS
|
||||
self._translation_budget_seconds = TRANSLATION_BUDGET_SECONDS
|
||||
# Appels MAP par VAGUES de cette taille : l'ordre narratif est préservé
|
||||
# (fusion vague par vague, dans l'ordre du livre) mais le mur d'attente
|
||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||
self._map_concurrency = max(1, map_concurrency)
|
||||
|
||||
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
|
||||
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
structured = self._structure(doc, language)
|
||||
if structured is not None:
|
||||
arcs, method = structured
|
||||
done: dict = {}
|
||||
async for event in self._structured_stream(doc, arcs, method, language):
|
||||
if event["type"] == "done":
|
||||
done = event
|
||||
return CampaignImportResult(
|
||||
arcs=_arcs_from_dicts(done.get("arcs", [])),
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
npcs=[NpcImportProposal(n["name"], n["description"]) for n in done.get("npcs", [])],
|
||||
)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
toc_block = _format_toc(doc.toc)
|
||||
merger = _TreeMerger()
|
||||
@@ -371,7 +436,7 @@ class ImportCampaignUseCase:
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
results = await asyncio.gather(*(
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||
for i, c in wave
|
||||
))
|
||||
for res in results:
|
||||
@@ -386,7 +451,7 @@ class ImportCampaignUseCase:
|
||||
npcs=merger.npcs(),
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes):
|
||||
async def stream(self, pdf_bytes: bytes, language: str = "fr"):
|
||||
"""Variante streamée : yield des évènements d'avancement.
|
||||
|
||||
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
||||
@@ -397,6 +462,12 @@ class ImportCampaignUseCase:
|
||||
yield {"type": "extracting"}
|
||||
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
structured = self._structure(doc, language)
|
||||
if structured is not None:
|
||||
arcs, method = structured
|
||||
async for event in self._structured_stream(doc, arcs, method, language):
|
||||
yield event
|
||||
return
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
toc_block = _format_toc(doc.toc)
|
||||
total = len(chunks)
|
||||
@@ -432,7 +503,7 @@ class ImportCampaignUseCase:
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
gathered = asyncio.gather(
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||
for i, c in wave),
|
||||
return_exceptions=True,
|
||||
)
|
||||
@@ -512,6 +583,147 @@ class ImportCampaignUseCase:
|
||||
finally:
|
||||
reset_status_queue(status_token)
|
||||
|
||||
# --- Import par la structure du livre ------------------------------------
|
||||
|
||||
def _structure(self, doc, language: str) -> tuple[list[dict], str] | None:
|
||||
"""Arbre de la campagne tiré de la structure du PDF, ou None s'il faut passer par
|
||||
l'IA (réglage coupé, PDF sans signets ni titres repérables, livre sans matière)."""
|
||||
if not self._structure_first:
|
||||
return None
|
||||
outline = book_outline(doc)
|
||||
if outline.method == NONE:
|
||||
logger.info("Import campagne : pas de structure exploitable dans ce PDF — découpage par l'IA.")
|
||||
return None
|
||||
arcs = campaign_from_outline(
|
||||
outline, default_arc=prompts.default_arc_name(language),
|
||||
overview_title=prompts.overview_title(language),
|
||||
appendix_arc=prompts.appendix_arc_name(language))
|
||||
if not arcs:
|
||||
return None
|
||||
return arcs, outline.method
|
||||
|
||||
async def _structured_stream(self, doc, arcs: list[dict], method: str, language: str):
|
||||
"""Campagne découpée par la structure du livre : le texte est déjà là. Deux passes de
|
||||
l'IA, toutes deux facultatives — un échec ne retire rien au texte : les AIDES (synopsis
|
||||
de chaque scène, fiches des PNJ nommés), puis la TRADUCTION si le livre n'est pas dans
|
||||
la langue de l'interface."""
|
||||
scenes = all_scenes(arcs)
|
||||
arc_count, chapter_count, scene_count, room_count = counts(arcs)
|
||||
# Les annexes (bestiaire, objets) ne reçoivent pas d'aides : leur synopsis est la liste
|
||||
# de ce qu'elles contiennent, et un profil de créature n'est pas un PNJ.
|
||||
batches = _aid_batches(played_scenes(arcs), self._aid_batch_chars)
|
||||
total = max(1, len(batches))
|
||||
logger.info("Import campagne : %s page(s), découpage par la structure du PDF (%s) : %s arc(s), "
|
||||
"%s aventure(s), %s scène(s), %s salle(s), sans IA ; %s lot(s) d'aides.",
|
||||
doc.page_count, method, arc_count, chapter_count, scene_count, room_count, len(batches))
|
||||
yield {"type": "start", "page_count": doc.page_count, "ocr_page_count": doc.ocr_page_count, "total": total}
|
||||
origin = "la table des matières du PDF" if method == BOOKMARKS else "les titres du livre"
|
||||
|
||||
def progress(current: int, npc_count: int, skipped: int) -> dict:
|
||||
return {"type": "progress", "current": current, "total": total, "arc_count": arc_count,
|
||||
"chapter_count": chapter_count, "scene_count": scene_count,
|
||||
"npc_count": npc_count, "skipped": skipped}
|
||||
|
||||
# L'avancement d'abord : à l'écran, il efface le message d'état en cours.
|
||||
yield progress(0, 0, 0)
|
||||
yield {"type": "status",
|
||||
"message": f"Découpage d'après {origin} : {chapter_count} aventure(s), "
|
||||
f"{scene_count} scène(s), sans IA."}
|
||||
|
||||
# L'arbre est livré AVANT les passes de l'IA : si le flux s'interrompt ensuite, le Core
|
||||
# a déjà la campagne, avec le texte du livre.
|
||||
yield {"type": "extracted", "arcs": arcs, "npcs": [], "page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count, "split_method": method}
|
||||
|
||||
# --- Aides : synopsis des scènes et fiches de PNJ --------------------------------
|
||||
npcs: dict[str, dict] = {}
|
||||
skipped = 0
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + self._aids_budget_seconds
|
||||
for index, batch in enumerate(batches):
|
||||
if loop.time() >= deadline:
|
||||
yield {"type": "status",
|
||||
"message": "Temps imparti aux aides de l'IA dépassé : les scènes restantes "
|
||||
"gardent le début de leur texte en guise de synopsis."}
|
||||
break
|
||||
yield {"type": "status",
|
||||
"message": f"Texte du livre repris tel quel ({scene_count} scène(s)). L'IA rédige les "
|
||||
f"synopsis et relève les PNJ : lot {index + 1}/{total}…"}
|
||||
try:
|
||||
parsed: dict | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._aids(batch, language), interval=self._heartbeat_seconds):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": index + 1, "total": total}
|
||||
elif kind == "result":
|
||||
parsed = payload
|
||||
_apply_aids(batch, parsed, npcs)
|
||||
except LLMProviderError as exc:
|
||||
skipped += 1
|
||||
logger.warning("Aides de l'IA : lot %s/%s ignoré : %s", index + 1, total, exc)
|
||||
yield {"type": "chunk_failed", "current": index + 1, "total": total, "message": str(exc)[:300]}
|
||||
yield progress(index + 1, len(npcs), skipped)
|
||||
|
||||
# Créatures génériques prises pour des PNJ : jugées sur tout le texte du livre, tant
|
||||
# qu'il est dans sa langue d'origine.
|
||||
played = played_scenes(arcs)
|
||||
book_text = "\n".join(_aid_text(scene, 10 ** 9) for scene in played)
|
||||
npcs = {key: npc for key, npc in npcs.items() if not _is_generic(npc["name"], book_text)}
|
||||
# Personnes réelles (auteurs, éditeurs) : citées seulement là où le livre parle de lui-même.
|
||||
npcs = _met_in_the_adventure(npcs, played)
|
||||
|
||||
# --- Traduction fidèle, si le livre n'est pas dans la langue de l'interface -------
|
||||
untranslated = 0
|
||||
sample = "\n".join(scene["gm_notes"] for scene in scenes)[:_DETECT_CHARS]
|
||||
source = detect_language(sample, default=language)
|
||||
if source != language and language in LANGUAGES:
|
||||
units, labels = _translation_units(scenes)
|
||||
try:
|
||||
async for kind, payload in translate_sections(
|
||||
RulesTranslator(self._llm), units, source, language,
|
||||
concurrency=self._translation_concurrency,
|
||||
budget_seconds=self._translation_budget_seconds,
|
||||
heartbeat_seconds=self._heartbeat_seconds,
|
||||
with_titles=False, labels=labels):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": total, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload}
|
||||
else:
|
||||
untranslated = len(payload.untranslated)
|
||||
_apply_translation(scenes, payload.sections)
|
||||
if untranslated:
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(language)}) incomplète : "
|
||||
f"{untranslated} texte(s) sur {len(units)} gardent la langue du livre."}
|
||||
except LLMProviderError as exc:
|
||||
untranslated = len(units)
|
||||
logger.warning("Traduction de la campagne (%s) impossible : %s", language, exc)
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(language)}) impossible : {str(exc)[:200]}"}
|
||||
|
||||
yield {
|
||||
"type": "done",
|
||||
"arcs": arcs,
|
||||
"npcs": list(npcs.values()),
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
"split_method": method,
|
||||
"source_language": source,
|
||||
"untranslated": untranslated,
|
||||
}
|
||||
|
||||
async def _aids(self, batch: list[tuple[int, dict]], language: str) -> dict | None:
|
||||
"""Un appel au modèle pour les aides d'un lot de scènes → JSON {scenes, npcs}."""
|
||||
listing = "\n\n".join(
|
||||
f"=== SCÈNE {number} : {scene['name']} ===\n{_aid_text(scene, self._aid_batch_chars // 2)}"
|
||||
for number, (_, scene) in enumerate(batch, start=1))
|
||||
prompt = prompts.AIDS_PROMPT.format(language_name=language_name(language), scenes=listing)
|
||||
raw = await generate_with_retry(self._llm, prompt, output_format=_AIDS_SCHEMA, temperature=_TEMPERATURE)
|
||||
parsed, _ = load_json_object(raw)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
|
||||
# --- Consolidation finale (fusion des quasi-doublons) ---------------------
|
||||
|
||||
async def _consolidate(self, merger: _TreeMerger) -> None:
|
||||
@@ -553,21 +765,23 @@ class ImportCampaignUseCase:
|
||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||
|
||||
async def _map_chunk(
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = ""
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
|
||||
) -> dict:
|
||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||
return await self._extract_payload(
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block)
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
|
||||
|
||||
async def _extract_payload(
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
|
||||
language: str = "fr",
|
||||
) -> dict:
|
||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||
prompt = (
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
|
||||
+ prompts.language_block(language)
|
||||
+ toc_section
|
||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||
"Renvoie maintenant le JSON de l'arborescence."
|
||||
@@ -591,9 +805,9 @@ class ImportCampaignUseCase:
|
||||
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||
"re-découpage en 2 moitiés plus digestes…")
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
payload, truncated = self._parse_payload(raw, index=index)
|
||||
|
||||
@@ -607,9 +821,9 @@ class ImportCampaignUseCase:
|
||||
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||
"re-découpage en 2 moitiés plus digestes…")
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
if truncated:
|
||||
logger.warning(
|
||||
@@ -639,6 +853,281 @@ class ImportCampaignUseCase:
|
||||
return empty, recovered
|
||||
|
||||
|
||||
# --- Import par la structure du livre : lots d'aides, traduction ------------------------------
|
||||
|
||||
def _aid_text(scene: dict, limit: int) -> str:
|
||||
"""Texte d'une scène confié au modèle pour ses aides : ses notes et ses salles, borné.
|
||||
|
||||
Un lieu explorable s'ouvre sur la liste de ses pièces : son texte est surtout dans leurs
|
||||
descriptions, dont le modèle ne verra que le début."""
|
||||
names = "; ".join(room["name"] for room in scene["rooms"])[:_ROOM_LIST_CHARS]
|
||||
listing = f"[Lieu explorable, {len(scene['rooms'])} pièce(s) : {names}]" if names else ""
|
||||
rooms = "\n\n".join(f"{room['name']}\n{room['description']}" for room in scene["rooms"])
|
||||
return "\n\n".join(part for part in (listing, scene["gm_notes"], rooms) if part)[:limit]
|
||||
|
||||
|
||||
def _aid_batches(scenes: list[dict], budget_chars: int) -> list[list[tuple[int, dict]]]:
|
||||
"""Scènes regroupées en lots, dans l'ordre du livre, chacun sous `budget_chars`. Une
|
||||
scène plus longue que la moitié du budget y est bornée (cf. _aid_text) : seules les aides
|
||||
en dépendent, son texte reste entier."""
|
||||
batches: list[list[tuple[int, dict]]] = []
|
||||
current: list[tuple[int, dict]] = []
|
||||
size = 0
|
||||
for index, scene in enumerate(scenes):
|
||||
length = min(len(_aid_text(scene, budget_chars // 2)), budget_chars // 2) + len(scene["name"]) + 30
|
||||
if current and (size + length > budget_chars or len(current) >= _MAX_SCENES_PER_BATCH):
|
||||
batches.append(current)
|
||||
current, size = [], 0
|
||||
current.append((index, scene))
|
||||
size += length
|
||||
if current:
|
||||
batches.append(current)
|
||||
return batches
|
||||
|
||||
|
||||
def _fold(text: str) -> str:
|
||||
return " ".join("".join(c.lower() if c.isalnum() else " " for c in text).split())
|
||||
|
||||
|
||||
def _apply_aids(batch: list[tuple[int, dict]], parsed: dict | None, npcs: dict[str, dict]) -> None:
|
||||
"""Range les aides du modèle : le synopsis de chaque scène, et les PNJ dont le NOM figure
|
||||
bien dans le texte du lot (un PNJ inventé est écarté)."""
|
||||
if not parsed:
|
||||
return
|
||||
for item in parsed.get("scenes") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
number = int(item.get("n"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
synopsis = " ".join(str(item.get("synopsis") or "").split())
|
||||
if 1 <= number <= len(batch) and synopsis:
|
||||
batch[number - 1][1]["description"] = synopsis[:_MAX_SYNOPSIS_CHARS]
|
||||
haystack = _fold("\n".join(scene["name"] + "\n" + _aid_text(scene, 10 ** 9) for _, scene in batch))
|
||||
for item in parsed.get("npcs") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
# Appel de note collé au nom par la mise en page (« King RatII », « RidwikI »).
|
||||
name = _FOOTNOTE_MARK.sub("", " ".join(str(item.get("name") or "").split()))
|
||||
key = _fold(name)
|
||||
# Un nom sans majuscule (« ogre », « gobelins ») est une créature générique ; un nom
|
||||
# tout en capitales (« ZOMBIE SARGASSIEN ») est le titre d'un profil de créature.
|
||||
if len(key) < 3 or key not in haystack or not any(c.isupper() for c in name) or name.isupper():
|
||||
continue
|
||||
description = " ".join(str(item.get("description") or "").split())
|
||||
if _is_group(name, description):
|
||||
continue
|
||||
known = _same_npc(name, npcs)
|
||||
if known is None:
|
||||
npcs[key] = {"name": name, "description": description}
|
||||
continue
|
||||
# Déjà relevé, parfois sous un nom plus court (« Arumvel », « Arumvel the Wicked ») :
|
||||
# on garde le nom le plus complet et la fiche la plus fournie.
|
||||
if len(name) > len(known["name"]):
|
||||
known["name"] = name
|
||||
if len(description) > len(known["description"]):
|
||||
known["description"] = description
|
||||
|
||||
|
||||
# Titres placés devant un nom : « dame Cynaëlle » et « Cynaëlle de Tyrmallan » sont la même.
|
||||
_HONORIFICS = frozenset("""
|
||||
dame sire seigneur maitre maitresse capitaine lieutenant commandant commandante sergent general
|
||||
pere mere frere soeur sœur roi reine prince princesse baron baronne comte comtesse duc duchesse
|
||||
docteur professeur messire monsieur madame mademoiselle
|
||||
lord lady sir captain master mistress father mother brother sister king queen duke duchess
|
||||
count countess doctor dr professor mr mrs miss
|
||||
""".split())
|
||||
|
||||
|
||||
_ARTICLES = frozenset({"le", "la", "l", "les", "the"})
|
||||
|
||||
|
||||
def _bare_name(key: str) -> str:
|
||||
"""Nom sans l'article ni les titres qui le précèdent (au moins un mot est gardé)."""
|
||||
words = key.split()
|
||||
while len(words) > 1 and (words[0] in _ARTICLES or _strip_accents(words[0]) in _HONORIFICS):
|
||||
words.pop(0)
|
||||
return " ".join(words)
|
||||
|
||||
|
||||
def _strip_accents(text: str) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFD", text) if unicodedata.category(c) != "Mn")
|
||||
|
||||
|
||||
def _aliases(name: str) -> list[str]:
|
||||
"""Noms sous lesquels un PNJ est connu : « Arvell/Alezzandro » en porte deux."""
|
||||
return [alias for alias in (_bare_name(_fold(part)) for part in name.split("/")) if alias]
|
||||
|
||||
|
||||
def _same_npc(name: str, npcs: dict[str, dict]) -> dict | None:
|
||||
"""PNJ déjà relevé sous ce nom — à un titre près, à un tiret près (« Trois-Doigts »,
|
||||
« Troisdoigts ») — ou sous un nom dont celui-ci est le début (ou l'inverse)."""
|
||||
names = _aliases(name)
|
||||
for entry in npcs.values():
|
||||
for other in _aliases(entry["name"]):
|
||||
for mine in names:
|
||||
if (mine.replace(" ", "") == other.replace(" ", "")
|
||||
or mine.startswith(other + " ") or other.startswith(mine + " ")):
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
_FOOTNOTE_MARK = re.compile(r"(?<=[a-zà-ÿ])I{1,3}$")
|
||||
_FOOTNOTE_IN_TEXT = re.compile(r"(?<=[a-zà-ÿ])I{1,3}(?![^\W\d_])")
|
||||
# Mots qui désignent un groupe, en tête ou en fin de nom (« Rump family », « Légion noire »).
|
||||
_GROUP_NAME_WORDS = frozenset("""
|
||||
famille family clan guilde guild legion ordre order tribu tribe culte cult secte sect faction
|
||||
gardes guards soldats soldiers villageois villagers cultistes cultists pirates bandits milice militia
|
||||
""".split())
|
||||
# Début d'une fiche qui décrit un groupe : « Ce sont… », « C'est un clan… », « La famille… ».
|
||||
_GROUP_DESCRIPTION = re.compile(
|
||||
r"^(?:ce sont|ils sont|elles sont|they are|these are|those are)\b"
|
||||
r"|^(?:(?:c est|il s agit d|it is|this is)\s+)?(?:(?:un|une|le|la|l|ce|cet|cette|ces|d un|d une|a|an|the|this)\s+)?"
|
||||
r"(?:clan|guilde|guild|secte|sect|culte|cult|groupe|group|faction|organisation|organization|famille|family"
|
||||
r"|peuple|race|tribu|tribe|ordre|order|espece|species|bande|band|gang|compagnie|company)\b")
|
||||
|
||||
|
||||
_COUNT_WORDS = frozenset("""
|
||||
two three four five six seven eight nine ten eleven twelve several many some
|
||||
deux trois quatre cinq six sept huit neuf dix onze douze plusieurs quelques
|
||||
""".split())
|
||||
|
||||
|
||||
_LETTER = r"[^\W\d_]"
|
||||
_ELISION = re.compile(r"^l['’]", re.IGNORECASE)
|
||||
_INDEFINITE = "|".join(sorted({"un", "une", "des", "a", "an", *_COUNT_WORDS}, key=len, reverse=True))
|
||||
|
||||
|
||||
def _without_article(name: str) -> list[str]:
|
||||
"""Mots du nom sans l'article qui le précède : « La commandante », « L'aubergiste »."""
|
||||
words = name.split()
|
||||
if len(words) > 1 and words[0].lower() in _ARTICLES:
|
||||
words = words[1:]
|
||||
elif words and _ELISION.match(words[0]) and len(words[0]) > 2:
|
||||
words = [_ELISION.sub("", words[0]), *words[1:]]
|
||||
return words
|
||||
|
||||
|
||||
def _is_unique_role(phrase: str, book_text: str) -> bool:
|
||||
"""Le livre parle-t-il de CE personnage plutôt que d'une créature parmi d'autres ?
|
||||
|
||||
Un rôle unique sans nom est toujours désigné par l'article défini (« la commandante »,
|
||||
« the innkeeper ») ; une créature générique apparaît aussi avec un article indéfini, un
|
||||
nombre ou au pluriel (« a wraith », « deux gobelins », « ghosts »)."""
|
||||
target = re.escape(phrase)
|
||||
flags = re.IGNORECASE
|
||||
definite = re.findall(rf"(?<!{_LETTER})(?:le |la |l['’]|the ){target}(?!{_LETTER})", book_text, flags)
|
||||
indefinite = re.search(rf"(?<!{_LETTER})(?:{_INDEFINITE}|\d+) {target}", book_text, flags)
|
||||
plural = re.search(rf"(?<!{_LETTER}){target}(?:s|es|x)(?!{_LETTER})", book_text, flags)
|
||||
return len(definite) >= 2 and not indefinite and not plural
|
||||
|
||||
|
||||
def _is_generic(name: str, book_text: str) -> bool:
|
||||
"""Le nom est-il celui d'une créature générique plutôt que d'un personnage ?
|
||||
|
||||
« Nine ghouls » commence par un nombre. Sinon, pour un nom dont seul le premier mot porte
|
||||
une majuscule (« Wraith », « Giant rat »), on regarde comment le livre l'écrit : un nom
|
||||
commun y figure en minuscules (« a wraith ») et jamais avec une majuscule en cours de
|
||||
phrase ; un nom propre, si (« led by Key », « Paltuis le mage »). Un nom commun reste un
|
||||
PNJ quand il désigne un rôle unique (« la commandante » : cf. _is_unique_role)."""
|
||||
words = _without_article(name)
|
||||
if not words:
|
||||
return True
|
||||
first = words[0]
|
||||
if first[0].isdigit() or first.lower() in _COUNT_WORDS:
|
||||
return True
|
||||
if any(word[:1].isupper() for word in words[1:]):
|
||||
return False
|
||||
capital = first[:1].upper() + first[1:]
|
||||
common = re.search(rf"(?<!{_LETTER}){re.escape(first.lower())}(?!{_LETTER})", book_text)
|
||||
proper = re.search(rf"[a-zà-ÿ,;:] {re.escape(capital)}(?!{_LETTER})", book_text)
|
||||
if not common or proper:
|
||||
return False
|
||||
return not _is_unique_role(" ".join(words).lower(), book_text)
|
||||
|
||||
|
||||
# Titres des textes où le livre parle de lui-même : préface, note de l'auteur, mode d'emploi.
|
||||
_FRONT_MATTER = re.compile(
|
||||
r"^(?:foreword|preface|avant propos|a note from|note from|notes? de l auteur|notes? des auteurs"
|
||||
r"|mot de l auteur|about the authors?|a propos de l auteur|a propos des auteurs|acknowledg\w*"
|
||||
r"|remerciements|dedication|dedicace|how this book|how to use|using this"
|
||||
r"|about this (?:book|adventure|module)|comment utiliser|a propos de (?:ce|cet|cette))\b")
|
||||
# Une année de notre monde et un mot d'édition dans le même texte : l'histoire du livre, pas celle
|
||||
# de l'aventure (« First published in 1977… », « Financé sur Kickstarter en 2019 »).
|
||||
_REAL_YEAR = re.compile(r"(?<!\d)(?:19[7-9]\d|20[0-3]\d)(?!\d)")
|
||||
_PUBLISHING = re.compile(
|
||||
r"\b(?:publish\w*|publi[ée]e?s?|kickstarter|copyright|play-?test\w*|isbn|reprint\w*|r[ée][ée]dit\w*"
|
||||
r"|game designers?|role-?playing|jeux? de r[ôo]le)\b|©", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_about_the_book(scene: dict) -> bool:
|
||||
"""La scène parle-t-elle du livre (préface, historique de l'édition) plutôt que de l'aventure ?"""
|
||||
titles = [_strip_accents(_fold(part)) for part in scene["name"].split("›")]
|
||||
if any(_FRONT_MATTER.match(title) for title in titles):
|
||||
return True
|
||||
text = scene["gm_notes"]
|
||||
return bool(_REAL_YEAR.search(text) and _PUBLISHING.search(text))
|
||||
|
||||
|
||||
def _met_in_the_adventure(npcs: dict[str, dict], scenes: list[dict]) -> dict[str, dict]:
|
||||
"""PNJ dont le nom figure dans l'aventure elle-même. Une personne citée seulement dans une
|
||||
préface ou dans l'historique de l'édition (un auteur, un éditeur) est une personne réelle."""
|
||||
fiction = [scene for scene in scenes if not _is_about_the_book(scene)]
|
||||
if not fiction or len(fiction) == len(scenes):
|
||||
return npcs
|
||||
raw = "\n".join(scene["name"] + "\n" + _aid_text(scene, 10 ** 9) for scene in fiction)
|
||||
# Un appel de note collé au nom (« PandemagisticatorII ») ne doit pas le rendre introuvable.
|
||||
text = " " + _fold(_FOOTNOTE_IN_TEXT.sub("", raw)) + " "
|
||||
return {key: npc for key, npc in npcs.items()
|
||||
if any(f" {alias} " in text for alias in _aliases(npc["name"]))}
|
||||
|
||||
|
||||
def _is_group(name: str, description: str) -> bool:
|
||||
"""Le nom ou la fiche désigne-t-il un groupe (peuple, clan, gardes) plutôt qu'un individu ?"""
|
||||
words = _strip_accents(_fold(name)).split()
|
||||
if not words or words[0] in ("les", "des") or words[0] in _GROUP_NAME_WORDS or words[-1] in _GROUP_NAME_WORDS:
|
||||
return True
|
||||
return bool(_GROUP_DESCRIPTION.match(_strip_accents(_fold(description))))
|
||||
|
||||
|
||||
def _translation_units(scenes: list[dict]) -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""Textes à traduire (notes des scènes, descriptions des salles), repérés par une clé, et
|
||||
leur libellé pour les messages d'avancement."""
|
||||
units: dict[str, str] = {}
|
||||
labels: dict[str, str] = {}
|
||||
for index, scene in enumerate(scenes):
|
||||
if scene["gm_notes"].strip():
|
||||
units[f"s{index}"] = scene["gm_notes"]
|
||||
labels[f"s{index}"] = scene["name"]
|
||||
for rank, room in enumerate(scene["rooms"]):
|
||||
if room["description"].strip():
|
||||
units[f"s{index}r{rank}"] = room["description"]
|
||||
labels[f"s{index}r{rank}"] = f"{scene['name']} › {room['name']}"
|
||||
return units, labels
|
||||
|
||||
|
||||
def _apply_translation(scenes: list[dict], translated: dict[str, str]) -> None:
|
||||
"""Remet chaque texte traduit à sa place. Un texte non traduit revient tel quel."""
|
||||
for index, scene in enumerate(scenes):
|
||||
scene["gm_notes"] = translated.get(f"s{index}", scene["gm_notes"])
|
||||
for rank, room in enumerate(scene["rooms"]):
|
||||
room["description"] = translated.get(f"s{index}r{rank}", room["description"])
|
||||
|
||||
|
||||
def _arcs_from_dicts(arcs: list[dict]) -> list[ArcProposal]:
|
||||
return [
|
||||
ArcProposal(arc["name"], arc["description"], arc.get("type", "LINEAR"), [
|
||||
ChapterProposal(chapter["name"], chapter["description"], [
|
||||
SceneProposal(scene["name"], scene["description"], scene["player_narration"], scene["gm_notes"],
|
||||
[RoomProposal(r["name"], r["description"], r["enemies"], r["loot"])
|
||||
for r in scene["rooms"]])
|
||||
for scene in chapter["scenes"]])
|
||||
for chapter in arc["chapters"]])
|
||||
for arc in arcs
|
||||
]
|
||||
|
||||
|
||||
def _serialize_arcs(arcs: list[ArcProposal]) -> list[dict]:
|
||||
"""Sérialise l'arbre de dataclasses en dicts JSON pour le flux SSE."""
|
||||
return [
|
||||
|
||||
@@ -25,8 +25,16 @@ from app.application.import_status import (
|
||||
)
|
||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.pdf_structure import BOOKMARKS, NONE, StructureSplit, split_by_structure
|
||||
from app.application.prompts import import_rules as prompts
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.application.rules_translation import (
|
||||
DEFAULT_CONCURRENCY,
|
||||
RulesTranslator,
|
||||
detect_language,
|
||||
other_languages,
|
||||
translate_sections,
|
||||
)
|
||||
from app.application.streaming import HEARTBEAT_INTERVAL_SECONDS, with_heartbeat
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
|
||||
# Repli anti-troncature : si la SORTIE d'un morceau est coupée (le modèle ne peut
|
||||
@@ -90,6 +98,21 @@ _ANCHORS_SCHEMA: dict = {
|
||||
}
|
||||
|
||||
|
||||
# Méthode de découpage annoncée à l'appelant quand c'est l'IA qui a découpé le livre.
|
||||
AI_SPLIT = "ai"
|
||||
# Nombre de titres de section annoncés d'un coup dans le flux d'avancement.
|
||||
_ANNOUNCED_TITLES = 40
|
||||
|
||||
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
|
||||
_DETECT_CHARS = 20_000
|
||||
|
||||
# Mode segmentation : clé interne du texte d'un morceau que le modèle n'a pas su découper
|
||||
# (aucun repère retrouvé, réponse illisible, appel en échec). Le texte original est entre
|
||||
# nos mains : il n'est JAMAIS abandonné — la fusion le place à la suite de la section
|
||||
# précédente (cf. _SectionMerger). Un petit modèle local perdait ainsi, sans rien dire,
|
||||
# 1 morceau sur 15 d'un livre de 29 pages (mesuré le 2026-11-13).
|
||||
UNSORTED = "\x00unsorted"
|
||||
|
||||
class _SectionMerger:
|
||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||
|
||||
@@ -98,15 +121,22 @@ class _SectionMerger:
|
||||
morceau — sert au flux de progression pour annoncer les sections trouvées.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, unsorted_title: str = "") -> None:
|
||||
"""`unsorted_title` : titre donné au texte non découpé quand aucune section ne le
|
||||
précède (premier morceau du livre)."""
|
||||
self._merged: dict[str, list[str]] = {}
|
||||
self._canonical_key: dict[str, str] = {}
|
||||
self._last: str | None = None
|
||||
self._unsorted_title = unsorted_title or prompts.CANONICAL_SECTIONS[0]
|
||||
|
||||
def add(self, sections: dict[str, str]) -> list[str]:
|
||||
touched: list[str] = []
|
||||
for title, content in sections.items():
|
||||
title = title.strip()
|
||||
content = (content or "").strip()
|
||||
if title == UNSORTED:
|
||||
# Texte non découpé : suite de la dernière section rencontrée.
|
||||
title = self._last or self._unsorted_title
|
||||
title = title.strip()
|
||||
if not title or not content:
|
||||
continue
|
||||
key = title.lower()
|
||||
@@ -116,6 +146,7 @@ class _SectionMerger:
|
||||
canonical = self._canonical_key[key]
|
||||
self._merged[canonical].append(content)
|
||||
touched.append(canonical)
|
||||
self._last = canonical
|
||||
# Dé-duplication en préservant l'ordre d'apparition.
|
||||
seen: set[str] = set()
|
||||
return [t for t in touched if not (t in seen or seen.add(t))]
|
||||
@@ -211,6 +242,9 @@ def _combine_sections(a: dict[str, str], b: dict[str, str]) -> dict[str, str]:
|
||||
out = dict(a)
|
||||
by_lower = {k.lower(): k for k in out}
|
||||
for title, content in b.items():
|
||||
if title == UNSORTED and out:
|
||||
# Texte non découpé de la seconde moitié : suite de ce qui le précède.
|
||||
title = next(reversed(out))
|
||||
key = by_lower.get(title.lower())
|
||||
if key is not None:
|
||||
out[key] = f"{out[key]}\n\n{content}".strip()
|
||||
@@ -229,6 +263,7 @@ class ImportRulesUseCase:
|
||||
extractor: PdfTextExtractor,
|
||||
chunk_target_tokens: int = CHUNK_TARGET_TOKENS,
|
||||
segment_only: bool = False,
|
||||
structure_first: bool = False,
|
||||
) -> None:
|
||||
"""`segment_only=True` (modèles locaux) : le LLM ne renvoie que les
|
||||
frontières des sections (titre + premiers mots) et le texte original est
|
||||
@@ -238,22 +273,53 @@ class ImportRulesUseCase:
|
||||
self._extractor = extractor
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
self._segment_only = segment_only
|
||||
# `structure_first` : découper d'abord le livre par SA propre structure (signets du
|
||||
# PDF, sinon titres repérés à leur taille), sans IA — instantané, fidèle, identique
|
||||
# sur toutes les machines. L'IA ne sert plus qu'aux PDF sans structure.
|
||||
self._structure_first = structure_first
|
||||
# Intervalle des signaux de vie envoyés pendant la traduction (réglable pour les tests).
|
||||
self._heartbeat_seconds = HEARTBEAT_INTERVAL_SECONDS
|
||||
# Un modèle local traite les demandes l'une après l'autre : en envoyer plusieurs
|
||||
# ne ferait qu'allonger leur attente (et déclencher le délai maximal d'un appel).
|
||||
self._translation_concurrency = 1 if segment_only else DEFAULT_CONCURRENCY
|
||||
|
||||
async def execute(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG) -> RulesImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie le résultat complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
logger.info(
|
||||
"Import règles : %s page(s) (%s via OCR), %s morceau(x) à traiter.",
|
||||
doc.page_count, doc.ocr_page_count, len(chunks),
|
||||
)
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
structure = self._split_by_structure(doc, language)
|
||||
if structure is not None:
|
||||
sections = structure.sections
|
||||
else:
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
logger.info(
|
||||
"Import règles : %s page(s) (%s via OCR), %s morceau(x) à traiter.",
|
||||
doc.page_count, doc.ocr_page_count, len(chunks),
|
||||
)
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
try:
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
except LLMProviderError:
|
||||
if not self._segment_only:
|
||||
raise
|
||||
# Segmentation : le texte du morceau est gardé même si l'appel échoue.
|
||||
merger.add({UNSORTED: chunk})
|
||||
sections = merger.result()
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
by_language = {source: sections}
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
async for kind, payload in self._translate(sections, source, target):
|
||||
if kind == "result":
|
||||
by_language[target] = payload.sections
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
return RulesImportResult(
|
||||
sections=merger.result(),
|
||||
sections=sections,
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
sections_by_language=by_language,
|
||||
source_language=source,
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
||||
@@ -269,88 +335,168 @@ class ImportRulesUseCase:
|
||||
yield {"type": "extracting"}
|
||||
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
total = len(chunks)
|
||||
logger.info(
|
||||
"Import règles (stream) : %s page(s) (%s via OCR), %s morceau(x).",
|
||||
doc.page_count, doc.ocr_page_count, total,
|
||||
)
|
||||
yield {
|
||||
"type": "start",
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
merger = _SectionMerger()
|
||||
structure = self._split_by_structure(doc, language)
|
||||
split_method = structure.method if structure is not None else AI_SPLIT
|
||||
skipped = 0
|
||||
last_error: str | None = None
|
||||
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
||||
status_queue: asyncio.Queue = asyncio.Queue()
|
||||
status_token = set_status_queue(status_queue)
|
||||
try:
|
||||
for i, chunk in enumerate(chunks):
|
||||
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
||||
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
||||
# HEARTBEAT : on émet des keep-alive pendant l'appel LLM (long sur un
|
||||
# provider lent) pour que le flux SSE ne soit jamais coupé par le Core.
|
||||
new_titles: list[str] = []
|
||||
try:
|
||||
sections: dict[str, str] | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._map_chunk(chunk, index=i, total=total, language=language),
|
||||
status_queue=status_queue,
|
||||
):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload,
|
||||
"current": i + 1, "total": total}
|
||||
else:
|
||||
sections = payload
|
||||
new_titles = merger.add(sections or {})
|
||||
except LLMProviderError as exc:
|
||||
skipped += 1
|
||||
last_error = str(exc)
|
||||
logger.warning("Morceau %s/%s ignoré (échec LLM) : %s", i + 1, total, exc)
|
||||
yield {"type": "chunk_failed", "current": i + 1, "total": total,
|
||||
"message": str(exc)[:300]}
|
||||
yield {
|
||||
"type": "progress",
|
||||
"current": i + 1,
|
||||
"total": total,
|
||||
"new_sections": new_titles,
|
||||
"skipped": skipped,
|
||||
}
|
||||
finally:
|
||||
reset_status_queue(status_token)
|
||||
if structure is not None:
|
||||
# Le livre porte son propre découpage : on le suit, sans appeler l'IA.
|
||||
sections = structure.sections
|
||||
total = 1
|
||||
yield {"type": "start", "page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count, "total": 1}
|
||||
origin = ("la table des matières du PDF" if structure.method == BOOKMARKS
|
||||
else "les titres du livre")
|
||||
yield {"type": "status",
|
||||
"message": f"Découpage d'après {origin} : {len(sections)} sections, sans IA."}
|
||||
yield {"type": "progress", "current": 1, "total": 1,
|
||||
"new_sections": list(sections)[:_ANNOUNCED_TITLES], "skipped": 0}
|
||||
else:
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
total = len(chunks)
|
||||
logger.info(
|
||||
"Import règles (stream) : %s page(s) (%s via OCR), %s morceau(x).",
|
||||
doc.page_count, doc.ocr_page_count, total,
|
||||
)
|
||||
yield {
|
||||
"type": "start",
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
if total > 0 and skipped == total:
|
||||
yield {"type": "error",
|
||||
"message": "Tous les morceaux ont échoué auprès du fournisseur IA. "
|
||||
f"Dernier message : {last_error or 'inconnu'}"}
|
||||
return
|
||||
merger = _SectionMerger()
|
||||
skipped = 0
|
||||
last_error: str | None = None
|
||||
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
||||
status_queue: asyncio.Queue = asyncio.Queue()
|
||||
status_token = set_status_queue(status_queue)
|
||||
try:
|
||||
for i, chunk in enumerate(chunks):
|
||||
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
||||
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
||||
# HEARTBEAT : on émet des keep-alive pendant l'appel LLM (long sur un
|
||||
# provider lent) pour que le flux SSE ne soit jamais coupé par le Core.
|
||||
new_titles: list[str] = []
|
||||
try:
|
||||
sections: dict[str, str] | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._map_chunk(chunk, index=i, total=total, language=language),
|
||||
status_queue=status_queue,
|
||||
):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload,
|
||||
"current": i + 1, "total": total}
|
||||
else:
|
||||
sections = payload
|
||||
new_titles = merger.add(sections or {})
|
||||
except LLMProviderError as exc:
|
||||
skipped += 1
|
||||
last_error = str(exc)
|
||||
logger.warning("Morceau %s/%s ignoré (échec LLM) : %s", i + 1, total, exc)
|
||||
yield {"type": "chunk_failed", "current": i + 1, "total": total,
|
||||
"message": str(exc)[:300]}
|
||||
if self._segment_only:
|
||||
# Segmentation : le texte original est là, on ne le perd pas. Si TOUS
|
||||
# les morceaux échouent, l'import reste une erreur (cf. plus bas).
|
||||
new_titles = merger.add({UNSORTED: chunk})
|
||||
yield {
|
||||
"type": "progress",
|
||||
"current": i + 1,
|
||||
"total": total,
|
||||
"new_sections": new_titles,
|
||||
"skipped": skipped,
|
||||
}
|
||||
finally:
|
||||
reset_status_queue(status_token)
|
||||
|
||||
sections = merger.result()
|
||||
if total > 0 and not sections:
|
||||
# Le texte a bien été extrait mais AUCUN morceau n'a produit de JSON
|
||||
# exploitable (sorties coupées/illisibles). Sans ce signal, l'UI reçoit
|
||||
# un `done` vide et l'utilisateur conclut à tort que le PDF est illisible.
|
||||
yield {"type": "error",
|
||||
"message": "Le texte du PDF a été extrait, mais le modèle n'a produit "
|
||||
"aucune section exploitable (réponses JSON vides ou coupées). "
|
||||
"Réduisez la taille des morceaux d'import, augmentez la fenêtre "
|
||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||
return
|
||||
if total > 0 and skipped == total:
|
||||
yield {"type": "error",
|
||||
"message": "Tous les morceaux ont échoué auprès du fournisseur IA. "
|
||||
f"Dernier message : {last_error or 'inconnu'}"}
|
||||
return
|
||||
|
||||
sections = merger.result()
|
||||
if total > 0 and not sections:
|
||||
# Le texte a bien été extrait mais AUCUN morceau n'a produit de JSON
|
||||
# exploitable (sorties coupées/illisibles). Sans ce signal, l'UI reçoit
|
||||
# un `done` vide et l'utilisateur conclut à tort que le PDF est illisible.
|
||||
yield {"type": "error",
|
||||
"message": "Le texte du PDF a été extrait, mais le modèle n'a produit "
|
||||
"aucune section exploitable (réponses JSON vides ou coupées). "
|
||||
"Réduisez la taille des morceaux d'import, augmentez la fenêtre "
|
||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||
return
|
||||
|
||||
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
|
||||
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
# L'extraction est livrée AVANT la traduction : si le flux s'interrompt pendant la
|
||||
# traduction (longue), le Core a déjà de quoi proposer les règles dans leur langue.
|
||||
yield {
|
||||
"type": "done",
|
||||
"type": "extracted",
|
||||
"sections": sections,
|
||||
"split_method": split_method,
|
||||
"source_language": source,
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||
untranslated: list[str] = []
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
async for kind, payload in self._translate(sections, source, target):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": total, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload}
|
||||
else:
|
||||
by_language[target] = payload.sections
|
||||
untranslated = payload.untranslated
|
||||
if untranslated:
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(target)}) incomplète : "
|
||||
f"{len(untranslated)} section(s) sur {len(sections)} "
|
||||
"gardent le texte d'origine."}
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
|
||||
|
||||
yield {
|
||||
"type": "done",
|
||||
"sections": sections,
|
||||
"sections_by_language": by_language,
|
||||
"source_language": source,
|
||||
"split_method": split_method,
|
||||
"untranslated": untranslated,
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
def _split_by_structure(self, doc, language: str) -> StructureSplit | None:
|
||||
"""Découpage par la structure du PDF, ou None s'il faut passer par l'IA (réglage
|
||||
coupé, extracteur sans lignes, PDF sans signets ni titres repérables)."""
|
||||
if not self._structure_first:
|
||||
return None
|
||||
split = split_by_structure(
|
||||
doc, preamble_title="Front matter" if language == "en" else "Préambule")
|
||||
if split.method == NONE:
|
||||
logger.info("Import règles : pas de structure exploitable dans ce PDF — découpage par l'IA.")
|
||||
return None
|
||||
logger.info("Import règles : %s page(s), découpage par la structure du PDF (%s) : %s sections, "
|
||||
"%s titres, sans IA.", doc.page_count, split.method, len(split.sections), split.heading_count)
|
||||
return split
|
||||
|
||||
def _translate(self, sections: dict[str, str], source: str, target: str):
|
||||
"""Traduction des sections vers `target` (cf. rules_translation.translate_sections)."""
|
||||
return translate_sections(RulesTranslator(self._llm), sections, source, target,
|
||||
concurrency=self._translation_concurrency,
|
||||
heartbeat_seconds=self._heartbeat_seconds)
|
||||
|
||||
# --- MAP : un morceau → sections -----------------------------------------
|
||||
|
||||
@@ -417,6 +563,15 @@ class ImportRulesUseCase:
|
||||
if truncated:
|
||||
logger.warning(
|
||||
"Morceau %s : sortie tronquée, profondeur max atteinte — partiel conservé.", index)
|
||||
if self._segment_only and not sections and text.strip():
|
||||
# Aucun repère exploitable : le texte suit la section précédente au lieu de disparaître.
|
||||
logger.warning(
|
||||
"Morceau %s : aucune section repérée par le modèle — texte gardé à la suite de "
|
||||
"la section précédente (%s caractères).", index, len(text))
|
||||
notify_status(
|
||||
f"Le modèle n'a pas su découper le morceau {index + 1} : son texte est gardé "
|
||||
"à la suite de la section précédente.")
|
||||
return {UNSORTED: text}
|
||||
return sections
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -113,5 +113,8 @@ async def generate_with_retry(
|
||||
+ str(exc)[:160]
|
||||
)
|
||||
await asyncio.sleep(wait)
|
||||
# Le message « nouvel essai dans Ns » deviendrait faux : on dit que
|
||||
# l'essai suivant est lancé (il peut durer plusieurs minutes).
|
||||
notify_status(f"Nouvel essai en cours (tentative {attempt + 2}/{_ATTEMPTS})…")
|
||||
assert last_error is not None
|
||||
raise last_error
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
"""Découpage d'un livre par la structure que son PDF porte déjà — sans IA.
|
||||
|
||||
Un livre mis en page par un éditeur dit lui-même où commencent ses sections, de deux façons :
|
||||
A. ses SIGNETS (table des matières intégrée au PDF) ;
|
||||
B. ses TITRES, écrits nettement plus gros que le corps du texte.
|
||||
On suit les signets quand il y en a assez ; les titres repérés affinent ce que les signets ne
|
||||
détaillent pas, ou les remplacent quand le PDF n'en a pas. Sans l'un ni l'autre (scan passé à
|
||||
l'OCR, texte tout de la même taille), ce module rend « none » et l'appelant passe par l'IA.
|
||||
|
||||
Mesuré le 2026-11-13 sur 159 livres de jeu de rôle : 82 % découpés sans section trop grosse,
|
||||
en 2 secondes par livre, et les titres repérés retrouvent 93 % des signets (médiane).
|
||||
|
||||
Le texte n'est jamais réécrit : chaque section est une tranche du livre, dans l'ordre de
|
||||
lecture. Seule la mise en forme change — lignes d'un même paragraphe recollées, mots coupés
|
||||
en fin de ligne réunis, intertitres en `###`, puces en listes, en-têtes et numéros de page
|
||||
retirés.
|
||||
|
||||
Logique pure : elle ne voit que des `TextLine` et des `TocEntry`, pas PyMuPDF.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from app.domain.models import ExtractedDocument, TextLine, TocEntry
|
||||
|
||||
# Un titre de section est écrit nettement plus gros que le corps du texte…
|
||||
HEADING_RATIO = 1.25
|
||||
# …un intertitre, un peu plus gros : il reste dans le contenu, en `####`.
|
||||
SUBHEADING_RATIO = 1.12
|
||||
MAX_TITLE_CHARS = 90
|
||||
# Taille visée d'une section : au-delà, un chapitre est rendu par ses sous-sections, et une
|
||||
# section sans sous-section est coupée en parties. Assez court pour être lu d'une traite et
|
||||
# fourni d'un bloc à une IA, même avec une petite fenêtre de contexte.
|
||||
MAX_SECTION_CHARS = 12_000
|
||||
# En-deçà, le texte d'introduction d'un chapitre découpé rejoint sa première sous-section.
|
||||
MIN_OWN_CHARS = 200
|
||||
PATH_SEPARATOR = " › "
|
||||
# Un titre de section reprend au plus ses trois derniers niveaux (« Chapitre › Section › Partie »).
|
||||
MAX_PATH_PARTS = 3
|
||||
|
||||
BOOKMARKS = "bookmarks"
|
||||
HEADINGS = "headings"
|
||||
NONE = "none"
|
||||
|
||||
_BULLETS = "•▪●◦■"
|
||||
# Séparateur des cellules d'une rangée de tableau dans le texte d'une ligne (cf. TextLine.cells).
|
||||
CELL_SEPARATOR = " | "
|
||||
_SENTENCE_END = ".!?:;…»”\")"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StructureSplit:
|
||||
"""Résultat du découpage. `method` : BOOKMARKS, HEADINGS ou NONE (aucune structure)."""
|
||||
|
||||
method: str
|
||||
sections: dict[str, str] = field(default_factory=dict)
|
||||
heading_count: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OutlineNode:
|
||||
"""Un nœud de l'arbre du livre. `text` : son texte propre, avant sa première sous-section
|
||||
(markdown, repris du livre). `page` : 1-based."""
|
||||
|
||||
title: str
|
||||
level: int
|
||||
page: int
|
||||
text: str
|
||||
children: tuple["OutlineNode", ...] = ()
|
||||
|
||||
@property
|
||||
def chars(self) -> int:
|
||||
"""Taille du texte du nœud et de tous ses descendants."""
|
||||
return len(self.text) + sum(child.chars for child in self.children)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BookOutline:
|
||||
"""Arbre du livre. `method` : BOOKMARKS, HEADINGS ou NONE ; `preamble` : ce qui précède
|
||||
le premier titre (couverture, crédits)."""
|
||||
|
||||
method: str
|
||||
preamble: str = ""
|
||||
nodes: tuple[OutlineNode, ...] = ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Heading:
|
||||
index: int # première ligne du titre (ou de sa page, si le titre n'y est pas retrouvé)
|
||||
end: int # première ligne du contenu
|
||||
level: int
|
||||
title: str
|
||||
page: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Node:
|
||||
heading: _Heading
|
||||
own: tuple[int, int] = (0, 0) # lignes de son texte propre, avant sa 1re sous-section
|
||||
children: list["_Node"] = field(default_factory=list)
|
||||
|
||||
|
||||
# Ligne d'un sommaire imprimé : un titre, des points de conduite, un numéro de page.
|
||||
_LEADERS = re.compile(r"(\S)\1{5,}\s*\d{1,4}\b")
|
||||
# Numéro de page seul, parfois entre barres ou tirets : « 12 », « /11 », « - 12 - ».
|
||||
_PAGE_NUMBER = re.compile(r"[/|–—-]?\s*\d{1,4}\s*[/|–—-]?")
|
||||
# Titre courant accolé au numéro de page : « 4/Grimmsgate », « Introduction /3 ».
|
||||
_RUNNING_HEAD = re.compile(r"\d{1,4}\s*/\s*\D.{0,50}|\D.{0,50}?(?:\s*/\s*\d{1,4})+")
|
||||
|
||||
|
||||
def _fold(text: str) -> str:
|
||||
"""Comparaison tolérante : sans accents, casse, ni ponctuation."""
|
||||
text = unicodedata.normalize("NFD", text)
|
||||
text = "".join(c for c in text if unicodedata.category(c) != "Mn").lower()
|
||||
return re.sub(r"[^a-z0-9]+", " ", text).strip()
|
||||
|
||||
|
||||
# Caractères invisibles que certains éditeurs glissent dans leurs titres et leurs signets.
|
||||
_INVISIBLE = re.compile("[\u200b\u200c\u200d\u2060\ufeff]")
|
||||
|
||||
|
||||
def _title(text: str) -> str:
|
||||
"""Titre sans caractères invisibles ni espaces en trop."""
|
||||
return " ".join(_INVISIBLE.sub("", text).split())
|
||||
|
||||
|
||||
def _plain(text: str) -> str:
|
||||
"""Texte d'une ligne sans séparateurs de cellules : un titre écrit en gros est un titre,
|
||||
même si un grand blanc le coupe en deux (« Flame Dart 1 Action »)."""
|
||||
return text.replace(CELL_SEPARATOR, " ")
|
||||
|
||||
|
||||
def _has_word(text: str) -> bool:
|
||||
return bool(re.search(r"[^\W\d_]{2}", text))
|
||||
|
||||
|
||||
def _body_size(lines: list[TextLine]) -> float:
|
||||
"""Taille de caractères du corps du texte : celle qui porte le plus de texte."""
|
||||
weights: collections.Counter = collections.Counter()
|
||||
for line in lines:
|
||||
if line.size > 0:
|
||||
weights[line.size] += len(line.text)
|
||||
return weights.most_common(1)[0][0] if weights else 0.0
|
||||
|
||||
|
||||
# Un en-tête, un pied de page ou un numéro de page se trouve parmi les toutes premières ou
|
||||
# toutes dernières lignes de sa page.
|
||||
_PAGE_EDGE_LINES = 3
|
||||
|
||||
|
||||
def _noise(lines: list[TextLine], page_count: int) -> set[int]:
|
||||
"""Lignes qui ne sont pas du texte du livre : lignes d'un sommaire imprimé, numéros de
|
||||
page, en-têtes et pieds de page (le même texte court répété de page en page).
|
||||
|
||||
Numéros et en-têtes ne sont retirés qu'en HAUT ou en BAS de page : un libellé répété au
|
||||
fil du texte (« Actions », « Armor Class » dans un bestiaire) ou un nombre dans un
|
||||
tableau font partie du livre."""
|
||||
# L'extracteur dit quelles lignes sont en haut ou en bas de page. S'il ne le dit pour
|
||||
# aucune (pages passées à l'OCR, autre extracteur), on prend les premières et dernières
|
||||
# lignes de chaque page.
|
||||
edges = {i for i, line in enumerate(lines) if line.edge}
|
||||
if not edges:
|
||||
by_page: dict[int, list[int]] = collections.defaultdict(list)
|
||||
for i, line in enumerate(lines):
|
||||
by_page[line.page].append(i)
|
||||
for indices in by_page.values():
|
||||
edges.update(indices[:_PAGE_EDGE_LINES])
|
||||
edges.update(indices[-_PAGE_EDGE_LINES:])
|
||||
|
||||
where: dict[str, set[int]] = collections.defaultdict(set)
|
||||
for i in edges:
|
||||
if len(lines[i].text) <= 60:
|
||||
where[_fold(lines[i].text)].add(lines[i].page)
|
||||
threshold = max(4, page_count * 0.15)
|
||||
repeated = {key for key, pages in where.items() if key and len(pages) >= threshold}
|
||||
|
||||
out: set[int] = set()
|
||||
for i, line in enumerate(lines):
|
||||
text = line.text.strip()
|
||||
if _LEADERS.search(text):
|
||||
out.add(i)
|
||||
elif i in edges and (_PAGE_NUMBER.fullmatch(text) or (len(text) <= 60 and _fold(text) in repeated)):
|
||||
out.add(i)
|
||||
elif i in edges and line.cells == 1 and len(text) <= 60 and _RUNNING_HEAD.fullmatch(text):
|
||||
out.add(i)
|
||||
return out
|
||||
|
||||
|
||||
def _font_headings(lines: list[TextLine], noise: set[int], body: float) -> list[_Heading]:
|
||||
"""Titres repérés à la taille des caractères, sur trois niveaux au plus."""
|
||||
if not body:
|
||||
return []
|
||||
candidates = [
|
||||
(i, line) for i, line in enumerate(lines)
|
||||
if i not in noise and line.size >= body * HEADING_RATIO
|
||||
and 2 < len(line.text) <= MAX_TITLE_CHARS and _has_word(line.text)
|
||||
]
|
||||
# Un titre écrit sur plusieurs lignes (« GARDEN OF » / « DEATH ») n'en fait qu'un.
|
||||
merged: list[tuple[int, int, TextLine]] = [] # (première ligne, dernière ligne, titre)
|
||||
for i, line in candidates:
|
||||
if merged:
|
||||
first, last, title = merged[-1]
|
||||
if (title.page == line.page and title.size == line.size and i - last <= 1
|
||||
and len(title.text) + len(line.text) < MAX_TITLE_CHARS):
|
||||
merged[-1] = (first, i, TextLine(title.page, title.block, f"{title.text} {line.text}", title.size))
|
||||
continue
|
||||
merged.append((i, i, line))
|
||||
|
||||
counts = collections.Counter(title.size for _, _, title in merged)
|
||||
# Une taille vue une seule fois est un titre de couverture ou un ornement, pas un niveau.
|
||||
sizes = sorted((size for size, n in counts.items() if n >= 2), reverse=True) or sorted(counts, reverse=True)
|
||||
level_of = {size: min(rank + 1, 3) for rank, size in enumerate(sizes)}
|
||||
return [_Heading(first, last + 1, level_of[title.size], _title(_plain(title.text)), title.page)
|
||||
for first, last, title in merged if title.size in level_of]
|
||||
|
||||
|
||||
def _bookmark_headings(toc: list[TocEntry], lines: list[TextLine], page_count: int) -> list[_Heading]:
|
||||
"""Signets du PDF, placés sur la ligne qui porte leur titre — sinon au début de leur page."""
|
||||
first_of_page: dict[int, int] = {}
|
||||
for i, line in enumerate(lines):
|
||||
first_of_page.setdefault(line.page, i)
|
||||
pages_with_text = sorted(first_of_page)
|
||||
out: list[_Heading] = []
|
||||
for entry in toc:
|
||||
title = _title(entry.title)
|
||||
page = max(0, entry.page - 1)
|
||||
if not title or page >= page_count:
|
||||
continue
|
||||
start = first_of_page.get(page)
|
||||
if start is None:
|
||||
# Page sans texte (illustration pleine page) : la section commence à la suivante.
|
||||
later = [p for p in pages_with_text if p > page]
|
||||
if not later:
|
||||
continue
|
||||
start = first_of_page[later[0]]
|
||||
index, end = start, start
|
||||
wanted = _fold(title)
|
||||
if wanted:
|
||||
for i in range(start, len(lines)):
|
||||
if lines[i].page > page + 1:
|
||||
break
|
||||
here = _fold(lines[i].text)
|
||||
if not here:
|
||||
continue
|
||||
if here == wanted or (len(here) > 3 and wanted.startswith(here + " ")) or here.startswith(wanted + " "):
|
||||
index, end = i, i + 1
|
||||
# Titre sur plusieurs lignes : les suivantes complètent le signet.
|
||||
joined = here
|
||||
while end < len(lines) and len(joined) < len(wanted):
|
||||
more = _fold(lines[end].text)
|
||||
if not more or not wanted.startswith(f"{joined} {more}"):
|
||||
break
|
||||
joined = f"{joined} {more}"
|
||||
end += 1
|
||||
break
|
||||
out.append(_Heading(index, end, entry.level, title, page))
|
||||
out.sort(key=lambda h: (h.index, h.level))
|
||||
return out
|
||||
|
||||
|
||||
def _combine(marks: list[_Heading], fonts: list[_Heading]) -> list[_Heading]:
|
||||
"""Signets, détaillés par les titres repérés qu'ils ne couvrent pas déjà."""
|
||||
if not marks:
|
||||
return fonts
|
||||
deepest = max(h.level for h in marks)
|
||||
covered = {i for h in marks for i in range(h.index, max(h.end, h.index + 1))}
|
||||
known = {(h.page, _fold(h.title)) for h in marks}
|
||||
extra = [
|
||||
_Heading(h.index, h.end, deepest + h.level, h.title, h.page) for h in fonts
|
||||
if h.index not in covered and (h.page, _fold(h.title)) not in known
|
||||
]
|
||||
return sorted(marks + extra, key=lambda h: (h.index, h.level))
|
||||
|
||||
|
||||
def _tree(headings: list[_Heading], line_count: int) -> list[_Node]:
|
||||
"""Arbre des sections. Le texte propre d'un nœud s'arrête à son premier descendant."""
|
||||
# Deux titres sur la même ligne : le plus haut placé dans la hiérarchie l'emporte.
|
||||
unique: list[_Heading] = []
|
||||
for heading in headings:
|
||||
if unique and unique[-1].index == heading.index and unique[-1].end > unique[-1].index:
|
||||
continue
|
||||
unique.append(heading)
|
||||
roots: list[_Node] = []
|
||||
stack: list[_Node] = []
|
||||
for position, heading in enumerate(unique):
|
||||
stop = unique[position + 1].index if position + 1 < len(unique) else line_count
|
||||
node = _Node(heading, (min(heading.end, stop), stop))
|
||||
while stack and stack[-1].heading.level >= heading.level:
|
||||
stack.pop()
|
||||
(stack[-1].children if stack else roots).append(node)
|
||||
stack.append(node)
|
||||
return roots
|
||||
|
||||
|
||||
class _Renderer:
|
||||
"""Met en forme des tranches de lignes en markdown, sans rien réécrire."""
|
||||
|
||||
def __init__(self, lines: list[TextLine], noise: set[int], body: float) -> None:
|
||||
self._lines = lines
|
||||
self._noise = noise
|
||||
self._body = body
|
||||
|
||||
def text(self, start: int, stop: int) -> str:
|
||||
paragraphs: list[str] = []
|
||||
current: list[str] = []
|
||||
key: tuple[int, int] | None = None
|
||||
|
||||
def flush() -> None:
|
||||
if current:
|
||||
paragraphs.append(_join_lines(current))
|
||||
current.clear()
|
||||
|
||||
rows: list[list[str]] = []
|
||||
|
||||
def flush_rows() -> None:
|
||||
if rows:
|
||||
paragraphs.extend(_tables(rows))
|
||||
rows.clear()
|
||||
|
||||
for i in range(start, stop):
|
||||
if i in self._noise:
|
||||
continue
|
||||
line = self._lines[i]
|
||||
text = line.text.strip()
|
||||
if not text:
|
||||
continue
|
||||
if line.cells > 1 and not self._is_subheading(line):
|
||||
# Rangée de tableau : ses voisines la rejoignent dans le même tableau.
|
||||
flush()
|
||||
rows.append([cell.strip() for cell in text.split(CELL_SEPARATOR)])
|
||||
key = None
|
||||
continue
|
||||
flush_rows()
|
||||
if self._is_subheading(line):
|
||||
flush()
|
||||
paragraphs.append(f"#### {_plain(text)}")
|
||||
key = None
|
||||
continue
|
||||
bullet = text[0] in _BULLETS
|
||||
if (line.page, line.block) != key or bullet:
|
||||
flush()
|
||||
key = (line.page, line.block)
|
||||
current.append(f"- {text[1:].strip()}" if bullet else text)
|
||||
flush()
|
||||
flush_rows()
|
||||
|
||||
# Un paragraphe coupé par un changement de colonne ou de page est recollé.
|
||||
merged: list[str] = []
|
||||
for paragraph in paragraphs:
|
||||
if merged and _continues(merged[-1], paragraph):
|
||||
merged[-1] = _glue(merged[-1], paragraph)
|
||||
else:
|
||||
merged.append(paragraph)
|
||||
return "\n\n".join(merged)
|
||||
|
||||
def _is_subheading(self, line: TextLine) -> bool:
|
||||
return (self._body > 0 and line.size >= self._body * SUBHEADING_RATIO
|
||||
and len(line.text) <= MAX_TITLE_CHARS and _has_word(line.text)
|
||||
and not line.text.rstrip().endswith((".", ",", ";")))
|
||||
|
||||
def node(self, node: _Node, depth: int = 0) -> str:
|
||||
"""Un nœud entier : son texte, puis ses sous-sections sous des intertitres."""
|
||||
parts = [self.text(*node.own)]
|
||||
for child in node.children:
|
||||
marker = "###" if depth == 0 else "####"
|
||||
parts.append(f"{marker} {child.heading.title}")
|
||||
parts.append(self.node(child, depth + 1))
|
||||
return "\n\n".join(part for part in parts if part.strip())
|
||||
|
||||
def raw_chars(self, node: _Node) -> int:
|
||||
total = sum(len(self._lines[i].text) for i in range(*node.own) if i not in self._noise)
|
||||
return total + sum(self.raw_chars(child) for child in node.children)
|
||||
|
||||
|
||||
def _join_lines(parts: list[str]) -> str:
|
||||
out = parts[0]
|
||||
for part in parts[1:]:
|
||||
out = _glue(out, part)
|
||||
return out
|
||||
|
||||
|
||||
# Tirets de fin de ligne : trait d'union, tiret typographique (U+2010), tiret insécable (U+2011).
|
||||
_HYPHENS = ("-", "\u2010", "\u2011")
|
||||
|
||||
|
||||
def _glue(before: str, after: str) -> str:
|
||||
"""Recolle deux bouts de texte, en réunissant un mot coupé en fin de ligne.
|
||||
|
||||
« atta- » / « quer » → « attaquer » ; un nom composé coupé à son tiret le garde :
|
||||
« Trois- » / « Doigts » → « Trois-Doigts »."""
|
||||
if before.endswith("\u00ad"):
|
||||
return before[:-1] + after
|
||||
if before.endswith(_HYPHENS) and len(before) > 1 and before[-2].isalpha():
|
||||
if after[:1].islower():
|
||||
return before[:-1] + after
|
||||
if after[:1].isupper():
|
||||
return before + after
|
||||
return f"{before} {after}"
|
||||
|
||||
|
||||
def _tables(rows: list[list[str]]) -> list[str]:
|
||||
"""Rangées de tableau qui se suivent → tableaux markdown. Des rangées de même largeur font
|
||||
un tableau (la première en donne les titres de colonnes) ; une rangée isolée reste une
|
||||
ligne, ses cellules séparées par un tiret."""
|
||||
out: list[str] = []
|
||||
start = 0
|
||||
while start < len(rows):
|
||||
end = start + 1
|
||||
while end < len(rows) and len(rows[end]) == len(rows[start]):
|
||||
end += 1
|
||||
run = rows[start:end]
|
||||
if len(run) == 1:
|
||||
out.append(" — ".join(run[0]))
|
||||
else:
|
||||
width = len(run[0])
|
||||
body = ["| " + " | ".join(cells) + " |" for cells in run]
|
||||
out.append("\n".join([body[0], "|" + " --- |" * width, *body[1:]]))
|
||||
start = end
|
||||
return out
|
||||
|
||||
|
||||
def _continues(previous: str, following: str) -> bool:
|
||||
if previous.startswith(("#", "|")) or following.startswith(("#", "- ", "|")):
|
||||
return False
|
||||
return previous[-1:] not in _SENTENCE_END and following[:1].islower()
|
||||
|
||||
|
||||
def _parts(markdown: str, limit: int) -> list[str]:
|
||||
"""Coupe un texte trop long en parties, entre deux paragraphes (de préférence avant un
|
||||
intertitre). Un texte qui tient reste entier."""
|
||||
if len(markdown) <= limit * 1.5:
|
||||
return [markdown]
|
||||
count = max(2, round(len(markdown) / limit))
|
||||
target = len(markdown) / count
|
||||
parts: list[str] = []
|
||||
current: list[str] = []
|
||||
size = 0
|
||||
for paragraph in markdown.split("\n\n"):
|
||||
heading = paragraph.startswith("#")
|
||||
if current and len(parts) < count - 1 and (size >= target or (heading and size >= target * 0.7)):
|
||||
parts.append("\n\n".join(current))
|
||||
current, size = [], 0
|
||||
current.append(paragraph)
|
||||
size += len(paragraph) + 2
|
||||
if current:
|
||||
parts.append("\n\n".join(current))
|
||||
return parts
|
||||
|
||||
|
||||
class _Sections:
|
||||
"""Sections dans l'ordre du livre, titres uniques."""
|
||||
|
||||
def __init__(self, limit: int) -> None:
|
||||
self._limit = limit
|
||||
self.out: dict[str, str] = {}
|
||||
|
||||
def add(self, path: list[str], markdown: str) -> None:
|
||||
markdown = markdown.strip()
|
||||
if not markdown:
|
||||
return
|
||||
title = PATH_SEPARATOR.join(path[-MAX_PATH_PARTS:])
|
||||
parts = _parts(markdown, self._limit)
|
||||
for number, part in enumerate(parts, start=1):
|
||||
name = title if len(parts) == 1 else f"{title} ({number}/{len(parts)})"
|
||||
self.out[self._free(name)] = part
|
||||
|
||||
def _free(self, title: str) -> str:
|
||||
if title not in self.out:
|
||||
return title
|
||||
n = 2
|
||||
while f"{title} ({n})" in self.out:
|
||||
n += 1
|
||||
return f"{title} ({n})"
|
||||
|
||||
|
||||
def _analyse(doc: ExtractedDocument) -> tuple[str, list[_Node], _Renderer, int, int] | None:
|
||||
"""Structure du livre : (méthode, arbre des sections, rendu du texte, fin du préambule,
|
||||
nombre de titres). None quand le PDF n'a pas assez de signets ni de titres repérables, ou
|
||||
que l'extracteur n'a pas fourni ses lignes."""
|
||||
lines = doc.lines
|
||||
if not lines:
|
||||
return None
|
||||
page_count = doc.page_count
|
||||
noise = _noise(lines, page_count)
|
||||
body = _body_size(lines)
|
||||
fonts = _font_headings(lines, noise, body)
|
||||
marks = _bookmark_headings(doc.toc, lines, page_count)
|
||||
enough = max(3, page_count // 40)
|
||||
if len(marks) >= enough:
|
||||
method, headings = BOOKMARKS, _combine(marks, fonts)
|
||||
elif len(fonts) >= enough:
|
||||
method, headings = HEADINGS, fonts
|
||||
else:
|
||||
return None
|
||||
|
||||
roots = _tree(headings, len(lines))
|
||||
# Un seul signet coiffe tout le livre (« Cover ») : ce sont ses enfants, les chapitres.
|
||||
# Son texte propre (la couverture) rejoint le préambule.
|
||||
front_stop = roots[0].heading.index if roots else 0
|
||||
while len(roots) == 1 and len(roots[0].children) >= 2:
|
||||
front_stop = roots[0].own[1]
|
||||
roots = roots[0].children
|
||||
return method, roots, _Renderer(lines, noise, body), front_stop, len(headings)
|
||||
|
||||
|
||||
def split_by_structure(
|
||||
doc: ExtractedDocument,
|
||||
*,
|
||||
preamble_title: str = "Préambule",
|
||||
max_section_chars: int = MAX_SECTION_CHARS,
|
||||
) -> StructureSplit:
|
||||
"""Découpe `doc` par ses signets et ses titres. `method == NONE` quand le PDF n'a pas assez
|
||||
de structure (ou que l'extracteur n'a pas fourni ses lignes) : rien n'est alors rendu."""
|
||||
analysis = _analyse(doc)
|
||||
if analysis is None:
|
||||
return StructureSplit(NONE)
|
||||
method, roots, renderer, front_stop, heading_count = analysis
|
||||
sections = _Sections(max_section_chars)
|
||||
|
||||
def emit(node: _Node, path: list[str], intro: str = "") -> None:
|
||||
if not node.children or renderer.raw_chars(node) <= max_section_chars:
|
||||
sections.add(path, "\n\n".join(p for p in (intro, renderer.node(node)) if p))
|
||||
return
|
||||
# Chapitre trop gros : il est rendu par ses sous-sections. Son introduction devient
|
||||
# une section à part si elle a de la matière, sinon elle ouvre la première sous-section.
|
||||
own = "\n\n".join(p for p in (intro, renderer.text(*node.own)) if p)
|
||||
carry = ""
|
||||
if len(own) >= MIN_OWN_CHARS:
|
||||
sections.add(path, own)
|
||||
else:
|
||||
carry = own
|
||||
for position, child in enumerate(node.children):
|
||||
emit(child, [*path, child.heading.title], carry if position == 0 else "")
|
||||
|
||||
preamble = renderer.text(0, front_stop)
|
||||
carry = ""
|
||||
if len(preamble) >= MIN_OWN_CHARS:
|
||||
sections.add([preamble_title], preamble)
|
||||
else:
|
||||
carry = preamble
|
||||
for position, root in enumerate(roots):
|
||||
emit(root, [root.heading.title], carry if position == 0 else "")
|
||||
|
||||
if not sections.out:
|
||||
return StructureSplit(NONE)
|
||||
return StructureSplit(method, sections.out, heading_count)
|
||||
|
||||
|
||||
def book_outline(doc: ExtractedDocument) -> BookOutline:
|
||||
"""L'arbre du livre tel que son PDF le donne : chapitres, sections, sous-sections, chacun
|
||||
avec son texte propre. `method == NONE` quand le PDF n'a pas assez de structure."""
|
||||
analysis = _analyse(doc)
|
||||
if analysis is None:
|
||||
return BookOutline(NONE)
|
||||
method, roots, renderer, front_stop, _ = analysis
|
||||
|
||||
def build(node: _Node) -> OutlineNode:
|
||||
return OutlineNode(node.heading.title, node.heading.level, node.heading.page + 1,
|
||||
renderer.text(*node.own), tuple(build(child) for child in node.children))
|
||||
|
||||
return BookOutline(method, renderer.text(0, front_stop), tuple(build(root) for root in roots))
|
||||
|
||||
|
||||
def outline_text(node: OutlineNode, depth: int = 0) -> str:
|
||||
"""Texte entier d'un nœud : le sien, puis ses sous-sections sous des intertitres."""
|
||||
parts = [node.text]
|
||||
for child in node.children:
|
||||
parts.append(f"{'###' if depth == 0 else '####'} {child.title}")
|
||||
parts.append(outline_text(child, depth + 1))
|
||||
return "\n\n".join(part for part in parts if part.strip())
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
|
||||
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
|
||||
Plan du méchant…).
|
||||
|
||||
Générique : le front décrit la méthode (nom ; principe suivi du rôle de chaque étape, comme
|
||||
dans l'assistant manuel) et ses questions (clé, libellé,
|
||||
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
|
||||
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def _field_line(field: dict) -> str:
|
||||
key = str(field.get("key") or "").strip()
|
||||
label = str(field.get("label") or key).strip()
|
||||
hint = str(field.get("hint") or "").strip()
|
||||
step = str(field.get("step") or "").strip()
|
||||
line = f'- "{key}"'
|
||||
if step:
|
||||
line += f" [{step}]"
|
||||
line += f" : {label}"
|
||||
if hint:
|
||||
line += f" — {hint}"
|
||||
options = field.get("options") or []
|
||||
if options:
|
||||
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
|
||||
line += f" — UNE valeur parmi : {values}"
|
||||
return line
|
||||
|
||||
|
||||
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
|
||||
fields: list[dict], existing: dict[str, str], language: str) -> str:
|
||||
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
|
||||
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
|
||||
existing_lines = "\n".join(
|
||||
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
|
||||
existing_block = (
|
||||
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
|
||||
f"{existing_lines}\n" if existing_lines else ""
|
||||
)
|
||||
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
|
||||
guide = method_principle.strip() if method_principle else ""
|
||||
guide_block = (
|
||||
"\nLa méthode, telle que le MJ la suit à la main (principe, puis rôle de chaque étape) :\n"
|
||||
f"{guide}\n" if guide else ""
|
||||
)
|
||||
return (
|
||||
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
|
||||
f"avec la méthode « {method_name.strip() or 'guidée'} ».\n"
|
||||
f"{guide_block}\n"
|
||||
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
|
||||
f"{context_block}{existing_block}\n"
|
||||
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
|
||||
f"{fields_list}\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
|
||||
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
|
||||
"valeurs proposées.\n"
|
||||
"- Pars de l'idée du MJ et développe-la : garde son ton, ses lieux, ses personnages ; n'en change "
|
||||
"pas le sujet.\n"
|
||||
"- Respecte la méthode : chaque réponse remplit le rôle de SON étape, tel que décrit ci-dessus "
|
||||
"(ex. une épreuve qui ne se règle pas par un combat, des pistes qui se recoupent). Ne mélange pas "
|
||||
"les étapes.\n"
|
||||
"- Toutes les réponses forment UNE aventure cohérente, concrète et jouable "
|
||||
"(noms, lieux, motivations précises ; pas de généralités).\n"
|
||||
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
|
||||
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
|
||||
f"- Rédige les réponses en {language_name(language)}.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -1,7 +1,29 @@
|
||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||
DEFAULT_ARC_NAME = "Aventure principale"
|
||||
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
|
||||
|
||||
|
||||
def default_arc_name(language: str) -> str:
|
||||
"""Nom de l'arc unique, dans la langue de l'interface."""
|
||||
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
|
||||
|
||||
|
||||
def language_block(language: str) -> str:
|
||||
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
|
||||
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
|
||||
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
|
||||
name = language_name(language)
|
||||
return (
|
||||
"\n\nLANGUE DE SORTIE :\n"
|
||||
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
|
||||
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
|
||||
"fidèlement, sans les résumer davantage.\n"
|
||||
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
|
||||
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
|
||||
)
|
||||
|
||||
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||
@@ -98,3 +120,49 @@ Réponds UNIQUEMENT par un objet JSON valide :
|
||||
"scene_merges": [{{"chapter": "nom du chapitre", "into": "nom de la scène à garder",
|
||||
"merge": ["nom à fusionner", ...]}}]}}
|
||||
S'il n'y a RIEN à fusionner (cas le plus fréquent) : {{"chapter_merges": [], "scene_merges": []}}"""
|
||||
|
||||
|
||||
# --- Aides de l'IA sur une campagne découpée par la structure du livre ------------------------
|
||||
# Le texte des scènes vient du livre, mot pour mot, et n'est jamais confié au modèle pour
|
||||
# réécriture. Le modèle n'écrit que deux AIDES, courtes et séparées du texte : un synopsis par
|
||||
# scène, et les fiches des PNJ nommés.
|
||||
AIDS_PROMPT = """Tu aides un MJ à préparer une campagne de jeu de rôle. Voici des SCÈNES tirées
|
||||
d'un livre de campagne. Leur texte est celui du livre : il ne sera PAS modifié, et tu ne dois
|
||||
PAS le réécrire.
|
||||
|
||||
Ta tâche se limite à deux aides, courtes :
|
||||
1. Pour CHAQUE scène, un SYNOPSIS de 1 à 2 phrases : ce qui s'y passe, pour que le MJ la
|
||||
retrouve d'un coup d'œil.
|
||||
2. Les PNJ NOMMÉS et les créatures UNIQUES (boss) présents dans ces scènes, chacun avec une
|
||||
fiche de 2 à 4 phrases : rôle dans l'histoire, apparence, motivations, où on le rencontre.
|
||||
|
||||
Règles IMPÉRATIVES :
|
||||
- Ne t'appuie QUE sur le texte fourni. N'invente rien, ne complète pas avec ce que tu sais.
|
||||
- Un synopsis par scène, repéré par son numéro "n". Une scène sans matière narrative (bloc de
|
||||
statistiques, table, crédits) reçoit un synopsis vide "".
|
||||
- PNJ : écris leur nom EXACTEMENT comme dans le texte. Pas de monstres génériques sans nom
|
||||
(« 3 gobelins », « un loup »). Aucun PNJ nommé → "npcs": [].
|
||||
- Un PNJ est un INDIVIDU. Ne relève PAS les peuples, factions, organisations, groupes, lieux,
|
||||
objets, ni les profils de créature (« Légionnaire », « Zombie », « Garde »).
|
||||
- Chaque PNJ une seule fois, sous son nom le plus complet, sans son titre (« dame », « capitaine »).
|
||||
- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour :
|
||||
{{"scenes": [{{"n": 1, "synopsis": "…"}}], "npcs": [{{"name": "…", "description": "…"}}]}}
|
||||
- Rédige les synopsis et les fiches en {language_name}, quelle que soit la langue du texte.
|
||||
Garde tels quels les noms propres.
|
||||
|
||||
{scenes}
|
||||
|
||||
Renvoie maintenant le JSON."""
|
||||
|
||||
OVERVIEW_TITLES = {"fr": "Présentation", "en": "Overview"}
|
||||
APPENDIX_ARC_NAMES = {"fr": "Annexes", "en": "Appendices"}
|
||||
|
||||
|
||||
def appendix_arc_name(language: str) -> str:
|
||||
"""Nom de l'arc qui réunit les annexes du livre (bestiaire, objets, aides de jeu)."""
|
||||
return APPENDIX_ARC_NAMES.get(language, APPENDIX_ARC_NAMES["fr"])
|
||||
|
||||
|
||||
def overview_title(language: str) -> str:
|
||||
"""Nom de la scène qui porte le texte d'introduction d'une aventure."""
|
||||
return OVERVIEW_TITLES.get(language, OVERVIEW_TITLES["fr"])
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Prompt d'étoffage des champs d'une entité narrative (arc / chapitre / scène) — Pilier A.
|
||||
|
||||
Générique : le Core (Java) est la SOURCE DE VÉRITÉ des champs (clé + libellé) et les
|
||||
passe en entrée ; ce module ne fait que formuler le prompt. Le modèle ne renvoie que les
|
||||
clés fournies et OMET celles pour lesquelles il n'a rien de pertinent (pas de remplissage forcé).
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Étiquette lisible du type d'entité, pour la formulation du prompt.
|
||||
ENTITY_LABEL: dict[str, str] = {
|
||||
"arc": "cet arc narratif",
|
||||
"chapter": "ce chapitre",
|
||||
"scene": "cette scène",
|
||||
}
|
||||
|
||||
|
||||
def narrative_fields_prompt(entity_type: str, entity_context: str, instruction: str,
|
||||
fields: list[dict], language: str) -> str:
|
||||
"""Construit le prompt d'étoffage. `fields` = [{key, label}] (whitelist du Core)."""
|
||||
label = ENTITY_LABEL.get(entity_type or "", "cette entité narrative")
|
||||
lines = []
|
||||
for f in fields or []:
|
||||
key = str(f.get("key") or "").strip()
|
||||
if not key:
|
||||
continue
|
||||
flabel = str(f.get("label") or key).strip()
|
||||
lines.append(f'- "{key}" : {flabel}')
|
||||
fields_list = "\n".join(lines)
|
||||
instruction_block = (
|
||||
f"\nConsigne particulière du MJ : {instruction.strip()}\n"
|
||||
if instruction and instruction.strip() else ""
|
||||
)
|
||||
return (
|
||||
f"Tu es un co-Maître de Jeu. On te donne l'état ACTUEL d'{label} de jeu de rôle. "
|
||||
"Propose des valeurs pour l'ÉTOFFER, cohérentes avec ce qui existe déjà.\n\n"
|
||||
f"{entity_context.strip()}\n"
|
||||
f"{instruction_block}\n"
|
||||
"Champs que tu peux remplir (n'utilise QUE ces clés) :\n"
|
||||
f"{fields_list}\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"fields": {"cle": "valeur proposée", ...}}\n'
|
||||
"- N'inclus QUE des clés de la liste ci-dessus. N'invente AUCUNE autre clé.\n"
|
||||
"- Si un champ est déjà bien rempli ou si tu n'as rien de pertinent, OMETS-le "
|
||||
"(ne le renvoie pas) plutôt que de le remplir de force.\n"
|
||||
"- Reste cohérent avec le contexte : n'invente pas d'élément qui contredit "
|
||||
"l'entité ou la campagne.\n"
|
||||
f"- Rédige les valeurs en {language_name(language)}.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Prompts de l'entraînement aux règles : série de situations, puis comparaison d'une réponse.
|
||||
|
||||
Le MJ apprend son système en tranchant des situations tirées de ses propres scènes. Le
|
||||
Core envoie les sections de règles utiles (déjà choisies et bornées) et un résumé des
|
||||
scènes ; ce module ne fait que formuler les prompts.
|
||||
|
||||
Deux principes tiennent toute la fonction :
|
||||
- le corrigé cite les règles MOT POUR MOT : le Core vérifie que l'extrait se retrouve
|
||||
dans la section envoyée, et écarte la situation sinon ;
|
||||
- le modèle ne lance aucun dé et ne calcule rien : il dit quelle règle s'applique.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Verdicts possibles d'une comparaison (relayés tels quels au Core).
|
||||
VERDICTS = ("right", "partial", "off")
|
||||
|
||||
|
||||
def _rules_block(sections: dict[str, str]) -> str:
|
||||
return "\n\n".join(
|
||||
f"### {title.strip()}\n{content.strip()}"
|
||||
for title, content in (sections or {}).items()
|
||||
if isinstance(content, str) and content.strip()
|
||||
)
|
||||
|
||||
|
||||
def _system_label(system_name: str) -> str:
|
||||
return system_name.strip() if system_name and system_name.strip() else "ce jeu"
|
||||
|
||||
|
||||
def rule_drills_prompt(system_name: str, sections: dict[str, str], scenes: list[dict],
|
||||
count: int, avoid: list[str], language: str) -> str:
|
||||
"""Prompt d'une série. `scenes` = [{"name", "kind", "text"}] (peut être vide)."""
|
||||
scene_lines = []
|
||||
for index, scene in enumerate(scenes or [], start=1):
|
||||
name = str(scene.get("name") or "").strip() or f"Scène {index}"
|
||||
kind = str(scene.get("kind") or "").strip()
|
||||
text = str(scene.get("text") or "").strip()
|
||||
head = f"[{index}] {name}" + (f" ({kind})" if kind else "")
|
||||
scene_lines.append(f"{head}\n{text}" if text else head)
|
||||
if scene_lines:
|
||||
scenes_block = (
|
||||
"Scènes du scénario (le décor des situations ; elles ne contiennent AUCUNE règle) :\n"
|
||||
+ "\n\n".join(scene_lines) + "\n\n"
|
||||
"Chaque situation se passe dans UNE de ces scènes et reprend ce qui s'y trouve "
|
||||
'(lieu, personnages, adversaires). "scene" = le numéro entre crochets de cette scène.\n'
|
||||
)
|
||||
else:
|
||||
scenes_block = (
|
||||
"Aucune scène n'est fournie : imagine des situations typiques d'une partie de ce "
|
||||
'jeu, et mets "scene" à 0.\n'
|
||||
)
|
||||
avoided = "\n".join(f"- {s.strip()}" for s in avoid or [] if s and s.strip())
|
||||
avoid_block = (
|
||||
"\nSituations DÉJÀ posées (propose autre chose, sur d'autres règles si possible) :\n"
|
||||
f"{avoided}\n" if avoided else ""
|
||||
)
|
||||
return (
|
||||
f"Tu prépares un entraînement pour un MJ qui apprend les règles du jeu de rôle "
|
||||
f"« {_system_label(system_name)} » avant de le faire jouer.\n"
|
||||
f"Écris {count} situations de table. Dans chacune, un joueur tente quelque chose, ou "
|
||||
"quelque chose arrive aux personnages, et le MJ doit décider quelle règle s'applique. "
|
||||
"Le MJ répondra de mémoire, puis lira ton corrigé.\n\n"
|
||||
"Extraits des règles (SEULE source autorisée pour les règles) :\n"
|
||||
f"{_rules_block(sections)}\n\n"
|
||||
f"{scenes_block}"
|
||||
f"{avoid_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"drills": [{"scene": 1, "situation": "…", "section": "titre de la '
|
||||
'section", "excerpt": "…", "ruling": "…"}]}\n'
|
||||
'- "situation" : 2 ou 3 phrases concrètes sur ce qui se passe à la table (un joueur annonce '
|
||||
"une action, un adversaire agit, un danger se déclenche), puis une question courte. N'y "
|
||||
"donne ni la règle ni la réponse, et ne nomme pas la valeur ou le jet à utiliser. Ce n'est "
|
||||
"pas une question de cours : ne demande pas quelle caractéristique consulter ni comment "
|
||||
"une valeur se calcule en général.\n"
|
||||
"- Adresse-toi directement au MJ, à la deuxième personne (« vous » en français), dans la "
|
||||
"question comme dans le corrigé : pas de « le MJ doit… ».\n"
|
||||
"- Chaque situation porte sur UNE règle précise, écrite dans les extraits. N'utilise "
|
||||
"aucune règle absente des extraits et n'importe pas les habitudes d'un autre jeu. Si les "
|
||||
'extraits ne contiennent aucune règle applicable à la table, renvoie {"drills": []}.\n'
|
||||
'- "excerpt" : le passage des extraits qui tranche la situation, COPIÉ MOT POUR MOT '
|
||||
"(1 à 4 phrases qui se suivent). Ne reformule pas, ne corrige pas, ne coupe pas au milieu, "
|
||||
"n'ajoute ni points de suspension ni guillemets.\n"
|
||||
'- "section" : le titre EXACT de la section d\'où vient ce passage.\n'
|
||||
'- "ruling" : ce que le MJ doit faire à la table, en 2 à 4 phrases, en s\'appuyant '
|
||||
"uniquement sur le passage cité.\n"
|
||||
"- Ne lance AUCUN dé et ne calcule aucun résultat : dis quel jet, quelle valeur ou quelle "
|
||||
"procédure s'applique, pas ce qui en sort.\n"
|
||||
"- Varie les règles et les sections d'une situation à l'autre, et commence par les règles "
|
||||
"qui servent le plus souvent en jeu.\n"
|
||||
f"- Rédige situations et corrigés en {language_name(language)}. Le passage cité reste "
|
||||
"dans la langue des extraits, tel quel.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
|
||||
|
||||
def rule_drill_review_prompt(system_name: str, section_title: str, section_text: str,
|
||||
situation: str, excerpt: str, ruling: str, answer: str,
|
||||
language: str) -> str:
|
||||
"""Prompt de comparaison : la décision écrite par le MJ face au corrigé."""
|
||||
return (
|
||||
f"Un MJ s'entraîne aux règles du jeu de rôle « {_system_label(system_name)} ». "
|
||||
"Il a tranché une situation de mémoire ; compare sa décision aux règles.\n\n"
|
||||
f"Règles — section « {section_title.strip()} » (SEULE source autorisée) :\n"
|
||||
f"{section_text.strip()}\n\n"
|
||||
f"Situation :\n{situation.strip()}\n\n"
|
||||
f"Passage qui s'applique :\n{excerpt.strip()}\n\n"
|
||||
f"Corrigé de référence :\n{ruling.strip()}\n\n"
|
||||
f"Décision du MJ :\n{answer.strip()}\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"verdict": "right", "feedback": "…"}\n'
|
||||
'- "verdict" : "right" si la décision applique la règle ; "partial" si elle va dans le '
|
||||
'bon sens mais oublie ou déforme un point ; "off" si elle applique autre chose.\n'
|
||||
'- "feedback" : 1 à 3 phrases adressées au MJ à la deuxième personne (« vous » en '
|
||||
"français). Dis ce qui est juste, puis ce qui manque "
|
||||
"ou diverge, en nommant le point de règle. Une décision différente du corrigé mais "
|
||||
"conforme aux règles fournies est juste.\n"
|
||||
"- Juge sur le fond, pas sur la formulation ni sur l'orthographe.\n"
|
||||
"- Ne t'appuie que sur les règles fournies. Ne lance aucun dé et ne calcule rien.\n"
|
||||
f"- Rédige le retour en {language_name(language)}.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Prompt d'ébauche de scènes pour un chapitre (Pilier A — capacité « create »).
|
||||
|
||||
Le co-MJ propose plusieurs scènes cohérentes pour PEUPLER un chapitre vide (ou en manque).
|
||||
JSON structuré, une liste de scènes ; l'humain révise et ne crée que celles qu'il retient.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def scene_drafts_prompt(context: str, instruction: str, count: int, language: str) -> str:
|
||||
instruction_block = (
|
||||
f"\nConsigne particulière du MJ : {instruction.strip()}\n"
|
||||
if instruction and instruction.strip() else ""
|
||||
)
|
||||
return (
|
||||
f"Tu es un co-Maître de Jeu. Propose {count} SCÈNES de jeu de rôle pour PEUPLER ce "
|
||||
"chapitre, cohérentes entre elles et avec le contexte.\n\n"
|
||||
f"{context.strip()}\n"
|
||||
f"{instruction_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"scenes": [{"name": "...", "description": "...", "playerNarration": "..."}]}\n'
|
||||
f"- Propose AU PLUS {count} scènes, distinctes et complémentaires (une progression du chapitre).\n"
|
||||
"- 'name' : titre court et évocateur (OBLIGATOIRE).\n"
|
||||
"- 'description' : un résumé bref (une phrase).\n"
|
||||
"- 'playerNarration' : 2-3 phrases de mise en scène lues aux joueurs.\n"
|
||||
"- Ne DUPLIQUE pas les scènes déjà présentes ; reste cohérent avec le chapitre et la campagne "
|
||||
"(n'invente pas d'élément qui les contredit).\n"
|
||||
f"- Rédige en {language_name(language)}.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Prompt du récap « précédemment dans… » (mode séance).
|
||||
|
||||
Le Core envoie le journal chronologique de la séance PRÉCÉDENTE ; le modèle rédige un
|
||||
récapitulatif court, à lire aux joueurs à l'ouverture de la séance suivante. Texte libre
|
||||
(pas de JSON) : c'est de la narration.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
|
||||
def session_recap_prompt(transcript: str, context: str, language: str) -> str:
|
||||
context_block = f"\n{context.strip()}\n" if context and context.strip() else ""
|
||||
return (
|
||||
"Tu es le Maître du Jeu. Voici le journal de la SÉANCE PRÉCÉDENTE de ta table "
|
||||
"(entrées chronologiques : notes, évènements, jets de dés, actions des joueurs).\n"
|
||||
f"{context_block}\n"
|
||||
"Journal :\n"
|
||||
f"{transcript.strip()}\n\n"
|
||||
"Rédige un récapitulatif « Précédemment… » à LIRE AUX JOUEURS pour ouvrir la "
|
||||
"nouvelle séance :\n"
|
||||
"- 4 à 8 phrases, ton narratif et vivant, au passé.\n"
|
||||
"- Uniquement ce qui s'est réellement passé dans le journal — n'invente RIEN, "
|
||||
"ne révèle aucun secret du MJ.\n"
|
||||
"- Termine sur la situation où les joueurs se sont arrêtés (le « cliffhanger »).\n"
|
||||
f"- Rédige en {language_name(language)}. Pas de préambule ni de méta : juste le récit."
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Prompt de proposition d'un modèle de fiche (PJ, PNJ, ennemi) à partir des règles.
|
||||
|
||||
Le Core envoie les sections de règles utiles (déjà choisies et bornées en taille) ; ce
|
||||
module ne fait que formuler le prompt. La fiche est une liste de champs typés que le MJ
|
||||
relit avant de les ajouter : seule source autorisée = les extraits fournis, rien n'est
|
||||
inventé ni emprunté à un autre jeu.
|
||||
"""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Types qu'un champ proposé peut prendre (les autres types de l'appli — image, tableau —
|
||||
# ne se déduisent pas des règles).
|
||||
ALLOWED_TYPES = ("TEXT", "NUMBER", "KEY_VALUE_LIST")
|
||||
|
||||
_SHEETS: dict[str, tuple[str, str]] = {
|
||||
"character": (
|
||||
"PERSONNAGE JOUEUR",
|
||||
"Ce qu'un joueur note sur sa feuille : son identité de jeu (classe, métier, origine… "
|
||||
"si le jeu en a), ses caractéristiques, ses jauges (points de vie…), ses compétences, "
|
||||
"son équipement, ses capacités.",
|
||||
),
|
||||
"npc": (
|
||||
"PERSONNAGE NON-JOUEUR",
|
||||
"Une fiche COURTE : ce que les règles demandent pour faire jouer un PNJ (valeurs de jeu "
|
||||
"simplifiées, attitude, rôle). Les champs purement narratifs (apparence, motivation) "
|
||||
"existent en général déjà : ne les propose que si les règles les nomment. Ne recopie ni la "
|
||||
"fiche d'une créature ou d'un monstre, ni la feuille complète d'un personnage joueur : si les "
|
||||
"règles ne disent rien de particulier sur les PNJ, renvoie une liste vide.",
|
||||
),
|
||||
"enemy": (
|
||||
"ENNEMI (créature, adversaire)",
|
||||
"Le bloc de statistiques de combat tel que les règles le présentent : défense, points de "
|
||||
"vie, attaques, capacités spéciales, faiblesses, butin… Le niveau est déjà géré par "
|
||||
"l'application.",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def sheet_label(sheet: str) -> str:
|
||||
"""Nom lisible de la fiche (pour le prompt et les messages)."""
|
||||
return _SHEETS.get(sheet, _SHEETS["character"])[0]
|
||||
|
||||
|
||||
def sheet_template_prompt(sheet: str, system_name: str, sections: dict[str, str],
|
||||
existing_fields: list[str], language: str) -> str:
|
||||
"""Construit le prompt. `sections` = {titre → règles} ; `existing_fields` = noms déjà en place."""
|
||||
label, guidance = _SHEETS.get(sheet, _SHEETS["character"])
|
||||
rules = "\n\n".join(
|
||||
f"### {title.strip()}\n{content.strip()}"
|
||||
for title, content in (sections or {}).items()
|
||||
if isinstance(content, str) and content.strip()
|
||||
)
|
||||
existing = "\n".join(f"- {name.strip()}" for name in existing_fields or [] if name and name.strip())
|
||||
existing_block = (
|
||||
"\nChamps DÉJÀ présents dans la fiche (ne les repropose pas, même sous un autre nom) :\n"
|
||||
f"{existing}\n" if existing else ""
|
||||
)
|
||||
system = system_name.strip() if system_name and system_name.strip() else "ce jeu"
|
||||
return (
|
||||
f"Tu aides un MJ à préparer la fiche de {label} du jeu de rôle « {system} » dans une "
|
||||
"application de préparation de parties.\n"
|
||||
"Une fiche est une liste de CHAMPS que le MJ remplira ensuite pour chaque fiche.\n"
|
||||
f"{guidance}\n\n"
|
||||
"Types de champ disponibles :\n"
|
||||
'- "TEXT" : texte libre (classe, historique, équipement, capacités…).\n'
|
||||
'- "NUMBER" : UNE valeur numérique (niveau, points de vie, défense…).\n'
|
||||
'- "KEY_VALUE_LIST" : une liste FIXE de lignes ayant chacune une valeur (caractéristiques, '
|
||||
'compétences, jets de sauvegarde…). "labels" donne ces lignes, dans l\'ordre des règles.\n\n'
|
||||
"Extraits des règles (SEULE source autorisée) :\n"
|
||||
f"{rules}\n"
|
||||
f"{existing_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"fields": [{"name": "nom du champ", "type": "KEY_VALUE_LIST", '
|
||||
'"labels": ["ligne 1", "ligne 2"], "source": "titre de la section"}, '
|
||||
'{"name": "nom du champ", "type": "NUMBER", "labels": [], "source": "titre de la section"}]}\n'
|
||||
"- Ne propose QUE des champs que les extraits décrivent. N'invente rien et n'importe pas "
|
||||
'les habitudes d\'un autre jeu. Si les extraits ne décrivent pas cette fiche, renvoie {"fields": []}.\n'
|
||||
"- Reprends les termes EXACTS des règles, y compris pour nommer un groupe : si le jeu appelle "
|
||||
"ses caractéristiques « Traits » ou ses compétences « Savoir-faire », le champ porte ce nom.\n"
|
||||
'- "labels" : uniquement pour KEY_VALUE_LIST, de 2 à 30 lignes ; liste vide pour les autres types.\n'
|
||||
'- "source" : le titre EXACT de la section d\'où vient le champ.\n'
|
||||
"- N'inclus ni le nom, ni le portrait, ni les images : l'application les gère déjà.\n"
|
||||
"- De 5 à 20 champs, du plus important au moins important. Regroupe : UNE liste pour un "
|
||||
"groupe de valeurs de même nature, plutôt qu'un champ par valeur.\n"
|
||||
f"- Noms de champs et lignes en {language_name(language)}, en gardant les termes propres au jeu.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Prompt du relevé de sorts dans un texte de règles.
|
||||
|
||||
Le MJ a déjà les règles de son système ; il veut en tirer un catalogue de sorts sans les
|
||||
retaper. Le Core envoie UN morceau de règles (borné) et les champs du modèle de sort ; ce
|
||||
module ne fait que formuler le prompt.
|
||||
|
||||
Un principe tient toute la fonction : le modèle DÉSIGNE, il n'écrit pas. Il rend le nom du
|
||||
sort tel qu'il est dans le texte, son niveau, son école, et les premiers mots de son bloc ;
|
||||
la description, elle, est reprise du texte par le code (cf. spell_location), mot pour mot.
|
||||
"""
|
||||
|
||||
|
||||
def _system_label(system_name: str) -> str:
|
||||
return system_name.strip() if system_name and system_name.strip() else "ce jeu"
|
||||
|
||||
|
||||
def spell_extraction_prompt(system_name: str, section_title: str, text: str,
|
||||
fields: list[dict], avoid: list[str]) -> str:
|
||||
"""Prompt du relevé. `fields` = [{"name", "type"}] (peut être vide) ; `avoid` = noms déjà relevés."""
|
||||
field_lines = []
|
||||
for field in fields or []:
|
||||
name = str(field.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
kind = "nombre" if str(field.get("type") or "").upper() == "NUMBER" else "texte"
|
||||
field_lines.append(f"- {name} ({kind})")
|
||||
if field_lines:
|
||||
fields_block = (
|
||||
"Champs d'un sort dans ce système (les SEULES clés autorisées dans \"values\") :\n"
|
||||
+ "\n".join(field_lines) + "\n"
|
||||
'Dans "values", ne mets un champ que si le texte donne sa valeur pour ce sort ; '
|
||||
"recopie la valeur telle qu'elle est écrite. Un champ « nombre » ne reçoit que des "
|
||||
"chiffres.\n"
|
||||
)
|
||||
else:
|
||||
fields_block = 'Aucun champ particulier n\'est défini : renvoie "values": {}.\n'
|
||||
avoided = "\n".join(f"- {name.strip()}" for name in avoid or [] if name and name.strip())
|
||||
avoid_block = (
|
||||
"\nSorts DÉJÀ relevés (ne les renvoie pas) :\n"
|
||||
f"{avoided}\n" if avoided else ""
|
||||
)
|
||||
title = section_title.strip()
|
||||
source = f"section « {title} »" if title else "extrait"
|
||||
return (
|
||||
f"Tu aides un MJ à constituer le catalogue de sorts du jeu de rôle "
|
||||
f"« {_system_label(system_name)} » à partir de ses règles.\n"
|
||||
"Relève CHAQUE sort décrit dans le texte ci-dessous. Compte comme un sort tout effet "
|
||||
"magique NOMMÉ que l'on lance ou active et dont le texte décrit l'effet (sort, "
|
||||
"incantation, prière, pouvoir, rituel…).\n\n"
|
||||
f"Texte des règles — {source} (SEULE source autorisée) :\n"
|
||||
f"{text.strip()}\n\n"
|
||||
f"{fields_block}"
|
||||
f"{avoid_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format exact : {"spells": [{"name": "…", "level": "…", "school": "…", '
|
||||
'"values": {"Champ": "valeur"}, "start": "…"}]}\n'
|
||||
'- "name" : le nom du sort, écrit EXACTEMENT comme dans le texte.\n'
|
||||
'- "level" : son niveau si le texte le donne, sinon "". Écris-le TOUJOURS de la même '
|
||||
"façon : un niveau numéroté par son SEUL nombre (« 1 », jamais « Niveau 1 » ni "
|
||||
"« NIVEAU 1 ») ; un sort de niveau 0 (tour de magie, cantrip, sort mineur) par "
|
||||
"« Tour de magie » si le texte est en français, « Cantrip » s'il est en anglais ; un "
|
||||
"autre palier par le terme du texte (« Rang II »). N'y ajoute rien d'autre (ni zone, ni "
|
||||
"type, ni durée).\n"
|
||||
'- "school" : son école, sa liste ou sa tradition si le texte la donne, sinon "". Donne '
|
||||
"son nom COURT, au singulier, sans « Sorts de » ni « École de » (« Foudre », pas « Sorts "
|
||||
"de foudre »), écrit de la même façon pour tous les sorts de cette école. Si le titre de "
|
||||
"la section ou un titre placé au-dessus du sort nomme l'école, c'est elle.\n"
|
||||
'- "start" : les 4 à 8 PREMIERS MOTS du bloc de ce sort, COPIÉS MOT POUR MOT depuis le '
|
||||
"texte, à partir de la ligne qui ouvre le sort (la ligne de son niveau si elle est juste "
|
||||
"au-dessus de son nom, sinon la ligne de son nom).\n"
|
||||
"- Ne recopie PAS la description du sort : l'application la reprend elle-même dans le "
|
||||
"texte, mot pour mot. Ne résume rien, ne traduis rien.\n"
|
||||
"- N'invente aucun sort et ne complète pas avec ce que tu sais d'un autre jeu. Un sort "
|
||||
"seulement cité, sans que le texte décrive son effet, n'est pas relevé.\n"
|
||||
"- Ne relève pas les règles générales de magie (comment lancer un sort, ce que coûte la "
|
||||
"magie) : seulement les sorts eux-mêmes.\n"
|
||||
"- Un OBJET n'est pas un sort, même s'il permet d'en lancer un : ne relève ni parchemin, "
|
||||
"ni baguette, ni potion, ni flacon, ni anneau, ni aucun autre objet magique.\n"
|
||||
'- Si le texte ne décrit aucun sort, renvoie {"spells": []}.\n'
|
||||
"- Garde la langue du texte : ne traduis pas les noms.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
|
||||
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
|
||||
|
||||
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
|
||||
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
|
||||
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
|
||||
pour rester sous les limites de sortie des modèles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.streaming import HEARTBEAT_INTERVAL_SECONDS, with_heartbeat
|
||||
from app.core.language import language_name
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LANGUAGES = ("fr", "en")
|
||||
|
||||
# Sections traduites en même temps (fournisseur distant). Traduites l'une après l'autre,
|
||||
# les sections d'un livre de 30 pages prenaient près d'une heure avec un modèle lent.
|
||||
DEFAULT_CONCURRENCY = 3
|
||||
# Durée maximale de la traduction. Au-delà, les sections restantes gardent le texte du livre.
|
||||
BUDGET_SECONDS = 60 * 60
|
||||
# Sections en échec à partir desquelles on n'en lance plus de nouvelles : le fournisseur est
|
||||
# en panne ou saturé, insister ferait attendre pour rien.
|
||||
MAX_FAILED_SECTIONS = 3
|
||||
|
||||
# Nombre de titres de section traduits par appel.
|
||||
TITLES_PER_CALL = 40
|
||||
|
||||
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||
CHUNK_CHARS = 6000
|
||||
|
||||
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
|
||||
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
|
||||
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
|
||||
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
|
||||
|
||||
|
||||
def detect_language(text: str, default: str = "fr") -> str:
|
||||
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
|
||||
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
|
||||
fr = sum(1 for w in words if w in _FR_WORDS)
|
||||
en = sum(1 for w in words if w in _EN_WORDS)
|
||||
if fr == en:
|
||||
return default if default in LANGUAGES else "fr"
|
||||
return "fr" if fr > en else "en"
|
||||
|
||||
|
||||
def other_languages(source: str) -> list[str]:
|
||||
return [lang for lang in LANGUAGES if lang != source]
|
||||
|
||||
|
||||
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
||||
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
|
||||
if len(text) <= max_chars:
|
||||
return [text]
|
||||
chunks: list[str] = []
|
||||
current = ""
|
||||
for para in re.split(r"(\n\s*\n)", text):
|
||||
if len(current) + len(para) <= max_chars:
|
||||
current += para
|
||||
continue
|
||||
if current.strip():
|
||||
chunks.append(current)
|
||||
current = ""
|
||||
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
|
||||
cut = para.rfind("\n", 0, max_chars)
|
||||
cut = cut if cut > 0 else max_chars
|
||||
chunks.append(para[:cut])
|
||||
para = para[cut:]
|
||||
current = para
|
||||
if current.strip():
|
||||
chunks.append(current)
|
||||
return chunks
|
||||
|
||||
|
||||
# Termes de jeu courants (vocabulaire des jeux « 5e »), anglais → français. Un petit modèle
|
||||
# les traduit au hasard (« WIS » → « SAGES », « Saving Throws » → « Sauvetages ») : on lui donne
|
||||
# ceux que l'extrait contient. Les abréviations (en capitales, ou monnaies) sont cherchées
|
||||
# telles quelles ; le reste sans tenir compte de la casse.
|
||||
_GLOSSARY_EN_FR: tuple[tuple[str, str], ...] = (
|
||||
("Armor Class", "Classe d'armure"), ("Hit Points", "Points de vie"), ("Speed", "Vitesse"),
|
||||
("Saving Throws", "Jets de sauvegarde"), ("saving throw", "jet de sauvegarde"),
|
||||
("Skills", "Compétences"), ("Senses", "Sens"), ("Languages", "Langues"), ("Challenge", "Puissance"),
|
||||
("Damage Resistances", "Résistances aux dégâts"), ("Damage Immunities", "Immunités aux dégâts"),
|
||||
("Damage Vulnerabilities", "Vulnérabilités aux dégâts"), ("Condition Immunities", "Immunités aux états"),
|
||||
("passive Perception", "Perception passive"), ("darkvision", "vision dans le noir"),
|
||||
("blindsight", "vision aveugle"), ("truesight", "vision véritable"),
|
||||
("tremorsense", "perception des vibrations"),
|
||||
("Legendary Actions", "Actions légendaires"), ("Reactions", "Réactions"), ("Multiattack", "Attaques multiples"),
|
||||
("Melee Weapon Attack", "Attaque au corps à corps avec une arme"),
|
||||
("Ranged Weapon Attack", "Attaque à distance avec une arme"),
|
||||
("Melee Spell Attack", "Attaque de sort au corps à corps"),
|
||||
("Ranged Spell Attack", "Attaque de sort à distance"),
|
||||
("to hit", "au toucher"), ("reach", "allonge"), ("one target", "une cible"),
|
||||
("Strength", "Force"), ("Dexterity", "Dextérité"), ("Wisdom", "Sagesse"), ("Charisma", "Charisme"),
|
||||
("STR", "FOR"), ("DEX", "DEX"), ("CON", "CON"), ("INT", "INT"), ("WIS", "SAG"), ("CHA", "CHA"),
|
||||
("AC", "CA"), ("DC", "DD"), ("HP", "PV"), ("XP", "PX"),
|
||||
("gp", "po"), ("sp", "pa"), ("cp", "pc"),
|
||||
("beast", "bête"), ("undead", "mort-vivant"), ("fiend", "fiélon"), ("fey", "fée"),
|
||||
("construct", "créature artificielle"), ("monstrosity", "monstruosité"), ("ooze", "vase"),
|
||||
("humanoid", "humanoïde"), ("unaligned", "non aligné"),
|
||||
("lawful good", "loyal bon"), ("lawful neutral", "loyal neutre"), ("lawful evil", "loyal mauvais"),
|
||||
("neutral good", "neutre bon"), ("neutral evil", "neutre mauvais"), ("chaotic good", "chaotique bon"),
|
||||
("chaotic neutral", "chaotique neutre"), ("chaotic evil", "chaotique mauvais"),
|
||||
("advantage", "avantage"), ("disadvantage", "désavantage"), ("short rest", "repos court"),
|
||||
("long rest", "repos long"), ("proficiency bonus", "bonus de maîtrise"),
|
||||
("spell slot", "emplacement de sort"), ("cantrip", "tour de magie"), ("Hit Dice", "dés de vie"),
|
||||
("bonus action", "action bonus"), ("difficult terrain", "terrain difficile"),
|
||||
("ability check", "test de caractéristique"), ("attack roll", "jet d'attaque"),
|
||||
("temporary hit points", "points de vie temporaires"), ("requires attunement", "nécessite un lien"),
|
||||
("Wondrous item", "Objet merveilleux"), ("very rare", "très rare"), ("uncommon", "peu commun"),
|
||||
("legendary", "légendaire"),
|
||||
("blinded", "aveuglé"), ("charmed", "charmé"), ("deafened", "assourdi"), ("frightened", "effrayé"),
|
||||
("grappled", "agrippé"), ("incapacitated", "neutralisé"), ("paralyzed", "paralysé"),
|
||||
("petrified", "pétrifié"), ("poisoned", "empoisonné"), ("prone", "à terre"), ("restrained", "entravé"),
|
||||
("stunned", "étourdi"), ("unconscious", "inconscient"), ("exhaustion", "épuisement"),
|
||||
("bludgeoning", "contondant"), ("piercing", "perforant"), ("slashing", "tranchant"),
|
||||
("necrotic", "nécrotique"), ("psychic", "psychique"), ("thunder", "tonnerre"), ("lightning", "foudre"),
|
||||
)
|
||||
_GLOSSARIES: dict[tuple[str, str], tuple[tuple[str, str], ...]] = {
|
||||
("en", "fr"): _GLOSSARY_EN_FR,
|
||||
("fr", "en"): tuple((french, english) for english, french in _GLOSSARY_EN_FR),
|
||||
}
|
||||
# Nombre maximal de termes donnés pour un extrait : le prompt d'un petit modèle reste court.
|
||||
GLOSSARY_TERMS = 45
|
||||
_EXACT_CASE = frozenset({"gp", "sp", "cp", "po", "pa", "pc"})
|
||||
|
||||
|
||||
def glossary(text: str, source: str, target: str, limit: int = GLOSSARY_TERMS) -> list[tuple[str, str]]:
|
||||
"""Termes de jeu présents dans `text`, avec leur traduction attendue (dans l'ordre du
|
||||
glossaire, `limit` au plus). Liste vide pour un couple de langues sans glossaire."""
|
||||
found: list[tuple[str, str]] = []
|
||||
for term, translation in _GLOSSARIES.get((source, target), ()):
|
||||
exact = term.isupper() or term in _EXACT_CASE
|
||||
pattern = rf"(?<![^\W\d_]){re.escape(term)}(?![^\W\d_])"
|
||||
if re.search(pattern, text, 0 if exact else re.IGNORECASE):
|
||||
found.append((term, translation))
|
||||
if len(found) >= limit:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def content_prompt(text: str, source: str, target: str) -> str:
|
||||
terms = glossary(text, source, target)
|
||||
block = ""
|
||||
if terms:
|
||||
block = ("Glossaire — pour ces termes de jeu, emploie EXACTEMENT la traduction indiquée :\n"
|
||||
+ "\n".join(f"- {term} → {translation}" for term, translation in terms) + "\n\n")
|
||||
return (
|
||||
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
||||
f"vers la langue « {language_name(target)} ».\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
|
||||
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||
"objets nommés.\n"
|
||||
"- Garde TELS QUELS les nombres, les dés (2d6 + 3) et les unités : ne convertis rien.\n"
|
||||
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
|
||||
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||
f"{block}"
|
||||
"Extrait :\n"
|
||||
f"{text}"
|
||||
)
|
||||
|
||||
|
||||
def titles_prompt(titles: list[str], source: str, target: str) -> str:
|
||||
listing = "\n".join(f"- {t}" for t in titles)
|
||||
return (
|
||||
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
|
||||
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
|
||||
"Garde les noms propres tels quels.\n"
|
||||
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
|
||||
f"{listing}"
|
||||
)
|
||||
|
||||
|
||||
class RulesTranslator:
|
||||
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
|
||||
|
||||
def __init__(self, llm: LLMProvider) -> None:
|
||||
self._llm = llm
|
||||
|
||||
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
|
||||
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
|
||||
out: dict[str, str] = {}
|
||||
# Par lots : un livre découpé par sa structure a des centaines de titres, trop pour
|
||||
# une seule réponse JSON d'un petit modèle.
|
||||
for start in range(0, len(titles), TITLES_PER_CALL):
|
||||
batch = titles[start:start + TITLES_PER_CALL]
|
||||
raw = await generate_with_retry(self._llm, titles_prompt(batch, source, target),
|
||||
output_format="json", temperature=0.2)
|
||||
parsed, _ = load_json_object(raw)
|
||||
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||
for title in batch:
|
||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||
translated = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||
# Le séparateur des niveaux d'un titre (« Magic › Fire Spells ») reste le même.
|
||||
if " › " in title and " › " not in translated:
|
||||
translated = translated.replace(" > ", " › ")
|
||||
out[title] = translated
|
||||
return out
|
||||
|
||||
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
|
||||
if not text or not text.strip():
|
||||
return text
|
||||
parts = []
|
||||
for chunk in split_markdown(text):
|
||||
if not chunk.strip():
|
||||
parts.append(chunk)
|
||||
continue
|
||||
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
|
||||
temperature=0.2)
|
||||
parts.append(translated.strip())
|
||||
return "\n\n".join(p for p in parts if p.strip())
|
||||
|
||||
|
||||
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
|
||||
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
|
||||
seen: dict[str, int] = {}
|
||||
out: dict[str, str] = {}
|
||||
for original, translated in titles.items():
|
||||
count = seen.get(translated, 0)
|
||||
seen[translated] = count + 1
|
||||
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class TranslatedRules:
|
||||
"""Règles dans la langue cible, dans l'ordre du livre.
|
||||
|
||||
`untranslated` liste les titres (d'origine) des sections qui n'ont pas pu être traduites :
|
||||
elles figurent dans `sections` avec leur titre et leur texte d'origine, pour que la
|
||||
version traduite reste complète.
|
||||
"""
|
||||
|
||||
sections: dict[str, str]
|
||||
untranslated: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _free_key(key: str, taken: dict[str, str]) -> str:
|
||||
"""`key`, ou `key (2)`, `key (3)`… si une section porte déjà ce titre."""
|
||||
if key not in taken:
|
||||
return key
|
||||
n = 2
|
||||
while f"{key} ({n})" in taken:
|
||||
n += 1
|
||||
return f"{key} ({n})"
|
||||
|
||||
|
||||
async def translate_sections(
|
||||
translator: RulesTranslator,
|
||||
sections: dict[str, str],
|
||||
source: str,
|
||||
target: str,
|
||||
*,
|
||||
concurrency: int = DEFAULT_CONCURRENCY,
|
||||
budget_seconds: float = BUDGET_SECONDS,
|
||||
heartbeat_seconds: float = HEARTBEAT_INTERVAL_SECONDS,
|
||||
with_titles: bool = True,
|
||||
labels: dict[str, str] | None = None,
|
||||
) -> AsyncIterator[tuple[str, Any]]:
|
||||
"""Traduit des sections {titre: markdown} et rend compte de l'avancement.
|
||||
|
||||
`with_titles=False` : les clés ne sont pas des titres à traduire mais de simples repères
|
||||
(scènes d'une campagne, dont les noms restent ceux du livre) ; `labels` donne alors le
|
||||
libellé de chacune pour les messages d'avancement.
|
||||
|
||||
Émet ('status', message) à chaque section terminée, ('heartbeat', None) tant que rien ne
|
||||
se termine, puis ('result', TranslatedRules).
|
||||
|
||||
- Les sections sont traduites `concurrency` à la fois.
|
||||
- Une section en échec garde son titre et son texte d'origine ; au bout de
|
||||
MAX_FAILED_SECTIONS échecs on n'en lance plus de nouvelles.
|
||||
- Passé `budget_seconds`, les traductions en cours sont abandonnées de la même façon.
|
||||
|
||||
Lève LLMProviderError si les titres ne peuvent pas être traduits (premier appel : le
|
||||
fournisseur ne répond pas) ou si aucune section n'a pu l'être.
|
||||
"""
|
||||
titles = list(sections)
|
||||
if not titles:
|
||||
yield ("result", TranslatedRules({}))
|
||||
return
|
||||
total = len(titles)
|
||||
label = language_name(target)
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
deadline = started + budget_seconds
|
||||
logger.info("Traduction des règles (%s → %s) : %s section(s), %s à la fois.",
|
||||
source, target, total, max(1, concurrency))
|
||||
|
||||
mapping: dict[str, str] = {}
|
||||
if with_titles:
|
||||
yield ("status", f"Traduction ({label}) des titres…")
|
||||
async for kind, payload in with_heartbeat(
|
||||
translator.translate_titles(titles, source, target), interval=heartbeat_seconds):
|
||||
if kind == "heartbeat":
|
||||
yield ("heartbeat", None)
|
||||
elif kind == "result":
|
||||
mapping = unique_titles(payload)
|
||||
|
||||
semaphore = asyncio.Semaphore(max(1, concurrency))
|
||||
failures: list[str] = []
|
||||
|
||||
async def translate_one(title: str) -> tuple[str, str | None]:
|
||||
async with semaphore:
|
||||
if len(failures) >= MAX_FAILED_SECTIONS:
|
||||
return title, None
|
||||
try:
|
||||
return title, await translator.translate_content(sections[title], source, target)
|
||||
except LLMProviderError as exc:
|
||||
failures.append(str(exc))
|
||||
logger.warning("Traduction (%s) de la section « %s » impossible : %s", target, title, exc)
|
||||
return title, None
|
||||
|
||||
tasks = [asyncio.ensure_future(translate_one(title)) for title in titles]
|
||||
translated: dict[str, str] = {}
|
||||
finished = 0
|
||||
out_of_time = False
|
||||
try:
|
||||
pending: set[asyncio.Future] = set(tasks)
|
||||
while pending:
|
||||
remaining = deadline - loop.time()
|
||||
if remaining <= 0:
|
||||
out_of_time = True
|
||||
break
|
||||
done, pending = await asyncio.wait(
|
||||
pending, timeout=min(heartbeat_seconds, remaining), return_when=asyncio.FIRST_COMPLETED)
|
||||
if not done:
|
||||
yield ("heartbeat", None)
|
||||
continue
|
||||
last = ""
|
||||
for task in done:
|
||||
title, text = task.result()
|
||||
finished += 1
|
||||
last = title
|
||||
# Une réponse vide pour un texte non vide n'est pas une traduction.
|
||||
if text is not None and (text.strip() or not sections[title].strip()):
|
||||
translated[title] = text
|
||||
yield ("status", f"Traduction ({label}) : {finished}/{total} — {(labels or {}).get(last, last)}")
|
||||
finally:
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
# Laisse les traductions abandonnées se défaire (appels au fournisseur refermés).
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
untranslated = [title for title in titles if title not in translated]
|
||||
elapsed = int(loop.time() - started)
|
||||
if not translated:
|
||||
if out_of_time:
|
||||
reason = "temps imparti dépassé"
|
||||
else:
|
||||
reason = failures[-1] if failures else "aucune réponse exploitable"
|
||||
raise LLMProviderError(f"aucune section n'a pu être traduite ({reason})")
|
||||
|
||||
out: dict[str, str] = {}
|
||||
for title in titles:
|
||||
if title in translated:
|
||||
out[_free_key(mapping.get(title, title), out)] = translated[title]
|
||||
else:
|
||||
out[_free_key(title, out)] = sections[title]
|
||||
logger.info("Traduction des règles (%s → %s) terminée en %ss : %s section(s) traduite(s), %s non traduite(s)%s.",
|
||||
source, target, elapsed, len(translated), len(untranslated),
|
||||
" (temps imparti dépassé)" if out_of_time else "")
|
||||
yield ("result", TranslatedRules(out, untranslated))
|
||||
@@ -0,0 +1,233 @@
|
||||
"""Relevé de sorts : le modèle DÉSIGNE les sorts, le code RECOPIE leur description.
|
||||
|
||||
Le texte d'un livre de règles fait autorité : la description d'un sort ne doit pas être
|
||||
réécrite par une IA, même « recopiée » — un petit modèle traduit, résume ou saute des mots
|
||||
(mesuré le 2026-11-13 : 18 sorts sur 18 écartés d'un morceau parce que le modèle les avait
|
||||
traduits). Ici le modèle ne rend que ce qu'il sait faire sans se tromper — le nom du sort, son
|
||||
niveau, son école, et les premiers mots de son bloc — et ce module retrouve le bloc dans le
|
||||
texte : la description est la tranche du livre qui va du nom du sort au sort suivant.
|
||||
|
||||
Logique pure : aucun appel au modèle ici.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
# Longueur maximale du passage cité (le début de la description), que le Core vérifie.
|
||||
EXCERPT_CHARS = 160
|
||||
# Le Core écarte un sort dont le passage cité fait moins de 25 caractères utiles. Une première
|
||||
# ligne plus courte que ce seuil (« 1 Action », « Rituel ») est donc prolongée par les suivantes.
|
||||
MIN_EXCERPT_CHARS = 40
|
||||
_LEADING = " \t:—–-·|"
|
||||
# Ce qui précède le nom dans son bloc (sa ligne de niveau : « TIER 1 », « Tour de magie ») est
|
||||
# gardé en tête de la description, tant que c'est court.
|
||||
_PREFIX_CHARS = 80
|
||||
# Ligne de niveau placée juste au-dessus du nom d'un sort.
|
||||
_LEVEL_LINE = re.compile(
|
||||
r"^(?:tier|niveau|level|lvl|rang|rank|cercle|circle|cantrip|tours? de magie|sorts? mineurs?)\b",
|
||||
re.IGNORECASE)
|
||||
_LEVEL_LINE_CHARS = 40
|
||||
# Un objet magique se reconnaît à sa rareté, donnée dès le début de son texte (« Very rare
|
||||
# flask », « Flacon très rare ») : un sort n'en a pas.
|
||||
_RARITY = re.compile(
|
||||
r"\b(?:common|uncommon|rare|very rare|legendary|artifact|commune?s?|peu commune?s?|tr[eè]s rares?"
|
||||
r"|l[ée]gendaires?|art[ée]fact)\b", re.IGNORECASE)
|
||||
_RARITY_WITHIN = 40
|
||||
# Un « nom » qui n'est qu'un niveau : la ligne d'un tableau (prix des parchemins par niveau).
|
||||
_LEVEL_NAME = re.compile(
|
||||
r"^(?:(?:sorts?|spells?)\s+(?:de\s+|du\s+|of\s+)?)?"
|
||||
r"(?:tier|niveau|level|lvl|rang|rank|cercle|circle|cantrips?|tours? de magie|sorts? mineurs?)\b"
|
||||
r"(?:\s*\d+)?(?:\s+(?:spells?|sorts?))?\s*$",
|
||||
re.IGNORECASE)
|
||||
_HEADING = re.compile(r"^#{2,4}\s+(.+?)\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LocatedSpell:
|
||||
name: str
|
||||
level: str
|
||||
school: str
|
||||
description: str
|
||||
excerpt: str
|
||||
values: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _text(value: object) -> str:
|
||||
"""Texte d'une valeur renvoyée par le modèle (un nombre arrive parfois en nombre)."""
|
||||
if isinstance(value, bool) or value is None:
|
||||
return ""
|
||||
if isinstance(value, (str, int, float)):
|
||||
return str(value).strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _find(text: str, wanted: str) -> tuple[int, int] | None:
|
||||
"""Première occurrence de `wanted` dans `text` (début, fin), aux espaces puis à la casse
|
||||
près : le modèle recopie parfois un retour à la ligne en espace, ou change une majuscule."""
|
||||
words = wanted.split()
|
||||
if not words:
|
||||
return None
|
||||
pattern = r"\s+".join(re.escape(word) for word in words)
|
||||
match = re.search(pattern, text) or re.search(pattern, text, re.IGNORECASE)
|
||||
return match.span() if match else None
|
||||
|
||||
|
||||
def _line_start(text: str, position: int) -> int:
|
||||
return text.rfind("\n", 0, position) + 1
|
||||
|
||||
|
||||
def _excerpt(description: str) -> str:
|
||||
"""Début de la description : le passage que le Core retrouve dans le texte envoyé.
|
||||
|
||||
C'est sa première ligne — prolongée par les suivantes tant qu'elle est trop courte pour
|
||||
faire foi (« 1 Action » ne prouve rien, « 1 Action Reaction: When an enemy… » si). Les
|
||||
lignes sont réunies par une espace : le Core compare aux espaces près."""
|
||||
lines = [line.strip() for line in description.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
return ""
|
||||
excerpt = lines[0].lstrip("#>*- ").strip() or lines[0]
|
||||
for line in lines[1:]:
|
||||
if len(excerpt) >= MIN_EXCERPT_CHARS:
|
||||
break
|
||||
excerpt = f"{excerpt} {line}"
|
||||
if len(excerpt) <= EXCERPT_CHARS:
|
||||
return excerpt
|
||||
cut = excerpt.rfind(" ", 0, EXCERPT_CHARS)
|
||||
return excerpt[:cut if cut > 0 else EXCERPT_CHARS]
|
||||
|
||||
|
||||
def _level_line_above(text: str, line_start: int) -> int:
|
||||
"""Début du bloc d'un sort dont le nom ouvre la ligne `line_start` : la ligne de niveau
|
||||
placée juste au-dessus (« TIER 1 », « CANTRIP », « Tour de magie ») en fait partie."""
|
||||
above = text[:line_start].rstrip()
|
||||
start = above.rfind("\n") + 1
|
||||
line = above[start:].strip()
|
||||
if not line or len(line) > _LEVEL_LINE_CHARS or line.startswith(("#", "|", "-")):
|
||||
return line_start
|
||||
return start if _LEVEL_LINE.match(line) else line_start
|
||||
|
||||
|
||||
def _level_from(prefix: str) -> str:
|
||||
"""Niveau que donne la ligne placée au-dessus du nom : « TIER 2, AOE » → « 2 »,
|
||||
« CANTRIP » → « Cantrip », « TOUR DE MAGIE » → « Tour de magie ». '' si ce n'en est pas une."""
|
||||
line = prefix.splitlines()[0].strip() if prefix.strip() else ""
|
||||
match = _LEVEL_LINE.match(line)
|
||||
if not match:
|
||||
return ""
|
||||
number = re.search(r"\d+", line)
|
||||
if number:
|
||||
return number.group()
|
||||
label = match.group(0) # « TOUR DE MAGIE UTILITÉ DE FEU » → « Tour de magie »
|
||||
return label[:1].upper() + label[1:].lower()
|
||||
|
||||
|
||||
def _is_item(description: str) -> bool:
|
||||
"""Le texte est-il celui d'un objet magique (rareté annoncée d'emblée) plutôt que d'un sort ?"""
|
||||
first = next((line for line in description.splitlines() if line.strip()), "")
|
||||
return bool(_RARITY.search(first[:_RARITY_WITHIN]))
|
||||
|
||||
|
||||
_SCHOOL_IN_TITLE = (
|
||||
re.compile(r"^(?P<school>.+?)\s+spells?$", re.IGNORECASE), # « Fire Spells »
|
||||
re.compile(r"^(?:sorts?|sortil[eè]ges?)\s+(?:de la |de l['’]|de |du |des |d['’])?(?P<school>.+)$",
|
||||
re.IGNORECASE), # « Sorts de feu »
|
||||
)
|
||||
|
||||
|
||||
def school_from_title(section_title: str) -> str:
|
||||
"""École que nomme le titre de la section (« Magic › Fire Spells » → « Fire »), ou ''."""
|
||||
# « › » sépare les niveaux d'un titre ; un titre traduit par l'IA porte parfois « > ».
|
||||
last = re.split(r"[›>]", section_title)[-1].strip()
|
||||
for pattern in _SCHOOL_IN_TITLE:
|
||||
match = pattern.match(last)
|
||||
if match:
|
||||
school = match.group("school").strip()
|
||||
return school[:1].upper() + school[1:]
|
||||
return ""
|
||||
|
||||
|
||||
def unclaimed_headings(text: str, spells: list[LocatedSpell]) -> list[str]:
|
||||
"""Intertitres du texte qu'aucun sort relevé ne nomme : dans une section de sorts, ce sont
|
||||
ceux que le modèle a laissés de côté."""
|
||||
names = [spell.name.casefold() for spell in spells]
|
||||
return [heading for heading in _HEADING.findall(text)
|
||||
if not any(name in heading.casefold() for name in names)]
|
||||
|
||||
|
||||
def named_by_a_heading(entries: object, headings: list[str]) -> list[dict]:
|
||||
"""Entrées du modèle dont le nom est celui d'un de ces intertitres."""
|
||||
folded = [heading.casefold() for heading in headings]
|
||||
return [entry for entry in entries if isinstance(entry, dict)
|
||||
and len(_text(entry.get("name"))) >= 3
|
||||
and any(_text(entry.get("name")).casefold() in heading for heading in folded)
|
||||
] if isinstance(entries, list) else []
|
||||
|
||||
|
||||
def locate_spells(entries: object, text: str, section_title: str = "") -> list[LocatedSpell]:
|
||||
"""Sorts désignés par le modèle, avec leur description reprise du texte.
|
||||
|
||||
Un sort dont le modèle ne donne pas l'école prend celle que nomme le titre de la section.
|
||||
|
||||
`entries` : la liste renvoyée par le modèle, des objets {name, level, school, values, start}.
|
||||
Un sort dont le nom ne figure pas dans le texte est écarté (inventé, traduit, ou venu d'un
|
||||
autre jeu), de même qu'un sort seulement cité, sans texte après son nom, et qu'un objet
|
||||
magique (son texte s'ouvre sur sa rareté)."""
|
||||
if not isinstance(entries, list):
|
||||
return []
|
||||
found: list[tuple[int, int, int, dict]] = [] # (début du bloc, début du nom, fin du nom, entrée)
|
||||
for entry in entries:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
name = _text(entry.get("name"))
|
||||
if not name or _LEVEL_NAME.match(name):
|
||||
continue
|
||||
# Le nom est cherché à partir des premiers mots du bloc quand le modèle les donne :
|
||||
# un sort cité plus haut dans le texte (dans une liste, un sommaire) n'est pas son bloc.
|
||||
start = _find(text, _text(entry.get("start")))
|
||||
name_span = None
|
||||
if start is not None:
|
||||
after = _find(text[start[0]:], name)
|
||||
if after is not None and after[0] <= 200:
|
||||
name_span = (start[0] + after[0], start[0] + after[1])
|
||||
if name_span is None:
|
||||
name_span = _find(text, name)
|
||||
start = None
|
||||
if name_span is None:
|
||||
continue
|
||||
block_start = _line_start(text, start[0] if start is not None else name_span[0])
|
||||
if start is None:
|
||||
block_start = _level_line_above(text, block_start)
|
||||
found.append((block_start, name_span[0], name_span[1], entry))
|
||||
|
||||
found.sort(key=lambda item: item[0])
|
||||
fallback_school = school_from_title(section_title)
|
||||
out: list[LocatedSpell] = []
|
||||
seen: set[str] = set()
|
||||
for position, (block_start, name_start, name_end, entry) in enumerate(found):
|
||||
name = _text(entry.get("name"))
|
||||
if name.lower() in seen:
|
||||
continue
|
||||
block_end = next((nxt[0] for nxt in found[position + 1:] if nxt[0] > block_start), len(text))
|
||||
body = text[name_end:max(name_end, block_end)].strip().lstrip(_LEADING).strip()
|
||||
if not body or _is_item(body):
|
||||
continue
|
||||
# Ce qui précède le nom dans son bloc — sa ligne de niveau — ouvre la description.
|
||||
prefix = text[block_start:name_start].strip().strip("#").strip()
|
||||
description = f"{prefix}\n\n{body}" if prefix and len(prefix) <= _PREFIX_CHARS else body
|
||||
values = entry.get("values")
|
||||
seen.add(name.lower())
|
||||
out.append(LocatedSpell(
|
||||
name=name,
|
||||
# Le niveau se lit d'abord sur la ligne de niveau du livre : elle fait foi. À
|
||||
# défaut, c'est celui que donne le modèle.
|
||||
level=_level_from(prefix) or _text(entry.get("level")),
|
||||
school=_text(entry.get("school")) or fallback_school,
|
||||
description=description,
|
||||
# Le passage cité part de ce qui suit le nom : dans le livre, le nom sépare la
|
||||
# ligne de niveau du reste, et le Core cherche un passage d'un seul tenant.
|
||||
excerpt=_excerpt(body),
|
||||
values={str(k).strip(): _text(v) for k, v in values.items() if str(k).strip() and _text(v)}
|
||||
if isinstance(values, dict) else {},
|
||||
))
|
||||
return out
|
||||
@@ -332,6 +332,26 @@ class TocEntry:
|
||||
page: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TextLine:
|
||||
"""Une ligne de texte du PDF, dans l'ordre de lecture, avec ce que la mise en page en dit.
|
||||
|
||||
`block` : rang du bloc de texte dans sa page (un bloc ≈ un paragraphe). `size` : taille de
|
||||
caractères dominante de la ligne, en points ; 0 quand elle est inconnue (page passée à
|
||||
l'OCR). C'est la taille qui distingue un titre du corps du texte, sans IA.
|
||||
`edge` : la ligne est tout en haut ou tout en bas de sa page (en-tête, pied, numéro de
|
||||
page). `cells` : nombre de cellules d'une rangée de tableau réunies dans cette ligne,
|
||||
séparées par « | » (1 = ligne ordinaire).
|
||||
"""
|
||||
|
||||
page: int # 0-based
|
||||
block: int
|
||||
text: str
|
||||
size: float
|
||||
edge: bool = False
|
||||
cells: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedDocument:
|
||||
"""Résultat brut de l'extraction d'un PDF : une entrée par page."""
|
||||
@@ -340,6 +360,9 @@ class ExtractedDocument:
|
||||
# Table des matières (bookmarks PDF). Vide si le PDF n'en a pas — fréquent
|
||||
# pour les scans ; les livres born-digital en ont presque toujours une.
|
||||
toc: list[TocEntry] = field(default_factory=list)
|
||||
# Lignes du livre avec leur taille de caractères (cf. TextLine). Vide quand l'extracteur
|
||||
# ne les fournit pas : le découpage par la structure du PDF est alors impossible.
|
||||
lines: list[TextLine] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
@@ -367,6 +390,10 @@ class RulesImportResult:
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
|
||||
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
|
||||
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||
source_language: str = ""
|
||||
|
||||
def to_markdown(self) -> str:
|
||||
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Socle commun aux adapters LLM « OpenAI-compatible » (OpenRouter, Gemini,
|
||||
Mistral) — ils exposent tous `POST {base}/chat/completions` en SSE avec le même
|
||||
schéma de payload et de flux.
|
||||
|
||||
Cette classe de base porte la mécanique partagée (construction du payload, appel
|
||||
HTTP streamé, parsing SSE, garde-fous de timeout au temps écoulé, traduction des
|
||||
erreurs). Chaque adapter concret ne fournit plus que ses spécificités :
|
||||
URL, en-têtes, support du mode JSON natif, messages d'erreur, lecture de la config.
|
||||
|
||||
`generate` one-shot passe lui aussi par le streaming (puis recollage) pour éviter
|
||||
les coupures de passerelle sur les longues générations (cf. Cloudflare 524).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Délai max pour le PREMIER token de contenu. Un modèle « en file d'attente »
|
||||
# n'envoie que des keep-alive (aucun contenu) → on échoue vite et clairement au
|
||||
# lieu de pendre. Le timeout réseau d'httpx ne suffit pas : des keep-alive font
|
||||
# « arriver des octets » et empêchent son read-timeout de se déclencher.
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
||||
|
||||
|
||||
def _answer_text(chunks: list[object]) -> str:
|
||||
"""Texte de réponse d'une liste de morceaux typés ; la réflexion est écartée."""
|
||||
parts: list[str] = []
|
||||
for chunk in chunks:
|
||||
if isinstance(chunk, dict) and chunk.get("type") == "text" and isinstance(chunk.get("text"), str):
|
||||
parts.append(chunk["text"])
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
class BaseOpenAICompatibleAdapter:
|
||||
"""Base des adapters clients d'une API OpenAI-compatible (chat/completions SSE).
|
||||
|
||||
Satisfait par duck typing les ports LLMProvider et LLMChatProvider. Les
|
||||
sous-classes définissent : ``_provider_label``, ``_api_url``,
|
||||
``_supports_json_object`` (mode JSON natif), et surchargent au besoin
|
||||
``_headers`` / ``_error_for_status`` / les messages de timeout.
|
||||
"""
|
||||
|
||||
# Surchargés par les sous-classes.
|
||||
_provider_label: str = "LLM"
|
||||
_api_url: str = ""
|
||||
_supports_json_object: bool = False
|
||||
|
||||
def __init__(self, api_key: str, model: str, timeout: int) -> None:
|
||||
self._api_key = api_key
|
||||
self._model = model
|
||||
self._timeout = timeout
|
||||
|
||||
# --- Spécificités surchargeables ----------------------------------------
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self._api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def _first_token_timeout_message(self) -> str:
|
||||
return (
|
||||
f"Erreur {self._provider_label} : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s — le modèle est probablement en "
|
||||
"file d'attente / saturé. Réessayez plus tard ou choisissez un autre modèle."
|
||||
)
|
||||
|
||||
def _generation_timeout_message(self) -> str:
|
||||
return (
|
||||
f"Erreur {self._provider_label} : génération non terminée en {self._timeout}s. "
|
||||
"Réduisez la taille des morceaux d'import, augmentez le timeout, ou changez de modèle."
|
||||
)
|
||||
|
||||
def _error_for_status(self, status_code: int, detail: str) -> LLMProviderError:
|
||||
"""Erreur de domaine pour une réponse HTTP >= 400 (détail déjà lu)."""
|
||||
return LLMProviderError(
|
||||
f"Erreur {self._provider_label} (HTTP {status_code})"
|
||||
+ (f" : {detail[:500]}" if detail else "")
|
||||
)
|
||||
|
||||
# --- API publique (ports) -----------------------------------------------
|
||||
|
||||
async def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
*,
|
||||
output_format: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> str:
|
||||
"""One-shot via streaming (puis recollage), avec garde-fous au temps écoulé."""
|
||||
return await self._collect_with_timeouts(
|
||||
[ChatMessage(role="user", content=prompt)], temperature, output_format
|
||||
)
|
||||
|
||||
async def stream_chat(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
*,
|
||||
system_prompt: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
async for token in self._stream(messages, system_prompt, temperature):
|
||||
if token: # jeton vide = le modèle réfléchit encore, rien à afficher
|
||||
yield token
|
||||
|
||||
# --- Mécanique partagée -------------------------------------------------
|
||||
|
||||
async def _collect_with_timeouts(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
temperature: float | None,
|
||||
output_format: str | None,
|
||||
) -> str:
|
||||
"""Collecte le stream avec DEUX garde-fous au temps écoulé :
|
||||
- 1er token borné (`_FIRST_TOKEN_TIMEOUT_SECONDS`) : détecte un modèle bloqué
|
||||
en file d'attente (que des keep-alive, aucun contenu) → échec rapide ;
|
||||
- ceiling global (`self._timeout`) : génération qui ne se termine jamais.
|
||||
"""
|
||||
async def _collect() -> str:
|
||||
chunks: list[str] = []
|
||||
started = False
|
||||
agen = self._stream(messages, None, temperature, output_format)
|
||||
try:
|
||||
while True:
|
||||
# Borne SEULEMENT l'attente du 1er signe d'activité ; ensuite on
|
||||
# laisse générer (le ceiling global couvre le reste). Un jeton vide
|
||||
# (modèle qui réfléchit) compte comme activité : il n'est pas en
|
||||
# file d'attente.
|
||||
first = None if started else _FIRST_TOKEN_TIMEOUT_SECONDS
|
||||
try:
|
||||
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
raise LLMProviderError(self._first_token_timeout_message())
|
||||
started = True
|
||||
if token:
|
||||
chunks.append(token)
|
||||
finally:
|
||||
await agen.aclose()
|
||||
return "".join(chunks)
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(_collect(), timeout=self._timeout)
|
||||
except asyncio.TimeoutError as exc:
|
||||
raise LLMGenerationTimeout(self._generation_timeout_message()) from exc
|
||||
|
||||
def _build_body(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
system_prompt: str | None,
|
||||
temperature: float | None,
|
||||
output_format: str | None,
|
||||
) -> dict[str, object]:
|
||||
payload_messages: list[dict[str, str]] = []
|
||||
if system_prompt:
|
||||
payload_messages.append({"role": "system", "content": system_prompt})
|
||||
for m in messages:
|
||||
payload_messages.append({"role": m.role, "content": m.content})
|
||||
|
||||
body: dict[str, object] = {
|
||||
"model": self._model,
|
||||
"messages": payload_messages,
|
||||
"stream": True,
|
||||
}
|
||||
if temperature is not None:
|
||||
body["temperature"] = temperature
|
||||
# Mode JSON natif : supprime les fences ```json et le JSON invalide (retours
|
||||
# à la ligne bruts), principale cause de morceaux d'import ignorés. Un SCHÉMA
|
||||
# (dict) est traduit en json_object — suffisant, les grands modèles cloud
|
||||
# respectent la structure demandée par le prompt. Désactivé pour les
|
||||
# providers/modèles gratuits qui ne le supportent pas (réponse vide).
|
||||
if self._supports_json_object and output_format is not None:
|
||||
body["response_format"] = {"type": "json_object"}
|
||||
return body
|
||||
|
||||
async def _stream(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
system_prompt: str | None,
|
||||
temperature: float | None,
|
||||
output_format: str | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
body = self._build_body(messages, system_prompt, temperature, output_format)
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
async with client.stream(
|
||||
"POST", self._api_url, headers=self._headers(), json=body
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
# En streaming le corps n'est pas lu automatiquement : on le
|
||||
# lit pour exposer le détail du provider (le 429 précise le
|
||||
# type de quota, le 401 la clé invalide…), sinon on n'a que
|
||||
# le code HTTP nu et le diagnostic est impossible.
|
||||
detail = (await response.aread()).decode("utf-8", "replace").strip()
|
||||
raise self._error_for_status(response.status_code, detail)
|
||||
async for token in self._parse_sse(response):
|
||||
yield token
|
||||
except httpx.HTTPError as exc:
|
||||
raise LLMProviderError(self._format_http_error(exc)) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
||||
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`.
|
||||
|
||||
Un modèle à raisonnement (Mistral Large 4…) envoie `content` sous forme de
|
||||
LISTE de morceaux typés : sa réflexion (`thinking`), puis le texte de la
|
||||
réponse (`text`). Seul le texte est transmis ; pendant la réflexion on émet
|
||||
un jeton VIDE, qui signale l'activité sans rien ajouter à la réponse.
|
||||
"""
|
||||
async for line in response.aiter_lines():
|
||||
if not line or not line.startswith("data:"):
|
||||
continue # lignes vides ou commentaires keep-alive (`: ...`)
|
||||
data = line[len("data:"):].strip()
|
||||
if data == "[DONE]":
|
||||
return
|
||||
try:
|
||||
obj = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
choices = obj.get("choices")
|
||||
if not choices:
|
||||
continue
|
||||
delta = choices[0].get("delta") or {}
|
||||
content = delta.get("content")
|
||||
if isinstance(content, str):
|
||||
if content:
|
||||
yield content
|
||||
elif isinstance(content, list):
|
||||
yield _answer_text(content)
|
||||
|
||||
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
||||
"""Message lisible (timeout, quota 429, crédits 402, modèle inconnu…)."""
|
||||
if isinstance(exc, httpx.TimeoutException):
|
||||
return (
|
||||
f"Erreur {self._provider_label} : délai dépassé (timeout {self._timeout}s). "
|
||||
"Le modèle a mis trop de temps — réduis la taille des morceaux d'import ou "
|
||||
"augmente le timeout."
|
||||
)
|
||||
detail = str(exc) or exc.__class__.__name__
|
||||
return f"Erreur {self._provider_label} ({exc.__class__.__name__}) : {detail}"
|
||||
@@ -1,194 +1,66 @@
|
||||
"""Adapter Google Gemini — implémente les ports LLMProvider / LLMChatProvider.
|
||||
|
||||
Gemini expose un endpoint COMPATIBLE OpenAI
|
||||
(POST {base}/openai/chat/completions, SSE), donc cet adapter est un client
|
||||
"OpenAI-compatible" — même structure que les adapters OpenRouter / Mistral.
|
||||
(POST {base}/openai/chat/completions, SSE) : client "OpenAI-compatible" qui hérite
|
||||
de BaseOpenAICompatibleAdapter et ne fournit que ses spécificités (dont un message
|
||||
dédié quand Google refuse la clé en 401/403).
|
||||
|
||||
Tier GRATUIT : clé API sur aistudio.google.com (sans CB). Atout majeur pour
|
||||
l'extraction de PDF : un CONTEXTE de ~1M tokens → un livre entier tient en 1-2
|
||||
appels, donc quasi aucun morceau perdu et peu de requêtes (limites jamais
|
||||
atteintes). Modèle conseillé : `gemini-2.0-flash` (rapide, gros contexte, fidèle).
|
||||
appels. Modèle conseillé : `gemini-2.0-flash` (rapide, gros contexte, fidèle).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_API_URL = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
|
||||
|
||||
# Délai max pour le PREMIER token de contenu (échec rapide si le modèle ne produit
|
||||
# rien). Gemini répond vite ; 120s est large.
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
||||
from app.domain.ports import LLMProviderError
|
||||
from app.infrastructure.base_openai_adapter import (
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS,
|
||||
BaseOpenAICompatibleAdapter,
|
||||
)
|
||||
|
||||
|
||||
class GeminiLLMProvider:
|
||||
class GeminiLLMProvider(BaseOpenAICompatibleAdapter):
|
||||
"""Adapter Gemini (OpenAI-compatible) — satisfait LLMProvider et LLMChatProvider."""
|
||||
|
||||
_provider_label = "Gemini"
|
||||
_api_url = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
|
||||
_supports_json_object = True
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
if not settings.gemini_api_key:
|
||||
raise LLMProviderError(
|
||||
"Clé API Gemini manquante. Configure-la depuis l'écran Paramètres "
|
||||
"(clé gratuite sur aistudio.google.com)."
|
||||
)
|
||||
self._api_key = settings.gemini_api_key
|
||||
self._model = settings.gemini_model
|
||||
self._timeout = settings.llm_timeout_seconds
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self._api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
async def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
*,
|
||||
output_format: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> str:
|
||||
"""One-shot via streaming (puis recollage), avec garde-fous au temps écoulé."""
|
||||
return await self._collect_with_timeouts(
|
||||
[ChatMessage(role="user", content=prompt)], temperature, output_format
|
||||
super().__init__(
|
||||
settings.gemini_api_key, settings.gemini_model, settings.llm_timeout_seconds
|
||||
)
|
||||
|
||||
async def _collect_with_timeouts(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
temperature: float | None,
|
||||
output_format: str | None,
|
||||
) -> str:
|
||||
"""Collecte le stream avec deux garde-fous : 1er token borné (échec rapide
|
||||
si rien ne sort) + ceiling global `self._timeout`."""
|
||||
async def _collect() -> str:
|
||||
chunks: list[str] = []
|
||||
agen = self._stream(messages, None, temperature, output_format)
|
||||
try:
|
||||
while True:
|
||||
first = _FIRST_TOKEN_TIMEOUT_SECONDS if not chunks else None
|
||||
try:
|
||||
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
raise LLMProviderError(
|
||||
f"Erreur Gemini : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s. Réessayez ou vérifiez "
|
||||
"votre quota gratuit."
|
||||
)
|
||||
chunks.append(token)
|
||||
finally:
|
||||
await agen.aclose()
|
||||
return "".join(chunks)
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {**super()._headers(), "Accept": "application/json"}
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(_collect(), timeout=self._timeout)
|
||||
except asyncio.TimeoutError as exc:
|
||||
raise LLMGenerationTimeout(
|
||||
f"Erreur Gemini : génération non terminée en {self._timeout}s. Réduisez la "
|
||||
"taille des morceaux d'import ou augmentez le timeout."
|
||||
) from exc
|
||||
def _first_token_timeout_message(self) -> str:
|
||||
return (
|
||||
f"Erreur Gemini : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s. Réessayez ou vérifiez "
|
||||
"votre quota gratuit."
|
||||
)
|
||||
|
||||
async def stream_chat(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
*,
|
||||
system_prompt: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
async for token in self._stream(messages, system_prompt, temperature):
|
||||
yield token
|
||||
def _generation_timeout_message(self) -> str:
|
||||
return (
|
||||
f"Erreur Gemini : génération non terminée en {self._timeout}s. Réduisez la "
|
||||
"taille des morceaux d'import ou augmentez le timeout."
|
||||
)
|
||||
|
||||
async def _stream(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
system_prompt: str | None,
|
||||
temperature: float | None,
|
||||
output_format: str | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
payload_messages: list[dict[str, str]] = []
|
||||
if system_prompt:
|
||||
payload_messages.append({"role": "system", "content": system_prompt})
|
||||
for m in messages:
|
||||
payload_messages.append({"role": m.role, "content": m.content})
|
||||
|
||||
body: dict[str, object] = {
|
||||
"model": self._model,
|
||||
"messages": payload_messages,
|
||||
"stream": True,
|
||||
}
|
||||
if temperature is not None:
|
||||
body["temperature"] = temperature
|
||||
# Mode JSON natif (supporté par l'endpoint OpenAI-compatible de Gemini) :
|
||||
# supprime fences ```json et JSON invalide, principale cause de morceaux
|
||||
# ignorés. Un SCHÉMA (dict) est traduit en json_object : suffisant, les
|
||||
# grands modèles cloud respectent la structure demandée par le prompt.
|
||||
if output_format is not None:
|
||||
body["response_format"] = {"type": "json_object"}
|
||||
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
async with client.stream(
|
||||
"POST", _API_URL, headers=self._headers(), json=body
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
detail = (await response.aread()).decode("utf-8", "replace").strip()
|
||||
# 401/403 = clé rejetée par GOOGLE (pas un problème LoreMind) :
|
||||
# message actionnable plutôt que le JSON brut de l'API.
|
||||
if response.status_code in (401, 403):
|
||||
raise LLMProviderError(
|
||||
"Erreur Gemini : clé API refusée par Google "
|
||||
f"(HTTP {response.status_code}). Vérifiez que la clé vient bien "
|
||||
"de aistudio.google.com (« Get API key ») et qu'elle n'a pas de "
|
||||
"restrictions (API ou adresse IP) dans la Google Cloud Console. "
|
||||
f"Détail : {detail[:300]}"
|
||||
)
|
||||
raise LLMProviderError(
|
||||
f"Erreur Gemini (HTTP {response.status_code})"
|
||||
+ (f" : {detail[:500]}" if detail else "")
|
||||
)
|
||||
async for token in self._parse_sse(response):
|
||||
yield token
|
||||
except httpx.HTTPError as exc:
|
||||
raise LLMProviderError(self._format_http_error(exc)) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
||||
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`."""
|
||||
async for line in response.aiter_lines():
|
||||
if not line or not line.startswith("data:"):
|
||||
continue
|
||||
data = line[len("data:"):].strip()
|
||||
if data == "[DONE]":
|
||||
return
|
||||
try:
|
||||
obj = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
choices = obj.get("choices")
|
||||
if not choices:
|
||||
continue
|
||||
delta = choices[0].get("delta") or {}
|
||||
content = delta.get("content")
|
||||
if content:
|
||||
yield content
|
||||
|
||||
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
||||
if isinstance(exc, httpx.TimeoutException):
|
||||
return (
|
||||
f"Erreur Gemini : délai dépassé (timeout {self._timeout}s). Le modèle a "
|
||||
"mis trop de temps — réduis la taille des morceaux d'import ou augmente le timeout."
|
||||
def _error_for_status(self, status_code: int, detail: str) -> LLMProviderError:
|
||||
# 401/403 = clé rejetée par GOOGLE (pas un problème LoreMind) : message
|
||||
# actionnable plutôt que le JSON brut de l'API.
|
||||
if status_code in (401, 403):
|
||||
return LLMProviderError(
|
||||
"Erreur Gemini : clé API refusée par Google "
|
||||
f"(HTTP {status_code}). Vérifiez que la clé vient bien "
|
||||
"de aistudio.google.com (« Get API key ») et qu'elle n'a pas de "
|
||||
"restrictions (API ou adresse IP) dans la Google Cloud Console. "
|
||||
f"Détail : {detail[:300]}"
|
||||
)
|
||||
detail = str(exc) or exc.__class__.__name__
|
||||
return f"Erreur Gemini ({exc.__class__.__name__}) : {detail}"
|
||||
return super()._error_for_status(status_code, detail)
|
||||
|
||||
@@ -1,195 +1,48 @@
|
||||
"""Adapter Mistral — implémente les ports LLMProvider / LLMChatProvider.
|
||||
|
||||
Mistral (La Plateforme) expose l'API OpenAI standard (POST {base}/chat/completions,
|
||||
SSE), donc cet adapter est un client "OpenAI-compatible" — même structure que
|
||||
l'adapter OpenRouter. Le `generate` one-shot passe par le streaming (puis
|
||||
recollage) avec un timeout au temps écoulé pour ne jamais pendre à l'infini.
|
||||
SSE) : client "OpenAI-compatible" qui hérite de BaseOpenAICompatibleAdapter et ne
|
||||
fournit que ses spécificités.
|
||||
|
||||
Tier GRATUIT : compte sur console.mistral.ai (tier « Experiment »), clé API à
|
||||
coller dans l'écran Paramètres. Modèles conseillés pour l'extraction : un grand
|
||||
contexte fidèle comme `mistral-large-latest` (128k) ou `mistral-small-latest`.
|
||||
|
||||
Mode JSON natif : TOUS les modèles Mistral le supportent (`_supports_json_object`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_API_URL = "https://api.mistral.ai/v1/chat/completions"
|
||||
|
||||
# Délai max pour le PREMIER token de contenu (échec rapide si le modèle est en file
|
||||
# d'attente et n'envoie que des keep-alive). Généreux car la file d'un tier gratuit
|
||||
# peut être longue.
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
||||
from app.domain.ports import LLMProviderError
|
||||
from app.infrastructure.base_openai_adapter import (
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS,
|
||||
BaseOpenAICompatibleAdapter,
|
||||
)
|
||||
|
||||
|
||||
class MistralLLMProvider:
|
||||
class MistralLLMProvider(BaseOpenAICompatibleAdapter):
|
||||
"""Adapter Mistral (OpenAI-compatible) — satisfait LLMProvider et LLMChatProvider."""
|
||||
|
||||
_provider_label = "Mistral"
|
||||
_api_url = "https://api.mistral.ai/v1/chat/completions"
|
||||
_supports_json_object = True
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
if not settings.mistral_api_key:
|
||||
raise LLMProviderError(
|
||||
"Clé API Mistral manquante. Configure-la depuis l'écran Paramètres."
|
||||
)
|
||||
self._api_key = settings.mistral_api_key
|
||||
self._model = settings.mistral_model
|
||||
self._timeout = settings.llm_timeout_seconds
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self._api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
async def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
*,
|
||||
output_format: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> str:
|
||||
"""One-shot via streaming (puis recollage) pour robustesse sur longues sorties.
|
||||
|
||||
Timeout au TEMPS ÉCOULÉ (asyncio) en plus du timeout réseau d'httpx :
|
||||
si le provider envoyait des keep-alive sans contenu, l'appel pendrait à
|
||||
l'infini. Ici on coupe net après `self._timeout` secondes.
|
||||
"""
|
||||
return await self._collect_with_timeouts(
|
||||
[ChatMessage(role="user", content=prompt)], temperature, output_format
|
||||
super().__init__(
|
||||
settings.mistral_api_key, settings.mistral_model, settings.llm_timeout_seconds
|
||||
)
|
||||
|
||||
async def _collect_with_timeouts(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
temperature: float | None,
|
||||
output_format: str | None,
|
||||
) -> str:
|
||||
"""Collecte le stream avec deux garde-fous au temps écoulé : 1er token borné
|
||||
(file d'attente → échec rapide) + ceiling global `self._timeout`."""
|
||||
async def _collect() -> str:
|
||||
chunks: list[str] = []
|
||||
agen = self._stream(messages, None, temperature, output_format)
|
||||
try:
|
||||
while True:
|
||||
first = _FIRST_TOKEN_TIMEOUT_SECONDS if not chunks else None
|
||||
try:
|
||||
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
raise LLMProviderError(
|
||||
f"Erreur Mistral : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s — le modèle est probablement "
|
||||
"en file d'attente (tier gratuit, 2 req/min). Réessayez plus tard ou "
|
||||
"choisissez un modèle plus disponible."
|
||||
)
|
||||
chunks.append(token)
|
||||
finally:
|
||||
await agen.aclose()
|
||||
return "".join(chunks)
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {**super()._headers(), "Accept": "application/json"}
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(_collect(), timeout=self._timeout)
|
||||
except asyncio.TimeoutError as exc:
|
||||
raise LLMGenerationTimeout(
|
||||
f"Erreur Mistral : génération non terminée en {self._timeout}s. Réduisez la "
|
||||
"taille des morceaux d'import, augmentez le timeout, ou changez de modèle."
|
||||
) from exc
|
||||
|
||||
async def stream_chat(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
*,
|
||||
system_prompt: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
async for token in self._stream(messages, system_prompt, temperature):
|
||||
yield token
|
||||
|
||||
async def _stream(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
system_prompt: str | None,
|
||||
temperature: float | None,
|
||||
output_format: str | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
payload_messages: list[dict[str, str]] = []
|
||||
if system_prompt:
|
||||
payload_messages.append({"role": "system", "content": system_prompt})
|
||||
for m in messages:
|
||||
payload_messages.append({"role": m.role, "content": m.content})
|
||||
|
||||
body: dict[str, object] = {
|
||||
"model": self._model,
|
||||
"messages": payload_messages,
|
||||
"stream": True,
|
||||
}
|
||||
if temperature is not None:
|
||||
body["temperature"] = temperature
|
||||
# Mode JSON natif : TOUS les modèles Mistral le supportent → plus de fences
|
||||
# ```json ni de JSON invalide (retours à la ligne bruts dans les chaînes),
|
||||
# principale cause de morceaux d'import ignorés. Un SCHÉMA (dict) est
|
||||
# traduit en json_object : suffisant ici, les grands modèles cloud
|
||||
# respectent la structure demandée par le prompt.
|
||||
if output_format is not None:
|
||||
body["response_format"] = {"type": "json_object"}
|
||||
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
async with client.stream(
|
||||
"POST", _API_URL, headers=self._headers(), json=body
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
# En streaming le corps n'est pas lu automatiquement : on le
|
||||
# lit pour exposer le détail de Mistral (modèle inconnu, clé
|
||||
# invalide 401, quota 429…), sinon on n'a que le code HTTP nu.
|
||||
detail = (await response.aread()).decode("utf-8", "replace").strip()
|
||||
raise LLMProviderError(
|
||||
f"Erreur Mistral (HTTP {response.status_code})"
|
||||
+ (f" : {detail[:500]}" if detail else "")
|
||||
)
|
||||
async for token in self._parse_sse(response):
|
||||
yield token
|
||||
except httpx.HTTPError as exc:
|
||||
raise LLMProviderError(self._format_http_error(exc)) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
||||
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`."""
|
||||
async for line in response.aiter_lines():
|
||||
if not line or not line.startswith("data:"):
|
||||
continue # lignes vides ou keep-alive (`: ...`)
|
||||
data = line[len("data:"):].strip()
|
||||
if data == "[DONE]":
|
||||
return
|
||||
try:
|
||||
obj = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
choices = obj.get("choices")
|
||||
if not choices:
|
||||
continue
|
||||
delta = choices[0].get("delta") or {}
|
||||
content = delta.get("content")
|
||||
if content:
|
||||
yield content
|
||||
|
||||
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
||||
"""Message lisible (timeout, quota 429, clé invalide 401, modèle inconnu…)."""
|
||||
if isinstance(exc, httpx.TimeoutException):
|
||||
return (
|
||||
f"Erreur Mistral : délai dépassé (timeout {self._timeout}s). Le modèle a "
|
||||
"mis trop de temps — réduis la taille des morceaux d'import ou augmente le timeout."
|
||||
)
|
||||
detail = str(exc) or exc.__class__.__name__
|
||||
return f"Erreur Mistral ({exc.__class__.__name__}) : {detail}"
|
||||
def _first_token_timeout_message(self) -> str:
|
||||
return (
|
||||
f"Erreur Mistral : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s — le modèle est probablement "
|
||||
"en file d'attente (tier gratuit, 2 req/min). Réessayez plus tard ou "
|
||||
"choisissez un modèle plus disponible."
|
||||
)
|
||||
|
||||
@@ -16,6 +16,10 @@ from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Modèles dont Ollama a refusé le paramètre `think` (modèle sans mode « réflexion » sur une
|
||||
# version d'Ollama qui le signale par une erreur) : on ne le leur renvoie plus.
|
||||
_THINK_PARAM_REFUSED: set[str] = set()
|
||||
|
||||
|
||||
class OllamaLLMProvider:
|
||||
"""Implémentation des ports LLM — appelle un serveur Ollama via HTTP.
|
||||
@@ -64,20 +68,40 @@ class OllamaLLMProvider:
|
||||
# clés "thought" bavardes ou de texte hors JSON.
|
||||
if output_format is not None:
|
||||
payload["format"] = output_format
|
||||
# Réflexion COUPÉE pour ces appels uniques (relevés, découpages, traductions). Un
|
||||
# modèle à « réflexion » (qwen3.x…) rend sinon une réponse VIDE dès qu'un format
|
||||
# JSON est imposé — l'import concluait « aucune section exploitable » — et met plus
|
||||
# de deux fois plus de temps sur le reste (mesuré le 2026-11-13).
|
||||
if self._model not in _THINK_PARAM_REFUSED:
|
||||
payload["think"] = False
|
||||
|
||||
response = await self._post_generate(url, payload)
|
||||
if response.status_code == 400 and "think" in payload and "think" in response.text.lower():
|
||||
# Ce modèle n'a pas de mode « réflexion » et cette version d'Ollama refuse le
|
||||
# paramètre : on réessaie sans lui, et on s'en souvient.
|
||||
_THINK_PARAM_REFUSED.add(self._model)
|
||||
payload.pop("think")
|
||||
response = await self._post_generate(url, payload)
|
||||
if response.status_code >= 400:
|
||||
body = response.text
|
||||
try:
|
||||
err_obj = json.loads(body)
|
||||
err_msg = err_obj.get("error") or body
|
||||
except json.JSONDecodeError:
|
||||
err_msg = body
|
||||
raise LLMProviderError(
|
||||
f"Ollama HTTP {response.status_code} : {err_msg.strip()[:500]}"
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
return self._checked_response(data)
|
||||
|
||||
async def _post_generate(self, url: str, payload: dict[str, object]) -> httpx.Response:
|
||||
"""Envoie l'appel et rend la réponse HTTP telle quelle ; les pannes de transport
|
||||
deviennent des erreurs du domaine."""
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
response = await client.post(url, json=payload)
|
||||
if response.status_code >= 400:
|
||||
body = response.text
|
||||
try:
|
||||
err_obj = json.loads(body)
|
||||
err_msg = err_obj.get("error") or body
|
||||
except json.JSONDecodeError:
|
||||
err_msg = body
|
||||
raise LLMProviderError(
|
||||
f"Ollama HTTP {response.status_code} : {err_msg.strip()[:500]}"
|
||||
)
|
||||
return await client.post(url, json=payload)
|
||||
except httpx.ConnectTimeout as exc:
|
||||
# Serveur injoignable : erreur d'infrastructure, pas de lenteur.
|
||||
raise LLMProviderError(
|
||||
@@ -99,7 +123,8 @@ class OllamaLLMProvider:
|
||||
f"Erreur lors de l'appel à Ollama : {exc}"
|
||||
) from exc
|
||||
|
||||
data = response.json()
|
||||
def _checked_response(self, data: dict) -> str:
|
||||
"""Texte de la réponse, après le diagnostic d'une génération interrompue."""
|
||||
# Diagnostic crucial pour les imports : `done_reason` != "stop" signifie que
|
||||
# la génération a été INTERROMPUE (fenêtre de contexte pleine, num_predict…)
|
||||
# et non terminée par le modèle. Sans ce log, on ne voit qu'un JSON coupé
|
||||
|
||||
@@ -1,205 +1,57 @@
|
||||
"""Adapter OpenRouter — implémente les ports LLMProvider / LLMChatProvider.
|
||||
|
||||
OpenRouter expose l'API OpenAI standard (POST {base}/chat/completions, SSE), donc
|
||||
cet adapter est en réalité un client "OpenAI-compatible". Le `generate` one-shot
|
||||
passe lui aussi par le streaming (puis recollage) pour éviter les coupures de
|
||||
passerelle sur les longues générations (cf. 1min.ai / Cloudflare 524).
|
||||
cet adapter est un client "OpenAI-compatible" : il hérite de toute la mécanique de
|
||||
BaseOpenAICompatibleAdapter et ne fournit que ses spécificités (URL, en-têtes
|
||||
d'attribution, messages, lecture de config).
|
||||
|
||||
Modèles GRATUITS : utiliser un id finissant par `:free` (ex.
|
||||
`meta-llama/llama-3.3-70b-instruct:free`) ou le routeur `openrouter/free` (défaut)
|
||||
qui choisit automatiquement un modèle gratuit — aucun crédit consommé.
|
||||
|
||||
NB : on n'impose PAS `response_format=json_object` (`_supports_json_object=False`).
|
||||
Beaucoup de modèles/providers GRATUITS ne le supportent pas et renvoient une
|
||||
réponse VIDE. On laisse le modèle répondre librement ; l'extraction JSON en aval
|
||||
(load_json_object + nettoyage du raisonnement) récupère le JSON dans la prose.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.domain.models import ChatMessage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
_API_URL = "https://openrouter.ai/api/v1/chat/completions"
|
||||
|
||||
# Délai max pour le PREMIER token de contenu. Un modèle gratuit "en file d'attente"
|
||||
# n'envoie que des keep-alive (aucun contenu) → on échoue vite et clairement au lieu
|
||||
# de pendre. Généreux (2 min) car la file d'attente d'un tier gratuit peut être longue.
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
||||
from app.domain.ports import LLMProviderError
|
||||
from app.infrastructure.base_openai_adapter import (
|
||||
_FIRST_TOKEN_TIMEOUT_SECONDS,
|
||||
BaseOpenAICompatibleAdapter,
|
||||
)
|
||||
|
||||
|
||||
class OpenRouterLLMProvider:
|
||||
class OpenRouterLLMProvider(BaseOpenAICompatibleAdapter):
|
||||
"""Adapter OpenRouter (OpenAI-compatible) — satisfait LLMProvider et LLMChatProvider."""
|
||||
|
||||
_provider_label = "OpenRouter"
|
||||
_api_url = "https://openrouter.ai/api/v1/chat/completions"
|
||||
_supports_json_object = False
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
if not settings.openrouter_api_key:
|
||||
raise LLMProviderError(
|
||||
"Clé API OpenRouter manquante. Configure-la depuis l'écran Paramètres."
|
||||
)
|
||||
self._api_key = settings.openrouter_api_key
|
||||
self._model = settings.openrouter_model
|
||||
self._timeout = settings.llm_timeout_seconds
|
||||
super().__init__(
|
||||
settings.openrouter_api_key, settings.openrouter_model, settings.llm_timeout_seconds
|
||||
)
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self._api_key}",
|
||||
"Content-Type": "application/json",
|
||||
**super()._headers(),
|
||||
# Attribution facultative (classement OpenRouter) — sans impact fonctionnel.
|
||||
"HTTP-Referer": "https://loremind.app",
|
||||
"X-Title": "LoreMind",
|
||||
}
|
||||
|
||||
async def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
*,
|
||||
output_format: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> str:
|
||||
"""One-shot via streaming (puis recollage) pour robustesse sur longues sorties.
|
||||
|
||||
Timeout au TEMPS ÉCOULÉ (asyncio) en plus du timeout réseau d'httpx : un
|
||||
modèle gratuit saturé/en file d'attente envoie des keep-alive (`: OPENROUTER
|
||||
PROCESSING`) mais AUCUN contenu → httpx ne déclenche jamais son read-timeout
|
||||
(des octets arrivent) et l'appel pendrait à l'infini. Ici on coupe net après
|
||||
`self._timeout` secondes, quoi qu'il arrive.
|
||||
"""
|
||||
return await self._collect_with_timeouts(
|
||||
[ChatMessage(role="user", content=prompt)], temperature, output_format, "OpenRouter"
|
||||
def _first_token_timeout_message(self) -> str:
|
||||
return (
|
||||
f"Erreur OpenRouter : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s — le modèle gratuit est "
|
||||
"probablement en file d'attente / saturé. Réessayez plus tard ou "
|
||||
"choisissez un autre modèle (1min.ai, ou payant)."
|
||||
)
|
||||
|
||||
async def _collect_with_timeouts(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
temperature: float | None,
|
||||
output_format: str | None,
|
||||
provider: str,
|
||||
) -> str:
|
||||
"""Collecte le stream avec DEUX garde-fous au temps écoulé :
|
||||
- 1er token borné (`_FIRST_TOKEN_TIMEOUT_SECONDS`) : détecte un modèle bloqué
|
||||
en file d'attente (que des keep-alive, aucun contenu) → échec rapide ;
|
||||
- ceiling global (`self._timeout`) : génération qui ne se termine jamais.
|
||||
Le timeout réseau d'httpx ne suffit pas : des keep-alive font 'arriver des
|
||||
octets' et empêchent son read-timeout de se déclencher.
|
||||
"""
|
||||
async def _collect() -> str:
|
||||
chunks: list[str] = []
|
||||
agen = self._stream(messages, None, temperature, output_format)
|
||||
try:
|
||||
while True:
|
||||
# Borne SEULEMENT l'attente du 1er token (file d'attente) ; ensuite
|
||||
# on laisse générer (le ceiling global couvre le reste).
|
||||
first = _FIRST_TOKEN_TIMEOUT_SECONDS if not chunks else None
|
||||
try:
|
||||
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
raise LLMProviderError(
|
||||
f"Erreur {provider} : aucun contenu produit en "
|
||||
f"{int(_FIRST_TOKEN_TIMEOUT_SECONDS)}s — le modèle gratuit est "
|
||||
"probablement en file d'attente / saturé. Réessayez plus tard ou "
|
||||
"choisissez un autre modèle (1min.ai, ou payant)."
|
||||
)
|
||||
chunks.append(token)
|
||||
finally:
|
||||
await agen.aclose()
|
||||
return "".join(chunks)
|
||||
|
||||
try:
|
||||
return await asyncio.wait_for(_collect(), timeout=self._timeout)
|
||||
except asyncio.TimeoutError as exc:
|
||||
raise LLMGenerationTimeout(
|
||||
f"Erreur {provider} : génération non terminée en {self._timeout}s. Réduisez la "
|
||||
"taille des morceaux d'import, augmentez le timeout, ou changez de modèle."
|
||||
) from exc
|
||||
|
||||
async def stream_chat(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
*,
|
||||
system_prompt: str | None = None,
|
||||
temperature: float | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
async for token in self._stream(messages, system_prompt, temperature):
|
||||
yield token
|
||||
|
||||
async def _stream(
|
||||
self,
|
||||
messages: list[ChatMessage],
|
||||
system_prompt: str | None,
|
||||
temperature: float | None,
|
||||
output_format: str | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
payload_messages: list[dict[str, str]] = []
|
||||
if system_prompt:
|
||||
payload_messages.append({"role": "system", "content": system_prompt})
|
||||
for m in messages:
|
||||
payload_messages.append({"role": m.role, "content": m.content})
|
||||
|
||||
body: dict[str, object] = {
|
||||
"model": self._model,
|
||||
"messages": payload_messages,
|
||||
"stream": True,
|
||||
}
|
||||
if temperature is not None:
|
||||
body["temperature"] = temperature
|
||||
# NB : on n'impose PAS `response_format=json_object`. Beaucoup de modèles/
|
||||
# providers GRATUITS ne le supportent pas et renvoient une réponse VIDE.
|
||||
# On laisse le modèle répondre librement ; l'extraction JSON en aval
|
||||
# (load_json_object + nettoyage du raisonnement) récupère le JSON dans la prose.
|
||||
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
async with client.stream(
|
||||
"POST", _API_URL, headers=self._headers(), json=body
|
||||
) as response:
|
||||
if response.status_code >= 400:
|
||||
# En streaming, le corps n'est pas lu automatiquement : on le
|
||||
# lit pour exposer le détail d'OpenRouter (ex. le 429 précise
|
||||
# "free-models-per-day" vs "per-minute"), sinon on n'a que le
|
||||
# code HTTP nu et le diagnostic est impossible.
|
||||
detail = (await response.aread()).decode("utf-8", "replace").strip()
|
||||
raise LLMProviderError(
|
||||
f"Erreur OpenRouter (HTTP {response.status_code})"
|
||||
+ (f" : {detail[:500]}" if detail else "")
|
||||
)
|
||||
async for token in self._parse_sse(response):
|
||||
yield token
|
||||
except httpx.HTTPError as exc:
|
||||
raise LLMProviderError(self._format_http_error(exc)) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
||||
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`."""
|
||||
async for line in response.aiter_lines():
|
||||
if not line or not line.startswith("data:"):
|
||||
continue # lignes vides ou commentaires keep-alive (`: ...`)
|
||||
data = line[len("data:"):].strip()
|
||||
if data == "[DONE]":
|
||||
return
|
||||
try:
|
||||
obj = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
choices = obj.get("choices")
|
||||
if not choices:
|
||||
continue
|
||||
delta = choices[0].get("delta") or {}
|
||||
content = delta.get("content")
|
||||
if content:
|
||||
yield content
|
||||
|
||||
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
||||
"""Message lisible (timeout, quota 429, crédits 402, modèle inconnu…)."""
|
||||
if isinstance(exc, httpx.TimeoutException):
|
||||
return (
|
||||
f"Erreur OpenRouter : délai dépassé (timeout {self._timeout}s). Le modèle a "
|
||||
"mis trop de temps — réduis la taille des morceaux d'import ou augmente le timeout."
|
||||
)
|
||||
detail = str(exc) or exc.__class__.__name__
|
||||
return f"Erreur OpenRouter ({exc.__class__.__name__}) : {detail}"
|
||||
|
||||
@@ -17,13 +17,15 @@ et le diagnostic le signale (used_ocr reste False, texte vide).
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
import pymupdf as fitz # PyMuPDF — on importe par le nom canonique `pymupdf`
|
||||
# (et NON `import fitz`) pour éviter la collision avec le faux paquet PyPI "fitz"
|
||||
# qui échoue sur `from frontend import *`.
|
||||
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage, TocEntry
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage, TextLine, TocEntry
|
||||
from app.domain.ports import PdfExtractionError
|
||||
from app.infrastructure.pdf_layout import CELL_SEPARATOR, LayoutBlock, LayoutLine, place_lines, split_cells
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -41,6 +43,15 @@ _OCR_DPI = 300
|
||||
_OCR_LANGS = "fra+eng"
|
||||
|
||||
|
||||
# Caractères de contrôle laissés par certaines mises en page (tabulations, retours arrière…).
|
||||
_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]+")
|
||||
|
||||
|
||||
def _clean(text: str) -> str:
|
||||
"""Texte d'une ligne sans caractères de contrôle ni espaces en trop."""
|
||||
return " ".join(_CONTROL_CHARS.sub(" ", text).split())
|
||||
|
||||
|
||||
class PyMuPdfTextExtractor:
|
||||
"""Extracteur PDF basé sur PyMuPDF, avec repli OCR Tesseract optionnel."""
|
||||
|
||||
@@ -73,6 +84,7 @@ class PyMuPdfTextExtractor:
|
||||
|
||||
pages: list[ExtractedPage] = []
|
||||
toc: list[TocEntry] = []
|
||||
lines: list[TextLine] = []
|
||||
try:
|
||||
# Bookmarks/outline du PDF : structure officielle du livre, gratuite
|
||||
# (pas d'appel LLM). Sert de squelette de référence aux imports.
|
||||
@@ -93,10 +105,61 @@ class PyMuPdfTextExtractor:
|
||||
text = ocr_text.strip()
|
||||
used_ocr = True
|
||||
pages.append(ExtractedPage(index=index, text=text, used_ocr=used_ocr))
|
||||
lines.extend(self._ocr_lines(index, text) if used_ocr else self._page_lines(index, page))
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
return ExtractedDocument(pages=pages, toc=toc)
|
||||
return ExtractedDocument(pages=pages, toc=toc, lines=lines)
|
||||
|
||||
@staticmethod
|
||||
def _page_lines(index: int, page: "fitz.Page") -> list[TextLine]:
|
||||
"""Lignes d'une page à couche texte, avec leur taille de caractères dominante.
|
||||
|
||||
Best-effort : une page dont la mise en page ne se lit pas ne rend aucune ligne,
|
||||
sans faire échouer l'extraction."""
|
||||
out: list[TextLine] = []
|
||||
try:
|
||||
blocks = page.get_text("dict").get("blocks", [])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Lecture de la mise en page impossible (page %s) : %s", index + 1, exc)
|
||||
return out
|
||||
layout: list[LayoutBlock] = []
|
||||
for block in blocks:
|
||||
lines: list[LayoutLine] = []
|
||||
for line in block.get("lines", []):
|
||||
spans = [s for s in line.get("spans", []) if _clean(str(s.get("text", "")))]
|
||||
if not spans:
|
||||
continue
|
||||
dominant = max(spans, key=lambda s: len(s["text"]))
|
||||
# Arrondi au demi-point : deux lignes d'un même style ont la même taille.
|
||||
size = round(float(dominant.get("size", 0)) * 2) / 2
|
||||
x0, y0, x1, y1 = line.get("bbox", block.get("bbox", (0, 0, 0, 0)))
|
||||
# Un grand blanc dans la ligne sépare deux cellules d'un tableau.
|
||||
cells = split_cells(
|
||||
[(s["bbox"][0], s["bbox"][2], _CONTROL_CHARS.sub(" ", str(s.get("text", ""))).replace("|", "/"))
|
||||
for s in line["spans"] if "bbox" in s], size)
|
||||
if not cells:
|
||||
continue
|
||||
lines.append(LayoutLine(x0, y0, x1, y1, CELL_SEPARATOR.join(cells), size, len(cells)))
|
||||
if lines:
|
||||
bx0, by0, bx1, by1 = block.get("bbox", (0, 0, 0, 0))
|
||||
layout.append(LayoutBlock(bx0, by0, bx1, by1, lines))
|
||||
# Ordre de lecture par colonnes et rangées de tableau réunies : cf. pdf_layout.
|
||||
for placed in place_lines(layout, float(page.rect.width), float(page.rect.height)):
|
||||
out.append(TextLine(index, placed.block, placed.text, placed.size, placed.edge, placed.cells))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _ocr_lines(index: int, text: str) -> list[TextLine]:
|
||||
"""Lignes d'une page passée à l'OCR : taille inconnue (0), un bloc par paragraphe."""
|
||||
out: list[TextLine] = []
|
||||
block_no = 0
|
||||
for raw in text.split("\n"):
|
||||
if not raw.strip():
|
||||
block_no += 1
|
||||
continue
|
||||
out.append(TextLine(index, block_no, raw.strip(), 0.0))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _ocr_page(page: "fitz.Page") -> str:
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
"""Mise en page d'une page de PDF : ordre de lecture et rangées de tableau.
|
||||
|
||||
PyMuPDF rend les blocs de texte dans l'ordre où le PDF les dessine. C'est le plus souvent
|
||||
l'ordre de lecture, mais pas toujours : sur 27 % des pages d'un corpus de 150 livres de jeu de
|
||||
rôle (2026-11-13), au moins un bloc revient en arrière — pied de page dessiné avant le corps,
|
||||
ou colonnes dessinées dans le désordre (bas de la colonne droite, puis bas de la gauche, puis
|
||||
les hauts). Et les cellules d'un tableau sortent chacune sur sa ligne.
|
||||
|
||||
Ce module remet de l'ordre, sans rien changer au texte :
|
||||
1. les lignes placées à la même hauteur dans une même colonne sont les cellules d'une
|
||||
RANGÉE de tableau : elles sont réunies en une ligne, cellules séparées par CELL_SEPARATOR ;
|
||||
2. une page dont les blocs reviennent en arrière est relue colonne par colonne, de haut en
|
||||
bas, les blocs pleine largeur (titres, tableaux) séparant les bandes — seulement si ses
|
||||
colonnes sont nettes ; au moindre doute, elle garde l'ordre du PDF ;
|
||||
3. chaque ligne dit si elle est en HAUT ou en BAS de page (en-tête, pied, numéro de page).
|
||||
|
||||
Logique pure, sans PyMuPDF : elle ne voit que des boîtes et du texte.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
# Séparateur des cellules d'une rangée de tableau dans le texte d'une ligne.
|
||||
CELL_SEPARATOR = " | "
|
||||
# Hauteur (part de la page) des bandes d'en-tête et de pied de page.
|
||||
EDGE_BAND = 0.07
|
||||
# Marge latérale (part de la largeur) : une ligne qui y tient tout entière est un onglet de
|
||||
# chapitre ou un repère de maquette, pas du texte.
|
||||
SIDE_BAND = 0.05
|
||||
# Un bloc « pleine largeur » occupe au moins cette part de la largeur du texte de la page.
|
||||
WIDE_RATIO = 0.6
|
||||
# Un bloc de cette taille est un paragraphe : ce sont eux qui dessinent les colonnes.
|
||||
PARAGRAPH_CHARS = 150
|
||||
# Les blocs plus courts ne comptent pas pour juger du désordre d'une page.
|
||||
MIN_ORDER_CHARS = 40
|
||||
# Écart horizontal minimal (points) entre deux cellules d'une rangée.
|
||||
MIN_CELL_GAP = 3.0
|
||||
# Dans une ligne, un blanc d'au moins cette largeur sépare deux cellules : MIN_SPAN_GAP points,
|
||||
# ou SPAN_GAP_RATIO fois la taille des caractères (un espace entre deux mots en fait le quart).
|
||||
MIN_SPAN_GAP = 12.0
|
||||
SPAN_GAP_RATIO = 1.5
|
||||
# Un bloc appartient à une colonne s'il y tient presque entier et ne déborde guère sur une autre.
|
||||
COLUMN_FIT = 0.8
|
||||
COLUMN_SPILL = 0.1
|
||||
# Un blanc horizontal d'au moins cette part de la hauteur de page, commun à toutes les
|
||||
# colonnes, sépare deux bandes (l'espace entre deux paragraphes est bien plus petit).
|
||||
BAND_GAP = 0.03
|
||||
# Un « grand titre » : un bloc court dont les caractères font au moins cette fois la taille du
|
||||
# texte courant de la page.
|
||||
TITLE_RATIO = 1.5
|
||||
TITLE_CHARS = 80
|
||||
# Une ligne plus grosse que le texte courant dans ce rapport est un intertitre, pas une cellule :
|
||||
# deux intertitres à la même hauteur dans deux colonnes ne font pas une rangée de tableau.
|
||||
SUBTITLE_RATIO = 1.25
|
||||
# Deux rangées d'un même tableau se suivent de près (en tailles de caractères) et leurs
|
||||
# premières cellules sont alignées (en points).
|
||||
ROW_PITCH = 3.0
|
||||
ROW_ALIGN = 6.0
|
||||
# Blanc maximal (en tailles de caractères) entre deux cellules d'une rangée isolée.
|
||||
LONE_ROW_GAP = 5.0
|
||||
# Une page plus large que haute dans ce rapport est une double page : chaque moitié a ses titres.
|
||||
SPREAD_RATIO = 1.2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LayoutLine:
|
||||
x0: float
|
||||
y0: float
|
||||
x1: float
|
||||
y1: float
|
||||
text: str
|
||||
size: float
|
||||
# Nombre de cellules réunies dans cette ligne (1 = ligne ordinaire).
|
||||
cells: int = 1
|
||||
|
||||
|
||||
@dataclass(eq=False) # deux blocs de même contenu restent deux blocs : comparaison par identité
|
||||
class LayoutBlock:
|
||||
x0: float
|
||||
y0: float
|
||||
x1: float
|
||||
y1: float
|
||||
lines: list[LayoutLine] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def chars(self) -> int:
|
||||
return sum(len(line.text) for line in self.lines)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlacedLine:
|
||||
"""Une ligne dans l'ordre de lecture. `block` : rang de son bloc dans la page ; `cells` :
|
||||
nombre de cellules réunies (1 = ligne ordinaire) ; `edge` : en haut ou en bas de page."""
|
||||
|
||||
block: int
|
||||
text: str
|
||||
size: float
|
||||
edge: bool = False
|
||||
cells: int = 1
|
||||
|
||||
|
||||
def _is_edge(y0: float, y1: float, height: float) -> bool:
|
||||
return y1 <= EDGE_BAND * height or y0 >= (1 - EDGE_BAND) * height
|
||||
|
||||
|
||||
def _merge_intervals(intervals: list[tuple[float, float]]) -> list[tuple[float, float]]:
|
||||
"""Réunit les intervalles qui se recouvrent : chaque résultat est une colonne."""
|
||||
out: list[tuple[float, float]] = []
|
||||
for left, right in sorted(intervals):
|
||||
if out and left < out[-1][1] - 1:
|
||||
out[-1] = (out[-1][0], max(out[-1][1], right))
|
||||
else:
|
||||
out.append((left, right))
|
||||
return out
|
||||
|
||||
|
||||
def _columns(blocks: list[LayoutBlock], height: float) -> list[tuple[float, float]]:
|
||||
"""Colonnes de la page, dessinées par ses paragraphes. Vide : pas de colonne repérable."""
|
||||
return _merge_intervals([
|
||||
(b.x0, b.x1) for b in blocks
|
||||
if b.chars >= PARAGRAPH_CHARS and not _is_edge(b.y0, b.y1, height)
|
||||
])
|
||||
|
||||
|
||||
def _column_of(line: LayoutLine, columns: list[tuple[float, float]]) -> int:
|
||||
center = (line.x0 + line.x1) / 2
|
||||
for rank, (left, right) in enumerate(columns):
|
||||
if left - 2 <= center <= right + 2:
|
||||
return rank
|
||||
return -1
|
||||
|
||||
|
||||
def _gather_rows(blocks: list[LayoutBlock], height: float) -> list[LayoutBlock]:
|
||||
"""Réunit les cellules d'une même rangée : des lignes à la même hauteur, côte à côte dans
|
||||
la même colonne. La rangée prend la place de sa cellule de gauche ; les blocs vidés de
|
||||
leurs lignes disparaissent."""
|
||||
columns = _columns(blocks, height)
|
||||
body = _body_size(blocks)
|
||||
entries = [
|
||||
(b, i, line) for b, block in enumerate(blocks) for i, line in enumerate(block.lines)
|
||||
if not _is_edge(line.y0, line.y1, height)
|
||||
]
|
||||
# Rangées candidates : même colonne, bas de ligne à la même hauteur. Un seul balayage,
|
||||
# colonne par colonne et de haut en bas.
|
||||
# Un bloc d'une seule rangée (toutes ses lignes à la même hauteur) est une rangée ou une
|
||||
# cellule de tableau. Un bloc de plusieurs rangées est un paragraphe : ses lignes ne sont
|
||||
# jamais rapprochées de celles d'un autre bloc — un encadré voisin d'un tableau y laissait
|
||||
# des bouts de phrase.
|
||||
single_row = [
|
||||
max(line.y1 for line in block.lines) - min(line.y1 for line in block.lines)
|
||||
<= max(1.5, 0.3 * block.lines[0].size)
|
||||
for block in blocks
|
||||
]
|
||||
|
||||
def zone(block_rank: int, line: LayoutLine) -> int:
|
||||
"""Zone où chercher les cellules voisines : la colonne de la ligne si son bloc est une
|
||||
rangée, sinon son seul bloc (cellules d'un même bloc, tableau hors des colonnes)."""
|
||||
subtitle = body > 0 and line.size >= SUBTITLE_RATIO * body
|
||||
column = (_column_of(line, columns) if columns else 0) if single_row[block_rank] and not subtitle else -1
|
||||
return column if column != -1 else -(block_rank + 2)
|
||||
|
||||
keyed = sorted(((zone(b, line), line.y1, b, i, line) for b, i, line in entries), key=lambda e: (e[0], e[1]))
|
||||
groups: list[list[tuple[int, int, LayoutLine]]] = []
|
||||
current_zone, anchor = None, None
|
||||
for where, _, b, i, line in keyed:
|
||||
tolerance = max(1.5, 0.3 * line.size)
|
||||
same_row = (where == current_zone and anchor is not None
|
||||
and abs(anchor.y1 - line.y1) <= tolerance and abs(anchor.y0 - line.y0) <= tolerance * 2)
|
||||
if not same_row:
|
||||
groups.append([])
|
||||
current_zone, anchor = where, line
|
||||
groups[-1].append((b, i, line))
|
||||
|
||||
merged: dict[tuple[int, int], LayoutLine] = {} # (bloc, ligne) de gauche → rangée
|
||||
removed: set[tuple[int, int]] = set()
|
||||
widened: dict[int, float] = {}
|
||||
rows = [sorted(cells, key=lambda c: c[2].x0) for cells in groups if len(cells) >= 2]
|
||||
for cells in rows:
|
||||
if any(right[2].x0 < left[2].x1 + MIN_CELL_GAP for left, right in zip(cells, cells[1:])):
|
||||
continue # des lignes qui se chevauchent ne sont pas des cellules
|
||||
# Des lignes de blocs différents à la même hauteur sont une rangée si leurs cellules se
|
||||
# touchent presque, ou si le tableau continue. Éloignées et seules, ce sont deux bouts
|
||||
# de texte de deux colonnes (l'étiquette d'un sort à gauche, celle d'un autre à droite).
|
||||
if (len({b for b, _, _ in cells}) > 1 and not _close_cells(cells)
|
||||
and not any(_neighbour_rows(cells, other) for other in rows)):
|
||||
continue
|
||||
b, i, first = cells[0]
|
||||
texts = [c[2].text for c in cells]
|
||||
if len(cells) == 2 and len(texts[0]) <= 3 and all(c[2].cells == 1 for c in cells):
|
||||
# Une puce ou un numéro et son texte : une seule ligne ordinaire.
|
||||
text, count = f"{texts[0]} {texts[1]}", 1
|
||||
else:
|
||||
text, count = CELL_SEPARATOR.join(texts), sum(c[2].cells for c in cells)
|
||||
right = max(c[2].x1 for c in cells)
|
||||
merged[(b, i)] = LayoutLine(first.x0, min(c[2].y0 for c in cells), right,
|
||||
max(c[2].y1 for c in cells), text, first.size, count)
|
||||
widened[b] = max(widened.get(b, 0.0), right)
|
||||
removed.update((cb, ci) for cb, ci, _ in cells[1:])
|
||||
|
||||
out: list[LayoutBlock] = []
|
||||
for b, block in enumerate(blocks):
|
||||
lines = [merged.get((b, i), line) for i, line in enumerate(block.lines) if (b, i) not in removed]
|
||||
if lines:
|
||||
out.append(LayoutBlock(block.x0, block.y0, max(block.x1, widened.get(b, 0.0)), block.y1, lines))
|
||||
return out
|
||||
|
||||
|
||||
def _close_cells(row: list[tuple[int, int, LayoutLine]]) -> bool:
|
||||
"""Cellules assez proches pour former une rangée à elles seules (« 15-16 | Texte »)."""
|
||||
return all(right[2].x0 - left[2].x1 <= LONE_ROW_GAP * max(left[2].size, right[2].size)
|
||||
for left, right in zip(row, row[1:]))
|
||||
|
||||
|
||||
def _neighbour_rows(row: list[tuple[int, int, LayoutLine]], other: list[tuple[int, int, LayoutLine]]) -> bool:
|
||||
"""Deux rangées voisines d'un même tableau : l'une près de l'autre, leurs deux premières
|
||||
cellules alignées (à gauche, à droite ou au centre : une colonne de nombres s'aligne à droite).
|
||||
Le titre d'un sort et son coût, sur une ligne, ne font pas un tableau avec les étiquettes
|
||||
de niveau des colonnes voisines."""
|
||||
if row is other:
|
||||
return False
|
||||
first, second = row[0][2], other[0][2]
|
||||
if not 0 < abs(first.y0 - second.y0) <= ROW_PITCH * max(first.size, second.size):
|
||||
return False
|
||||
|
||||
def aligned(a: LayoutLine, b: LayoutLine) -> bool:
|
||||
return (abs(a.x0 - b.x0) <= ROW_ALIGN or abs(a.x1 - b.x1) <= ROW_ALIGN
|
||||
or abs((a.x0 + a.x1) - (b.x0 + b.x1)) <= 2 * ROW_ALIGN)
|
||||
|
||||
return all(aligned(mine[2], theirs[2]) for mine, theirs in zip(row[:2], other[:2]))
|
||||
|
||||
|
||||
def _goes_backward(blocks: list[LayoutBlock], width: float) -> bool:
|
||||
"""La suite de blocs revient-elle en arrière ? Même colonne et plus haut, ou plus à gauche
|
||||
et plus haut. Passer à la colonne suivante (à droite, plus haut) est l'ordre normal."""
|
||||
for before, after in zip(blocks, blocks[1:]):
|
||||
overlap = min(before.x1, after.x1) - max(before.x0, after.x0)
|
||||
same_column = overlap > 0.5 * min(before.x1 - before.x0, after.x1 - after.x0)
|
||||
above = after.y1 <= before.y0 + 2
|
||||
left = after.x1 <= before.x0 + 0.02 * width
|
||||
if above and (same_column or left):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _column_order(blocks: list[LayoutBlock], height: float) -> list[LayoutBlock] | None:
|
||||
"""Ordre de lecture d'une page aux colonnes NETTES : les blocs pleine largeur, de haut en
|
||||
bas, séparent des bandes lues colonne par colonne, chaque colonne de haut en bas.
|
||||
|
||||
Rend None dès que la page est ambiguë — pas de colonne dessinée par des paragraphes, ou un
|
||||
bloc à cheval sur deux colonnes, ou hors de toute colonne (encadré, note de marge, tableau
|
||||
posé ailleurs). Mieux vaut alors l'ordre du PDF qu'un ordre deviné : une double page à
|
||||
quatre colonnes, relue à tort, voyait ses colonnes entremêlées."""
|
||||
span = max(b.x1 for b in blocks) - min(b.x0 for b in blocks)
|
||||
wide = [b for b in blocks if b.x1 - b.x0 >= WIDE_RATIO * span]
|
||||
narrow = [b for b in blocks if b not in wide]
|
||||
columns = _merge_intervals([(b.x0, b.x1) for b in narrow if b.chars >= PARAGRAPH_CHARS])
|
||||
if not columns:
|
||||
return None
|
||||
by_column: list[list[LayoutBlock]] = [[] for _ in columns]
|
||||
for block in narrow:
|
||||
width = max(block.x1 - block.x0, 1.0)
|
||||
inside = [max(0.0, min(block.x1, right) - max(block.x0, left)) / width for left, right in columns]
|
||||
best = max(range(len(columns)), key=lambda rank: inside[rank])
|
||||
others = sum(inside) - inside[best]
|
||||
if inside[best] < COLUMN_FIT or others > COLUMN_SPILL:
|
||||
return None
|
||||
by_column[best].append(block)
|
||||
|
||||
def band(top: float, bottom: float) -> list[LayoutBlock]:
|
||||
out: list[LayoutBlock] = []
|
||||
for members in by_column:
|
||||
out += sorted((b for b in members if top <= (b.y0 + b.y1) / 2 < bottom), key=lambda b: (b.y0, b.x0))
|
||||
return out
|
||||
|
||||
# Les bandes sont séparées par les blocs pleine largeur, et par les grands blancs
|
||||
# horizontaux qui traversent toutes les colonnes : deux bandes de deux colonnes empilées
|
||||
# se lisent l'une après l'autre, pas colonne entière par colonne entière.
|
||||
cuts: list[tuple[float, LayoutBlock | None]] = [(b.y0, b) for b in wide]
|
||||
bottom = None
|
||||
for block in sorted(blocks, key=lambda b: b.y0):
|
||||
if bottom is not None and block.y0 - bottom >= BAND_GAP * height:
|
||||
cuts.append(((bottom + block.y0) / 2, None))
|
||||
bottom = block.y1 if bottom is None else max(bottom, block.y1)
|
||||
|
||||
ordered: list[LayoutBlock] = []
|
||||
cursor = float("-inf")
|
||||
for y, separator in sorted(cuts, key=lambda cut: cut[0]):
|
||||
ordered += band(cursor, y)
|
||||
if separator is not None:
|
||||
ordered.append(separator)
|
||||
cursor = y
|
||||
return ordered + band(cursor, float("inf"))
|
||||
|
||||
|
||||
def reading_order(blocks: list[LayoutBlock], width: float, height: float) -> list[LayoutBlock]:
|
||||
"""Blocs dans l'ordre de lecture. Une page que le PDF rend déjà dans l'ordre n'est pas
|
||||
touchée. Une page dont le CORPS revient en arrière est relue colonne par colonne — si ses
|
||||
colonnes sont nettes (cf. _column_order) ; sinon elle garde l'ordre du PDF."""
|
||||
body = [b for b in blocks if not _is_edge(b.y0, b.y1, height)]
|
||||
if len(body) < 2 or not _goes_backward([b for b in body if b.chars >= MIN_ORDER_CHARS], width):
|
||||
return blocks
|
||||
ordered = _column_order(body, height)
|
||||
if ordered is None:
|
||||
return blocks
|
||||
top = [b for b in blocks if b not in body and b.y1 <= EDGE_BAND * height]
|
||||
bottom = [b for b in blocks if b not in body and b not in top]
|
||||
return top + ordered + bottom
|
||||
|
||||
|
||||
def split_cells(spans: list[tuple[float, float, str]], size: float) -> list[str]:
|
||||
"""Cellules d'une ligne : ses morceaux de texte (x0, x1, texte), séparés là où un grand
|
||||
blanc les écarte — plus qu'un espace entre deux mots. Une ligne ordinaire rend une seule
|
||||
cellule, tout comme une puce ou un numéro suivi de son texte."""
|
||||
gap = max(MIN_SPAN_GAP, SPAN_GAP_RATIO * size)
|
||||
cells: list[list[str]] = []
|
||||
previous_right: float | None = None
|
||||
for x0, x1, text in spans:
|
||||
if previous_right is None or x0 - previous_right >= gap:
|
||||
cells.append([])
|
||||
cells[-1].append(text)
|
||||
previous_right = x1
|
||||
texts = [" ".join("".join(parts).split()) for parts in cells]
|
||||
texts = [t for t in texts if t]
|
||||
if len(texts) == 2 and len(texts[0]) <= 3:
|
||||
return [f"{texts[0]} {texts[1]}"]
|
||||
return texts
|
||||
|
||||
|
||||
def without_overprints(blocks: list[LayoutBlock]) -> list[LayoutBlock]:
|
||||
"""Retire les lignes dessinées deux fois au même endroit.
|
||||
|
||||
Pour épaissir un titre, certains PDF le dessinent deux fois, l'un sur l'autre : sans ce
|
||||
tri, le titre ressort doublé (« Notes Notes ») et ne correspond plus à la table des
|
||||
matières. Seule une ligne de même texte ET de même position est retirée."""
|
||||
seen: set[tuple[int, int, int, int, str]] = set()
|
||||
out: list[LayoutBlock] = []
|
||||
for block in blocks:
|
||||
kept: list[LayoutLine] = []
|
||||
for line in block.lines:
|
||||
key = (round(line.x0), round(line.y0), round(line.x1), round(line.y1), line.text)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
kept.append(line)
|
||||
if len(kept) == len(block.lines):
|
||||
out.append(block)
|
||||
elif kept:
|
||||
out.append(LayoutBlock(block.x0, block.y0, block.x1, block.y1, kept))
|
||||
return out
|
||||
|
||||
|
||||
def without_margin_tabs(blocks: list[LayoutBlock], width: float) -> list[LayoutBlock]:
|
||||
"""Retire les lignes qui tiennent tout entières dans la marge de gauche ou de droite.
|
||||
|
||||
Beaucoup de livres portent dans la marge un onglet au nom du chapitre (souvent écrit à la
|
||||
verticale) et son numéro : mêlés au texte, ils coupent les paragraphes de page en page."""
|
||||
if width <= 0:
|
||||
return blocks
|
||||
out: list[LayoutBlock] = []
|
||||
for block in blocks:
|
||||
kept = [line for line in block.lines
|
||||
if not (line.x1 <= SIDE_BAND * width or line.x0 >= (1 - SIDE_BAND) * width)]
|
||||
if len(kept) == len(block.lines):
|
||||
out.append(block)
|
||||
elif kept:
|
||||
out.append(LayoutBlock(block.x0, block.y0, block.x1, block.y1, kept))
|
||||
return out
|
||||
|
||||
|
||||
def _body_size(blocks: list[LayoutBlock]) -> float:
|
||||
"""Taille de caractères du texte courant : celle qui porte le plus de texte sur la page."""
|
||||
weight: dict[float, int] = {}
|
||||
for block in blocks:
|
||||
for line in block.lines:
|
||||
weight[line.size] = weight.get(line.size, 0) + len(line.text)
|
||||
return max(weight, key=lambda size: weight[size]) if weight else 0.0
|
||||
|
||||
|
||||
def hoist_titles(blocks: list[LayoutBlock], width: float, height: float) -> list[LayoutBlock]:
|
||||
"""Remet à sa place un grand titre dessiné après le texte qu'il coiffe.
|
||||
|
||||
Certains PDF tracent d'abord le contenu d'une page, puis ses grands titres par-dessus : lus
|
||||
dans cet ordre, le titre arrive après son texte, qui se retrouve rangé sous le titre
|
||||
précédent (les sorts nécrotiques sous « Radiant Spells »). Un grand titre remonte donc
|
||||
devant les blocs qui le précèdent dans le PDF alors qu'ils sont SOUS lui dans la page, à
|
||||
son aplomb. On s'arrête au premier bloc qui est au-dessus de lui, ou qui barre la page.
|
||||
Dans une double page, un titre ne sort pas de sa moitié."""
|
||||
body = _body_size(blocks)
|
||||
if not body or width <= 0:
|
||||
return blocks
|
||||
spread = width >= SPREAD_RATIO * height
|
||||
out = list(blocks)
|
||||
for title in blocks:
|
||||
if _is_edge(title.y0, title.y1, height) or title.chars > TITLE_CHARS or not title.lines \
|
||||
or min(line.size for line in title.lines) < TITLE_RATIO * body:
|
||||
continue
|
||||
low, high = 0.0, width
|
||||
if spread:
|
||||
low, high = (0.0, width / 2) if (title.x0 + title.x1) / 2 < width / 2 else (width / 2, width)
|
||||
zone = [title.x0, title.x1]
|
||||
position = next(i for i, block in enumerate(out) if block is title)
|
||||
target = None
|
||||
for index in range(position - 1, -1, -1):
|
||||
other = out[index]
|
||||
if _is_edge(other.y0, other.y1, height):
|
||||
continue
|
||||
if other.x1 - other.x0 >= WIDE_RATIO * (high - low):
|
||||
break # un bloc qui barre la page : une autre bande
|
||||
center = (other.x0 + other.x1) / 2
|
||||
if other.x1 <= zone[0] or other.x0 >= zone[1] or not low <= center <= high:
|
||||
continue # ailleurs dans la page
|
||||
# La boîte d'un gros titre déborde sous ses lettres : un bloc est « sous » le titre
|
||||
# dès qu'il commence sous son milieu.
|
||||
if other.y0 < (title.y0 + title.y1) / 2:
|
||||
break # au-dessus du titre : il est à sa place
|
||||
target = index
|
||||
zone = [max(low, min(zone[0], other.x0)), min(high, max(zone[1], other.x1))]
|
||||
if target is not None:
|
||||
out.insert(target, out.pop(position))
|
||||
return out
|
||||
|
||||
|
||||
def place_lines(blocks: list[LayoutBlock], width: float, height: float) -> list[PlacedLine]:
|
||||
"""Lignes d'une page dans l'ordre de lecture, rangées de tableau réunies."""
|
||||
blocks = without_overprints(without_margin_tabs([b for b in blocks if b.lines], width))
|
||||
if not blocks:
|
||||
return []
|
||||
ordered = hoist_titles(reading_order(_gather_rows(blocks, height), width, height), width, height)
|
||||
out: list[PlacedLine] = []
|
||||
for rank, block in enumerate(ordered):
|
||||
for line in block.lines:
|
||||
out.append(PlacedLine(rank, line.text, line.size, _is_edge(line.y0, line.y1, height), line.cells))
|
||||
return out
|
||||
+19
-1
@@ -9,7 +9,9 @@ import hmac
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exception_handlers import http_exception_handler
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.api.routers import (
|
||||
chat,
|
||||
@@ -18,7 +20,9 @@ from app.api.routers import (
|
||||
models,
|
||||
notebooks,
|
||||
settings as settings_router,
|
||||
spells,
|
||||
tables,
|
||||
training,
|
||||
)
|
||||
from app.core.config import get_settings
|
||||
from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_model
|
||||
@@ -26,7 +30,7 @@ from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_mo
|
||||
app = FastAPI(
|
||||
title="LoreMind Brain",
|
||||
description="Backend IA pour la génération de contenu narratif.",
|
||||
version="0.16.0",
|
||||
version="1.7.0-beta",
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -61,6 +65,18 @@ async def require_internal_secret(request: Request, call_next):
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def log_server_errors(request: Request, exc: StarletteHTTPException):
|
||||
"""Journalise les erreurs 5xx avec leur détail (message du fournisseur IA…).
|
||||
|
||||
Sans cela le journal ne garde que « 502 Bad Gateway » : la cause réelle n'est
|
||||
visible que dans la réponse, que le Core résume. La réponse est inchangée.
|
||||
"""
|
||||
if exc.status_code >= 500:
|
||||
logger.warning("%s %s -> HTTP %s : %s", request.method, request.url.path, exc.status_code, exc.detail)
|
||||
return await http_exception_handler(request, exc)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
"""Sonde de santé — permet au Core Java de vérifier que le Brain répond."""
|
||||
@@ -85,6 +101,8 @@ async def _auto_install_embedding_model() -> None:
|
||||
app.include_router(generation.router)
|
||||
app.include_router(chat.router)
|
||||
app.include_router(tables.router)
|
||||
app.include_router(training.router)
|
||||
app.include_router(spells.router)
|
||||
app.include_router(imports.router)
|
||||
app.include_router(notebooks.router)
|
||||
app.include_router(settings_router.router)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
[pytest]
|
||||
# Tests unitaires du brain. asyncio_mode=auto : les coroutines de test sont
|
||||
# exécutées sans décorateur @pytest.mark.asyncio explicite.
|
||||
asyncio_mode = auto
|
||||
# Ajoute la racine du brain au sys.path pour `import app...` sans installation.
|
||||
pythonpath = .
|
||||
testpaths = tests
|
||||
@@ -0,0 +1,11 @@
|
||||
# Dépendances de TEST uniquement (non embarquées dans l'image / le bundle desktop).
|
||||
# Installer avec : .venv/Scripts/python -m pip install -r requirements-dev.txt
|
||||
-r requirements.txt
|
||||
|
||||
pytest>=8,<9
|
||||
pytest-asyncio>=0.24,<1
|
||||
# Mock du transport httpx (intercepte les appels aux API LLM dans les tests).
|
||||
respx>=0.21,<1
|
||||
# Couverture de tests (équivalent JaCoCo) : `pytest --cov=app --cov-report=html`
|
||||
# → rapport HTML dans htmlcov/. La CI ajoute --cov-fail-under pour le plancher.
|
||||
pytest-cov>=5,<7
|
||||
+44
-2
@@ -13,15 +13,57 @@ On insere le dossier de CE fichier dans sys.path pour que le package `app`
|
||||
soit importable quel que soit le repertoire de travail (le Core fixe le cwd
|
||||
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
||||
"""
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, _HERE)
|
||||
|
||||
# Journal : le Core ecrit la sortie du Brain dans logs/brain.log. On la met en
|
||||
# UTF-8 (sinon les accents dependent de la page de code Windows) et on date les
|
||||
# journaux de l'application AVANT de l'importer : certains messages sont emis
|
||||
# des le chargement (ex. OCR indisponible). httpx reste discret : une ligne par
|
||||
# appel sortant n'apporte rien.
|
||||
for _stream in (sys.stdout, sys.stderr):
|
||||
if hasattr(_stream, "reconfigure"):
|
||||
_stream.reconfigure(encoding="utf-8", errors="replace")
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s : %(message)s")
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
|
||||
# OCR : si un Tesseract est bundlé à côté (mode desktop), on y pointe pytesseract
|
||||
# AVANT que l'app n'importe le pdf_extractor (qui détecte la version au chargement).
|
||||
# tessdata (fra+eng) est embarqué dans tesseract/tessdata. Sans ce bloc, l'OCR
|
||||
# reste désactivé en dégradation gracieuse (PDF born-digital OK, scans signalés).
|
||||
# Binaire selon l'OS : tesseract.exe (Windows embeddable) ou tesseract (Linux/Mac).
|
||||
# Si aucun Tesseract n'est bundlé (cas Linux/AppImage par défaut), le bloc est
|
||||
# sauté et pytesseract retombe sur le tesseract SYSTÈME du PATH (ex. apt install
|
||||
# tesseract-ocr) — sinon OCR désactivé en dégradation gracieuse.
|
||||
_TESS = os.path.join(_HERE, "tesseract", "tesseract.exe" if os.name == "nt" else "tesseract")
|
||||
if os.path.exists(_TESS):
|
||||
os.environ.setdefault("TESSDATA_PREFIX", os.path.join(_HERE, "tesseract"))
|
||||
try:
|
||||
import pytesseract
|
||||
pytesseract.pytesseract.tesseract_cmd = _TESS
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
import uvicorn # noqa: E402
|
||||
|
||||
from app.main import app # noqa: E402
|
||||
|
||||
|
||||
def _dated_log_config() -> dict:
|
||||
"""Journaux d'uvicorn (demarrage, requetes) dates eux aussi : une ligne sans
|
||||
date ne permet pas de retrouver une panne."""
|
||||
config = copy.deepcopy(uvicorn.config.LOGGING_CONFIG)
|
||||
config["formatters"]["default"]["fmt"] = "%(asctime)s %(levelprefix)s %(message)s"
|
||||
config["formatters"]["access"]["fmt"] = (
|
||||
'%(asctime)s %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s')
|
||||
return config
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# host 127.0.0.1 : accessible uniquement depuis le Core sur la meme machine.
|
||||
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
|
||||
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info", log_config=_dated_log_config())
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Tests du use case de conseils d'adaptation (app.application.adapt_campaign)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.adapt_campaign import AdaptCampaignUseCase
|
||||
from app.domain.models import ChatMessage, ExtractedDocument, ExtractedPage
|
||||
from app.domain.ports import PdfExtractionError
|
||||
|
||||
|
||||
class FakeExtractor:
|
||||
def __init__(self, doc: ExtractedDocument) -> None:
|
||||
self._doc = doc
|
||||
|
||||
def extract(self, pdf_bytes: bytes) -> ExtractedDocument:
|
||||
return self._doc
|
||||
|
||||
|
||||
class FakeChatLLM:
|
||||
def __init__(self, tokens: list[str]) -> None:
|
||||
self._tokens = tokens
|
||||
self.system_prompt: str | None = None
|
||||
self.messages: list[ChatMessage] | None = None
|
||||
|
||||
async def stream_chat(self, messages, *, system_prompt=None, temperature=None):
|
||||
self.messages = messages
|
||||
self.system_prompt = system_prompt
|
||||
for t in self._tokens:
|
||||
yield t
|
||||
|
||||
|
||||
def _doc(text: str) -> ExtractedDocument:
|
||||
return ExtractedDocument(pages=[ExtractedPage(index=0, text=text, used_ocr=False)])
|
||||
|
||||
|
||||
async def test_stream_yields_tokens_and_builds_context():
|
||||
llm = FakeChatLLM(["con", "seil"])
|
||||
uc = AdaptCampaignUseCase(llm, FakeExtractor(_doc("contenu du pdf")))
|
||||
out = [t async for t in uc.stream(b"x", "mon brief de campagne",
|
||||
[ChatMessage(role="user", content="aide")])]
|
||||
assert out == ["con", "seil"]
|
||||
assert "mon brief de campagne" in llm.system_prompt
|
||||
assert "contenu du pdf" in llm.system_prompt
|
||||
|
||||
|
||||
async def test_stream_empty_pdf_text_raises():
|
||||
uc = AdaptCampaignUseCase(FakeChatLLM([]), FakeExtractor(_doc(" ")))
|
||||
with pytest.raises(PdfExtractionError):
|
||||
[t async for t in uc.stream(b"x", "brief", [])]
|
||||
|
||||
|
||||
async def test_stream_injects_default_request_when_no_messages():
|
||||
llm = FakeChatLLM(["ok"])
|
||||
uc = AdaptCampaignUseCase(llm, FakeExtractor(_doc("texte du pdf")))
|
||||
_ = [t async for t in uc.stream(b"x", "", [])]
|
||||
assert llm.messages[0].role == "user"
|
||||
assert "campagne" in llm.messages[0].content.lower()
|
||||
|
||||
|
||||
def test_fit_pdf_short_text_not_truncated():
|
||||
uc = AdaptCampaignUseCase(None, None, max_input_tokens=10000)
|
||||
text, truncated = uc._fit_pdf_to_budget("court texte", "brief")
|
||||
assert truncated is False
|
||||
assert text == "court texte"
|
||||
|
||||
|
||||
def test_fit_pdf_long_text_is_truncated():
|
||||
uc = AdaptCampaignUseCase(None, None, max_input_tokens=2100)
|
||||
long_text = "mot " * 5000
|
||||
text, truncated = uc._fit_pdf_to_budget(long_text, "")
|
||||
assert truncated is True
|
||||
assert len(text) < len(long_text)
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Arbre d'un livre de campagne → arcs, aventures, scènes, salles, sans IA."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.campaign_structure import (
|
||||
all_scenes, campaign_from_outline, counts, is_skipped, lead, played_scenes,
|
||||
)
|
||||
from app.application.pdf_structure import BOOKMARKS, BookOutline, OutlineNode
|
||||
|
||||
LONG = "Texte d'introduction assez long pour faire une scène à lui seul. " * 4
|
||||
|
||||
|
||||
def node(title: str, text: str = "", *children: OutlineNode, level: int = 1) -> OutlineNode:
|
||||
return OutlineNode(title, level, 1, text, tuple(children))
|
||||
|
||||
|
||||
def outline(*nodes: OutlineNode) -> BookOutline:
|
||||
return BookOutline(BOOKMARKS, "", tuple(nodes))
|
||||
|
||||
|
||||
def _names(arcs: list[dict]) -> list[tuple[str, list[str]]]:
|
||||
return [(chapter["name"], [scene["name"] for scene in chapter["scenes"]])
|
||||
for arc in arcs for chapter in arc["chapters"]]
|
||||
|
||||
|
||||
def test_chapters_become_adventures_and_their_sections_scenes():
|
||||
arcs = campaign_from_outline(outline(
|
||||
node("The Adventure", "", node("A Bloodied History", LONG), node("The Old Watchtower", LONG)),
|
||||
node("Leaving the Vale", "", node("Closing Time!", LONG)),
|
||||
))
|
||||
assert [arc["name"] for arc in arcs] == ["Aventure principale"]
|
||||
assert _names(arcs) == [("The Adventure", ["A Bloodied History", "The Old Watchtower"]),
|
||||
("Leaving the Vale", ["Closing Time!"])]
|
||||
scene = arcs[0]["chapters"][0]["scenes"][0]
|
||||
# Le texte de la scène est celui du livre ; rien d'autre n'est écrit ici.
|
||||
assert scene["gm_notes"] == LONG.strip()
|
||||
assert scene["player_narration"] == "" and scene["rooms"] == []
|
||||
|
||||
|
||||
def test_the_fallback_synopsis_is_the_beginning_of_the_text():
|
||||
text = "### Un intertitre\n\nLe pont enjambe la rivière. Au-delà, la tour de guet tient encore debout. " + "Suite. " * 60
|
||||
arcs = campaign_from_outline(outline(node("Aventure", "", node("La tour", text), node("Autre", LONG))))
|
||||
assert arcs[0]["chapters"][0]["scenes"][0]["description"].startswith("Le pont enjambe la rivière.")
|
||||
assert len(arcs[0]["chapters"][0]["scenes"][0]["description"]) <= 241
|
||||
assert lead("") == "" and lead("| a | b |\n\n- puce") == ""
|
||||
|
||||
|
||||
def test_the_introduction_of_a_chapter_is_a_scene_of_its_own():
|
||||
arcs = campaign_from_outline(outline(node("Chapitre 1", LONG, node("La foire", LONG))),
|
||||
overview_title="Présentation")
|
||||
assert _names(arcs) == [("Chapitre 1", ["Présentation", "La foire"])]
|
||||
|
||||
|
||||
def test_a_short_introduction_opens_the_first_scene():
|
||||
arcs = campaign_from_outline(outline(node("Chapitre 1", "Quelques mots.", node("La foire", LONG), node("La nuit", LONG))))
|
||||
scenes = arcs[0]["chapters"][0]["scenes"]
|
||||
assert [s["name"] for s in scenes] == ["La foire", "La nuit"]
|
||||
assert scenes[0]["gm_notes"].startswith("Quelques mots.\n\n" + LONG.strip()[:20])
|
||||
|
||||
|
||||
def test_a_chapter_without_sections_is_one_scene():
|
||||
arcs = campaign_from_outline(outline(node("Épilogue", LONG), node("Prologue", LONG)))
|
||||
assert _names(arcs) == [("Épilogue", ["Épilogue"]), ("Prologue", ["Prologue"])]
|
||||
|
||||
|
||||
def test_numbered_places_are_the_rooms_of_one_scene():
|
||||
crypt = node("La crypte", "La crypte s'ouvre sous l'autel. " * 8,
|
||||
node("1. Entrée", "Une grille rouillée."), node("2. Salle des gardes", "Deux squelettes."),
|
||||
node("A3. Tombeau", "Le sarcophage du roi.", node("Trésor", "Une couronne.")),
|
||||
node("Suite de l'aventure", "Les héros ressortent."))
|
||||
arcs = campaign_from_outline(outline(node("Chapitre 1", "", crypt, node("Le village", LONG))))
|
||||
scene = arcs[0]["chapters"][0]["scenes"][0]
|
||||
assert scene["name"] == "La crypte"
|
||||
assert [room["name"] for room in scene["rooms"]] == ["1. Entrée", "2. Salle des gardes", "A3. Tombeau"]
|
||||
assert scene["rooms"][2]["description"] == "Le sarcophage du roi.\n\n### Trésor\n\nUne couronne."
|
||||
assert scene["rooms"][0]["enemies"] == "" and scene["rooms"][0]["loot"] == ""
|
||||
# Ce qui n'est pas un lieu numéroté reste dans le texte de la scène.
|
||||
assert "### Suite de l'aventure\n\nLes héros ressortent." in scene["gm_notes"]
|
||||
assert counts(arcs) == (1, 1, 2, 3)
|
||||
|
||||
|
||||
def test_a_dungeon_chapter_is_one_scene_with_its_rooms():
|
||||
arcs = campaign_from_outline(outline(
|
||||
node("Cragmaw Hideout", "Le repaire des gobelins.", node("Area 1: Cave Mouth", "Un ruisseau. " * 12),
|
||||
node("Area 2: Goblin Blind", "Deux gobelins. " * 12)),
|
||||
node("Phandalin", LONG)))
|
||||
scenes = arcs[0]["chapters"][0]["scenes"]
|
||||
assert [s["name"] for s in scenes] == ["Cragmaw Hideout"]
|
||||
assert len(scenes[0]["rooms"]) == 2 and scenes[0]["gm_notes"] == "Le repaire des gobelins."
|
||||
|
||||
|
||||
def test_numbered_places_may_carry_a_hyphen():
|
||||
temple = node("Elder Temple Map", LONG, node("T-10. Mole-man Lair", "Des hommes-taupes."),
|
||||
node("T-11. Main Temple Entrance", "Une double porte."), node("Concluding the Adventure", "Fin."))
|
||||
arcs = campaign_from_outline(outline(node("The Elder Temple", "", temple, node("The Road", LONG))))
|
||||
scene = arcs[0]["chapters"][0]["scenes"][0]
|
||||
assert [room["name"] for room in scene["rooms"]] == ["T-10. Mole-man Lair", "T-11. Main Temple Entrance"]
|
||||
assert "### Concluding the Adventure" in scene["gm_notes"]
|
||||
|
||||
|
||||
def test_a_dungeon_filed_under_a_region_keeps_its_rooms():
|
||||
"""Signets mal emboîtés : le donjon rangé parmi les lieux de la région qui y mène."""
|
||||
temple = node("Elder Temple Map", LONG, node("T-10. Mole-man Lair", "Des hommes-taupes."),
|
||||
node("T-11. Main Temple Entrance", "Une double porte."))
|
||||
region = node("The Elder Temple", "", node("W-3. Harkin's Ford", "Un gué."), node("W-4. Young Black Dragon", "Un dragon."),
|
||||
node("W-5. Bandit Camp", "Des bandits."), node("The Road Back", "Le retour."), temple)
|
||||
arcs = campaign_from_outline(outline(region, node("Appendix", LONG)))
|
||||
wilderness, dungeon = arcs[0]["chapters"][0]["scenes"]
|
||||
assert (wilderness["name"], len(wilderness["rooms"])) == ("The Elder Temple", 3)
|
||||
assert "### The Road Back" in wilderness["gm_notes"] and "Mole-man" not in wilderness["gm_notes"]
|
||||
assert dungeon["name"] == "Elder Temple Map"
|
||||
assert [room["name"] for room in dungeon["rooms"]] == ["T-10. Mole-man Lair", "T-11. Main Temple Entrance"]
|
||||
|
||||
|
||||
def test_a_section_that_is_too_long_is_given_by_its_subsections():
|
||||
big = "Un long passage. " * 600
|
||||
arcs = campaign_from_outline(outline(node("La vallée", "", node(
|
||||
"Le col", LONG, node("Le village (C)", big), node("La forêt (D)", big)), node("Fin", LONG))))
|
||||
assert _names(arcs)[0] == ("La vallée", ["Le col", "Le col › Le village (C)", "Le col › La forêt (D)", "Fin"])
|
||||
|
||||
|
||||
def test_a_short_section_keeps_its_subsections_as_subheadings():
|
||||
arcs = campaign_from_outline(outline(node("La vallée", "", node(
|
||||
"Le col", "Le col est gardé.", node("Le pont", "Un pont de corde.")), node("Fin", LONG))))
|
||||
assert arcs[0]["chapters"][0]["scenes"][0]["gm_notes"] == "Le col est gardé.\n\n### Le pont\n\nUn pont de corde."
|
||||
|
||||
|
||||
def test_parts_of_the_book_become_arcs():
|
||||
arcs = campaign_from_outline(outline(
|
||||
node("Introduction", LONG),
|
||||
node("Part 1: The Arrival", "", node("The Road", "", node("Ambush", LONG))),
|
||||
node("Part 2: To Hunt the Devil", LONG, node("The Cliffs", "", node("The Lair", LONG))),
|
||||
), overview_title="Overview")
|
||||
assert [arc["name"] for arc in arcs] == ["Introduction", "Part 1: The Arrival", "Part 2: To Hunt the Devil"]
|
||||
assert [c["name"] for c in arcs[1]["chapters"]] == ["The Road"]
|
||||
# Le texte d'introduction d'une partie fait une aventure de présentation.
|
||||
assert [c["name"] for c in arcs[2]["chapters"]] == ["Overview", "The Cliffs"]
|
||||
assert all(arc["type"] == "LINEAR" for arc in arcs)
|
||||
|
||||
|
||||
def test_one_part_alone_does_not_make_arcs():
|
||||
arcs = campaign_from_outline(outline(node("Part 1", "", node("Scène", LONG)), node("Épilogue", LONG)))
|
||||
assert [arc["name"] for arc in arcs] == ["Aventure principale"]
|
||||
|
||||
|
||||
def test_cover_credits_contents_and_legal_pages_are_left_out():
|
||||
arcs = campaign_from_outline(outline(
|
||||
node("Cover", LONG), node("Crédits", LONG), node("Table des matières", LONG),
|
||||
node("Hall of the Rainbow Mage Cover PDF 5e", "ISBN 978."), node("L'aventure", "", node("Scène", LONG)),
|
||||
node("Legal Appendix", LONG), node("Carte du donjon", "Légende."), node("Index", LONG)))
|
||||
assert _names(arcs) == [("L'aventure", ["Scène"])]
|
||||
assert is_skipped("Open Game License v1.0a") and is_skipped("livre.pdf") and not is_skipped("Introduction")
|
||||
assert is_skipped("Legal Aappendix") and not is_skipped("Legends of the Vale")
|
||||
|
||||
|
||||
def test_a_node_that_holds_the_whole_book_is_only_a_wrapper():
|
||||
"""Signets mal rangés : tout le livre sous un nom de fichier, ou sous « Crédits »."""
|
||||
book = node("Lost Crypt 5e PDF Download.pdf", "", node("Introduction", LONG),
|
||||
node("Crypt Entrance", LONG), node("The Lower Halls", LONG))
|
||||
arcs = campaign_from_outline(outline(node("Lost Crypt 5e PDF Cover", "Couverture."), book,
|
||||
node("Legal Appendix", LONG)))
|
||||
assert [name for name, _ in _names(arcs)] == ["Introduction", "Crypt Entrance", "The Lower Halls"]
|
||||
|
||||
under_credits = node("Crédits", "Auteurs : ...", node("Les secrets de Calice", LONG),
|
||||
node("La vallée des ours", LONG), node("Les marais", LONG))
|
||||
arcs = campaign_from_outline(outline(under_credits))
|
||||
assert [name for name, _ in _names(arcs)] == ["Les secrets de Calice", "La vallée des ours", "Les marais"]
|
||||
|
||||
|
||||
def test_appendices_go_to_an_arc_of_their_own_as_a_few_reading_scenes():
|
||||
creature = "Petite bête, non alignée. Classe d'armure 12. " * 6 # ≈ 280 caractères
|
||||
bestiary = node("Appendix II: Creatures", "", node("A", "", node("Animated Chain", creature),
|
||||
node("Demon Doll", creature)), node("B", "", node("Bat, Vampire", creature)))
|
||||
items = node("Appendix VI: New Magic Items", "Quelques objets.", node("Endless Rope", creature))
|
||||
arcs = campaign_from_outline(outline(node("Chapter 1", "", node("The Village", LONG)), bestiary, items),
|
||||
appendix_arc="Annexes")
|
||||
assert [(arc["name"], arc["type"]) for arc in arcs] == [("Aventure principale", "LINEAR"), ("Annexes", "HUB")]
|
||||
assert arcs[1]["reference"] is True and "reference" not in arcs[0]
|
||||
# Le bestiaire tient en une scène de lecture, pas une scène par créature.
|
||||
creatures, magic = arcs[1]["chapters"]
|
||||
assert [scene["name"] for scene in creatures["scenes"]] == ["A – B"]
|
||||
scene = creatures["scenes"][0]
|
||||
assert scene["description"] == "A, B"
|
||||
assert "### A\n\n#### Animated Chain\n\n" + creature.strip() in scene["gm_notes"]
|
||||
assert "#### Bat, Vampire" in scene["gm_notes"]
|
||||
# Une annexe d'une seule entrée garde son nom ; son court texte d'introduction l'ouvre.
|
||||
assert [scene["name"] for scene in magic["scenes"]] == ["Endless Rope"]
|
||||
assert magic["scenes"][0]["gm_notes"].startswith("Quelques objets.\n\n" + creature[:20])
|
||||
assert [scene["name"] for scene in played_scenes(arcs)] == ["The Village"]
|
||||
assert len(all_scenes(arcs)) == 3
|
||||
|
||||
|
||||
def test_a_long_appendix_is_cut_in_several_reading_scenes_in_the_order_of_the_book():
|
||||
entry = "Un profil de créature. " * 300 # ≈ 6 900 caractères
|
||||
bestiary = node("Bestiaire", LONG, *(node(f"Créature {i}", entry) for i in range(1, 6)))
|
||||
arcs = campaign_from_outline(outline(node("L'aventure", "", node("Scène", LONG)), bestiary))
|
||||
scenes = arcs[1]["chapters"][0]["scenes"]
|
||||
assert [scene["name"] for scene in scenes] == [
|
||||
"Présentation", "Créature 1 – Créature 2", "Créature 3 – Créature 4", "Créature 5"]
|
||||
assert scenes[1]["description"] == "Créature 1, Créature 2"
|
||||
|
||||
|
||||
def test_reference_titles_count_only_at_the_end_of_the_book():
|
||||
arcs = campaign_from_outline(outline(
|
||||
node("Monsters", "", node("The Lair", LONG)), node("The Road", LONG),
|
||||
node("NEW CREATURES", LONG), node("New Magic Items", LONG)))
|
||||
assert [arc["name"] for arc in arcs] == ["Aventure principale", "Annexes"]
|
||||
assert [chapter["name"] for chapter in arcs[0]["chapters"]] == ["Monsters", "The Road"]
|
||||
assert [chapter["name"] for chapter in arcs[1]["chapters"]] == ["NEW CREATURES", "New Magic Items"]
|
||||
|
||||
|
||||
def test_a_book_made_only_of_appendices_is_left_as_it_is():
|
||||
arcs = campaign_from_outline(outline(node("Appendix A", LONG), node("Bestiary", LONG)))
|
||||
assert [arc["name"] for arc in arcs] == ["Aventure principale"]
|
||||
assert played_scenes(arcs) == all_scenes(arcs)
|
||||
|
||||
|
||||
def test_two_scenes_with_the_same_name_are_told_apart():
|
||||
arcs = campaign_from_outline(outline(node("Chapitre", "", node("Rencontre", LONG), node("Rencontre", LONG))))
|
||||
assert _names(arcs) == [("Chapitre", ["Rencontre", "Rencontre (2)"])]
|
||||
|
||||
|
||||
def test_a_book_without_matter_gives_nothing():
|
||||
assert campaign_from_outline(outline(node("Cover", LONG), node("Index", LONG))) == []
|
||||
assert campaign_from_outline(BookOutline("none")) == []
|
||||
assert all_scenes([]) == []
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Tests de la construction du system prompt du chat (app.application.chat).
|
||||
|
||||
Assertions par INCLUSION (présence des données/sections clés) plutôt que sur le
|
||||
texte exact des consignes : robuste aux retouches de formulation, tout en
|
||||
vérifiant que chaque contexte est bien injecté.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.chat import ChatUseCase
|
||||
from app.domain.models import (
|
||||
ArcSummary,
|
||||
CampaignStructuralContext,
|
||||
ChapterSummary,
|
||||
CharacterSummary,
|
||||
ChatMessage,
|
||||
GameSystemContext,
|
||||
JournalEntrySummary,
|
||||
LoreStructuralContext,
|
||||
NarrativeEntityContext,
|
||||
NpcSummary,
|
||||
PageContext,
|
||||
PageSummary,
|
||||
SceneSummary,
|
||||
SessionContext,
|
||||
)
|
||||
|
||||
|
||||
def _build(**kw) -> str:
|
||||
return ChatUseCase(None).build_system_prompt(**kw)
|
||||
|
||||
|
||||
def _empty_lore() -> LoreStructuralContext:
|
||||
return LoreStructuralContext(lore_name="L", lore_description=None, folders={}, tags=[])
|
||||
|
||||
|
||||
def test_base_prompt_without_context_is_non_empty():
|
||||
assert len(_build()) > 0
|
||||
|
||||
|
||||
def test_lore_block_renders_pages_with_values_tags_and_links():
|
||||
lore = LoreStructuralContext(
|
||||
lore_name="Eldoria", lore_description="un monde sombre",
|
||||
folders={"PNJ": [PageSummary(
|
||||
title="Aragorn", template_name="Personnage",
|
||||
values={"apparence": "grand et noble"}, tags=["héros"],
|
||||
related_page_titles=["Gondor"])]},
|
||||
tags=["dark-fantasy"])
|
||||
p = _build(lore_context=lore)
|
||||
assert "Eldoria" in p
|
||||
assert "un monde sombre" in p
|
||||
assert "Aragorn" in p
|
||||
assert "apparence" in p and "grand et noble" in p
|
||||
assert "héros" in p
|
||||
assert "Gondor" in p
|
||||
|
||||
|
||||
def test_empty_lore_signals_vide():
|
||||
assert "Lore vide" in _build(lore_context=_empty_lore())
|
||||
|
||||
|
||||
def test_page_context_block_lists_fields_and_empty_marker():
|
||||
page = PageContext(title="Aragorn", template_name="Personnage",
|
||||
template_fields=["apparence", "histoire"],
|
||||
values={"apparence": "grand"})
|
||||
p = _build(page_context=page)
|
||||
assert "PAGE EN COURS" in p
|
||||
assert "Aragorn" in p
|
||||
assert "apparence" in p
|
||||
assert "(vide)" in p # 'histoire' sans valeur
|
||||
|
||||
|
||||
def test_campaign_block_with_arc_and_empty_pj_npc_and_no_lore_note():
|
||||
camp = CampaignStructuralContext(
|
||||
campaign_name="La Malédiction", campaign_description="horreur gothique",
|
||||
arcs=[ArcSummary(name="Acte I", description="intro",
|
||||
chapters=[ChapterSummary(name="Ch1", description="",
|
||||
scenes=[SceneSummary(name="Sc1", description="")])])],
|
||||
characters=[], npcs=[])
|
||||
p = _build(campaign_context=camp)
|
||||
assert "CAMPAGNE COURANTE" in p
|
||||
assert "La Malédiction" in p
|
||||
assert "Acte I" in p
|
||||
assert "aucune fiche" in p # pas de PJ
|
||||
assert "aucun univers" in p # pas de lore lié
|
||||
|
||||
|
||||
def test_campaign_with_characters_npcs_and_lore_present_note():
|
||||
camp = CampaignStructuralContext(
|
||||
campaign_name="C", campaign_description=None, arcs=[],
|
||||
characters=[CharacterSummary(name="Tav", snippet="roublarde")],
|
||||
npcs=[NpcSummary(name="Strahd", snippet="vampire de Barovia")])
|
||||
p = _build(campaign_context=camp, lore_context=_empty_lore())
|
||||
assert "Tav" in p and "roublarde" in p
|
||||
assert "Strahd" in p and "vampire de Barovia" in p
|
||||
assert "liée à l'univers" in p
|
||||
|
||||
|
||||
def test_game_system_narrative_and_session_sections_injected():
|
||||
gs = GameSystemContext(system_name="Nimble", system_description=None,
|
||||
sections={"Combat": "règles de combat"})
|
||||
narr = NarrativeEntityContext(entity_type="scene", title="L'auberge du Portail",
|
||||
fields={"ambiance": "tendue"})
|
||||
sess = SessionContext(
|
||||
session_name="Séance 3", active=True, started_at=None,
|
||||
entries=[JournalEntrySummary(type="EVENT", content="Le pont s'effondre", occurred_at=None)],
|
||||
previous_events=[])
|
||||
p = _build(lore_context=_empty_lore(), game_system_context=gs,
|
||||
narrative_entity=narr, session_context=sess)
|
||||
assert "Nimble" in p
|
||||
assert "L'auberge du Portail" in p
|
||||
assert "Séance 3" in p
|
||||
assert "Le pont s'effondre" in p
|
||||
|
||||
|
||||
async def test_stream_passes_built_prompt_to_llm():
|
||||
class FakeChatLLM:
|
||||
def __init__(self) -> None:
|
||||
self.system_prompt = None
|
||||
|
||||
async def stream_chat(self, messages, *, system_prompt=None, temperature=None):
|
||||
self.system_prompt = system_prompt
|
||||
yield "tok"
|
||||
|
||||
llm = FakeChatLLM()
|
||||
out = [t async for t in ChatUseCase(llm).stream(
|
||||
[ChatMessage(role="user", content="salut")],
|
||||
lore_context=LoreStructuralContext("Eldoria", None, {}, []))]
|
||||
assert out == ["tok"]
|
||||
assert "Eldoria" in llm.system_prompt
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Tests du découpage de texte (app.application.chunking).
|
||||
|
||||
Vérifie le découpage par paragraphes vers une cible de tokens, le découpage des
|
||||
paragraphes géants, le recouvrement (overlap), et le split_in_half du repli
|
||||
anti-troncature. tiktoken (cl100k_base) est déterministe → assertions stables.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.chunking import chunk_text, split_in_half
|
||||
|
||||
|
||||
def test_empty_text_returns_no_chunk():
|
||||
assert chunk_text("") == []
|
||||
assert chunk_text(" \n\n ") == []
|
||||
|
||||
|
||||
def test_short_text_stays_single_chunk():
|
||||
chunks = chunk_text("Paragraphe un.\n\nParagraphe deux.", target_tokens=1000)
|
||||
assert len(chunks) == 1
|
||||
assert "Paragraphe un." in chunks[0]
|
||||
assert "Paragraphe deux." in chunks[0]
|
||||
|
||||
|
||||
def test_splits_into_several_chunks_when_exceeding_target():
|
||||
paras = [f"Paragraphe numero {i} avec un peu de contenu." for i in range(20)]
|
||||
full = "\n\n".join(paras)
|
||||
chunks = chunk_text(full, target_tokens=20)
|
||||
assert len(chunks) > 1
|
||||
# Aucun paragraphe perdu : tous présents quelque part.
|
||||
joined = "\n\n".join(chunks)
|
||||
for p in paras:
|
||||
assert p in joined
|
||||
|
||||
|
||||
def test_oversized_single_paragraph_is_split():
|
||||
# Un seul paragraphe (aucun "\n\n") plus gros que la cible → plusieurs sous-blocs.
|
||||
huge = "mot " * 500
|
||||
chunks = chunk_text(huge, target_tokens=50)
|
||||
assert len(chunks) > 1
|
||||
|
||||
|
||||
def test_overlap_repeats_content_without_losing_paragraphs():
|
||||
paras = [f"Bloc {i} de texte distinct." for i in range(12)]
|
||||
full = "\n\n".join(paras)
|
||||
chunks = chunk_text(full, target_tokens=20, overlap_tokens=10)
|
||||
assert len(chunks) > 1
|
||||
joined = "\n\n".join(chunks)
|
||||
for p in paras:
|
||||
assert p in joined
|
||||
|
||||
|
||||
# --- split_in_half -------------------------------------------------------------
|
||||
|
||||
def test_split_in_half_too_short_returns_empty():
|
||||
assert split_in_half("court") == ("", "")
|
||||
|
||||
|
||||
def test_split_in_half_splits_on_newline_near_middle():
|
||||
text = "A" * 300 + "\n" + "B" * 300
|
||||
left, right = split_in_half(text)
|
||||
assert left and right
|
||||
assert left.startswith("A")
|
||||
assert right.startswith("B")
|
||||
|
||||
|
||||
def test_split_in_half_halves_cover_all_content():
|
||||
text = "\n".join(f"ligne {i} " + "x" * 20 for i in range(40))
|
||||
left, right = split_in_half(text)
|
||||
assert left and right
|
||||
# Le découpage ne perd rien : la concaténation contient début et fin.
|
||||
assert "ligne 0" in left
|
||||
assert "ligne 39" in right
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Tests des adapters d'embeddings (Mistral cloud + Ollama local)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
|
||||
from app.application.embeddings import EmbeddingError
|
||||
from app.core.config import Settings
|
||||
from app.infrastructure.mistral_embedding_adapter import MistralEmbeddingProvider
|
||||
from app.infrastructure.ollama_embedding_adapter import OllamaEmbeddingProvider
|
||||
|
||||
_MISTRAL = "https://api.mistral.ai/v1/embeddings"
|
||||
_OLLAMA = "http://ollama:11434/api/embed"
|
||||
|
||||
|
||||
def _settings(**kw) -> Settings:
|
||||
base = dict(_env_file=None, llm_timeout_seconds=30, ollama_base_url="http://ollama:11434")
|
||||
base.update(kw)
|
||||
return Settings(**base)
|
||||
|
||||
|
||||
# --- Mistral -------------------------------------------------------------------
|
||||
|
||||
def test_mistral_missing_key_raises_at_construction():
|
||||
with pytest.raises(EmbeddingError):
|
||||
MistralEmbeddingProvider(_settings(mistral_api_key=""))
|
||||
|
||||
|
||||
async def test_mistral_empty_texts_short_circuits():
|
||||
svc = MistralEmbeddingProvider(_settings(mistral_api_key="k"))
|
||||
assert await svc.embed([]) == []
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_mistral_returns_vectors():
|
||||
respx.post(_MISTRAL).mock(return_value=httpx.Response(200, json={
|
||||
"data": [{"embedding": [0.1, 0.2]}, {"embedding": [0.3, 0.4]}]
|
||||
}))
|
||||
svc = MistralEmbeddingProvider(_settings(mistral_api_key="k", mistral_embedding_model="mistral-embed"))
|
||||
vectors = await svc.embed(["texte un", "texte deux"])
|
||||
assert vectors == [[0.1, 0.2], [0.3, 0.4]]
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_mistral_http_error_raises():
|
||||
respx.post(_MISTRAL).mock(return_value=httpx.Response(429, text="rate limit"))
|
||||
svc = MistralEmbeddingProvider(_settings(mistral_api_key="k"))
|
||||
with pytest.raises(EmbeddingError) as exc:
|
||||
await svc.embed(["x"])
|
||||
assert "429" in str(exc.value)
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_mistral_size_mismatch_raises():
|
||||
respx.post(_MISTRAL).mock(return_value=httpx.Response(200, json={"data": [{"embedding": [0.1]}]}))
|
||||
svc = MistralEmbeddingProvider(_settings(mistral_api_key="k"))
|
||||
with pytest.raises(EmbeddingError):
|
||||
await svc.embed(["a", "b"]) # 2 demandés, 1 reçu
|
||||
|
||||
|
||||
# --- Ollama --------------------------------------------------------------------
|
||||
|
||||
async def test_ollama_empty_texts_short_circuits():
|
||||
svc = OllamaEmbeddingProvider(_settings(ollama_embedding_model="nomic-embed-text"))
|
||||
assert await svc.embed([]) == []
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_ollama_returns_vectors():
|
||||
respx.post(_OLLAMA).mock(return_value=httpx.Response(200, json={"embeddings": [[0.1], [0.2]]}))
|
||||
svc = OllamaEmbeddingProvider(_settings(ollama_embedding_model="mxbai-embed-large"))
|
||||
assert await svc.embed(["a", "b"]) == [[0.1], [0.2]]
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_ollama_applies_nomic_task_prefix():
|
||||
route = respx.post(_OLLAMA).mock(return_value=httpx.Response(200, json={"embeddings": [[0.0]]}))
|
||||
svc = OllamaEmbeddingProvider(_settings(ollama_embedding_model="nomic-embed-text"))
|
||||
await svc.embed(["question ?"], kind="query")
|
||||
sent = json.loads(route.calls.last.request.content)["input"]
|
||||
assert sent == ["search_query: question ?"]
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_ollama_no_prefix_for_non_nomic_model():
|
||||
route = respx.post(_OLLAMA).mock(return_value=httpx.Response(200, json={"embeddings": [[0.0]]}))
|
||||
svc = OllamaEmbeddingProvider(_settings(ollama_embedding_model="mxbai-embed-large"))
|
||||
await svc.embed(["doc"], kind="document")
|
||||
sent = json.loads(route.calls.last.request.content)["input"]
|
||||
assert sent == ["doc"]
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_ollama_http_error_mentions_pull_hint():
|
||||
respx.post(_OLLAMA).mock(return_value=httpx.Response(404, text="model not found"))
|
||||
svc = OllamaEmbeddingProvider(_settings(ollama_embedding_model="nomic-embed-text"))
|
||||
with pytest.raises(EmbeddingError) as exc:
|
||||
await svc.embed(["x"])
|
||||
assert "ollama pull" in str(exc.value)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Journal du Brain : une erreur 5xx renvoyée par une route y figure avec son détail.
|
||||
|
||||
En application de bureau, la sortie du Brain est écrite dans `logs/brain.log`. Sans ce
|
||||
détail, le journal ne garderait que « 502 Bad Gateway » et la cause (clé refusée, quota,
|
||||
modèle inconnu…) resterait introuvable.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.main import app
|
||||
|
||||
_SECRET = "secret-de-test"
|
||||
_BODY = {"method_name": "Donjon en 5 salles", "idea": "Une tour", "fields": [{"key": "name", "label": "Nom"}]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||
with TestClient(app) as test_client:
|
||||
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_a_5xx_error_is_logged_with_its_detail_and_still_returned(client, caplog):
|
||||
def failing_provider():
|
||||
raise HTTPException(status_code=502, detail="Erreur Mistral : clé refusée (401).")
|
||||
|
||||
app.dependency_overrides[get_llm_provider] = failing_provider
|
||||
with caplog.at_level(logging.WARNING, logger="app.main"):
|
||||
response = client.post("/generate/guided-answers", json=_BODY)
|
||||
|
||||
assert response.status_code == 502
|
||||
assert response.json() == {"detail": "Erreur Mistral : clé refusée (401)."}
|
||||
logged = [r.getMessage() for r in caplog.records if r.name == "app.main"]
|
||||
assert logged == ["POST /generate/guided-answers -> HTTP 502 : Erreur Mistral : clé refusée (401)."]
|
||||
|
||||
|
||||
def test_a_4xx_error_is_not_logged(client, caplog):
|
||||
def refusing_provider():
|
||||
raise HTTPException(status_code=422, detail="Demande invalide.")
|
||||
|
||||
app.dependency_overrides[get_llm_provider] = refusing_provider
|
||||
with caplog.at_level(logging.WARNING, logger="app.main"):
|
||||
response = client.post("/generate/guided-answers", json=_BODY)
|
||||
|
||||
assert response.status_code == 422
|
||||
assert [r for r in caplog.records if r.name == "app.main"] == []
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Tests du use case de génération de page (app.application.generate_page)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.generate_page import GeneratePageUseCase
|
||||
from app.domain.models import PageGenerationContext
|
||||
from app.domain.ports import LLMProviderError
|
||||
|
||||
_CTX = PageGenerationContext(
|
||||
lore_name="Eldoria",
|
||||
folder_name="PNJ",
|
||||
template_name="Personnage",
|
||||
template_fields=["apparence", "histoire"],
|
||||
page_title="Aragorn",
|
||||
lore_description="un monde sombre",
|
||||
)
|
||||
|
||||
|
||||
def test_build_prompt_includes_context_and_fields():
|
||||
p = GeneratePageUseCase._build_prompt(_CTX, "fr")
|
||||
assert "Eldoria" in p
|
||||
assert "Aragorn" in p
|
||||
assert '"apparence"' in p
|
||||
assert "un monde sombre" in p
|
||||
|
||||
|
||||
def test_build_prompt_omits_lore_description_when_absent():
|
||||
ctx = PageGenerationContext("L", "F", "T", ["a"], "Titre", None)
|
||||
assert "Description de l'univers" not in GeneratePageUseCase._build_prompt(ctx)
|
||||
|
||||
|
||||
def test_parse_values_keeps_only_expected_fields():
|
||||
out = GeneratePageUseCase._parse_values(
|
||||
'{"apparence":"grand","histoire":"longue","extra":"ignoré"}',
|
||||
["apparence", "histoire"])
|
||||
assert out == {"apparence": "grand", "histoire": "longue"}
|
||||
|
||||
|
||||
def test_parse_values_missing_field_becomes_empty_string():
|
||||
out = GeneratePageUseCase._parse_values('{"apparence":"grand"}', ["apparence", "histoire"])
|
||||
assert out == {"apparence": "grand", "histoire": ""}
|
||||
|
||||
|
||||
def test_parse_values_casts_to_str_and_strips():
|
||||
out = GeneratePageUseCase._parse_values('{"n": 42, "s": " x "}', ["n", "s"])
|
||||
assert out == {"n": "42", "s": "x"}
|
||||
|
||||
|
||||
def test_parse_values_bad_json_raises():
|
||||
with pytest.raises(LLMProviderError):
|
||||
GeneratePageUseCase._parse_values("pas du json", ["a"])
|
||||
|
||||
|
||||
def test_parse_values_non_object_raises():
|
||||
with pytest.raises(LLMProviderError):
|
||||
GeneratePageUseCase._parse_values("[1, 2]", ["a"])
|
||||
|
||||
|
||||
async def test_execute_returns_filtered_result():
|
||||
class FakeLLM:
|
||||
async def generate(self, prompt, *, output_format=None, temperature=None):
|
||||
return '{"apparence":"grand","histoire":"épique","parasite":"x"}'
|
||||
result = await GeneratePageUseCase(FakeLLM()).execute(_CTX)
|
||||
assert result.values == {"apparence": "grand", "histoire": "épique"}
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
|
||||
from app.application.prompts.guided_answers import guided_answers_prompt
|
||||
|
||||
|
||||
def _fields() -> dict[str, GuidedFieldDTO]:
|
||||
return {
|
||||
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
|
||||
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
|
||||
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
|
||||
}
|
||||
|
||||
|
||||
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
|
||||
prompt = guided_answers_prompt(
|
||||
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
|
||||
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
|
||||
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
|
||||
{"truth": "Le notaire est coupable", "empty": " "}, "en")
|
||||
|
||||
assert "Une tour qui se rallume" in prompt
|
||||
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
|
||||
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
|
||||
assert "Le notaire est coupable" in prompt
|
||||
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
|
||||
assert "Campagne : Valfroide" in prompt
|
||||
assert "anglais" in prompt
|
||||
|
||||
|
||||
def test_prompt_lists_the_method_steps_and_asks_to_follow_them():
|
||||
guide = ("Cinq temps dans un même lieu.\n\n"
|
||||
"- Salle 2 : l'épreuve : ici, l'épée ne suffit pas.\n"
|
||||
"- Salle 3 : le revers : les choses se compliquent.")
|
||||
p = guided_answers_prompt("Donjon en 5 salles", guide, "Une crypte", "", [{"key": "room2.name"}], {}, "fr")
|
||||
assert "telle que le MJ la suit à la main" in p
|
||||
assert "- Salle 2 : l'épreuve : ici, l'épée ne suffit pas." in p
|
||||
assert "rôle de SON étape" in p
|
||||
assert "Idée de départ du MJ : Une crypte" in p
|
||||
|
||||
|
||||
def test_prompt_without_idea_asks_for_an_original_adventure():
|
||||
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
|
||||
assert "propose une aventure originale" in prompt
|
||||
assert "français" in prompt
|
||||
|
||||
|
||||
def test_clean_keeps_requested_keys_and_valid_choices_only():
|
||||
out = _clean_guided_answers({
|
||||
"title": " L'héritage empoisonné ",
|
||||
"node1.nature": "npc",
|
||||
"unknown": "ignorée",
|
||||
"empty": "",
|
||||
}, _fields())
|
||||
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
|
||||
|
||||
|
||||
def test_clean_rejects_an_invalid_choice_and_non_text_values():
|
||||
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
|
||||
assert out == {}
|
||||
assert _clean_guided_answers("pas un objet", _fields()) == {}
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Tests des parseurs robustes des use cases d'import (méthodes statiques).
|
||||
|
||||
_parse_payload (campagne), _parse_sections / _parse_anchors (règles) : transforment
|
||||
la réponse brute du LLM en structure exploitable + un drapeau « tronqué » qui
|
||||
déclenche le re-découpage.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.import_campaign import ImportCampaignUseCase
|
||||
from app.application.import_rules import ImportRulesUseCase
|
||||
|
||||
_parse_payload = ImportCampaignUseCase._parse_payload
|
||||
_parse_sections = ImportRulesUseCase._parse_sections
|
||||
_parse_anchors = ImportRulesUseCase._parse_anchors
|
||||
|
||||
|
||||
# --- campagne : _parse_payload -------------------------------------------------
|
||||
|
||||
def test_parse_payload_valid():
|
||||
payload, truncated = _parse_payload('{"arcs":[{"name":"A"}],"npcs":[{"name":"N"}]}', index=0)
|
||||
assert truncated is False
|
||||
assert payload == {"arcs": [{"name": "A"}], "npcs": [{"name": "N"}]}
|
||||
|
||||
|
||||
def test_parse_payload_truncated_flags_recut():
|
||||
payload, truncated = _parse_payload('{"arcs":[{"name":"A"', index=0)
|
||||
assert truncated is True
|
||||
assert payload == {"arcs": [], "npcs": []}
|
||||
|
||||
|
||||
def test_parse_payload_prose_is_empty_not_truncated():
|
||||
payload, truncated = _parse_payload('juste de la prose sans json', index=0)
|
||||
assert truncated is False
|
||||
assert payload == {"arcs": [], "npcs": []}
|
||||
|
||||
|
||||
def test_parse_payload_recovers_truncated_array():
|
||||
raw = '{"arcs":[{"name":"A"},{"name":"B"},{"name":'
|
||||
payload, truncated = _parse_payload(raw, index=0)
|
||||
assert truncated is True
|
||||
assert payload == {"arcs": [{"name": "A"}, {"name": "B"}], "npcs": []}
|
||||
|
||||
|
||||
def test_parse_payload_coerces_non_list_fields():
|
||||
payload, _ = _parse_payload('{"arcs":"oops","npcs":null}', index=0)
|
||||
assert payload == {"arcs": [], "npcs": []}
|
||||
|
||||
|
||||
# --- règles : _parse_sections --------------------------------------------------
|
||||
|
||||
def test_parse_sections_valid_and_normalized():
|
||||
sections, truncated = _parse_sections('{"sections":{"Combat":"texte"}}', index=0)
|
||||
assert truncated is False
|
||||
assert sections == {"Combat": "texte"}
|
||||
|
||||
|
||||
def test_parse_sections_truncated():
|
||||
sections, truncated = _parse_sections('{"Combat":"texte non termin', index=0)
|
||||
assert truncated is True
|
||||
assert sections == {}
|
||||
|
||||
|
||||
def test_parse_sections_prose_is_empty():
|
||||
sections, truncated = _parse_sections('pas de json ici', index=0)
|
||||
assert truncated is False
|
||||
assert sections == {}
|
||||
|
||||
|
||||
# --- règles (mode segmentation) : _parse_anchors -------------------------------
|
||||
|
||||
def test_parse_anchors_locates_and_splits_text():
|
||||
text = "Préambule.\nLE COMBAT commence ici, brutal.\nLA MAGIE ensuite, subtile."
|
||||
raw = ('{"sections":[{"titre":"Combat","debut":"LE COMBAT commence"},'
|
||||
'{"titre":"Magie","debut":"LA MAGIE ensuite"}]}')
|
||||
sections, truncated = _parse_anchors(raw, text, index=0)
|
||||
assert truncated is False
|
||||
assert "Combat" in sections and "Magie" in sections
|
||||
# La 1re section absorbe le préambule (avant la 1re ancre).
|
||||
assert "Préambule." in sections["Combat"]
|
||||
assert "LE COMBAT commence ici, brutal." in sections["Combat"]
|
||||
assert "LA MAGIE ensuite, subtile." in sections["Magie"]
|
||||
|
||||
|
||||
def test_parse_anchors_unparseable_returns_empty():
|
||||
sections, truncated = _parse_anchors("pas du json", "texte", index=0)
|
||||
assert sections == {}
|
||||
assert truncated is False
|
||||
|
||||
|
||||
def test_parse_anchors_anchor_not_found_is_dropped():
|
||||
text = "Seulement ce paragraphe existe."
|
||||
raw = '{"sections":[{"titre":"Fantôme","debut":"ancre absente du texte"}]}'
|
||||
sections, _ = _parse_anchors(raw, text, index=0)
|
||||
# Aucune ancre localisée → aucune section.
|
||||
assert sections == {}
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Tests du canal de statut d'import (app.application.import_status)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from app.application import import_status
|
||||
|
||||
|
||||
def test_notify_is_noop_without_queue():
|
||||
# Hors import (aucune queue installée) : ne lève pas, ne fait rien.
|
||||
import_status.notify_status("personne n'écoute") # ne doit pas lever
|
||||
|
||||
|
||||
def test_notify_publishes_when_queue_installed():
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
token = import_status.set_status_queue(queue)
|
||||
try:
|
||||
import_status.notify_status("morceau re-découpé")
|
||||
assert queue.get_nowait() == "morceau re-découpé"
|
||||
finally:
|
||||
import_status.reset_status_queue(token)
|
||||
|
||||
|
||||
def test_reset_restores_noop():
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
token = import_status.set_status_queue(queue)
|
||||
import_status.reset_status_queue(token)
|
||||
# Après reset : plus de queue active → no-op, la queue reste vide.
|
||||
import_status.notify_status("ignoré")
|
||||
assert queue.empty()
|
||||
@@ -0,0 +1,827 @@
|
||||
"""Tests des use cases d'import via FAKES (ports LLM + extracteur PDF).
|
||||
|
||||
Exerce la chaîne map-reduce complète (extraction → chunking → MAP → REDUCE →
|
||||
streaming d'événements) SANS réseau ni vrai PDF. `chunk_text` est monkeypatché
|
||||
pour un découpage déterministe (le chunking est testé à part). `asyncio.sleep`
|
||||
est neutralisé pour que les backoffs de retry n'imposent aucune attente.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.import_campaign import ImportCampaignUseCase
|
||||
from app.application.import_rules import ImportRulesUseCase
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage
|
||||
from app.domain.ports import LLMProviderError
|
||||
|
||||
|
||||
# --- fakes ---------------------------------------------------------------------
|
||||
|
||||
class FakeExtractor:
|
||||
def __init__(self, doc: ExtractedDocument) -> None:
|
||||
self._doc = doc
|
||||
|
||||
def extract(self, pdf_bytes: bytes) -> ExtractedDocument:
|
||||
return self._doc
|
||||
|
||||
|
||||
class ScriptedLLM:
|
||||
"""Rejoue une réponse par appel (la dernière est répétée si on dépasse)."""
|
||||
|
||||
def __init__(self, responses: list) -> None:
|
||||
self._responses = list(responses)
|
||||
self.calls = 0
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
r = self._responses[min(self.calls, len(self._responses) - 1)]
|
||||
self.calls += 1
|
||||
if isinstance(r, Exception):
|
||||
raise r
|
||||
return r
|
||||
|
||||
|
||||
class ContentLLM:
|
||||
"""Répond selon le CONTENU du prompt (chunk) : (sous-chaîne → réponse/exception)."""
|
||||
|
||||
def __init__(self, rules: list) -> None:
|
||||
self._rules = rules
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
for sub, r in self._rules:
|
||||
if sub in prompt:
|
||||
if isinstance(r, Exception):
|
||||
raise r
|
||||
return r
|
||||
raise AssertionError(f"aucune règle ContentLLM ne matche : {prompt[:60]!r}")
|
||||
|
||||
|
||||
def _doc(text: str = "Texte du PDF.", *, ocr: bool = False) -> ExtractedDocument:
|
||||
return ExtractedDocument(pages=[ExtractedPage(index=0, text=text, used_ocr=ocr)])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_sleep(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("asyncio.sleep", _noop)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def one_chunk(monkeypatch):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["chunk"])
|
||||
monkeypatch.setattr("app.application.import_campaign.chunk_text", lambda *a, **k: ["chunk"])
|
||||
|
||||
|
||||
# --- import de règles ----------------------------------------------------------
|
||||
|
||||
async def test_rules_execute_returns_merged_sections(one_chunk):
|
||||
llm = ScriptedLLM(['{"Combat":"## Combat\\nrègles de combat"}'])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc(ocr=True)))
|
||||
result = await uc.execute(b"pdf")
|
||||
assert result.sections == {"Combat": "## Combat\nrègles de combat"}
|
||||
assert result.page_count == 1
|
||||
assert result.ocr_page_count == 1
|
||||
|
||||
|
||||
async def test_rules_stream_emits_extracting_start_progress_done(one_chunk):
|
||||
llm = ScriptedLLM(['{"Magie":"sorts"}'])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
types = [e["type"] for e in events]
|
||||
assert types[0] == "extracting"
|
||||
assert types[1] == "start"
|
||||
assert "progress" in types
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["sections"] == {"Magie": "sorts"}
|
||||
|
||||
|
||||
async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
types = [e["type"] for e in events]
|
||||
assert "chunk_failed" in types
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["sections"] == {"Magie": "sorts"}
|
||||
assert done["skipped"] == 1
|
||||
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
|
||||
assert done["source_language"] == "fr"
|
||||
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
|
||||
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
|
||||
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["source_language"] == "en"
|
||||
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
|
||||
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_rules_stream_hands_over_the_extraction_before_translating(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_doc())).stream(b"pdf")]
|
||||
types = [e["type"] for e in events]
|
||||
extracted = events[types.index("extracted")]
|
||||
assert extracted["sections"] == {"Magie": "sorts"}
|
||||
assert extracted["source_language"] == "fr"
|
||||
assert extracted["page_count"] == 1
|
||||
# L'extraction part avant le premier message de traduction.
|
||||
first_translation = next(i for i, e in enumerate(events)
|
||||
if e["type"] == "status" and "Traduction" in e["message"])
|
||||
assert types.index("extracted") < first_translation
|
||||
assert events[-1]["untranslated"] == []
|
||||
|
||||
|
||||
async def test_rules_stream_reports_the_sections_left_untranslated(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic", "Combat": "Fighting"}}'),
|
||||
("Extrait :\nles sorts", LLMProviderError("HTTP 503 saturé")),
|
||||
("Extrait :\nles coups", "blows"),
|
||||
("BBB second", '{"Magie":"les sorts","Combat":"les coups"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_doc())).stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["untranslated"] == ["Magie"]
|
||||
assert done["sections_by_language"]["en"] == {"Magie": "les sorts", "Fighting": "blows"}
|
||||
assert any(e["type"] == "status" and "incomplète" in e["message"] for e in events)
|
||||
|
||||
|
||||
def test_rules_translation_runs_one_at_a_time_on_a_local_model():
|
||||
local = ImportRulesUseCase(ScriptedLLM(["{}"]), FakeExtractor(_doc()), segment_only=True)
|
||||
remote = ImportRulesUseCase(ScriptedLLM(["{}"]), FakeExtractor(_doc()))
|
||||
assert local._translation_concurrency == 1
|
||||
assert remote._translation_concurrency > 1
|
||||
|
||||
|
||||
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||
llm = ScriptedLLM([LLMProviderError("HTTP 500 panne")])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
assert events[-1]["type"] == "error"
|
||||
assert "échoué" in events[-1]["message"]
|
||||
|
||||
|
||||
# --- import de campagne --------------------------------------------------------
|
||||
|
||||
_TREE = ('{"arcs":[{"name":"Acte I","description":"intro",'
|
||||
'"chapters":[{"name":"Ch1","scenes":[{"name":"Sc1"}]}]}],'
|
||||
'"npcs":[{"name":"Gandalf","description":"magicien"}]}')
|
||||
|
||||
|
||||
async def test_campaign_execute_builds_tree_and_npcs(one_chunk):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([_TREE]), FakeExtractor(_doc()))
|
||||
result = await uc.execute(b"pdf")
|
||||
assert result.counts() == (1, 1, 1)
|
||||
assert result.arcs[0].name == "Acte I"
|
||||
assert result.arcs[0].chapters[0].scenes[0].name == "Sc1"
|
||||
assert [n.name for n in result.npcs] == ["Gandalf"]
|
||||
|
||||
|
||||
async def test_campaign_stream_emits_done_with_serialized_tree(one_chunk):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([_TREE]), FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
types = [e["type"] for e in events]
|
||||
assert types[0] == "extracting"
|
||||
assert types[1] == "start"
|
||||
assert "progress" in types
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["arcs"][0]["name"] == "Acte I"
|
||||
assert done["arcs"][0]["chapters"][0]["scenes"][0]["name"] == "Sc1"
|
||||
assert done["npcs"] == [{"name": "Gandalf", "description": "magicien"}]
|
||||
|
||||
|
||||
async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
assert events[-1]["type"] == "error"
|
||||
|
||||
|
||||
class _RecordingLLM(ScriptedLLM):
|
||||
"""ScriptedLLM qui garde les prompts reçus."""
|
||||
|
||||
def __init__(self, responses: list) -> None:
|
||||
super().__init__(responses)
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
return await super().generate(prompt, output_format=output_format, temperature=temperature)
|
||||
|
||||
|
||||
async def test_campaign_import_writes_in_the_interface_language_and_keeps_names():
|
||||
llm = _RecordingLLM([_TREE])
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf", language="en")]
|
||||
assert events[-1]["type"] == "done"
|
||||
prompt = llm.prompts[0]
|
||||
assert "LANGUE DE SORTIE" in prompt
|
||||
assert "en anglais" in prompt
|
||||
assert "noms propres" in prompt
|
||||
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
|
||||
|
||||
|
||||
async def test_campaign_import_defaults_to_french():
|
||||
llm = _RecordingLLM([_TREE])
|
||||
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||
assert "en français" in llm.prompts[0]
|
||||
assert '"Aventure principale"' in llm.prompts[0]
|
||||
|
||||
|
||||
# --- mode segmentation (modèle local) : le texte n'est jamais perdu -------------------------
|
||||
|
||||
def _anchors(*pairs) -> str:
|
||||
import json as _json
|
||||
return _json.dumps({"sections": [{"titre": t, "debut": d} for t, d in pairs]})
|
||||
|
||||
|
||||
async def test_local_import_keeps_the_text_of_a_chunk_the_model_could_not_split(monkeypatch, no_sleep):
|
||||
"""Un petit modèle rend parfois des repères introuvables : 1 morceau sur 15 disparaissait."""
|
||||
chunks = ["AAA le combat se joue en tours.", "BBB suite du combat, sans repère.", "CCC la magie coûte du mana."]
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: chunks)
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA le combat", _anchors(("Combat", "AAA le combat"))),
|
||||
("BBB suite", _anchors(("Combat", "un début qui n'est pas dans le texte"))),
|
||||
("CCC la magie", _anchors(("Magie", "CCC la magie"))),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
# Le morceau sans repère suit la section précédente : rien n'est perdu.
|
||||
assert extracted["sections"] == {
|
||||
"Combat": "AAA le combat se joue en tours.\n\nBBB suite du combat, sans repère.",
|
||||
"Magie": "CCC la magie coûte du mana.",
|
||||
}
|
||||
assert sum(len(c) for c in extracted["sections"].values()) >= sum(len(c) for c in chunks)
|
||||
assert any(e["type"] == "status" and "gardé" in e["message"] for e in events)
|
||||
assert extracted["skipped"] == 0
|
||||
|
||||
|
||||
async def test_local_import_puts_an_unsplit_first_chunk_under_the_general_rules(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA préambule illisible pour le modèle.", "BBB le combat."])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA préambule", "je ne sais pas"), # pas de JSON du tout
|
||||
("BBB le combat", _anchors(("Combat", "BBB le combat"))),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
result = await uc.execute(b"pdf")
|
||||
assert result.sections == {"Règles générales": "AAA préambule illisible pour le modèle.",
|
||||
"Combat": "BBB le combat."}
|
||||
|
||||
|
||||
async def test_local_import_keeps_the_text_of_a_chunk_whose_call_failed(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA le combat.", "BBB la suite."])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA le combat", _anchors(("Combat", "AAA le combat"))),
|
||||
("BBB la suite", LLMProviderError("Ollama HTTP 500 : prediction aborted")),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["sections"] == {"Combat": "AAA le combat.\n\nBBB la suite."}
|
||||
# L'échec reste signalé : le MJ sait qu'un morceau n'a pas été découpé.
|
||||
assert any(e["type"] == "chunk_failed" for e in events)
|
||||
assert extracted["skipped"] == 1
|
||||
|
||||
|
||||
async def test_local_import_still_fails_when_every_call_fails(one_chunk, no_sleep):
|
||||
llm = ScriptedLLM([LLMProviderError("Ollama injoignable")])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
assert events[-1]["type"] == "error"
|
||||
assert all(e["type"] != "extracted" for e in events)
|
||||
|
||||
|
||||
async def test_cloud_import_does_not_keep_the_raw_text_of_a_failed_chunk(monkeypatch, no_sleep):
|
||||
"""Hors segmentation, le texte brut du PDF n'est pas une section : comportement inchangé."""
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_doc())).stream(b"pdf")]
|
||||
assert next(e for e in events if e["type"] == "extracted")["sections"] == {"Magie": "sorts"}
|
||||
|
||||
|
||||
def test_combining_the_two_halves_keeps_unsplit_text_after_what_precedes_it():
|
||||
from app.application.import_rules import UNSORTED, _combine_sections, _SectionMerger
|
||||
combined = _combine_sections({"Combat": "a"}, {UNSORTED: "b", "Magie": "c"})
|
||||
assert combined == {"Combat": "a\n\nb", "Magie": "c"}
|
||||
merger = _SectionMerger()
|
||||
merger.add({"Combat": "a"})
|
||||
assert merger.add({UNSORTED: "suite"}) == ["Combat"]
|
||||
assert merger.result() == {"Combat": "a\n\nsuite"}
|
||||
|
||||
|
||||
# --- découpage par la structure du PDF, sans IA ---------------------------------------------
|
||||
|
||||
def _structured_doc():
|
||||
"""Livre de 3 pages : signets et gros titres, comme un PDF d'éditeur."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
lines, toc = [], []
|
||||
for page, (title, text) in enumerate([("Combat", "Each round, you roll the dice and the heroes act."),
|
||||
("Magic", "Casting a spell costs mana for the caster."),
|
||||
("Rest", "A night of rest restores all the wounds.")]):
|
||||
lines += [TextLine(page, 0, title, 24.0), TextLine(page, 1, text, 10.0)]
|
||||
toc.append(TocEntry(level=1, title=title, page=page + 1))
|
||||
pages = [ExtractedPage(index=p, text=f"{lines[2 * p].text}\n{lines[2 * p + 1].text}", used_ocr=False)
|
||||
for p in range(3)]
|
||||
return ExtractedDocument(pages=pages, toc=toc, lines=lines)
|
||||
|
||||
|
||||
class CountingLLM(ContentLLM):
|
||||
def __init__(self, rules: list) -> None:
|
||||
super().__init__(rules)
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
return await super().generate(prompt, output_format=output_format, temperature=temperature)
|
||||
|
||||
|
||||
async def test_local_import_follows_the_structure_of_the_pdf_without_the_ai(no_sleep):
|
||||
llm = CountingLLM([("Traduis ces titres", LLMProviderError("pas de traduction dans ce test"))])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_structured_doc()), segment_only=True, structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["split_method"] == "bookmarks"
|
||||
assert extracted["sections"] == {
|
||||
"Combat": "Each round, you roll the dice and the heroes act.",
|
||||
"Magic": "Casting a spell costs mana for the caster.",
|
||||
"Rest": "A night of rest restores all the wounds.",
|
||||
}
|
||||
assert extracted["source_language"] == "en"
|
||||
# Aucun appel à l'IA pour découper : le seul prompt envoyé est celui de la traduction.
|
||||
assert all("Traduis" in prompt for prompt in llm.prompts)
|
||||
assert any(e["type"] == "status" and "table des matières du PDF" in e["message"]
|
||||
and "sans IA" in e["message"] for e in events)
|
||||
progress = next(e for e in events if e["type"] == "progress")
|
||||
assert progress["new_sections"] == ["Combat", "Magic", "Rest"]
|
||||
assert events[-1]["type"] == "done" and events[-1]["split_method"] == "bookmarks"
|
||||
|
||||
|
||||
async def test_local_import_falls_back_on_the_ai_when_the_pdf_has_no_structure(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["AAA le combat."])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA le combat", _anchors(("Combat", "AAA le combat"))),
|
||||
])
|
||||
# Document sans lignes ni signets (scan, ou extracteur qui ne les fournit pas).
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True, structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["split_method"] == "ai"
|
||||
assert extracted["sections"] == {"Combat": "AAA le combat."}
|
||||
|
||||
|
||||
async def test_cloud_import_does_not_use_the_structure_unless_asked(one_chunk, no_sleep):
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("chunk", '{"Combat":"réécrit par le modèle"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_structured_doc())).stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["split_method"] == "ai"
|
||||
assert extracted["sections"] == {"Combat": "réécrit par le modèle"}
|
||||
|
||||
|
||||
async def test_execute_follows_the_structure_too(no_sleep):
|
||||
llm = ContentLLM([("Traduis ces titres", LLMProviderError("pas de traduction dans ce test"))])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_structured_doc()), segment_only=True, structure_first=True)
|
||||
result = await uc.execute(b"pdf")
|
||||
assert list(result.sections) == ["Combat", "Magic", "Rest"]
|
||||
|
||||
|
||||
async def test_local_import_by_structure_survives_a_slow_translation(no_sleep):
|
||||
"""Un signal de vie émis pendant la traduction faisait planter le chemin sans IA."""
|
||||
import asyncio
|
||||
|
||||
class SlowTitles:
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
if "Traduis ces titres" in prompt:
|
||||
await asyncio.Event().wait() # ne répond jamais : seuls des signaux de vie partent
|
||||
return "traduit"
|
||||
|
||||
uc = ImportRulesUseCase(SlowTitles(), FakeExtractor(_structured_doc()), segment_only=True, structure_first=True)
|
||||
uc._heartbeat_seconds = 0.01
|
||||
seen: list[str] = []
|
||||
stream = uc.stream(b"pdf")
|
||||
async for event in stream:
|
||||
seen.append(event["type"])
|
||||
if seen.count("heartbeat") >= 2:
|
||||
break
|
||||
await stream.aclose()
|
||||
assert "extracted" in seen and seen.count("heartbeat") >= 2
|
||||
|
||||
|
||||
def test_no_provider_ever_rewrites_the_text_of_the_book():
|
||||
"""Les règles doivent correspondre au PDF : structure d'abord, sinon l'IA ne fait que
|
||||
repérer les frontières — en local comme avec un fournisseur cloud."""
|
||||
from app.api.deps import get_import_rules_use_case
|
||||
from app.core.config import Settings
|
||||
|
||||
for provider in ("ollama", "mistral", "gemini", "openrouter"):
|
||||
settings = Settings(_env_file=None, llm_provider=provider)
|
||||
uc = get_import_rules_use_case(ScriptedLLM(["{}"]), settings)
|
||||
assert uc._structure_first is True
|
||||
assert uc._segment_only is True
|
||||
|
||||
|
||||
|
||||
# --- import de campagne par la structure du livre ---------------------------------------------
|
||||
|
||||
def _campaign_doc(language: str = "fr"):
|
||||
"""Petit livre de campagne : 2 aventures, 3 scènes, signets et gros titres."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
if language == "fr":
|
||||
book = [("L'aventure", [("La foire", "Le marchand Aldric vend des reliques volées dans la foire du village. " * 4),
|
||||
("La crypte", "Sous l'autel, la crypte abrite le spectre de Dame Ysolde et ses gardes. " * 4)]),
|
||||
("Épilogue", [("Le retour", "Les héros rentrent au village avec la relique et le maire les récompense. " * 4)])]
|
||||
else:
|
||||
book = [("The Adventure", [("The Fair", "The merchant Aldric sells stolen relics at the fair of the village for you. " * 4),
|
||||
("The Crypt", "Under the altar, the crypt is the home of the ghost of Lady Ysolde and of the guards. " * 4)]),
|
||||
("Epilogue", [("The Return", "The heroes are back in the village with the relic and the mayor rewards you. " * 4)])]
|
||||
lines, toc, pages = [], [], []
|
||||
for page, (chapter, scenes) in enumerate(book):
|
||||
toc.append(TocEntry(level=1, title=chapter, page=page + 1))
|
||||
lines.append(TextLine(page, 0, chapter, 24.0))
|
||||
for block, (title, text) in enumerate(scenes, start=1):
|
||||
toc.append(TocEntry(level=2, title=title, page=page + 1))
|
||||
lines += [TextLine(page, 2 * block, title, 16.0), TextLine(page, 2 * block + 1, text.strip(), 10.0)]
|
||||
pages.append(ExtractedPage(index=page, text="texte", used_ocr=False))
|
||||
return ExtractedDocument(pages=pages, toc=toc, lines=lines)
|
||||
|
||||
|
||||
class AidsLLM:
|
||||
"""Répond aux demandes d'aides et de traduction ; garde les prompts reçus."""
|
||||
|
||||
def __init__(self, aids: object, translate=str.upper) -> None:
|
||||
self._aids = aids
|
||||
self._translate = translate
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
if "SYNOPSIS" in prompt:
|
||||
if isinstance(self._aids, Exception):
|
||||
raise self._aids
|
||||
return self._aids
|
||||
if "Traduis cet extrait" in prompt:
|
||||
if self._translate is None:
|
||||
raise LLMProviderError("HTTP 503 saturé")
|
||||
return self._translate(prompt.split("Extrait :\n", 1)[1])
|
||||
raise AssertionError(f"prompt inattendu : {prompt[:60]!r}")
|
||||
|
||||
|
||||
_AIDS = ('{"scenes": [{"n": 1, "synopsis": "Aldric écoule des reliques volées."}, {"n": 2, "synopsis": ""},'
|
||||
' {"n": 3, "synopsis": "Retour au village."}, {"n": 9, "synopsis": "hors lot"}],'
|
||||
' "npcs": [{"name": "Aldric", "description": "Marchand receleur."},'
|
||||
' {"name": "Gandalf", "description": "Absent du livre."}, {"name": "Dame Ysolde"}]}')
|
||||
_NO_AIDS = '{"scenes": [], "npcs": []}'
|
||||
|
||||
|
||||
async def test_campaign_import_keeps_the_text_of_the_book_and_adds_only_aids(no_sleep):
|
||||
llm = AidsLLM(_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and done["split_method"] == "bookmarks"
|
||||
chapters = done["arcs"][0]["chapters"]
|
||||
assert [(c["name"], [s["name"] for s in c["scenes"]]) for c in chapters] == [
|
||||
("L'aventure", ["La foire", "La crypte"]), ("Épilogue", ["Le retour"])]
|
||||
fair, crypt = chapters[0]["scenes"]
|
||||
# Le texte de la scène est celui du livre, mot pour mot.
|
||||
assert fair["gm_notes"] == ("Le marchand Aldric vend des reliques volées dans la foire du village. " * 4).strip()
|
||||
# Le synopsis vient de l'IA ; une scène sans synopsis garde le début de son texte.
|
||||
assert fair["description"] == "Aldric écoule des reliques volées."
|
||||
assert crypt["description"].startswith("Sous l'autel, la crypte abrite le spectre")
|
||||
# PNJ : seuls ceux dont le nom figure dans le texte sont gardés.
|
||||
assert done["npcs"] == [{"name": "Aldric", "description": "Marchand receleur."},
|
||||
{"name": "Dame Ysolde", "description": ""}]
|
||||
# Livre déjà dans la langue de l'interface : aucune traduction.
|
||||
assert done["source_language"] == "fr" and done["untranslated"] == 0
|
||||
assert all("Traduis" not in p for p in llm.prompts)
|
||||
assert any(e["type"] == "status" and "sans IA" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_campaign_import_hands_over_the_tree_before_the_ai_passes(no_sleep):
|
||||
uc = ImportCampaignUseCase(AidsLLM(_AIDS), FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
types = [e["type"] for e in events]
|
||||
extracted = events[types.index("extracted")]
|
||||
assert len(extracted["arcs"][0]["chapters"]) == 2 and extracted["npcs"] == []
|
||||
assert types.index("extracted") < types.index("done")
|
||||
progress = [e for e in events if e["type"] == "progress"]
|
||||
assert (progress[0]["current"], progress[0]["scene_count"], progress[-1]["npc_count"]) == (0, 3, 2)
|
||||
|
||||
|
||||
async def test_campaign_import_survives_a_failure_of_the_aids(no_sleep):
|
||||
uc = ImportCampaignUseCase(AidsLLM(LLMProviderError("HTTP 503 saturé")), FakeExtractor(_campaign_doc()),
|
||||
structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and done["skipped"] == 1 and done["npcs"] == []
|
||||
assert any(e["type"] == "chunk_failed" for e in events)
|
||||
# Sans aides, le synopsis est le début du texte : la campagne est entière.
|
||||
scene = done["arcs"][0]["chapters"][0]["scenes"][0]
|
||||
assert scene["description"].startswith("Le marchand Aldric vend des reliques volées")
|
||||
assert scene["gm_notes"]
|
||||
|
||||
|
||||
async def test_campaign_import_translates_a_book_in_another_language(no_sleep):
|
||||
llm = AidsLLM(_NO_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc("en")), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["source_language"] == "en" and done["untranslated"] == 0
|
||||
chapters = done["arcs"][0]["chapters"]
|
||||
# Les noms restent ceux du livre ; le texte de chaque scène est traduit en entier.
|
||||
assert [s["name"] for s in chapters[0]["scenes"]] == ["The Fair", "The Crypt"]
|
||||
assert chapters[0]["scenes"][0]["gm_notes"].startswith("THE MERCHANT ALDRIC SELLS STOLEN RELICS")
|
||||
assert any(e["type"] == "status" and e["message"].startswith("Traduction (français) : 3/3") for e in events)
|
||||
assert sum(1 for p in llm.prompts if "Traduis cet extrait" in p) == 3
|
||||
assert all("Traduis ces titres" not in p for p in llm.prompts)
|
||||
|
||||
|
||||
async def test_campaign_import_keeps_the_book_text_when_the_translation_fails(no_sleep):
|
||||
llm = AidsLLM(_NO_AIDS, translate=None)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc("en")), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and done["untranslated"] == 3
|
||||
assert done["arcs"][0]["chapters"][0]["scenes"][0]["gm_notes"].startswith("The merchant Aldric sells")
|
||||
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_campaign_translation_stops_when_its_time_is_up(no_sleep):
|
||||
llm = AidsLLM(_NO_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc("en")), structure_first=True)
|
||||
assert uc._translation_budget_seconds == 3 * 60 * 60
|
||||
uc._translation_budget_seconds = 0
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
# Rien n'a pu être traduit dans le temps imparti : la campagne garde le texte du livre.
|
||||
assert done["type"] == "done" and done["untranslated"] == 3
|
||||
assert done["arcs"][0]["chapters"][0]["scenes"][0]["gm_notes"].startswith("The merchant Aldric sells")
|
||||
|
||||
|
||||
async def test_campaign_import_stops_the_aids_when_time_is_up(no_sleep):
|
||||
llm = AidsLLM(_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
uc._aids_budget_seconds = 0
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
assert events[-1]["type"] == "done" and llm.prompts == []
|
||||
assert any(e["type"] == "status" and "Temps imparti" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_campaign_import_falls_back_on_the_ai_without_structure(one_chunk, no_sleep):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([_TREE]), FakeExtractor(_doc()), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and "split_method" not in done
|
||||
assert done["arcs"][0]["name"] == "Acte I"
|
||||
|
||||
|
||||
async def test_campaign_execute_follows_the_structure_too(no_sleep):
|
||||
uc = ImportCampaignUseCase(AidsLLM(_AIDS), FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
result = await uc.execute(b"pdf", language="fr")
|
||||
assert [c.name for c in result.arcs[0].chapters] == ["L'aventure", "Épilogue"]
|
||||
assert result.arcs[0].chapters[0].scenes[0].description == "Aldric écoule des reliques volées."
|
||||
assert [n.name for n in result.npcs] == ["Aldric", "Dame Ysolde"]
|
||||
|
||||
|
||||
def test_campaign_npcs_are_named_characters_listed_once():
|
||||
from app.application.import_campaign import _apply_aids
|
||||
|
||||
scene = {"name": "Le temple", "gm_notes": "Arumvel the Wicked attend avec un ogre. Jylagura veille.", "rooms": []}
|
||||
npcs: dict[str, dict] = {}
|
||||
_apply_aids([(0, scene)], {"scenes": [], "npcs": [
|
||||
{"name": "Arumvel", "description": "Un acolyte possédé par le démon."},
|
||||
{"name": "ogre", "description": "Une brute."},
|
||||
{"name": "Arumvel the Wicked", "description": "Possédé."},
|
||||
{"name": "Jylagura", "description": "Garde."},
|
||||
]}, npcs)
|
||||
assert list(npcs.values()) == [
|
||||
{"name": "Arumvel the Wicked", "description": "Un acolyte possédé par le démon."},
|
||||
{"name": "Jylagura", "description": "Garde."}]
|
||||
# Le même personnage revu dans un autre lot ne fait pas une seconde fiche.
|
||||
_apply_aids([(0, scene)], {"npcs": [{"name": "Arumvel", "description": "x"}]}, npcs)
|
||||
assert len(npcs) == 2
|
||||
|
||||
|
||||
def test_campaign_npcs_ignore_titles_hyphens_and_stat_block_names():
|
||||
from app.application.import_campaign import _apply_aids
|
||||
|
||||
scene = {"name": "Sanctepierre", "rooms": [], "gm_notes": (
|
||||
"Dame Cynaëlle de Tyrmallan reçoit le capitaine Dranand. Maître Domin et Finnlor Trois-Doigts "
|
||||
"(Finnlor Troisdoigts sur l'enseigne) se méfient de Dranand. ZOMBIE SARGASSIEN : NC 1.")}
|
||||
npcs: dict[str, dict] = {}
|
||||
_apply_aids([(0, scene)], {"npcs": [
|
||||
{"name": "dame Cynaëlle"}, {"name": "Cynaëlle de Tyrmallan"}, {"name": "capitaine Dranand"},
|
||||
{"name": "Dranand"}, {"name": "Maître Domin"}, {"name": "Domin"}, {"name": "Finnlor Trois-Doigts"},
|
||||
{"name": "Finnlor Troisdoigts"}, {"name": "ZOMBIE SARGASSIEN"},
|
||||
]}, npcs)
|
||||
assert [n["name"] for n in npcs.values()] == [
|
||||
"Cynaëlle de Tyrmallan", "capitaine Dranand", "Maître Domin", "Finnlor Trois-Doigts"]
|
||||
|
||||
|
||||
def test_campaign_npcs_are_individuals_not_groups():
|
||||
from app.application.import_campaign import _apply_aids
|
||||
|
||||
scene = {"name": "Calice", "rooms": [], "gm_notes": (
|
||||
"Les Talïns et les Vanams vivent sur la Couronne. Les Capeorns et La Main se disputent le port. Céles, de l'Ordre "
|
||||
"déchu, veille. Rump family owns the manor; Guards watch the door. King RatII rules the nest. "
|
||||
"Arvell/Alezzandro ment sur son nom. Brand est un prêtre nain.")}
|
||||
npcs: dict[str, dict] = {}
|
||||
_apply_aids([(0, scene)], {"npcs": [
|
||||
{"name": "Talïns", "description": "Ce sont les habitants qui vivent sur la Couronne."},
|
||||
{"name": "Vanams", "description": "Ce groupe est le seul à profiter du labeur des gratteux."},
|
||||
{"name": "Les Capeorns", "description": "Un clan criminel familial."},
|
||||
{"name": "La Main", "description": "C'est une guilde d'assassins qui est également une secte."},
|
||||
{"name": "Ordre déchu", "description": "Anciens gardiens."},
|
||||
{"name": "Rump family", "description": "Owners of the manor."},
|
||||
{"name": "Guards", "description": "They are guards posted at the door."},
|
||||
{"name": "Céles", "description": "Il fut un membre très actif de l'Ordre déchu."},
|
||||
{"name": "King RatII", "description": "Il est le maître de la faction de rats."},
|
||||
{"name": "Arvell/Alezzandro", "description": "Un passager."},
|
||||
{"name": "Alezzandro", "description": "Un passager qui voyage sous un faux nom."},
|
||||
{"name": "Brand", "description": "C'est un prêtre nain de Thor."},
|
||||
]}, npcs)
|
||||
assert [n["name"] for n in npcs.values()] == ["Céles", "King Rat", "Arvell/Alezzandro", "Brand"]
|
||||
assert npcs["arvell alezzandro"]["description"] == "Un passager qui voyage sous un faux nom."
|
||||
|
||||
|
||||
def test_generic_creatures_are_told_from_named_characters_by_the_way_the_book_writes_them():
|
||||
from app.application.import_campaign import _is_generic
|
||||
|
||||
book = ("A wraith sits in a great leather chair. Wraith. Medium undead. The pirates are led by Key, who holds "
|
||||
"the key of the vault. Nine ghouls wait below with a giant rat. Giant rat. Small beast. "
|
||||
"Le vieux Paltuis le mage vit ici ; on y croise Dodi la pieuvre. Ruang the Ripper sleeps in B12.")
|
||||
assert _is_generic("Wraith", book) and _is_generic("Giant rat", book) and _is_generic("Nine ghouls", book)
|
||||
assert _is_generic("3 gobelins", book)
|
||||
# « Key » est aussi un nom commun, mais le livre l'écrit avec une majuscule en cours de phrase.
|
||||
assert not _is_generic("Key", book)
|
||||
assert not _is_generic("Paltuis le mage", book) and not _is_generic("Dodi la pieuvre", book)
|
||||
assert not _is_generic("Ruang the Ripper", book) and not _is_generic("Brand", book)
|
||||
|
||||
|
||||
def test_a_unique_role_without_a_name_is_still_a_character():
|
||||
from app.application.import_campaign import _is_generic
|
||||
|
||||
book = ("La commandante garde la clé du Dédale. Les PJ préviennent la commandante, qui fait ouvrir le "
|
||||
"cercueil. Plus tard, la commandante les convoque. Un spectre surgit ; le spectre attaque, puis "
|
||||
"deux spectres le rejoignent. L’aubergiste se méfie, mais l’aubergiste parle volontiers. "
|
||||
"The innkeeper pours ale and the innkeeper listens. A ghost appears; the ghost wails, the ghost flees.")
|
||||
# Toujours « la commandante », jamais « une commandante » ni au pluriel : un personnage.
|
||||
assert not _is_generic("La commandante", book) and not _is_generic("Commandante", book)
|
||||
assert not _is_generic("L’aubergiste", book) and not _is_generic("Innkeeper", book)
|
||||
# « un spectre », « deux spectres », « a ghost » : une créature parmi d'autres.
|
||||
assert _is_generic("Spectre", book) and _is_generic("Le spectre", book) and _is_generic("Ghost", book)
|
||||
# Cité une seule fois avec l'article défini : pas assez pour en faire un personnage.
|
||||
assert _is_generic("Cercueil", book)
|
||||
|
||||
|
||||
def test_scenes_about_the_book_itself_are_recognized():
|
||||
from app.application.import_campaign import _is_about_the_book
|
||||
|
||||
def scene(name, notes):
|
||||
return {"name": name, "gm_notes": notes, "rooms": []}
|
||||
|
||||
assert _is_about_the_book(scene("A note from Bill Webb on Tegel Manor", "That little kid was me."))
|
||||
assert _is_about_the_book(scene("Introduction › Avant-propos", "Bienvenue."))
|
||||
assert _is_about_the_book(scene("Overview", "First published in 1977, Tegel Manor is the oldest adventure."))
|
||||
assert _is_about_the_book(scene("Historique", "Ce module a été financé sur Kickstarter en 2019."))
|
||||
# Une année seule, ou un mot d'édition seul, ne suffit pas ; une date du monde de jeu non plus.
|
||||
assert not _is_about_the_book(scene("Le journal", "Le journal, publié par la guilde, date de l'an 1372."))
|
||||
assert not _is_about_the_book(scene("La crypte", "En 1985, le professeur disparut dans la crypte."))
|
||||
assert not _is_about_the_book(scene("How the Demon Rose", "Arumvel touched the jar."))
|
||||
|
||||
|
||||
async def test_real_people_named_only_in_the_preface_are_not_npcs(no_sleep):
|
||||
"""« Bill Webb » n'est cité que dans la préface ; « Aldric » y est cité aussi, mais on le croise
|
||||
dans l'aventure."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
doc = _campaign_doc()
|
||||
page = doc.page_count
|
||||
preface = ("Publié pour la première fois en 1977 par Bill Webb, ce module doit beaucoup à ses joueurs. "
|
||||
"Le marchand Aldric est né à sa table. ") * 3
|
||||
doc.toc.insert(0, TocEntry(level=1, title="Préface", page=page + 1))
|
||||
doc.lines.extend([TextLine(page, 0, "Préface", 24.0), TextLine(page, 1, preface.strip(), 10.0)])
|
||||
doc.pages.append(ExtractedPage(index=page, text="texte", used_ocr=False))
|
||||
aids = ('{"scenes": [], "npcs": [{"name": "Bill Webb", "description": "Auteur du module."},'
|
||||
' {"name": "Aldric", "description": "Marchand receleur."}]}')
|
||||
uc = ImportCampaignUseCase(AidsLLM(aids), FakeExtractor(doc), structure_first=True)
|
||||
done = [e async for e in uc.stream(b"pdf", language="fr")][-1]
|
||||
assert any(scene["name"] == "Préface" for arc in done["arcs"] for ch in arc["chapters"] for scene in ch["scenes"])
|
||||
assert [n["name"] for n in done["npcs"]] == ["Aldric"]
|
||||
|
||||
|
||||
async def test_campaign_import_leaves_generic_creatures_out_of_the_npcs(no_sleep):
|
||||
aids = ('{"scenes": [], "npcs": [{"name": "Aldric", "description": "Marchand receleur."},'
|
||||
' {"name": "Reliques", "description": "Objets."}, {"name": "La Dame Ysolde", "description": "Spectre."},'
|
||||
' {"name": "Dame Ysolde", "description": "Le spectre de la crypte, gardé par ses fidèles."}]}')
|
||||
uc = ImportCampaignUseCase(AidsLLM(aids), FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
done = [e async for e in uc.stream(b"pdf", language="fr")][-1]
|
||||
# « reliques » est un nom commun du livre ; « La Dame Ysolde » n'y figure pas sous cette forme.
|
||||
assert done["npcs"] == [{"name": "Aldric", "description": "Marchand receleur."},
|
||||
{"name": "Dame Ysolde", "description": "Le spectre de la crypte, gardé par ses fidèles."}]
|
||||
|
||||
|
||||
async def test_campaign_appendices_get_no_aids_from_the_ai(no_sleep):
|
||||
"""Le bestiaire en annexe : ni synopsis rédigé, ni PNJ — mais traduit comme le reste."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
doc = _campaign_doc()
|
||||
page = doc.page_count
|
||||
profile = "Le spectre Vorlak est une créature mort-vivante qui hante la crypte et draine la vie. " * 4
|
||||
doc.toc.append(TocEntry(level=1, title="Annexe : Créatures", page=page + 1))
|
||||
doc.toc.append(TocEntry(level=2, title="Spectre", page=page + 1))
|
||||
doc.lines.extend([TextLine(page, 0, "Annexe : Créatures", 24.0), TextLine(page, 1, "Spectre", 16.0),
|
||||
TextLine(page, 2, profile.strip(), 10.0)])
|
||||
doc.pages.append(ExtractedPage(index=page, text="texte", used_ocr=False))
|
||||
llm = AidsLLM(_AIDS.replace('"Dame Ysolde"}', '"Dame Ysolde"}, {"name": "Vorlak", "description": "Spectre."}'))
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(doc), structure_first=True)
|
||||
done = [e async for e in uc.stream(b"pdf", language="fr")][-1]
|
||||
assert [(arc["name"], arc["type"]) for arc in done["arcs"]] == [("Aventure principale", "LINEAR"), ("Annexes", "HUB")]
|
||||
appendix = done["arcs"][1]["chapters"][0]["scenes"][0]
|
||||
assert appendix["name"] == "Spectre" and appendix["gm_notes"] == profile.strip()
|
||||
# Le texte de l'annexe n'est pas montré au modèle : il n'en tire ni synopsis ni PNJ.
|
||||
assert all("Vorlak" not in prompt for prompt in llm.prompts)
|
||||
assert [n["name"] for n in done["npcs"]] == ["Aldric", "Dame Ysolde"]
|
||||
|
||||
|
||||
def test_the_model_sees_the_list_of_rooms_of_an_explorable_place_first():
|
||||
from app.application.import_campaign import _aid_text
|
||||
|
||||
dungeon = {"name": "Crypte", "gm_notes": "Conclusion.", "rooms": [
|
||||
{"name": "1. Entrée", "description": "Une grille."}, {"name": "2. Tombeau", "description": "Un roi."}]}
|
||||
text = _aid_text(dungeon, 10_000)
|
||||
assert text.startswith("[Lieu explorable, 2 pièce(s) : 1. Entrée; 2. Tombeau]\n\nConclusion.\n\n1. Entrée\nUne grille.")
|
||||
assert _aid_text({"name": "Route", "gm_notes": "Une route.", "rooms": []}, 10_000) == "Une route."
|
||||
|
||||
|
||||
def test_campaign_rooms_are_translated_and_put_back_in_place():
|
||||
from app.application.import_campaign import _apply_translation, _translation_units
|
||||
|
||||
scenes = [{"name": "Crypt", "gm_notes": "Notes.", "rooms": [
|
||||
{"name": "1. Gate", "description": "A gate.", "enemies": "", "loot": ""},
|
||||
{"name": "2. Empty", "description": " ", "enemies": "", "loot": ""}]},
|
||||
{"name": "Road", "gm_notes": "", "rooms": []}]
|
||||
units, labels = _translation_units(scenes)
|
||||
assert units == {"s0": "Notes.", "s0r0": "A gate."}
|
||||
assert labels == {"s0": "Crypt", "s0r0": "Crypt › 1. Gate"}
|
||||
_apply_translation(scenes, {"s0r0": "Une grille."})
|
||||
assert scenes[0]["gm_notes"] == "Notes." and scenes[0]["rooms"][0]["description"] == "Une grille."
|
||||
|
||||
|
||||
def test_campaign_aids_are_asked_by_batches_in_the_order_of_the_book():
|
||||
from app.application.import_campaign import _aid_batches
|
||||
|
||||
scenes = [{"name": f"Scène {i}", "gm_notes": "x" * 3_000, "rooms": []} for i in range(5)]
|
||||
batches = _aid_batches(scenes, 8_000)
|
||||
assert [[index for index, _ in batch] for batch in batches] == [[0, 1], [2, 3], [4]]
|
||||
# Une scène très longue est bornée pour les aides : elle ne fait pas déborder le lot.
|
||||
assert len(_aid_batches([{"name": "Longue", "gm_notes": "x" * 50_000, "rooms": []}], 8_000)) == 1
|
||||
assert len(_aid_batches([{"name": f"S{i}", "gm_notes": "x", "rooms": []} for i in range(30)], 8_000)) == 3
|
||||
|
||||
|
||||
def test_campaign_import_uses_the_structure_and_one_call_at_a_time_locally():
|
||||
from app.api.deps import get_import_campaign_use_case
|
||||
from app.core.config import Settings
|
||||
|
||||
local = get_import_campaign_use_case(ScriptedLLM(["{}"]), Settings(_env_file=None, llm_provider="ollama"))
|
||||
cloud = get_import_campaign_use_case(ScriptedLLM(["{}"]), Settings(_env_file=None, llm_provider="mistral"))
|
||||
assert local._structure_first and cloud._structure_first
|
||||
assert local._map_concurrency == 1 and local._translation_concurrency == 1
|
||||
assert cloud._map_concurrency > 1 and cloud._translation_concurrency > 1
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Tests de la normalisation de langue (app.core.language)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core import language
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
("fr", "fr"),
|
||||
("en", "en"),
|
||||
("EN", "en"),
|
||||
("en-US", "en"),
|
||||
("fr-FR,fr;q=0.9,en;q=0.8", "fr"),
|
||||
("en-GB,en;q=0.9", "en"),
|
||||
("de", "fr"), # non supporté → défaut
|
||||
("", "fr"),
|
||||
(None, "fr"),
|
||||
(" EN-gb ", "en"), # casse + espaces tolérés
|
||||
])
|
||||
def test_normalize(raw, expected):
|
||||
assert language.normalize(raw) == expected
|
||||
|
||||
|
||||
def test_language_name_known_and_fallback():
|
||||
assert language.language_name("fr") == "français"
|
||||
assert language.language_name("en") == "anglais"
|
||||
# Code inconnu → nom de la langue par défaut.
|
||||
assert language.language_name("xx") == "français"
|
||||
|
||||
|
||||
def test_instruction_mentions_target_language():
|
||||
assert "anglais" in language.instruction("en")
|
||||
assert "français" in language.instruction("fr")
|
||||
|
||||
|
||||
def test_get_user_language_uses_normalize():
|
||||
assert language.get_user_language("en-US") == "en"
|
||||
assert language.get_user_language(None) == "fr"
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Tests de la lecture robuste de JSON depuis une réponse LLM (app.application.llm_json).
|
||||
|
||||
Couvre l'extraction du premier objet équilibré (en ignorant les accolades dans
|
||||
les chaînes), la réparation d'un JSON tronqué, la détection « ça ressemble à du
|
||||
JSON coupé », et le strip des blocs de raisonnement <think>…</think>.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.llm_json import (
|
||||
extract_json_object,
|
||||
load_json_object,
|
||||
looks_like_truncated_json,
|
||||
repair_truncated_json,
|
||||
)
|
||||
|
||||
|
||||
# --- extract_json_object -------------------------------------------------------
|
||||
|
||||
def test_extract_simple_object():
|
||||
assert extract_json_object('{"a": 1}') == '{"a": 1}'
|
||||
|
||||
|
||||
def test_extract_ignores_surrounding_prose_and_fences():
|
||||
raw = 'Voici le JSON :\n```json\n{"a": 1}\n```\nMerci.'
|
||||
assert extract_json_object(raw) == '{"a": 1}'
|
||||
|
||||
|
||||
def test_extract_stops_at_first_balanced_object():
|
||||
assert extract_json_object('{"a": 1} et puis {"b": 2}') == '{"a": 1}'
|
||||
|
||||
|
||||
def test_extract_keeps_nested_object_whole():
|
||||
assert extract_json_object('{"a": {"b": 1}}') == '{"a": {"b": 1}}'
|
||||
|
||||
|
||||
def test_extract_ignores_braces_inside_strings():
|
||||
raw = '{"a": "}{ pas du json "}'
|
||||
assert extract_json_object(raw) == raw
|
||||
|
||||
|
||||
def test_extract_handles_escaped_quote_in_string():
|
||||
raw = '{"a": "x\\"y"}'
|
||||
assert extract_json_object(raw) == raw
|
||||
|
||||
|
||||
def test_extract_returns_none_when_unclosed():
|
||||
assert extract_json_object('{"a": 1') is None
|
||||
|
||||
|
||||
def test_extract_returns_none_without_brace():
|
||||
assert extract_json_object('aucune accolade ici') is None
|
||||
|
||||
|
||||
def test_extract_returns_none_on_empty():
|
||||
assert extract_json_object('') is None
|
||||
|
||||
|
||||
# --- load_json_object ----------------------------------------------------------
|
||||
|
||||
def test_load_valid_object_not_recovered():
|
||||
obj, recovered = load_json_object('{"x": 42}')
|
||||
assert obj == {"x": 42}
|
||||
assert recovered is False
|
||||
|
||||
|
||||
def test_load_tolerates_raw_control_chars_in_strings():
|
||||
# Retour à la ligne BRUT dans une chaîne : invalide en strict, accepté ici.
|
||||
obj, recovered = load_json_object('{"a": "ligne1\nligne2"}')
|
||||
assert obj == {"a": "ligne1\nligne2"}
|
||||
assert recovered is False
|
||||
|
||||
|
||||
def test_load_strips_reasoning_block_before_parsing():
|
||||
raw = '<think>je réfléchis { ] [ }</think>{"ok": true}'
|
||||
obj, recovered = load_json_object(raw)
|
||||
assert obj == {"ok": True}
|
||||
assert recovered is False
|
||||
|
||||
|
||||
def test_load_repairs_truncated_array_and_flags_recovered():
|
||||
raw = '{"items": [{"a": 1}, {"b": 2}, {"c":'
|
||||
obj, recovered = load_json_object(raw)
|
||||
assert obj == {"items": [{"a": 1}, {"b": 2}]}
|
||||
assert recovered is True
|
||||
|
||||
|
||||
def test_load_returns_none_on_garbage():
|
||||
obj, recovered = load_json_object('juste de la prose sans json')
|
||||
assert obj is None
|
||||
assert recovered is False
|
||||
|
||||
|
||||
# --- looks_like_truncated_json -------------------------------------------------
|
||||
|
||||
def test_truncated_detection_no_brace_is_false():
|
||||
assert looks_like_truncated_json('rien') is False
|
||||
|
||||
|
||||
def test_truncated_detection_short_object_start_unbalanced_is_true():
|
||||
# Démarre par '{' et déséquilibré → coupé net, même très court.
|
||||
assert looks_like_truncated_json('{"') is True
|
||||
|
||||
|
||||
def test_truncated_detection_balanced_object_is_false():
|
||||
assert looks_like_truncated_json('{"a": 1}') is False
|
||||
|
||||
|
||||
def test_truncated_detection_short_prose_with_braces_is_false():
|
||||
assert looks_like_truncated_json('texte { incomplet') is False
|
||||
|
||||
|
||||
def test_truncated_detection_long_prose_unbalanced_is_true():
|
||||
raw = 'prose ' * 30 + '{ structure ouverte mais jamais refermée'
|
||||
assert len(raw) >= 100
|
||||
assert looks_like_truncated_json(raw) is True
|
||||
|
||||
|
||||
# --- repair_truncated_json -----------------------------------------------------
|
||||
|
||||
def test_repair_closes_open_containers_after_last_complete_element():
|
||||
repaired = repair_truncated_json('{"items": [{"a": 1}, {"b": 2}, {"c":')
|
||||
assert repaired == '{"items": [{"a": 1}, {"b": 2}]}'
|
||||
|
||||
|
||||
def test_repair_returns_none_when_nothing_complete():
|
||||
assert repair_truncated_json('{"a": "jamais fermé') is None
|
||||
|
||||
|
||||
def test_repair_returns_none_without_brace():
|
||||
assert repair_truncated_json('pas de json') is None
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Tests du retry des appels LLM one-shot (app.application.llm_retry).
|
||||
|
||||
`asyncio.sleep` est neutralisé (et enregistré) pour que les backoffs n'imposent
|
||||
aucune attente réelle tout en vérifiant les durées choisies.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application import llm_retry
|
||||
from app.application.llm_retry import (
|
||||
_is_daily_quota,
|
||||
_is_rate_limit,
|
||||
_suggested_retry_after,
|
||||
generate_with_retry,
|
||||
)
|
||||
from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
|
||||
class FakeLLM:
|
||||
"""LLM factice : rejoue une liste de comportements (exception ou texte)."""
|
||||
|
||||
def __init__(self, behaviors: list) -> None:
|
||||
self._behaviors = list(behaviors)
|
||||
self.calls = 0
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
b = self._behaviors[self.calls]
|
||||
self.calls += 1
|
||||
if isinstance(b, Exception):
|
||||
raise b
|
||||
return b
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def slept(monkeypatch):
|
||||
"""Neutralise asyncio.sleep et enregistre les durées demandées."""
|
||||
recorded: list[float] = []
|
||||
|
||||
async def fake_sleep(d):
|
||||
recorded.append(d)
|
||||
|
||||
monkeypatch.setattr("asyncio.sleep", fake_sleep)
|
||||
return recorded
|
||||
|
||||
|
||||
# --- helpers de classification -------------------------------------------------
|
||||
|
||||
def test_is_rate_limit():
|
||||
assert _is_rate_limit(LLMProviderError("HTTP 429 Too Many Requests"))
|
||||
assert _is_rate_limit(LLMProviderError("rate limit reached"))
|
||||
assert not _is_rate_limit(LLMProviderError("HTTP 500"))
|
||||
|
||||
|
||||
def test_is_daily_quota():
|
||||
assert _is_daily_quota(LLMProviderError("free-models-per-day limit"))
|
||||
assert _is_daily_quota(LLMProviderError("quota per day exceeded"))
|
||||
assert not _is_daily_quota(LLMProviderError("429 per-minute"))
|
||||
|
||||
|
||||
def test_suggested_retry_after():
|
||||
assert _suggested_retry_after(LLMProviderError('{"retry_after_seconds": 8}')) == 8.0
|
||||
assert _suggested_retry_after(LLMProviderError('Retry-After: 12')) == 12.0
|
||||
assert _suggested_retry_after(LLMProviderError("pas de hint")) is None
|
||||
|
||||
|
||||
# --- generate_with_retry -------------------------------------------------------
|
||||
|
||||
async def test_returns_on_first_success(slept):
|
||||
llm = FakeLLM(["réponse"])
|
||||
assert await generate_with_retry(llm, "p") == "réponse"
|
||||
assert llm.calls == 1
|
||||
assert slept == []
|
||||
|
||||
|
||||
async def test_retries_transient_error_then_succeeds(slept):
|
||||
llm = FakeLLM([LLMProviderError("HTTP 503"), "ok"])
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
assert llm.calls == 2
|
||||
assert slept == [3.0] # _BASE_DELAY_SECONDS
|
||||
|
||||
|
||||
async def test_timeout_raises_immediately_without_retry(slept):
|
||||
llm = FakeLLM([LLMGenerationTimeout("trop lent")])
|
||||
with pytest.raises(LLMGenerationTimeout):
|
||||
await generate_with_retry(llm, "p")
|
||||
assert llm.calls == 1
|
||||
assert slept == []
|
||||
|
||||
|
||||
async def test_daily_quota_aborts_immediately(slept):
|
||||
llm = FakeLLM([LLMProviderError("free-models-per-day exceeded")])
|
||||
with pytest.raises(LLMProviderError):
|
||||
await generate_with_retry(llm, "p")
|
||||
assert llm.calls == 1
|
||||
assert slept == []
|
||||
|
||||
|
||||
async def test_exhausts_attempts_then_raises_last(slept):
|
||||
llm = FakeLLM([LLMProviderError("503 a"), LLMProviderError("503 b"), LLMProviderError("503 c")])
|
||||
with pytest.raises(LLMProviderError, match="503 c"):
|
||||
await generate_with_retry(llm, "p")
|
||||
assert llm.calls == 3
|
||||
# 2 attentes entre 3 tentatives (backoff exponentiel 3s puis 6s).
|
||||
assert slept == [3.0, 6.0]
|
||||
|
||||
|
||||
async def test_rate_limit_respects_suggested_retry_after(slept):
|
||||
llm = FakeLLM([LLMProviderError('429 {"retry_after_seconds": 8}'), "ok"])
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
# min(8 + 2, 60) = 10
|
||||
assert slept == [10.0]
|
||||
|
||||
|
||||
async def test_tells_the_ui_when_the_next_attempt_starts(slept):
|
||||
import asyncio
|
||||
|
||||
from app.application.import_status import reset_status_queue, set_status_queue
|
||||
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
token = set_status_queue(queue)
|
||||
try:
|
||||
llm = FakeLLM([LLMProviderError("Erreur Mistral (ReadError) : ReadError"), "ok"])
|
||||
assert await generate_with_retry(llm, "p") == "ok"
|
||||
finally:
|
||||
reset_status_queue(token)
|
||||
messages = [queue.get_nowait() for _ in range(queue.qsize())]
|
||||
assert "nouvel essai dans 3s" in messages[0]
|
||||
# Sans ce second message, « nouvel essai dans 3s » restait affiché pendant tout l'essai suivant.
|
||||
assert messages[1] == "Nouvel essai en cours (tentative 2/3)…"
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Tests de la logique portée par les modèles de domaine (app.domain.models)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.domain.models import (
|
||||
ArcProposal,
|
||||
CampaignImportResult,
|
||||
ChapterProposal,
|
||||
ExtractedDocument,
|
||||
ExtractedPage,
|
||||
RulesImportResult,
|
||||
SceneProposal,
|
||||
)
|
||||
|
||||
|
||||
def test_extracted_document_properties():
|
||||
doc = ExtractedDocument(pages=[
|
||||
ExtractedPage(index=0, text="page un", used_ocr=False),
|
||||
ExtractedPage(index=1, text="page deux", used_ocr=True),
|
||||
ExtractedPage(index=2, text=" ", used_ocr=False), # vide → exclue de full_text
|
||||
])
|
||||
assert doc.page_count == 3
|
||||
assert doc.ocr_page_count == 1
|
||||
assert doc.full_text == "page un\n\npage deux"
|
||||
|
||||
|
||||
def test_rules_import_result_to_markdown():
|
||||
result = RulesImportResult(
|
||||
sections={"Combat": "règles de combat", "Magie": "règles de magie"},
|
||||
page_count=10, ocr_page_count=0,
|
||||
)
|
||||
md = result.to_markdown()
|
||||
assert "## Combat\n\nrègles de combat" in md
|
||||
assert "## Magie\n\nrègles de magie" in md
|
||||
assert md.endswith("\n")
|
||||
|
||||
|
||||
def test_campaign_import_result_counts():
|
||||
arcs = [
|
||||
ArcProposal("A1", "", chapters=[
|
||||
ChapterProposal("C1", "", scenes=[SceneProposal("S1", ""), SceneProposal("S2", "")]),
|
||||
ChapterProposal("C2", "", scenes=[SceneProposal("S3", "")]),
|
||||
]),
|
||||
ArcProposal("A2", "", chapters=[]),
|
||||
]
|
||||
result = CampaignImportResult(arcs=arcs, page_count=1, ocr_page_count=0)
|
||||
assert result.counts() == (2, 2, 3)
|
||||
|
||||
|
||||
def test_arc_proposal_defaults():
|
||||
arc = ArcProposal("Acte", "synopsis")
|
||||
assert arc.arc_type == "LINEAR"
|
||||
assert arc.chapters == []
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Tests de caractérisation de l'adapter Ollama (protocole propre : /api/generate
|
||||
one-shot + /api/chat NDJSON streamé)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
from app.infrastructure.ollama_adapter import OllamaLLMProvider
|
||||
|
||||
_GEN = "http://ollama:11434/api/generate"
|
||||
_CHAT = "http://ollama:11434/api/chat"
|
||||
|
||||
|
||||
def _svc() -> OllamaLLMProvider:
|
||||
s = Settings(_env_file=None, ollama_base_url="http://ollama:11434",
|
||||
llm_model="gemma", llm_timeout_seconds=30, llm_num_ctx=8192)
|
||||
return OllamaLLMProvider(s)
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_returns_response_field():
|
||||
respx.post(_GEN).mock(return_value=httpx.Response(200, json={"response": "texte", "done_reason": "stop"}))
|
||||
assert await _svc().generate("prompt") == "texte"
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_payload_always_sends_num_ctx_and_omits_temperature():
|
||||
route = respx.post(_GEN).mock(return_value=httpx.Response(200, json={"response": "x"}))
|
||||
await _svc().generate("p")
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
assert body["model"] == "gemma"
|
||||
assert body["stream"] is False
|
||||
assert body["options"] == {"num_ctx": 8192}
|
||||
assert "format" not in body
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_payload_includes_temperature_and_format_when_given():
|
||||
route = respx.post(_GEN).mock(return_value=httpx.Response(200, json={"response": "x"}))
|
||||
await _svc().generate("p", output_format="json", temperature=0.1)
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
assert body["options"]["temperature"] == 0.1
|
||||
assert body["format"] == "json"
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_http_error_surfaces_ollama_message():
|
||||
respx.post(_GEN).mock(return_value=httpx.Response(404, json={"error": "model 'x' not found"}))
|
||||
with pytest.raises(LLMProviderError) as exc:
|
||||
await _svc().generate("p")
|
||||
assert "not found" in str(exc.value)
|
||||
assert "404" in str(exc.value)
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_read_timeout_is_generation_timeout():
|
||||
respx.post(_GEN).mock(side_effect=httpx.ReadTimeout("trop lent"))
|
||||
with pytest.raises(LLMGenerationTimeout):
|
||||
await _svc().generate("p")
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_connect_timeout_is_provider_error():
|
||||
respx.post(_GEN).mock(side_effect=httpx.ConnectTimeout("injoignable"))
|
||||
with pytest.raises(LLMProviderError) as exc:
|
||||
await _svc().generate("p")
|
||||
assert not isinstance(exc.value, LLMGenerationTimeout)
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_stream_chat_yields_tokens_until_done():
|
||||
body = (
|
||||
'{"message":{"content":"Bon"},"done":false}\n'
|
||||
'{"message":{"content":"jour"},"done":false}\n'
|
||||
'{"done":true}\n'
|
||||
)
|
||||
respx.post(_CHAT).mock(return_value=httpx.Response(200, text=body))
|
||||
tokens = [t async for t in _svc().stream_chat([ChatMessage(role="user", content="hi")])]
|
||||
assert tokens == ["Bon", "jour"]
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_stream_chat_prepends_system_prompt():
|
||||
route = respx.post(_CHAT).mock(return_value=httpx.Response(200, text='{"done":true}\n'))
|
||||
_ = [t async for t in _svc().stream_chat(
|
||||
[ChatMessage(role="user", content="Q")], system_prompt="SYS")]
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
assert body["messages"][0] == {"role": "system", "content": "SYS"}
|
||||
assert body["messages"][-1] == {"role": "user", "content": "Q"}
|
||||
|
||||
|
||||
# --- Réflexion coupée (modèles qwen3.x… : réponse vide dès qu'un JSON est attendu) ---------
|
||||
|
||||
@pytest.fixture
|
||||
def forget_refused_models():
|
||||
from app.infrastructure import ollama_adapter
|
||||
ollama_adapter._THINK_PARAM_REFUSED.clear()
|
||||
yield
|
||||
ollama_adapter._THINK_PARAM_REFUSED.clear()
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_turns_thinking_off(forget_refused_models):
|
||||
route = respx.post(_GEN).mock(return_value=httpx.Response(200, json={"response": "{}"}))
|
||||
await _svc().generate("p", output_format={"type": "object"})
|
||||
assert json.loads(route.calls.last.request.content)["think"] is False
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_retries_without_think_when_ollama_refuses_it(forget_refused_models):
|
||||
route = respx.post(_GEN).mock(side_effect=[
|
||||
httpx.Response(400, json={"error": '"gemma" does not support thinking'}),
|
||||
httpx.Response(200, json={"response": "ok"}),
|
||||
httpx.Response(200, json={"response": "encore"}),
|
||||
])
|
||||
assert await _svc().generate("p") == "ok"
|
||||
assert "think" in json.loads(route.calls[0].request.content)
|
||||
assert "think" not in json.loads(route.calls[1].request.content)
|
||||
# Le refus est retenu : l'appel suivant n'envoie plus le paramètre (un seul aller-retour).
|
||||
assert await _svc().generate("p") == "encore"
|
||||
assert "think" not in json.loads(route.calls[2].request.content)
|
||||
assert route.call_count == 3
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_does_not_retry_another_bad_request(forget_refused_models):
|
||||
route = respx.post(_GEN).mock(return_value=httpx.Response(400, json={"error": "invalid format schema"}))
|
||||
with pytest.raises(LLMProviderError, match="invalid format schema"):
|
||||
await _svc().generate("p")
|
||||
assert route.call_count == 1
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Tests de l'adapter 1min.ai (API propriétaire : prompt unique aplati, SSE
|
||||
`event: content`/`data:{content}`)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError
|
||||
from app.infrastructure.onemin_adapter import OneMinAiLLMProvider
|
||||
|
||||
_URL = "https://api.1min.ai/api/chat-with-ai?isStreaming=true"
|
||||
|
||||
|
||||
def _svc() -> OneMinAiLLMProvider:
|
||||
s = Settings(_env_file=None, onemin_api_key="k", onemin_model="gpt-4o-mini",
|
||||
llm_timeout_seconds=30)
|
||||
return OneMinAiLLMProvider(s)
|
||||
|
||||
|
||||
def _sse(*blocks: str) -> str:
|
||||
return "".join(blocks)
|
||||
|
||||
|
||||
# --- streaming -----------------------------------------------------------------
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_collects_content_chunks():
|
||||
body = _sse(
|
||||
"event: content\ndata: {\"content\": \"Bon\"}\n\n",
|
||||
"event: content\ndata: {\"content\": \"jour\"}\n\n",
|
||||
"event: done\ndata: {}\n\n",
|
||||
)
|
||||
respx.post(_URL).mock(return_value=httpx.Response(200, text=body))
|
||||
assert await _svc().generate("salut") == "Bonjour"
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_sends_api_key_header_and_prompt_payload():
|
||||
route = respx.post(_URL).mock(return_value=httpx.Response(
|
||||
200, text="event: done\ndata: {}\n\n"))
|
||||
await _svc().generate("ma question")
|
||||
req = route.calls.last.request
|
||||
assert req.headers["API-KEY"] == "k"
|
||||
import json
|
||||
body = json.loads(req.content)
|
||||
assert body["model"] == "gpt-4o-mini"
|
||||
assert body["promptObject"]["prompt"] == "ma question"
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_error_event_raises_provider_error():
|
||||
body = "event: error\ndata: {\"message\": \"quota dépassé\"}\n\n"
|
||||
respx.post(_URL).mock(return_value=httpx.Response(200, text=body))
|
||||
with pytest.raises(LLMProviderError) as exc:
|
||||
await _svc().generate("p")
|
||||
assert "quota dépassé" in str(exc.value)
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_http_error_is_translated():
|
||||
respx.post(_URL).mock(return_value=httpx.Response(502, text="bad gateway"))
|
||||
with pytest.raises(LLMProviderError) as exc:
|
||||
await _svc().generate("p")
|
||||
assert "1min.ai" in str(exc.value)
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_stream_chat_flattens_and_streams():
|
||||
route = respx.post(_URL).mock(return_value=httpx.Response(
|
||||
200, text="event: content\ndata: {\"content\": \"R\"}\n\nevent: done\ndata: {}\n\n"))
|
||||
tokens = [t async for t in _svc().stream_chat(
|
||||
[ChatMessage(role="user", content="Q")], system_prompt="SYS")]
|
||||
assert tokens == ["R"]
|
||||
import json
|
||||
prompt = json.loads(route.calls.last.request.content)["promptObject"]["prompt"]
|
||||
assert "[SYSTEM]" in prompt and "SYS" in prompt
|
||||
assert "[USER]" in prompt and "Q" in prompt
|
||||
|
||||
|
||||
# --- helpers purs --------------------------------------------------------------
|
||||
|
||||
def test_flatten_messages_structure():
|
||||
out = OneMinAiLLMProvider._flatten_messages(
|
||||
[ChatMessage(role="user", content="Q1"), ChatMessage(role="assistant", content="R1")],
|
||||
"instructions système",
|
||||
)
|
||||
assert "[SYSTEM]\ninstructions système" in out
|
||||
assert "[USER]\nQ1" in out
|
||||
assert "[ASSISTANT]\nR1" in out
|
||||
assert out.rstrip().endswith("[ASSISTANT]")
|
||||
|
||||
|
||||
def test_extract_content_chunk_json_and_fallback():
|
||||
assert OneMinAiLLMProvider._extract_content_chunk('{"content": "x"}') == "x"
|
||||
assert OneMinAiLLMProvider._extract_content_chunk('{"token": "y"}') == "y"
|
||||
# Non-JSON : filet de sécurité, on renvoie le brut.
|
||||
assert OneMinAiLLMProvider._extract_content_chunk("texte brut") == "texte brut"
|
||||
|
||||
|
||||
def test_extract_result_reads_nested_result_object():
|
||||
payload = {"aiRecord": {"aiRecordDetail": {"resultObject": ["partie 1", "partie 2"]}}}
|
||||
assert OneMinAiLLMProvider._extract_result(payload) == "partie 1partie 2"
|
||||
|
||||
|
||||
def test_extract_result_raises_on_unexpected_schema():
|
||||
with pytest.raises(LLMProviderError):
|
||||
OneMinAiLLMProvider._extract_result({"unexpected": True})
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Tests de caractérisation des adapters LLM « OpenAI-compatible »
|
||||
(OpenRouter, Gemini, Mistral).
|
||||
|
||||
But : VERROUILLER le comportement observable AVANT d'extraire une classe de base
|
||||
commune (les trois adapters partageaient ~80 % de code). On couvre via respx
|
||||
(mock du transport httpx) : collecte du stream, payload envoyé, en-têtes, parsing
|
||||
SSE, et traduction des erreurs HTTP — sans aucun appel réseau réel.
|
||||
|
||||
Ces tests doivent rester verts à l'identique après le refactor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import respx
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError
|
||||
from app.infrastructure.gemini_adapter import GeminiLLMProvider
|
||||
from app.infrastructure.mistral_adapter import MistralLLMProvider
|
||||
from app.infrastructure.openrouter_adapter import OpenRouterLLMProvider
|
||||
|
||||
|
||||
def _settings(**kw) -> Settings:
|
||||
return Settings(_env_file=None, llm_timeout_seconds=30, **kw)
|
||||
|
||||
|
||||
def _sse(*contents: str) -> str:
|
||||
"""Construit un corps SSE OpenAI : une trame `data: {choices:[{delta:{content}}]}`
|
||||
par fragment, terminé par `data: [DONE]`."""
|
||||
lines: list[str] = []
|
||||
for c in contents:
|
||||
lines.append("data: " + json.dumps({"choices": [{"delta": {"content": c}}]}))
|
||||
lines.append("")
|
||||
lines += ["data: [DONE]", ""]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# (id, classe, url, kwargs settings (clé+modèle), supporte response_format=json_object)
|
||||
CASES = [
|
||||
pytest.param(
|
||||
OpenRouterLLMProvider,
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
dict(openrouter_api_key="k", openrouter_model="m"),
|
||||
False,
|
||||
"OpenRouter",
|
||||
id="openrouter",
|
||||
),
|
||||
pytest.param(
|
||||
GeminiLLMProvider,
|
||||
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
|
||||
dict(gemini_api_key="k", gemini_model="m"),
|
||||
True,
|
||||
"Gemini",
|
||||
id="gemini",
|
||||
),
|
||||
pytest.param(
|
||||
MistralLLMProvider,
|
||||
"https://api.mistral.ai/v1/chat/completions",
|
||||
dict(mistral_api_key="k", mistral_model="m"),
|
||||
True,
|
||||
"Mistral",
|
||||
id="mistral",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_generate_collects_full_stream(cls, url, skw, supports_json, label):
|
||||
respx.post(url).mock(return_value=httpx.Response(200, text=_sse("Bonjour", " le", " monde")))
|
||||
svc = cls(_settings(**skw))
|
||||
assert await svc.generate("salut") == "Bonjour le monde"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_stream_chat_yields_tokens(cls, url, skw, supports_json, label):
|
||||
respx.post(url).mock(return_value=httpx.Response(200, text=_sse("A", "B", "C")))
|
||||
svc = cls(_settings(**skw))
|
||||
tokens = [t async for t in svc.stream_chat([ChatMessage(role="user", content="hi")])]
|
||||
assert tokens == ["A", "B", "C"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_payload_system_prompt_and_temperature(cls, url, skw, supports_json, label):
|
||||
route = respx.post(url).mock(return_value=httpx.Response(200, text=_sse("x")))
|
||||
svc = cls(_settings(**skw))
|
||||
_ = [t async for t in svc.stream_chat(
|
||||
[ChatMessage(role="user", content="Q")],
|
||||
system_prompt="SYS",
|
||||
temperature=0.5,
|
||||
)]
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
assert body["model"] == "m"
|
||||
assert body["stream"] is True
|
||||
assert body["messages"][0] == {"role": "system", "content": "SYS"}
|
||||
assert body["messages"][-1] == {"role": "user", "content": "Q"}
|
||||
assert body["temperature"] == 0.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_payload_omits_temperature_when_none(cls, url, skw, supports_json, label):
|
||||
route = respx.post(url).mock(return_value=httpx.Response(200, text=_sse("x")))
|
||||
svc = cls(_settings(**skw))
|
||||
await svc.generate("p")
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
assert "temperature" not in body
|
||||
# Sans system_prompt, generate envoie un unique message user.
|
||||
assert body["messages"] == [{"role": "user", "content": "p"}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_response_format_json_only_when_supported(cls, url, skw, supports_json, label):
|
||||
route = respx.post(url).mock(return_value=httpx.Response(200, text=_sse("{}")))
|
||||
svc = cls(_settings(**skw))
|
||||
await svc.generate("p", output_format="json")
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
if supports_json:
|
||||
assert body["response_format"] == {"type": "json_object"}
|
||||
else:
|
||||
assert "response_format" not in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_authorization_header_bearer(cls, url, skw, supports_json, label):
|
||||
route = respx.post(url).mock(return_value=httpx.Response(200, text=_sse("x")))
|
||||
svc = cls(_settings(**skw))
|
||||
await svc.generate("p")
|
||||
assert route.calls.last.request.headers["Authorization"] == "Bearer k"
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_openrouter_attribution_headers():
|
||||
route = respx.post("https://openrouter.ai/api/v1/chat/completions").mock(
|
||||
return_value=httpx.Response(200, text=_sse("x")))
|
||||
svc = OpenRouterLLMProvider(_settings(openrouter_api_key="k", openrouter_model="m"))
|
||||
await svc.generate("p")
|
||||
headers = route.calls.last.request.headers
|
||||
assert headers["HTTP-Referer"] == "https://loremind.app"
|
||||
assert headers["X-Title"] == "LoreMind"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_http_error_translated_to_provider_error(cls, url, skw, supports_json, label):
|
||||
respx.post(url).mock(return_value=httpx.Response(429, text="quota exceeded"))
|
||||
svc = cls(_settings(**skw))
|
||||
with pytest.raises(LLMProviderError) as exc:
|
||||
await svc.generate("p")
|
||||
msg = str(exc.value)
|
||||
assert label in msg
|
||||
assert "429" in msg
|
||||
assert "quota exceeded" in msg
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_gemini_rejected_key_gives_actionable_message():
|
||||
respx.post(
|
||||
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
|
||||
).mock(return_value=httpx.Response(403, text="API key not valid"))
|
||||
svc = GeminiLLMProvider(_settings(gemini_api_key="k", gemini_model="m"))
|
||||
with pytest.raises(LLMProviderError) as exc:
|
||||
await svc.generate("p")
|
||||
assert "refusée par Google" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_sse_skips_keepalive_and_malformed_lines(cls, url, skw, supports_json, label):
|
||||
body = "\n".join([
|
||||
": OPENROUTER PROCESSING", # commentaire keep-alive
|
||||
"",
|
||||
"data: not-json", # JSON invalide -> ignoré
|
||||
"",
|
||||
"data: " + json.dumps({"choices": []}), # pas de choix -> ignoré
|
||||
"",
|
||||
"data: " + json.dumps({"choices": [{"delta": {}}]}), # delta sans content -> ignoré
|
||||
"",
|
||||
"data: " + json.dumps({"choices": [{"delta": {"content": "OK"}}]}),
|
||||
"",
|
||||
"data: [DONE]",
|
||||
"",
|
||||
])
|
||||
respx.post(url).mock(return_value=httpx.Response(200, text=body))
|
||||
svc = cls(_settings(**skw))
|
||||
assert await svc.generate("p") == "OK"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, skw", [
|
||||
pytest.param(OpenRouterLLMProvider, dict(openrouter_api_key=""), id="openrouter"),
|
||||
pytest.param(GeminiLLMProvider, dict(gemini_api_key=""), id="gemini"),
|
||||
pytest.param(MistralLLMProvider, dict(mistral_api_key=""), id="mistral"),
|
||||
])
|
||||
def test_missing_api_key_raises_at_construction(cls, skw):
|
||||
with pytest.raises(LLMProviderError):
|
||||
cls(_settings(**skw))
|
||||
|
||||
|
||||
# --- Modèles à raisonnement : `content` en liste de morceaux typés -----------
|
||||
|
||||
def _sse_deltas(*contents: object) -> str:
|
||||
"""Comme `_sse`, mais `content` peut être une liste de morceaux typés."""
|
||||
lines: list[str] = []
|
||||
for c in contents:
|
||||
lines.append("data: " + json.dumps({"choices": [{"delta": {"content": c}}]}))
|
||||
lines.append("")
|
||||
lines += ["data: [DONE]", ""]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# Les trois phases d'un flux Mistral Large 4 : réflexion, fin de réflexion + début
|
||||
# de la réponse dans la même liste, puis suite de la réponse en texte simple.
|
||||
_REASONING_STREAM = _sse_deltas(
|
||||
[{"type": "thinking", "thinking": [{"type": "text", "text": "L'utilisateur veut"}]}],
|
||||
[{"type": "thinking", "thinking": [{"type": "text", "text": " un mot."}]}],
|
||||
[{"type": "thinking", "thinking": [], "closed": True}, {"type": "text", "text": "Bon"}],
|
||||
"jour",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_generate_keeps_only_the_answer_of_a_reasoning_model(cls, url, skw, supports_json, label):
|
||||
respx.post(url).mock(return_value=httpx.Response(200, text=_REASONING_STREAM))
|
||||
svc = cls(_settings(**skw))
|
||||
assert await svc.generate("x", output_format="json") == "Bonjour"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_stream_chat_hides_the_thinking_of_a_reasoning_model(cls, url, skw, supports_json, label):
|
||||
respx.post(url).mock(return_value=httpx.Response(200, text=_REASONING_STREAM))
|
||||
svc = cls(_settings(**skw))
|
||||
tokens = [t async for t in svc.stream_chat([ChatMessage(role="user", content="x")])]
|
||||
assert tokens == ["Bon", "jour"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls, url, skw, supports_json, label", CASES)
|
||||
@respx.mock
|
||||
async def test_generate_survives_a_reasoning_only_stream(cls, url, skw, supports_json, label):
|
||||
"""Que de la réflexion, aucune réponse : chaîne vide, pas d'exception de type."""
|
||||
body = _sse_deltas([{"type": "thinking", "thinking": [{"type": "text", "text": "…"}]}])
|
||||
respx.post(url).mock(return_value=httpx.Response(200, text=body))
|
||||
svc = cls(_settings(**skw))
|
||||
assert await svc.generate("x") == ""
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Mise en page d'une page de PDF : ordre de lecture par colonnes, rangées de tableau."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.infrastructure.pdf_layout import (
|
||||
CELL_SEPARATOR, LayoutBlock, LayoutLine, hoist_titles, place_lines, reading_order, split_cells,
|
||||
without_overprints,
|
||||
)
|
||||
|
||||
WIDTH, HEIGHT = 600.0, 800.0
|
||||
PARAGRAPH = "Texte d'un paragraphe assez long pour dessiner une colonne. " * 4
|
||||
|
||||
|
||||
def line(x0: float, y0: float, x1: float, text: str, size: float = 10.0) -> LayoutLine:
|
||||
return LayoutLine(x0, y0, x1, y0 + size, text, size)
|
||||
|
||||
|
||||
def block(x0: float, y0: float, x1: float, y1: float, *lines: LayoutLine) -> LayoutBlock:
|
||||
return LayoutBlock(x0, y0, x1, y1, list(lines))
|
||||
|
||||
|
||||
def paragraph(x0: float, y0: float, x1: float, y1: float, text: str = PARAGRAPH) -> LayoutBlock:
|
||||
return block(x0, y0, x1, y1, line(x0, y0, x1, text))
|
||||
|
||||
|
||||
def texts(blocks: list[LayoutBlock]) -> list[str]:
|
||||
return [b.lines[0].text[:12] for b in blocks]
|
||||
|
||||
|
||||
# --- ordre de lecture ------------------------------------------------------------------------
|
||||
|
||||
def _two_columns_out_of_order() -> list[LayoutBlock]:
|
||||
"""Deux colonnes nettes, dessinées dans le désordre : bas à droite, bas à gauche, haut à
|
||||
gauche, haut à droite (vu dans un vrai livre)."""
|
||||
return [
|
||||
paragraph(310, 400, 560, 700, "D bas droite " + PARAGRAPH),
|
||||
paragraph(40, 400, 290, 700, "B bas gauche " + PARAGRAPH),
|
||||
paragraph(40, 100, 290, 380, "A haut gauche " + PARAGRAPH),
|
||||
paragraph(310, 100, 560, 380, "C haut droite " + PARAGRAPH),
|
||||
]
|
||||
|
||||
|
||||
def test_a_page_drawn_out_of_order_is_read_column_by_column():
|
||||
ordered = reading_order(_two_columns_out_of_order(), WIDTH, HEIGHT)
|
||||
assert [b.lines[0].text[0] for b in ordered] == ["A", "B", "C", "D"]
|
||||
|
||||
|
||||
def test_a_page_already_in_order_is_left_untouched():
|
||||
blocks = [paragraph(40, 100, 290, 380), paragraph(40, 400, 290, 700),
|
||||
paragraph(310, 100, 560, 380), paragraph(310, 400, 560, 700)]
|
||||
assert reading_order(blocks, WIDTH, HEIGHT) is blocks
|
||||
|
||||
|
||||
def test_a_full_width_block_separates_two_bands():
|
||||
blocks = [
|
||||
paragraph(310, 450, 560, 700, "E droite, sous le titre " + PARAGRAPH),
|
||||
paragraph(40, 450, 290, 700, "D gauche, sous le titre " + PARAGRAPH),
|
||||
paragraph(40, 400, 560, 430, "C titre pleine largeur " + PARAGRAPH),
|
||||
paragraph(310, 100, 560, 380, "B droite, au-dessus " + PARAGRAPH),
|
||||
paragraph(40, 100, 290, 380, "A gauche, au-dessus " + PARAGRAPH),
|
||||
]
|
||||
assert [b.lines[0].text[0] for b in reading_order(blocks, WIDTH, HEIGHT)] == ["A", "B", "C", "D", "E"]
|
||||
|
||||
|
||||
def test_two_stacked_bands_of_columns_are_read_one_after_the_other():
|
||||
"""Sans bloc pleine largeur entre elles : c'est le grand blanc horizontal qui les sépare.
|
||||
Lue colonne entière par colonne entière, la page coupait une phrase en deux."""
|
||||
blocks = [
|
||||
paragraph(310, 460, 560, 700, "D bas droite " + PARAGRAPH),
|
||||
paragraph(40, 460, 290, 700, "C bas gauche " + PARAGRAPH),
|
||||
paragraph(40, 100, 290, 380, "A haut gauche " + PARAGRAPH),
|
||||
paragraph(310, 100, 560, 380, "B haut droite " + PARAGRAPH),
|
||||
]
|
||||
assert [b.lines[0].text[0] for b in reading_order(blocks, WIDTH, HEIGHT)] == ["A", "B", "C", "D"]
|
||||
|
||||
|
||||
def test_a_block_straddling_two_columns_keeps_the_order_of_the_pdf():
|
||||
"""Double page à quatre colonnes : un petit titre à cheval faisait entremêler deux colonnes."""
|
||||
blocks = _two_columns_out_of_order() + [block(200, 385, 400, 398, line(200, 385, 400, "Titre à cheval"))]
|
||||
assert reading_order(blocks, WIDTH, HEIGHT) is blocks
|
||||
|
||||
|
||||
def test_a_block_outside_every_column_keeps_the_order_of_the_pdf():
|
||||
blocks = _two_columns_out_of_order() + [block(570, 300, 598, 320, line(570, 300, 598, "note de marge"))]
|
||||
assert reading_order(blocks, WIDTH, HEIGHT) is blocks
|
||||
|
||||
|
||||
def test_a_footer_drawn_first_does_not_reorder_the_page():
|
||||
footer = block(40, 770, 200, 785, line(40, 770, 200, "30 | Hell Comes to Bogtown, pied de page répété"))
|
||||
body = [paragraph(40, 100, 290, 700), paragraph(310, 100, 560, 700)]
|
||||
blocks = [footer, *body]
|
||||
assert reading_order(blocks, WIDTH, HEIGHT) is blocks
|
||||
|
||||
|
||||
# --- rangées de tableau ------------------------------------------------------------------------
|
||||
|
||||
def test_cells_at_the_same_height_in_a_block_are_one_row():
|
||||
row = block(40, 100, 560, 110, line(40, 100, 90, "Dagger"), line(150, 100, 260, "1d4+DEX piercing"),
|
||||
line(300, 100, 380, "Light, Thrown 4"), line(520, 100, 560, "3 gp"))
|
||||
placed = place_lines([row], WIDTH, HEIGHT)
|
||||
assert [(p.text, p.cells) for p in placed] == [("Dagger | 1d4+DEX piercing | Light, Thrown 4 | 3 gp", 4)]
|
||||
|
||||
|
||||
def test_cells_of_a_row_spread_over_several_blocks_are_gathered():
|
||||
blocks = [
|
||||
paragraph(40, 100, 560, 300), # dessine la colonne
|
||||
block(40, 400, 120, 410, line(40, 400, 120, "Wooden Buckler")),
|
||||
block(300, 400, 320, 410, line(300, 400, 320, "+2")),
|
||||
block(500, 400, 540, 410, line(500, 400, 540, "5 gp")),
|
||||
block(40, 415, 120, 425, line(40, 415, 120, "Iron Shield")),
|
||||
block(300, 415, 320, 425, line(300, 415, 320, "+3")),
|
||||
block(500, 415, 540, 425, line(500, 415, 540, "20 gp")),
|
||||
]
|
||||
placed = place_lines(blocks, WIDTH, HEIGHT)
|
||||
assert [p.text for p in placed[-2:]] == ["Wooden Buckler | +2 | 5 gp", "Iron Shield | +3 | 20 gp"]
|
||||
assert placed[-1].cells == 3
|
||||
|
||||
|
||||
def test_two_lone_labels_at_the_same_height_are_not_a_table_row():
|
||||
"""Double colonne de sorts : « CANTRIP » ouvre un sort à gauche, « TIER 4 » un autre à droite."""
|
||||
blocks = [
|
||||
paragraph(40, 100, 560, 300),
|
||||
block(40, 400, 80, 408, line(40, 400, 80, "CANTRIP", 8.0)),
|
||||
block(40, 410, 260, 450, line(40, 410, 260, "Rebuke : la cible subit 1d8 dégâts radiants,"),
|
||||
line(40, 422, 260, "et ne peut plus attaquer ce tour.")),
|
||||
block(300, 400, 335, 408, line(300, 400, 335, "TIER 4", 8.0)),
|
||||
block(300, 410, 540, 450, line(300, 410, 540, "Shield of Justice : vos attaquants sont aveuglés"),
|
||||
line(300, 422, 540, "jusqu'à la fin de leur prochain tour.")),
|
||||
block(40, 520, 80, 528, line(40, 520, 80, "TIER 1", 8.0)),
|
||||
block(300, 520, 335, 528, line(300, 520, 335, "TIER 6", 8.0)),
|
||||
]
|
||||
read = [p.text for p in place_lines(blocks, WIDTH, HEIGHT)]
|
||||
assert "CANTRIP" in read and "TIER 4" in read and "TIER 1" in read and "TIER 6" in read
|
||||
assert not any(" | " in text for text in read)
|
||||
|
||||
|
||||
def test_lines_of_a_paragraph_are_never_pulled_into_a_neighbouring_row():
|
||||
"""Un encadré à la hauteur d'un tableau y laissait des bouts de phrase."""
|
||||
sidebar = block(330, 395, 560, 430, line(330, 395, 560, "Deflect! Heroes proficient with shields"),
|
||||
line(330, 410, 560, "may reduce the damage of an attack."))
|
||||
blocks = [
|
||||
paragraph(40, 100, 560, 300),
|
||||
block(40, 395, 120, 405, line(40, 395, 120, "Wooden Buckler")),
|
||||
block(200, 395, 220, 405, line(200, 395, 220, "+2")),
|
||||
block(40, 410, 120, 420, line(40, 410, 120, "Iron Shield")),
|
||||
block(200, 410, 220, 420, line(200, 410, 220, "+3")),
|
||||
sidebar,
|
||||
]
|
||||
placed = place_lines(blocks, WIDTH, HEIGHT)
|
||||
assert "Wooden Buckler | +2" in [p.text for p in placed]
|
||||
assert "Deflect! Heroes proficient with shields" in [p.text for p in placed]
|
||||
|
||||
|
||||
def test_a_bullet_and_its_text_are_an_ordinary_line():
|
||||
item = block(40, 100, 560, 110, line(40, 100, 46, "•"), line(60, 100, 560, "2-handed. Can be held in a single hand."))
|
||||
placed = place_lines([item], WIDTH, HEIGHT)
|
||||
assert [(p.text, p.cells) for p in placed] == [("• 2-handed. Can be held in a single hand.", 1)]
|
||||
|
||||
|
||||
def test_two_columns_of_text_at_the_same_height_are_not_a_table():
|
||||
blocks = [block(40, 100, 290, 130, line(40, 100, 290, "Le combat se joue en tours et chaque héros " * 2),
|
||||
line(40, 115, 290, "agit une fois. " * 6)),
|
||||
block(310, 100, 560, 130, line(310, 100, 560, "La magie coûte du mana au lanceur de sorts. " * 2),
|
||||
line(310, 115, 560, "Un sort rate sur un 1. " * 4))]
|
||||
assert all(p.cells == 1 for p in place_lines(blocks, WIDTH, HEIGHT))
|
||||
|
||||
|
||||
def test_lines_at_the_top_and_bottom_of_the_page_are_flagged():
|
||||
blocks = [block(40, 20, 300, 32, line(40, 20, 300, "NIMBLE — RÈGLES")),
|
||||
paragraph(40, 100, 560, 300),
|
||||
block(280, 770, 300, 782, line(280, 770, 300, "12"))]
|
||||
assert [p.edge for p in place_lines(blocks, WIDTH, HEIGHT)] == [True, False, True]
|
||||
|
||||
|
||||
# --- grands titres dessinés après leur texte ---------------------------------------------------
|
||||
|
||||
def _spell(x0: float, y0: float, name: str) -> LayoutBlock:
|
||||
return block(x0, y0, x0 + 160, y0 + 60, LayoutLine(x0, y0, x0 + 160, y0 + 12, name, 12.0),
|
||||
line(x0, y0 + 14, x0 + 160, "Portée 8. Dégâts 2d12, puis la cible est entravée jusqu'à la fin."))
|
||||
|
||||
|
||||
def _big_title(x0: float, y0: float, text: str) -> LayoutBlock:
|
||||
return block(x0, y0, x0 + 150, y0 + 30, LayoutLine(x0, y0, x0 + 150, y0 + 30, text, 25.0))
|
||||
|
||||
|
||||
def test_a_big_title_drawn_after_the_text_it_heads_is_put_back_above_it():
|
||||
"""Double page d'un livre de sorts : chaque moitié a deux colonnes de sorts sous son titre,
|
||||
mais le PDF trace les sorts d'abord, le titre de l'école ensuite."""
|
||||
width, height = 840.0, 600.0
|
||||
radiant = [_spell(30, 80, "Rebuke"), _spell(30, 200, "Heal"), _spell(220, 80, "Vengeance")]
|
||||
necrotic = [block(450, 100, 475, 110, line(450, 100, 475, "CANTRIP", 7.5)),
|
||||
_spell(450, 115, "Entice"), _spell(640, 115, "Vigor Mortis")]
|
||||
radiant_title, necrotic_title = _big_title(150, 30, "Radiant Spells"), _big_title(570, 60, "Necrotic Spells")
|
||||
redeem = _spell(80, 520, "Redeem")
|
||||
drawn = [*radiant, radiant_title, redeem, *necrotic, necrotic_title]
|
||||
ordered = hoist_titles(drawn, width, height)
|
||||
assert ordered == [radiant_title, *radiant, redeem, necrotic_title, *necrotic]
|
||||
# Par place_lines, le texte suit : le titre de l'école précède ses sorts.
|
||||
read = [placed.text for placed in place_lines(drawn, width, height)]
|
||||
assert read.index("Radiant Spells") < read.index("Rebuke") < read.index("Redeem")
|
||||
assert read.index("Redeem") < read.index("Necrotic Spells") < read.index("CANTRIP") < read.index("Entice")
|
||||
|
||||
|
||||
def test_a_label_brushing_the_bottom_of_a_big_title_is_still_below_it():
|
||||
"""La boîte d'un titre de 25 points descend sous ses lettres : l'étiquette « CANTRIP » du
|
||||
premier sort la frôle, sans être au-dessus du titre."""
|
||||
title = _big_title(150, 30, "Radiant Spells") # boîte de 30 à 60
|
||||
label = block(30, 57, 60, 66, line(30, 57, 60, "CANTRIP", 7.5))
|
||||
spell = _spell(30, 70, "Rebuke")
|
||||
assert hoist_titles([label, spell, title], 840.0, 600.0) == [title, label, spell]
|
||||
|
||||
|
||||
def test_two_subheadings_at_the_same_height_in_two_columns_are_not_a_table_row():
|
||||
left = block(30, 200, 190, 212, LayoutLine(30, 200, 190, 212, "Heal | 1 Action", 12.0, 2))
|
||||
right = block(220, 200, 380, 212, LayoutLine(220, 200, 380, 212, "Sacrifice | 1 Action", 12.0, 2))
|
||||
texts_ = [paragraph(30, 216, 190, 260), paragraph(220, 216, 380, 260)]
|
||||
read = [placed.text for placed in place_lines([left, texts_[0], right, texts_[1]], 840.0, 600.0)]
|
||||
assert "Heal | 1 Action" in read and "Sacrifice | 1 Action" in read
|
||||
# Des cellules à la taille du texte courant restent une rangée.
|
||||
cells = [block(30, 300, 80, 310, line(30, 300, 80, "Épée")), block(110, 300, 160, 310, line(110, 300, 160, "1d8")),
|
||||
block(30, 314, 80, 324, line(30, 314, 80, "Dague")), block(110, 314, 160, 324, line(110, 314, 160, "1d4"))]
|
||||
assert "Épée | 1d8" in [placed.text for placed in place_lines([*texts_, *cells], 840.0, 600.0)]
|
||||
|
||||
|
||||
def test_a_title_already_in_place_or_heading_another_column_does_not_move():
|
||||
# Page simple, deux colonnes : le titre en tête de la seconde ne passe pas devant la première.
|
||||
first = [paragraph(40, 60, 280, 300), paragraph(40, 320, 280, 560)]
|
||||
title = _big_title(320, 60, "Magie")
|
||||
second = [paragraph(320, 100, 560, 300)]
|
||||
drawn = [*first, title, *second]
|
||||
assert hoist_titles(drawn, WIDTH, HEIGHT) == drawn
|
||||
# Un titre placé plus bas que ce qui le précède reste où il est.
|
||||
lower = [paragraph(40, 60, 560, 200), _big_title(40, 240, "Combat"), paragraph(40, 290, 560, 400)]
|
||||
assert hoist_titles(lower, WIDTH, HEIGHT) == lower
|
||||
|
||||
|
||||
def test_a_title_does_not_climb_over_a_block_that_spans_the_page():
|
||||
banner = paragraph(40, 200, 560, 240) # barre la page, sous le titre
|
||||
below = paragraph(40, 260, 280, 400)
|
||||
title = _big_title(40, 150, "Rituels")
|
||||
drawn = [paragraph(40, 60, 560, 120), banner, below, title]
|
||||
# Le titre remonte devant le bloc qu'il coiffe, pas au-delà de la bande qui barre la page.
|
||||
assert hoist_titles(drawn, WIDTH, HEIGHT) == [drawn[0], banner, title, below]
|
||||
|
||||
|
||||
def test_a_title_drawn_twice_at_the_same_place_is_read_once():
|
||||
title = line(50, 100, 120, "Notes", 18.0)
|
||||
twice = block(50, 100, 300, 140, title, LayoutLine(50.2, 100.1, 120.1, 118.0, "Notes", 18.0),
|
||||
line(50, 120, 300, "Avant de jouer cette aventure, lisez-la en entier."))
|
||||
placed = place_lines([twice], WIDTH, HEIGHT)
|
||||
assert [p.text for p in placed] == ["Notes", "Avant de jouer cette aventure, lisez-la en entier."]
|
||||
# Un bloc qui ne contient que la copie disparaît ; un bloc intact reste le même objet.
|
||||
copy = block(50, 100, 120, 118, title)
|
||||
intact = paragraph(50, 200, 300, 240)
|
||||
assert without_overprints([block(50, 100, 120, 118, title), copy, intact])[1:] == [intact]
|
||||
|
||||
|
||||
def test_a_chapter_tab_in_the_side_margin_is_not_text():
|
||||
text = paragraph(60, 100, 540, 140)
|
||||
tab = block(578, 60, 590, 260, LayoutLine(578, 60, 590, 80, "1", 18.0),
|
||||
LayoutLine(578, 90, 590, 260, "Les Passagers du destin", 9.0))
|
||||
left_tab = block(8, 60, 20, 260, LayoutLine(8, 90, 20, 260, "Les Passagers du destin", 9.0))
|
||||
placed = place_lines([tab, text, left_tab], WIDTH, HEIGHT)
|
||||
assert [p.text for p in placed] == [PARAGRAPH]
|
||||
# Une ligne qui dépasse de la marge reste du texte.
|
||||
wide = block(8, 300, 300, 312, line(8, 300, 300, "Une note qui commence dans la marge."))
|
||||
assert len(place_lines([text, wide], WIDTH, HEIGHT)) == 2
|
||||
|
||||
|
||||
def test_the_same_words_elsewhere_on_the_page_are_kept():
|
||||
rows = block(50, 100, 300, 140, line(50, 100, 120, "1d6"), line(50, 112, 120, "1d6"), line(200, 100, 270, "1d6"))
|
||||
assert len(without_overprints([rows])[0].lines) == 3
|
||||
|
||||
|
||||
def test_no_text_no_lines():
|
||||
assert place_lines([], WIDTH, HEIGHT) == []
|
||||
assert place_lines([LayoutBlock(0, 0, 10, 10, [])], WIDTH, HEIGHT) == []
|
||||
|
||||
|
||||
# --- cellules d'une ligne ------------------------------------------------------------------------
|
||||
|
||||
def test_a_wide_gap_in_a_line_separates_two_cells():
|
||||
spans = [(40.0, 80.0, "Dagger"), (150.0, 260.0, "1d4+DEX "), (260.0, 300.0, "piercing"), (520.0, 560.0, "3 gp")]
|
||||
assert split_cells(spans, 10.0) == ["Dagger", "1d4+DEX piercing", "3 gp"]
|
||||
|
||||
|
||||
def test_words_of_a_sentence_are_one_cell():
|
||||
spans = [(40.0, 120.0, "Le combat "), (122.0, 200.0, "se joue "), (203.0, 300.0, "en tours.")]
|
||||
assert split_cells(spans, 10.0) == ["Le combat se joue en tours."]
|
||||
|
||||
|
||||
def test_a_number_and_its_text_are_one_cell():
|
||||
assert split_cells([(40.0, 52.0, "10"), (80.0, 400.0, "Londar s'est fait sauter.")], 10.0) == [
|
||||
"10 Londar s'est fait sauter."]
|
||||
assert split_cells([(40.0, 46.0, "•"), (70.0, 400.0, "Portée 8")], 10.0) == ["• Portée 8"]
|
||||
|
||||
|
||||
def test_the_cell_separator_is_the_one_the_structure_splitter_expects():
|
||||
from app.application.pdf_structure import CELL_SEPARATOR as expected
|
||||
assert CELL_SEPARATOR == expected
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Découpage d'un livre par la structure de son PDF (signets, titres), sans IA."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.pdf_structure import BOOKMARKS, HEADINGS, NONE, split_by_structure
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage, TextLine, TocEntry
|
||||
|
||||
BODY = 10.0
|
||||
TITLE = 24.0
|
||||
SUBTITLE = 16.0
|
||||
|
||||
|
||||
class Book:
|
||||
"""Fabrique un livre ligne par ligne : chaque appel à `para` ouvre un nouveau bloc."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.lines: list[TextLine] = []
|
||||
self.page = 0
|
||||
self._block = 0
|
||||
|
||||
def next_page(self) -> "Book":
|
||||
self.page += 1
|
||||
self._block = 0
|
||||
return self
|
||||
|
||||
def title(self, text: str, size: float = TITLE) -> "Book":
|
||||
return self.para(text, size=size)
|
||||
|
||||
def para(self, *lines: str, size: float = BODY) -> "Book":
|
||||
for text in lines:
|
||||
self.lines.append(TextLine(self.page, self._block, text, size))
|
||||
self._block += 1
|
||||
return self
|
||||
|
||||
def doc(self, toc: list[TocEntry] | None = None) -> ExtractedDocument:
|
||||
pages = [ExtractedPage(index=p, text="texte", used_ocr=False) for p in range(self.page + 1)]
|
||||
return ExtractedDocument(pages=pages, toc=toc or [], lines=self.lines)
|
||||
|
||||
|
||||
def _three_chapters() -> Book:
|
||||
return (Book()
|
||||
.title("Combat").para("Le combat se joue en tours.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
|
||||
|
||||
def _toc(*entries: tuple[int, str, int]) -> list[TocEntry]:
|
||||
return [TocEntry(level=level, title=title, page=page) for level, title, page in entries]
|
||||
|
||||
|
||||
# --- signets --------------------------------------------------------------------------------
|
||||
|
||||
def test_bookmarks_give_the_sections_of_the_book():
|
||||
split = split_by_structure(_three_chapters().doc(_toc((1, "Combat", 1), (1, "Magie", 2), (1, "Repos", 3))))
|
||||
assert split.method == BOOKMARKS
|
||||
assert split.sections == {
|
||||
"Combat": "Le combat se joue en tours.",
|
||||
"Magie": "La magie coûte du mana.",
|
||||
"Repos": "Une nuit de repos soigne tout.",
|
||||
}
|
||||
|
||||
|
||||
def test_a_small_chapter_stays_whole_with_its_subsections_as_subheadings():
|
||||
book = (Book().title("Combat").para("Le combat se joue en tours.")
|
||||
.title("Attaquer", SUBTITLE).para("Lancez le dé de dégâts.")
|
||||
.title("Défendre", SUBTITLE).para("Réduisez les dégâts.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
toc = _toc((1, "Combat", 1), (2, "Attaquer", 1), (2, "Défendre", 1), (1, "Magie", 2), (1, "Repos", 3))
|
||||
split = split_by_structure(book.doc(toc))
|
||||
assert list(split.sections) == ["Combat", "Magie", "Repos"]
|
||||
assert split.sections["Combat"] == (
|
||||
"Le combat se joue en tours.\n\n### Attaquer\n\nLancez le dé de dégâts.\n\n### Défendre\n\nRéduisez les dégâts.")
|
||||
|
||||
|
||||
def test_a_big_chapter_is_given_by_its_subsections():
|
||||
book = (Book().title("Combat").para("Intro.")
|
||||
.title("Attaquer", SUBTITLE).para("Lancez le dé. " * 30)
|
||||
.title("Défendre", SUBTITLE).para("Réduisez les dégâts. " * 30)
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
toc = _toc((1, "Combat", 1), (2, "Attaquer", 1), (2, "Défendre", 1), (1, "Magie", 2), (1, "Repos", 3))
|
||||
split = split_by_structure(book.doc(toc), max_section_chars=500)
|
||||
assert list(split.sections) == ["Combat › Attaquer", "Combat › Défendre", "Magie", "Repos"]
|
||||
# L'introduction du chapitre, trop courte pour faire une section, ouvre la première.
|
||||
assert split.sections["Combat › Attaquer"].startswith("Intro.\n\nLancez le dé.")
|
||||
|
||||
|
||||
def test_a_substantial_chapter_introduction_is_a_section_of_its_own():
|
||||
book = (Book().title("Combat").para("Présentation du combat. " * 12)
|
||||
.title("Attaquer", SUBTITLE).para("Lancez le dé. " * 30)
|
||||
.title("Défendre", SUBTITLE).para("Réduisez les dégâts. " * 30)
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
toc = _toc((1, "Combat", 1), (2, "Attaquer", 1), (2, "Défendre", 1), (1, "Magie", 2), (1, "Repos", 3))
|
||||
split = split_by_structure(book.doc(toc), max_section_chars=500)
|
||||
assert list(split.sections)[:3] == ["Combat", "Combat › Attaquer", "Combat › Défendre"]
|
||||
|
||||
|
||||
def test_a_bookmark_missing_from_its_page_starts_at_the_top_of_the_page():
|
||||
# Titre dessiné dans une illustration : le signet existe, pas la ligne de texte.
|
||||
book = (Book().para("Le combat se joue en tours.")
|
||||
.next_page().para("La magie coûte du mana.")
|
||||
.next_page().para("Une nuit de repos soigne tout."))
|
||||
split = split_by_structure(book.doc(_toc((1, "Combat", 1), (1, "Magie", 2), (1, "Repos", 3))))
|
||||
assert split.sections == {
|
||||
"Combat": "Le combat se joue en tours.",
|
||||
"Magie": "La magie coûte du mana.",
|
||||
"Repos": "Une nuit de repos soigne tout.",
|
||||
}
|
||||
|
||||
|
||||
def test_titles_found_by_size_detail_what_bookmarks_do_not():
|
||||
book = (Book().title("Magie").para("La magie coûte du mana.")
|
||||
.title("Sorts de feu", SUBTITLE).para("Dard de flamme. " * 20)
|
||||
.title("Sorts de glace", SUBTITLE).para("Lance de glace. " * 20)
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout.")
|
||||
.next_page().title("Glossaire").para("Avantage : lancez un dé de plus."))
|
||||
split = split_by_structure(book.doc(_toc((1, "Magie", 1), (1, "Repos", 2), (1, "Glossaire", 3))),
|
||||
max_section_chars=400)
|
||||
assert split.method == BOOKMARKS
|
||||
assert list(split.sections) == ["Magie › Sorts de feu", "Magie › Sorts de glace", "Repos", "Glossaire"]
|
||||
|
||||
|
||||
# --- titres repérés à leur taille ---------------------------------------------------------------
|
||||
|
||||
def test_without_bookmarks_big_titles_give_the_sections():
|
||||
split = split_by_structure(_three_chapters().doc())
|
||||
assert split.method == HEADINGS
|
||||
assert list(split.sections) == ["Combat", "Magie", "Repos"]
|
||||
|
||||
|
||||
def test_a_title_on_two_lines_is_one_title():
|
||||
book = (Book().para("GARDEN OF", "DEATH", size=TITLE).para("Un jardin mortel.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert list(split_by_structure(book.doc()).sections) == ["GARDEN OF DEATH", "Magie", "Repos"]
|
||||
|
||||
|
||||
def test_a_slightly_bigger_line_is_a_subheading_inside_its_section():
|
||||
book = (Book().title("Combat").para("Le combat se joue en tours.")
|
||||
.para("Surprise", size=11.5).para("La surprise donne l'avantage.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert split_by_structure(book.doc()).sections["Combat"] == (
|
||||
"Le combat se joue en tours.\n\n#### Surprise\n\nLa surprise donne l'avantage.")
|
||||
|
||||
|
||||
# --- mise en forme, sans réécriture ----------------------------------------------------------------
|
||||
|
||||
def test_lines_of_a_paragraph_are_joined_and_split_words_reunited():
|
||||
book = (Book().title("Combat")
|
||||
.para("Le combat se joue en tours et chaque héros agit une fois avec son équi",
|
||||
"pement. Un mot coupé par un tiret est réuni : atta-", "quer coûte une action.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert split_by_structure(book.doc()).sections["Combat"] == (
|
||||
"Le combat se joue en tours et chaque héros agit une fois avec son équipement. "
|
||||
"Un mot coupé par un tiret est réuni : attaquer coûte une action.")
|
||||
|
||||
|
||||
def test_words_cut_by_a_typographic_hyphen_are_reunited_and_compound_names_keep_theirs():
|
||||
book = (Book().title("Combat")
|
||||
.para("Cet événement n'intervient que si les joueurs piétinent com‑",
|
||||
"plètement. L'aubergiste Finnlor Trois‑", "Doigts les met sur la piste, pro‐",
|
||||
"gressivement.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert split_by_structure(book.doc()).sections["Combat"] == (
|
||||
"Cet événement n'intervient que si les joueurs piétinent complètement. "
|
||||
"L'aubergiste Finnlor Trois‑Doigts les met sur la piste, progressivement.")
|
||||
|
||||
|
||||
def test_a_paragraph_cut_by_a_page_break_is_joined_again():
|
||||
book = (Book().title("Combat").para("Le combat se joue en tours et chaque héros")
|
||||
.next_page().para("agit une fois.").title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert split_by_structure(book.doc()).sections["Combat"] == "Le combat se joue en tours et chaque héros agit une fois."
|
||||
|
||||
|
||||
def test_bullets_become_a_list():
|
||||
book = (Book().title("Combat").para("Vous pouvez :", "• attaquer", "• vous déplacer")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert split_by_structure(book.doc()).sections["Combat"] == "Vous pouvez :\n\n- attaquer\n\n- vous déplacer"
|
||||
|
||||
|
||||
def test_page_numbers_running_headers_and_printed_contents_are_left_out():
|
||||
book = Book()
|
||||
for page in range(8):
|
||||
if page:
|
||||
book.next_page()
|
||||
book.para("NIMBLE — RÈGLES").title(f"Chapitre {page + 1}").para(f"Texte du chapitre {page + 1}.").para(str(page + 1))
|
||||
book.lines.insert(1, TextLine(0, 9, "Combat........................12", BODY))
|
||||
sections = split_by_structure(book.doc()).sections
|
||||
assert len(sections) == 8
|
||||
assert sections["Chapitre 3"] == "Texte du chapitre 3."
|
||||
assert all("NIMBLE" not in text and "....." not in text for text in sections.values())
|
||||
|
||||
|
||||
def test_what_comes_before_the_first_title_is_the_preamble():
|
||||
book = (Book().para("Crédits et remerciements. " * 10)
|
||||
.next_page().title("Combat").para("Le combat se joue en tours.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert list(split_by_structure(book.doc()).sections)[0] == "Préambule"
|
||||
assert list(split_by_structure(book.doc(), preamble_title="Front matter").sections)[0] == "Front matter"
|
||||
|
||||
|
||||
def test_a_section_without_subsections_that_is_too_long_is_cut_in_parts():
|
||||
book = Book().title("Glossaire")
|
||||
for i in range(40):
|
||||
book.para(f"Terme {i} : " + "définition " * 12)
|
||||
book.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
book.next_page().title("Repos").para("Une nuit de repos soigne tout.")
|
||||
sections = split_by_structure(book.doc(), max_section_chars=2000).sections
|
||||
parts = [title for title in sections if title.startswith("Glossaire")]
|
||||
assert parts[0] == "Glossaire (1/3)" and len(parts) == 3
|
||||
# Rien n'est perdu ni répété d'une partie à l'autre.
|
||||
assert sum(sections[p].count("Terme ") for p in parts) == 40
|
||||
|
||||
|
||||
def test_two_sections_with_the_same_title_do_not_overwrite_each_other():
|
||||
book = (Book().title("Notes").para("Premières notes.")
|
||||
.next_page().title("Notes").para("Secondes notes.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
assert list(split_by_structure(book.doc()).sections) == ["Notes", "Notes (2)", "Repos"]
|
||||
|
||||
|
||||
def test_the_whole_text_of_the_book_is_kept():
|
||||
book = (Book().title("Combat").para("Alpha bravo.")
|
||||
.title("Attaquer", SUBTITLE).para("Charlie delta.")
|
||||
.next_page().title("Magie").para("Echo foxtrot.")
|
||||
.next_page().title("Repos").para("Golf hotel."))
|
||||
everything = " ".join(split_by_structure(book.doc()).sections.values())
|
||||
for word in ("Alpha", "bravo", "Charlie", "delta", "Echo", "foxtrot", "Golf", "hotel", "Attaquer"):
|
||||
assert word in everything
|
||||
|
||||
|
||||
# --- pas de structure : à l'appelant de passer par l'IA --------------------------------------------
|
||||
|
||||
def test_a_scan_with_text_all_the_same_size_has_no_structure():
|
||||
book = Book()
|
||||
for page in range(5):
|
||||
if page:
|
||||
book.next_page()
|
||||
book.para("COMBAT", "Le combat se joue en tours.", "MAGIE", "La magie coûte du mana.", size=11.0)
|
||||
assert split_by_structure(book.doc()).method == NONE
|
||||
assert split_by_structure(book.doc()).sections == {}
|
||||
|
||||
|
||||
def test_an_ocr_page_has_no_size_and_no_title():
|
||||
book = Book()
|
||||
for page in range(4):
|
||||
if page:
|
||||
book.next_page()
|
||||
book.para("COMBAT", "Le combat se joue en tours.", size=0.0)
|
||||
assert split_by_structure(book.doc()).method == NONE
|
||||
|
||||
|
||||
def test_no_lines_no_structure():
|
||||
doc = ExtractedDocument(pages=[ExtractedPage(index=0, text="texte", used_ocr=False)])
|
||||
assert split_by_structure(doc).method == NONE
|
||||
|
||||
|
||||
def test_too_few_titles_for_a_long_book_is_not_a_structure():
|
||||
book = Book().title("Couverture")
|
||||
for _ in range(200):
|
||||
book.next_page().para("Texte d'une page.")
|
||||
book.title("Fin")
|
||||
assert split_by_structure(book.doc()).method == NONE
|
||||
|
||||
|
||||
# --- défauts vus sur un corpus de 185 livres ----------------------------------------------------
|
||||
|
||||
def test_a_label_repeated_inside_the_text_is_part_of_the_book():
|
||||
"""Bestiaire : « Actions » revient sur chaque page, au milieu de la fiche de la créature."""
|
||||
book = Book()
|
||||
for page in range(8):
|
||||
if page:
|
||||
book.next_page()
|
||||
(book.title(f"Créature {page + 1}").para("Une créature redoutable.").para("Classe d'armure 12")
|
||||
.para("Actions").para("12").para("Morsure : 1d6 dégâts.").para("Fin de la fiche.")
|
||||
.para("Encore une ligne.").para("Et une dernière."))
|
||||
sections = split_by_structure(book.doc()).sections
|
||||
assert "Actions" in sections["Créature 3"]
|
||||
# Un nombre seul au milieu de la page (cellule de tableau) n'est pas un numéro de page.
|
||||
assert "\n\n12\n\n" in sections["Créature 3"]
|
||||
|
||||
|
||||
def test_a_single_bookmark_over_the_whole_book_does_not_prefix_every_title():
|
||||
book = (Book().para("Couverture du livre. " * 12)
|
||||
.next_page().title("Combat").para("Le combat se joue en tours.")
|
||||
.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
.next_page().title("Repos").para("Une nuit de repos soigne tout."))
|
||||
toc = _toc((1, "Cover", 1), (2, "Combat", 2), (2, "Magie", 3), (2, "Repos", 4))
|
||||
sections = split_by_structure(book.doc(toc)).sections
|
||||
assert list(sections) == ["Préambule", "Combat", "Magie", "Repos"]
|
||||
assert sections["Préambule"].startswith("Couverture du livre.")
|
||||
|
||||
|
||||
def test_invisible_characters_are_removed_from_titles():
|
||||
book = _three_chapters()
|
||||
toc = _toc((1, "Combat", 1), (1, "Magie", 2), (1, "Repos", 3))
|
||||
assert list(split_by_structure(book.doc(toc)).sections) == ["Combat", "Magie", "Repos"]
|
||||
|
||||
|
||||
# --- tableaux et lignes à cellules ---------------------------------------------------------------
|
||||
|
||||
def test_a_running_head_with_the_page_number_is_removed_even_if_it_never_repeats():
|
||||
book = Book()
|
||||
heads = ["Introduction /3 /3", "4/Grimmsgate", "Grimmsgate/5", "6/The Wilderness", "/11", "- 12 -"]
|
||||
for page, head in enumerate(heads):
|
||||
if page:
|
||||
book.next_page()
|
||||
book.lines.append(TextLine(page, 0, head, BODY, True))
|
||||
book._block = 1
|
||||
book.title(f"Chapitre {page + 1}").para("Dégâts 2d6/tour, portée 9/18 m.").para("Suite du texte.")
|
||||
sections = split_by_structure(book.doc()).sections
|
||||
# L'en-tête part ; une ligne du texte qui contient une barre oblique reste.
|
||||
assert sections["Chapitre 1"] == "Dégâts 2d6/tour, portée 9/18 m.\n\nSuite du texte."
|
||||
assert all("Grimmsgate" not in text and "/3" not in text for text in sections.values())
|
||||
assert sections["Chapitre 5"] == sections["Chapitre 6"] == sections["Chapitre 1"]
|
||||
|
||||
|
||||
def _row(book: Book, text: str, cells: int, size: float = BODY) -> None:
|
||||
book.lines.append(TextLine(book.page, 90 + len(book.lines), text, size, False, cells))
|
||||
|
||||
|
||||
def test_rows_that_follow_each_other_make_a_table():
|
||||
book = Book().title("Armes").para("Les armes de mêlée :")
|
||||
_row(book, "ITEM | DAMAGE | COST", 3)
|
||||
_row(book, "Dagger | 1d4+DEX piercing | 3 gp", 3)
|
||||
_row(book, "Sickle | 1d4+DEX slashing | 10 gp", 3)
|
||||
book.para("Fin du tableau.")
|
||||
book.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
book.next_page().title("Repos").para("Une nuit de repos soigne tout.")
|
||||
assert split_by_structure(book.doc()).sections["Armes"] == (
|
||||
"Les armes de mêlée :\n\n"
|
||||
"| ITEM | DAMAGE | COST |\n| --- | --- | --- |\n"
|
||||
"| Dagger | 1d4+DEX piercing | 3 gp |\n| Sickle | 1d4+DEX slashing | 10 gp |\n\n"
|
||||
"Fin du tableau.")
|
||||
|
||||
|
||||
def test_a_lone_row_and_rows_of_another_width_are_not_forced_into_one_table():
|
||||
book = Book().title("Armes")
|
||||
_row(book, "SHIELDS | DEFENSE | COST", 3)
|
||||
_row(book, "Wooden Buckler | +2 | 5 gp", 3)
|
||||
_row(book, "Dragon Shield | +8", 2)
|
||||
book.next_page().title("Magie").para("La magie coûte du mana.")
|
||||
book.next_page().title("Repos").para("Une nuit de repos soigne tout.")
|
||||
assert split_by_structure(book.doc()).sections["Armes"] == (
|
||||
"| SHIELDS | DEFENSE | COST |\n| --- | --- | --- |\n| Wooden Buckler | +2 | 5 gp |\n\n"
|
||||
"Dragon Shield — +8")
|
||||
|
||||
|
||||
def test_a_big_line_cut_by_a_wide_gap_is_still_a_title():
|
||||
book = Book().title("Magie").para("La magie coûte du mana.")
|
||||
_row(book, "Flame Dart | 1 Action", 2, size=SUBTITLE)
|
||||
book.para("Portée : 10. Dégâts : 1d10.")
|
||||
book.next_page().title("Repos").para("Une nuit de repos soigne tout.")
|
||||
book.next_page().title("Glossaire").para("Avantage : un dé de plus.")
|
||||
assert "### Flame Dart 1 Action\n\nPortée : 10." in split_by_structure(book.doc()).sections["Magie"]
|
||||
|
||||
|
||||
def test_headers_flagged_by_the_extractor_are_removed_wherever_they_are_in_the_page():
|
||||
"""Après une remise en ordre des colonnes, un en-tête n'est plus forcément en tête de page."""
|
||||
book = Book()
|
||||
for page in range(8):
|
||||
if page:
|
||||
book.next_page()
|
||||
book.title(f"Chapitre {page + 1}").para("Début du texte.")
|
||||
book.lines.append(TextLine(page, 50, "NIMBLE — RÈGLES", BODY, True))
|
||||
book.para("Milieu du texte.").para("Fin du texte.").para("Dernière ligne.").para("Vraiment la dernière.")
|
||||
sections = split_by_structure(book.doc()).sections
|
||||
assert sections["Chapitre 3"] == (
|
||||
"Début du texte.\n\nMilieu du texte.\n\nFin du texte.\n\nDernière ligne.\n\nVraiment la dernière.")
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Tests de la réécriture de question autonome (app.application.query_rewrite)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.query_rewrite import standalone_question
|
||||
from app.domain.models import ChatMessage
|
||||
|
||||
|
||||
class FakeLLM:
|
||||
def __init__(self, response: str | None = None, exc: Exception | None = None) -> None:
|
||||
self.response = response
|
||||
self.exc = exc
|
||||
self.called = False
|
||||
|
||||
async def generate(self, prompt, *, temperature=None, output_format=None) -> str:
|
||||
self.called = True
|
||||
if self.exc:
|
||||
raise self.exc
|
||||
return self.response
|
||||
|
||||
|
||||
async def test_single_turn_returns_last_user_without_calling_llm():
|
||||
llm = FakeLLM()
|
||||
q = await standalone_question(llm, [ChatMessage(role="user", content="Qui est Strahd ?")])
|
||||
assert q == "Qui est Strahd ?"
|
||||
assert llm.called is False
|
||||
|
||||
|
||||
async def test_multi_turn_uses_llm_rewrite_and_strips_quotes():
|
||||
llm = FakeLLM(response='"Quelles sont les faiblesses de Strahd ?"')
|
||||
msgs = [
|
||||
ChatMessage(role="user", content="Qui est Strahd ?"),
|
||||
ChatMessage(role="assistant", content="Un vampire."),
|
||||
ChatMessage(role="user", content="Et ses faiblesses ?"),
|
||||
]
|
||||
assert await standalone_question(llm, msgs) == "Quelles sont les faiblesses de Strahd ?"
|
||||
assert llm.called is True
|
||||
|
||||
|
||||
async def test_llm_failure_falls_back_to_last_user():
|
||||
llm = FakeLLM(exc=RuntimeError("LLM HS"))
|
||||
msgs = [ChatMessage(role="user", content="A"), ChatMessage(role="user", content="B")]
|
||||
assert await standalone_question(llm, msgs) == "B"
|
||||
|
||||
|
||||
async def test_suspiciously_long_rewrite_falls_back():
|
||||
llm = FakeLLM(response="x" * 500)
|
||||
msgs = [ChatMessage(role="user", content="A"), ChatMessage(role="user", content="B")]
|
||||
assert await standalone_question(llm, msgs) == "B"
|
||||
|
||||
|
||||
async def test_empty_messages_returns_empty_string():
|
||||
llm = FakeLLM()
|
||||
assert await standalone_question(llm, []) == ""
|
||||
assert llm.called is False
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Tests du reranking LLM des passages RAG (app.application.rerank)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.rerank import pool_size, rerank
|
||||
|
||||
|
||||
class FakeLLM:
|
||||
def __init__(self, response: str | None = None, exc: Exception | None = None) -> None:
|
||||
self.response = response
|
||||
self.exc = exc
|
||||
|
||||
async def generate(self, prompt, *, temperature=None, output_format=None) -> str:
|
||||
if self.exc:
|
||||
raise self.exc
|
||||
return self.response
|
||||
|
||||
|
||||
def test_pool_size():
|
||||
assert pool_size(8) == 24 # min(max(24, 8), 24)
|
||||
assert pool_size(4) == 12 # 4 * 3
|
||||
assert pool_size(10) == 24 # plafonné à POOL_MAX
|
||||
assert pool_size(1) == 3
|
||||
|
||||
|
||||
async def test_rerank_skips_when_pool_not_larger_than_top_k():
|
||||
passages = [{"text": "a"}, {"text": "b"}]
|
||||
# len <= top_k → renvoyé tel quel, sans appel LLM.
|
||||
assert await rerank(FakeLLM(exc=AssertionError("ne doit pas être appelé")),
|
||||
"q", passages, top_k=3) == passages
|
||||
|
||||
|
||||
async def test_rerank_reorders_by_llm_scores():
|
||||
passages = [{"text": "a"}, {"text": "b"}, {"text": "c"}]
|
||||
out = await rerank(FakeLLM(response='{"scores":[1, 9, 5]}'), "q", passages, top_k=2)
|
||||
assert [p["text"] for p in out] == ["b", "c"]
|
||||
|
||||
|
||||
async def test_rerank_stable_on_score_ties():
|
||||
passages = [{"text": "a"}, {"text": "b"}, {"text": "c"}]
|
||||
# Notes égales → ordre cosinus d'origine préservé.
|
||||
out = await rerank(FakeLLM(response='{"scores":[5, 5, 5]}'), "q", passages, top_k=2)
|
||||
assert [p["text"] for p in out] == ["a", "b"]
|
||||
|
||||
|
||||
async def test_rerank_llm_failure_falls_back_to_cosine_order():
|
||||
passages = [{"text": "a"}, {"text": "b"}, {"text": "c"}]
|
||||
out = await rerank(FakeLLM(exc=RuntimeError("LLM HS")), "q", passages, top_k=2)
|
||||
assert [p["text"] for p in out] == ["a", "b"]
|
||||
|
||||
|
||||
async def test_rerank_wrong_score_count_falls_back():
|
||||
passages = [{"text": "a"}, {"text": "b"}, {"text": "c"}]
|
||||
out = await rerank(FakeLLM(response='{"scores":[1, 2]}'), "q", passages, top_k=2)
|
||||
assert [p["text"] for p in out] == ["a", "b"]
|
||||
|
||||
|
||||
async def test_rerank_non_numeric_scores_fall_back():
|
||||
passages = [{"text": "a"}, {"text": "b"}, {"text": "c"}]
|
||||
out = await rerank(FakeLLM(response='{"scores":["x","y","z"]}'), "q", passages, top_k=2)
|
||||
assert [p["text"] for p in out] == ["a", "b"]
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Entraînement aux règles : prompts, nettoyage et routes (série, comparaison)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.api.routers.training import _clean_drills
|
||||
from app.application.prompts.rule_training import rule_drill_review_prompt, rule_drills_prompt
|
||||
from app.main import app
|
||||
|
||||
_SECRET = "secret-de-test"
|
||||
_SECTIONS = {"Combat": "Une attaque réussit si le jet dépasse la Garde.", "Repos": "Une nuit rend tous les PV."}
|
||||
_SCENES = [{"name": "La crypte", "kind": "ENCOUNTER", "text": "Deux gardes devant une statue."}]
|
||||
|
||||
|
||||
class FakeLLM:
|
||||
def __init__(self, response: str) -> None:
|
||||
self.response = response
|
||||
self.prompt: str | None = None
|
||||
self.output_format: object = None
|
||||
self.temperature: float | None = None
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompt = prompt
|
||||
self.output_format = output_format
|
||||
self.temperature = temperature
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||
with TestClient(app) as test_client:
|
||||
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_drills_prompt_carries_rules_scenes_count_avoided_and_language():
|
||||
prompt = rule_drills_prompt(
|
||||
"Brumes", {**_SECTIONS, "Vide": " "}, _SCENES, 4, ["Un joueur saute le ravin.", " "], "en")
|
||||
|
||||
assert "« Brumes »" in prompt
|
||||
assert "Écris 4 situations" in prompt
|
||||
assert "### Combat\nUne attaque réussit si le jet dépasse la Garde." in prompt
|
||||
assert "### Vide" not in prompt, "une section sans contenu n'est pas envoyée"
|
||||
assert "[1] La crypte (ENCOUNTER)\nDeux gardes devant une statue." in prompt
|
||||
assert "- Un joueur saute le ravin." in prompt
|
||||
assert "MOT POUR MOT" in prompt
|
||||
assert "Ne lance AUCUN dé" in prompt
|
||||
assert '{"drills": []}' in prompt
|
||||
assert "anglais" in prompt
|
||||
|
||||
|
||||
def test_drills_prompt_without_scene_or_avoided_situation():
|
||||
prompt = rule_drills_prompt("", _SECTIONS, [], 5, [], "fr")
|
||||
|
||||
assert "« ce jeu »" in prompt
|
||||
assert "Aucune scène n'est fournie" in prompt
|
||||
assert "DÉJÀ posées" not in prompt
|
||||
|
||||
|
||||
def test_review_prompt_carries_the_section_the_answer_and_the_verdicts():
|
||||
prompt = rule_drill_review_prompt(
|
||||
"Brumes", "Combat", _SECTIONS["Combat"], "Un joueur frappe le garde.",
|
||||
"Une attaque réussit si le jet dépasse la Garde.", "Demandez un jet contre la Garde.",
|
||||
"Je demande un jet d'attaque.", "fr")
|
||||
|
||||
assert "section « Combat »" in prompt
|
||||
assert "Décision du MJ :\nJe demande un jet d'attaque." in prompt
|
||||
assert '"right"' in prompt and '"partial"' in prompt and '"off"' in prompt
|
||||
assert "français" in prompt
|
||||
|
||||
|
||||
def test_clean_keeps_complete_drills_and_normalizes_the_scene_number():
|
||||
out = _clean_drills([
|
||||
{"scene": 2, "situation": " S ", "section": " Combat ", "excerpt": " E ", "ruling": " R "},
|
||||
{"scene": "1", "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||
{"scene": -3, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||
{"scene": True, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||
{"scene": 1, "situation": "S", "section": "Repos", "excerpt": " ", "ruling": "R"},
|
||||
{"scene": 1, "situation": "S", "section": "Repos", "excerpt": "E"},
|
||||
"pas un objet",
|
||||
])
|
||||
|
||||
assert [d.model_dump() for d in out] == [
|
||||
{"scene": 2, "situation": "S", "section": "Combat", "excerpt": "E", "ruling": "R"},
|
||||
{"scene": 1, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||
{"scene": 0, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||
{"scene": 0, "situation": "S", "section": "Repos", "excerpt": "E", "ruling": "R"},
|
||||
]
|
||||
assert _clean_drills({"drills": []}) == []
|
||||
|
||||
|
||||
def test_drills_route_returns_the_series(client):
|
||||
llm = FakeLLM('{"drills": [{"scene": 1, "situation": "Un joueur frappe.", "section": "Combat", '
|
||||
'"excerpt": "Une attaque réussit si le jet dépasse la Garde.", "ruling": "Jet contre la Garde."}]}')
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
response = client.post("/generate/rule-drills", json={
|
||||
"system_name": "Brumes", "sections": _SECTIONS, "scenes": _SCENES, "count": 3})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"drills": [{
|
||||
"scene": 1, "situation": "Un joueur frappe.", "section": "Combat",
|
||||
"excerpt": "Une attaque réussit si le jet dépasse la Garde.", "ruling": "Jet contre la Garde."}]}
|
||||
assert "Écris 3 situations" in llm.prompt and "[1] La crypte" in llm.prompt
|
||||
assert isinstance(llm.output_format, dict), "sortie structurée demandée au modèle"
|
||||
|
||||
|
||||
def test_drills_route_refuses_a_request_without_rules(client):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("{}")
|
||||
|
||||
response = client.post("/generate/rule-drills", json={"sections": {"Combat": " "}})
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
def test_drills_route_reports_an_unusable_answer(client):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("Je ne sais pas.")
|
||||
|
||||
response = client.post("/generate/rule-drills", json={"sections": _SECTIONS})
|
||||
|
||||
assert response.status_code == 502
|
||||
assert response.json() == {"detail": "Le modèle n'a pas renvoyé de série exploitable."}
|
||||
|
||||
|
||||
_REVIEW_BODY = {
|
||||
"system_name": "Brumes", "section_title": "Combat", "section_text": _SECTIONS["Combat"],
|
||||
"situation": "Un joueur frappe le garde.", "excerpt": "Une attaque réussit si le jet dépasse la Garde.",
|
||||
"ruling": "Jet contre la Garde.", "answer": "Je demande un jet d'attaque."}
|
||||
|
||||
|
||||
def test_review_route_returns_the_verdict(client):
|
||||
llm = FakeLLM('{"verdict": "Partial", "feedback": " Il manque la Garde. "}')
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
response = client.post("/generate/rule-drill-review", json=_REVIEW_BODY)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"verdict": "partial", "feedback": "Il manque la Garde."}
|
||||
assert llm.temperature == 0.2
|
||||
|
||||
|
||||
def test_review_route_refuses_an_empty_answer(client):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("{}")
|
||||
|
||||
response = client.post("/generate/rule-drill-review", json={**_REVIEW_BODY, "answer": " "})
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [
|
||||
"Je ne sais pas.",
|
||||
'{"verdict": "bravo", "feedback": "ok"}',
|
||||
'{"verdict": "right", "feedback": ""}',
|
||||
])
|
||||
def test_review_route_reports_an_unusable_answer(client, answer):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM(answer)
|
||||
|
||||
response = client.post("/generate/rule-drill-review", json=_REVIEW_BODY)
|
||||
|
||||
assert response.status_code == 502
|
||||
assert response.json() == {"detail": "Le modèle n'a pas renvoyé de comparaison exploitable."}
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application import rules_translation
|
||||
from app.application.rules_translation import (
|
||||
RulesTranslator, TranslatedRules, detect_language, other_languages, split_markdown,
|
||||
translate_sections, unique_titles,
|
||||
)
|
||||
from app.domain.ports import LLMProviderError
|
||||
|
||||
|
||||
class EchoLLM:
|
||||
"""Traduit « en majuscules » et garde trace des prompts reçus."""
|
||||
|
||||
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
|
||||
self.prompts: list[str] = []
|
||||
self._titles_json = titles_json
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
if "Traduis ces titres" in prompt:
|
||||
return self._titles_json
|
||||
return prompt.split("Extrait :\n", 1)[1].upper()
|
||||
|
||||
|
||||
def test_detect_language():
|
||||
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
|
||||
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
|
||||
assert detect_language("", default="en") == "en"
|
||||
assert other_languages("fr") == ["en"]
|
||||
assert other_languages("en") == ["fr"]
|
||||
|
||||
|
||||
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
|
||||
assert split_markdown("court") == ["court"]
|
||||
text = "\n\n".join(["a" * 40] * 10)
|
||||
chunks = split_markdown(text, max_chars=100)
|
||||
assert all(len(c) <= 100 for c in chunks)
|
||||
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
|
||||
|
||||
|
||||
def test_split_markdown_cuts_a_giant_paragraph():
|
||||
chunks = split_markdown("x" * 250, max_chars=100)
|
||||
assert [len(c) for c in chunks] == [100, 100, 50]
|
||||
|
||||
|
||||
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
|
||||
llm = EchoLLM()
|
||||
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
|
||||
assert out == "## COMBAT\n\nCHAQUE ROUND."
|
||||
assert "noms propres" in llm.prompts[0]
|
||||
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
|
||||
|
||||
|
||||
async def test_translate_titles_falls_back_to_the_original_title():
|
||||
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
|
||||
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
|
||||
assert out == {"Combat": "Fighting", "Magie": "Magie"}
|
||||
|
||||
|
||||
def test_unique_titles_avoids_collisions():
|
||||
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
||||
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
|
||||
|
||||
|
||||
# --- traduction des sections d'un livre ----------------------------------------
|
||||
|
||||
class SectionLLM:
|
||||
"""Traduit « en majuscules ». `fail` : sous-chaînes dont la traduction échoue ;
|
||||
`slow` : sous-chaînes dont la traduction ne se termine jamais. Mesure aussi le nombre
|
||||
d'appels de contenu menés en même temps."""
|
||||
|
||||
def __init__(self, titles_json: str = '{"titles": {}}', fail=(), slow=()) -> None:
|
||||
self._titles_json = titles_json
|
||||
self._fail = tuple(fail)
|
||||
self._slow = tuple(slow)
|
||||
self.running = 0
|
||||
self.max_running = 0
|
||||
self.content_calls = 0
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
if "Traduis ces titres" in prompt:
|
||||
if self._titles_json is None:
|
||||
raise LLMProviderError("HTTP 401 clé refusée")
|
||||
return self._titles_json
|
||||
text = prompt.split("Extrait :\n", 1)[1]
|
||||
self.content_calls += 1
|
||||
self.running += 1
|
||||
self.max_running = max(self.max_running, self.running)
|
||||
try:
|
||||
await asyncio.sleep(0) # laisse démarrer les traductions voisines
|
||||
if any(mark in text for mark in self._fail):
|
||||
raise LLMProviderError("HTTP 401 clé refusée")
|
||||
if any(mark in text for mark in self._slow):
|
||||
await asyncio.Event().wait()
|
||||
return text.upper()
|
||||
finally:
|
||||
self.running -= 1
|
||||
|
||||
|
||||
async def _run(llm, sections, **kwargs):
|
||||
events = [e async for e in translate_sections(RulesTranslator(llm), sections, "fr", "en", **kwargs)]
|
||||
assert events[-1][0] == "result"
|
||||
return events, events[-1][1]
|
||||
|
||||
|
||||
async def test_translate_sections_translates_several_at_once_and_keeps_the_book_order():
|
||||
sections = {f"Titre {i}": f"texte {i}" for i in range(7)}
|
||||
llm = SectionLLM('{"titles": {"Titre 0": "Title 0"}}')
|
||||
events, result = await _run(llm, sections, concurrency=3)
|
||||
assert llm.max_running == 3
|
||||
assert list(result.sections) == ["Title 0"] + [f"Titre {i}" for i in range(1, 7)]
|
||||
assert result.sections["Title 0"] == "TEXTE 0"
|
||||
assert result.untranslated == []
|
||||
statuses = [payload for kind, payload in events if kind == "status"]
|
||||
assert statuses[0] == "Traduction (anglais) des titres…"
|
||||
assert any(s.startswith("Traduction (anglais) : 7/7") for s in statuses)
|
||||
|
||||
|
||||
async def test_translate_sections_one_at_a_time_for_a_local_model():
|
||||
llm = SectionLLM()
|
||||
await _run(llm, {"A": "a", "B": "b", "C": "c"}, concurrency=1)
|
||||
assert llm.max_running == 1
|
||||
|
||||
|
||||
async def test_translate_sections_keeps_the_original_text_of_a_failed_section(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
llm = SectionLLM('{"titles": {"Combat": "Fighting", "Magie": "Magic"}}', fail=["sorts"])
|
||||
_, result = await _run(llm, {"Combat": "les coups", "Magie": "les sorts"}, concurrency=1)
|
||||
# La section en échec garde son titre et son texte d'origine : rien n'est perdu.
|
||||
assert result == TranslatedRules({"Fighting": "LES COUPS", "Magie": "les sorts"}, ["Magie"])
|
||||
|
||||
|
||||
async def test_translate_sections_stops_launching_after_repeated_failures(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
sections = {"Ok": "bon"} | {f"S{i}": f"panne {i}" for i in range(8)}
|
||||
llm = SectionLLM(fail=["panne"])
|
||||
_, result = await _run(llm, sections, concurrency=1)
|
||||
assert result.sections["Ok"] == "BON"
|
||||
assert len(result.untranslated) == 8
|
||||
# 1 réussite, puis 3 sections en échec (3 tentatives chacune) : les 5 autres ne partent pas.
|
||||
assert llm.content_calls == 1 + rules_translation.MAX_FAILED_SECTIONS * 3
|
||||
|
||||
|
||||
async def test_translate_sections_gives_up_the_running_ones_when_time_is_up():
|
||||
llm = SectionLLM(slow=["lent"])
|
||||
events, result = await _run(llm, {"Vite": "court", "Lent": "lent"},
|
||||
concurrency=2, budget_seconds=0.2, heartbeat_seconds=0.05)
|
||||
assert result == TranslatedRules({"Vite": "COURT", "Lent": "lent"}, ["Lent"])
|
||||
assert any(kind == "heartbeat" for kind, _ in events)
|
||||
assert llm.running == 0 # la traduction en cours a bien été annulée
|
||||
|
||||
|
||||
async def test_translate_sections_fails_when_nothing_could_be_translated(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
with pytest.raises(LLMProviderError, match="aucune section"):
|
||||
await _run(SectionLLM(fail=["texte"]), {"A": "texte a", "B": "texte b"})
|
||||
with pytest.raises(LLMProviderError, match="temps imparti"):
|
||||
await _run(SectionLLM(slow=["texte"]), {"A": "texte a"}, budget_seconds=0.1, heartbeat_seconds=0.05)
|
||||
with pytest.raises(LLMProviderError, match="401"):
|
||||
await _run(SectionLLM(titles_json=None), {"A": "texte a"})
|
||||
|
||||
|
||||
async def test_translate_sections_avoids_two_sections_under_the_same_title(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
# « Combat » est traduit en « Magie » alors que la section « Magie », en échec, garde son titre.
|
||||
llm = SectionLLM('{"titles": {"Combat": "Magie"}}', fail=["sorts"])
|
||||
_, result = await _run(llm, {"Combat": "les coups", "Magie": "les sorts"}, concurrency=1)
|
||||
assert result.sections == {"Magie": "LES COUPS", "Magie (2)": "les sorts"}
|
||||
|
||||
|
||||
async def test_translate_sections_of_nothing():
|
||||
_, result = await _run(SectionLLM(), {})
|
||||
assert result == TranslatedRules({})
|
||||
|
||||
|
||||
async def test_translate_titles_sends_a_long_list_in_several_calls():
|
||||
"""Un livre découpé par sa structure a des centaines de titres."""
|
||||
titles = [f"Titre {i}" for i in range(rules_translation.TITLES_PER_CALL * 2 + 5)]
|
||||
|
||||
class BatchLLM:
|
||||
def __init__(self) -> None:
|
||||
self.sizes: list[int] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
listed = [line[2:] for line in prompt.splitlines() if line.startswith("- Titre ")]
|
||||
self.sizes.append(len(listed))
|
||||
import json as _json
|
||||
return _json.dumps({"titles": {t: t.replace("Titre", "Title") for t in listed}})
|
||||
|
||||
llm = BatchLLM()
|
||||
out = await RulesTranslator(llm).translate_titles(titles, "fr", "en")
|
||||
assert llm.sizes == [rules_translation.TITLES_PER_CALL, rules_translation.TITLES_PER_CALL, 5]
|
||||
assert out["Titre 0"] == "Title 0" and out[titles[-1]] == titles[-1].replace("Titre", "Title")
|
||||
assert list(out) == titles
|
||||
|
||||
|
||||
|
||||
async def test_translated_titles_keep_the_path_separator():
|
||||
class TitlesLLM:
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
return ('{"titles": {"Magic › Fire Spells": "Magie > Sorts de feu", "Combat": "Combat",'
|
||||
' "Gear › A > B": "Équipement › A > B"}}')
|
||||
|
||||
titles = await rules_translation.RulesTranslator(TitlesLLM()).translate_titles(
|
||||
["Magic › Fire Spells", "Combat", "Gear › A > B"], "en", "fr")
|
||||
assert titles == {"Magic › Fire Spells": "Magie › Sorts de feu", "Combat": "Combat",
|
||||
"Gear › A > B": "Équipement › A > B"}
|
||||
|
||||
|
||||
# --- glossaire des termes de jeu ---------------------------------------------------------------
|
||||
|
||||
_STAT_BLOCK = ("Tiny beast, unaligned\n\nArmor Class 12 Hit Points 22 (4d6 + 8) Speed 10 ft., fly 40 ft.\n\n"
|
||||
"| STR | DEX | CON | INT | WIS | CHA |\n| --- | --- | --- | --- | --- | --- |\n"
|
||||
"Saving Throws CON +4 Senses darkvision 60 ft., passive Perception 11 Challenge 1/4 (50 XP)")
|
||||
|
||||
|
||||
def test_the_glossary_gives_the_game_terms_found_in_the_text():
|
||||
from app.application.rules_translation import glossary
|
||||
|
||||
terms = dict(glossary(_STAT_BLOCK, "en", "fr"))
|
||||
assert terms["Saving Throws"] == "Jets de sauvegarde" and terms["WIS"] == "SAG" and terms["STR"] == "FOR"
|
||||
assert terms["Armor Class"] == "Classe d'armure" and terms["darkvision"] == "vision dans le noir"
|
||||
assert terms["beast"] == "bête" and terms["XP"] == "PX"
|
||||
# Rien que ce que le texte contient ; une abréviation n'est pas cherchée dans un mot.
|
||||
assert "Wisdom" not in terms and "AC" not in terms and "sp" not in terms
|
||||
assert glossary("The acolyte whispers in the dark.", "en", "fr") == []
|
||||
assert glossary("You win 25 gp and the DC is 13.", "en", "fr") == [("DC", "DD"), ("gp", "po")]
|
||||
|
||||
|
||||
def test_the_glossary_works_both_ways_and_is_bounded():
|
||||
from app.application.rules_translation import GLOSSARY_TERMS, _GLOSSARY_EN_FR, glossary
|
||||
|
||||
assert glossary("Jets de sauvegarde +4, vision dans le noir 18 m.", "fr", "en") == [
|
||||
("Jets de sauvegarde", "Saving Throws"), ("vision dans le noir", "darkvision")]
|
||||
everything = " ".join(term for term, _ in _GLOSSARY_EN_FR)
|
||||
assert len(glossary(everything, "en", "fr")) == GLOSSARY_TERMS
|
||||
# Pas de glossaire pour un autre couple de langues.
|
||||
assert glossary(_STAT_BLOCK, "en", "de") == []
|
||||
|
||||
|
||||
def test_the_translation_prompt_carries_the_glossary_only_when_needed():
|
||||
from app.application.rules_translation import content_prompt
|
||||
|
||||
prompt = content_prompt(_STAT_BLOCK, "en", "fr")
|
||||
assert "- Saving Throws → Jets de sauvegarde\n" in prompt and "- WIS → SAG\n" in prompt
|
||||
assert prompt.index("Glossaire") < prompt.index("Extrait :\n")
|
||||
assert prompt.endswith("Extrait :\n" + _STAT_BLOCK)
|
||||
assert "ne convertis rien" in prompt
|
||||
assert "Glossaire" not in content_prompt("The road goes north through the pines.", "en", "fr")
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Tests des helpers de l'import de règles (app.application.import_rules) :
|
||||
_SectionMerger, _normalize_sections, _coerce_markdown, _find_anchor, _combine_sections.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.import_rules import (
|
||||
_SectionMerger,
|
||||
_coerce_markdown,
|
||||
_combine_sections,
|
||||
_find_anchor,
|
||||
_normalize_sections,
|
||||
)
|
||||
|
||||
|
||||
# --- _SectionMerger ------------------------------------------------------------
|
||||
|
||||
def test_section_merger_case_insensitive_and_joins():
|
||||
m = _SectionMerger()
|
||||
touched = m.add({"Combat": "règle A", "combat": "règle B"})
|
||||
assert touched == ["Combat"] # clé canonique = 1re vue
|
||||
res = m.result()
|
||||
assert list(res.keys()) == ["Combat"]
|
||||
assert res["Combat"] == "règle A\n\nrègle B"
|
||||
|
||||
|
||||
def test_section_merger_skips_empty_title_or_content():
|
||||
m = _SectionMerger()
|
||||
touched = m.add({"": "x", "Titre": " ", "Vrai": "contenu"})
|
||||
assert touched == ["Vrai"]
|
||||
assert m.result() == {"Vrai": "contenu"}
|
||||
|
||||
|
||||
def test_section_merger_accumulates_across_chunks():
|
||||
m = _SectionMerger()
|
||||
m.add({"Combat": "p1"})
|
||||
m.add({"Combat": "p2", "Magie": "sorts"})
|
||||
res = m.result()
|
||||
assert res["Combat"] == "p1\n\np2"
|
||||
assert res["Magie"] == "sorts"
|
||||
|
||||
|
||||
# --- _normalize_sections -------------------------------------------------------
|
||||
|
||||
def test_normalize_unwraps_known_envelope():
|
||||
assert _normalize_sections({"sections": {"Combat": "x"}}) == {"Combat": "x"}
|
||||
assert _normalize_sections({"règles": {"A": "y"}}) == {"A": "y"}
|
||||
|
||||
|
||||
def test_normalize_title_content_schema():
|
||||
assert _normalize_sections({"title": "Combat", "content": "texte"}) == {"Combat": "texte"}
|
||||
|
||||
|
||||
def test_normalize_strips_meta_keys():
|
||||
assert _normalize_sections({"Combat": "x", "thought": "bla", "notes": "y"}) == {"Combat": "x"}
|
||||
|
||||
|
||||
def test_normalize_passthrough_plain_sections():
|
||||
assert _normalize_sections({"A": "1", "B": "2"}) == {"A": "1", "B": "2"}
|
||||
|
||||
|
||||
# --- _coerce_markdown ----------------------------------------------------------
|
||||
|
||||
def test_coerce_markdown_string_passthrough():
|
||||
assert _coerce_markdown("texte") == "texte"
|
||||
|
||||
|
||||
def test_coerce_markdown_none_is_empty():
|
||||
assert _coerce_markdown(None) == ""
|
||||
|
||||
|
||||
def test_coerce_markdown_list_joined():
|
||||
assert _coerce_markdown(["a", "b"]) == "a\n\nb"
|
||||
|
||||
|
||||
def test_coerce_markdown_dict_flattened():
|
||||
out = _coerce_markdown({"Sous-titre": "contenu"})
|
||||
assert "Sous-titre" in out
|
||||
assert "contenu" in out
|
||||
|
||||
|
||||
# --- _find_anchor --------------------------------------------------------------
|
||||
|
||||
def test_find_anchor_exact():
|
||||
text = "Chapitre 1. Le héros entre."
|
||||
assert _find_anchor(text, "Le héros entre", 0) == text.index("Le héros entre")
|
||||
|
||||
|
||||
def test_find_anchor_whitespace_flexible():
|
||||
text = "Le héros\nentre dans la taverne."
|
||||
# Espaces multiples / saut de ligne dans le texte source, anchor normalisé.
|
||||
assert _find_anchor(text, "Le héros entre dans la taverne", 0) is not None
|
||||
|
||||
|
||||
def test_find_anchor_case_insensitive():
|
||||
assert _find_anchor("LE DONJON s'ouvre", "le donjon", 0) is not None
|
||||
|
||||
|
||||
def test_find_anchor_not_found():
|
||||
assert _find_anchor("texte quelconque", "introuvable xyz", 0) is None
|
||||
|
||||
|
||||
# --- _combine_sections ---------------------------------------------------------
|
||||
|
||||
def test_combine_sections_case_insensitive_concat():
|
||||
out = _combine_sections({"Combat": "p1"}, {"combat": "p2", "Magie": "sorts"})
|
||||
assert out["Combat"] == "p1\n\np2"
|
||||
assert out["Magie"] == "sorts"
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Tests des overrides runtime persistés (app.core.settings_store).
|
||||
|
||||
Le chemin du fichier est redirigé vers un tmp_path pour isoler chaque test.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core import settings_store
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_store(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings_store, "_OVERRIDES_PATH", tmp_path / "settings.json")
|
||||
return tmp_path / "settings.json"
|
||||
|
||||
|
||||
def test_load_missing_file_returns_empty():
|
||||
assert settings_store.load_overrides() == {}
|
||||
|
||||
|
||||
def test_save_filters_to_allowlist_and_persists(isolated_store):
|
||||
result = settings_store.save_overrides({
|
||||
"llm_model": "gemma3:12b",
|
||||
"internal_shared_secret": "HACK", # hors allow-list → ignoré
|
||||
"champ_inconnu": "x", # hors allow-list → ignoré
|
||||
})
|
||||
assert result == {"llm_model": "gemma3:12b"}
|
||||
on_disk = json.loads(Path(isolated_store).read_text(encoding="utf-8"))
|
||||
assert on_disk == {"llm_model": "gemma3:12b"}
|
||||
|
||||
|
||||
def test_save_merges_with_existing():
|
||||
settings_store.save_overrides({"llm_model": "a"})
|
||||
merged = settings_store.save_overrides({"llm_provider": "ollama"})
|
||||
assert merged == {"llm_model": "a", "llm_provider": "ollama"}
|
||||
|
||||
|
||||
def test_load_ignores_non_allowlisted_keys_on_disk(isolated_store):
|
||||
Path(isolated_store).write_text(
|
||||
json.dumps({"llm_model": "ok", "internal_shared_secret": "leak"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert settings_store.load_overrides() == {"llm_model": "ok"}
|
||||
|
||||
|
||||
def test_load_corrupted_file_returns_empty(isolated_store):
|
||||
Path(isolated_store).write_text("{ pas du json", encoding="utf-8")
|
||||
assert settings_store.load_overrides() == {}
|
||||
|
||||
|
||||
def test_load_non_dict_json_returns_empty(isolated_store):
|
||||
Path(isolated_store).write_text("[1, 2, 3]", encoding="utf-8")
|
||||
assert settings_store.load_overrides() == {}
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Modèle de fiche proposé à partir des règles : prompt, nettoyage et route."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.api.routers.generation import _clean_sheet_fields
|
||||
from app.application.prompts.sheet_template import sheet_template_prompt
|
||||
from app.main import app
|
||||
|
||||
_SECRET = "secret-de-test"
|
||||
_SECTIONS = {"Création de personnage": "Six caractéristiques : Force, Agilité…", "Combat": "Les PV…"}
|
||||
|
||||
|
||||
class FakeLLM:
|
||||
def __init__(self, response: str) -> None:
|
||||
self.response = response
|
||||
self.prompt: str | None = None
|
||||
self.output_format: object = None
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompt = prompt
|
||||
self.output_format = output_format
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||
with TestClient(app) as test_client:
|
||||
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_prompt_contains_rules_existing_fields_sheet_and_language():
|
||||
prompt = sheet_template_prompt(
|
||||
"character", "Nimble", {**_SECTIONS, "Vide": " "}, ["Histoire", " "], "en")
|
||||
|
||||
assert "PERSONNAGE JOUEUR" in prompt
|
||||
assert "« Nimble »" in prompt
|
||||
assert "### Création de personnage\nSix caractéristiques : Force, Agilité…" in prompt
|
||||
assert "### Vide" not in prompt, "une section sans contenu n'est pas envoyée"
|
||||
assert "- Histoire" in prompt
|
||||
assert "SEULE source autorisée" in prompt
|
||||
assert '{"fields": []}' in prompt
|
||||
assert "anglais" in prompt
|
||||
|
||||
|
||||
def test_prompt_adapts_to_the_sheet_and_omits_the_existing_block_when_empty():
|
||||
enemy = sheet_template_prompt("enemy", "", _SECTIONS, [], "fr")
|
||||
assert "ENNEMI" in enemy
|
||||
assert "« ce jeu »" in enemy
|
||||
assert "DÉJÀ présents" not in enemy
|
||||
assert "PERSONNAGE NON-JOUEUR" in sheet_template_prompt("npc", "X", _SECTIONS, [], "fr")
|
||||
|
||||
|
||||
def test_clean_keeps_well_formed_fields_and_normalizes_them():
|
||||
out = _clean_sheet_fields([
|
||||
{"name": " Caractéristiques ", "type": "key_value_list", "labels": ["Force", " ", 3], "source": " Combat "},
|
||||
{"name": "PV", "type": "NUMBER"},
|
||||
{"name": "", "type": "TEXT"},
|
||||
{"name": "Sans type"},
|
||||
{"name": ["liste"], "type": "TEXT"},
|
||||
"pas un objet",
|
||||
])
|
||||
|
||||
assert [f.model_dump() for f in out] == [
|
||||
{"name": "Caractéristiques", "type": "KEY_VALUE_LIST", "labels": ["Force", "3"], "source": "Combat"},
|
||||
{"name": "PV", "type": "NUMBER", "labels": [], "source": ""},
|
||||
]
|
||||
assert _clean_sheet_fields({"fields": []}) == []
|
||||
|
||||
|
||||
def test_route_returns_the_proposed_fields(client):
|
||||
llm = FakeLLM('{"fields": [{"name": "Points de vie", "type": "NUMBER", "labels": [], "source": "Combat"}]}')
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
response = client.post("/generate/sheet-template", json={
|
||||
"sheet": "enemy", "system_name": "Nimble", "sections": _SECTIONS, "existing_fields": ["Butin"]})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"fields": [{"name": "Points de vie", "type": "NUMBER", "labels": [], "source": "Combat"}]}
|
||||
assert "ENNEMI" in llm.prompt and "- Butin" in llm.prompt
|
||||
assert isinstance(llm.output_format, dict), "sortie structurée demandée au modèle"
|
||||
|
||||
|
||||
def test_route_refuses_a_request_without_rules(client):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("{}")
|
||||
|
||||
response = client.post("/generate/sheet-template", json={"sheet": "character", "sections": {"Combat": " "}})
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
def test_route_reports_an_unusable_answer(client):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM("Je ne sais pas.")
|
||||
|
||||
response = client.post("/generate/sheet-template", json={"sheet": "character", "sections": _SECTIONS})
|
||||
|
||||
assert response.status_code == 502
|
||||
assert response.json() == {"detail": "Le modèle n'a pas renvoyé de fiche exploitable."}
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Relevé de sorts dans un texte de règles : prompt, nettoyage et route."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.application.spell_location import locate_spells
|
||||
from app.application.prompts.spell_extraction import spell_extraction_prompt
|
||||
from app.main import app
|
||||
|
||||
_SECRET = "secret-de-test"
|
||||
_TEXT = (
|
||||
"### Éclair de givre\nNiveau 1 — Évocation. Portée : 18 m.\n"
|
||||
"Un trait de givre frappe une cible : 2d6 dégâts de froid."
|
||||
)
|
||||
_FIELDS = [{"name": "Portée", "type": "TEXT"}, {"name": "Coût", "type": "NUMBER"}, {"name": " ", "type": "TEXT"}]
|
||||
|
||||
|
||||
class FakeLLM:
|
||||
def __init__(self, response: str) -> None:
|
||||
self.response = response
|
||||
self.prompt: str | None = None
|
||||
self.output_format: object = None
|
||||
self.temperature: float | None = None
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompt = prompt
|
||||
self.output_format = output_format
|
||||
self.temperature = temperature
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setenv("INTERNAL_SHARED_SECRET", _SECRET)
|
||||
with TestClient(app) as test_client:
|
||||
test_client.headers["X-Internal-Secret"] = _SECRET
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_prompt_carries_text_fields_avoided_names_and_fidelity_rules():
|
||||
prompt = spell_extraction_prompt("Brumes", "Magie", _TEXT, _FIELDS, ["Voile de brume", " "])
|
||||
|
||||
assert "« Brumes »" in prompt
|
||||
assert "section « Magie »" in prompt
|
||||
assert "Un trait de givre frappe une cible" in prompt
|
||||
assert "- Portée (texte)" in prompt
|
||||
assert "- Coût (nombre)" in prompt
|
||||
assert "- (" not in prompt, "un champ sans nom n'est pas envoyé"
|
||||
assert "- Voile de brume" in prompt
|
||||
assert "MOT POUR MOT" in prompt
|
||||
assert "EXACTEMENT comme dans le texte" in prompt
|
||||
assert "Ne recopie PAS la description" in prompt
|
||||
assert "ne traduis" in prompt
|
||||
assert '{"spells": []}' in prompt
|
||||
|
||||
|
||||
def test_prompt_without_field_title_or_avoided_name():
|
||||
prompt = spell_extraction_prompt("", "", _TEXT, [], [])
|
||||
|
||||
assert "« ce jeu »" in prompt
|
||||
assert "— extrait (SEULE source autorisée)" in prompt
|
||||
assert '"values": {}' in prompt
|
||||
assert "DÉJÀ relevés" not in prompt
|
||||
|
||||
|
||||
_BOOK = (
|
||||
"## Magic › Fire Spells\n\n"
|
||||
"CANTRIP\n\n"
|
||||
"### Flame Dart 1 Action\n\n"
|
||||
"Range: 10. Damage: 1d10. On crit: Smoldering.\n\n"
|
||||
"High Levels: +5 damage every 5th level.\n\n"
|
||||
"TIER 1\n\n"
|
||||
"### Ignite 2 Actions\n\n"
|
||||
"Range: 10. Damage: 4d10 to a Smoldering target.\n\n"
|
||||
"Upcast: +10 damage.\n\n"
|
||||
"TIER 2\n\n"
|
||||
"### Enchant Weapon 1 Action\n\n"
|
||||
"Concentration: 1 min. Reach: 8."
|
||||
)
|
||||
|
||||
|
||||
def test_the_description_of_a_spell_is_the_slice_of_the_book_that_follows_its_name():
|
||||
spells = locate_spells([
|
||||
{"name": "Flame Dart", "level": "Cantrip", "school": "Fire", "start": "CANTRIP"},
|
||||
{"name": "Ignite", "level": 1, "school": "Fire", "start": "TIER 1"},
|
||||
{"name": "Enchant Weapon", "level": "2", "school": None, "start": "TIER 2"},
|
||||
], _BOOK)
|
||||
|
||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite", "Enchant Weapon"]
|
||||
# Mot pour mot, de la ligne de niveau qui ouvre le sort à celle qui ouvre le suivant :
|
||||
# rien n'est réécrit, seul le nom (déjà dans le titre de la fiche) est retiré.
|
||||
assert spells[0].description == (
|
||||
"CANTRIP\n\n1 Action\n\nRange: 10. Damage: 1d10. On crit: Smoldering.\n\n"
|
||||
"High Levels: +5 damage every 5th level.")
|
||||
assert spells[1].description == (
|
||||
"TIER 1\n\n2 Actions\n\nRange: 10. Damage: 4d10 to a Smoldering target.\n\nUpcast: +10 damage.")
|
||||
assert spells[2].description == "TIER 2\n\n1 Action\n\nConcentration: 1 min. Reach: 8."
|
||||
assert all(part in _BOOK for spell in spells for part in spell.description.split("\n\n"))
|
||||
# Le passage cité est le début de ce qui suit le nom, assez long pour faire foi : le Core
|
||||
# le retrouve dans le texte, aux espaces près.
|
||||
assert [s.excerpt for s in spells] == [
|
||||
"1 Action Range: 10. Damage: 1d10. On crit: Smoldering.",
|
||||
"2 Actions Range: 10. Damage: 4d10 to a Smoldering target.",
|
||||
"1 Action Concentration: 1 min. Reach: 8."]
|
||||
assert (spells[1].level, spells[1].school, spells[2].school) == ("1", "Fire", "")
|
||||
|
||||
|
||||
def test_spells_are_put_back_in_the_order_of_the_book_whatever_the_order_of_the_answer():
|
||||
spells = locate_spells([
|
||||
{"name": "Ignite", "start": "TIER 1"},
|
||||
{"name": "Flame Dart", "start": "CANTRIP"},
|
||||
], _BOOK)
|
||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite"]
|
||||
assert spells[0].description.endswith("every 5th level.")
|
||||
|
||||
|
||||
def test_without_its_first_words_a_spell_is_found_by_its_name():
|
||||
spells = locate_spells([{"name": "Flame Dart"}, {"name": "ignite", "start": "des mots absents du texte"}], _BOOK)
|
||||
assert [s.name for s in spells] == ["Flame Dart", "ignite"]
|
||||
# Même sans repère donné par le modèle, la ligne de niveau placée au-dessus du nom ouvre
|
||||
# le sort : elle ne reste pas en fin de la description précédente.
|
||||
assert spells[0].description.endswith("every 5th level.")
|
||||
assert spells[1].description.startswith("TIER 1\n\n2 Actions")
|
||||
|
||||
|
||||
def test_a_spell_whose_name_is_not_in_the_text_is_left_out():
|
||||
"""Inventé, traduit ou venu d'un autre jeu : un petit modèle avait traduit 18 noms sur 18."""
|
||||
spells = locate_spells([
|
||||
{"name": "Dard de flamme", "start": "CANTRIP"},
|
||||
{"name": "Fireball", "start": "TIER 3"},
|
||||
{"name": "Ignite", "start": "TIER 1"},
|
||||
], _BOOK)
|
||||
assert [s.name for s in spells] == ["Ignite"]
|
||||
|
||||
|
||||
def test_a_spell_only_named_at_the_very_end_has_no_description():
|
||||
assert locate_spells([{"name": "Reach: 8."}], _BOOK) == []
|
||||
|
||||
|
||||
def test_malformed_entries_values_and_duplicates():
|
||||
spells = locate_spells([
|
||||
{"name": " Flame Dart ", "level": 0, "start": "CANTRIP",
|
||||
"values": {"Portée": " 10 ", "Coût": 2, "Vide": " ", " ": "x", "Liste": ["a"]}},
|
||||
{"name": "Flame Dart", "start": "CANTRIP"},
|
||||
{"name": "Ignite", "start": "TIER 1", "values": ["x"]},
|
||||
{"name": ""},
|
||||
"pas un objet",
|
||||
], _BOOK)
|
||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite"]
|
||||
# Le niveau écrit dans le livre (« CANTRIP ») prime sur celui du modèle (0).
|
||||
assert spells[0].level == "Cantrip"
|
||||
assert spells[0].values == {"Portée": "10", "Coût": "2"}
|
||||
assert spells[1].values == {}
|
||||
assert locate_spells(None, _BOOK) == []
|
||||
assert locate_spells({"name": "x"}, _BOOK) == []
|
||||
|
||||
|
||||
def test_a_spell_without_school_takes_the_one_named_by_the_section_title():
|
||||
from app.application.spell_location import school_from_title
|
||||
|
||||
assert school_from_title("Magic › Fire Spells") == "Fire"
|
||||
assert school_from_title("Sorts de foudre") == "Foudre"
|
||||
assert school_from_title("Magie › Sortilèges d'ombre") == "Ombre"
|
||||
assert school_from_title("Combat") == ""
|
||||
assert school_from_title("") == ""
|
||||
spells = locate_spells([{"name": "Flame Dart", "start": "CANTRIP"},
|
||||
{"name": "Ignite", "school": "Pyromancie", "start": "TIER 1"}],
|
||||
_BOOK, "Magic › Fire Spells")
|
||||
assert [s.school for s in spells] == ["Fire", "Pyromancie"]
|
||||
|
||||
|
||||
_NIMBLE = (
|
||||
"Upcast: +10 damage.\n\nCANTRIP\n\n### Withering Touch 1 Action\n\n"
|
||||
"Reach: 1. Damage: 1d12. On damage, target is considered undead for 1 round.\n\n"
|
||||
"High Levels: +6 damage every 5th level.\n\nTIER 1\n\n### Shadow Trap 1 Action\n\n"
|
||||
"Reaction: When an enemy moves next to an ally within Reach 8.\n\nDamage: 2d12.\n"
|
||||
)
|
||||
|
||||
|
||||
def test_a_short_first_line_is_extended_so_that_the_excerpt_proves_something():
|
||||
"""« 1 Action » seul ne passe pas la vérification du Core (25 caractères au moins)."""
|
||||
spells = locate_spells([{"name": "Withering Touch"}, {"name": "Shadow Trap"}], _NIMBLE)
|
||||
assert spells[0].excerpt == "1 Action Reach: 1. Damage: 1d12. On damage, target is considered undead for 1 round."
|
||||
assert spells[1].excerpt == "1 Action Reaction: When an enemy moves next to an ally within Reach 8."
|
||||
# Le passage se retrouve dans le texte, aux espaces près — ce que compare le Core.
|
||||
flat = " ".join(_NIMBLE.replace("#", " ").split())
|
||||
assert all(spell.excerpt in flat and len(spell.excerpt) >= 25 for spell in spells)
|
||||
|
||||
|
||||
def test_the_level_line_above_the_name_opens_the_spell_instead_of_closing_the_previous_one():
|
||||
by_name = locate_spells([{"name": "Withering Touch"}, {"name": "Shadow Trap"}], _NIMBLE)
|
||||
by_start = locate_spells([{"name": "Withering Touch", "start": "CANTRIP"},
|
||||
{"name": "Shadow Trap", "start": "TIER 1"}], _NIMBLE)
|
||||
for spells in (by_name, by_start):
|
||||
assert spells[0].description == (
|
||||
"CANTRIP\n\n1 Action\n\nReach: 1. Damage: 1d12. On damage, target is considered undead for 1 round.\n\n"
|
||||
"High Levels: +6 damage every 5th level.")
|
||||
assert spells[1].description.startswith("TIER 1\n\n1 Action\n\nReaction: When an enemy")
|
||||
# Une ligne ordinaire au-dessus du nom reste au sort précédent.
|
||||
plain = "### Brume\n\nLa brume se lève sur la lande.\n\nDurée : 1 min\n\n### Givre\n\nLe sol gèle sous vos pas, d'un coup."
|
||||
brume, givre = locate_spells([{"name": "Brume"}, {"name": "Givre"}], plain)
|
||||
assert brume.description.endswith("Durée : 1 min") and givre.description.startswith("Le sol gèle")
|
||||
|
||||
|
||||
def test_the_level_is_read_on_the_level_line_of_the_book_before_the_answer_of_the_model():
|
||||
text = ("TIER 2, AOE\n\n### Enchant Weapon 1 Action\n\nConcentration: 1 min. Reach: 8. A weapon you choose glows.\n\n"
|
||||
"TOUR DE MAGIE\n\n### Souffle de vie 1 Action\n\nPortée : 6. Restaure 1d4 PV à une créature mourante.\n\n"
|
||||
"CANTRIP\n\n### Zap 1 Action\n\nRange: 8. Damage: 2d8 lightning to one target you can see.\n")
|
||||
spells = locate_spells([{"name": "Enchant Weapon"}, {"name": "Souffle de vie", "level": "1"},
|
||||
{"name": "Zap", "level": ""}], text)
|
||||
assert [spell.level for spell in spells] == ["2", "Tour de magie", "Cantrip"]
|
||||
# Sans ligne de niveau au-dessus du nom, le niveau est celui que donne le modèle.
|
||||
plain = "### Brume\n\nLa brume se lève sur la lande et cache tout ce qui s'y trouve."
|
||||
assert locate_spells([{"name": "Brume", "level": "3"}], plain)[0].level == "3"
|
||||
utility = "TOUR DE MAGIE UTILITÉ DE FOUDRE\n\n### Zap\n\nPortée : 8. Une étincelle frappe la cible."
|
||||
assert locate_spells([{"name": "Zap"}], utility)[0].level == "Tour de magie"
|
||||
|
||||
|
||||
def test_the_school_is_read_in_a_translated_title_too():
|
||||
from app.application.spell_location import school_from_title
|
||||
assert school_from_title("Magie > Sorts de feu") == "Feu"
|
||||
assert school_from_title("Magie › Sorts radiants") == "Radiants"
|
||||
|
||||
|
||||
def test_a_magic_item_is_not_a_spell():
|
||||
text = ("### Flacon de Coup de Glaçage\n\nFlacon très rare, Niveau 8 (1 charge) Recharge : laisser le flacon "
|
||||
"au fond d'un lac.\n\n### Wand of Sparks\n\nUncommon wand, Tier 1 (3 charges). Cast Spark.\n\n"
|
||||
"### Étincelle\n\nUne étincelle jaillit de vos doigts et frappe une cible à portée, rarement deux.\n")
|
||||
spells = locate_spells([{"name": "Flacon de Coup de Glaçage"}, {"name": "Wand of Sparks"},
|
||||
{"name": "Étincelle"}], text)
|
||||
assert [spell.name for spell in spells] == ["Étincelle"]
|
||||
|
||||
|
||||
def test_a_level_is_not_the_name_of_a_spell():
|
||||
"""Tableau des prix de parchemins : « Tour de magie | 10 po », « Sort de Niveau 1 | 35 po »."""
|
||||
table = ("| Tour de magie | 10 po | Sort de Niveau 5 | 3 000 po |\n| Sort de Niveau 1 | 35 po | Tier 6 | 10 000 po |\n\n"
|
||||
"### Étincelle\n\nUne étincelle jaillit de vos doigts et frappe une cible à portée.\n")
|
||||
spells = locate_spells([{"name": "Tour de magie"}, {"name": "Sort de Niveau 1"}, {"name": "Tier 6"},
|
||||
{"name": "Cantrip"}, {"name": "Level 3 spell"}, {"name": "Étincelle"}], table)
|
||||
assert [spell.name for spell in spells] == ["Étincelle"]
|
||||
|
||||
|
||||
class ScriptedLLM:
|
||||
def __init__(self, *responses: str) -> None:
|
||||
self.responses = list(responses)
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
return self.responses[min(len(self.prompts), len(self.responses)) - 1]
|
||||
|
||||
|
||||
_SIX = "".join(f"### Sort {n}\n\nLe sort numéro {n} frappe une cible à portée et lui inflige des dégâts.\n\n"
|
||||
for n in range(1, 7))
|
||||
|
||||
|
||||
def test_route_asks_again_when_most_headings_have_no_spell(client):
|
||||
llm = ScriptedLLM(
|
||||
json.dumps({"spells": [{"name": "Sort 1"}, {"name": "Sort 2"}]}),
|
||||
# Relance : les sorts manquants, et un « sort » qui n'est pas un intertitre (écarté).
|
||||
json.dumps({"spells": [{"name": "Sort 3"}, {"name": "Sort 4"}, {"name": "Sort 5"}, {"name": "Sort 6"},
|
||||
{"name": "dégâts"}]}))
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
response = client.post("/generate/spell-extraction", json={"system_name": "Jeu", "text": _SIX})
|
||||
|
||||
assert [spell["name"] for spell in response.json()["spells"]] == [f"Sort {n}" for n in range(1, 7)]
|
||||
assert len(llm.prompts) == 2
|
||||
assert "- Sort 1" in llm.prompts[1] and "- Sort 2" in llm.prompts[1]
|
||||
# Les sorts déjà relevés ne sont pas découpés par la relance.
|
||||
assert response.json()["spells"][0]["description"] == "Le sort numéro 1 frappe une cible à portée et lui inflige des dégâts."
|
||||
|
||||
|
||||
def test_route_does_not_ask_again_when_the_answer_is_complete_or_empty(client):
|
||||
complete = ScriptedLLM(json.dumps({"spells": [{"name": f"Sort {n}"} for n in range(1, 7)]}))
|
||||
app.dependency_overrides[get_llm_provider] = lambda: complete
|
||||
assert len(client.post("/generate/spell-extraction", json={"text": _SIX}).json()["spells"]) == 6
|
||||
assert len(complete.prompts) == 1
|
||||
|
||||
none = ScriptedLLM(json.dumps({"spells": []}))
|
||||
app.dependency_overrides[get_llm_provider] = lambda: none
|
||||
assert client.post("/generate/spell-extraction", json={"text": _SIX}).json() == {"spells": []}
|
||||
assert len(none.prompts) == 1
|
||||
|
||||
|
||||
def test_route_stops_asking_when_a_pass_finds_nothing_new(client):
|
||||
llm = ScriptedLLM(json.dumps({"spells": [{"name": "Sort 1"}]}), json.dumps({"spells": []}))
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
assert len(client.post("/generate/spell-extraction", json={"text": _SIX}).json()["spells"]) == 1
|
||||
assert len(llm.prompts) == 2
|
||||
|
||||
|
||||
def test_prompt_says_that_an_item_is_not_a_spell():
|
||||
prompt = spell_extraction_prompt("Nimble", "Équipement", "Texte.", [], [])
|
||||
assert "Un OBJET n'est pas un sort" in prompt and "parchemin" in prompt and "baguette" in prompt
|
||||
|
||||
|
||||
def test_a_long_first_line_gives_a_short_excerpt():
|
||||
text = "### Mur de feu\n\n" + "Un mur de flammes se dresse devant vous " * 12
|
||||
spell = locate_spells([{"name": "Mur de feu"}], text)[0]
|
||||
assert len(spell.excerpt) <= 160 and spell.description.startswith(spell.excerpt)
|
||||
|
||||
|
||||
def test_route_returns_the_text_of_the_rules_not_the_words_of_the_model(client):
|
||||
llm = FakeLLM(json.dumps({"spells": [
|
||||
{"name": "Éclair de givre", "level": "1", "school": "Évocation", "values": {"Portée": "18 m"},
|
||||
"start": "### Éclair de givre",
|
||||
# Un modèle qui écrirait quand même une description : elle est ignorée.
|
||||
"description": "Un rayon glacé inventé par le modèle.", "excerpt": "Un rayon glacé"},
|
||||
{"name": "Sort absent du texte", "start": "nulle part"},
|
||||
]}))
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
response = client.post("/generate/spell-extraction", json={
|
||||
"system_name": "Brumes", "section_title": "Magie", "text": _TEXT,
|
||||
"fields": _FIELDS, "avoid": ["Voile de brume"]})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"spells": [{
|
||||
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||
"description": "Niveau 1 — Évocation. Portée : 18 m.\nUn trait de givre frappe une cible : 2d6 dégâts de froid.",
|
||||
"values": {"Portée": "18 m"},
|
||||
"excerpt": "Niveau 1 — Évocation. Portée : 18 m. Un trait de givre frappe une cible : 2d6 dégâts de froid."}]}
|
||||
assert llm.temperature == 0.1
|
||||
assert llm.output_format["required"] == ["spells"]
|
||||
assert "description" not in llm.output_format["properties"]["spells"]["items"]["properties"]
|
||||
assert "- Voile de brume" in llm.prompt
|
||||
|
||||
|
||||
def test_route_rejects_empty_text_and_reports_unusable_answer(client):
|
||||
llm = FakeLLM("pas du JSON")
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
assert client.post("/generate/spell-extraction", json={"text": " "}).status_code == 422
|
||||
assert llm.prompt is None, "aucun appel au modèle sans texte"
|
||||
|
||||
response = client.post("/generate/spell-extraction", json={"text": _TEXT})
|
||||
assert response.status_code == 502
|
||||
assert "exploitable" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_route_with_no_spell_returns_empty_list(client):
|
||||
app.dependency_overrides[get_llm_provider] = lambda: FakeLLM('{"spells": []}')
|
||||
|
||||
response = client.post("/generate/spell-extraction", json={"text": "Une nuit complète rend tous les PV."})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"spells": []}
|
||||
|
||||
|
||||
def test_prompt_asks_for_one_way_to_write_levels_and_schools():
|
||||
"""D'un morceau à l'autre, l'IA écrivait « 1 », « Niveau 1 », « Tour », « Cantrip »…"""
|
||||
from app.application.prompts.spell_extraction import spell_extraction_prompt
|
||||
|
||||
prompt = spell_extraction_prompt("Nimble", "Magie", "Zap. Portée 8.", [], [])
|
||||
assert "par son SEUL nombre" in prompt
|
||||
assert "jamais « Niveau 1 »" in prompt
|
||||
assert "« Tour de magie » si le texte est en français" in prompt
|
||||
assert "sans « Sorts de »" in prompt
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Tests des heartbeats SSE (app.application.streaming.with_heartbeat)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application.streaming import with_heartbeat
|
||||
|
||||
|
||||
async def _collect(agen) -> list[tuple[str, object]]:
|
||||
return [ev async for ev in agen]
|
||||
|
||||
|
||||
async def test_fast_coro_emits_only_result():
|
||||
async def quick() -> int:
|
||||
return 42
|
||||
events = await _collect(with_heartbeat(quick(), interval=0.05))
|
||||
assert events == [("result", 42)]
|
||||
|
||||
|
||||
async def test_slow_coro_emits_heartbeats_then_result():
|
||||
async def slow() -> str:
|
||||
await asyncio.sleep(0.06)
|
||||
return "fini"
|
||||
events = await _collect(with_heartbeat(slow(), interval=0.02))
|
||||
assert ("heartbeat", None) in events
|
||||
assert events[-1] == ("result", "fini")
|
||||
|
||||
|
||||
async def test_relays_status_messages_from_queue():
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
|
||||
async def work() -> str:
|
||||
await asyncio.sleep(0.05)
|
||||
return "ok"
|
||||
|
||||
queue.put_nowait("fournisseur saturé, nouvel essai")
|
||||
events = await _collect(with_heartbeat(work(), interval=0.02, status_queue=queue))
|
||||
assert ("status", "fournisseur saturé, nouvel essai") in events
|
||||
assert events[-1] == ("result", "ok")
|
||||
|
||||
|
||||
async def test_propagates_coro_exception():
|
||||
async def boom() -> None:
|
||||
raise ValueError("échec interne")
|
||||
with pytest.raises(ValueError, match="échec interne"):
|
||||
await _collect(with_heartbeat(boom(), interval=0.05))
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Tests du _TreeMerger de l'import de campagne (app.application.import_campaign).
|
||||
|
||||
Cœur du REDUCE : fusion par nom (insensible à la casse) des sous-arbres
|
||||
arc→chapitre→scène→pièce produits morceau par morceau, + accumulation des PNJ.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.import_campaign import _TreeMerger
|
||||
|
||||
|
||||
def test_single_chunk_builds_full_tree():
|
||||
m = _TreeMerger()
|
||||
m.add([{
|
||||
"name": "Acte I", "description": "intro",
|
||||
"chapters": [{
|
||||
"name": "Ch1", "description": "d",
|
||||
"scenes": [{
|
||||
"name": "Sc1", "description": "s",
|
||||
"player_narration": "PN", "gm_notes": "GM",
|
||||
"rooms": [{"name": "R1", "description": "rd", "enemies": "gob", "loot": "or"}],
|
||||
}],
|
||||
}],
|
||||
}])
|
||||
arcs = m.result()
|
||||
assert len(arcs) == 1
|
||||
arc = arcs[0]
|
||||
assert arc.name == "Acte I"
|
||||
assert arc.arc_type == "LINEAR"
|
||||
sc = arc.chapters[0].scenes[0]
|
||||
assert sc.player_narration == "PN"
|
||||
assert sc.gm_notes == "GM"
|
||||
room = sc.rooms[0]
|
||||
assert (room.name, room.enemies, room.loot) == ("R1", "gob", "or")
|
||||
|
||||
|
||||
def test_case_insensitive_arc_and_chapter_merge():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "Acte I", "chapters": [{"name": "Ch1", "scenes": []}]}])
|
||||
m.add([{"name": "acte i", "chapters": [{"name": "ch1", "scenes": []},
|
||||
{"name": "Ch2", "scenes": []}]}])
|
||||
arcs = m.result()
|
||||
assert len(arcs) == 1
|
||||
assert {c.name for c in arcs[0].chapters} == {"Ch1", "Ch2"}
|
||||
|
||||
|
||||
def test_description_first_non_empty_wins():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "A", "description": "", "chapters": []}])
|
||||
m.add([{"name": "A", "description": "vraie", "chapters": []}])
|
||||
m.add([{"name": "A", "description": "autre", "chapters": []}])
|
||||
assert m.result()[0].description == "vraie"
|
||||
|
||||
|
||||
def test_hub_type_wins_if_any_chunk_signals_it():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "A", "type": "LINEAR", "chapters": []}])
|
||||
m.add([{"name": "A", "type": "HUB", "chapters": []}])
|
||||
assert m.result()[0].arc_type == "HUB"
|
||||
|
||||
|
||||
def _scene(narr=None, gm=None):
|
||||
s = {"name": "S"}
|
||||
if narr is not None:
|
||||
s["player_narration"] = narr
|
||||
if gm is not None:
|
||||
s["gm_notes"] = gm
|
||||
return {"name": "A", "chapters": [{"name": "C", "scenes": [s]}]}
|
||||
|
||||
|
||||
def test_scene_narration_concatenated_across_chunks():
|
||||
m = _TreeMerger()
|
||||
m.add([_scene(narr="début")])
|
||||
m.add([_scene(narr="suite")])
|
||||
sc = m.result()[0].chapters[0].scenes[0]
|
||||
assert sc.player_narration == "début\n\nsuite"
|
||||
|
||||
|
||||
def test_scene_field_dedups_exact_overlap():
|
||||
m = _TreeMerger()
|
||||
m.add([_scene(gm="texte identique")])
|
||||
m.add([_scene(gm="texte identique")])
|
||||
assert m.result()[0].chapters[0].scenes[0].gm_notes == "texte identique"
|
||||
|
||||
|
||||
def test_scene_field_takes_superset_version():
|
||||
m = _TreeMerger()
|
||||
m.add([_scene(gm="court")])
|
||||
m.add([_scene(gm="court et bien plus long")])
|
||||
assert m.result()[0].chapters[0].scenes[0].gm_notes == "court et bien plus long"
|
||||
|
||||
|
||||
def test_npcs_longest_description_wins():
|
||||
m = _TreeMerger()
|
||||
m.add_npcs([{"name": "Thorin", "description": "court"}])
|
||||
m.add_npcs([{"name": "thorin", "description": "une description bien plus complète"}])
|
||||
npcs = m.npcs()
|
||||
assert len(npcs) == 1
|
||||
assert npcs[0].name == "Thorin"
|
||||
assert npcs[0].description == "une description bien plus complète"
|
||||
|
||||
|
||||
def test_counts():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "A", "chapters": [
|
||||
{"name": "C1", "scenes": [{"name": "S1"}, {"name": "S2"}]},
|
||||
{"name": "C2", "scenes": []},
|
||||
]}])
|
||||
assert m.counts() == (1, 2, 2)
|
||||
|
||||
|
||||
def test_blank_names_are_skipped():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "", "chapters": []},
|
||||
{"name": " ", "chapters": []},
|
||||
{"name": "OK", "chapters": [{"name": "", "scenes": []}]}])
|
||||
arcs = m.result()
|
||||
assert len(arcs) == 1
|
||||
assert arcs[0].name == "OK"
|
||||
assert arcs[0].chapters == []
|
||||
|
||||
|
||||
def test_merge_chapters_consolidation():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "A", "chapters": [
|
||||
{"name": "Intro", "scenes": [{"name": "S1"}]},
|
||||
{"name": "Introduction", "scenes": [{"name": "S2"}]},
|
||||
]}])
|
||||
assert m.merge_chapters("Intro", ["Introduction"]) is True
|
||||
chapters = m.result()[0].chapters
|
||||
assert len(chapters) == 1
|
||||
assert {s.name for s in chapters[0].scenes} == {"S1", "S2"}
|
||||
|
||||
|
||||
def test_merge_chapters_unknown_target_returns_false():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "A", "chapters": [{"name": "Intro", "scenes": []}]}])
|
||||
assert m.merge_chapters("Inexistant", ["Intro"]) is False
|
||||
|
||||
|
||||
def test_merge_scenes_consolidation():
|
||||
m = _TreeMerger()
|
||||
m.add([{"name": "A", "chapters": [{"name": "C", "scenes": [
|
||||
{"name": "Combat", "gm_notes": "x"},
|
||||
{"name": "Le combat", "gm_notes": "y"},
|
||||
]}]}])
|
||||
assert m.merge_scenes("C", "Combat", ["Le combat"]) is True
|
||||
scenes = m.result()[0].chapters[0].scenes
|
||||
assert len(scenes) == 1
|
||||
assert scenes[0].name == "Combat"
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Tests du stockage vectoriel fichier + recherche hybride (app.infrastructure.vector_store).
|
||||
|
||||
Le répertoire de stockage est redirigé vers un tmp_path et le cache mémoire est
|
||||
vidé avant chaque test pour une isolation totale.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.infrastructure import vector_store
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_store(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(vector_store, "_STORE_DIR", tmp_path)
|
||||
vector_store._CACHE.clear()
|
||||
yield
|
||||
vector_store._CACHE.clear()
|
||||
|
||||
|
||||
# --- cosinus -------------------------------------------------------------------
|
||||
|
||||
def test_cosine_identical_is_one():
|
||||
assert vector_store._cosine([1.0, 0.0], [2.0, 0.0]) == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_cosine_orthogonal_is_zero():
|
||||
assert vector_store._cosine([1.0, 0.0], [0.0, 1.0]) == 0.0
|
||||
|
||||
|
||||
def test_cosine_mismatched_or_zero_is_zero():
|
||||
assert vector_store._cosine([1.0], [1.0, 2.0]) == 0.0
|
||||
assert vector_store._cosine([0.0, 0.0], [1.0, 1.0]) == 0.0
|
||||
assert vector_store.cosine_similarity([], [1.0]) == 0.0 # alias public
|
||||
|
||||
|
||||
# --- mots significatifs --------------------------------------------------------
|
||||
|
||||
def test_significant_words_filters_stopwords_and_short():
|
||||
words = vector_store._significant_words("Le dragon DORT dans la caverne avec les gobelins")
|
||||
assert "dragon" in words
|
||||
assert "caverne" in words
|
||||
assert "gobelins" in words
|
||||
assert "les" not in words and "avec" not in words and "la" not in words
|
||||
|
||||
|
||||
# --- save / exists / delete ----------------------------------------------------
|
||||
|
||||
def test_save_then_exists_and_delete():
|
||||
vector_store.save("src1", ["chunk a"], [[1.0, 0.0]])
|
||||
assert vector_store.exists("src1") is True
|
||||
vector_store.delete("src1")
|
||||
assert vector_store.exists("src1") is False
|
||||
|
||||
|
||||
def test_save_rejects_mismatched_lengths():
|
||||
with pytest.raises(ValueError):
|
||||
vector_store.save("s", ["a", "b"], [[1.0]])
|
||||
with pytest.raises(ValueError):
|
||||
vector_store.save("s", ["a"], [[1.0]], pages=[1, 2])
|
||||
|
||||
|
||||
def test_all_chunks_returns_text_and_page():
|
||||
vector_store.save("s", ["t1", "t2"], [[1.0], [2.0]], pages=[3, 7])
|
||||
chunks = vector_store.all_chunks("s")
|
||||
assert chunks == [{"text": "t1", "page": 3}, {"text": "t2", "page": 7}]
|
||||
|
||||
|
||||
# --- recherche -----------------------------------------------------------------
|
||||
|
||||
def test_search_ranks_by_cosine():
|
||||
vector_store.save("s", ["proche", "loin"], [[1.0, 0.0], [0.0, 1.0]])
|
||||
results = vector_store.search(["s"], [1.0, 0.0], top_k=2)
|
||||
assert [r["text"] for r in results] == ["proche", "loin"]
|
||||
assert results[0]["score"] > results[1]["score"]
|
||||
|
||||
|
||||
def test_search_respects_top_k():
|
||||
vector_store.save("s", ["a", "b", "c"], [[1.0], [0.9], [0.8]])
|
||||
assert len(vector_store.search(["s"], [1.0], top_k=2)) == 2
|
||||
|
||||
|
||||
def test_search_min_score_filters_out_weak_matches():
|
||||
vector_store.save("s", ["proche", "orthogonal"], [[1.0, 0.0], [0.0, 1.0]])
|
||||
results = vector_store.search(["s"], [1.0, 0.0], top_k=5, min_score=0.5)
|
||||
assert [r["text"] for r in results] == ["proche"]
|
||||
|
||||
|
||||
def test_search_lexical_bonus_promotes_exact_term_match():
|
||||
# Deux extraits de cosinus IDENTIQUE : le bonus lexical départage celui qui
|
||||
# contient le mot exact de la question.
|
||||
vector_store.save(
|
||||
"s",
|
||||
["Strahd règne sur Barovia", "un texte neutre sans rapport"],
|
||||
[[1.0, 0.0], [1.0, 0.0]],
|
||||
)
|
||||
results = vector_store.search(["s"], [1.0, 0.0], top_k=2, query_text="Strahd")
|
||||
assert results[0]["text"] == "Strahd règne sur Barovia"
|
||||
assert results[0]["score"] > results[1]["score"]
|
||||
|
||||
|
||||
def test_search_includes_source_id_and_page():
|
||||
vector_store.save("livre", ["extrait"], [[1.0]], pages=[42])
|
||||
[res] = vector_store.search(["livre"], [1.0], top_k=1)
|
||||
assert res["source_id"] == "livre"
|
||||
assert res["page"] == 42
|
||||
|
||||
|
||||
# --- résumés (analyse approfondie) ---------------------------------------------
|
||||
|
||||
def test_summaries_roundtrip_keyed_by_batch_tokens():
|
||||
vector_store.save_summaries("s", 1000, [{"summary": "résumé", "vector": [1.0]}])
|
||||
assert vector_store.load_summaries("s", 1000) == [{"summary": "résumé", "vector": [1.0]}]
|
||||
# Taille de lot différente → invalidé (le découpage ne correspondrait plus).
|
||||
assert vector_store.load_summaries("s", 2000) is None
|
||||
|
||||
|
||||
def test_load_summaries_absent_returns_none():
|
||||
assert vector_store.load_summaries("inconnu", 1000) is None
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
|
||||
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
if [ -n "${JAVA_HOME-}" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
Vendored
+189
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
+90
-21
@@ -14,7 +14,7 @@
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>0.16.0</version>
|
||||
<version>1.7.0-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
@@ -24,6 +24,19 @@
|
||||
>= 3.18 : corrige CVE-2025-48924 (recursion infinie ClassUtils.getClass).
|
||||
Propriete reconnue par le BOM Spring Boot → s'applique partout. -->
|
||||
<commons-lang3.version>3.20.0</commons-lang3.version>
|
||||
<!-- Overrides CVE (detectes par Trivy en CI — job quality.yml) :
|
||||
proprietes reconnues par le BOM Spring Boot, comme ci-dessus. -->
|
||||
<!-- >= 2.21.4 : CVE-2026-54512 / CVE-2026-54513 (execution de code
|
||||
arbitraire via contournement du PolymorphicTypeValidator). -->
|
||||
<jackson-bom.version>2.21.4</jackson-bom.version>
|
||||
<!-- >= 4.1.135 : lot de CVE netty (DoS codec/handler, bypass de
|
||||
verification hostname CVE-2026-50010, DNS CVE-2026-45674/47691). -->
|
||||
<netty.version>4.1.135.Final</netty.version>
|
||||
<!-- >= 10.1.55 : 3 CRITICAL Tomcat (CVE-2026-41293 headers HTTP/2 non
|
||||
valides, CVE-2026-43512 bypass auth digest, CVE-2026-43515). -->
|
||||
<tomcat.version>10.1.55</tomcat.version>
|
||||
<!-- >= 42.7.11 : CVE-2026-42198 (DoS client via SCRAM-SHA-256). -->
|
||||
<postgresql.version>42.7.11</postgresql.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -124,34 +137,65 @@
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
|
||||
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle.
|
||||
>= 10.0.2 : corrige CVE-2025-53864 (DoS par JSON profondement imbrique
|
||||
dans le claim set — surface critique : JWT colle par l'utilisateur). -->
|
||||
<!-- openhtmltopdf — rendu XHTML+CSS -> PDF, 100 % JVM (pas de binaire natif :
|
||||
compatible distribution bureau locale via jpackage). Sert l'export PDF
|
||||
d'une campagne (livret). -->
|
||||
<dependency>
|
||||
<groupId>com.nimbusds</groupId>
|
||||
<artifactId>nimbus-jose-jwt</artifactId>
|
||||
<version>10.9.1</version>
|
||||
<groupId>com.openhtmltopdf</groupId>
|
||||
<artifactId>openhtmltopdf-pdfbox</artifactId>
|
||||
<version>1.0.10</version>
|
||||
</dependency>
|
||||
<!-- TwelveMonkeys imageio-webp — décodeur WebP pur Java pour ImageIO. Sans lui,
|
||||
ImageIO (et donc openhtmltopdf/PDFBox) ne sait pas lire le WebP : les
|
||||
portraits/illustrations WebP seraient absents du PDF. -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.84</version>
|
||||
</dependency>
|
||||
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
|
||||
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
|
||||
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
|
||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify().
|
||||
>= 1.15 : embarque un protobuf-java corrige (CVE-2024-7254). -->
|
||||
<dependency>
|
||||
<groupId>com.google.crypto.tink</groupId>
|
||||
<artifactId>tink</artifactId>
|
||||
<version>1.21.0</version>
|
||||
<groupId>com.twelvemonkeys.imageio</groupId>
|
||||
<artifactId>imageio-webp</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- Declare EXPLICITEMENT le processor d'annotations Lombok : sinon javac
|
||||
avertit que l'annotation processing implicite (processeur trouve sur le
|
||||
classpath sans etre declare) sera desactivee dans un futur JDK. -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- Expose le chemin du jar mockito-core dans la propriete
|
||||
${org.mockito:mockito-core:jar}, consommee par surefire ci-dessous. -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<!-- Charge Mockito comme un VRAI -javaagent (au lieu de l'auto-attachement
|
||||
dynamique de byte-buddy, qui imprime un avertissement et sera interdit
|
||||
dans un futur JDK). `@{argLine}` preserve l'argLine pose par JaCoCo. -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>@{argLine} -javaagent:${org.mockito:mockito-core:jar} -Xshare:off</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
@@ -195,6 +239,31 @@
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<!-- Plancher ANTI-REGRESSION : `mvn test` echoue si la couverture
|
||||
d'instructions du bundle passe sous 60% (mesure actuelle ~68%).
|
||||
A remonter au fil du temps. N'impacte PAS le build Docker
|
||||
(qui passe -DskipTests) : le gating est porte par la CI. -->
|
||||
<execution>
|
||||
<id>check</id>
|
||||
<phase>test</phase>
|
||||
<goals>
|
||||
<goal>check</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<rules>
|
||||
<rule>
|
||||
<element>BUNDLE</element>
|
||||
<limits>
|
||||
<limit>
|
||||
<counter>INSTRUCTION</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.60</minimum>
|
||||
</limit>
|
||||
</limits>
|
||||
</rule>
|
||||
</rules>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.generation.FieldProposal;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.shared.ReorderSupport;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -23,13 +27,16 @@ public class ArcService {
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final QuestRepository questRepository;
|
||||
|
||||
public ArcService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository) {
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** Compte des entités qui seront supprimées en cascade avec l'arc. */
|
||||
@@ -86,6 +93,37 @@ public class ArcService {
|
||||
return arcRepository.save(arc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch CIBLÉ champ-par-champ d'un arc (Pilier A — co-création). Applique UNIQUEMENT
|
||||
* les {@link FieldProposal} reçus ; les autres champs restent INTACTS (contraste voulu
|
||||
* avec {@link #updateArc} qui écrase tout via BeanUtils).
|
||||
*/
|
||||
@Transactional
|
||||
public Arc patchArc(String id, List<FieldProposal> fields) {
|
||||
Arc arc = arcRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Arc non trouvé avec l'ID: " + id));
|
||||
if (fields != null) {
|
||||
for (FieldProposal f : fields) {
|
||||
if (f == null || f.key() == null) continue;
|
||||
applyField(arc, f.key(), f.proposedValue());
|
||||
}
|
||||
}
|
||||
return arcRepository.save(arc);
|
||||
}
|
||||
|
||||
/** Whitelist STRICTE des champs étoffables d'un arc ; clé inconnue ignorée. */
|
||||
private void applyField(Arc arc, String key, String value) {
|
||||
switch (key) {
|
||||
case "description" -> arc.setDescription(value);
|
||||
case "themes" -> arc.setThemes(value);
|
||||
case "stakes" -> arc.setStakes(value);
|
||||
case "rewards" -> arc.setRewards(value);
|
||||
case "resolution" -> arc.setResolution(value);
|
||||
case "gmNotes" -> arc.setGmNotes(value);
|
||||
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule l'impact d'une suppression en cascade : chapitres + scènes
|
||||
* qui disparaîtront avec l'arc.
|
||||
@@ -111,10 +149,28 @@ public class ArcService {
|
||||
}
|
||||
chapterRepository.deleteById(chapter.getId());
|
||||
}
|
||||
// Détache les quêtes rattachées (arc HUB) : elles deviennent TRANSVERSES plutôt
|
||||
// que fantômes (arcId pointant un arc disparu). Weak ref, pas de FK cascade.
|
||||
for (Quest quest : questRepository.findByArcId(id)) {
|
||||
quest.setArcId(null);
|
||||
questRepository.save(quest);
|
||||
}
|
||||
arcRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public boolean arcExists(String id) {
|
||||
return arcRepository.existsById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Réordonne les arcs d'une campagne : {@code order} = position dans la liste fournie.
|
||||
* Les ids inconnus sont ignorés. Transactionnel.
|
||||
*/
|
||||
@Transactional
|
||||
public void reorderArcs(List<String> orderedIds) {
|
||||
ReorderSupport.reorder(orderedIds,
|
||||
arcRepository::findById,
|
||||
Arc::setOrder,
|
||||
arcRepository::save);
|
||||
}
|
||||
}
|
||||
|
||||
+38
-24
@@ -41,6 +41,16 @@ public class CampaignBriefBuilder {
|
||||
sb.append("# Campagne : ").append(cc.campaignName()).append("\n");
|
||||
if (notBlank(cc.campaignDescription())) sb.append(cc.campaignDescription()).append("\n");
|
||||
|
||||
appendStructure(sb, cc);
|
||||
appendNpcs(sb, cc);
|
||||
|
||||
if (campaign.isLinkedToLore()) {
|
||||
loreContextBuilder.buildOptional(campaign.getLoreId()).ifPresent(lore -> appendLore(sb, lore));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void appendStructure(StringBuilder sb, CampaignStructuralContext cc) {
|
||||
sb.append("\n## Structure (arcs → chapitres → scènes)\n");
|
||||
sb.append("_Un arc HUB contient des chapitres parallèles appelés « quêtes » ; ")
|
||||
.append("un arc LINEAR contient des chapitres en séquence._\n");
|
||||
@@ -48,34 +58,38 @@ public class CampaignBriefBuilder {
|
||||
sb.append("_(aucun arc pour le moment)_\n");
|
||||
}
|
||||
for (ArcSummary arc : cc.arcs()) {
|
||||
sb.append(arc.hub() ? "### Arc HUB (à quêtes) : " : "### Arc : ").append(arc.name());
|
||||
if (notBlank(arc.description())) sb.append(" — ").append(arc.description());
|
||||
appendArc(sb, arc);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendArc(StringBuilder sb, ArcSummary arc) {
|
||||
sb.append(arc.hub() ? "### Arc HUB (à quêtes) : " : "### Arc : ").append(arc.name());
|
||||
if (notBlank(arc.description())) sb.append(" — ").append(arc.description());
|
||||
sb.append("\n");
|
||||
for (ChapterSummary ch : arc.chapters()) {
|
||||
appendChapter(sb, arc.hub(), ch);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendChapter(StringBuilder sb, boolean hub, ChapterSummary ch) {
|
||||
sb.append(hub ? "- Quête : " : "- Chapitre : ").append(ch.name());
|
||||
if (notBlank(ch.description())) sb.append(" — ").append(ch.description());
|
||||
sb.append("\n");
|
||||
for (SceneSummary sc : ch.scenes()) {
|
||||
sb.append(" - Scène : ").append(sc.name());
|
||||
if (notBlank(sc.description())) sb.append(" — ").append(sc.description());
|
||||
sb.append("\n");
|
||||
for (ChapterSummary ch : arc.chapters()) {
|
||||
sb.append(arc.hub() ? "- Quête : " : "- Chapitre : ").append(ch.name());
|
||||
if (notBlank(ch.description())) sb.append(" — ").append(ch.description());
|
||||
sb.append("\n");
|
||||
for (SceneSummary sc : ch.scenes()) {
|
||||
sb.append(" - Scène : ").append(sc.name());
|
||||
if (notBlank(sc.description())) sb.append(" — ").append(sc.description());
|
||||
sb.append("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!cc.npcs().isEmpty()) {
|
||||
sb.append("\n## PNJ existants\n");
|
||||
for (NpcSummary n : cc.npcs()) {
|
||||
sb.append("- ").append(n.name());
|
||||
if (notBlank(n.snippet())) sb.append(" : ").append(n.snippet());
|
||||
sb.append("\n");
|
||||
}
|
||||
private void appendNpcs(StringBuilder sb, CampaignStructuralContext cc) {
|
||||
if (cc.npcs().isEmpty()) return;
|
||||
sb.append("\n## PNJ existants\n");
|
||||
for (NpcSummary n : cc.npcs()) {
|
||||
sb.append("- ").append(n.name());
|
||||
if (notBlank(n.snippet())) sb.append(" : ").append(n.snippet());
|
||||
sb.append("\n");
|
||||
}
|
||||
|
||||
if (campaign.isLinkedToLore()) {
|
||||
loreContextBuilder.buildOptional(campaign.getLoreId()).ifPresent(lore -> appendLore(sb, lore));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void appendLore(StringBuilder sb, LoreStructuralContext lore) {
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CampaignContentHit;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignContentSearchRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CampaignContentSearchService {
|
||||
private final CampaignContentSearchRepository repository;
|
||||
|
||||
public CampaignContentSearchService(CampaignContentSearchRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<CampaignContentHit> search(String query) {
|
||||
String value = query == null ? "" : query.strip();
|
||||
return value.length() < 2 ? List.of() : repository.searchByName(value);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Formateur de contexte campagne pour les prompts IA.
|
||||
* Centralise la construction du bloc "nom + description + système de jeu".
|
||||
*/
|
||||
@Component
|
||||
public class CampaignContextFormatter {
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
|
||||
public CampaignContextFormatter(CampaignRepository campaignRepository,
|
||||
GameSystemRepository gameSystemRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
}
|
||||
|
||||
/** Contexte compact : nom de campagne + description + système de jeu. */
|
||||
public String format(String campaignId) {
|
||||
if (campaignId == null) return "";
|
||||
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
|
||||
if (campaign == null) return "";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Campagne : ").append(campaign.getName());
|
||||
if (campaign.getDescription() != null && !campaign.getDescription().isBlank()) {
|
||||
sb.append(" — ").append(campaign.getDescription().trim());
|
||||
}
|
||||
if (campaign.getGameSystemId() != null && !campaign.getGameSystemId().isBlank()) {
|
||||
gameSystemRepository.findById(campaign.getGameSystemId())
|
||||
.ifPresent(gs -> sb.append("\nSystème de jeu : ").append(gs.getName()));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
+91
-61
@@ -1,17 +1,17 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.ArcType;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.ArcProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.ChapterProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.NpcProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.RoomProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.SceneProposal;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Room;
|
||||
import com.loremind.domain.campaigncontext.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ArcProposal;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ChapterProposal;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.NpcProposal;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.RoomProposal;
|
||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.SceneProposal;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignPdfImporter;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -83,66 +83,95 @@ public class CampaignImportService {
|
||||
throw new IllegalArgumentException("Campagne introuvable : " + campaignId);
|
||||
}
|
||||
|
||||
int arcsCreated = 0, chaptersCreated = 0, scenesCreated = 0;
|
||||
int arcsCreated = 0;
|
||||
int chaptersCreated = 0;
|
||||
int scenesCreated = 0;
|
||||
|
||||
// Les nouveaux nœuds sont ordonnés APRÈS les frères existants (déjà comptés
|
||||
// via leur existingId dans l'arbre fusionné venu de la revue).
|
||||
int arcOrder = countExisting(proposal.arcs(), ArcProposal::existingId);
|
||||
for (ArcProposal arcP : proposal.arcs()) {
|
||||
if (isBlank(arcP.name())) continue;
|
||||
String arcId;
|
||||
if (!isBlank(arcP.existingId())) {
|
||||
arcId = arcP.existingId(); // arc déjà présent → on s'y rattache
|
||||
} else {
|
||||
arcOrder++;
|
||||
Arc arc = arcService.createArc(Arc.builder()
|
||||
.name(arcP.name().trim())
|
||||
.description(nullIfBlank(arcP.description()))
|
||||
.campaignId(campaignId)
|
||||
.order(arcOrder)
|
||||
.type(parseArcType(arcP.type()))
|
||||
.build());
|
||||
arcId = arc.getId();
|
||||
arcsCreated++;
|
||||
}
|
||||
|
||||
int chapterOrder = countExisting(arcP.chapters(), ChapterProposal::existingId);
|
||||
for (ChapterProposal chapP : safe(arcP.chapters())) {
|
||||
if (isBlank(chapP.name())) continue;
|
||||
String chapId;
|
||||
if (!isBlank(chapP.existingId())) {
|
||||
chapId = chapP.existingId();
|
||||
} else {
|
||||
chapterOrder++;
|
||||
Chapter chapter = chapterService.createChapter(
|
||||
chapP.name().trim(), nullIfBlank(chapP.description()), arcId, chapterOrder);
|
||||
chapId = chapter.getId();
|
||||
chaptersCreated++;
|
||||
}
|
||||
|
||||
int sceneOrder = countExisting(chapP.scenes(), SceneProposal::existingId);
|
||||
for (SceneProposal sceneP : safe(chapP.scenes())) {
|
||||
if (isBlank(sceneP.name())) continue;
|
||||
if (!isBlank(sceneP.existingId())) continue; // scène déjà présente
|
||||
sceneOrder++;
|
||||
sceneService.createScene(Scene.builder()
|
||||
.name(sceneP.name().trim())
|
||||
.description(nullIfBlank(sceneP.description()))
|
||||
.playerNarration(nullIfBlank(sceneP.playerNarration()))
|
||||
.gmSecretNotes(nullIfBlank(sceneP.gmNotes()))
|
||||
.chapterId(chapId)
|
||||
.order(sceneOrder)
|
||||
.rooms(toRooms(sceneP.rooms()))
|
||||
.build());
|
||||
scenesCreated++;
|
||||
}
|
||||
}
|
||||
ArcOutcome outcome = applyArc(campaignId, arcP, arcOrder);
|
||||
arcOrder = outcome.nextOrder();
|
||||
arcsCreated += outcome.arcsCreated();
|
||||
chaptersCreated += outcome.chaptersCreated();
|
||||
scenesCreated += outcome.scenesCreated();
|
||||
}
|
||||
|
||||
int npcsCreated = createNpcs(campaignId, proposal.npcs());
|
||||
return new ApplyResult(arcsCreated, chaptersCreated, scenesCreated, npcsCreated);
|
||||
}
|
||||
|
||||
/** Ordre d'arc suivant + compteurs créés (arc et, en cascade, ses chapitres/scènes). */
|
||||
private record ArcOutcome(int nextOrder, int arcsCreated, int chaptersCreated, int scenesCreated) {}
|
||||
|
||||
private ArcOutcome applyArc(String campaignId, ArcProposal arcP, int arcOrder) {
|
||||
String arcId;
|
||||
int arcsCreated = 0;
|
||||
if (!isBlank(arcP.existingId())) {
|
||||
arcId = arcP.existingId(); // arc déjà présent → on s'y rattache
|
||||
} else {
|
||||
arcOrder++;
|
||||
Arc arc = arcService.createArc(Arc.builder()
|
||||
.name(arcP.name().trim())
|
||||
.description(nullIfBlank(arcP.description()))
|
||||
.campaignId(campaignId)
|
||||
.order(arcOrder)
|
||||
.type(parseArcType(arcP.type()))
|
||||
.build());
|
||||
arcId = arc.getId();
|
||||
arcsCreated = 1;
|
||||
}
|
||||
|
||||
int chapterOrder = countExisting(arcP.chapters(), ChapterProposal::existingId);
|
||||
int chaptersCreated = 0;
|
||||
int scenesCreated = 0;
|
||||
for (ChapterProposal chapP : safe(arcP.chapters())) {
|
||||
if (isBlank(chapP.name())) continue;
|
||||
ChapterOutcome outcome = applyChapter(arcId, chapP, chapterOrder);
|
||||
chapterOrder = outcome.nextOrder();
|
||||
chaptersCreated += outcome.chaptersCreated();
|
||||
scenesCreated += outcome.scenesCreated();
|
||||
}
|
||||
return new ArcOutcome(arcOrder, arcsCreated, chaptersCreated, scenesCreated);
|
||||
}
|
||||
|
||||
/** Ordre de chapitre suivant + compteurs créés (chapitre et, en cascade, ses scènes). */
|
||||
private record ChapterOutcome(int nextOrder, int chaptersCreated, int scenesCreated) {}
|
||||
|
||||
private ChapterOutcome applyChapter(String arcId, ChapterProposal chapP, int chapterOrder) {
|
||||
String chapId;
|
||||
int chaptersCreated = 0;
|
||||
if (!isBlank(chapP.existingId())) {
|
||||
chapId = chapP.existingId();
|
||||
} else {
|
||||
chapterOrder++;
|
||||
Chapter chapter = chapterService.createChapter(
|
||||
chapP.name().trim(), nullIfBlank(chapP.description()), arcId, chapterOrder);
|
||||
chapId = chapter.getId();
|
||||
chaptersCreated = 1;
|
||||
}
|
||||
|
||||
int sceneOrder = countExisting(chapP.scenes(), SceneProposal::existingId);
|
||||
int scenesCreated = 0;
|
||||
for (SceneProposal sceneP : safe(chapP.scenes())) {
|
||||
if (isBlank(sceneP.name()) || !isBlank(sceneP.existingId())) continue; // vide ou déjà présente
|
||||
sceneOrder++;
|
||||
sceneService.createScene(Scene.builder()
|
||||
.name(sceneP.name().trim())
|
||||
.description(nullIfBlank(sceneP.description()))
|
||||
.playerNarration(nullIfBlank(sceneP.playerNarration()))
|
||||
.gmSecretNotes(nullIfBlank(sceneP.gmNotes()))
|
||||
.chapterId(chapId)
|
||||
.order(sceneOrder)
|
||||
.rooms(toRooms(sceneP.rooms()))
|
||||
.build());
|
||||
scenesCreated++;
|
||||
}
|
||||
return new ChapterOutcome(chapterOrder, chaptersCreated, scenesCreated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée les PNJ proposés (description → values["Description"], même convention
|
||||
* que les cartes d'action des ateliers). Les PNJ portant un nom déjà présent
|
||||
@@ -182,7 +211,8 @@ public class CampaignImportService {
|
||||
|
||||
/** "HUB" (insensible à la casse) → {@link ArcType#HUB} ; tout le reste → LINEAR. */
|
||||
private static ArcType parseArcType(String type) {
|
||||
return "HUB".equalsIgnoreCase(type == null ? "" : type.trim()) ? ArcType.HUB : ArcType.LINEAR;
|
||||
String normalized = type == null ? "" : type.trim();
|
||||
return "HUB".equalsIgnoreCase(normalized) ? ArcType.HUB : ArcType.LINEAR;
|
||||
}
|
||||
|
||||
/** Convertit les pièces proposées en {@link Room} (ID généré, ordre = index). */
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessStatus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Bilan de préparation d'une campagne (read-model, Pilier B « guidage »).
|
||||
*
|
||||
* @param campaignId campagne évaluée
|
||||
* @param overallStatus statut agrégé (DRAFT si ≥1 gap bloquant, PLAYABLE si ≥1
|
||||
* recommandé sans bloquant, POLISHED sinon)
|
||||
* @param counts nombre de gaps par sévérité ({@code "BLOCKING"|"RECOMMENDED"|"OPTIONAL"})
|
||||
* @param gaps liste des manques, triés par gravité décroissante
|
||||
*/
|
||||
public record CampaignReadinessAssessment(
|
||||
String campaignId,
|
||||
ReadinessStatus overallStatus,
|
||||
Map<String, Integer> counts,
|
||||
List<ReadinessGap> gaps
|
||||
) {
|
||||
}
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.bestiary.Enemy;
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessSeverity;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessStatus;
|
||||
import com.loremind.domain.campaigncontext.structure.Room;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Service applicatif du Pilier B (« guidage / readiness ») : calcule à la volée
|
||||
* l'état de préparation d'une campagne et la liste des manques (« gaps ») à combler,
|
||||
* chacun cliquable vers l'éditeur concerné côté front.
|
||||
*
|
||||
* <p><b>Déterministe, sans IA, sans persistance</b> (aucune colonne readiness — recalcul
|
||||
* à chaque appel, comme le statut de quête). <b>Orthogonalité stricte</b> : n'injecte
|
||||
* AUCUN repository du Play Context ; le readiness ne dépend jamais d'un Playthrough,
|
||||
* d'un flag ou d'une progression. Purement indicatif : aucune sévérité ne bloque une action.</p>
|
||||
*
|
||||
* <p>Chargement en une passe façon {@code CampaignStructuralContextBuilder} : arcs →
|
||||
* chapitres (par arc) → scènes (par chapitre), + quêtes et bestiaire de la campagne
|
||||
* chargés une seule fois, indexés par id pour résoudre les références faibles sans N+1.</p>
|
||||
*
|
||||
* <p>Périmètre MVP : le noyau BLOQUANT (vides, branches/portes cassées, quête sans nœud
|
||||
* ou à nœud mort, prérequis cassé) + le trio « combat » RECOMMANDÉ (combat annoncé sans
|
||||
* ennemi, réf d'ennemi cassée en scène et en pièce). Les règles narratives/ambiance et
|
||||
* les orphelins (état que l'UI empêche) sont hors MVP.</p>
|
||||
*/
|
||||
@Service
|
||||
public class CampaignReadinessService {
|
||||
|
||||
private static final String SCENE_FALLBACK_NAME = "Scène";
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final QuestRepository questRepository;
|
||||
private final EnemyRepository enemyRepository;
|
||||
|
||||
public CampaignReadinessService(CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository,
|
||||
EnemyRepository enemyRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
this.enemyRepository = enemyRepository;
|
||||
}
|
||||
|
||||
/** Évalue la préparation d'une campagne (arbre + quêtes) et agrège son statut. */
|
||||
public CampaignReadinessAssessment assess(String campaignId) {
|
||||
List<ReadinessGap> gaps = new ArrayList<>();
|
||||
|
||||
String campaignName = campaignRepository.findById(campaignId)
|
||||
.map(Campaign::getName).orElse(null);
|
||||
|
||||
// Bestiaire de la campagne, indexé pour résoudre les weak refs sans N+1.
|
||||
// On écarte les ids vides/blancs : ils ne doivent jamais « résoudre » une référence.
|
||||
Set<String> enemyIds = enemyRepository.findByCampaignId(campaignId).stream()
|
||||
.map(Enemy::getId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||
|
||||
List<Quest> quests = questRepository.findByCampaignId(campaignId);
|
||||
// Arcs HUB « portés » par ≥1 quête rattachée : ne comptent PAS comme vides
|
||||
// (un arc HUB contient des quêtes, un arc LINÉAIRE des chapitres).
|
||||
Set<String> arcsWithQuests = quests.stream()
|
||||
.map(Quest::getArcId).filter(id -> id != null && !id.isBlank())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||
|
||||
// Index global chapitres / scènes (cibles possibles des nœuds de quête).
|
||||
Set<String> allChapterIds = new HashSet<>();
|
||||
Set<String> allSceneIds = new HashSet<>();
|
||||
int totalScenes = 0;
|
||||
for (Arc arc : arcs) {
|
||||
ArcScan scan = checkArc(arc, arcsWithQuests, enemyIds, gaps);
|
||||
allChapterIds.addAll(scan.chapterIds());
|
||||
allSceneIds.addAll(scan.sceneIds());
|
||||
totalScenes += scan.sceneCount();
|
||||
}
|
||||
|
||||
// Campagne vide : ni scène jouable, ni quête porteuse de contenu (couvre le mode plat).
|
||||
if (totalScenes == 0 && !anyQuestHasNodes(quests)) {
|
||||
gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||
"CAMP-001-NO-CONTENT",
|
||||
"Campagne vide : ajoutez une scène ou une aventure pour commencer à jouer.",
|
||||
ReadinessSeverity.BLOCKING, null, null));
|
||||
}
|
||||
|
||||
Set<String> questIds = quests.stream()
|
||||
.map(Quest::getId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
for (Quest quest : quests) {
|
||||
checkQuest(quest, allChapterIds, allSceneIds, questIds, gaps);
|
||||
}
|
||||
|
||||
return aggregate(campaignId, gaps);
|
||||
}
|
||||
|
||||
/** Résultat du scan d'un arc : chapitres/scènes indexés (cibles des nœuds de quête) + total scènes. */
|
||||
private record ArcScan(Set<String> chapterIds, Set<String> sceneIds, int sceneCount) {}
|
||||
|
||||
private ArcScan checkArc(Arc arc, Set<String> arcsWithQuests, Set<String> enemyIds, List<ReadinessGap> gaps) {
|
||||
List<Chapter> chapters = chapterRepository.findByArcId(arc.getId());
|
||||
// Arc SYSTEM (conteneurs des quêtes libres) : jamais « vide » — c'est de la
|
||||
// plomberie invisible. Ses chapitres restent analysés (CHAP-001 des conteneurs).
|
||||
boolean hubCoveredByQuest = arc.getType() == ArcType.HUB && arcsWithQuests.contains(arc.getId());
|
||||
if (chapters.isEmpty() && !hubCoveredByQuest && arc.getType() != ArcType.SYSTEM) {
|
||||
gaps.add(emptyArcGap(arc));
|
||||
}
|
||||
|
||||
Set<String> chapterIds = new HashSet<>();
|
||||
Set<String> sceneIds = new HashSet<>();
|
||||
int sceneCount = 0;
|
||||
for (Chapter chapter : chapters) {
|
||||
chapterIds.add(chapter.getId());
|
||||
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
|
||||
if (scenes.isEmpty()) {
|
||||
// Arc SYSTEM : ses chapitres sont les espaces de scènes des quêtes annexes.
|
||||
String kind = arc.getType() == ArcType.SYSTEM ? "Quête annexe" : "Aventure";
|
||||
gaps.add(new ReadinessGap(ReadinessEntityType.CHAPTER, chapter.getId(),
|
||||
labelOr(chapter.getName(), kind), "CHAP-001-NO-SCENE",
|
||||
kind + " vide : ajoutez au moins une scène pour pouvoir la jouer.",
|
||||
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
|
||||
}
|
||||
Set<String> chapterSceneIds = scenes.stream()
|
||||
.map(Scene::getId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
sceneCount += scenes.size();
|
||||
for (Scene scene : scenes) {
|
||||
sceneIds.add(scene.getId());
|
||||
checkScene(scene, arc.getId(), chapter.getId(), chapterSceneIds, enemyIds, gaps);
|
||||
}
|
||||
}
|
||||
return new ArcScan(chapterIds, sceneIds, sceneCount);
|
||||
}
|
||||
|
||||
private ReadinessGap emptyArcGap(Arc arc) {
|
||||
// Même mot pour l'auteur, que l'arc soit linéaire ou à ordre libre (HUB) : une aventure.
|
||||
String msg = "Arc vide : ajoutez une aventure, ou supprimez-le.";
|
||||
return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null);
|
||||
}
|
||||
|
||||
private static boolean anyQuestHasNodes(List<Quest> quests) {
|
||||
return quests.stream().anyMatch(q -> q.getNodes() != null && !q.getNodes().isEmpty());
|
||||
}
|
||||
|
||||
private void checkScene(Scene scene, String arcId, String chapterId,
|
||||
Set<String> chapterSceneIds, Set<String> enemyIds, List<ReadinessGap> gaps) {
|
||||
checkSceneName(scene, arcId, chapterId, gaps);
|
||||
checkSceneBranches(scene, arcId, chapterId, chapterSceneIds, gaps);
|
||||
checkSceneCombat(scene, arcId, chapterId, enemyIds, gaps);
|
||||
checkSceneEnemyRefs(scene, arcId, chapterId, enemyIds, gaps);
|
||||
checkSceneRooms(scene, arcId, chapterId, enemyIds, gaps);
|
||||
}
|
||||
|
||||
/** SCENE-001 — scène sans titre. */
|
||||
private void checkSceneName(Scene scene, String arcId, String chapterId, List<ReadinessGap> gaps) {
|
||||
if (isBlank(scene.getName())) {
|
||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-001-NO-NAME",
|
||||
"Scène sans titre : donnez-lui un nom pour l'identifier et la jouer.",
|
||||
ReadinessSeverity.BLOCKING));
|
||||
}
|
||||
}
|
||||
|
||||
/** SCENE-010 — branche de sortie cassée (vide / hors chapitre / auto-référence). */
|
||||
private void checkSceneBranches(Scene scene, String arcId, String chapterId,
|
||||
Set<String> chapterSceneIds, List<ReadinessGap> gaps) {
|
||||
List<SceneBranch> branches = scene.getBranches();
|
||||
if (branches == null) return;
|
||||
boolean invalid = branches.stream().anyMatch(b ->
|
||||
isBlank(b.targetSceneId())
|
||||
|| b.targetSceneId().equals(scene.getId())
|
||||
|| !chapterSceneIds.contains(b.targetSceneId()));
|
||||
if (invalid) {
|
||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID",
|
||||
"Branche cassée : une sortie de « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
|
||||
+ " » pointe dans le vide, hors de l'aventure, ou sur elle-même.",
|
||||
ReadinessSeverity.BLOCKING));
|
||||
}
|
||||
}
|
||||
|
||||
/** SCENE-011 — combat annoncé sans adversaire (règle produit clé). */
|
||||
private void checkSceneCombat(Scene scene, String arcId, String chapterId,
|
||||
Set<String> enemyIds, List<ReadinessGap> gaps) {
|
||||
if (isBlank(scene.getCombatDifficulty())) return;
|
||||
boolean hasEnemyText = !isBlank(scene.getEnemies());
|
||||
boolean hasResolvedEnemy = scene.getEnemyIds() != null
|
||||
&& scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && enemyIds.contains(id));
|
||||
if (!hasEnemyText && !hasResolvedEnemy) {
|
||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-011-COMBAT-NO-ENEMY",
|
||||
"Combat annoncé sans adversaire : ajoutez une fiche du bestiaire ou décrivez les ennemis.",
|
||||
ReadinessSeverity.RECOMMENDED));
|
||||
}
|
||||
}
|
||||
|
||||
/** SCENE-012 — référence d'ennemi cassée (fiche supprimée). */
|
||||
private void checkSceneEnemyRefs(Scene scene, String arcId, String chapterId,
|
||||
Set<String> enemyIds, List<ReadinessGap> gaps) {
|
||||
if (scene.getEnemyIds() == null) return;
|
||||
boolean broken = scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && !enemyIds.contains(id));
|
||||
if (broken) {
|
||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-012-ENEMY-REF-BROKEN",
|
||||
"Ennemi introuvable : « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
|
||||
+ " » référence une fiche du bestiaire supprimée. Retirez la référence ou recréez la fiche.",
|
||||
ReadinessSeverity.RECOMMENDED));
|
||||
}
|
||||
}
|
||||
|
||||
/** SCENE-041 / SCENE-042 — pièces explorables : portes cassées + ennemis fantômes. */
|
||||
private void checkSceneRooms(Scene scene, String arcId, String chapterId,
|
||||
Set<String> enemyIds, List<ReadinessGap> gaps) {
|
||||
List<Room> rooms = scene.getRooms();
|
||||
if (rooms == null || rooms.isEmpty()) return;
|
||||
String name = labelOr(scene.getName(), SCENE_FALLBACK_NAME);
|
||||
Set<String> roomIds = rooms.stream()
|
||||
.map(Room::getId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
|
||||
if (rooms.stream().anyMatch(room -> hasInvalidBranch(room, roomIds))) {
|
||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-041-ROOMBRANCH-INVALID",
|
||||
"Porte cassée : dans « " + name
|
||||
+ " », une sortie de pièce pointe hors de la scène ou dans le vide.",
|
||||
ReadinessSeverity.BLOCKING));
|
||||
}
|
||||
if (rooms.stream().anyMatch(room -> hasBrokenEnemyRef(room, enemyIds))) {
|
||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-042-ROOM-ENEMY-BROKEN",
|
||||
"Ennemi introuvable dans une pièce de « " + name
|
||||
+ " » : la référence pointe vers une fiche supprimée.",
|
||||
ReadinessSeverity.RECOMMENDED));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasInvalidBranch(Room room, Set<String> roomIds) {
|
||||
if (room.getBranches() == null) return false;
|
||||
return room.getBranches().stream().anyMatch(rb ->
|
||||
isBlank(rb.targetRoomId())
|
||||
|| rb.targetRoomId().equals(room.getId())
|
||||
|| !roomIds.contains(rb.targetRoomId()));
|
||||
}
|
||||
|
||||
private static boolean hasBrokenEnemyRef(Room room, Set<String> enemyIds) {
|
||||
if (room.getEnemyIds() == null) return false;
|
||||
return room.getEnemyIds().stream().anyMatch(id -> !isBlank(id) && !enemyIds.contains(id));
|
||||
}
|
||||
|
||||
private void checkQuest(Quest quest, Set<String> allChapterIds, Set<String> allSceneIds,
|
||||
Set<String> questIds, List<ReadinessGap> gaps) {
|
||||
// Rattachée à un arc (HUB, « à ordre libre ») : c'est une aventure de cet arc pour
|
||||
// l'auteur. Sans arc : une quête annexe.
|
||||
boolean adventure = !isBlank(quest.getArcId());
|
||||
String name = labelOr(quest.getName(), adventure ? "Aventure" : "Quête annexe");
|
||||
|
||||
// QUEST-001 — quête sans nœud ; sinon QUEST-010 — nœud pointant dans le vide.
|
||||
if (quest.getNodes() == null || quest.getNodes().isEmpty()) {
|
||||
gaps.add(questGap(quest, "QUEST-001-NO-NODES",
|
||||
(adventure ? "Aventure" : "Quête annexe")
|
||||
+ " sans contenu : ajoutez au moins une scène à « " + name + " »."));
|
||||
} else if (quest.getNodes().stream().anyMatch(n ->
|
||||
n.nodeType() == null
|
||||
|| isBlank(n.nodeId())
|
||||
|| (n.nodeType() == NodeType.CHAPTER && !allChapterIds.contains(n.nodeId()))
|
||||
|| (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) {
|
||||
gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN",
|
||||
"Lien cassé : dans « " + name
|
||||
+ " », une aventure ou une scène référencée n'existe plus."));
|
||||
}
|
||||
|
||||
// CAMP-010 — prérequis QuestCompleted pointant une quête disparue.
|
||||
if (quest.getPrerequisites() != null && quest.getPrerequisites().stream()
|
||||
.filter(p -> p instanceof Prerequisite.QuestCompleted)
|
||||
.map(p -> ((Prerequisite.QuestCompleted) p).questId())
|
||||
.anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) {
|
||||
gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ",
|
||||
"Prérequis cassé : « " + name
|
||||
+ " » dépend d'une aventure ou d'une quête qui n'existe plus. Corrigez la condition de déblocage."));
|
||||
}
|
||||
}
|
||||
|
||||
private CampaignReadinessAssessment aggregate(String campaignId, List<ReadinessGap> gaps) {
|
||||
Map<String, Integer> counts = new LinkedHashMap<>();
|
||||
counts.put(ReadinessSeverity.BLOCKING.name(), 0);
|
||||
counts.put(ReadinessSeverity.RECOMMENDED.name(), 0);
|
||||
counts.put(ReadinessSeverity.OPTIONAL.name(), 0);
|
||||
for (ReadinessGap g : gaps) {
|
||||
counts.merge(g.severity().name(), 1, Integer::sum);
|
||||
}
|
||||
|
||||
ReadinessStatus status;
|
||||
if (counts.get(ReadinessSeverity.BLOCKING.name()) > 0) {
|
||||
status = ReadinessStatus.DRAFT;
|
||||
} else if (counts.get(ReadinessSeverity.RECOMMENDED.name()) > 0) {
|
||||
status = ReadinessStatus.PLAYABLE;
|
||||
} else {
|
||||
status = ReadinessStatus.POLISHED;
|
||||
}
|
||||
|
||||
gaps.sort(Comparator.comparingInt(g -> severityRank(g.severity())));
|
||||
return new CampaignReadinessAssessment(campaignId, status, counts, gaps);
|
||||
}
|
||||
|
||||
private ReadinessGap sceneGap(Scene scene, String arcId, String chapterId,
|
||||
String ruleId, String message, ReadinessSeverity severity) {
|
||||
return new ReadinessGap(ReadinessEntityType.SCENE, scene.getId(),
|
||||
labelOr(scene.getName(), SCENE_FALLBACK_NAME), ruleId, message, severity, arcId, chapterId);
|
||||
}
|
||||
|
||||
private ReadinessGap questGap(Quest quest, String ruleId, String message) {
|
||||
return new ReadinessGap(ReadinessEntityType.QUEST, quest.getId(),
|
||||
labelOr(quest.getName(), isBlank(quest.getArcId()) ? "Quête annexe" : "Aventure"), ruleId, message, ReadinessSeverity.BLOCKING, null, null);
|
||||
}
|
||||
|
||||
private static int severityRank(ReadinessSeverity severity) {
|
||||
return switch (severity) {
|
||||
case BLOCKING -> 0;
|
||||
case RECOMMENDED -> 1;
|
||||
case OPTIONAL -> 2;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String labelOr(String value, String fallback) {
|
||||
return isBlank(value) ? fallback : value;
|
||||
}
|
||||
}
|
||||
+16
-20
@@ -1,10 +1,8 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
@@ -12,35 +10,33 @@ import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Service applicatif : énumère les noms de faits ({@link Prerequisite.FlagSet})
|
||||
* référencés par les chapitres d'une Campagne.
|
||||
* référencés par les quêtes d'une Campagne.
|
||||
*
|
||||
* <p>Modèle "déclaration implicite" : il n'existe pas de table de faits déclarés
|
||||
* globalement. Un fait existe dès qu'au moins une quête le référence dans ses
|
||||
* prérequis. Ce service expose la liste dédupliquée pour les UIs (toggle dans
|
||||
* la Partie, autocomplete dans l'éditeur de prérequis).</p>
|
||||
* la Partie, autocomplete dans l'éditeur de prérequis de quête).</p>
|
||||
*
|
||||
* <p>Niveau 1 : lit désormais les quêtes (entité de première classe), plus les
|
||||
* chapitres HUB.</p>
|
||||
*/
|
||||
@Service
|
||||
public class CampaignReferencedFlagsService {
|
||||
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final QuestRepository questRepository;
|
||||
|
||||
public CampaignReferencedFlagsService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
public CampaignReferencedFlagsService(QuestRepository questRepository) {
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** Retourne la liste triée alphabétiquement des noms de faits référencés. */
|
||||
public List<String> listForCampaign(String campaignId) {
|
||||
TreeSet<String> unique = new TreeSet<>();
|
||||
for (Arc arc : arcRepository.findByCampaignId(campaignId)) {
|
||||
for (Chapter chapter : chapterRepository.findByArcId(arc.getId())) {
|
||||
if (chapter.getPrerequisites() == null) continue;
|
||||
for (Prerequisite p : chapter.getPrerequisites()) {
|
||||
if (p instanceof Prerequisite.FlagSet f && f.flagName() != null && !f.flagName().isBlank()) {
|
||||
unique.add(f.flagName());
|
||||
}
|
||||
for (Quest quest : questRepository.findByCampaignId(campaignId)) {
|
||||
if (quest.getPrerequisites() == null) continue;
|
||||
for (Prerequisite p : quest.getPrerequisites()) {
|
||||
if (p instanceof Prerequisite.FlagSet f && f.flagName() != null && !f.flagName().isBlank()) {
|
||||
unique.add(f.flagName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.application.playcontext.PlaythroughService;
|
||||
import com.loremind.domain.campaigncontext.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.CampaignPublication;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
@@ -48,7 +49,7 @@ public class CampaignService {
|
||||
this.playthroughService = playthroughService;
|
||||
}
|
||||
|
||||
public record CampaignData(String name, String description, String loreId, String gameSystemId) {}
|
||||
public record CampaignData(String name, String description, String loreId, String gameSystemId, int playerCount) {}
|
||||
|
||||
public record DeletionImpact(int arcs, int chapters, int scenes, int playthroughs) {}
|
||||
|
||||
@@ -59,6 +60,7 @@ public class CampaignService {
|
||||
.loreId(normalizeId(data.loreId()))
|
||||
.gameSystemId(normalizeId(data.gameSystemId()))
|
||||
.arcsCount(0)
|
||||
.playerCount(data.playerCount())
|
||||
.build();
|
||||
Campaign saved = campaignRepository.save(campaign);
|
||||
|
||||
@@ -87,9 +89,43 @@ public class CampaignService {
|
||||
campaign.setDescription(data.description());
|
||||
campaign.setLoreId(normalizeId(data.loreId()));
|
||||
campaign.setGameSystemId(normalizeId(data.gameSystemId()));
|
||||
campaign.setPlayerCount(data.playerCount());
|
||||
return campaignRepository.save(campaign);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sauvegarde les positions du graphe de campagne (JSON opaque, état de
|
||||
* présentation possédé par le front). Null/vide = retour à la disposition
|
||||
* automatique. Taille bornée : ce champ ne doit pas devenir un fourre-tout.
|
||||
*/
|
||||
public void updateGraphPositions(String id, String positionsJson) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
String value = (positionsJson == null || positionsJson.isBlank()) ? null : positionsJson;
|
||||
if (value != null && value.length() > 200_000) {
|
||||
throw new IllegalArgumentException("Positions de graphe trop volumineuses");
|
||||
}
|
||||
campaign.setGraphPositions(value);
|
||||
campaignRepository.save(campaign);
|
||||
}
|
||||
|
||||
/** Fiche « Publication » de la campagne (vide si jamais renseignée). */
|
||||
public CampaignPublication getPublication(String id) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
return campaign.getPublication() != null ? campaign.getPublication() : CampaignPublication.empty();
|
||||
}
|
||||
|
||||
/** Remplace la fiche « Publication » (nettoyée : blancs → vide, longueurs bornées). */
|
||||
public CampaignPublication updatePublication(String id, CampaignPublication publication) {
|
||||
Campaign campaign = campaignRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Campaign non trouvé avec l'ID: " + id));
|
||||
CampaignPublication clean = publication != null ? publication.normalized() : CampaignPublication.empty();
|
||||
campaign.setPublication(clean.hasContent() ? clean : null);
|
||||
campaignRepository.save(campaign);
|
||||
return clean;
|
||||
}
|
||||
|
||||
private String normalizeId(String id) {
|
||||
return (id == null || id.isBlank()) ? null : id;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.generation.FieldProposal;
|
||||
import com.loremind.domain.shared.ReorderSupport;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
@@ -76,10 +78,64 @@ public class ChapterService {
|
||||
}
|
||||
|
||||
Chapter chapter = existingChapter.get();
|
||||
BeanUtils.copyProperties(updated, chapter, "id");
|
||||
// guidedMethod : jamais porté par le formulaire d'édition, il ne doit pas être effacé.
|
||||
BeanUtils.copyProperties(updated, chapter, "id", "guidedMethod");
|
||||
return chapterRepository.save(chapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rattache le chapitre à une méthode guidée, ou l'en détache ({@code null} / vide).
|
||||
* Changer ou retirer la méthode efface le rôle de ses scènes : un rôle n'a de sens que
|
||||
* dans la méthode qui le définit. Transactionnel.
|
||||
*
|
||||
* @throws IllegalArgumentException chapitre inconnu ou identifiant de méthode invalide
|
||||
*/
|
||||
@Transactional
|
||||
public Chapter setGuidedMethod(String id, String method) {
|
||||
Chapter chapter = chapterRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Chapter non trouvé avec l'ID: " + id));
|
||||
String next = GuidedKeys.normalize(method);
|
||||
if (!java.util.Objects.equals(next, chapter.getGuidedMethod())) {
|
||||
for (var scene : sceneRepository.findByChapterId(id)) {
|
||||
if (scene.getGuidedRole() != null) {
|
||||
scene.setGuidedRole(null);
|
||||
sceneRepository.save(scene);
|
||||
}
|
||||
}
|
||||
}
|
||||
chapter.setGuidedMethod(next);
|
||||
return chapterRepository.save(chapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch CIBLÉ champ-par-champ d'un chapitre (Pilier A — co-création). Applique
|
||||
* UNIQUEMENT les {@link FieldProposal} reçus ; les autres champs restent INTACTS
|
||||
* (contraste voulu avec {@link #updateChapter} qui écrase tout via BeanUtils).
|
||||
*/
|
||||
@Transactional
|
||||
public Chapter patchChapter(String id, List<FieldProposal> fields) {
|
||||
Chapter chapter = chapterRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Chapter non trouvé avec l'ID: " + id));
|
||||
if (fields != null) {
|
||||
for (FieldProposal f : fields) {
|
||||
if (f == null || f.key() == null) continue;
|
||||
applyField(chapter, f.key(), f.proposedValue());
|
||||
}
|
||||
}
|
||||
return chapterRepository.save(chapter);
|
||||
}
|
||||
|
||||
/** Whitelist STRICTE des champs étoffables d'un chapitre ; clé inconnue ignorée. */
|
||||
private void applyField(Chapter chapter, String key, String value) {
|
||||
switch (key) {
|
||||
case "description" -> chapter.setDescription(value);
|
||||
case "gmNotes" -> chapter.setGmNotes(value);
|
||||
case "playerObjectives" -> chapter.setPlayerObjectives(value);
|
||||
case "narrativeStakes" -> chapter.setNarrativeStakes(value);
|
||||
default -> { /* clé inconnue → ignorée (garde-fou anti-écrasement) */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** Compte des scènes qui tomberont avec le chapitre. */
|
||||
public DeletionImpact getDeletionImpact(String id) {
|
||||
return new DeletionImpact(sceneRepository.findByChapterId(id).size());
|
||||
@@ -97,4 +153,19 @@ public class ChapterService {
|
||||
public boolean chapterExists(String id) {
|
||||
return chapterRepository.existsById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Réordonne (et déplace) les chapitres d'un arc : {@code order} = position. Si
|
||||
* {@code arcId} est fourni, on réaffecte le chapitre à cet arc. Transactionnel.
|
||||
*/
|
||||
@Transactional
|
||||
public void reorderChapters(String arcId, List<String> orderedIds) {
|
||||
ReorderSupport.reorder(orderedIds,
|
||||
chapterRepository::findById,
|
||||
(chapter, i) -> {
|
||||
if (arcId != null && !arcId.isBlank()) chapter.setArcId(arcId);
|
||||
chapter.setOrder(i);
|
||||
},
|
||||
chapterRepository::save);
|
||||
}
|
||||
}
|
||||
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
import com.loremind.domain.campaigncontext.PrerequisiteEvaluator;
|
||||
import com.loremind.domain.campaigncontext.ProgressionStatus;
|
||||
import com.loremind.domain.campaigncontext.QuestStatus;
|
||||
import com.loremind.domain.playcontext.QuestProgression;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughFlagRepository;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import com.loremind.domain.playcontext.ports.QuestProgressionRepository;
|
||||
import com.loremind.domain.playcontext.ports.SessionRepository;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ChapterDTO;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Service applicatif : enrichit des ChapterDTO avec leur {@link QuestStatus} effectif,
|
||||
* relatif à un Playthrough donné.
|
||||
*
|
||||
* <p>Depuis l'introduction de Playthrough : la progression et les flags vivent au niveau
|
||||
* de la Partie, plus de la Campagne. L'enrichissement nécessite donc un playthroughId.</p>
|
||||
*/
|
||||
@Service
|
||||
public class ChapterStatusEnricher {
|
||||
|
||||
private final PlaythroughRepository playthroughRepository;
|
||||
private final QuestProgressionRepository progressionRepository;
|
||||
private final PlaythroughFlagRepository flagRepository;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final PrerequisiteEvaluator evaluator = new PrerequisiteEvaluator();
|
||||
|
||||
public ChapterStatusEnricher(PlaythroughRepository playthroughRepository,
|
||||
QuestProgressionRepository progressionRepository,
|
||||
PlaythroughFlagRepository flagRepository,
|
||||
SessionRepository sessionRepository) {
|
||||
this.playthroughRepository = playthroughRepository;
|
||||
this.progressionRepository = progressionRepository;
|
||||
this.flagRepository = flagRepository;
|
||||
this.sessionRepository = sessionRepository;
|
||||
}
|
||||
|
||||
/** Contexte d'évaluation + map chapterId -> ProgressionStatus pour ce Playthrough. */
|
||||
public record PlaythroughEvalSnapshot(
|
||||
PrerequisiteEvaluator.EvaluationContext ctx,
|
||||
Map<String, ProgressionStatus> progressionByChapterId
|
||||
) {}
|
||||
|
||||
/** Construit le snapshot d'évaluation pour un Playthrough. */
|
||||
public PlaythroughEvalSnapshot buildSnapshot(String playthroughId) {
|
||||
if (playthroughId == null || playthroughRepository.findById(playthroughId).isEmpty()) {
|
||||
return new PlaythroughEvalSnapshot(
|
||||
new PrerequisiteEvaluator.EvaluationContext(Collections.emptySet(), 0, Collections.emptyMap()),
|
||||
Collections.emptyMap()
|
||||
);
|
||||
}
|
||||
Map<String, Boolean> flags = flagRepository.findByPlaythroughId(playthroughId);
|
||||
Set<String> completedQuestIds = progressionRepository.findCompletedChapterIdsByPlaythroughId(playthroughId);
|
||||
int sessionCount = sessionRepository.findByPlaythroughId(playthroughId).size();
|
||||
|
||||
Map<String, ProgressionStatus> progressionMap = new HashMap<>();
|
||||
for (QuestProgression qp : progressionRepository.findByPlaythroughId(playthroughId)) {
|
||||
progressionMap.put(qp.getChapterId(), qp.getStatus());
|
||||
}
|
||||
|
||||
return new PlaythroughEvalSnapshot(
|
||||
new PrerequisiteEvaluator.EvaluationContext(completedQuestIds, sessionCount, flags),
|
||||
progressionMap
|
||||
);
|
||||
}
|
||||
|
||||
/** Calcule le statut effectif d'un seul chapitre relatif à un Playthrough. */
|
||||
public QuestStatus computeFor(Chapter chapter, String playthroughId) {
|
||||
PlaythroughEvalSnapshot snap = buildSnapshot(playthroughId);
|
||||
ProgressionStatus progression = snap.progressionByChapterId()
|
||||
.getOrDefault(chapter.getId(), ProgressionStatus.NOT_STARTED);
|
||||
return evaluator.computeStatus(progression, chapter.getPrerequisites(), snap.ctx());
|
||||
}
|
||||
|
||||
/**
|
||||
* Injecte le {@code effectiveStatus} et le {@code progressionStatus} dans une liste de DTOs.
|
||||
* Un seul build du snapshot pour toute la liste (optimal pour les vues qui listent un arc).
|
||||
*/
|
||||
public void enrich(List<ChapterDTO> dtos, List<Chapter> domain, String playthroughId) {
|
||||
if (dtos == null || dtos.isEmpty()) return;
|
||||
PlaythroughEvalSnapshot snap = buildSnapshot(playthroughId);
|
||||
Map<String, Chapter> byId = domain.stream()
|
||||
.collect(Collectors.toMap(Chapter::getId, c -> c));
|
||||
for (ChapterDTO dto : dtos) {
|
||||
Chapter c = byId.get(dto.getId());
|
||||
if (c == null) continue;
|
||||
ProgressionStatus progression = snap.progressionByChapterId()
|
||||
.getOrDefault(c.getId(), ProgressionStatus.NOT_STARTED);
|
||||
QuestStatus status = evaluator.computeStatus(progression, c.getPrerequisites(), snap.ctx());
|
||||
dto.setProgressionStatus(progression.name());
|
||||
dto.setEffectiveStatus(status.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Character;
|
||||
import com.loremind.domain.campaigncontext.bestiary.Character;
|
||||
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -41,9 +41,9 @@ public class CharacterService {
|
||||
.name(data.name())
|
||||
.portraitImageId(data.portraitImageId())
|
||||
.headerImageId(data.headerImageId())
|
||||
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
|
||||
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
||||
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
||||
.values(copyStringMap(data.values()))
|
||||
.imageValues(copyStringListMap(data.imageValues()))
|
||||
.keyValueValues(copyStringMapMap(data.keyValueValues()))
|
||||
.playthroughId(data.playthroughId())
|
||||
.order(order)
|
||||
.build();
|
||||
@@ -64,9 +64,9 @@ public class CharacterService {
|
||||
existing.setName(data.name());
|
||||
existing.setPortraitImageId(data.portraitImageId());
|
||||
existing.setHeaderImageId(data.headerImageId());
|
||||
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
||||
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||
existing.setValues(copyStringMap(data.values()));
|
||||
existing.setImageValues(copyStringListMap(data.imageValues()));
|
||||
existing.setKeyValueValues(copyStringMapMap(data.keyValueValues()));
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
@@ -89,4 +89,16 @@ public class CharacterService {
|
||||
.max()
|
||||
.orElse(-1) + 1;
|
||||
}
|
||||
|
||||
private static Map<String, String> copyStringMap(Map<String, String> map) {
|
||||
return map != null ? new HashMap<>(map) : new HashMap<>();
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> copyStringListMap(Map<String, List<String>> map) {
|
||||
return map != null ? new HashMap<>(map) : new HashMap<>();
|
||||
}
|
||||
|
||||
private static Map<String, Map<String, String>> copyStringMapMap(Map<String, Map<String, String>> map) {
|
||||
return map != null ? new HashMap<>(map) : new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Enemy;
|
||||
import com.loremind.domain.campaigncontext.bestiary.Enemy;
|
||||
import com.loremind.domain.shared.ReorderSupport;
|
||||
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||
import com.loremind.domain.images.Image;
|
||||
import com.loremind.application.images.ImageService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Service d'application pour les fiches d'ennemis (bestiaire de campagne).
|
||||
@@ -16,10 +19,14 @@ import java.util.Optional;
|
||||
@Service
|
||||
public class EnemyService {
|
||||
|
||||
private final EnemyRepository enemyRepository;
|
||||
private static final Logger log = LoggerFactory.getLogger(EnemyService.class);
|
||||
|
||||
public EnemyService(EnemyRepository enemyRepository) {
|
||||
private final EnemyRepository enemyRepository;
|
||||
private final ImageService imageService;
|
||||
|
||||
public EnemyService(EnemyRepository enemyRepository, ImageService imageService) {
|
||||
this.enemyRepository = enemyRepository;
|
||||
this.imageService = imageService;
|
||||
}
|
||||
|
||||
public record EnemyData(
|
||||
@@ -37,18 +44,10 @@ public class EnemyService {
|
||||
|
||||
public Enemy createEnemy(EnemyData data) {
|
||||
int order = data.order() != null ? data.order() : nextOrderFor(data.campaignId());
|
||||
Enemy enemy = Enemy.builder()
|
||||
.name(data.name())
|
||||
.level(normalize(data.level()))
|
||||
.folder(normalize(data.folder()))
|
||||
.portraitImageId(data.portraitImageId())
|
||||
.headerImageId(data.headerImageId())
|
||||
.values(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>())
|
||||
.imageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>())
|
||||
.keyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>())
|
||||
.campaignId(data.campaignId())
|
||||
.order(order)
|
||||
.build();
|
||||
Enemy enemy = Enemy.builder().build();
|
||||
applyCommonEnemyFields(enemy, data);
|
||||
enemy.setCampaignId(data.campaignId());
|
||||
enemy.setOrder(order);
|
||||
return enemyRepository.save(enemy);
|
||||
}
|
||||
|
||||
@@ -63,17 +62,11 @@ public class EnemyService {
|
||||
public Enemy updateEnemy(String id, EnemyData data) {
|
||||
Enemy existing = enemyRepository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Enemy non trouvé avec l'ID: " + id));
|
||||
existing.setName(data.name());
|
||||
existing.setLevel(normalize(data.level()));
|
||||
existing.setFolder(normalize(data.folder()));
|
||||
existing.setPortraitImageId(data.portraitImageId());
|
||||
existing.setHeaderImageId(data.headerImageId());
|
||||
existing.setValues(data.values() != null ? new HashMap<>(data.values()) : new HashMap<>());
|
||||
existing.setImageValues(data.imageValues() != null ? new HashMap<>(data.imageValues()) : new HashMap<>());
|
||||
existing.setKeyValueValues(data.keyValueValues() != null ? new HashMap<>(data.keyValueValues()) : new HashMap<>());
|
||||
applyCommonEnemyFields(existing, data);
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
// campaignId immuable après création.
|
||||
return enemyRepository.save(existing);
|
||||
}
|
||||
|
||||
@@ -81,6 +74,139 @@ public class EnemyService {
|
||||
enemyRepository.deleteById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Réordonne (et reclasse) les ennemis d'un dossier : {@code order} = position, et
|
||||
* le dossier de chaque ennemi est posé à {@code folder} (glisser-déposer).
|
||||
*/
|
||||
@org.springframework.transaction.annotation.Transactional
|
||||
public void reorderEnemies(String folder, List<String> orderedIds) {
|
||||
String f = normalize(folder);
|
||||
ReorderSupport.reorder(orderedIds,
|
||||
enemyRepository::findById,
|
||||
(enemy, i) -> { enemy.setFolder(f); enemy.setOrder(i); },
|
||||
enemyRepository::save);
|
||||
}
|
||||
|
||||
// --- Import de monstres depuis un compendium Foundry -------------------
|
||||
|
||||
/**
|
||||
* Un monstre du catalogue Foundry : nom + référence + snapshot de stats + dossier
|
||||
* + vignette du portrait (data URL base64, optionnelle).
|
||||
*/
|
||||
public record MonsterImport(String name, String foundryRef, Map<String, String> stats,
|
||||
String folder, String imgData) {}
|
||||
|
||||
/**
|
||||
* Dossier LoreMind d'un monstre importé : on conserve l'arborescence Foundry
|
||||
* sous un dossier racine « Foundry » ("Foundry/Briarban", "Foundry" si aucun).
|
||||
*/
|
||||
private static String foundryFolder(String path) {
|
||||
String p = path == null ? "" : path.trim();
|
||||
return p.isEmpty() ? "Foundry" : "Foundry/" + p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Décode une vignette de portrait (data URL base64 "data:image/webp;base64,…")
|
||||
* et l'enregistre comme image LoreMind. Renvoie l'id de l'image, ou null si
|
||||
* absente/illisible (l'import ne doit jamais échouer à cause d'un portrait).
|
||||
*/
|
||||
private String storePortrait(String dataUrl, String name) {
|
||||
if (dataUrl == null || !dataUrl.startsWith("data:")) return null;
|
||||
int comma = dataUrl.indexOf(',');
|
||||
if (comma < 0) return null;
|
||||
String header = dataUrl.substring(5, comma); // "image/webp;base64"
|
||||
String contentType = header.split(";")[0].toLowerCase();
|
||||
byte[] bytes;
|
||||
try {
|
||||
bytes = Base64.getDecoder().decode(dataUrl.substring(comma + 1));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
if (bytes.length == 0) return null;
|
||||
String ext = pickExtension(contentType);
|
||||
// Type MIME canonique dérivé de l'extension : un data URL "image/jpg" (non
|
||||
// standard) serait rejeté par ImageService (qui n'accepte que "image/jpeg").
|
||||
String mimeType = "jpg".equals(ext) ? "image/jpeg" : "image/" + ext;
|
||||
String filename = (name == null || name.isBlank() ? "monstre" : name.replaceAll("[^a-zA-Z0-9._-]", "_")) + "." + ext;
|
||||
try {
|
||||
Image img = imageService.upload(filename, mimeType,
|
||||
new ByteArrayInputStream(bytes), bytes.length);
|
||||
return img.getId();
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Portrait de monstre ignoré (\"{}\") : {}", name, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Extension déduite du content-type ; "webp" par défaut si non reconnu. */
|
||||
private static String pickExtension(String contentType) {
|
||||
if (contentType.contains("png")) return "png";
|
||||
if (contentType.contains("jpeg") || contentType.contains("jpg")) return "jpg";
|
||||
if (contentType.contains("gif")) return "gif";
|
||||
return "webp";
|
||||
}
|
||||
|
||||
public record MonsterImportResult(int created, int updated) {}
|
||||
|
||||
/**
|
||||
* Importe (upsert) des monstres Foundry dans le bestiaire d'une campagne.
|
||||
* Dédup par {@code foundryRef} : un monstre déjà importé est mis à jour (nom),
|
||||
* jamais dupliqué. Fiche minimale (nom + référence) ; les stats restent côté
|
||||
* Foundry et sont ré-instanciées à l'export.
|
||||
*/
|
||||
public MonsterImportResult importFoundryMonsters(String campaignId, List<MonsterImport> monsters) {
|
||||
List<Enemy> existing = enemyRepository.findByCampaignId(campaignId);
|
||||
Map<String, Enemy> byRef = new HashMap<>();
|
||||
for (Enemy e : existing) {
|
||||
if (e.getFoundryRef() != null) byRef.put(e.getFoundryRef(), e);
|
||||
}
|
||||
int order = existing.stream().mapToInt(Enemy::getOrder).max().orElse(-1) + 1;
|
||||
|
||||
int created = 0;
|
||||
int updated = 0;
|
||||
for (MonsterImport m : monsters) {
|
||||
if (isBlank(m.foundryRef()) || isBlank(m.name())) continue;
|
||||
Map<String, String> stats = m.stats() != null ? new HashMap<>(m.stats()) : new HashMap<>();
|
||||
Enemy ex = byRef.get(m.foundryRef());
|
||||
if (ex != null) {
|
||||
updateMonster(ex, m, stats);
|
||||
updated++;
|
||||
} else {
|
||||
byRef.put(m.foundryRef(), createMonster(campaignId, m, stats, order++));
|
||||
created++;
|
||||
}
|
||||
}
|
||||
return new MonsterImportResult(created, updated);
|
||||
}
|
||||
|
||||
/** Met à jour un monstre déjà importé : nom, snapshot de stats, dossier, portrait manquant. */
|
||||
private void updateMonster(Enemy ex, MonsterImport m, Map<String, String> stats) {
|
||||
ex.setName(m.name());
|
||||
ex.setFoundryStats(stats); // rafraîchit le snapshot
|
||||
ex.setFolder(foundryFolder(m.folder())); // ré-aligne sur l'arborescence Foundry
|
||||
// Portrait : seulement s'il manque (pas de ré-upload à chaque import).
|
||||
if (ex.getPortraitImageId() == null) {
|
||||
String portrait = storePortrait(m.imgData(), m.name());
|
||||
if (portrait != null) ex.setPortraitImageId(portrait);
|
||||
}
|
||||
enemyRepository.save(ex);
|
||||
}
|
||||
|
||||
private Enemy createMonster(String campaignId, MonsterImport m, Map<String, String> stats, int order) {
|
||||
return enemyRepository.save(Enemy.builder()
|
||||
.name(m.name())
|
||||
.foundryRef(m.foundryRef())
|
||||
.foundryStats(stats)
|
||||
.folder(foundryFolder(m.folder()))
|
||||
.portraitImageId(storePortrait(m.imgData(), m.name()))
|
||||
.campaignId(campaignId)
|
||||
.order(order)
|
||||
.values(new HashMap<>())
|
||||
.imageValues(new HashMap<>())
|
||||
.keyValueValues(new HashMap<>())
|
||||
.build());
|
||||
}
|
||||
|
||||
public List<Enemy> searchEnemies(String query) {
|
||||
if (query == null || query.isBlank()) return List.of();
|
||||
return enemyRepository.searchByName(query.trim());
|
||||
@@ -93,10 +219,37 @@ public class EnemyService {
|
||||
return trimmed.isEmpty() ? null : trimmed;
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private int nextOrderFor(String campaignId) {
|
||||
return enemyRepository.findByCampaignId(campaignId).stream()
|
||||
.mapToInt(Enemy::getOrder)
|
||||
.max()
|
||||
.orElse(-1) + 1;
|
||||
}
|
||||
|
||||
private static Map<String, String> copyStringMap(Map<String, String> map) {
|
||||
return map != null ? new HashMap<>(map) : new HashMap<>();
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> copyStringListMap(Map<String, List<String>> map) {
|
||||
return map != null ? new HashMap<>(map) : new HashMap<>();
|
||||
}
|
||||
|
||||
private static Map<String, Map<String, String>> copyStringMapMap(Map<String, Map<String, String>> map) {
|
||||
return map != null ? new HashMap<>(map) : new HashMap<>();
|
||||
}
|
||||
|
||||
private static void applyCommonEnemyFields(Enemy enemy, EnemyData data) {
|
||||
enemy.setName(data.name());
|
||||
enemy.setLevel(normalize(data.level()));
|
||||
enemy.setFolder(normalize(data.folder()));
|
||||
enemy.setPortraitImageId(data.portraitImageId());
|
||||
enemy.setHeaderImageId(data.headerImageId());
|
||||
enemy.setValues(copyStringMap(data.values()));
|
||||
enemy.setImageValues(copyStringListMap(data.imageValues()));
|
||||
enemy.setKeyValueValues(copyStringMapMap(data.keyValueValues()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
|
||||
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* IA des méthodes guidées (Mentor d'écriture) : propose des réponses aux questions d'une
|
||||
* méthode à partir de l'idée de départ du MJ et de la campagne. Rien n'est enregistré : le
|
||||
* front remplit les champs vides et le MJ relit, corrige ou relance.
|
||||
*
|
||||
* <p>Garde-fous : nombre de questions et longueur des textes bornés (le prompt reste
|
||||
* raisonnable) ; en retour, seules les clés demandées sont gardées, et une question à choix
|
||||
* n'accepte qu'une des valeurs proposées.</p>
|
||||
*/
|
||||
@Service
|
||||
public class GuidedAssistService {
|
||||
|
||||
static final int MAX_QUESTIONS = 80;
|
||||
static final int MAX_TEXT = 4_000;
|
||||
|
||||
private final GuidedMethodAssistant assistant;
|
||||
private final CampaignContextFormatter contextFormatter;
|
||||
|
||||
public GuidedAssistService(GuidedMethodAssistant assistant, CampaignContextFormatter contextFormatter) {
|
||||
this.assistant = assistant;
|
||||
this.contextFormatter = contextFormatter;
|
||||
}
|
||||
|
||||
/** Demande à proposer des réponses. @throws IllegalArgumentException aucune question valide */
|
||||
public Map<String, String> suggest(String campaignId, String methodName, String principle, String idea,
|
||||
List<Question> questions, Map<String, String> existing) {
|
||||
List<Question> valid = questions == null ? List.of() : questions.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.filter(q -> q.key() != null && !q.key().isBlank())
|
||||
.limit(MAX_QUESTIONS)
|
||||
.toList();
|
||||
if (valid.isEmpty()) {
|
||||
throw new IllegalArgumentException("Aucune question à laquelle répondre.");
|
||||
}
|
||||
Map<String, String> answers = assistant.answer(cap(methodName), cap(principle), cap(idea),
|
||||
contextFormatter.format(campaignId), valid, capAll(existing));
|
||||
return keepValid(answers, valid);
|
||||
}
|
||||
|
||||
/** Clés demandées uniquement, valeurs non vides ; choix limités aux valeurs proposées. */
|
||||
static Map<String, String> keepValid(Map<String, String> answers, List<Question> questions) {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
if (answers == null) return out;
|
||||
Map<String, Question> byKey = questions.stream()
|
||||
.collect(Collectors.toMap(Question::key, q -> q, (a, b) -> a, LinkedHashMap::new));
|
||||
for (Map.Entry<String, String> e : answers.entrySet()) {
|
||||
Question q = byKey.get(e.getKey());
|
||||
String value = e.getValue() == null ? "" : e.getValue().trim();
|
||||
if (q == null || value.isEmpty()) continue;
|
||||
if (q.options() != null && !q.options().isEmpty()) {
|
||||
Set<String> allowed = q.options().stream().map(Choice::value).collect(Collectors.toSet());
|
||||
if (!allowed.contains(value)) continue;
|
||||
}
|
||||
out.put(q.key(), cap(value));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, String> capAll(Map<String, String> existing) {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
if (existing == null) return out;
|
||||
existing.forEach((k, v) -> {
|
||||
if (k != null && v != null && !v.isBlank()) out.put(k, cap(v.trim()));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String cap(String s) {
|
||||
if (s == null) return "";
|
||||
return s.length() > MAX_TEXT ? s.substring(0, MAX_TEXT) : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Identifiants des méthodes guidées et de leurs rôles (« five-room », « room3 »…). Le Core
|
||||
* ne connaît pas la liste des méthodes (elles sont décrites côté front) : il vérifie
|
||||
* seulement la forme de l'identifiant avant de le stocker.
|
||||
*/
|
||||
final class GuidedKeys {
|
||||
|
||||
private static final Pattern KEY = Pattern.compile("[A-Za-z0-9_-]{1,64}");
|
||||
|
||||
private GuidedKeys() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return l'identifiant nettoyé, ou {@code null} s'il est absent ou vide
|
||||
* @throws IllegalArgumentException identifiant mal formé
|
||||
*/
|
||||
static String normalize(String key) {
|
||||
if (key == null || key.isBlank()) return null;
|
||||
String trimmed = key.trim();
|
||||
if (!KEY.matcher(trimmed).matches()) {
|
||||
throw new IllegalArgumentException("Identifiant de méthode guidée invalide.");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Forme des méthodes guidées que la relecture sait juger : pour chaque méthode, ses rôles
|
||||
* dans l'ordre. Les méthodes elles-mêmes (questions, textes) sont décrites côté front
|
||||
* ({@code web/src/app/campaigns/guided/methods}) ; seule cette liste est répétée ici, et le
|
||||
* test front {@code guided-methods.spec.ts} vérifie que les deux côtés disent la même chose.
|
||||
*
|
||||
* <p>Une méthode absente de cette table reste utilisable : la relecture ne dit simplement
|
||||
* rien de propre à elle.</p>
|
||||
*/
|
||||
final class GuidedMethodShapes {
|
||||
|
||||
static final String FIVE_ROOM = "five-room";
|
||||
static final String INVESTIGATION = "investigation";
|
||||
static final String VILLAIN_PLAN = "villain-plan";
|
||||
|
||||
/** Donjon en 5 salles : l'épreuve, qui ne se règle pas à l'épée. */
|
||||
static final String FIVE_ROOM_TRIAL = "room2";
|
||||
/** Enquête en nœuds : la conclusion, que trois pistes doivent atteindre. */
|
||||
static final String INVESTIGATION_CONCLUSION = "conclusion";
|
||||
|
||||
private static final Map<String, List<String>> ROLES = Map.of(
|
||||
FIVE_ROOM, List.of("room1", "room2", "room3", "room4", "room5"),
|
||||
INVESTIGATION, List.of("hook", "node1", "node2", "node3", "conclusion", "proactive"),
|
||||
VILLAIN_PLAN, List.of("step1", "step2", "step3", "step4", "step5", "step6"));
|
||||
|
||||
private GuidedMethodShapes() {
|
||||
}
|
||||
|
||||
/** Rôles de la méthode, dans l'ordre ; liste vide si la méthode est absente ou inconnue. */
|
||||
static List<String> rolesOf(String method) {
|
||||
return method == null ? List.of() : ROLES.getOrDefault(method, List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3 —
|
||||
* voir docs/conception-mentor-ecriture.md) : un chapitre et ses scènes, rédigés par le MJ
|
||||
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
||||
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||
*
|
||||
* <p>Placement en chapitre : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le
|
||||
* chapitre est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la
|
||||
* suite). Exactement l'un des deux.</p>
|
||||
*
|
||||
* <p>Placement en quête ({@code asQuest}) : l'aventure devient une quête, rangée dans l'arc
|
||||
* de quêtes {@code arcId} (arc HUB), ou libre si {@code arcId} est absent. Le texte du
|
||||
* chapitre va sur la quête ; ses scènes vont dans le chapitre-conteneur de la quête, qui
|
||||
* garde la méthode.</p>
|
||||
*
|
||||
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||
* @param chapter le chapitre (nom obligatoire)
|
||||
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
|
||||
* @param linkSequentially relier chaque scène à la suivante par une sortie
|
||||
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
||||
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
||||
* une enquête en nœuds relie ses pistes en réseau, pas en chaîne
|
||||
* @param clock horloge à créer dans chaque partie de la campagne (plan du méchant), ou {@code null}
|
||||
* @param method identifiant de la méthode suivie (« five-room »…), gardé sur le chapitre, ou {@code null}
|
||||
* @param asQuest {@code true} : créer une quête plutôt qu'un chapitre
|
||||
* @param intoChapterId chapitre VIDE de {@code arcId} à remplir au lieu d'en créer un (campagne « à plat » :
|
||||
* son chapitre créé d'office) ; ignoré s'il a déjà des scènes ou n'est pas dans l'arc
|
||||
*/
|
||||
public record GuidedSkeleton(
|
||||
String arcId,
|
||||
String newArcName,
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel,
|
||||
List<LinkSpec> links,
|
||||
ClockSpec clock,
|
||||
String method,
|
||||
Boolean asQuest,
|
||||
String intoChapterId
|
||||
) {
|
||||
|
||||
/** Squelette rangé dans un nouveau chapitre (ni quête, ni chapitre vide à remplir). */
|
||||
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||
boolean linkSequentially, String linkLabel, List<LinkSpec> links, ClockSpec clock,
|
||||
String method) {
|
||||
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, links, clock, method, null, null);
|
||||
}
|
||||
|
||||
/** Squelette sans méthode nommée (appels antérieurs à la mémorisation de la méthode). */
|
||||
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||
boolean linkSequentially, String linkLabel, List<LinkSpec> links, ClockSpec clock) {
|
||||
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, links, clock, null, null, null);
|
||||
}
|
||||
|
||||
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
||||
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||
boolean linkSequentially, String linkLabel) {
|
||||
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null, null, null, null);
|
||||
}
|
||||
|
||||
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes,
|
||||
String gmNotes) {
|
||||
public ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
this(name, description, playerObjectives, narrativeStakes, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lien d'une scène vers une autre, par position dans {@code scenes}.
|
||||
*
|
||||
* @param from index de la scène de départ
|
||||
* @param to index de la scène d'arrivée
|
||||
* @param label libellé du lien (langue du MJ)
|
||||
* @param kind nature du lien (sortie, piste, indice) ; {@code null} = sortie
|
||||
*/
|
||||
public record LinkSpec(int from, int to, String label, LinkType kind) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Horloge de progression à créer dans chaque partie (Playthrough) de la campagne.
|
||||
*
|
||||
* @param name nom de l'horloge
|
||||
* @param description ce qui arrive quand elle est pleine
|
||||
* @param segments nombre de segments (une étape du plan = un segment)
|
||||
*/
|
||||
public record ClockSpec(String name, String description, int segments) {
|
||||
}
|
||||
|
||||
/** @param role rôle de la scène dans la méthode (« room3 », « conclusion »…), ou {@code null} */
|
||||
public record SceneSpec(
|
||||
String name, String description, SceneType type, String location,
|
||||
String choicesConsequences, String gmSecretNotes, String enemies, String role) {
|
||||
public SceneSpec(String name, String description, SceneType type, String location,
|
||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||
this(name, description, type, location, choicesConsequences, gmSecretNotes, enemies, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ce qui a été créé, pour que le front ouvre directement le chapitre.
|
||||
*
|
||||
* @param clocks nombre d'horloges créées (une par partie de la campagne)
|
||||
* @param questId quête créée (placement en quête), ou {@code null} ; {@code arcId} et
|
||||
* {@code chapterId} désignent alors son chapitre-conteneur
|
||||
*/
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds, int clocks, String questId) {
|
||||
public Result(String arcId, String chapterId, List<String> sceneIds, int clocks) {
|
||||
this(arcId, chapterId, sceneIds, clocks, null);
|
||||
}
|
||||
|
||||
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
this(arcId, chapterId, sceneIds, 0, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.application.playcontext.ClockService;
|
||||
import com.loremind.domain.playcontext.ClockTrigger;
|
||||
import com.loremind.domain.playcontext.Playthrough;
|
||||
import com.loremind.domain.playcontext.ports.PlaythroughRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Persiste d'un bloc le squelette d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
||||
*
|
||||
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
||||
* arc et le nouveau chapitre se placent à la suite). Seule exception : le chapitre VIDE
|
||||
* d'une campagne « à plat », créé d'office, peut être rempli au lieu d'être doublé.
|
||||
* L'aventure peut aussi devenir une quête (arc de quêtes ou quête libre).
|
||||
* Transactionnel : tout ou rien.</p>
|
||||
*/
|
||||
@Service
|
||||
public class GuidedSkeletonService {
|
||||
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final ArcService arcService;
|
||||
private final ChapterService chapterService;
|
||||
private final SceneService sceneService;
|
||||
private final PlaythroughRepository playthroughRepository;
|
||||
private final ClockService clockService;
|
||||
private final QuestService questService;
|
||||
private final QuestRepository questRepository;
|
||||
|
||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService,
|
||||
PlaythroughRepository playthroughRepository,
|
||||
ClockService clockService,
|
||||
QuestService questService,
|
||||
QuestRepository questRepository) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
this.playthroughRepository = playthroughRepository;
|
||||
this.clockService = clockService;
|
||||
this.questService = questService;
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** Où l'aventure a été rangée : son chapitre (ou conteneur de quête) et, le cas échéant, la quête. */
|
||||
private record Placement(Chapter chapter, String questId) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||
* arc d'une autre campagne ou du mauvais type)
|
||||
*/
|
||||
@Transactional
|
||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||
validate(skeleton);
|
||||
String method = GuidedKeys.normalize(skeleton.method());
|
||||
Placement placement = isQuest(skeleton)
|
||||
? placeInQuest(campaignId, skeleton, method)
|
||||
: placeInChapter(campaignId, skeleton, method);
|
||||
Chapter chapter = placement.chapter();
|
||||
|
||||
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
List<Scene> byIndex = new ArrayList<>();
|
||||
int order = 0;
|
||||
for (GuidedSkeleton.SceneSpec spec : skeleton.scenes()) {
|
||||
if (spec == null || isBlank(spec.name())) {
|
||||
byIndex.add(null);
|
||||
continue;
|
||||
}
|
||||
Scene created = sceneService.createScene(Scene.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
||||
.location(blankToNull(spec.location()))
|
||||
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||
.enemies(blankToNull(spec.enemies()))
|
||||
.guidedRole(chapter.getGuidedMethod() == null ? null : GuidedKeys.normalize(spec.role()))
|
||||
.chapterId(chapter.getId())
|
||||
.order(order++)
|
||||
.build());
|
||||
scenes.add(created);
|
||||
byIndex.add(created);
|
||||
}
|
||||
|
||||
if (skeleton.linkSequentially()) {
|
||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||
}
|
||||
if (skeleton.links() != null && !skeleton.links().isEmpty()) {
|
||||
linkExplicitly(byIndex, skeleton.links());
|
||||
}
|
||||
int clocks = createClocks(campaignId, skeleton.clock());
|
||||
|
||||
return new GuidedSkeleton.Result(chapter.getArcId(), chapter.getId(),
|
||||
scenes.stream().map(Scene::getId).toList(), clocks, placement.questId());
|
||||
}
|
||||
|
||||
private static boolean isQuest(GuidedSkeleton skeleton) {
|
||||
return Boolean.TRUE.equals(skeleton.asQuest());
|
||||
}
|
||||
|
||||
/** Aventure rangée dans un chapitre : le chapitre vide désigné s'il est utilisable, sinon un nouveau. */
|
||||
private Placement placeInChapter(String campaignId, GuidedSkeleton skeleton, String method) {
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter empty = emptyChapterToFill(arcId, skeleton.intoChapterId());
|
||||
Chapter chapter = empty != null
|
||||
? fillChapter(empty, skeleton.chapter(), method)
|
||||
: createChapter(arcId, skeleton.chapter(), method);
|
||||
return new Placement(chapter, null);
|
||||
}
|
||||
|
||||
/** Le chapitre désigné, s'il est bien dans l'arc et sans aucune scène ; sinon {@code null}. */
|
||||
private Chapter emptyChapterToFill(String arcId, String chapterId) {
|
||||
if (isBlank(chapterId)) return null;
|
||||
return chapterRepository.findById(chapterId)
|
||||
.filter(c -> arcId.equals(c.getArcId()))
|
||||
.filter(c -> sceneRepository.findByChapterId(c.getId()).isEmpty())
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private Chapter fillChapter(Chapter chapter, GuidedSkeleton.ChapterSpec spec, String method) {
|
||||
chapter.setName(spec.name().trim());
|
||||
chapter.setDescription(blankToNull(spec.description()));
|
||||
chapter.setPlayerObjectives(blankToNull(spec.playerObjectives()));
|
||||
chapter.setNarrativeStakes(blankToNull(spec.narrativeStakes()));
|
||||
chapter.setGmNotes(blankToNull(spec.gmNotes()));
|
||||
chapter.setGuidedMethod(method);
|
||||
return chapterRepository.save(chapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aventure rangée dans une quête : le texte du chapitre va sur la quête (c'est elle que le
|
||||
* MJ lit), les scènes dans son chapitre-conteneur, qui garde la méthode.
|
||||
*/
|
||||
private Placement placeInQuest(String campaignId, GuidedSkeleton skeleton, String method) {
|
||||
String hubArcId = isBlank(skeleton.arcId()) ? null : resolveHubArc(campaignId, skeleton.arcId());
|
||||
GuidedSkeleton.ChapterSpec spec = skeleton.chapter();
|
||||
int order = questRepository.findByCampaignId(campaignId).stream()
|
||||
.mapToInt(Quest::getOrder).max().orElse(0) + 1;
|
||||
Quest quest = questService.createQuest(Quest.builder()
|
||||
.campaignId(campaignId)
|
||||
.arcId(hubArcId)
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||
.gmNotes(blankToNull(spec.gmNotes()))
|
||||
.order(order)
|
||||
.build());
|
||||
Chapter container = quest.getNodes().stream()
|
||||
.filter(n -> n.nodeType() == NodeType.CHAPTER)
|
||||
.map(QuestNodeRef::nodeId)
|
||||
.findFirst()
|
||||
.flatMap(chapterRepository::findById)
|
||||
.orElseThrow(() -> new IllegalStateException("La quête créée n'a pas de conteneur de scènes."));
|
||||
container.setGuidedMethod(method);
|
||||
return new Placement(chapterRepository.save(container), quest.getId());
|
||||
}
|
||||
|
||||
private String resolveHubArc(String campaignId, String arcId) {
|
||||
Arc arc = arcRepository.findByCampaignId(campaignId).stream()
|
||||
.filter(a -> arcId.equals(a.getId())).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||
if (arc.getType() != ArcType.HUB) {
|
||||
throw new IllegalArgumentException("Une quête guidée se range dans un arc de quêtes.");
|
||||
}
|
||||
return arc.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Liens explicites (réseau d'une enquête) : ajoutés aux sorties existantes. Un lien vers
|
||||
* ou depuis une scène ignorée (sans nom), hors limites ou en boucle sur soi est écarté.
|
||||
*/
|
||||
private void linkExplicitly(List<Scene> byIndex, List<GuidedSkeleton.LinkSpec> links) {
|
||||
java.util.Map<String, Scene> touched = new java.util.LinkedHashMap<>();
|
||||
for (GuidedSkeleton.LinkSpec link : links) {
|
||||
if (link == null || link.from() == link.to()) continue;
|
||||
Scene from = at(byIndex, link.from());
|
||||
Scene to = at(byIndex, link.to());
|
||||
if (from == null || to == null) continue;
|
||||
List<SceneBranch> branches = from.getBranches() == null ? new ArrayList<>() : new ArrayList<>(from.getBranches());
|
||||
String label = isBlank(link.label()) ? to.getName() : link.label().trim();
|
||||
branches.add(new SceneBranch(label, to.getId(), null,
|
||||
Objects.requireNonNullElse(link.kind(), LinkType.EXIT)));
|
||||
from.setBranches(branches);
|
||||
touched.put(from.getId(), from);
|
||||
}
|
||||
touched.values().forEach(sceneRepository::save);
|
||||
}
|
||||
|
||||
private static Scene at(List<Scene> byIndex, int index) {
|
||||
return index >= 0 && index < byIndex.size() ? byIndex.get(index) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Horloge du plan (méthode « Plan du méchant ») : créée dans chaque partie de la campagne,
|
||||
* car une horloge est de l'état de partie. Aucune partie : rien n'est créé (le MJ la
|
||||
* créera quand il lancera une partie).
|
||||
*/
|
||||
private int createClocks(String campaignId, GuidedSkeleton.ClockSpec clock) {
|
||||
if (clock == null || isBlank(clock.name())) return 0;
|
||||
int count = 0;
|
||||
for (Playthrough p : playthroughRepository.findByCampaignId(campaignId)) {
|
||||
clockService.create(p.getId(), clock.name().trim(), blankToNull(clock.description()),
|
||||
clock.segments(), ClockTrigger.NONE, null, null);
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void validate(GuidedSkeleton skeleton) {
|
||||
if (skeleton == null) {
|
||||
throw new IllegalArgumentException("Squelette manquant.");
|
||||
}
|
||||
boolean hasArc = !isBlank(skeleton.arcId());
|
||||
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||
if (isQuest(skeleton)) {
|
||||
// Quête : arc de quêtes facultatif (absent = quête libre), jamais de nouvel arc.
|
||||
if (hasNewArc) {
|
||||
throw new IllegalArgumentException("Une quête guidée ne crée pas d'arc.");
|
||||
}
|
||||
} else if (hasArc == hasNewArc) {
|
||||
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||
}
|
||||
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||
throw new IllegalArgumentException("Le chapitre doit avoir un nom.");
|
||||
}
|
||||
if (skeleton.scenes() == null || skeleton.scenes().stream().noneMatch(s -> s != null && !isBlank(s.name()))) {
|
||||
throw new IllegalArgumentException("Il faut au moins une scène nommée.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Arc existant (vérifié : même campagne, linéaire) ou nouvel arc linéaire placé à la suite. */
|
||||
private String resolveArc(String campaignId, GuidedSkeleton skeleton) {
|
||||
List<Arc> arcs = arcRepository.findByCampaignId(campaignId);
|
||||
if (!isBlank(skeleton.arcId())) {
|
||||
Arc arc = arcs.stream().filter(a -> skeleton.arcId().equals(a.getId())).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||
if (arc.getType() != ArcType.LINEAR) {
|
||||
throw new IllegalArgumentException("Une méthode guidée s'ajoute à un arc linéaire.");
|
||||
}
|
||||
return arc.getId();
|
||||
}
|
||||
// L'arc SYSTEM (« Quêtes libres », ordre 9999) reste en dernier : on ne le compte pas.
|
||||
int nextOrder = arcs.stream().filter(a -> a.getType() != ArcType.SYSTEM)
|
||||
.mapToInt(Arc::getOrder).max().orElse(-1) + 1;
|
||||
return arcService.createArc(Arc.builder()
|
||||
.name(skeleton.newArcName().trim())
|
||||
.campaignId(campaignId)
|
||||
.type(ArcType.LINEAR)
|
||||
.order(nextOrder)
|
||||
.build()).getId();
|
||||
}
|
||||
|
||||
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec, String method) {
|
||||
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||
return chapterService.createChapter(Chapter.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||
.gmNotes(blankToNull(spec.gmNotes()))
|
||||
.guidedMethod(method)
|
||||
.arcId(arcId)
|
||||
.order(nextOrder)
|
||||
.build());
|
||||
}
|
||||
|
||||
/** Chaque scène reçoit une sortie vers la suivante (la dernière n'en a pas). */
|
||||
private void linkInChain(List<Scene> scenes, String label) {
|
||||
for (int i = 0; i < scenes.size() - 1; i++) {
|
||||
Scene scene = scenes.get(i);
|
||||
scene.setBranches(new ArrayList<>(List.of(
|
||||
new SceneBranch(label, scenes.get(i + 1).getId(), null, LinkType.EXIT))));
|
||||
sceneRepository.save(scene);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String blankToNull(String s) {
|
||||
return isBlank(s) ? null : s.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Arc « implicite » : le seul arc visible de la campagne, linéaire, vide de texte et encore à
|
||||
* son nom d'office. L'auteur ne l'a pas créé (il vient d'une scène ajoutée rapidement ou
|
||||
* d'une méthode guidée) : l'interface ne le lui montre pas comme un arc, et la relecture ne
|
||||
* doit donc ni lui réclamer des enjeux, ni le citer par son nom.
|
||||
*
|
||||
* <p>Miroir de {@code implicitArc} côté front ({@code web/src/app/campaigns/flat-structure.ts}) ;
|
||||
* le test front {@code flat-structure.spec.ts} vérifie que les deux côtés connaissent les
|
||||
* mêmes noms d'office.</p>
|
||||
*/
|
||||
public final class ImplicitArc {
|
||||
|
||||
/** Noms donnés à l'arc créé d'office, dans chaque langue de l'interface. */
|
||||
public static final List<String> DEFAULT_NAMES = List.of("Arc principal", "Main arc");
|
||||
|
||||
private ImplicitArc() {
|
||||
}
|
||||
|
||||
static boolean is(Arc arc, List<Arc> campaignArcs) {
|
||||
long visible = campaignArcs.stream().filter(a -> a.getType() != ArcType.SYSTEM).count();
|
||||
return visible == 1
|
||||
&& arc.getType() != ArcType.SYSTEM && arc.getType() != ArcType.HUB
|
||||
&& isDefaultName(arc.getName())
|
||||
&& isBare(arc);
|
||||
}
|
||||
|
||||
/** L'arc porte-t-il encore le nom qu'on lui a donné d'office ? (le livret PDF applique la même règle) */
|
||||
public static boolean isDefaultName(String name) {
|
||||
return name != null && DEFAULT_NAMES.contains(name.trim());
|
||||
}
|
||||
|
||||
/** Aucun contenu d'écriture dans l'arc (son nom ne compte pas). */
|
||||
private static boolean isBare(Arc arc) {
|
||||
return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(),
|
||||
arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks())
|
||||
&& (arc.getIllustrationImageIds() == null || arc.getIllustrationImageIds().isEmpty());
|
||||
}
|
||||
|
||||
private static boolean allBlank(String... values) {
|
||||
for (String v : values) {
|
||||
if (v != null && !v.isBlank()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+7
-28
@@ -1,12 +1,9 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.itemcatalog.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.itemcatalog.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogRepository;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -21,18 +18,15 @@ public class ItemCatalogService {
|
||||
|
||||
private final ItemCatalogRepository repository;
|
||||
private final ItemCatalogGenerator generator;
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
private final CampaignContextFormatter campaignContextFormatter;
|
||||
|
||||
public ItemCatalogService(
|
||||
ItemCatalogRepository repository,
|
||||
ItemCatalogGenerator generator,
|
||||
CampaignRepository campaignRepository,
|
||||
GameSystemRepository gameSystemRepository) {
|
||||
CampaignContextFormatter campaignContextFormatter) {
|
||||
this.repository = repository;
|
||||
this.generator = generator;
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
this.campaignContextFormatter = campaignContextFormatter;
|
||||
}
|
||||
|
||||
public record CatalogData(
|
||||
@@ -89,7 +83,8 @@ public class ItemCatalogService {
|
||||
|
||||
/** Génère une PROPOSITION de catalogue (non persistée) via l'IA, contextualisée campagne. */
|
||||
public ItemCatalog generateProposal(String campaignId, String description) {
|
||||
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(description, buildContext(campaignId));
|
||||
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(
|
||||
description, campaignContextFormatter.format(campaignId));
|
||||
return ItemCatalog.builder()
|
||||
.name(g.name())
|
||||
.description(g.description())
|
||||
@@ -102,22 +97,6 @@ public class ItemCatalogService {
|
||||
return items != null ? new ArrayList<>(items) : new ArrayList<>();
|
||||
}
|
||||
|
||||
private String buildContext(String campaignId) {
|
||||
if (campaignId == null) return "";
|
||||
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
|
||||
if (campaign == null) return "";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Campagne : ").append(campaign.getName());
|
||||
if (campaign.getDescription() != null && !campaign.getDescription().isBlank()) {
|
||||
sb.append(" — ").append(campaign.getDescription().trim());
|
||||
}
|
||||
if (campaign.getGameSystemId() != null && !campaign.getGameSystemId().isBlank()) {
|
||||
gameSystemRepository.findById(campaign.getGameSystemId())
|
||||
.ifPresent(gs -> sb.append("\nSystème de jeu : ").append(gs.getName()));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private int nextOrderFor(String campaignId) {
|
||||
return repository.findByCampaignId(campaignId).stream()
|
||||
.mapToInt(ItemCatalog::getOrder)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user