Compare commits
9
Commits
c008c22e09
..
beta
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd54f05b78 | ||
|
|
4998ac3849 | ||
|
|
3c76762efc | ||
|
|
6c1d74f9a5 | ||
|
|
0d56f8527b | ||
|
|
3f0766ccbe | ||
|
|
b9020cb46f | ||
|
|
10574ba0c5 | ||
|
|
ace2e486fc |
@@ -104,6 +104,10 @@ jobs:
|
|||||||
windows:
|
windows:
|
||||||
needs: tests
|
needs: tests
|
||||||
runs-on: windows-latest
|
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:
|
steps:
|
||||||
# En declenchement manuel, on checkout le TAG correspondant a la version
|
# En declenchement manuel, on checkout le TAG correspondant a la version
|
||||||
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
# saisie (sinon checkout prendrait la branche par defaut). En push de tag,
|
||||||
@@ -167,17 +171,14 @@ jobs:
|
|||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
run: .\installers\desktop\build-windows.ps1 -Version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
# Release GitHub publique avec le .msi ; une beta est publiee en pre-release.
|
# Le .msi est passe au job `publish`, seul a creer la release.
|
||||||
# tag_name explicite : en declenchement manuel, github.ref est une branche,
|
- name: Keep installer for the release
|
||||||
# donc on cible le tag derive (la release est attachee au bon tag).
|
uses: actions/upload-artifact@v4
|
||||||
- name: Publish installer to GitHub Release
|
|
||||||
uses: softprops/action-gh-release@v2
|
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.ver.outputs.tag }}
|
name: installer-windows
|
||||||
files: core/target/dist-out/*.msi
|
path: core/target/dist-out/*.msi
|
||||||
fail_on_unmatched_files: true
|
if-no-files-found: error
|
||||||
generate_release_notes: true
|
retention-days: 7
|
||||||
prerelease: ${{ steps.ver.outputs.isbeta == 'true' }}
|
|
||||||
|
|
||||||
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
# LINUX : AppImage (1 fichier, toutes distros) attache a la MEME release.
|
||||||
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
# Tourne sur ubuntu-latest (jpackage ne cross-compile pas -> build natif Linux).
|
||||||
@@ -230,13 +231,40 @@ jobs:
|
|||||||
GITHUB_TOKEN: ${{ github.token }}
|
GITHUB_TOKEN: ${{ github.token }}
|
||||||
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
run: bash ./installers/desktop/build-linux.sh --version ${{ steps.ver.outputs.version }}
|
||||||
|
|
||||||
# Attache l'AppImage a la release (meme tag que le .msi -> les deux
|
# L'AppImage est passee au job `publish`, seul a creer la release.
|
||||||
# installeurs sur la meme release). prerelease aussi ici : le job qui cree
|
- name: Keep AppImage for the release
|
||||||
# la release en premier fixe son statut.
|
uses: actions/upload-artifact@v4
|
||||||
- name: Publish AppImage to GitHub Release
|
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
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.ver.outputs.tag }}
|
tag_name: ${{ needs.windows.outputs.tag }}
|
||||||
files: core/target/dist-out/DM_Loremind*.AppImage
|
files: dist/*
|
||||||
fail_on_unmatched_files: true
|
fail_on_unmatched_files: true
|
||||||
prerelease: ${{ steps.ver.outputs.isbeta == 'true' }}
|
generate_release_notes: true
|
||||||
|
prerelease: ${{ needs.windows.outputs.isbeta == 'true' }}
|
||||||
|
|||||||
+16
-6
@@ -111,14 +111,20 @@ def get_import_rules_use_case(
|
|||||||
settings: Annotated[Settings, Depends(get_settings)],
|
settings: Annotated[Settings, Depends(get_settings)],
|
||||||
) -> ImportRulesUseCase:
|
) -> ImportRulesUseCase:
|
||||||
"""Factory du use case d'import de règles PDF (extraction + structuration)."""
|
"""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
|
# Les règles importées doivent correspondre au texte du PDF : l'IA ne le réécrit jamais,
|
||||||
# sections (~200 tokens) et le texte original est découpé localement. Réécrire
|
# quel que soit le fournisseur.
|
||||||
# tout le contenu à ~100 tokens/s prendrait des dizaines de minutes par livre.
|
# - Le livre est d'abord découpé par sa propre structure (signets du PDF, sinon titres
|
||||||
# Les providers cloud (rapides, grand contexte) gardent la réécriture nettoyée.
|
# 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(
|
return ImportRulesUseCase(
|
||||||
llm=llm, extractor=_PDF_EXTRACTOR,
|
llm=llm, extractor=_PDF_EXTRACTOR,
|
||||||
chunk_target_tokens=_effective_import_chunk_tokens(settings),
|
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(
|
def get_import_campaign_use_case(
|
||||||
@@ -126,11 +132,15 @@ def get_import_campaign_use_case(
|
|||||||
settings: Annotated[Settings, Depends(get_settings)],
|
settings: Annotated[Settings, Depends(get_settings)],
|
||||||
) -> ImportCampaignUseCase:
|
) -> ImportCampaignUseCase:
|
||||||
"""Factory du use case d'import de campagne PDF (extraction + arborescence)."""
|
"""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(
|
return ImportCampaignUseCase(
|
||||||
llm=llm,
|
llm=llm,
|
||||||
extractor=_PDF_EXTRACTOR,
|
extractor=_PDF_EXTRACTOR,
|
||||||
chunk_target_tokens=_effective_import_chunk_tokens(settings),
|
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."""
|
"""Endpoint du chat contextuel (/chat/stream) : Structural Context + jauge tokens."""
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from typing import Annotated, AsyncIterator
|
from typing import Annotated, AsyncIterator
|
||||||
|
|
||||||
import tiktoken
|
import tiktoken
|
||||||
@@ -22,6 +23,8 @@ from app.core.language import get_user_language
|
|||||||
from app.domain.models import ChatMessage
|
from app.domain.models import ChatMessage
|
||||||
from app.domain.ports import LLMProviderError
|
from app.domain.ports import LLMProviderError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
# 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 f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||||
yield "event: done\ndata: {}\n\n"
|
yield "event: done\ndata: {}\n\n"
|
||||||
except LLMProviderError as exc:
|
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"
|
yield f"event: error\ndata: {json.dumps({'message': str(exc)})}\n\n"
|
||||||
|
|
||||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ 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 narrative_fields as narrative_fields_prompts
|
||||||
from app.application.prompts import scene_drafts as scene_drafts_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 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.config import Settings, get_settings
|
||||||
from app.core.language import get_user_language
|
from app.core.language import get_user_language
|
||||||
from app.domain.models import PageGenerationContext
|
from app.domain.models import PageGenerationContext
|
||||||
@@ -370,3 +371,105 @@ def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dic
|
|||||||
continue
|
continue
|
||||||
out[field.key] = text
|
out[field.key] = text
|
||||||
return out
|
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
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ async def import_rules_stream(
|
|||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — filet : une erreur inattendue ne doit
|
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
|
# PAS casser le flux SSE brutalement (sinon le Core n'a qu'un message générique
|
||||||
@@ -127,6 +128,8 @@ async def import_campaign_stream(
|
|||||||
|
|
||||||
Évènements : `extracting`, `start` {page_count, ocr_page_count, total},
|
Évènements : `extracting`, `start` {page_count, ocr_page_count, total},
|
||||||
`progress` {current, total, arc_count, chapter_count, scene_count},
|
`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}.
|
`done` {arcs:[...], page_count, ocr_page_count}, `error` {message}.
|
||||||
"""
|
"""
|
||||||
content = await file.read()
|
content = await file.read()
|
||||||
@@ -143,6 +146,7 @@ async def import_campaign_stream(
|
|||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas
|
except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas
|
||||||
# une erreur inattendue casser le flux sans détail.
|
# une erreur inattendue casser le flux sans détail.
|
||||||
@@ -189,6 +193,7 @@ async def adapt_campaign_stream(
|
|||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
|
logger.warning("Import : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
|
|
||||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
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(ev_type, ev)
|
||||||
yield sse_event("done", {})
|
yield sse_event("done", {})
|
||||||
except (LLMProviderError, EmbeddingError) as exc:
|
except (LLMProviderError, EmbeddingError) as exc:
|
||||||
|
logger.warning("Atelier : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux.
|
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux.
|
||||||
logger.exception("Chat notebook : erreur inattendue.")
|
logger.exception("Chat notebook : erreur inattendue.")
|
||||||
@@ -125,6 +126,7 @@ async def chat_notebook_deep_stream(
|
|||||||
ev_type = ev.pop("type")
|
ev_type = ev.pop("type")
|
||||||
yield sse_event(ev_type, ev)
|
yield sse_event(ev_type, ev)
|
||||||
except (LLMProviderError, EmbeddingError) as exc:
|
except (LLMProviderError, EmbeddingError) as exc:
|
||||||
|
logger.warning("Atelier : erreur du fournisseur IA : %s", exc)
|
||||||
yield sse_event("error", {"message": str(exc)})
|
yield sse_event("error", {"message": str(exc)})
|
||||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale.
|
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale.
|
||||||
logger.exception("Analyse approfondie : erreur inattendue.")
|
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 asyncio
|
||||||
import logging
|
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.chunking import chunk_text, split_in_half
|
||||||
from app.application.import_status import (
|
from app.application.import_status import (
|
||||||
notify_status,
|
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_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
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.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
|
# 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).
|
# 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
|
# 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).
|
# fragmenter en dizaines de scènes. Adapté aux providers à grand contexte (1min.ai).
|
||||||
_CHUNK_TARGET_TOKENS = 10000
|
_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
|
# 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
|
# contraint la grammaire : un modèle local ne PEUT plus produire de clés
|
||||||
@@ -352,10 +393,21 @@ class ImportCampaignUseCase:
|
|||||||
extractor: PdfTextExtractor,
|
extractor: PdfTextExtractor,
|
||||||
chunk_target_tokens: int = _CHUNK_TARGET_TOKENS,
|
chunk_target_tokens: int = _CHUNK_TARGET_TOKENS,
|
||||||
map_concurrency: int = 1,
|
map_concurrency: int = 1,
|
||||||
|
structure_first: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._llm = llm
|
self._llm = llm
|
||||||
self._extractor = extractor
|
self._extractor = extractor
|
||||||
self._chunk_target_tokens = chunk_target_tokens
|
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é
|
# 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
|
# (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.
|
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||||
@@ -364,6 +416,19 @@ class ImportCampaignUseCase:
|
|||||||
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
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)
|
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||||
toc_block = _format_toc(doc.toc)
|
toc_block = _format_toc(doc.toc)
|
||||||
merger = _TreeMerger()
|
merger = _TreeMerger()
|
||||||
@@ -397,6 +462,12 @@ class ImportCampaignUseCase:
|
|||||||
yield {"type": "extracting"}
|
yield {"type": "extracting"}
|
||||||
|
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
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)
|
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||||
toc_block = _format_toc(doc.toc)
|
toc_block = _format_toc(doc.toc)
|
||||||
total = len(chunks)
|
total = len(chunks)
|
||||||
@@ -512,6 +583,147 @@ class ImportCampaignUseCase:
|
|||||||
finally:
|
finally:
|
||||||
reset_status_queue(status_token)
|
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) ---------------------
|
# --- Consolidation finale (fusion des quasi-doublons) ---------------------
|
||||||
|
|
||||||
async def _consolidate(self, merger: _TreeMerger) -> None:
|
async def _consolidate(self, merger: _TreeMerger) -> None:
|
||||||
@@ -641,6 +853,281 @@ class ImportCampaignUseCase:
|
|||||||
return empty, recovered
|
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]:
|
def _serialize_arcs(arcs: list[ArcProposal]) -> list[dict]:
|
||||||
"""Sérialise l'arbre de dataclasses en dicts JSON pour le flux SSE."""
|
"""Sérialise l'arbre de dataclasses en dicts JSON pour le flux SSE."""
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -25,9 +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_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
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.prompts import import_rules as prompts
|
||||||
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
from app.application.rules_translation import (
|
||||||
from app.application.streaming import with_heartbeat
|
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
|
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
|
# Repli anti-troncature : si la SORTIE d'un morceau est coupée (le modèle ne peut
|
||||||
@@ -91,9 +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).
|
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
|
||||||
_DETECT_CHARS = 20_000
|
_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:
|
class _SectionMerger:
|
||||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||||
|
|
||||||
@@ -102,15 +121,22 @@ class _SectionMerger:
|
|||||||
morceau — sert au flux de progression pour annoncer les sections trouvées.
|
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._merged: dict[str, list[str]] = {}
|
||||||
self._canonical_key: dict[str, 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]:
|
def add(self, sections: dict[str, str]) -> list[str]:
|
||||||
touched: list[str] = []
|
touched: list[str] = []
|
||||||
for title, content in sections.items():
|
for title, content in sections.items():
|
||||||
title = title.strip()
|
|
||||||
content = (content or "").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:
|
if not title or not content:
|
||||||
continue
|
continue
|
||||||
key = title.lower()
|
key = title.lower()
|
||||||
@@ -120,6 +146,7 @@ class _SectionMerger:
|
|||||||
canonical = self._canonical_key[key]
|
canonical = self._canonical_key[key]
|
||||||
self._merged[canonical].append(content)
|
self._merged[canonical].append(content)
|
||||||
touched.append(canonical)
|
touched.append(canonical)
|
||||||
|
self._last = canonical
|
||||||
# Dé-duplication en préservant l'ordre d'apparition.
|
# Dé-duplication en préservant l'ordre d'apparition.
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
return [t for t in touched if not (t in seen or seen.add(t))]
|
return [t for t in touched if not (t in seen or seen.add(t))]
|
||||||
@@ -215,6 +242,9 @@ def _combine_sections(a: dict[str, str], b: dict[str, str]) -> dict[str, str]:
|
|||||||
out = dict(a)
|
out = dict(a)
|
||||||
by_lower = {k.lower(): k for k in out}
|
by_lower = {k.lower(): k for k in out}
|
||||||
for title, content in b.items():
|
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())
|
key = by_lower.get(title.lower())
|
||||||
if key is not None:
|
if key is not None:
|
||||||
out[key] = f"{out[key]}\n\n{content}".strip()
|
out[key] = f"{out[key]}\n\n{content}".strip()
|
||||||
@@ -233,6 +263,7 @@ class ImportRulesUseCase:
|
|||||||
extractor: PdfTextExtractor,
|
extractor: PdfTextExtractor,
|
||||||
chunk_target_tokens: int = CHUNK_TARGET_TOKENS,
|
chunk_target_tokens: int = CHUNK_TARGET_TOKENS,
|
||||||
segment_only: bool = False,
|
segment_only: bool = False,
|
||||||
|
structure_first: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""`segment_only=True` (modèles locaux) : le LLM ne renvoie que les
|
"""`segment_only=True` (modèles locaux) : le LLM ne renvoie que les
|
||||||
frontières des sections (titre + premiers mots) et le texte original est
|
frontières des sections (titre + premiers mots) et le texte original est
|
||||||
@@ -242,29 +273,45 @@ class ImportRulesUseCase:
|
|||||||
self._extractor = extractor
|
self._extractor = extractor
|
||||||
self._chunk_target_tokens = chunk_target_tokens
|
self._chunk_target_tokens = chunk_target_tokens
|
||||||
self._segment_only = segment_only
|
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:
|
async def execute(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG) -> RulesImportResult:
|
||||||
"""Variante non-streamée : traite tout puis renvoie le résultat complet."""
|
"""Variante non-streamée : traite tout puis renvoie le résultat complet."""
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
doc = self._extractor.extract(pdf_bytes)
|
||||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
structure = self._split_by_structure(doc, language)
|
||||||
logger.info(
|
if structure is not None:
|
||||||
"Import règles : %s page(s) (%s via OCR), %s morceau(x) à traiter.",
|
sections = structure.sections
|
||||||
doc.page_count, doc.ocr_page_count, len(chunks),
|
else:
|
||||||
)
|
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||||
merger = _SectionMerger()
|
logger.info(
|
||||||
for i, chunk in enumerate(chunks):
|
"Import règles : %s page(s) (%s via OCR), %s morceau(x) à traiter.",
|
||||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
doc.page_count, doc.ocr_page_count, len(chunks),
|
||||||
sections = merger.result()
|
)
|
||||||
|
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)
|
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||||
by_language = {source: sections}
|
by_language = {source: sections}
|
||||||
translator = RulesTranslator(self._llm)
|
|
||||||
for target in other_languages(source):
|
for target in other_languages(source):
|
||||||
try:
|
try:
|
||||||
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
|
async for kind, payload in self._translate(sections, source, target):
|
||||||
by_language[target] = {
|
if kind == "result":
|
||||||
titles.get(title, title): await translator.translate_content(content, source, target)
|
by_language[target] = payload.sections
|
||||||
for title, content in sections.items()
|
|
||||||
}
|
|
||||||
except LLMProviderError as exc:
|
except LLMProviderError as exc:
|
||||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||||
return RulesImportResult(
|
return RulesImportResult(
|
||||||
@@ -288,92 +335,132 @@ class ImportRulesUseCase:
|
|||||||
yield {"type": "extracting"}
|
yield {"type": "extracting"}
|
||||||
|
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
doc = self._extractor.extract(pdf_bytes)
|
||||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
structure = self._split_by_structure(doc, language)
|
||||||
total = len(chunks)
|
split_method = structure.method if structure is not None else AI_SPLIT
|
||||||
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()
|
|
||||||
skipped = 0
|
skipped = 0
|
||||||
last_error: str | None = None
|
if structure is not None:
|
||||||
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
# Le livre porte son propre découpage : on le suit, sans appeler l'IA.
|
||||||
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
sections = structure.sections
|
||||||
status_queue: asyncio.Queue = asyncio.Queue()
|
total = 1
|
||||||
status_token = set_status_queue(status_queue)
|
yield {"type": "start", "page_count": doc.page_count,
|
||||||
try:
|
"ocr_page_count": doc.ocr_page_count, "total": 1}
|
||||||
for i, chunk in enumerate(chunks):
|
origin = ("la table des matières du PDF" if structure.method == BOOKMARKS
|
||||||
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
else "les titres du livre")
|
||||||
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
yield {"type": "status",
|
||||||
# HEARTBEAT : on émet des keep-alive pendant l'appel LLM (long sur un
|
"message": f"Découpage d'après {origin} : {len(sections)} sections, sans IA."}
|
||||||
# provider lent) pour que le flux SSE ne soit jamais coupé par le Core.
|
yield {"type": "progress", "current": 1, "total": 1,
|
||||||
new_titles: list[str] = []
|
"new_sections": list(sections)[:_ANNOUNCED_TITLES], "skipped": 0}
|
||||||
try:
|
else:
|
||||||
sections: dict[str, str] | None = None
|
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||||
async for kind, payload in with_heartbeat(
|
total = len(chunks)
|
||||||
self._map_chunk(chunk, index=i, total=total, language=language),
|
logger.info(
|
||||||
status_queue=status_queue,
|
"Import règles (stream) : %s page(s) (%s via OCR), %s morceau(x).",
|
||||||
):
|
doc.page_count, doc.ocr_page_count, total,
|
||||||
if kind == "heartbeat":
|
)
|
||||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
yield {
|
||||||
elif kind == "status":
|
"type": "start",
|
||||||
yield {"type": "status", "message": payload,
|
"page_count": doc.page_count,
|
||||||
"current": i + 1, "total": total}
|
"ocr_page_count": doc.ocr_page_count,
|
||||||
else:
|
"total": total,
|
||||||
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 total > 0 and skipped == total:
|
merger = _SectionMerger()
|
||||||
yield {"type": "error",
|
skipped = 0
|
||||||
"message": "Tous les morceaux ont échoué auprès du fournisseur IA. "
|
last_error: str | None = None
|
||||||
f"Dernier message : {last_error or 'inconnu'}"}
|
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||||
return
|
# 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 skipped == total:
|
||||||
if total > 0 and not sections:
|
yield {"type": "error",
|
||||||
# Le texte a bien été extrait mais AUCUN morceau n'a produit de JSON
|
"message": "Tous les morceaux ont échoué auprès du fournisseur IA. "
|
||||||
# exploitable (sorties coupées/illisibles). Sans ce signal, l'UI reçoit
|
f"Dernier message : {last_error or 'inconnu'}"}
|
||||||
# un `done` vide et l'utilisateur conclut à tort que le PDF est illisible.
|
return
|
||||||
yield {"type": "error",
|
|
||||||
"message": "Le texte du PDF a été extrait, mais le modèle n'a produit "
|
sections = merger.result()
|
||||||
"aucune section exploitable (réponses JSON vides ou coupées). "
|
if total > 0 and not sections:
|
||||||
"Réduisez la taille des morceaux d'import, augmentez la fenêtre "
|
# Le texte a bien été extrait mais AUCUN morceau n'a produit de JSON
|
||||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
# exploitable (sorties coupées/illisibles). Sans ce signal, l'UI reçoit
|
||||||
return
|
# 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
|
# 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.
|
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
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": "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}
|
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||||
|
untranslated: list[str] = []
|
||||||
for target in other_languages(source):
|
for target in other_languages(source):
|
||||||
try:
|
try:
|
||||||
async for ev in self._translate_events(sections, source, target):
|
async for kind, payload in self._translate(sections, source, target):
|
||||||
if ev["type"] == "_translated":
|
if kind == "heartbeat":
|
||||||
by_language[target] = ev["sections"]
|
yield {"type": "heartbeat", "current": total, "total": total}
|
||||||
|
elif kind == "status":
|
||||||
|
yield {"type": "status", "message": payload}
|
||||||
else:
|
else:
|
||||||
yield ev
|
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:
|
except LLMProviderError as exc:
|
||||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||||
yield {"type": "status",
|
yield {"type": "status",
|
||||||
@@ -384,35 +471,32 @@ class ImportRulesUseCase:
|
|||||||
"sections": sections,
|
"sections": sections,
|
||||||
"sections_by_language": by_language,
|
"sections_by_language": by_language,
|
||||||
"source_language": source,
|
"source_language": source,
|
||||||
|
"split_method": split_method,
|
||||||
|
"untranslated": untranslated,
|
||||||
"page_count": doc.page_count,
|
"page_count": doc.page_count,
|
||||||
"ocr_page_count": doc.ocr_page_count,
|
"ocr_page_count": doc.ocr_page_count,
|
||||||
"skipped": skipped,
|
"skipped": skipped,
|
||||||
}
|
}
|
||||||
|
|
||||||
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
|
def _split_by_structure(self, doc, language: str) -> StructureSplit | None:
|
||||||
"""Évènements d'avancement de la traduction ; le dernier est
|
"""Découpage par la structure du PDF, ou None s'il faut passer par l'IA (réglage
|
||||||
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
|
coupé, extracteur sans lignes, PDF sans signets ni titres repérables)."""
|
||||||
translator = RulesTranslator(self._llm)
|
if not self._structure_first:
|
||||||
titles = list(sections)
|
return None
|
||||||
total = len(titles)
|
split = split_by_structure(
|
||||||
label = language_name(target)
|
doc, preamble_title="Front matter" if language == "en" else "Préambule")
|
||||||
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
|
if split.method == NONE:
|
||||||
mapping: dict[str, str] = {}
|
logger.info("Import règles : pas de structure exploitable dans ce PDF — découpage par l'IA.")
|
||||||
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
|
return None
|
||||||
if kind == "heartbeat":
|
logger.info("Import règles : %s page(s), découpage par la structure du PDF (%s) : %s sections, "
|
||||||
yield {"type": "heartbeat", "current": 0, "total": total}
|
"%s titres, sans IA.", doc.page_count, split.method, len(split.sections), split.heading_count)
|
||||||
elif kind == "result":
|
return split
|
||||||
mapping = unique_titles(payload)
|
|
||||||
out: dict[str, str] = {}
|
def _translate(self, sections: dict[str, str], source: str, target: str):
|
||||||
for i, title in enumerate(titles):
|
"""Traduction des sections vers `target` (cf. rules_translation.translate_sections)."""
|
||||||
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
|
return translate_sections(RulesTranslator(self._llm), sections, source, target,
|
||||||
"current": i + 1, "total": total}
|
concurrency=self._translation_concurrency,
|
||||||
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
|
heartbeat_seconds=self._heartbeat_seconds)
|
||||||
if kind == "heartbeat":
|
|
||||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
|
||||||
elif kind == "result":
|
|
||||||
out[mapping.get(title, title)] = payload
|
|
||||||
yield {"type": "_translated", "sections": out}
|
|
||||||
|
|
||||||
# --- MAP : un morceau → sections -----------------------------------------
|
# --- MAP : un morceau → sections -----------------------------------------
|
||||||
|
|
||||||
@@ -479,6 +563,15 @@ class ImportRulesUseCase:
|
|||||||
if truncated:
|
if truncated:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Morceau %s : sortie tronquée, profondeur max atteinte — partiel conservé.", index)
|
"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
|
return sections
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -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())
|
||||||
@@ -120,3 +120,49 @@ Réponds UNIQUEMENT par un objet JSON valide :
|
|||||||
"scene_merges": [{{"chapter": "nom du chapitre", "into": "nom de la scène à garder",
|
"scene_merges": [{{"chapter": "nom du chapitre", "into": "nom de la scène à garder",
|
||||||
"merge": ["nom à fusionner", ...]}}]}}
|
"merge": ["nom à fusionner", ...]}}]}}
|
||||||
S'il n'y a RIEN à fusionner (cas le plus fréquent) : {{"chapter_merges": [], "scene_merges": []}}"""
|
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,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,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."
|
||||||
|
)
|
||||||
@@ -8,15 +8,34 @@ pour rester sous les limites de sortie des modèles.
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
import re
|
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_json import load_json_object
|
||||||
from app.application.llm_retry import generate_with_retry
|
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.core.language import language_name
|
||||||
from app.domain.ports import LLMProvider
|
from app.domain.ports import LLMProvider, LLMProviderError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
LANGUAGES = ("fr", "en")
|
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).
|
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||||
CHUNK_CHARS = 6000
|
CHUNK_CHARS = 6000
|
||||||
|
|
||||||
@@ -64,7 +83,79 @@ def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
|||||||
return chunks
|
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:
|
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 (
|
return (
|
||||||
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
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"
|
f"vers la langue « {language_name(target)} ».\n\n"
|
||||||
@@ -72,8 +163,10 @@ def content_prompt(text: str, source: str, target: str) -> str:
|
|||||||
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\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 "
|
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||||
"objets nommés.\n"
|
"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"
|
"- 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"
|
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||||
|
f"{block}"
|
||||||
"Extrait :\n"
|
"Extrait :\n"
|
||||||
f"{text}"
|
f"{text}"
|
||||||
)
|
)
|
||||||
@@ -98,16 +191,22 @@ class RulesTranslator:
|
|||||||
|
|
||||||
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
|
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."""
|
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
|
||||||
if not titles:
|
|
||||||
return {}
|
|
||||||
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
|
|
||||||
output_format="json", temperature=0.2)
|
|
||||||
parsed, _ = load_json_object(raw)
|
|
||||||
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
|
||||||
out: dict[str, str] = {}
|
out: dict[str, str] = {}
|
||||||
for title in titles:
|
# Par lots : un livre découpé par sa structure a des centaines de titres, trop pour
|
||||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
# une seule réponse JSON d'un petit modèle.
|
||||||
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
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
|
return out
|
||||||
|
|
||||||
async def translate_content(self, text: str, source: str, target: str) -> str:
|
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||||
@@ -134,3 +233,144 @@ def unique_titles(titles: dict[str, str]) -> dict[str, str]:
|
|||||||
seen[translated] = count + 1
|
seen[translated] = count + 1
|
||||||
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||||
return out
|
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
|
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)
|
@dataclass(frozen=True)
|
||||||
class ExtractedDocument:
|
class ExtractedDocument:
|
||||||
"""Résultat brut de l'extraction d'un PDF : une entrée par page."""
|
"""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
|
# 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.
|
# pour les scans ; les livres born-digital en ont presque toujours une.
|
||||||
toc: list[TocEntry] = field(default_factory=list)
|
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
|
@property
|
||||||
def page_count(self) -> int:
|
def page_count(self) -> int:
|
||||||
|
|||||||
@@ -31,6 +31,15 @@ logger = logging.getLogger(__name__)
|
|||||||
_FIRST_TOKEN_TIMEOUT_SECONDS = 120.0
|
_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:
|
class BaseOpenAICompatibleAdapter:
|
||||||
"""Base des adapters clients d'une API OpenAI-compatible (chat/completions SSE).
|
"""Base des adapters clients d'une API OpenAI-compatible (chat/completions SSE).
|
||||||
|
|
||||||
@@ -100,7 +109,8 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
temperature: float | None = None,
|
temperature: float | None = None,
|
||||||
) -> AsyncIterator[str]:
|
) -> AsyncIterator[str]:
|
||||||
async for token in self._stream(messages, system_prompt, temperature):
|
async for token in self._stream(messages, system_prompt, temperature):
|
||||||
yield token
|
if token: # jeton vide = le modèle réfléchit encore, rien à afficher
|
||||||
|
yield token
|
||||||
|
|
||||||
# --- Mécanique partagée -------------------------------------------------
|
# --- Mécanique partagée -------------------------------------------------
|
||||||
|
|
||||||
@@ -117,19 +127,24 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
"""
|
"""
|
||||||
async def _collect() -> str:
|
async def _collect() -> str:
|
||||||
chunks: list[str] = []
|
chunks: list[str] = []
|
||||||
|
started = False
|
||||||
agen = self._stream(messages, None, temperature, output_format)
|
agen = self._stream(messages, None, temperature, output_format)
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
# Borne SEULEMENT l'attente du 1er token ; ensuite on laisse
|
# Borne SEULEMENT l'attente du 1er signe d'activité ; ensuite on
|
||||||
# générer (le ceiling global couvre le reste).
|
# laisse générer (le ceiling global couvre le reste). Un jeton vide
|
||||||
first = _FIRST_TOKEN_TIMEOUT_SECONDS if not chunks else None
|
# (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:
|
try:
|
||||||
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
token = await asyncio.wait_for(agen.__anext__(), timeout=first)
|
||||||
except StopAsyncIteration:
|
except StopAsyncIteration:
|
||||||
break
|
break
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
raise LLMProviderError(self._first_token_timeout_message())
|
raise LLMProviderError(self._first_token_timeout_message())
|
||||||
chunks.append(token)
|
started = True
|
||||||
|
if token:
|
||||||
|
chunks.append(token)
|
||||||
finally:
|
finally:
|
||||||
await agen.aclose()
|
await agen.aclose()
|
||||||
return "".join(chunks)
|
return "".join(chunks)
|
||||||
@@ -195,7 +210,13 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
async def _parse_sse(response: httpx.Response) -> AsyncIterator[str]:
|
||||||
"""SSE OpenAI : lignes `data: {json}`, fin sur `data: [DONE]`."""
|
"""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():
|
async for line in response.aiter_lines():
|
||||||
if not line or not line.startswith("data:"):
|
if not line or not line.startswith("data:"):
|
||||||
continue # lignes vides ou commentaires keep-alive (`: ...`)
|
continue # lignes vides ou commentaires keep-alive (`: ...`)
|
||||||
@@ -211,8 +232,11 @@ class BaseOpenAICompatibleAdapter:
|
|||||||
continue
|
continue
|
||||||
delta = choices[0].get("delta") or {}
|
delta = choices[0].get("delta") or {}
|
||||||
content = delta.get("content")
|
content = delta.get("content")
|
||||||
if content:
|
if isinstance(content, str):
|
||||||
yield content
|
if content:
|
||||||
|
yield content
|
||||||
|
elif isinstance(content, list):
|
||||||
|
yield _answer_text(content)
|
||||||
|
|
||||||
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
def _format_http_error(self, exc: httpx.HTTPError) -> str:
|
||||||
"""Message lisible (timeout, quota 429, crédits 402, modèle inconnu…)."""
|
"""Message lisible (timeout, quota 429, crédits 402, modèle inconnu…)."""
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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:
|
class OllamaLLMProvider:
|
||||||
"""Implémentation des ports LLM — appelle un serveur Ollama via HTTP.
|
"""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.
|
# clés "thought" bavardes ou de texte hors JSON.
|
||||||
if output_format is not None:
|
if output_format is not None:
|
||||||
payload["format"] = output_format
|
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:
|
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||||
try:
|
try:
|
||||||
response = await client.post(url, json=payload)
|
return 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]}"
|
|
||||||
)
|
|
||||||
except httpx.ConnectTimeout as exc:
|
except httpx.ConnectTimeout as exc:
|
||||||
# Serveur injoignable : erreur d'infrastructure, pas de lenteur.
|
# Serveur injoignable : erreur d'infrastructure, pas de lenteur.
|
||||||
raise LLMProviderError(
|
raise LLMProviderError(
|
||||||
@@ -99,7 +123,8 @@ class OllamaLLMProvider:
|
|||||||
f"Erreur lors de l'appel à Ollama : {exc}"
|
f"Erreur lors de l'appel à Ollama : {exc}"
|
||||||
) from 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
|
# Diagnostic crucial pour les imports : `done_reason` != "stop" signifie que
|
||||||
# la génération a été INTERROMPUE (fenêtre de contexte pleine, num_predict…)
|
# 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é
|
# et non terminée par le modèle. Sans ce log, on ne voit qu'un JSON coupé
|
||||||
|
|||||||
@@ -17,13 +17,15 @@ et le diagnostic le signale (used_ocr reste False, texte vide).
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
|
|
||||||
import pymupdf as fitz # PyMuPDF — on importe par le nom canonique `pymupdf`
|
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"
|
# (et NON `import fitz`) pour éviter la collision avec le faux paquet PyPI "fitz"
|
||||||
# qui échoue sur `from frontend import *`.
|
# 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.domain.ports import PdfExtractionError
|
||||||
|
from app.infrastructure.pdf_layout import CELL_SEPARATOR, LayoutBlock, LayoutLine, place_lines, split_cells
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -41,6 +43,15 @@ _OCR_DPI = 300
|
|||||||
_OCR_LANGS = "fra+eng"
|
_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:
|
class PyMuPdfTextExtractor:
|
||||||
"""Extracteur PDF basé sur PyMuPDF, avec repli OCR Tesseract optionnel."""
|
"""Extracteur PDF basé sur PyMuPDF, avec repli OCR Tesseract optionnel."""
|
||||||
|
|
||||||
@@ -73,6 +84,7 @@ class PyMuPdfTextExtractor:
|
|||||||
|
|
||||||
pages: list[ExtractedPage] = []
|
pages: list[ExtractedPage] = []
|
||||||
toc: list[TocEntry] = []
|
toc: list[TocEntry] = []
|
||||||
|
lines: list[TextLine] = []
|
||||||
try:
|
try:
|
||||||
# Bookmarks/outline du PDF : structure officielle du livre, gratuite
|
# Bookmarks/outline du PDF : structure officielle du livre, gratuite
|
||||||
# (pas d'appel LLM). Sert de squelette de référence aux imports.
|
# (pas d'appel LLM). Sert de squelette de référence aux imports.
|
||||||
@@ -93,10 +105,61 @@ class PyMuPdfTextExtractor:
|
|||||||
text = ocr_text.strip()
|
text = ocr_text.strip()
|
||||||
used_ocr = True
|
used_ocr = True
|
||||||
pages.append(ExtractedPage(index=index, text=text, used_ocr=used_ocr))
|
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:
|
finally:
|
||||||
doc.close()
|
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
|
@staticmethod
|
||||||
def _ocr_page(page: "fitz.Page") -> str:
|
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
|
import logging
|
||||||
|
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exception_handlers import http_exception_handler
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
|
||||||
from app.api.routers import (
|
from app.api.routers import (
|
||||||
chat,
|
chat,
|
||||||
@@ -18,7 +20,9 @@ from app.api.routers import (
|
|||||||
models,
|
models,
|
||||||
notebooks,
|
notebooks,
|
||||||
settings as settings_router,
|
settings as settings_router,
|
||||||
|
spells,
|
||||||
tables,
|
tables,
|
||||||
|
training,
|
||||||
)
|
)
|
||||||
from app.core.config import get_settings
|
from app.core.config import get_settings
|
||||||
from app.infrastructure.ollama_model_installer import ensure_ollama_embedding_model
|
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(
|
app = FastAPI(
|
||||||
title="LoreMind Brain",
|
title="LoreMind Brain",
|
||||||
description="Backend IA pour la génération de contenu narratif.",
|
description="Backend IA pour la génération de contenu narratif.",
|
||||||
version="1.6.2-beta",
|
version="1.7.0-beta",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -61,6 +65,18 @@ async def require_internal_secret(request: Request, call_next):
|
|||||||
return await call_next(request)
|
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")
|
@app.get("/health")
|
||||||
def health() -> dict[str, str]:
|
def health() -> dict[str, str]:
|
||||||
"""Sonde de santé — permet au Core Java de vérifier que le Brain répond."""
|
"""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(generation.router)
|
||||||
app.include_router(chat.router)
|
app.include_router(chat.router)
|
||||||
app.include_router(tables.router)
|
app.include_router(tables.router)
|
||||||
|
app.include_router(training.router)
|
||||||
|
app.include_router(spells.router)
|
||||||
app.include_router(imports.router)
|
app.include_router(imports.router)
|
||||||
app.include_router(notebooks.router)
|
app.include_router(notebooks.router)
|
||||||
app.include_router(settings_router.router)
|
app.include_router(settings_router.router)
|
||||||
|
|||||||
+25
-1
@@ -13,12 +13,25 @@ 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
|
soit importable quel que soit le repertoire de travail (le Core fixe le cwd
|
||||||
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
ailleurs, sous ~/.loremind/brain, pour y ecrire le dossier data/).
|
||||||
"""
|
"""
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
sys.path.insert(0, _HERE)
|
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
|
# 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).
|
# 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
|
# tessdata (fra+eng) est embarqué dans tesseract/tessdata. Sans ce bloc, l'OCR
|
||||||
@@ -40,6 +53,17 @@ import uvicorn # noqa: E402
|
|||||||
|
|
||||||
from app.main import app # 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__":
|
if __name__ == "__main__":
|
||||||
# host 127.0.0.1 : accessible uniquement depuis le Core sur la meme machine.
|
# 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,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,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"] == []
|
||||||
@@ -134,6 +134,49 @@ async def test_rules_stream_keeps_the_source_language_when_translation_fails(mon
|
|||||||
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
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):
|
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||||
llm = ScriptedLLM([LLMProviderError("HTTP 500 panne")])
|
llm = ScriptedLLM([LLMProviderError("HTTP 500 panne")])
|
||||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()))
|
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()))
|
||||||
@@ -207,3 +250,578 @@ async def test_campaign_import_defaults_to_french():
|
|||||||
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||||
assert "en français" in llm.prompts[0]
|
assert "en français" in llm.prompts[0]
|
||||||
assert '"Aventure principale"' 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
|
||||||
|
|||||||
@@ -93,3 +93,44 @@ async def test_stream_chat_prepends_system_prompt():
|
|||||||
body = json.loads(route.calls.last.request.content)
|
body = json.loads(route.calls.last.request.content)
|
||||||
assert body["messages"][0] == {"role": "system", "content": "SYS"}
|
assert body["messages"][0] == {"role": "system", "content": "SYS"}
|
||||||
assert body["messages"][-1] == {"role": "user", "content": "Q"}
|
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
|
||||||
|
|||||||
@@ -202,3 +202,52 @@ async def test_sse_skips_keepalive_and_malformed_lines(cls, url, skw, supports_j
|
|||||||
def test_missing_api_key_raises_at_construction(cls, skw):
|
def test_missing_api_key_raises_at_construction(cls, skw):
|
||||||
with pytest.raises(LLMProviderError):
|
with pytest.raises(LLMProviderError):
|
||||||
cls(_settings(**skw))
|
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,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."}
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.application import rules_translation
|
||||||
from app.application.rules_translation import (
|
from app.application.rules_translation import (
|
||||||
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
|
RulesTranslator, TranslatedRules, detect_language, other_languages, split_markdown,
|
||||||
|
translate_sections, unique_titles,
|
||||||
)
|
)
|
||||||
|
from app.domain.ports import LLMProviderError
|
||||||
|
|
||||||
|
|
||||||
class EchoLLM:
|
class EchoLLM:
|
||||||
@@ -58,3 +65,198 @@ async def test_translate_titles_falls_back_to_the_original_title():
|
|||||||
def test_unique_titles_avoids_collisions():
|
def test_unique_titles_avoids_collisions():
|
||||||
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
||||||
"A": "Combat", "B": "Combat (2)", "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,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
|
||||||
+1
-1
@@ -14,7 +14,7 @@
|
|||||||
|
|
||||||
<groupId>com.loremind</groupId>
|
<groupId>com.loremind</groupId>
|
||||||
<artifactId>loremind-core</artifactId>
|
<artifactId>loremind-core</artifactId>
|
||||||
<version>1.6.2-beta</version>
|
<version>1.7.0-beta</version>
|
||||||
<name>LoreMind Core</name>
|
<name>LoreMind Core</name>
|
||||||
<description>Backend Core - Architecture Hexagonale</description>
|
<description>Backend Core - Architecture Hexagonale</description>
|
||||||
|
|
||||||
|
|||||||
+18
-13
@@ -114,7 +114,7 @@ public class CampaignReadinessService {
|
|||||||
if (totalScenes == 0 && !anyQuestHasNodes(quests)) {
|
if (totalScenes == 0 && !anyQuestHasNodes(quests)) {
|
||||||
gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
gaps.add(new ReadinessGap(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||||
"CAMP-001-NO-CONTENT",
|
"CAMP-001-NO-CONTENT",
|
||||||
"Campagne vide : ajoutez un arc avec une scène, ou créez une quête, pour commencer à jouer.",
|
"Campagne vide : ajoutez une scène ou une aventure pour commencer à jouer.",
|
||||||
ReadinessSeverity.BLOCKING, null, null));
|
ReadinessSeverity.BLOCKING, null, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,9 +146,11 @@ public class CampaignReadinessService {
|
|||||||
chapterIds.add(chapter.getId());
|
chapterIds.add(chapter.getId());
|
||||||
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
|
List<Scene> scenes = sceneRepository.findByChapterId(chapter.getId());
|
||||||
if (scenes.isEmpty()) {
|
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(),
|
gaps.add(new ReadinessGap(ReadinessEntityType.CHAPTER, chapter.getId(),
|
||||||
labelOr(chapter.getName(), "Chapitre"), "CHAP-001-NO-SCENE",
|
labelOr(chapter.getName(), kind), "CHAP-001-NO-SCENE",
|
||||||
"Chapitre vide : ajoutez au moins une scène pour pouvoir le jouer.",
|
kind + " vide : ajoutez au moins une scène pour pouvoir la jouer.",
|
||||||
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
|
ReadinessSeverity.BLOCKING, arc.getId(), chapter.getId()));
|
||||||
}
|
}
|
||||||
Set<String> chapterSceneIds = scenes.stream()
|
Set<String> chapterSceneIds = scenes.stream()
|
||||||
@@ -163,9 +165,8 @@ public class CampaignReadinessService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private ReadinessGap emptyArcGap(Arc arc) {
|
private ReadinessGap emptyArcGap(Arc arc) {
|
||||||
String msg = arc.getType() == ArcType.HUB
|
// Même mot pour l'auteur, que l'arc soit linéaire ou à ordre libre (HUB) : une aventure.
|
||||||
? "Arc vide : ajoutez une quête (ou un chapitre), ou supprimez-le."
|
String msg = "Arc vide : ajoutez une aventure, ou supprimez-le.";
|
||||||
: "Arc vide : ajoutez un chapitre, ou supprimez-le.";
|
|
||||||
return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
return new ReadinessGap(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||||
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null);
|
"ARC-001-EMPTY", msg, ReadinessSeverity.BLOCKING, arc.getId(), null);
|
||||||
}
|
}
|
||||||
@@ -204,7 +205,7 @@ public class CampaignReadinessService {
|
|||||||
if (invalid) {
|
if (invalid) {
|
||||||
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID",
|
gaps.add(sceneGap(scene, arcId, chapterId, "SCENE-010-BRANCH-INVALID",
|
||||||
"Branche cassée : une sortie de « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
|
"Branche cassée : une sortie de « " + labelOr(scene.getName(), SCENE_FALLBACK_NAME)
|
||||||
+ " » pointe dans le vide, hors du chapitre, ou sur elle-même.",
|
+ " » pointe dans le vide, hors de l'aventure, ou sur elle-même.",
|
||||||
ReadinessSeverity.BLOCKING));
|
ReadinessSeverity.BLOCKING));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,20 +275,24 @@ public class CampaignReadinessService {
|
|||||||
|
|
||||||
private void checkQuest(Quest quest, Set<String> allChapterIds, Set<String> allSceneIds,
|
private void checkQuest(Quest quest, Set<String> allChapterIds, Set<String> allSceneIds,
|
||||||
Set<String> questIds, List<ReadinessGap> gaps) {
|
Set<String> questIds, List<ReadinessGap> gaps) {
|
||||||
String name = labelOr(quest.getName(), "Quête");
|
// 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.
|
// QUEST-001 — quête sans nœud ; sinon QUEST-010 — nœud pointant dans le vide.
|
||||||
if (quest.getNodes() == null || quest.getNodes().isEmpty()) {
|
if (quest.getNodes() == null || quest.getNodes().isEmpty()) {
|
||||||
gaps.add(questGap(quest, "QUEST-001-NO-NODES",
|
gaps.add(questGap(quest, "QUEST-001-NO-NODES",
|
||||||
"Quête sans contenu : ajoutez au moins un chapitre ou une scène à « " + name + " »."));
|
(adventure ? "Aventure" : "Quête annexe")
|
||||||
|
+ " sans contenu : ajoutez au moins une scène à « " + name + " »."));
|
||||||
} else if (quest.getNodes().stream().anyMatch(n ->
|
} else if (quest.getNodes().stream().anyMatch(n ->
|
||||||
n.nodeType() == null
|
n.nodeType() == null
|
||||||
|| isBlank(n.nodeId())
|
|| isBlank(n.nodeId())
|
||||||
|| (n.nodeType() == NodeType.CHAPTER && !allChapterIds.contains(n.nodeId()))
|
|| (n.nodeType() == NodeType.CHAPTER && !allChapterIds.contains(n.nodeId()))
|
||||||
|| (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) {
|
|| (n.nodeType() == NodeType.SCENE && !allSceneIds.contains(n.nodeId())))) {
|
||||||
gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN",
|
gaps.add(questGap(quest, "QUEST-010-NODE-REF-BROKEN",
|
||||||
"Nœud de quête cassé : dans « " + name
|
"Lien cassé : dans « " + name
|
||||||
+ " », un chapitre ou une scène référencé n'existe plus."));
|
+ " », une aventure ou une scène référencée n'existe plus."));
|
||||||
}
|
}
|
||||||
|
|
||||||
// CAMP-010 — prérequis QuestCompleted pointant une quête disparue.
|
// CAMP-010 — prérequis QuestCompleted pointant une quête disparue.
|
||||||
@@ -297,7 +302,7 @@ public class CampaignReadinessService {
|
|||||||
.anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) {
|
.anyMatch(qid -> isBlank(qid) || !questIds.contains(qid))) {
|
||||||
gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ",
|
gaps.add(questGap(quest, "CAMP-010-DANGLING-QUEST-PREREQ",
|
||||||
"Prérequis cassé : « " + name
|
"Prérequis cassé : « " + name
|
||||||
+ " » dépend d'une quête qui n'existe plus. Corrigez la condition de déblocage."));
|
+ " » dépend d'une aventure ou d'une quête qui n'existe plus. Corrigez la condition de déblocage."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -331,7 +336,7 @@ public class CampaignReadinessService {
|
|||||||
|
|
||||||
private ReadinessGap questGap(Quest quest, String ruleId, String message) {
|
private ReadinessGap questGap(Quest quest, String ruleId, String message) {
|
||||||
return new ReadinessGap(ReadinessEntityType.QUEST, quest.getId(),
|
return new ReadinessGap(ReadinessEntityType.QUEST, quest.getId(),
|
||||||
labelOr(quest.getName(), "Quête"), ruleId, message, ReadinessSeverity.BLOCKING, null, null);
|
labelOr(quest.getName(), isBlank(quest.getArcId()) ? "Quête annexe" : "Aventure"), ruleId, message, ReadinessSeverity.BLOCKING, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int severityRank(ReadinessSeverity severity) {
|
private static int severityRank(ReadinessSeverity severity) {
|
||||||
|
|||||||
@@ -78,7 +78,32 @@ public class ChapterService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Chapter chapter = existingChapter.get();
|
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);
|
return chapterRepository.save(chapter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,9 +11,14 @@ import java.util.List;
|
|||||||
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
* 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.
|
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||||
*
|
*
|
||||||
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
|
* <p>Placement en chapitre : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le
|
||||||
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
|
* chapitre est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la
|
||||||
* Exactement l'un des deux.</p>
|
* 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 arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||||
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||||
@@ -24,6 +29,10 @@ import java.util.List;
|
|||||||
* @param links liens explicites entre scènes (indices dans {@code scenes}), ou {@code null} :
|
* @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
|
* 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 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(
|
public record GuidedSkeleton(
|
||||||
String arcId,
|
String arcId,
|
||||||
@@ -33,13 +42,29 @@ public record GuidedSkeleton(
|
|||||||
boolean linkSequentially,
|
boolean linkSequentially,
|
||||||
String linkLabel,
|
String linkLabel,
|
||||||
List<LinkSpec> links,
|
List<LinkSpec> links,
|
||||||
ClockSpec clock
|
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). */
|
/** Squelette sans liens explicites ni horloge (Donjon en 5 salles). */
|
||||||
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
public GuidedSkeleton(String arcId, String newArcName, ChapterSpec chapter, List<SceneSpec> scenes,
|
||||||
boolean linkSequentially, String linkLabel) {
|
boolean linkSequentially, String linkLabel) {
|
||||||
this(arcId, newArcName, chapter, scenes, linkSequentially, linkLabel, null, null);
|
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) */
|
/** @param gmNotes notes réservées au MJ (vérité cachée d'une enquête, plan complet du méchant) */
|
||||||
@@ -71,19 +96,30 @@ public record GuidedSkeleton(
|
|||||||
public record ClockSpec(String name, String description, int segments) {
|
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(
|
public record SceneSpec(
|
||||||
String name, String description, SceneType type, String location,
|
String name, String description, SceneType type, String location,
|
||||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
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.
|
* 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 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) {
|
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) {
|
public Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||||
this(arcId, chapterId, sceneIds, 0);
|
this(arcId, chapterId, sceneIds, 0, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+108
-8
@@ -2,6 +2,10 @@ package com.loremind.application.campaigncontext;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
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.ports.SceneRepository;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
@@ -26,7 +30,10 @@ import java.util.Objects;
|
|||||||
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
* 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
|
* <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). Transactionnel : tout ou rien.</p>
|
* 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
|
@Service
|
||||||
public class GuidedSkeletonService {
|
public class GuidedSkeletonService {
|
||||||
@@ -39,6 +46,8 @@ public class GuidedSkeletonService {
|
|||||||
private final SceneService sceneService;
|
private final SceneService sceneService;
|
||||||
private final PlaythroughRepository playthroughRepository;
|
private final PlaythroughRepository playthroughRepository;
|
||||||
private final ClockService clockService;
|
private final ClockService clockService;
|
||||||
|
private final QuestService questService;
|
||||||
|
private final QuestRepository questRepository;
|
||||||
|
|
||||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||||
ChapterRepository chapterRepository,
|
ChapterRepository chapterRepository,
|
||||||
@@ -47,7 +56,9 @@ public class GuidedSkeletonService {
|
|||||||
ChapterService chapterService,
|
ChapterService chapterService,
|
||||||
SceneService sceneService,
|
SceneService sceneService,
|
||||||
PlaythroughRepository playthroughRepository,
|
PlaythroughRepository playthroughRepository,
|
||||||
ClockService clockService) {
|
ClockService clockService,
|
||||||
|
QuestService questService,
|
||||||
|
QuestRepository questRepository) {
|
||||||
this.arcRepository = arcRepository;
|
this.arcRepository = arcRepository;
|
||||||
this.chapterRepository = chapterRepository;
|
this.chapterRepository = chapterRepository;
|
||||||
this.sceneRepository = sceneRepository;
|
this.sceneRepository = sceneRepository;
|
||||||
@@ -56,17 +67,26 @@ public class GuidedSkeletonService {
|
|||||||
this.sceneService = sceneService;
|
this.sceneService = sceneService;
|
||||||
this.playthroughRepository = playthroughRepository;
|
this.playthroughRepository = playthroughRepository;
|
||||||
this.clockService = clockService;
|
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,
|
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||||
* arc d'une autre campagne ou non linéaire)
|
* arc d'une autre campagne ou du mauvais type)
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||||
validate(skeleton);
|
validate(skeleton);
|
||||||
String arcId = resolveArc(campaignId, skeleton);
|
String method = GuidedKeys.normalize(skeleton.method());
|
||||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
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.
|
// Une scène sans nom est ignorée ; byIndex garde la position d'origine pour les liens.
|
||||||
List<Scene> scenes = new ArrayList<>();
|
List<Scene> scenes = new ArrayList<>();
|
||||||
@@ -85,6 +105,7 @@ public class GuidedSkeletonService {
|
|||||||
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||||
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||||
.enemies(blankToNull(spec.enemies()))
|
.enemies(blankToNull(spec.enemies()))
|
||||||
|
.guidedRole(chapter.getGuidedMethod() == null ? null : GuidedKeys.normalize(spec.role()))
|
||||||
.chapterId(chapter.getId())
|
.chapterId(chapter.getId())
|
||||||
.order(order++)
|
.order(order++)
|
||||||
.build());
|
.build());
|
||||||
@@ -100,7 +121,80 @@ public class GuidedSkeletonService {
|
|||||||
}
|
}
|
||||||
int clocks = createClocks(campaignId, skeleton.clock());
|
int clocks = createClocks(campaignId, skeleton.clock());
|
||||||
|
|
||||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList(), clocks);
|
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -150,7 +244,12 @@ public class GuidedSkeletonService {
|
|||||||
}
|
}
|
||||||
boolean hasArc = !isBlank(skeleton.arcId());
|
boolean hasArc = !isBlank(skeleton.arcId());
|
||||||
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||||
if (hasArc == hasNewArc) {
|
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.");
|
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||||
}
|
}
|
||||||
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||||
@@ -183,7 +282,7 @@ public class GuidedSkeletonService {
|
|||||||
.build()).getId();
|
.build()).getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
|
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec, String method) {
|
||||||
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||||
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||||
return chapterService.createChapter(Chapter.builder()
|
return chapterService.createChapter(Chapter.builder()
|
||||||
@@ -192,6 +291,7 @@ public class GuidedSkeletonService {
|
|||||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||||
.gmNotes(blankToNull(spec.gmNotes()))
|
.gmNotes(blankToNull(spec.gmNotes()))
|
||||||
|
.guidedMethod(method)
|
||||||
.arcId(arcId)
|
.arcId(arcId)
|
||||||
.order(nextOrder)
|
.order(nextOrder)
|
||||||
.build());
|
.build());
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.structure.Scene;
|
|||||||
import com.loremind.domain.campaigncontext.generation.SceneDraft;
|
import com.loremind.domain.campaigncontext.generation.SceneDraft;
|
||||||
import com.loremind.domain.shared.ReorderSupport;
|
import com.loremind.domain.shared.ReorderSupport;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -80,7 +81,8 @@ public class SceneService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Scene scene = existingScene.get();
|
Scene scene = existingScene.get();
|
||||||
BeanUtils.copyProperties(updated, scene, "id");
|
// guidedRole : jamais porté par le formulaire d'édition, il ne doit pas être effacé.
|
||||||
|
BeanUtils.copyProperties(updated, scene, "id", "guidedRole");
|
||||||
|
|
||||||
// Validation métier : le graphe narratif doit rester cohérent.
|
// Validation métier : le graphe narratif doit rester cohérent.
|
||||||
validateBranches(scene);
|
validateBranches(scene);
|
||||||
@@ -88,6 +90,53 @@ public class SceneService {
|
|||||||
return sceneRepository.save(scene);
|
return sceneRepository.save(scene);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée, à la fin du chapitre, la scène qui tient un rôle de sa méthode guidée (rôle
|
||||||
|
* resté sans scène, ou méthode appliquée après coup à un chapitre existant).
|
||||||
|
* Transactionnel.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException nom vide ou identifiant de rôle invalide
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Scene createGuidedScene(String chapterId, String name, SceneType type, String role) {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("La scène doit avoir un nom.");
|
||||||
|
}
|
||||||
|
int order = sceneRepository.findByChapterId(chapterId).stream()
|
||||||
|
.mapToInt(Scene::getOrder).max().orElse(-1) + 1;
|
||||||
|
Scene created = sceneRepository.save(Scene.builder()
|
||||||
|
.name(name.trim())
|
||||||
|
.type(type != null ? type : SceneType.GENERIC)
|
||||||
|
.chapterId(chapterId)
|
||||||
|
.order(order)
|
||||||
|
.build());
|
||||||
|
return setGuidedRole(created.getId(), role);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Donne à la scène un rôle dans la méthode guidée de son chapitre, ou le retire
|
||||||
|
* ({@code null} / vide). Un rôle est tenu par une seule scène : la scène du même chapitre
|
||||||
|
* qui le tenait le perd. Transactionnel.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException scène inconnue ou identifiant de rôle invalide
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Scene setGuidedRole(String id, String role) {
|
||||||
|
Scene scene = sceneRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Scene non trouvée avec l'ID: " + id));
|
||||||
|
String next = GuidedKeys.normalize(role);
|
||||||
|
if (next != null) {
|
||||||
|
for (Scene other : sceneRepository.findByChapterId(scene.getChapterId())) {
|
||||||
|
if (!id.equals(other.getId()) && next.equals(other.getGuidedRole())) {
|
||||||
|
other.setGuidedRole(null);
|
||||||
|
sceneRepository.save(other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scene.setGuidedRole(next);
|
||||||
|
return sceneRepository.save(scene);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Patch CIBLÉ champ-par-champ d'une scène (Pilier A — co-création). Applique
|
* Patch CIBLÉ champ-par-champ d'une scène (Pilier A — co-création). Applique
|
||||||
* UNIQUEMENT les {@link FieldProposal} reçus (valeurs acceptées par l'utilisateur) sur
|
* UNIQUEMENT les {@link FieldProposal} reçus (valeurs acceptées par l'utilisateur) sur
|
||||||
@@ -200,6 +249,7 @@ public class SceneService {
|
|||||||
if (chapterId != null && !chapterId.isBlank() && !chapterId.equals(scene.getChapterId())) {
|
if (chapterId != null && !chapterId.isBlank() && !chapterId.equals(scene.getChapterId())) {
|
||||||
scene.setChapterId(chapterId);
|
scene.setChapterId(chapterId);
|
||||||
scene.setBranches(new ArrayList<>());
|
scene.setBranches(new ArrayList<>());
|
||||||
|
scene.setGuidedRole(null); // le rôle appartenait à la méthode de l'ancien chapitre
|
||||||
}
|
}
|
||||||
scene.setOrder(i);
|
scene.setOrder(i);
|
||||||
},
|
},
|
||||||
|
|||||||
+140
-15
@@ -9,7 +9,9 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
|||||||
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||||
|
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
@@ -64,6 +66,8 @@ public class WritingReviewService {
|
|||||||
static final int DUNGEON_MIN_ROOMS = 4;
|
static final int DUNGEON_MIN_ROOMS = 4;
|
||||||
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
/** WRITE-014 : taille minimale d'une enquête pour attendre une scène de relance. */
|
||||||
static final int PROACTIVE_MIN_SCENES = 3;
|
static final int PROACTIVE_MIN_SCENES = 3;
|
||||||
|
/** WRITE-021 : nombre minimal d'étapes écrites pour juger un plan du méchant. */
|
||||||
|
static final int PLAN_MIN_STEPS = 3;
|
||||||
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||||
static final int MONOTONOUS_RUN = 3;
|
static final int MONOTONOUS_RUN = 3;
|
||||||
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||||
@@ -73,6 +77,18 @@ public class WritingReviewService {
|
|||||||
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
||||||
static final double UNTYPED_RATIO = 0.7;
|
static final double UNTYPED_RATIO = 0.7;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paramètre ajouté aux remarques d'un chapitre qui suit une méthode guidée : le front
|
||||||
|
* ne lui conseille pas d'en suivre une autre.
|
||||||
|
*/
|
||||||
|
static final String PARAM_GUIDED_METHOD = "guidedMethod";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paramètre ajouté quand l'arc d'une remarque est l'arc créé d'office : le front choisit
|
||||||
|
* alors la formulation qui ne nomme pas l'arc ({@code observationNoArc}).
|
||||||
|
*/
|
||||||
|
static final String PARAM_IMPLICIT_ARC = "implicitArc";
|
||||||
|
|
||||||
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
||||||
static final String KIND_COMBAT = "COMBAT";
|
static final String KIND_COMBAT = "COMBAT";
|
||||||
|
|
||||||
@@ -115,8 +131,17 @@ public class WritingReviewService {
|
|||||||
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
||||||
List<WritingRemark> treeRemarks = new ArrayList<>();
|
List<WritingRemark> treeRemarks = new ArrayList<>();
|
||||||
|
|
||||||
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
|
List<Quest> quests = questRepository.findByCampaignId(campaignId);
|
||||||
|
Set<String> arcsWithQuests = quests.stream()
|
||||||
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||||
|
// Le texte d'une quête vit sur la quête, pas sur son chapitre-conteneur : ses enjeux
|
||||||
|
// valent pour lui (sinon WRITE-005 réclamerait des enjeux déjà écrits).
|
||||||
|
Set<String> chaptersWithQuestStakes = quests.stream()
|
||||||
|
.filter(q -> !isBlank(q.getNarrativeStakes()) && q.getNodes() != null)
|
||||||
|
.flatMap(q -> q.getNodes().stream())
|
||||||
|
.filter(n -> n.nodeType() == NodeType.CHAPTER)
|
||||||
|
.map(QuestNodeRef::nodeId)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||||
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||||
@@ -127,6 +152,8 @@ public class WritingReviewService {
|
|||||||
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||||
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||||
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||||
|
// Arc créé d'office, que l'auteur n'a jamais vu : on ne lui réclame rien, on ne le cite pas.
|
||||||
|
boolean implicitArc = ImplicitArc.is(arc, arcs);
|
||||||
|
|
||||||
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
// WRITE-017 — une seule accroche : les personnages n'ont qu'une raison de s'en mêler.
|
||||||
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
if (visibleArc && countLines(arc.getHooks()) == 1) {
|
||||||
@@ -134,7 +161,7 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||||
if (visibleArc && isBlank(arc.getStakes())
|
if (visibleArc && !implicitArc && isBlank(arc.getStakes())
|
||||||
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||||
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
}
|
}
|
||||||
@@ -147,7 +174,8 @@ public class WritingReviewService {
|
|||||||
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
||||||
|
|
||||||
if (visibleArc) {
|
if (visibleArc) {
|
||||||
reviewChapter(arc, chapter, scenes, treeRemarks);
|
reviewChapter(arc, chapter, scenes, chaptersWithQuestStakes.contains(chapter.getId()), treeRemarks);
|
||||||
|
reviewGuidedMethod(arc, chapter, scenes, treeRemarks);
|
||||||
}
|
}
|
||||||
for (Scene scene : scenes) {
|
for (Scene scene : scenes) {
|
||||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||||
@@ -159,7 +187,7 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
||||||
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
|
checkSingleEnding(arc, implicitArc, lastChapterScenes, treeRemarks);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +209,8 @@ public class WritingReviewService {
|
|||||||
|
|
||||||
// --- Niveau chapitre ---------------------------------------------------------------
|
// --- Niveau chapitre ---------------------------------------------------------------
|
||||||
|
|
||||||
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, boolean questHasStakes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
||||||
|
|
||||||
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
||||||
@@ -200,7 +229,7 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
||||||
if (isBlank(chapter.getNarrativeStakes())) {
|
if (isBlank(chapter.getNarrativeStakes()) && !questHasStakes) {
|
||||||
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,6 +242,81 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Méthode guidée du chapitre ----------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Règles propres à la méthode guidée que suit le chapitre (Donjon en 5 salles, Enquête
|
||||||
|
* en nœuds, Plan du méchant) : la méthode promet une forme, la relecture vérifie qu'elle
|
||||||
|
* tient encore après les retouches du MJ. Chapitre sans méthode, ou méthode inconnue du
|
||||||
|
* Core : rien.
|
||||||
|
*/
|
||||||
|
private void reviewGuidedMethod(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||||
|
List<String> roles = GuidedMethodShapes.rolesOf(chapter.getGuidedMethod());
|
||||||
|
if (roles.isEmpty() || scenes.isEmpty()) return;
|
||||||
|
Map<String, Scene> byRole = new HashMap<>();
|
||||||
|
for (Scene s : scenes) {
|
||||||
|
if (!isBlank(s.getGuidedRole())) byRole.putIfAbsent(s.getGuidedRole(), s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// WRITE-018 — méthode incomplète : des temps de la méthode n'ont plus (ou pas encore) de scène.
|
||||||
|
long missing = roles.stream().filter(r -> !byRole.containsKey(r)).count();
|
||||||
|
if (missing > 0) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-018-METHOD-INCOMPLETE", WritingRemarkCategory.PACING,
|
||||||
|
Map.of("count", String.valueOf(missing), "total", String.valueOf(roles.size()))));
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (chapter.getGuidedMethod()) {
|
||||||
|
case GuidedMethodShapes.FIVE_ROOM -> checkTrialIsCombat(arc, chapter, byRole, out);
|
||||||
|
case GuidedMethodShapes.INVESTIGATION -> checkConclusionClues(arc, chapter, byRole, scenes, out);
|
||||||
|
case GuidedMethodShapes.VILLAIN_PLAN -> checkPlanSigns(arc, chapter, byRole.values(), out);
|
||||||
|
default -> { /* méthode sans règle propre */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WRITE-019 — Donjon en 5 salles : l'épreuve (2e salle) est devenue un combat. */
|
||||||
|
private void checkTrialIsCombat(Arc arc, Chapter chapter, Map<String, Scene> byRole, List<WritingRemark> out) {
|
||||||
|
Scene trial = byRole.get(GuidedMethodShapes.FIVE_ROOM_TRIAL);
|
||||||
|
if (trial != null && isCombat(trial)) {
|
||||||
|
out.add(sceneRemark(arc, chapter, trial, "WRITE-019-TRIAL-IS-COMBAT", WritingRemarkCategory.PACING, Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-020 — Enquête en nœuds : la conclusion n'est plus atteinte par trois pistes.
|
||||||
|
* Une conclusion de type révélation est déjà relue par WRITE-003 : on ne le dit pas deux fois.
|
||||||
|
*/
|
||||||
|
private void checkConclusionClues(Arc arc, Chapter chapter, Map<String, Scene> byRole, List<Scene> scenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
|
Scene conclusion = byRole.get(GuidedMethodShapes.INVESTIGATION_CONCLUSION);
|
||||||
|
if (conclusion == null || isBlank(conclusion.getId()) || typeOf(conclusion) == SceneType.REVELATION) return;
|
||||||
|
int incoming = incomingSources(conclusion, scenes).size();
|
||||||
|
if (incoming < REVELATION_MIN_INCOMING) {
|
||||||
|
out.add(sceneRemark(arc, chapter, conclusion, "WRITE-020-CONCLUSION-FEW-CLUES", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("incoming", String.valueOf(incoming))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WRITE-021 — Plan du méchant : la plupart des étapes ne disent pas ce que les joueurs
|
||||||
|
* peuvent en voir. Un plan invisible ne laisse aucune occasion de réagir.
|
||||||
|
*/
|
||||||
|
private void checkPlanSigns(Arc arc, Chapter chapter, java.util.Collection<Scene> steps, List<WritingRemark> out) {
|
||||||
|
if (steps.size() < PLAN_MIN_STEPS) return;
|
||||||
|
long silent = steps.stream().filter(s -> isBlank(s.getChoicesConsequences())).count();
|
||||||
|
if (silent * 2 > steps.size()) {
|
||||||
|
out.add(chapterRemark(arc, chapter, "WRITE-021-PLAN-WITHOUT-SIGNS", WritingRemarkCategory.AGENCY,
|
||||||
|
Map.of("count", String.valueOf(silent), "total", String.valueOf(steps.size()))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scènes du chapitre (autres qu'elle-même) qui portent un lien vers {@code scene}. */
|
||||||
|
private static List<Scene> incomingSources(Scene scene, List<Scene> chapterScenes) {
|
||||||
|
return chapterScenes.stream()
|
||||||
|
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||||
|
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
private record MonotonousRun(String kind, int length) {}
|
private record MonotonousRun(String kind, int length) {}
|
||||||
|
|
||||||
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
||||||
@@ -325,7 +429,15 @@ public class WritingReviewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
checkChokepoint(arc, chapter, scenes, next, out);
|
// Un donjon en 5 salles s'enchaîne par construction : y voir un passage obligé
|
||||||
|
// reviendrait à reprocher au MJ d'avoir suivi la méthode.
|
||||||
|
if (!followsFiveRooms(chapter)) {
|
||||||
|
checkChokepoint(arc, chapter, scenes, next, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean followsFiveRooms(Chapter chapter) {
|
||||||
|
return GuidedMethodShapes.FIVE_ROOM.equals(chapter.getGuidedMethod());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -412,11 +524,11 @@ public class WritingReviewService {
|
|||||||
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||||
List<WritingRemark> out) {
|
List<WritingRemark> out) {
|
||||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||||
|
// La récompense d'un donjon en 5 salles se mérite au bout du parcours : une seule
|
||||||
|
// salle y mène, et c'est voulu (la règle des 3 indices vaut pour une enquête).
|
||||||
|
if (followsFiveRooms(chapter) && !isBlank(scene.getGuidedRole())) return;
|
||||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||||
List<Scene> sources = chapterScenes.stream()
|
List<Scene> sources = incomingSources(scene, chapterScenes);
|
||||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
|
||||||
.filter(s -> s.getBranches().stream().anyMatch(b -> scene.getId().equals(b.targetSceneId())))
|
|
||||||
.toList();
|
|
||||||
if (sources.size() < REVELATION_MIN_INCOMING) {
|
if (sources.size() < REVELATION_MIN_INCOMING) {
|
||||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||||
Map.of("incoming", String.valueOf(sources.size()))));
|
Map.of("incoming", String.valueOf(sources.size()))));
|
||||||
@@ -459,12 +571,17 @@ public class WritingReviewService {
|
|||||||
// --- Niveau arc -----------------------------------------------------------------------
|
// --- Niveau arc -----------------------------------------------------------------------
|
||||||
|
|
||||||
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
||||||
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
|
private void checkSingleEnding(Arc arc, boolean implicitArc, List<Scene> lastChapterScenes,
|
||||||
|
List<WritingRemark> out) {
|
||||||
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
||||||
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
||||||
|
// Arc créé d'office : le front parle alors de la fin « de la campagne », sans nommer l'arc.
|
||||||
|
Map<String, String> params = implicitArc
|
||||||
|
? Map.of("arc", labelOr(arc.getName(), "Arc"), PARAM_IMPLICIT_ARC, "true")
|
||||||
|
: Map.of("arc", labelOr(arc.getName(), "Arc"));
|
||||||
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
||||||
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
||||||
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
|
params, arc.getId(), finale.getChapterId()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -514,13 +631,21 @@ public class WritingReviewService {
|
|||||||
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
||||||
WritingRemarkCategory category, Map<String, String> params) {
|
WritingRemarkCategory category, Map<String, String> params) {
|
||||||
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
||||||
ruleId, category, params, arc.getId(), chapter.getId());
|
ruleId, category, withMethod(chapter, params), arc.getId(), chapter.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
||||||
WritingRemarkCategory category, Map<String, String> params) {
|
WritingRemarkCategory category, Map<String, String> params) {
|
||||||
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
||||||
ruleId, category, params, arc.getId(), chapter.getId());
|
ruleId, category, withMethod(chapter, params), arc.getId(), chapter.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Les paramètres de la remarque, plus la méthode guidée du chapitre s'il en suit une. */
|
||||||
|
private static Map<String, String> withMethod(Chapter chapter, Map<String, String> params) {
|
||||||
|
if (isBlank(chapter.getGuidedMethod())) return params;
|
||||||
|
Map<String, String> all = new HashMap<>(params);
|
||||||
|
all.put(PARAM_GUIDED_METHOD, chapter.getGuidedMethod());
|
||||||
|
return all;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
||||||
|
|||||||
+1
-1
@@ -61,7 +61,7 @@ public class GameSystemContextBuilder {
|
|||||||
* Découpe le markdown par titres H2. Préserve l'ordre d'apparition (LinkedHashMap).
|
* Découpe le markdown par titres H2. Préserve l'ordre d'apparition (LinkedHashMap).
|
||||||
* Le contenu avant le premier H2 est ignoré (préambule libre).
|
* Le contenu avant le premier H2 est ignoré (préambule libre).
|
||||||
*/
|
*/
|
||||||
Map<String, String> parseH2Sections(String markdown) {
|
static Map<String, String> parseH2Sections(String markdown) {
|
||||||
Map<String, String> sections = new LinkedHashMap<>();
|
Map<String, String> sections = new LinkedHashMap<>();
|
||||||
if (markdown == null || markdown.isBlank()) return sections;
|
if (markdown == null || markdown.isBlank()) return sections;
|
||||||
|
|
||||||
|
|||||||
+601
@@ -0,0 +1,601 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.bestiary.Enemy;
|
||||||
|
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.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.Room;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrill;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach.DrillCandidate;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach.SceneBrief;
|
||||||
|
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.EnumMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
import java.util.function.IntUnaryOperator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entraînement aux règles : le MJ tranche des situations tirées de ses scènes, puis lit un
|
||||||
|
* corrigé qui cite les règles de son système.
|
||||||
|
* <p>
|
||||||
|
* Une série se prépare en UN appel à l'IA (situations et corrigés ensemble) ; la comparaison
|
||||||
|
* d'une réponse écrite est un second appel, facultatif. Rien n'est enregistré.
|
||||||
|
* <p>
|
||||||
|
* Garde-fou central : une situation n'est gardée que si l'extrait cité se retrouve mot pour
|
||||||
|
* mot (aux espaces, à la casse et à la mise en forme près) dans une section de règles
|
||||||
|
* envoyée. L'extrait affiché vient donc toujours des règles du MJ ; seule la lecture qu'en
|
||||||
|
* fait l'IA reste à relire.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class RuleTrainingService {
|
||||||
|
|
||||||
|
/** Taille totale des règles envoyées (~6 000 jetons), comme pour la proposition de fiche. */
|
||||||
|
static final int MAX_RULES_CHARS = 24_000;
|
||||||
|
/** Part maximale d'une section : au-delà, elle est parcourue par morceaux d'une série à l'autre. */
|
||||||
|
static final int MAX_SECTION_CHARS = 9_000;
|
||||||
|
/** En dessous, un reste de budget ne vaut pas un extrait tronqué de plus. */
|
||||||
|
static final int MIN_WINDOW_CHARS = 400;
|
||||||
|
|
||||||
|
static final int DRILL_COUNT = 5;
|
||||||
|
static final int MAX_DRILLS = 8;
|
||||||
|
static final int MAX_SCENES = 8;
|
||||||
|
static final int MAX_SCENE_CHARS = 1_500;
|
||||||
|
static final int MAX_SCENE_FIELD_CHARS = 400;
|
||||||
|
static final int MAX_AVOIDED = 10;
|
||||||
|
static final int MAX_ANSWER_CHARS = 2_000;
|
||||||
|
|
||||||
|
/** Un extrait plus court ne prouve rien (« un jet », « 1d6 »). */
|
||||||
|
static final int MIN_EXCERPT_CHARS = 25;
|
||||||
|
/** Un extrait plus long n'est plus une citation, c'est la section recopiée. */
|
||||||
|
static final int MAX_EXCERPT_CHARS = 1_500;
|
||||||
|
/** Morceau minimal d'un extrait coupé par des points de suspension. */
|
||||||
|
static final int MIN_FRAGMENT_CHARS = 12;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections conseillées selon le type de scène (comparaison par {@code contains} sur le
|
||||||
|
* titre en minuscules, comme {@link com.loremind.domain.gamesystemcontext.GenerationIntent}).
|
||||||
|
*/
|
||||||
|
private static final Map<SceneType, Set<String>> FOCUS = new EnumMap<>(SceneType.class);
|
||||||
|
|
||||||
|
static {
|
||||||
|
FOCUS.put(SceneType.ENCOUNTER, Set.of("combat", "monstre", "monster", "créature", "creature",
|
||||||
|
"ennemi", "enemy", "adversaire", "bestiaire", "bestiary", "état", "etat", "condition",
|
||||||
|
"blessure", "dégât", "degat", "damage", "initiative"));
|
||||||
|
FOCUS.put(SceneType.LOCATION, Set.of("exploration", "déplacement", "deplacement", "movement",
|
||||||
|
"voyage", "travel", "piège", "piege", "trap", "perception", "environnement",
|
||||||
|
"environment", "danger", "hazard", "lumière", "light"));
|
||||||
|
FOCUS.put(SceneType.NPC, Set.of("social", "interaction", "pnj", "npc", "compétence",
|
||||||
|
"competence", "skill", "réaction", "reaction", "influence"));
|
||||||
|
FOCUS.put(SceneType.EVENT, Set.of("compétence", "competence", "skill", "test", "jet",
|
||||||
|
"résolution", "resolution", "action"));
|
||||||
|
FOCUS.put(SceneType.REVELATION, Set.of("enquête", "enquete", "investigation", "compétence",
|
||||||
|
"competence", "skill", "perception", "indice", "clue", "connaissance", "knowledge"));
|
||||||
|
FOCUS.put(SceneType.GENERIC, Set.of("résolution", "resolution", "test", "jet", "compétence",
|
||||||
|
"competence", "skill", "action", "base", "core", "système", "systeme", "mécanique",
|
||||||
|
"mecanique", "mechanic"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum Status { READY, NO_SYSTEM, NO_RULES }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Section de règles proposée au choix. {@code suggestedFor} : types de scène qui la
|
||||||
|
* précochent. {@code otherLanguage} : rédigée dans l'autre langue que l'interface, donc
|
||||||
|
* masquée tant que le MJ ne demande pas à la voir.
|
||||||
|
*/
|
||||||
|
public record SectionInfo(String title, int chars, List<SceneType> suggestedFor, boolean otherLanguage) {}
|
||||||
|
|
||||||
|
/** Sections des règles ({@code titre → texte}) et titres de celles rédigées dans l'autre langue. */
|
||||||
|
record Rules(Map<String, String> sections, Set<String> otherLanguage) {}
|
||||||
|
|
||||||
|
public record SceneInfo(String id, String name, SceneType type) {}
|
||||||
|
|
||||||
|
/** Aventure (ou espace de scènes d'une quête annexe) et ses scènes, dans l'ordre de la campagne. */
|
||||||
|
public record AdventureInfo(String id, String arcId, String name, boolean sideQuest, List<SceneInfo> scenes) {}
|
||||||
|
|
||||||
|
/** Ce que l'écran propose avant une série. */
|
||||||
|
public record Options(Status status, String gameSystemId, String gameSystemName,
|
||||||
|
List<SectionInfo> sections, List<AdventureInfo> adventures) {}
|
||||||
|
|
||||||
|
/** Une série. {@code dropped} : situations écartées parce que leur extrait ne figurait pas dans les règles. */
|
||||||
|
public record Series(String gameSystemName, List<RuleDrill> drills, List<String> sections, int dropped) {}
|
||||||
|
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
private final ArcRepository arcRepository;
|
||||||
|
private final ChapterRepository chapterRepository;
|
||||||
|
private final SceneRepository sceneRepository;
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final CurrentLanguage currentLanguage;
|
||||||
|
private final RuleTrainingCoach coach;
|
||||||
|
/** Choisit le morceau d'une section trop longue (borne exclusive → rang). */
|
||||||
|
private final IntUnaryOperator windowPicker;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public RuleTrainingService(CampaignRepository campaignRepository, ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository, SceneRepository sceneRepository,
|
||||||
|
EnemyRepository enemyRepository, GameSystemRepository gameSystemRepository,
|
||||||
|
CurrentLanguage currentLanguage, RuleTrainingCoach coach) {
|
||||||
|
this(campaignRepository, arcRepository, chapterRepository, sceneRepository, enemyRepository,
|
||||||
|
gameSystemRepository, currentLanguage, coach,
|
||||||
|
bound -> ThreadLocalRandom.current().nextInt(bound));
|
||||||
|
}
|
||||||
|
|
||||||
|
RuleTrainingService(CampaignRepository campaignRepository, ArcRepository arcRepository,
|
||||||
|
ChapterRepository chapterRepository, SceneRepository sceneRepository,
|
||||||
|
EnemyRepository enemyRepository, GameSystemRepository gameSystemRepository,
|
||||||
|
CurrentLanguage currentLanguage, RuleTrainingCoach coach,
|
||||||
|
IntUnaryOperator windowPicker) {
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
|
this.arcRepository = arcRepository;
|
||||||
|
this.chapterRepository = chapterRepository;
|
||||||
|
this.sceneRepository = sceneRepository;
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.currentLanguage = currentLanguage;
|
||||||
|
this.coach = coach;
|
||||||
|
this.windowPicker = windowPicker;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Ce que l'écran propose ---------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si la campagne est inconnue
|
||||||
|
*/
|
||||||
|
public Options options(String campaignId) {
|
||||||
|
Campaign campaign = campaign(campaignId);
|
||||||
|
List<AdventureInfo> adventures = adventures(campaignId);
|
||||||
|
Optional<GameSystem> system = system(campaign);
|
||||||
|
if (system.isEmpty()) {
|
||||||
|
return new Options(Status.NO_SYSTEM, null, "", List.of(), adventures);
|
||||||
|
}
|
||||||
|
GameSystem gs = system.get();
|
||||||
|
Rules rules = rules(gs);
|
||||||
|
List<SectionInfo> sections = rules.sections().entrySet().stream()
|
||||||
|
.map(e -> new SectionInfo(e.getKey(), e.getValue().length(), suggestedFor(e.getKey()),
|
||||||
|
rules.otherLanguage().contains(e.getKey())))
|
||||||
|
.toList();
|
||||||
|
return new Options(sections.isEmpty() ? Status.NO_RULES : Status.READY,
|
||||||
|
gs.getId(), nz(gs.getName()), sections, adventures);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AdventureInfo> adventures(String campaignId) {
|
||||||
|
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||||
|
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||||
|
List<AdventureInfo> out = new ArrayList<>();
|
||||||
|
for (Arc arc : arcs) {
|
||||||
|
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||||
|
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||||
|
for (Chapter chapter : chapters) {
|
||||||
|
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
|
||||||
|
if (scenes.isEmpty()) continue;
|
||||||
|
scenes.sort(Comparator.comparingInt(Scene::getOrder));
|
||||||
|
out.add(new AdventureInfo(chapter.getId(), arc.getId(), nz(chapter.getName()),
|
||||||
|
arc.getType() == ArcType.SYSTEM,
|
||||||
|
scenes.stream().map(s -> new SceneInfo(s.getId(), nz(s.getName()), typeOf(s))).toList()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<SceneType> suggestedFor(String title) {
|
||||||
|
String lower = title.toLowerCase(Locale.ROOT);
|
||||||
|
return FOCUS.entrySet().stream()
|
||||||
|
.filter(e -> e.getValue().stream().anyMatch(lower::contains))
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Une série ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prépare une série.
|
||||||
|
*
|
||||||
|
* @param sceneIds scènes qui servent de décor (aucune : situations générales)
|
||||||
|
* @param sectionTitles sections à travailler, par ordre de priorité (aucune : sections
|
||||||
|
* conseillées pour ces scènes, à défaut toutes, parmi celles rédigées
|
||||||
|
* dans la langue de l'interface)
|
||||||
|
* @param avoid situations déjà posées, à ne pas reposer
|
||||||
|
* @throws IllegalArgumentException si la campagne est inconnue, sans système ou sans règles
|
||||||
|
*/
|
||||||
|
public Series prepare(String campaignId, List<String> sceneIds, List<String> sectionTitles, List<String> avoid) {
|
||||||
|
Campaign campaign = campaign(campaignId);
|
||||||
|
GameSystem gs = system(campaign)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Cette campagne n'a pas de système de jeu."));
|
||||||
|
Rules rules = rules(gs);
|
||||||
|
Map<String, String> all = rules.sections();
|
||||||
|
if (all.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Ce système de jeu n'a pas encore de règles.");
|
||||||
|
}
|
||||||
|
List<Scene> scenes = scenesOf(campaignId, sceneIds);
|
||||||
|
Map<String, String> sent = selectSections(all,
|
||||||
|
wantedTitles(all, sectionTitles, scenes, rules.otherLanguage()), windowPicker);
|
||||||
|
List<SceneBrief> briefs = scenes.stream().map(this::brief).toList();
|
||||||
|
|
||||||
|
List<DrillCandidate> candidates = coach.prepare(nz(gs.getName()), sent, briefs, DRILL_COUNT, clean(avoid));
|
||||||
|
List<RuleDrill> drills = inLanguage(validate(candidates, sent, scenes), rules.otherLanguage(),
|
||||||
|
currentLanguage.get());
|
||||||
|
int received = candidates == null ? 0 : candidates.size();
|
||||||
|
return new Series(nz(gs.getName()), drills, List.copyOf(sent.keySet()), Math.max(0, received - drills.size()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Titres demandés qui existent ; à défaut ceux conseillés pour ces scènes ; à défaut tous.
|
||||||
|
* Une section rédigée dans l'autre langue n'est prise que si elle est demandée.
|
||||||
|
*/
|
||||||
|
static List<String> wantedTitles(Map<String, String> all, List<String> requested, List<Scene> scenes,
|
||||||
|
Set<String> otherLanguage) {
|
||||||
|
List<String> wanted = new ArrayList<>();
|
||||||
|
for (String title : requested == null ? List.<String>of() : requested) {
|
||||||
|
findTitle(all.keySet(), title).filter(t -> !wanted.contains(t)).ifPresent(wanted::add);
|
||||||
|
}
|
||||||
|
if (!wanted.isEmpty()) return wanted;
|
||||||
|
|
||||||
|
Set<SceneType> types = new LinkedHashSet<>();
|
||||||
|
scenes.forEach(s -> types.add(typeOf(s)));
|
||||||
|
if (types.isEmpty()) types.add(SceneType.GENERIC);
|
||||||
|
List<String> offered = all.keySet().stream().filter(t -> !otherLanguage.contains(t)).toList();
|
||||||
|
for (String title : offered) {
|
||||||
|
if (suggestedFor(title).stream().anyMatch(types::contains)) wanted.add(title);
|
||||||
|
}
|
||||||
|
return wanted.isEmpty() ? new ArrayList<>(offered) : wanted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Titres des sections rédigées dans l'autre langue que l'interface. Aucun si toutes le
|
||||||
|
* sont : des règles qui n'existent que dans une langue restent proposées en entier.
|
||||||
|
*/
|
||||||
|
static Set<String> otherLanguageTitles(Map<String, String> sections, String language) {
|
||||||
|
String wanted = RulesLanguage.of(language);
|
||||||
|
Set<String> other = new LinkedHashSet<>();
|
||||||
|
sections.forEach((title, content) -> {
|
||||||
|
if (RulesLanguage.detect(content).filter(found -> !found.equals(wanted)).isPresent()) other.add(title);
|
||||||
|
});
|
||||||
|
return other.size() == sections.size() ? Set.of() : other;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections envoyées, dans l'ordre demandé et dans la limite du budget. Une section trop
|
||||||
|
* longue n'envoie qu'un de ses morceaux : la série suivante en verra un autre.
|
||||||
|
*/
|
||||||
|
static Map<String, String> selectSections(Map<String, String> all, List<String> ordered, IntUnaryOperator picker) {
|
||||||
|
Map<String, String> selected = new LinkedHashMap<>();
|
||||||
|
int remaining = MAX_RULES_CHARS;
|
||||||
|
for (String title : ordered) {
|
||||||
|
String content = all.get(title);
|
||||||
|
if (content == null || content.isBlank()) continue;
|
||||||
|
int allowed = Math.min(MAX_SECTION_CHARS, remaining);
|
||||||
|
if (content.length() > allowed) {
|
||||||
|
if (allowed < MIN_WINDOW_CHARS) break;
|
||||||
|
List<String> windows = windows(content, allowed);
|
||||||
|
content = windows.get(Math.floorMod(picker.applyAsInt(windows.size()), windows.size()));
|
||||||
|
}
|
||||||
|
selected.put(title, content);
|
||||||
|
remaining -= content.length();
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Découpe un texte en morceaux d'au plus {@code max} caractères, aux lignes vides si possible. */
|
||||||
|
static List<String> windows(String content, int max) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
StringBuilder current = new StringBuilder();
|
||||||
|
for (String paragraph : content.split("\\n\\s*\\n")) {
|
||||||
|
String p = paragraph.strip();
|
||||||
|
if (p.isEmpty()) continue;
|
||||||
|
if (current.length() > 0 && current.length() + 2 + p.length() > max) {
|
||||||
|
out.add(current.toString());
|
||||||
|
current.setLength(0);
|
||||||
|
}
|
||||||
|
while (p.length() > max) {
|
||||||
|
if (current.length() > 0) {
|
||||||
|
out.add(current.toString());
|
||||||
|
current.setLength(0);
|
||||||
|
}
|
||||||
|
out.add(p.substring(0, max));
|
||||||
|
p = p.substring(max).strip();
|
||||||
|
}
|
||||||
|
if (p.isEmpty()) continue;
|
||||||
|
if (current.length() > 0) current.append("\n\n");
|
||||||
|
current.append(p);
|
||||||
|
}
|
||||||
|
if (current.length() > 0) out.add(current.toString());
|
||||||
|
return out.isEmpty() ? List.of(content.substring(0, Math.min(max, content.length()))) : out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Tri de la réponse -------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde les situations dont l'extrait figure dans une section envoyée. La section annoncée
|
||||||
|
* est corrigée si l'extrait se trouve dans une autre ; une situation sans extrait retrouvé,
|
||||||
|
* ou posée deux fois, est écartée.
|
||||||
|
*/
|
||||||
|
static List<RuleDrill> validate(List<DrillCandidate> candidates, Map<String, String> sent, List<Scene> scenes) {
|
||||||
|
Map<String, String> normalized = new LinkedHashMap<>();
|
||||||
|
sent.forEach((title, content) -> normalized.put(title, normalize(content)));
|
||||||
|
|
||||||
|
List<RuleDrill> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (DrillCandidate c : candidates == null ? List.<DrillCandidate>of() : candidates) {
|
||||||
|
if (out.size() >= MAX_DRILLS) break;
|
||||||
|
if (c == null || isBlank(c.situation()) || isBlank(c.ruling()) || isBlank(c.excerpt())) continue;
|
||||||
|
String excerpt = c.excerpt().strip();
|
||||||
|
if (excerpt.length() > MAX_EXCERPT_CHARS) continue;
|
||||||
|
Optional<String> section = locate(excerpt, c.section(), normalized);
|
||||||
|
if (section.isEmpty()) continue;
|
||||||
|
String situation = c.situation().strip();
|
||||||
|
if (!seen.add(situation.toLowerCase(Locale.ROOT))) continue;
|
||||||
|
|
||||||
|
Scene scene = c.scene() >= 1 && c.scene() <= scenes.size() ? scenes.get(c.scene() - 1) : null;
|
||||||
|
out.add(new RuleDrill(scene == null ? null : scene.getId(), scene == null ? "" : nz(scene.getName()),
|
||||||
|
situation, section.get(), excerpt, c.ruling().strip()));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Écarte les situations dont la citation est rédigée dans l'autre langue que l'interface
|
||||||
|
* (un passage resté en version originale dans une section traduite). Les sections que le
|
||||||
|
* MJ a choisies en sachant qu'elles sont dans l'autre langue ne sont pas concernées.
|
||||||
|
*/
|
||||||
|
static List<RuleDrill> inLanguage(List<RuleDrill> drills, Set<String> otherLanguage, String language) {
|
||||||
|
String wanted = RulesLanguage.of(language);
|
||||||
|
return drills.stream()
|
||||||
|
.filter(d -> otherLanguage.contains(d.section())
|
||||||
|
|| RulesLanguage.detect(d.excerpt()).filter(found -> !found.equals(wanted)).isEmpty())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Section qui contient l'extrait : celle annoncée d'abord, sinon la première autre. */
|
||||||
|
private static Optional<String> locate(String excerpt, String announced, Map<String, String> normalized) {
|
||||||
|
Optional<String> first = findTitle(normalized.keySet(), announced);
|
||||||
|
if (first.isPresent() && contains(normalized.get(first.get()), excerpt)) return first;
|
||||||
|
return normalized.entrySet().stream()
|
||||||
|
.filter(e -> contains(e.getValue(), excerpt))
|
||||||
|
.map(Map.Entry::getKey)
|
||||||
|
.findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* L'extrait figure-t-il dans le texte (déjà normalisé) ? Un extrait coupé par des points de
|
||||||
|
* suspension est accepté si ses morceaux s'y suivent dans l'ordre.
|
||||||
|
*/
|
||||||
|
static boolean contains(String normalizedText, String excerpt) {
|
||||||
|
int total = 0;
|
||||||
|
int from = 0;
|
||||||
|
for (String part : excerpt.split("\\[\\s*(?:…|\\.{3})\\s*]|…|\\.{3}")) {
|
||||||
|
String fragment = normalize(part);
|
||||||
|
if (fragment.length() < MIN_FRAGMENT_CHARS) continue;
|
||||||
|
int at = normalizedText.indexOf(fragment, from);
|
||||||
|
if (at < 0) return false;
|
||||||
|
from = at + fragment.length();
|
||||||
|
total += fragment.length();
|
||||||
|
}
|
||||||
|
return total >= MIN_EXCERPT_CHARS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Texte ramené à ce qui se lit : minuscules, mise en forme markdown et guillemets retirés,
|
||||||
|
* apostrophes et espaces unifiés. Un modèle qui recopie « **Garde** » en « Garde » cite
|
||||||
|
* fidèlement ; un modèle qui reformule ne passe pas.
|
||||||
|
*/
|
||||||
|
static String normalize(String text) {
|
||||||
|
if (text == null) return "";
|
||||||
|
StringBuilder sb = new StringBuilder(text.length());
|
||||||
|
boolean space = false;
|
||||||
|
for (int i = 0; i < text.length(); i++) {
|
||||||
|
char ch = text.charAt(i);
|
||||||
|
if (ch == '’' || ch == '‘' || ch == 'ʼ') ch = '\'';
|
||||||
|
if (ch == '*' || ch == '_' || ch == '`' || ch == '#' || ch == '>' || ch == '|'
|
||||||
|
|| ch == '"' || ch == '«' || ch == '»' || ch == '“' || ch == '”') {
|
||||||
|
ch = ' ';
|
||||||
|
}
|
||||||
|
if (Character.isWhitespace(ch) || Character.isSpaceChar(ch)) {
|
||||||
|
space = sb.length() > 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (space) {
|
||||||
|
sb.append(' ');
|
||||||
|
space = false;
|
||||||
|
}
|
||||||
|
sb.append(Character.toLowerCase(ch));
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Comparaison d'une réponse -----------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare la décision écrite par le MJ aux règles de la section et au corrigé.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException si la réponse est vide, ou si la section n'existe plus
|
||||||
|
*/
|
||||||
|
public RuleDrillReview review(String campaignId, String section, String situation,
|
||||||
|
String excerpt, String ruling, String answer) {
|
||||||
|
if (isBlank(answer) || isBlank(situation)) {
|
||||||
|
throw new IllegalArgumentException("Écrivez votre décision avant de la comparer.");
|
||||||
|
}
|
||||||
|
GameSystem gs = system(campaign(campaignId))
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Cette campagne n'a pas de système de jeu."));
|
||||||
|
Map<String, String> all = rules(gs).sections();
|
||||||
|
String title = findTitle(all.keySet(), section)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Cette section n'existe plus dans les règles."));
|
||||||
|
String trimmed = answer.strip();
|
||||||
|
return coach.review(nz(gs.getName()), title, windowAround(all.get(title), nz(excerpt)),
|
||||||
|
situation.strip(), nz(excerpt).strip(), nz(ruling).strip(),
|
||||||
|
trimmed.length() > MAX_ANSWER_CHARS ? trimmed.substring(0, MAX_ANSWER_CHARS) : trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** La section entière si elle tient, sinon son morceau qui contient l'extrait (à défaut le premier). */
|
||||||
|
static String windowAround(String content, String excerpt) {
|
||||||
|
if (content.length() <= MAX_SECTION_CHARS) return content;
|
||||||
|
List<String> windows = windows(content, MAX_SECTION_CHARS);
|
||||||
|
return windows.stream()
|
||||||
|
.filter(w -> contains(normalize(w), excerpt))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(windows.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Chargement --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private Campaign campaign(String campaignId) {
|
||||||
|
return campaignRepository.findById(campaignId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Campagne inconnue : " + campaignId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Optional<GameSystem> system(Campaign campaign) {
|
||||||
|
return campaign.getGameSystemId() == null || campaign.getGameSystemId().isBlank()
|
||||||
|
? Optional.empty()
|
||||||
|
: gameSystemRepository.findById(campaign.getGameSystemId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections non vides des règles, prises dans l'onglet de la langue de l'interface (repli
|
||||||
|
* sur l'autre s'il est vide), avec celles dont le texte est en réalité dans l'autre langue.
|
||||||
|
*/
|
||||||
|
private Rules rules(GameSystem gs) {
|
||||||
|
String language = currentLanguage.get();
|
||||||
|
Map<String, String> sections = new LinkedHashMap<>();
|
||||||
|
GameSystemContextBuilder.parseH2Sections(gs.rulesFor(language)).forEach((title, content) -> {
|
||||||
|
if (!isBlank(title) && !isBlank(content)) sections.put(title, content);
|
||||||
|
});
|
||||||
|
return new Rules(sections, otherLanguageTitles(sections, language));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scènes demandées qui appartiennent bien à la campagne, dans l'ordre demandé, sans doublon. */
|
||||||
|
private List<Scene> scenesOf(String campaignId, List<String> sceneIds) {
|
||||||
|
List<Scene> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String id : sceneIds == null ? List.<String>of() : sceneIds) {
|
||||||
|
if (out.size() >= MAX_SCENES) break;
|
||||||
|
if (id == null || !seen.add(id)) continue;
|
||||||
|
sceneRepository.findById(id).filter(s -> belongsTo(s, campaignId)).ifPresent(out::add);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean belongsTo(Scene scene, String campaignId) {
|
||||||
|
return Optional.ofNullable(scene.getChapterId())
|
||||||
|
.flatMap(chapterRepository::findById)
|
||||||
|
.map(Chapter::getArcId)
|
||||||
|
.flatMap(arcRepository::findById)
|
||||||
|
.map(arc -> Objects.equals(arc.getCampaignId(), campaignId))
|
||||||
|
.orElse(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Résumé d'une scène ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Ce qu'il faut de la scène pour y situer une action : lieu, personnages, adversaires. */
|
||||||
|
private SceneBrief brief(Scene scene) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
line(sb, "Résumé", scene.getDescription());
|
||||||
|
line(sb, "Lieu", scene.getLocation());
|
||||||
|
line(sb, "Moment", scene.getTiming());
|
||||||
|
line(sb, "Ambiance", scene.getAtmosphere());
|
||||||
|
line(sb, "Narration", scene.getPlayerNarration());
|
||||||
|
line(sb, "Choix", scene.getChoicesConsequences());
|
||||||
|
line(sb, "Adversaires", joinNonBlank(scene.getEnemies(), enemyNames(scene.getEnemyIds())));
|
||||||
|
line(sb, "Tactique", scene.getTactics());
|
||||||
|
line(sb, "Difficulté", scene.getCombatDifficulty());
|
||||||
|
line(sb, "Pièces", rooms(scene.getRooms()));
|
||||||
|
line(sb, "Notes du MJ", scene.getGmSecretNotes());
|
||||||
|
String text = sb.toString().strip();
|
||||||
|
return new SceneBrief(nz(scene.getName()), kindLabel(typeOf(scene)),
|
||||||
|
text.length() > MAX_SCENE_CHARS ? text.substring(0, MAX_SCENE_CHARS).stripTrailing() + "…" : text);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void line(StringBuilder sb, String label, String value) {
|
||||||
|
if (isBlank(value)) return;
|
||||||
|
String v = value.strip().replaceAll("\\s+", " ");
|
||||||
|
if (v.length() > MAX_SCENE_FIELD_CHARS) v = v.substring(0, MAX_SCENE_FIELD_CHARS).stripTrailing() + "…";
|
||||||
|
sb.append(label).append(" : ").append(v).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
private String enemyNames(List<String> enemyIds) {
|
||||||
|
List<String> names = new ArrayList<>();
|
||||||
|
for (String id : enemyIds == null ? List.<String>of() : enemyIds) {
|
||||||
|
enemyRepository.findById(id).map(Enemy::getName).filter(n -> !isBlank(n)).ifPresent(names::add);
|
||||||
|
}
|
||||||
|
return String.join(", ", names);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String rooms(List<Room> rooms) {
|
||||||
|
List<String> parts = new ArrayList<>();
|
||||||
|
for (Room room : rooms == null ? List.<Room>of() : rooms) {
|
||||||
|
if (room == null || isBlank(room.getName())) continue;
|
||||||
|
parts.add(joinNonBlank(room.getName().strip(), joinNonBlank(room.getEnemies(), room.getTraps())));
|
||||||
|
}
|
||||||
|
return String.join(" ; ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String kindLabel(SceneType type) {
|
||||||
|
return switch (type) {
|
||||||
|
case LOCATION -> "lieu à explorer";
|
||||||
|
case ENCOUNTER -> "rencontre ou combat";
|
||||||
|
case NPC -> "scène autour d'un personnage";
|
||||||
|
case EVENT -> "événement";
|
||||||
|
case REVELATION -> "révélation";
|
||||||
|
case GENERIC -> "";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Utilitaires -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static SceneType typeOf(Scene scene) {
|
||||||
|
return scene.getType() == null ? SceneType.GENERIC : scene.getType();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<String> findTitle(Set<String> titles, String wanted) {
|
||||||
|
if (isBlank(wanted)) return Optional.empty();
|
||||||
|
String key = wanted.strip();
|
||||||
|
return titles.stream().filter(t -> t.equalsIgnoreCase(key)).findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> clean(List<String> values) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (String value : values == null ? List.<String>of() : values) {
|
||||||
|
if (out.size() >= MAX_AVOIDED) break;
|
||||||
|
if (!isBlank(value)) out.add(value.strip());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String joinNonBlank(String a, String b) {
|
||||||
|
if (isBlank(a)) return nz(b).strip();
|
||||||
|
if (isBlank(b)) return a.strip();
|
||||||
|
return a.strip() + " — " + b.strip();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Langue dans laquelle un passage de règles est rédigé, d'après ses mots outils.
|
||||||
|
* <p>
|
||||||
|
* L'onglet français des règles peut contenir du texte anglais (livre importé en version
|
||||||
|
* originale), et l'inverse : le champ dans lequel un texte est rangé ne dit pas sa langue.
|
||||||
|
* Un passage trop court, ou partagé entre les deux langues, reste indéterminé.
|
||||||
|
*/
|
||||||
|
final class RulesLanguage {
|
||||||
|
|
||||||
|
static final String FRENCH = "fr";
|
||||||
|
static final String ENGLISH = "en";
|
||||||
|
|
||||||
|
/** En dessous, le passage (un tableau de chiffres, trois mots) ne permet pas de trancher. */
|
||||||
|
static final int MIN_MARKERS = 5;
|
||||||
|
|
||||||
|
/** Mots outils propres à une langue : « a », « on », « plus » ou « or » sont écartés. */
|
||||||
|
private static final Set<String> FRENCH_WORDS = Set.of(
|
||||||
|
"le", "la", "les", "de", "des", "une", "un", "du", "au", "aux", "et", "est", "sont", "dans",
|
||||||
|
"pour", "que", "qui", "avec", "vous", "votre", "vos", "sur", "pas", "ce", "cette", "ces",
|
||||||
|
"ou", "par", "peut", "ne", "se", "leur", "leurs", "chaque", "lorsque", "à", "il", "elle",
|
||||||
|
"ils", "mais", "être");
|
||||||
|
private static final Set<String> ENGLISH_WORDS = Set.of(
|
||||||
|
"the", "of", "and", "to", "is", "in", "you", "your", "that", "with", "for", "it", "as",
|
||||||
|
"can", "are", "be", "this", "when", "at", "from", "by", "not", "each", "may", "any", "if",
|
||||||
|
"must", "has", "have", "their", "they", "will", "which");
|
||||||
|
|
||||||
|
private static final Pattern WORD = Pattern.compile("\\p{L}+");
|
||||||
|
|
||||||
|
private RulesLanguage() {}
|
||||||
|
|
||||||
|
/** {@code fr} ou {@code en} si l'une des deux domine nettement, sinon rien. */
|
||||||
|
static Optional<String> detect(String text) {
|
||||||
|
if (text == null) return Optional.empty();
|
||||||
|
int french = 0;
|
||||||
|
int english = 0;
|
||||||
|
Matcher matcher = WORD.matcher(text.toLowerCase(Locale.ROOT));
|
||||||
|
while (matcher.find()) {
|
||||||
|
String word = matcher.group();
|
||||||
|
if (FRENCH_WORDS.contains(word)) french++;
|
||||||
|
else if (ENGLISH_WORDS.contains(word)) english++;
|
||||||
|
}
|
||||||
|
if (french + english < MIN_MARKERS) return Optional.empty();
|
||||||
|
if (french * 2 >= english * 3) return Optional.of(FRENCH);
|
||||||
|
if (english * 2 >= french * 3) return Optional.of(ENGLISH);
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Langue de l'interface ramenée à {@code fr} ou {@code en} ({@code fr} par défaut). */
|
||||||
|
static String of(String language) {
|
||||||
|
return ENGLISH.equalsIgnoreCase(language) ? ENGLISH : FRENCH;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CharacterRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.EnemyRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.NpcRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetSpellRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellRepository;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sorts connus d'une fiche (PJ, PNJ ou ennemi) : des liens vers des sorts du catalogue du
|
||||||
|
* système, rangés à part des fiches. Une fiche garde ainsi exactement ce qu'elle portait
|
||||||
|
* avant, et un sort retiré du catalogue disparaît de lui-même des fiches.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SheetSpellService {
|
||||||
|
|
||||||
|
/** Garde-fou : aucune fiche ne connaît autant de sorts. */
|
||||||
|
static final int MAX_SPELLS = 500;
|
||||||
|
|
||||||
|
private final SheetSpellRepository sheetSpellRepository;
|
||||||
|
private final SpellRepository spellRepository;
|
||||||
|
private final CharacterRepository characterRepository;
|
||||||
|
private final NpcRepository npcRepository;
|
||||||
|
private final EnemyRepository enemyRepository;
|
||||||
|
|
||||||
|
public SheetSpellService(SheetSpellRepository sheetSpellRepository, SpellRepository spellRepository,
|
||||||
|
CharacterRepository characterRepository, NpcRepository npcRepository,
|
||||||
|
EnemyRepository enemyRepository) {
|
||||||
|
this.sheetSpellRepository = sheetSpellRepository;
|
||||||
|
this.spellRepository = spellRepository;
|
||||||
|
this.characterRepository = characterRepository;
|
||||||
|
this.npcRepository = npcRepository;
|
||||||
|
this.enemyRepository = enemyRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si la fiche est inconnue
|
||||||
|
*/
|
||||||
|
public List<String> spellIds(SheetKind kind, String ownerId) {
|
||||||
|
requireOwner(kind, ownerId);
|
||||||
|
return sheetSpellRepository.findSpellIds(kind, ownerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remplace les sorts connus de la fiche. Les doublons et les sorts qui n'existent plus
|
||||||
|
* sont ignorés ; l'ordre reçu est gardé.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException si la fiche est inconnue ou si la liste est démesurée
|
||||||
|
*/
|
||||||
|
public List<String> replace(SheetKind kind, String ownerId, List<String> spellIds) {
|
||||||
|
requireOwner(kind, ownerId);
|
||||||
|
List<String> wanted = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String id : spellIds == null ? List.<String>of() : spellIds) {
|
||||||
|
if (isNumber(id) && seen.add(id.strip())) wanted.add(id.strip());
|
||||||
|
}
|
||||||
|
if (wanted.size() > MAX_SPELLS) {
|
||||||
|
throw new IllegalArgumentException("Une fiche ne peut pas connaître plus de " + MAX_SPELLS + " sorts.");
|
||||||
|
}
|
||||||
|
Set<String> existing = new HashSet<>(spellRepository.existingIds(wanted));
|
||||||
|
List<String> kept = wanted.stream().filter(existing::contains).toList();
|
||||||
|
sheetSpellRepository.replace(kind, ownerId, kept);
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOwner(SheetKind kind, String ownerId) {
|
||||||
|
boolean known = isNumber(ownerId) && switch (kind) {
|
||||||
|
case CHARACTER -> characterRepository.findById(ownerId.strip()).isPresent();
|
||||||
|
case NPC -> npcRepository.findById(ownerId.strip()).isPresent();
|
||||||
|
case ENEMY -> enemyRepository.findById(ownerId.strip()).isPresent();
|
||||||
|
};
|
||||||
|
if (!known) {
|
||||||
|
throw new IllegalArgumentException("Fiche inconnue : " + kind.wireName() + " " + ownerId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Les identifiants sont des entiers en base : tout le reste est ignoré plutôt que de planter. */
|
||||||
|
private static boolean isNumber(String value) {
|
||||||
|
return value != null && value.strip().matches("\\d{1,18}");
|
||||||
|
}
|
||||||
|
}
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetFieldProposal;
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetTemplateAdvisor;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetTemplateAdvisor.Candidate;
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Propose les champs d'une fiche (PJ, PNJ, ennemi) à partir des règles d'un système.
|
||||||
|
* <p>
|
||||||
|
* Travaille sur les règles telles qu'elles sont affichées dans l'éditeur (enregistrées
|
||||||
|
* ou non) : un système dont les règles viennent d'être importées, ou saisies à la main
|
||||||
|
* depuis longtemps, en profite de la même façon. Rien n'est enregistré : la proposition
|
||||||
|
* ne fait qu'AJOUTER des champs, que le MJ choisit un par un.
|
||||||
|
* <p>
|
||||||
|
* Deux garde-fous : seules les sections utiles à la fiche partent vers l'IA, dans une
|
||||||
|
* taille bornée ; et la réponse est triée (types connus, noms uniques, listes
|
||||||
|
* réellement remplies, plafond) avant d'atteindre l'écran.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SheetTemplateProposalService {
|
||||||
|
|
||||||
|
/** Taille totale des règles envoyées (~6 000 jetons, l'ordre de grandeur d'un morceau d'import). */
|
||||||
|
static final int MAX_RULES_CHARS = 24_000;
|
||||||
|
/** Part maximale d'une seule section : une section géante ne doit pas évincer les autres. */
|
||||||
|
static final int MAX_SECTION_CHARS = 9_000;
|
||||||
|
/** En dessous, un reste de budget ne vaut pas un extrait tronqué de plus. */
|
||||||
|
static final int MIN_EXCERPT_CHARS = 400;
|
||||||
|
|
||||||
|
static final int MAX_FIELDS = 25;
|
||||||
|
static final int MAX_NAME_CHARS = 60;
|
||||||
|
static final int MIN_LABELS = 2;
|
||||||
|
static final int MAX_LABELS = 30;
|
||||||
|
static final int MAX_LABEL_CHARS = 40;
|
||||||
|
|
||||||
|
/** Champs que l'application gère elle-même sur toutes les fiches. */
|
||||||
|
private static final Set<String> RESERVED_NAMES = Set.of(
|
||||||
|
"nom", "name", "portrait", "bandeau", "header", "image", "images", "illustration");
|
||||||
|
/** En plus, sur la fiche d'ennemi. */
|
||||||
|
private static final Set<String> RESERVED_ENEMY_NAMES = Set.of("niveau", "level", "dossier", "folder");
|
||||||
|
|
||||||
|
private static final Set<FieldType> PROPOSABLE_TYPES =
|
||||||
|
Set.of(FieldType.TEXT, FieldType.NUMBER, FieldType.KEY_VALUE_LIST);
|
||||||
|
|
||||||
|
/** Section de règles telle qu'affichée dans l'éditeur. */
|
||||||
|
public record RuleSection(String title, String content) {}
|
||||||
|
|
||||||
|
private final SheetTemplateAdvisor advisor;
|
||||||
|
|
||||||
|
public SheetTemplateProposalService(SheetTemplateAdvisor advisor) {
|
||||||
|
this.advisor = advisor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si aucune règle n'est fournie
|
||||||
|
*/
|
||||||
|
public List<SheetFieldProposal> propose(SheetKind kind, String systemName,
|
||||||
|
List<RuleSection> rules, List<String> existingFieldNames) {
|
||||||
|
Map<String, String> all = mergeSections(rules);
|
||||||
|
if (all.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Aucune règle à partir de laquelle proposer une fiche.");
|
||||||
|
}
|
||||||
|
Map<String, String> selected = selectSections(all, kind);
|
||||||
|
List<Candidate> candidates = advisor.propose(
|
||||||
|
kind, systemName == null ? "" : systemName.trim(), selected, cleanNames(existingFieldNames));
|
||||||
|
return validate(candidates, kind, selected.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Choix des sections envoyées ---------------------------------------------------------
|
||||||
|
|
||||||
|
/** Sections non vides, ordre préservé ; deux sections de même titre sont réunies. */
|
||||||
|
static Map<String, String> mergeSections(List<RuleSection> rules) {
|
||||||
|
Map<String, String> merged = new LinkedHashMap<>();
|
||||||
|
Map<String, String> canonical = new LinkedHashMap<>();
|
||||||
|
for (RuleSection section : rules == null ? List.<RuleSection>of() : rules) {
|
||||||
|
if (section == null || isBlank(section.title()) || isBlank(section.content())) continue;
|
||||||
|
String title = section.title().trim();
|
||||||
|
String key = canonical.computeIfAbsent(title.toLowerCase(Locale.ROOT), k -> title);
|
||||||
|
merged.merge(key, section.content().strip(), (a, b) -> a + "\n\n" + b);
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sections utiles à la fiche, par ordre de priorité, dans la limite du budget. Si aucun
|
||||||
|
* titre ne correspond (règles découpées avec des titres maison), toutes les sections sont
|
||||||
|
* candidates, dans l'ordre du document.
|
||||||
|
*/
|
||||||
|
static Map<String, String> selectSections(Map<String, String> all, SheetKind kind) {
|
||||||
|
List<String> ordered = new ArrayList<>();
|
||||||
|
for (Set<String> aliases : kind.sectionAliases()) {
|
||||||
|
for (String title : all.keySet()) {
|
||||||
|
String lower = title.toLowerCase(Locale.ROOT);
|
||||||
|
if (!ordered.contains(title) && aliases.stream().anyMatch(lower::contains)) {
|
||||||
|
ordered.add(title);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ordered.isEmpty()) {
|
||||||
|
ordered.addAll(all.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String> selected = new LinkedHashMap<>();
|
||||||
|
int remaining = MAX_RULES_CHARS;
|
||||||
|
for (String title : ordered) {
|
||||||
|
String content = all.get(title);
|
||||||
|
int allowed = Math.min(MAX_SECTION_CHARS, remaining);
|
||||||
|
if (content.length() > allowed) {
|
||||||
|
if (allowed < MIN_EXCERPT_CHARS) break;
|
||||||
|
content = truncate(content, allowed);
|
||||||
|
}
|
||||||
|
selected.put(title, content);
|
||||||
|
remaining -= content.length();
|
||||||
|
if (remaining <= 0) break;
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Coupe au dernier saut de ligne avant la limite (à défaut, à la limite) et le signale. */
|
||||||
|
private static String truncate(String content, int max) {
|
||||||
|
int cut = content.lastIndexOf('\n', max);
|
||||||
|
if (cut < max / 2) cut = max;
|
||||||
|
return content.substring(0, cut).stripTrailing() + "\n[…]";
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Tri de la réponse ------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde les champs utilisables : type proposable, nom court, unique et non réservé, liste
|
||||||
|
* de valeurs réellement remplie. La source n'est conservée que si elle désigne une section
|
||||||
|
* envoyée. Plafonné à {@link #MAX_FIELDS}.
|
||||||
|
*/
|
||||||
|
static List<SheetFieldProposal> validate(List<Candidate> candidates, SheetKind kind, Set<String> sentTitles) {
|
||||||
|
List<SheetFieldProposal> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (Candidate c : candidates == null ? List.<Candidate>of() : candidates) {
|
||||||
|
if (out.size() >= MAX_FIELDS) break;
|
||||||
|
if (c == null || isBlank(c.name())) continue;
|
||||||
|
String name = c.name().trim().replaceAll("\\s+", " ");
|
||||||
|
String key = name.toLowerCase(Locale.ROOT);
|
||||||
|
FieldType type = parseType(c.type());
|
||||||
|
if (type == null || name.length() > MAX_NAME_CHARS || isReserved(key, kind) || seen.contains(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> labels = type == FieldType.KEY_VALUE_LIST ? cleanLabels(c.labels()) : List.of();
|
||||||
|
if (type == FieldType.KEY_VALUE_LIST && labels.size() < MIN_LABELS) continue;
|
||||||
|
seen.add(key);
|
||||||
|
out.add(new SheetFieldProposal(name, type, labels, matchSource(c.source(), sentTitles)));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FieldType parseType(String raw) {
|
||||||
|
if (raw == null) return null;
|
||||||
|
try {
|
||||||
|
FieldType type = FieldType.valueOf(raw.trim().toUpperCase(Locale.ROOT));
|
||||||
|
return PROPOSABLE_TYPES.contains(type) ? type : null;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isReserved(String lowerName, SheetKind kind) {
|
||||||
|
return RESERVED_NAMES.contains(lowerName)
|
||||||
|
|| (kind == SheetKind.ENEMY && RESERVED_ENEMY_NAMES.contains(lowerName));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> cleanLabels(List<String> labels) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String label : labels == null ? List.<String>of() : labels) {
|
||||||
|
if (out.size() >= MAX_LABELS) break;
|
||||||
|
if (isBlank(label)) continue;
|
||||||
|
String clean = label.trim().replaceAll("\\s+", " ");
|
||||||
|
if (clean.length() <= MAX_LABEL_CHARS && seen.add(clean.toLowerCase(Locale.ROOT))) {
|
||||||
|
out.add(clean);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String matchSource(String source, Set<String> sentTitles) {
|
||||||
|
if (isBlank(source)) return "";
|
||||||
|
String wanted = source.trim();
|
||||||
|
return sentTitles.stream().filter(t -> t.equalsIgnoreCase(wanted)).findFirst().orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> cleanNames(List<String> names) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (String name : names == null ? List.<String>of() : names) {
|
||||||
|
if (!isBlank(name)) out.add(name.trim());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String s) {
|
||||||
|
return s == null || s.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellRepository;
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
import com.loremind.domain.shared.template.TemplateField;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catalogue de sorts d'un système de jeu : les sorts eux-mêmes, et le « modèle de sort »
|
||||||
|
* (champs propres au système : portée, durée, coût…).
|
||||||
|
* <p>
|
||||||
|
* L'écran d'édition d'un système enregistre tout d'un coup : le catalogue est donc remplacé
|
||||||
|
* en bloc. Un sort envoyé avec son identifiant est mis à jour (son identifiant reste stable),
|
||||||
|
* un sort sans identifiant est créé, un sort absent de l'envoi est supprimé.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SpellCatalogService {
|
||||||
|
|
||||||
|
/** Garde-fou : au-delà, l'envoi est une erreur (aucun livre n'en compte autant). */
|
||||||
|
static final int MAX_SPELLS = 3_000;
|
||||||
|
/** Longueur des colonnes nom, niveau et école. */
|
||||||
|
static final int MAX_LABEL_CHARS = 255;
|
||||||
|
|
||||||
|
/** Ce qu'un sort porte à l'enregistrement. {@code id} null = nouveau sort. */
|
||||||
|
public record SpellData(String id, String name, String level, String school, String description,
|
||||||
|
Map<String, String> values) {}
|
||||||
|
|
||||||
|
/** Le modèle de sort du système et ses sorts, dans l'ordre du catalogue. */
|
||||||
|
public record Catalog(List<TemplateField> template, List<Spell> spells) {}
|
||||||
|
|
||||||
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final SpellRepository spellRepository;
|
||||||
|
|
||||||
|
public SpellCatalogService(GameSystemRepository gameSystemRepository, SpellRepository spellRepository) {
|
||||||
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.spellRepository = spellRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws IllegalArgumentException si le système est inconnu
|
||||||
|
*/
|
||||||
|
public Catalog get(String gameSystemId) {
|
||||||
|
GameSystem gs = system(gameSystemId);
|
||||||
|
return new Catalog(List.copyOf(gs.getSpellTemplate()), spellRepository.findByGameSystemId(gs.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remplace le modèle de sort et le catalogue du système.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException si le système est inconnu, si le modèle a un champ sans
|
||||||
|
* nom, en double ou d'un type autre que texte ou nombre, ou
|
||||||
|
* si un sort n'a pas de nom
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Catalog replace(String gameSystemId, List<TemplateField> template, List<SpellData> spells) {
|
||||||
|
GameSystem gs = system(gameSystemId);
|
||||||
|
List<SpellData> incoming = spells == null ? List.of() : spells;
|
||||||
|
if (incoming.size() > MAX_SPELLS) {
|
||||||
|
throw new IllegalArgumentException("Un catalogue ne peut pas dépasser " + MAX_SPELLS + " sorts.");
|
||||||
|
}
|
||||||
|
for (SpellData data : incoming) {
|
||||||
|
if (data == null || isBlank(data.name())) {
|
||||||
|
throw new IllegalArgumentException("Un sort n'a pas de nom.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gs.replaceSpellTemplate(supported(template));
|
||||||
|
gs = gameSystemRepository.save(gs);
|
||||||
|
|
||||||
|
Map<String, Spell> existing = new LinkedHashMap<>();
|
||||||
|
spellRepository.findByGameSystemId(gs.getId()).forEach(s -> existing.put(s.getId(), s));
|
||||||
|
|
||||||
|
List<Spell> saved = new ArrayList<>();
|
||||||
|
Set<String> kept = new HashSet<>();
|
||||||
|
for (int i = 0; i < incoming.size(); i++) {
|
||||||
|
SpellData data = incoming.get(i);
|
||||||
|
// Un identifiant inconnu, d'un autre système ou déjà vu dans l'envoi : nouveau sort.
|
||||||
|
Spell current = data.id() != null && kept.add(data.id()) ? existing.get(data.id()) : null;
|
||||||
|
Spell spell = current != null ? current : Spell.builder().gameSystemId(gs.getId()).build();
|
||||||
|
spell.setName(label(data.name()));
|
||||||
|
spell.setLevel(label(data.level()));
|
||||||
|
spell.setSchool(label(data.school()));
|
||||||
|
spell.setDescription(isBlank(data.description()) ? null : data.description().strip());
|
||||||
|
spell.setValues(cleanValues(data.values()));
|
||||||
|
spell.setOrder(i);
|
||||||
|
saved.add(spellRepository.save(spell));
|
||||||
|
}
|
||||||
|
Set<String> savedIds = new HashSet<>();
|
||||||
|
saved.forEach(s -> savedIds.add(s.getId()));
|
||||||
|
existing.keySet().stream().filter(id -> !savedIds.contains(id)).forEach(spellRepository::deleteById);
|
||||||
|
|
||||||
|
return new Catalog(List.copyOf(gs.getSpellTemplate()), saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le modèle de sort ne porte que du texte et des nombres : une image ou une liste
|
||||||
|
* clé/valeur n'a pas de valeur simple à ranger dans un sort.
|
||||||
|
*/
|
||||||
|
private static List<TemplateField> supported(List<TemplateField> template) {
|
||||||
|
List<TemplateField> fields = template == null ? List.of() : template;
|
||||||
|
for (TemplateField field : fields) {
|
||||||
|
if (field != null && field.getType() != null
|
||||||
|
&& field.getType() != FieldType.TEXT && field.getType() != FieldType.NUMBER) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Un champ de sort est du texte ou un nombre : « " + field.getName() + " » ne l'est pas.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valeurs non vides, telles qu'envoyées. Une valeur dont le champ a quitté le modèle est
|
||||||
|
* gardée : modifier le modèle ne détruit jamais ce qui a été saisi.
|
||||||
|
*/
|
||||||
|
private static Map<String, String> cleanValues(Map<String, String> values) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (values == null) return out;
|
||||||
|
values.forEach((key, value) -> {
|
||||||
|
if (!isBlank(key) && !isBlank(value)) out.put(key.strip(), value.strip());
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GameSystem system(String gameSystemId) {
|
||||||
|
return gameSystemRepository.findById(gameSystemId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Système de jeu inconnu : " + gameSystemId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String label(String value) {
|
||||||
|
if (isBlank(value)) return null;
|
||||||
|
String trimmed = value.strip();
|
||||||
|
return trimmed.length() > MAX_LABEL_CHARS ? trimmed.substring(0, MAX_LABEL_CHARS) : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
+161
@@ -0,0 +1,161 @@
|
|||||||
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer.SpellCandidate;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer.SpellField;
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
import com.loremind.domain.shared.template.TemplateField;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proposition de sorts à partir des règles : l'IA relève les sorts décrits dans UN morceau
|
||||||
|
* de règles, et rien n'est enregistré (l'écran ajoute au catalogue les sorts que le MJ coche).
|
||||||
|
* <p>
|
||||||
|
* Garde-fou : un sort n'est proposé que si son nom ET le passage qu'il cite se retrouvent
|
||||||
|
* dans le texte envoyé (à la casse, aux espaces et à la mise en forme près, comme pour
|
||||||
|
* l'entraînement aux règles). Un sort inventé, ou importé d'un autre jeu, est écarté. La
|
||||||
|
* description et les valeurs, elles, restent à relire.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class SpellProposalService {
|
||||||
|
|
||||||
|
/** Un morceau plus long ferait une réponse trop longue pour être fiable : l'écran découpe avant. */
|
||||||
|
static final int MAX_TEXT_CHARS = 12_000;
|
||||||
|
static final int MAX_SPELLS = 60;
|
||||||
|
static final int MAX_AVOIDED = 150;
|
||||||
|
static final int MAX_LABEL_CHARS = 255;
|
||||||
|
/** Un nom plus court (« Ô », « X ») se retrouverait dans n'importe quel texte. */
|
||||||
|
static final int MIN_NAME_CHARS = 3;
|
||||||
|
|
||||||
|
private static final Pattern NUMBER = Pattern.compile("-?\\d+(?:[.,]\\d+)?");
|
||||||
|
|
||||||
|
/** Un sort proposé, vérifié. {@code excerpt} : passage des règles retrouvé mot pour mot. */
|
||||||
|
public record ProposedSpell(String name, String level, String school, String description,
|
||||||
|
Map<String, String> values, String excerpt) {}
|
||||||
|
|
||||||
|
/** {@code dropped} : sorts écartés parce que leur nom ou leur passage ne figurait pas dans le texte. */
|
||||||
|
public record Proposal(List<ProposedSpell> spells, int dropped) {}
|
||||||
|
|
||||||
|
private final SpellProposer proposer;
|
||||||
|
|
||||||
|
public SpellProposalService(SpellProposer proposer) {
|
||||||
|
this.proposer = proposer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param fields modèle de sort du système (les champs texte et nombre sont remplis)
|
||||||
|
* @param avoid noms déjà dans le catalogue ou déjà proposés
|
||||||
|
* @throws IllegalArgumentException si le texte est vide ou trop long
|
||||||
|
*/
|
||||||
|
public Proposal propose(String systemName, String sectionTitle, String text,
|
||||||
|
List<TemplateField> fields, List<String> avoid) {
|
||||||
|
if (isBlank(text)) {
|
||||||
|
throw new IllegalArgumentException("Aucun texte de règles à lire.");
|
||||||
|
}
|
||||||
|
if (text.length() > MAX_TEXT_CHARS) {
|
||||||
|
throw new IllegalArgumentException("Ce morceau de règles est trop long pour être lu d'une traite.");
|
||||||
|
}
|
||||||
|
List<SpellField> spellFields = spellFields(fields);
|
||||||
|
List<String> avoided = clean(avoid);
|
||||||
|
List<SpellCandidate> candidates = proposer.extract(nz(systemName).strip(), nz(sectionTitle).strip(),
|
||||||
|
text, spellFields, avoided);
|
||||||
|
return validate(candidates, text, spellFields, avoided);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Garde les sorts dont le nom et le passage cité figurent dans le texte, sans doublon. */
|
||||||
|
static Proposal validate(List<SpellCandidate> candidates, String text, List<SpellField> fields,
|
||||||
|
List<String> avoid) {
|
||||||
|
String normalized = RuleTrainingService.normalize(text);
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
for (String name : avoid) seen.add(key(name));
|
||||||
|
|
||||||
|
List<ProposedSpell> out = new ArrayList<>();
|
||||||
|
int dropped = 0;
|
||||||
|
for (SpellCandidate c : candidates == null ? List.<SpellCandidate>of() : candidates) {
|
||||||
|
if (out.size() >= MAX_SPELLS) break;
|
||||||
|
if (c == null || isBlank(c.name()) || isBlank(c.description())) continue;
|
||||||
|
String name = label(c.name());
|
||||||
|
// Déjà connu (catalogue, morceau précédent, même réponse) : ni proposé, ni compté comme écarté.
|
||||||
|
if (seen.contains(key(name))) continue;
|
||||||
|
String normalizedName = RuleTrainingService.normalize(name);
|
||||||
|
if (normalizedName.length() < MIN_NAME_CHARS || !normalized.contains(normalizedName)
|
||||||
|
|| isBlank(c.excerpt()) || !RuleTrainingService.contains(normalized, c.excerpt())) {
|
||||||
|
dropped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(key(name));
|
||||||
|
out.add(new ProposedSpell(name, label(c.level()), label(c.school()), c.description().strip(),
|
||||||
|
values(c.values(), fields), c.excerpt().strip()));
|
||||||
|
}
|
||||||
|
return new Proposal(out, dropped);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valeurs rangées sous le nom exact du champ du modèle. Une clé hors modèle est ignorée ;
|
||||||
|
* un champ « nombre » ne garde qu'un nombre.
|
||||||
|
*/
|
||||||
|
private static Map<String, String> values(Map<String, String> raw, List<SpellField> fields) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (raw == null) return out;
|
||||||
|
for (SpellField field : fields) {
|
||||||
|
raw.entrySet().stream()
|
||||||
|
.filter(e -> e.getKey() != null && key(e.getKey()).equals(key(field.name())))
|
||||||
|
.map(Map.Entry::getValue)
|
||||||
|
.filter(v -> !isBlank(v))
|
||||||
|
.map(String::strip)
|
||||||
|
.filter(v -> !field.number() || NUMBER.matcher(v).matches())
|
||||||
|
.findFirst()
|
||||||
|
.ifPresent(v -> out.put(field.name(), v));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Champs du modèle utilisables par le relevé : nommés, en texte ou en nombre. */
|
||||||
|
private static List<SpellField> spellFields(List<TemplateField> fields) {
|
||||||
|
List<SpellField> out = new ArrayList<>();
|
||||||
|
Set<String> names = new HashSet<>();
|
||||||
|
for (TemplateField field : fields == null ? List.<TemplateField>of() : fields) {
|
||||||
|
if (field == null || isBlank(field.getName())) continue;
|
||||||
|
if (field.getType() != null && field.getType() != FieldType.TEXT && field.getType() != FieldType.NUMBER) continue;
|
||||||
|
String name = field.getName().strip();
|
||||||
|
if (names.add(key(name))) out.add(new SpellField(name, field.getType() == FieldType.NUMBER));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> clean(List<String> values) {
|
||||||
|
List<String> out = new ArrayList<>();
|
||||||
|
for (String value : values == null ? List.<String>of() : values) {
|
||||||
|
if (out.size() >= MAX_AVOIDED) break;
|
||||||
|
if (!isBlank(value)) out.add(value.strip());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String key(String name) {
|
||||||
|
return name.strip().toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String label(String value) {
|
||||||
|
if (isBlank(value)) return "";
|
||||||
|
String trimmed = value.strip();
|
||||||
|
return trimmed.length() > MAX_LABEL_CHARS ? trimmed.substring(0, MAX_LABEL_CHARS) : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-1
@@ -8,7 +8,28 @@ import java.util.List;
|
|||||||
* PROPOSITION non persistée : l'UI laisse l'utilisateur réviser/éditer l'arbre
|
* PROPOSITION non persistée : l'UI laisse l'utilisateur réviser/éditer l'arbre
|
||||||
* avant la création effective des arcs/chapitres/scènes. Records purs (domaine).
|
* avant la création effective des arcs/chapitres/scènes. Records purs (domaine).
|
||||||
*/
|
*/
|
||||||
public record CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs) {
|
public record CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs, Outcome outcome) {
|
||||||
|
|
||||||
|
/** Proposition sans compte rendu d'import (arbre révisé renvoyé par l'UI, découpage par l'IA). */
|
||||||
|
public CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs) {
|
||||||
|
this(arcs, npcs, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compte rendu d'un import découpé d'après la structure du livre, affiché à la revue.
|
||||||
|
* Absent (null) quand c'est l'IA qui a reconstruit l'arborescence.
|
||||||
|
*
|
||||||
|
* @param splitMethod "bookmarks" (table des matières du PDF) ou "headings" (titres repérés)
|
||||||
|
* @param sourceLanguage langue du livre ("fr", "en"), null si inconnue
|
||||||
|
* @param untranslated textes restés dans la langue du livre faute de traduction
|
||||||
|
* @param skippedAids lots de scènes pour lesquels l'IA n'a pas rendu ses aides
|
||||||
|
* @param aiInterrupted vrai si les passes de l'IA n'ont pas abouti : la campagne est livrée
|
||||||
|
* avec le seul texte du livre (ni synopsis rédigés, ni PNJ, ni traduction)
|
||||||
|
*/
|
||||||
|
public record Outcome(
|
||||||
|
String splitMethod, String sourceLanguage, int untranslated, int skippedAids,
|
||||||
|
boolean aiInterrupted) {
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@code type} = "LINEAR" ou "HUB" (mappé sur {@link ArcType} à l'apply).
|
* {@code type} = "LINEAR" ou "HUB" (mappé sur {@link ArcType} à l'apply).
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine (Aggregate Root) représentant une Quête.
|
* Entité de domaine (Aggregate Root) représentant une Quête.
|
||||||
@@ -62,6 +64,13 @@ public class Quest {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@code ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine représentant un Arc narratif.
|
* Entité de domaine représentant un Arc narratif.
|
||||||
@@ -57,6 +59,13 @@ public class Arc {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@code ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine représentant un Chapter.
|
* Entité de domaine représentant un Chapter.
|
||||||
@@ -29,6 +31,14 @@ public class Chapter {
|
|||||||
private String playerObjectives; // Objectifs des joueurs dans ce chapitre
|
private String playerObjectives; // Objectifs des joueurs dans ce chapitre
|
||||||
private String narrativeStakes; // Enjeux narratifs dramatiques
|
private String narrativeStakes; // Enjeux narratifs dramatiques
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Méthode guidée suivie par ce chapitre (« five-room », « investigation »…), ou {@code null}.
|
||||||
|
* Identifiant opaque pour le Core : les méthodes sont décrites côté front. Posée par
|
||||||
|
* l'assistant ou par {@code ChapterService.setGuidedMethod} ; une mise à jour ordinaire
|
||||||
|
* du chapitre ne la touche pas.
|
||||||
|
*/
|
||||||
|
private String guidedMethod;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IDs des pages du Lore associées à ce chapitre (weak cross-context references).
|
* IDs des pages du Lore associées à ce chapitre (weak cross-context references).
|
||||||
* Permet au MJ de lier des PNJ / lieux / éléments du Lore qui apparaissent dans ce chapitre.
|
* Permet au MJ de lier des PNJ / lieux / éléments du Lore qui apparaissent dans ce chapitre.
|
||||||
@@ -42,6 +52,13 @@ public class Chapter {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@code ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.structure;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement d'une illustration dans le livret PDF, choisi par l'auteur pour une image DANS une
|
||||||
|
* galerie donnée (celle d'un arc, d'un chapitre ou d'une quête) : la même image peut être placée
|
||||||
|
* autrement ailleurs. Les galeries portent une carte « id d'image → nom du placement » ; une
|
||||||
|
* image absente de la carte est en {@link #AUTO}.
|
||||||
|
* <p>
|
||||||
|
* Seul le thème « Parchemin » du livret en tient compte ; le thème classique l'ignore.
|
||||||
|
*/
|
||||||
|
public enum ImagePlacement {
|
||||||
|
/** Règles du thème : la première image ouvre l'arc ou le chapitre, les autres vont dans le texte. */
|
||||||
|
AUTO,
|
||||||
|
/** Image encadrée dans le texte, jamais en ouverture. */
|
||||||
|
IN_TEXT,
|
||||||
|
/** Bandeau pleine largeur en ouverture. */
|
||||||
|
BANNER,
|
||||||
|
/** Planche pleine page, à fond perdu, en ouverture (l'image est recadrée au format de la page). */
|
||||||
|
FULL_PAGE,
|
||||||
|
/** Fondue dans le bas de la dernière page, si la place s'y prête ; sinon image encadrée en fin de texte. */
|
||||||
|
FADE_BOTTOM,
|
||||||
|
/** Bandeau d'ouverture à fond perdu en haut, bord inférieur fondu dans la page. */
|
||||||
|
FADE_TOP;
|
||||||
|
|
||||||
|
/** Placement nommé ; {@link #AUTO} pour une valeur absente ou inconnue (bundle plus récent, saisie libre). */
|
||||||
|
public static ImagePlacement of(String name) {
|
||||||
|
if (name == null || name.isBlank()) return AUTO;
|
||||||
|
try {
|
||||||
|
return valueOf(name.trim().toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return AUTO;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Placement d'une image d'après la carte de sa galerie ({@link #AUTO} si elle n'y figure pas). */
|
||||||
|
public static ImagePlacement of(Map<String, String> placements, String imageId) {
|
||||||
|
return placements == null || imageId == null ? AUTO : of(placements.get(imageId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carte nettoyée, telle qu'on la stocke : seulement des images de la galerie, des placements
|
||||||
|
* connus, et rien pour {@link #AUTO} (c'est l'absence d'entrée). Ordre de la galerie.
|
||||||
|
*/
|
||||||
|
public static Map<String, String> sanitize(Map<String, String> placements, Collection<String> imageIds) {
|
||||||
|
Map<String, String> clean = new LinkedHashMap<>();
|
||||||
|
if (placements == null || imageIds == null) return clean;
|
||||||
|
for (String id : imageIds) {
|
||||||
|
ImagePlacement placement = of(placements, id);
|
||||||
|
if (placement != AUTO) clean.put(id, placement.name());
|
||||||
|
}
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import lombok.Data;
|
|||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité de domaine représentant une Scene.
|
* Entité de domaine représentant une Scene.
|
||||||
@@ -19,6 +21,13 @@ public class Scene {
|
|||||||
private String name;
|
private String name;
|
||||||
private String description; // = Description courte dans l'UI
|
private String description; // = Description courte dans l'UI
|
||||||
private String chapterId; // Référence vers le Chapter parent
|
private String chapterId; // Référence vers le Chapter parent
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rôle de la scène dans la méthode guidée du chapitre (« room3 », « conclusion »…), ou
|
||||||
|
* {@code null}. Un rôle est tenu par une seule scène du chapitre. Posé par l'assistant ou
|
||||||
|
* par {@code SceneService.setGuidedRole} ; une mise à jour ordinaire ne le touche pas.
|
||||||
|
*/
|
||||||
|
private String guidedRole;
|
||||||
private int order; // Ordre de la scène dans le chapitre
|
private int order; // Ordre de la scène dans le chapitre
|
||||||
|
|
||||||
/** Cle d'icone choisie par l'utilisateur (cf. CAMPAIGN_ICON_OPTIONS cote front). */
|
/** Cle d'icone choisie par l'utilisateur (cf. CAMPAIGN_ICON_OPTIONS cote front). */
|
||||||
@@ -74,6 +83,13 @@ public class Scene {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement voulu dans le livret PDF pour certaines de ces illustrations : id d'image →
|
||||||
|
* nom d'un {@link ImagePlacement}. Une image absente de la carte suit les règles par défaut.
|
||||||
|
*/
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* "Battlemaps" de la scene destinees a l'export Foundry : liste de paires
|
* "Battlemaps" de la scene destinees a l'export Foundry : liste de paires
|
||||||
* { media + sidecar } etiquetees ({@link SceneBattlemap}). Plusieurs cartes =
|
* { media + sidecar } etiquetees ({@link SceneBattlemap}). Plusieurs cartes =
|
||||||
|
|||||||
@@ -68,6 +68,13 @@ public class GameSystem {
|
|||||||
*/
|
*/
|
||||||
private String foundryActorType;
|
private String foundryActorType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Modèle de sort : champs propres au système portés par chaque {@link Spell} du
|
||||||
|
* catalogue (portée, durée, coût…), en texte ou en nombre. Géré avec le catalogue
|
||||||
|
* (cf. SpellCatalogService), pas avec les modèles de fiche.
|
||||||
|
*/
|
||||||
|
private List<TemplateField> spellTemplate;
|
||||||
|
|
||||||
/** Auteur déclaré — futur marketplace. Nullable. */
|
/** Auteur déclaré — futur marketplace. Nullable. */
|
||||||
private String author;
|
private String author;
|
||||||
|
|
||||||
@@ -120,6 +127,16 @@ public class GameSystem {
|
|||||||
enemyTemplate = validateAndCopy(fields);
|
enemyTemplate = validateAndCopy(fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void replaceSpellTemplate(List<TemplateField> fields) {
|
||||||
|
spellTemplate = validateAndCopy(fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Jamais null : un système sans modèle de sort a une liste vide. */
|
||||||
|
public List<TemplateField> getSpellTemplate() {
|
||||||
|
if (spellTemplate == null) spellTemplate = new ArrayList<>();
|
||||||
|
return spellTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Helpers privés ----------------------------------------------------
|
// --- Helpers privés ----------------------------------------------------
|
||||||
|
|
||||||
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
private static List<TemplateField> appendField(List<TemplateField> current, TemplateField field) {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Une situation d'entraînement aux règles et son corrigé.
|
||||||
|
* <p>
|
||||||
|
* {@code excerpt} est un passage des règles du système, retrouvé mot pour mot dans la
|
||||||
|
* section {@code section} ; {@code ruling} est la lecture qu'en fait l'IA. {@code sceneId}
|
||||||
|
* et {@code sceneName} désignent la scène qui sert de décor ({@code null} et vide si la
|
||||||
|
* situation n'est rattachée à aucune scène).
|
||||||
|
*/
|
||||||
|
public record RuleDrill(String sceneId, String sceneName, String situation,
|
||||||
|
String section, String excerpt, String ruling) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/** Comparaison de la décision écrite par le MJ avec les règles : un verdict et un retour court. */
|
||||||
|
public record RuleDrillReview(Verdict verdict, String feedback) {
|
||||||
|
|
||||||
|
public enum Verdict {
|
||||||
|
/** La décision applique la règle. */
|
||||||
|
RIGHT,
|
||||||
|
/** Elle va dans le bon sens mais oublie ou déforme un point. */
|
||||||
|
PARTIAL,
|
||||||
|
/** Elle applique autre chose. */
|
||||||
|
OFF;
|
||||||
|
|
||||||
|
/** Nom échangé avec le front et le Brain ({@code right}, {@code partial}, {@code off}). */
|
||||||
|
public String wireName() {
|
||||||
|
return name().toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<Verdict> fromWireName(String value) {
|
||||||
|
if (value == null) return Optional.empty();
|
||||||
|
String wanted = value.trim().toLowerCase(Locale.ROOT);
|
||||||
|
for (Verdict verdict : values()) {
|
||||||
|
if (verdict.wireName().equals(wanted)) return Optional.of(verdict);
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.loremind.domain.gamesystemcontext;
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,10 +21,27 @@ public record RulesImportResult(
|
|||||||
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
|
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
|
||||||
Map<String, Map<String, String>> sectionsByLanguage,
|
Map<String, Map<String, String>> sectionsByLanguage,
|
||||||
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
|
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
|
||||||
String sourceLanguage) {
|
String sourceLanguage,
|
||||||
|
/**
|
||||||
|
* Titres (d'origine) des sections que la traduction n'a pas pu traiter : elles figurent
|
||||||
|
* dans la version traduite avec leur titre et leur texte d'origine.
|
||||||
|
*/
|
||||||
|
List<String> untranslatedTitles,
|
||||||
|
/**
|
||||||
|
* Comment le livre a été découpé en sections : « bookmarks » (signets du PDF),
|
||||||
|
* « headings » (titres repérés à leur taille) — les deux sans IA — ou « ai ».
|
||||||
|
* {@code null} quand le Brain ne le dit pas.
|
||||||
|
*/
|
||||||
|
String splitMethod) {
|
||||||
|
|
||||||
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
|
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
|
||||||
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
|
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
|
||||||
this(sections, pageCount, ocrPageCount, Map.of(), null);
|
this(sections, pageCount, ocrPageCount, Map.of(), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Résultat dont toutes les sections fournies sont traduites. */
|
||||||
|
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount,
|
||||||
|
Map<String, Map<String, String>> sectionsByLanguage, String sourceLanguage) {
|
||||||
|
this(sections, pageCount, ocrPageCount, sectionsByLanguage, sourceLanguage, List.of(), null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.shared.template.FieldType;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Champ proposé pour un modèle de fiche, tiré des règles du système.
|
||||||
|
* <p>
|
||||||
|
* C'est une PROPOSITION : rien n'est enregistré. Le MJ choisit les champs à ajouter
|
||||||
|
* à son modèle, puis enregistre le système comme d'habitude.
|
||||||
|
*
|
||||||
|
* @param name nom du champ, dans les termes des règles
|
||||||
|
* @param type {@code TEXT}, {@code NUMBER} ou {@code KEY_VALUE_LIST}
|
||||||
|
* @param labels lignes d'une liste de valeurs (vide pour les autres types)
|
||||||
|
* @param source titre de la section de règles d'où vient le champ, ou chaîne vide
|
||||||
|
*/
|
||||||
|
public record SheetFieldProposal(String name, FieldType type, List<String> labels, String source) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fiche dont on propose le modèle à partir des règles : PJ, PNJ ou ennemi.
|
||||||
|
* <p>
|
||||||
|
* Chaque fiche porte ses alias de sections de règles, par ordre de priorité : les
|
||||||
|
* sections du premier groupe sont envoyées à l'IA d'abord, puis celles des suivants
|
||||||
|
* tant que le budget de taille le permet. Comparaison par {@code contains} sur le
|
||||||
|
* titre en minuscules, comme {@link GenerationIntent}.
|
||||||
|
*/
|
||||||
|
public enum SheetKind {
|
||||||
|
|
||||||
|
CHARACTER("character", List.of(
|
||||||
|
Set.of("personnage", "character", "caractéristique", "caracteristique",
|
||||||
|
"attribut", "attribute", "abilit", "stats"),
|
||||||
|
Set.of("compétence", "competence", "skill", "classe", "class",
|
||||||
|
"progression", "niveau", "level"),
|
||||||
|
Set.of("combat", "équipement", "equipement", "equipment", "magie", "magic", "sort", "spell"))),
|
||||||
|
|
||||||
|
NPC("npc", List.of(
|
||||||
|
Set.of("pnj", "npc", "non-joueur", "non joueur", "non-player"),
|
||||||
|
Set.of("personnage", "character", "caractéristique", "caracteristique",
|
||||||
|
"attribut", "attribute", "abilit", "stats"),
|
||||||
|
Set.of("compétence", "competence", "skill", "combat", "maître", "maitre", "game master"))),
|
||||||
|
|
||||||
|
ENEMY("enemy", List.of(
|
||||||
|
Set.of("monstre", "monster", "créature", "creature", "ennemi", "enemy", "enemies",
|
||||||
|
"adversaire", "adversar", "bestiaire", "bestiary"),
|
||||||
|
Set.of("combat"),
|
||||||
|
Set.of("caractéristique", "caracteristique", "attribut", "attribute", "abilit", "stats",
|
||||||
|
"état", "etat", "condition")));
|
||||||
|
|
||||||
|
private final String wireName;
|
||||||
|
private final List<Set<String>> sectionAliases;
|
||||||
|
|
||||||
|
SheetKind(String wireName, List<Set<String>> sectionAliases) {
|
||||||
|
this.wireName = wireName;
|
||||||
|
this.sectionAliases = sectionAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nom échangé avec le front et le Brain ({@code character}, {@code npc}, {@code enemy}). */
|
||||||
|
public String wireName() {
|
||||||
|
return wireName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alias de titres de sections, du groupe le plus utile au moins utile. */
|
||||||
|
public List<Set<String>> sectionAliases() {
|
||||||
|
return sectionAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<SheetKind> fromWireName(String value) {
|
||||||
|
if (value == null) return Optional.empty();
|
||||||
|
String wanted = value.trim().toLowerCase(Locale.ROOT);
|
||||||
|
for (SheetKind kind : values()) {
|
||||||
|
if (kind.wireName.equals(wanted)) return Optional.of(kind);
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort du catalogue d'un système de jeu.
|
||||||
|
* <p>
|
||||||
|
* Même principe que les fiches du bestiaire : des champs communs à tous les systèmes
|
||||||
|
* (nom, niveau, école, description) + les valeurs des champs propres au système, dont la
|
||||||
|
* liste est {@link GameSystem#getSpellTemplate()} (portée, durée, coût…). Les règles de
|
||||||
|
* magie, elles, restent dans les sections de règles du système.
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class Spell {
|
||||||
|
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
/** Système de jeu auquel appartient ce sort. */
|
||||||
|
private String gameSystemId;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** Niveau, rang ou cercle — texte libre (« 3 », « Tour de magie », « Rang II »). Nullable. */
|
||||||
|
private String level;
|
||||||
|
|
||||||
|
/** École, liste ou tradition, pour classer (« Évocation », « Druide »). Nullable. */
|
||||||
|
private String school;
|
||||||
|
|
||||||
|
/** Ce que fait le sort. Nullable. */
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
/** Valeurs des champs du modèle de sort : nom du champ → valeur. Jamais null après construction. */
|
||||||
|
private Map<String, String> values;
|
||||||
|
|
||||||
|
/** Rang dans le catalogue. */
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
public Map<String, String> getValues() {
|
||||||
|
if (values == null) values = new HashMap<>();
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : l'IA qui prépare l'entraînement aux règles.
|
||||||
|
* <p>
|
||||||
|
* Les réponses sont des candidats bruts : la vérification des extraits contre les règles
|
||||||
|
* est faite par le service appelant, jamais par l'adapter.
|
||||||
|
*
|
||||||
|
* @throws com.loremind.domain.gamesystemcontext.ports.exceptions.RuleTrainingException
|
||||||
|
* si l'IA est injoignable ou répond de façon inexploitable
|
||||||
|
*/
|
||||||
|
public interface RuleTrainingCoach {
|
||||||
|
|
||||||
|
/** Une scène du scénario, résumée : le décor d'une situation. */
|
||||||
|
record SceneBrief(String name, String kind, String text) {}
|
||||||
|
|
||||||
|
/** Situation proposée. {@code scene} : rang de la scène dans la liste envoyée (à partir de 1), 0 si aucune. */
|
||||||
|
record DrillCandidate(int scene, String situation, String section, String excerpt, String ruling) {}
|
||||||
|
|
||||||
|
/** Prépare {@code count} situations, corrigé compris, à partir des sections de règles fournies. */
|
||||||
|
List<DrillCandidate> prepare(String systemName, Map<String, String> sections,
|
||||||
|
List<SceneBrief> scenes, int count, List<String> avoid);
|
||||||
|
|
||||||
|
/** Compare la décision du MJ aux règles de la section et au corrigé de la situation. */
|
||||||
|
RuleDrillReview review(String systemName, String sectionTitle, String sectionText,
|
||||||
|
String situation, String excerpt, String ruling, String answer);
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : sorts connus d'une fiche (PJ, PNJ ou ennemi), comme liens vers des sorts
|
||||||
|
* du catalogue du système.
|
||||||
|
*/
|
||||||
|
public interface SheetSpellRepository {
|
||||||
|
|
||||||
|
/** Identifiants des sorts connus de la fiche, dans l'ordre choisi. */
|
||||||
|
List<String> findSpellIds(SheetKind kind, String ownerId);
|
||||||
|
|
||||||
|
/** Remplace les sorts connus de la fiche par cette liste, dans cet ordre. */
|
||||||
|
void replace(SheetKind kind, String ownerId, List<String> spellIds);
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SheetProposalException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : propose les champs d'une fiche (PJ, PNJ, ennemi) à partir de
|
||||||
|
* sections de règles. L'implémentation délègue à l'IA ; le domaine ne connaît ni
|
||||||
|
* HTTP ni le fournisseur.
|
||||||
|
*/
|
||||||
|
public interface SheetTemplateAdvisor {
|
||||||
|
|
||||||
|
/** Champ tel que renvoyé par l'IA, avant tri métier (type en texte libre). */
|
||||||
|
record Candidate(String name, String type, List<String> labels, String source) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param kind fiche concernée
|
||||||
|
* @param systemName nom du système de jeu (peut être vide)
|
||||||
|
* @param sections sections de règles utiles, {titre → contenu}, ordre préservé
|
||||||
|
* @param existingFieldNames champs déjà présents dans le modèle
|
||||||
|
* @return les champs proposés, non triés ; liste vide si les règles ne décrivent pas la fiche
|
||||||
|
* @throws SheetProposalException si l'IA est indisponible ou répond de façon inexploitable
|
||||||
|
*/
|
||||||
|
List<Candidate> propose(SheetKind kind, String systemName,
|
||||||
|
Map<String, String> sections, List<String> existingFieldNames);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie : relève les sorts décrits dans un morceau de règles (IA).
|
||||||
|
* <p>
|
||||||
|
* Le relevé n'est qu'une proposition : l'appelant vérifie chaque sort contre le texte
|
||||||
|
* envoyé avant de le montrer.
|
||||||
|
*/
|
||||||
|
public interface SpellProposer {
|
||||||
|
|
||||||
|
/** Un champ du modèle de sort du système. {@code number} : le champ attend un nombre. */
|
||||||
|
record SpellField(String name, boolean number) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort relevé, non vérifié. {@code excerpt} : passage du texte censé venir mot pour
|
||||||
|
* mot de la description du sort.
|
||||||
|
*/
|
||||||
|
record SpellCandidate(String name, String level, String school, String description,
|
||||||
|
Map<String, String> values, String excerpt) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param avoid noms de sorts déjà connus, à ne pas relever de nouveau
|
||||||
|
* @throws com.loremind.domain.gamesystemcontext.ports.exceptions.SpellProposalException
|
||||||
|
* si l'IA est indisponible ou si sa réponse est inexploitable
|
||||||
|
*/
|
||||||
|
List<SpellCandidate> extract(String systemName, String sectionTitle, String text,
|
||||||
|
List<SpellField> fields, List<String> avoid);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie pour la persistance du catalogue de sorts d'un système de jeu.
|
||||||
|
*/
|
||||||
|
public interface SpellRepository {
|
||||||
|
|
||||||
|
Spell save(Spell spell);
|
||||||
|
|
||||||
|
/** Sorts d'un système, dans l'ordre du catalogue. */
|
||||||
|
List<Spell> findByGameSystemId(String gameSystemId);
|
||||||
|
|
||||||
|
void deleteById(String id);
|
||||||
|
|
||||||
|
/** Parmi ces identifiants, ceux qui désignent un sort existant. */
|
||||||
|
List<String> existingIds(List<String> ids);
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports.exceptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erreur de domaine : l'entraînement aux règles n'a pas pu être préparé ou corrigé (Brain
|
||||||
|
* injoignable, fournisseur IA en erreur, réponse inexploitable). Les couches supérieures
|
||||||
|
* la traduisent en réponse HTTP sans connaître l'adapter concret.
|
||||||
|
*/
|
||||||
|
public class RuleTrainingException extends RuntimeException {
|
||||||
|
|
||||||
|
public RuleTrainingException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RuleTrainingException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports.exceptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erreur de domaine : la proposition d'un modèle de fiche a échoué (Brain
|
||||||
|
* injoignable, fournisseur IA en erreur, réponse inexploitable). Les couches
|
||||||
|
* supérieures la traduisent en réponse HTTP sans connaître l'adapter concret.
|
||||||
|
*/
|
||||||
|
public class SheetProposalException extends RuntimeException {
|
||||||
|
|
||||||
|
public SheetProposalException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SheetProposalException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.loremind.domain.gamesystemcontext.ports.exceptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erreur de domaine : le relevé des sorts dans les règles n'a pas pu se faire (Brain
|
||||||
|
* injoignable, fournisseur IA en erreur, réponse inexploitable). Les couches supérieures
|
||||||
|
* la traduisent en réponse HTTP sans connaître l'adapter concret.
|
||||||
|
*/
|
||||||
|
public class SpellProposalException extends RuntimeException {
|
||||||
|
|
||||||
|
public SpellProposalException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SpellProposalException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,8 +69,10 @@ public class BrainAiChatClient implements AiChatProvider {
|
|||||||
try {
|
try {
|
||||||
// blockLast() : transforme le flux réactif en appel bloquant conforme
|
// blockLast() : transforme le flux réactif en appel bloquant conforme
|
||||||
// au contrat synchrone du port. L'appelant choisit le thread.
|
// au contrat synchrone du port. L'appelant choisit le thread.
|
||||||
|
// Délai entre deux évènements : un modèle à raisonnement réfléchit parfois
|
||||||
|
// plus de 100 s avant le premier mot de sa réponse.
|
||||||
flux
|
flux
|
||||||
.timeout(Duration.ofSeconds(120))
|
.timeout(Duration.ofSeconds(300))
|
||||||
.doOnNext(sse -> handleEvent(sse, callbacks))
|
.doOnNext(sse -> handleEvent(sse, callbacks))
|
||||||
.blockLast();
|
.blockLast();
|
||||||
callbacks.onComplete().run();
|
callbacks.onComplete().run();
|
||||||
|
|||||||
@@ -7,11 +7,14 @@ import com.loremind.domain.campaigncontext.generation.CampaignImportProposal;
|
|||||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ArcProposal;
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ArcProposal;
|
||||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ChapterProposal;
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.ChapterProposal;
|
||||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.NpcProposal;
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.NpcProposal;
|
||||||
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.Outcome;
|
||||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.RoomProposal;
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.RoomProposal;
|
||||||
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.SceneProposal;
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProposal.SceneProposal;
|
||||||
import com.loremind.domain.campaigncontext.ports.exceptions.CampaignImportException;
|
import com.loremind.domain.campaigncontext.ports.exceptions.CampaignImportException;
|
||||||
import com.loremind.domain.campaigncontext.ports.CampaignPdfImporter;
|
import com.loremind.domain.campaigncontext.ports.CampaignPdfImporter;
|
||||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.core.ParameterizedTypeReference;
|
import org.springframework.core.ParameterizedTypeReference;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
@@ -36,10 +39,14 @@ import java.util.function.Consumer;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainCampaignImportClient implements CampaignPdfImporter {
|
public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(BrainCampaignImportClient.class);
|
||||||
|
|
||||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
/** Champ JSON répété du proposal d'arbre (arc/chapitre/scène/salle/PNJ). */
|
/** Champ JSON répété du proposal d'arbre (arc/chapitre/scène/salle/PNJ). */
|
||||||
private static final String FIELD_DESCRIPTION = "description";
|
private static final String FIELD_DESCRIPTION = "description";
|
||||||
|
/** Champ JSON : façon dont le livre a été découpé (table des matières, titres). */
|
||||||
|
private static final String FIELD_SPLIT_METHOD = "split_method";
|
||||||
|
|
||||||
private final WebClient webClient;
|
private final WebClient webClient;
|
||||||
private final BrainSseImportSupport sse;
|
private final BrainSseImportSupport sse;
|
||||||
@@ -93,12 +100,28 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
int[] pageCount = {0};
|
int[] pageCount = {0};
|
||||||
int[] ocrPageCount = {0};
|
int[] ocrPageCount = {0};
|
||||||
boolean[] terminated = {false};
|
boolean[] terminated = {false};
|
||||||
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onError);
|
// Campagne découpée d'après la structure du livre, reçue AVANT les passes de l'IA
|
||||||
|
// (évènement `extracted`) : elle porte déjà le texte du livre. Si la suite échoue
|
||||||
|
// (aides ou traduction en panne, flux coupé), on la livre telle quelle plutôt que de
|
||||||
|
// perdre tout l'import : synopsis, fiches de PNJ et traduction sont un plus.
|
||||||
|
CampaignImportProposal[] extracted = {null};
|
||||||
|
Consumer<Throwable> onFailure = error -> {
|
||||||
|
CampaignImportProposal kept = extracted[0];
|
||||||
|
if (kept == null) {
|
||||||
|
onError.accept(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
extracted[0] = null;
|
||||||
|
log.warn("Import de campagne : passes de l'IA interrompues ({}) — campagne livrée avec "
|
||||||
|
+ "le texte du livre.", error.getMessage());
|
||||||
|
onDone.accept(kept);
|
||||||
|
};
|
||||||
|
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onFailure);
|
||||||
|
|
||||||
sse.runStream(
|
sse.runStream(
|
||||||
flux, importTimeoutSeconds, terminated,
|
flux, importTimeoutSeconds, terminated,
|
||||||
event -> handleEvent(event, pageCount, ocrPageCount, terminated, callbacks),
|
event -> handleEvent(event, pageCount, ocrPageCount, terminated, extracted, callbacks),
|
||||||
onError, CampaignImportException::new);
|
onFailure, CampaignImportException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleEvent(
|
private void handleEvent(
|
||||||
@@ -106,6 +129,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
int[] pageCount,
|
int[] pageCount,
|
||||||
int[] ocrPageCount,
|
int[] ocrPageCount,
|
||||||
boolean[] terminated,
|
boolean[] terminated,
|
||||||
|
CampaignImportProposal[] extracted,
|
||||||
ImportCallbacks callbacks) {
|
ImportCallbacks callbacks) {
|
||||||
|
|
||||||
String event = ssEvent.event();
|
String event = ssEvent.event();
|
||||||
@@ -156,13 +180,35 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
|||||||
node.path("chapter_count").asInt(),
|
node.path("chapter_count").asInt(),
|
||||||
node.path("scene_count").asInt(),
|
node.path("scene_count").asInt(),
|
||||||
node.path("npc_count").asInt()));
|
node.path("npc_count").asInt()));
|
||||||
|
} else if ("extracted".equals(event)) {
|
||||||
|
List<ArcProposal> arcs = toArcs(node.path("arcs"));
|
||||||
|
if (!arcs.isEmpty()) {
|
||||||
|
// Livrée seulement si la suite échoue : les passes de l'IA n'auront pas abouti.
|
||||||
|
extracted[0] = new CampaignImportProposal(arcs, toNpcs(node.path("npcs")),
|
||||||
|
new Outcome(node.path(FIELD_SPLIT_METHOD).asText(null), null, 0, 0, true));
|
||||||
|
}
|
||||||
} else if ("done".equals(event)) {
|
} else if ("done".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
|
extracted[0] = null;
|
||||||
callbacks.onDone().accept(new CampaignImportProposal(
|
callbacks.onDone().accept(new CampaignImportProposal(
|
||||||
toArcs(node.path("arcs")), toNpcs(node.path("npcs"))));
|
toArcs(node.path("arcs")), toNpcs(node.path("npcs")), toOutcome(node)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Compte rendu de l'import par la structure du livre ; null si l'IA a fait le découpage. */
|
||||||
|
private static Outcome toOutcome(JsonNode done) {
|
||||||
|
String method = done.path(FIELD_SPLIT_METHOD).asText(null);
|
||||||
|
if (method == null || method.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new Outcome(
|
||||||
|
method,
|
||||||
|
done.path("source_language").asText(null),
|
||||||
|
done.path("untranslated").asInt(),
|
||||||
|
done.path("skipped").asInt(),
|
||||||
|
false);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Parsing de l'arbre --------------------------------------------------
|
// --- Parsing de l'arbre --------------------------------------------------
|
||||||
|
|
||||||
private List<ArcProposal> toArcs(JsonNode arcsNode) {
|
private List<ArcProposal> toArcs(JsonNode arcsNode) {
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RuleDrillReview.Verdict;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.RuleTrainingCoach;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.RuleTrainingException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : entraînement aux règles via le Brain ({@code POST /generate/rule-drills}
|
||||||
|
* et {@code POST /generate/rule-drill-review}, one-shot). La langue de l'interface est relayée
|
||||||
|
* par l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainRuleTrainingClient implements RuleTrainingCoach {
|
||||||
|
|
||||||
|
private static final String DRILLS_PATH = "/generate/rule-drills";
|
||||||
|
private static final String REVIEW_PATH = "/generate/rule-drill-review";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainRuleTrainingClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DrillCandidate> prepare(String systemName, Map<String, String> sections,
|
||||||
|
List<SceneBrief> scenes, int count, List<String> avoid) {
|
||||||
|
List<Map<String, String>> sceneDtos = new ArrayList<>();
|
||||||
|
for (SceneBrief scene : scenes == null ? List.<SceneBrief>of() : scenes) {
|
||||||
|
Map<String, String> dto = new LinkedHashMap<>();
|
||||||
|
dto.put("name", nz(scene.name()));
|
||||||
|
dto.put("kind", nz(scene.kind()));
|
||||||
|
dto.put("text", nz(scene.text()));
|
||||||
|
sceneDtos.add(dto);
|
||||||
|
}
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("system_name", nz(systemName));
|
||||||
|
req.put("sections", sections == null ? Map.of() : sections);
|
||||||
|
req.put("scenes", sceneDtos);
|
||||||
|
req.put("count", count);
|
||||||
|
req.put("avoid", avoid == null ? List.of() : avoid);
|
||||||
|
return parseDrills(call(DRILLS_PATH, req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public RuleDrillReview review(String systemName, String sectionTitle, String sectionText,
|
||||||
|
String situation, String excerpt, String ruling, String answer) {
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("system_name", nz(systemName));
|
||||||
|
req.put("section_title", nz(sectionTitle));
|
||||||
|
req.put("section_text", nz(sectionText));
|
||||||
|
req.put("situation", nz(situation));
|
||||||
|
req.put("excerpt", nz(excerpt));
|
||||||
|
req.put("ruling", nz(ruling));
|
||||||
|
req.put("answer", nz(answer));
|
||||||
|
return parseReview(call(REVIEW_PATH, req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> call(String path, Map<String, Object> req) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + path, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new RuleTrainingException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new RuleTrainingException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuleTrainingException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new RuleTrainingException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lecture tolérante : une entrée mal formée est ignorée, la vérification est faite en amont. */
|
||||||
|
static List<DrillCandidate> parseDrills(Map<String, Object> resp) {
|
||||||
|
List<DrillCandidate> out = new ArrayList<>();
|
||||||
|
if (!(resp.get("drills") instanceof List<?> drills)) return out;
|
||||||
|
for (Object entry : drills) {
|
||||||
|
if (!(entry instanceof Map<?, ?> drill)) continue;
|
||||||
|
out.add(new DrillCandidate(
|
||||||
|
drill.get("scene") instanceof Number n ? n.intValue() : 0,
|
||||||
|
text(drill.get("situation")),
|
||||||
|
text(drill.get("section")),
|
||||||
|
text(drill.get("excerpt")),
|
||||||
|
text(drill.get("ruling"))));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static RuleDrillReview parseReview(Map<String, Object> resp) {
|
||||||
|
Verdict verdict = Verdict.fromWireName(text(resp.get("verdict")))
|
||||||
|
.orElseThrow(() -> new RuleTrainingException("Le Brain a renvoyé une comparaison inexploitable."));
|
||||||
|
String feedback = text(resp.get("feedback")).strip();
|
||||||
|
if (feedback.isEmpty()) {
|
||||||
|
throw new RuleTrainingException("Le Brain a renvoyé une comparaison inexploitable.");
|
||||||
|
}
|
||||||
|
return new RuleDrillReview(verdict, feedback);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(Object value) {
|
||||||
|
return value == null ? "" : value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ import com.loremind.domain.gamesystemcontext.RulesImportResult;
|
|||||||
import com.loremind.domain.gamesystemcontext.ports.exceptions.RulesImportException;
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.RulesImportException;
|
||||||
import com.loremind.domain.gamesystemcontext.ports.RulesPdfImporter;
|
import com.loremind.domain.gamesystemcontext.ports.RulesPdfImporter;
|
||||||
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
import com.loremind.infrastructure.web.config.UserLanguageHolder;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.core.ParameterizedTypeReference;
|
import org.springframework.core.ParameterizedTypeReference;
|
||||||
@@ -47,6 +49,8 @@ import java.util.function.Consumer;
|
|||||||
@Component
|
@Component
|
||||||
public class BrainRulesImportClient implements RulesPdfImporter {
|
public class BrainRulesImportClient implements RulesPdfImporter {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(BrainRulesImportClient.class);
|
||||||
|
|
||||||
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
private static final ParameterizedTypeReference<ServerSentEvent<String>> SSE_STRING_TYPE =
|
||||||
new ParameterizedTypeReference<>() {};
|
new ParameterizedTypeReference<>() {};
|
||||||
/** Nom de fichier par défaut du PDF de règles (filename absent/vide). */
|
/** Nom de fichier par défaut du PDF de règles (filename absent/vide). */
|
||||||
@@ -153,12 +157,27 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
int[] pageCount = {0};
|
int[] pageCount = {0};
|
||||||
int[] ocrPageCount = {0};
|
int[] ocrPageCount = {0};
|
||||||
boolean[] terminated = {false};
|
boolean[] terminated = {false};
|
||||||
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onError);
|
// Règles extraites, reçues AVANT la traduction (évènement `extracted`). Si la suite
|
||||||
|
// échoue (traduction en panne, flux coupé), on les livre dans leur langue d'origine
|
||||||
|
// plutôt que de perdre tout l'import : la traduction est un plus, pas une condition.
|
||||||
|
RulesImportResult[] extracted = {null};
|
||||||
|
Consumer<Throwable> onFailure = error -> {
|
||||||
|
RulesImportResult kept = extracted[0];
|
||||||
|
if (kept == null) {
|
||||||
|
onError.accept(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
extracted[0] = null;
|
||||||
|
log.warn("Import de règles : traduction interrompue ({}) — règles livrées dans leur "
|
||||||
|
+ "langue d'origine.", error.getMessage());
|
||||||
|
onDone.accept(kept);
|
||||||
|
};
|
||||||
|
ImportCallbacks callbacks = new ImportCallbacks(onProgress, onHeartbeat, onStatus, onDone, onFailure);
|
||||||
|
|
||||||
sse.runStream(
|
sse.runStream(
|
||||||
flux, importTimeoutSeconds, terminated,
|
flux, importTimeoutSeconds, terminated,
|
||||||
event -> handleEvent(event, pageCount, ocrPageCount, terminated, callbacks),
|
event -> handleEvent(event, pageCount, ocrPageCount, terminated, extracted, callbacks),
|
||||||
onError, RulesImportException::new);
|
onFailure, RulesImportException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleEvent(
|
private void handleEvent(
|
||||||
@@ -166,6 +185,7 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
int[] pageCount,
|
int[] pageCount,
|
||||||
int[] ocrPageCount,
|
int[] ocrPageCount,
|
||||||
boolean[] terminated,
|
boolean[] terminated,
|
||||||
|
RulesImportResult[] extracted,
|
||||||
ImportCallbacks callbacks) {
|
ImportCallbacks callbacks) {
|
||||||
|
|
||||||
String event = ssEvent.event();
|
String event = ssEvent.event();
|
||||||
@@ -215,14 +235,30 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
pageCount[0],
|
pageCount[0],
|
||||||
ocrPageCount[0],
|
ocrPageCount[0],
|
||||||
toStringList(node.path("new_sections"))));
|
toStringList(node.path("new_sections"))));
|
||||||
|
} else if ("extracted".equals(event)) {
|
||||||
|
Map<String, String> sections = toStringMap(node.path("sections"));
|
||||||
|
String source = node.path("source_language").asText(null);
|
||||||
|
if (!sections.isEmpty()) {
|
||||||
|
extracted[0] = new RulesImportResult(
|
||||||
|
sections,
|
||||||
|
node.path("page_count").asInt(),
|
||||||
|
node.path("ocr_page_count").asInt(),
|
||||||
|
source != null ? Map.of(source, sections) : Map.of(),
|
||||||
|
source,
|
||||||
|
List.of(),
|
||||||
|
node.path("split_method").asText(null));
|
||||||
|
}
|
||||||
} else if ("done".equals(event)) {
|
} else if ("done".equals(event)) {
|
||||||
terminated[0] = true;
|
terminated[0] = true;
|
||||||
|
extracted[0] = null;
|
||||||
callbacks.onDone().accept(new RulesImportResult(
|
callbacks.onDone().accept(new RulesImportResult(
|
||||||
toStringMap(node.path("sections")),
|
toStringMap(node.path("sections")),
|
||||||
node.path("page_count").asInt(),
|
node.path("page_count").asInt(),
|
||||||
node.path("ocr_page_count").asInt(),
|
node.path("ocr_page_count").asInt(),
|
||||||
toLanguageMap(node.path("sections_by_language")),
|
toLanguageMap(node.path("sections_by_language")),
|
||||||
node.path("source_language").asText(null)));
|
node.path("source_language").asText(null),
|
||||||
|
toStringList(node.path("untranslated")),
|
||||||
|
node.path("split_method").asText(null)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetTemplateAdvisor;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SheetProposalException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : proposition d'un modèle de fiche via le Brain
|
||||||
|
* ({@code POST /generate/sheet-template}, one-shot). La langue de l'interface est relayée par
|
||||||
|
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainSheetTemplateClient implements SheetTemplateAdvisor {
|
||||||
|
|
||||||
|
private static final String PATH = "/generate/sheet-template";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainSheetTemplateClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Candidate> propose(SheetKind kind, String systemName,
|
||||||
|
Map<String, String> sections, List<String> existingFieldNames) {
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("sheet", kind.wireName());
|
||||||
|
req.put("system_name", systemName == null ? "" : systemName);
|
||||||
|
req.put("sections", sections == null ? Map.of() : sections);
|
||||||
|
req.put("existing_fields", existingFieldNames == null ? List.of() : existingFieldNames);
|
||||||
|
return parse(call(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> call(Map<String, Object> req) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new SheetProposalException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new SheetProposalException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new SheetProposalException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new SheetProposalException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lecture tolérante : une entrée mal formée est ignorée, le tri métier est fait en amont. */
|
||||||
|
static List<Candidate> parse(Map<String, Object> resp) {
|
||||||
|
List<Candidate> out = new ArrayList<>();
|
||||||
|
if (!(resp.get("fields") instanceof List<?> fields)) return out;
|
||||||
|
for (Object entry : fields) {
|
||||||
|
if (!(entry instanceof Map<?, ?> field) || field.get("name") == null) continue;
|
||||||
|
List<String> labels = new ArrayList<>();
|
||||||
|
if (field.get("labels") instanceof List<?> rawLabels) {
|
||||||
|
rawLabels.forEach(l -> { if (l != null) labels.add(l.toString()); });
|
||||||
|
}
|
||||||
|
out.add(new Candidate(
|
||||||
|
field.get("name").toString(),
|
||||||
|
field.get("type") == null ? null : field.get("type").toString(),
|
||||||
|
labels,
|
||||||
|
field.get("source") == null ? "" : field.get("source").toString()));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import java.io.IOException;
|
|||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,6 +40,9 @@ public class BrainSidecar {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(BrainSidecar.class);
|
private static final Logger log = LoggerFactory.getLogger(BrainSidecar.class);
|
||||||
|
|
||||||
|
/** Au-dela, le journal du Brain est archive au demarrage (un seul fichier precedent garde). */
|
||||||
|
static final long MAX_LOG_BYTES = 5L * 1024 * 1024;
|
||||||
|
|
||||||
private final BrainSidecarProperties props;
|
private final BrainSidecarProperties props;
|
||||||
private final String internalSecret;
|
private final String internalSecret;
|
||||||
|
|
||||||
@@ -65,7 +69,10 @@ public class BrainSidecar {
|
|||||||
try {
|
try {
|
||||||
ProcessBuilder pb = new ProcessBuilder(props.getCommand());
|
ProcessBuilder pb = new ProcessBuilder(props.getCommand());
|
||||||
pb.redirectErrorStream(true);
|
pb.redirectErrorStream(true);
|
||||||
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
|
File logFile = prepareLogFile(props.getLogFile(), MAX_LOG_BYTES);
|
||||||
|
pb.redirectOutput(logFile != null
|
||||||
|
? ProcessBuilder.Redirect.appendTo(logFile)
|
||||||
|
: ProcessBuilder.Redirect.INHERIT);
|
||||||
|
|
||||||
File workingDir = resolveWorkingDir();
|
File workingDir = resolveWorkingDir();
|
||||||
if (workingDir != null) {
|
if (workingDir != null) {
|
||||||
@@ -78,8 +85,9 @@ public class BrainSidecar {
|
|||||||
|
|
||||||
Process started = pb.start();
|
Process started = pb.start();
|
||||||
this.process.set(started);
|
this.process.set(started);
|
||||||
log.info("[Brain] Sidecar demarre (pid={}, cwd={}).",
|
log.info("[Brain] Sidecar demarre (pid={}, cwd={}, journal={}).",
|
||||||
started.pid(), workingDir != null ? workingDir : "<heritee>");
|
started.pid(), workingDir != null ? workingDir : "<heritee>",
|
||||||
|
logFile != null ? logFile : "<sortie heritee>");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
log.error("[Brain] Echec du lancement du sidecar (commande={}). "
|
||||||
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
+ "Les fonctions IA seront indisponibles. Cause : {}",
|
||||||
@@ -106,6 +114,35 @@ public class BrainSidecar {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare le fichier journal du Brain : cree son dossier et, si le fichier depasse
|
||||||
|
* {@code maxBytes}, l'archive en {@code <nom>.1} (l'archive precedente est remplacee).
|
||||||
|
* Le journal reste ainsi borne sans tache de fond.
|
||||||
|
*
|
||||||
|
* @return le fichier a utiliser, ou {@code null} si aucun n'est configure ou s'il
|
||||||
|
* ne peut pas etre prepare (la sortie reste alors heritee du Core)
|
||||||
|
*/
|
||||||
|
static File prepareLogFile(String logFile, long maxBytes) {
|
||||||
|
if (logFile == null || logFile.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Path path = Path.of(logFile).toAbsolutePath().normalize();
|
||||||
|
try {
|
||||||
|
if (path.getParent() != null) {
|
||||||
|
Files.createDirectories(path.getParent());
|
||||||
|
}
|
||||||
|
if (Files.isRegularFile(path) && Files.size(path) > maxBytes) {
|
||||||
|
Files.move(path, path.resolveSibling(path.getFileName() + ".1"),
|
||||||
|
StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("[Brain] Journal {} inutilisable : {}. Sortie du Brain non conservee.",
|
||||||
|
path, e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return path.toFile();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resout (et cree au besoin) le repertoire de travail du Brain. Le Brain y
|
* Resout (et cree au besoin) le repertoire de travail du Brain. Le Brain y
|
||||||
* ecrit son dossier {@code data/} (index vectoriel, settings.json).
|
* ecrit son dossier {@code data/} (index vectoriel, settings.json).
|
||||||
|
|||||||
@@ -42,6 +42,13 @@ public class BrainSidecarProperties {
|
|||||||
*/
|
*/
|
||||||
private String workingDir;
|
private String workingDir;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fichier ou ecrire la sortie du Brain (journal date : requetes, erreurs du
|
||||||
|
* fournisseur IA, traces Python). Vide = sortie heritee du Core, donc perdue
|
||||||
|
* quand l'application tourne sans console.
|
||||||
|
*/
|
||||||
|
private String logFile;
|
||||||
|
|
||||||
public boolean isEnabled() { return enabled; }
|
public boolean isEnabled() { return enabled; }
|
||||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||||
|
|
||||||
@@ -50,4 +57,7 @@ public class BrainSidecarProperties {
|
|||||||
|
|
||||||
public String getWorkingDir() { return workingDir; }
|
public String getWorkingDir() { return workingDir; }
|
||||||
public void setWorkingDir(String workingDir) { this.workingDir = workingDir; }
|
public void setWorkingDir(String workingDir) { this.workingDir = workingDir; }
|
||||||
|
|
||||||
|
public String getLogFile() { return logFile; }
|
||||||
|
public void setLogFile(String logFile) { this.logFile = logFile; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellProposer;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.exceptions.SpellProposalException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : relevé des sorts dans un morceau de règles via le Brain
|
||||||
|
* ({@code POST /generate/spell-extraction}, one-shot).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainSpellProposalClient implements SpellProposer {
|
||||||
|
|
||||||
|
private static final String PATH = "/generate/spell-extraction";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainSpellProposalClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public List<SpellCandidate> extract(String systemName, String sectionTitle, String text,
|
||||||
|
List<SpellField> fields, List<String> avoid) {
|
||||||
|
List<Map<String, String>> fieldDtos = new ArrayList<>();
|
||||||
|
for (SpellField field : fields == null ? List.<SpellField>of() : fields) {
|
||||||
|
Map<String, String> dto = new LinkedHashMap<>();
|
||||||
|
dto.put("name", field.name());
|
||||||
|
dto.put("type", field.number() ? "NUMBER" : "TEXT");
|
||||||
|
fieldDtos.add(dto);
|
||||||
|
}
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("system_name", nz(systemName));
|
||||||
|
req.put("section_title", nz(sectionTitle));
|
||||||
|
req.put("text", nz(text));
|
||||||
|
req.put("fields", fieldDtos);
|
||||||
|
req.put("avoid", avoid == null ? List.of() : avoid);
|
||||||
|
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new SpellProposalException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new SpellProposalException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new SpellProposalException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new SpellProposalException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return parse(resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lecture tolérante : une entrée mal formée est ignorée, la vérification est faite en amont. */
|
||||||
|
static List<SpellCandidate> parse(Map<String, Object> resp) {
|
||||||
|
List<SpellCandidate> out = new ArrayList<>();
|
||||||
|
if (!(resp.get("spells") instanceof List<?> spells)) return out;
|
||||||
|
for (Object entry : spells) {
|
||||||
|
if (!(entry instanceof Map<?, ?> spell)) continue;
|
||||||
|
Map<String, String> values = new LinkedHashMap<>();
|
||||||
|
if (spell.get("values") instanceof Map<?, ?> raw) {
|
||||||
|
raw.forEach((key, value) -> {
|
||||||
|
if (key != null && value != null) values.put(key.toString(), value.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.add(new SpellCandidate(text(spell.get("name")), text(spell.get("level")), text(spell.get("school")),
|
||||||
|
text(spell.get("description")), values, text(spell.get("excerpt"))));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(Object value) {
|
||||||
|
return value == null ? "" : value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String value) {
|
||||||
|
return value == null ? "" : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,9 @@ package com.loremind.infrastructure.desktop;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.awt.Desktop;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
import java.nio.channels.FileChannel;
|
import java.nio.channels.FileChannel;
|
||||||
import java.nio.channels.FileLock;
|
import java.nio.channels.FileLock;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@@ -102,14 +104,20 @@ public final class DesktopSingleInstance {
|
|||||||
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
openUrl("http://localhost:" + DesktopUserConfig.runningPort() + "/");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ouvre le navigateur par defaut sur une URL quelconque (sans dependance AWT). */
|
/**
|
||||||
|
* Ouvre le navigateur par defaut sur une URL quelconque : API standard de Java
|
||||||
|
* (ShellExecute sous Windows), sinon commande du systeme. Plus de {@code rundll32
|
||||||
|
* url.dll} : outil Windows tres detourne par les logiciels malveillants, que des
|
||||||
|
* antivirus signalaient (Avast « IDP.Generic ») quand un programme peu connu le lance.
|
||||||
|
*/
|
||||||
public static void openUrl(String url) {
|
public static void openUrl(String url) {
|
||||||
|
if (browseWithJava(url)) return;
|
||||||
try {
|
try {
|
||||||
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
String os = System.getProperty(OS_NAME_PROPERTY, "").toLowerCase();
|
||||||
ProcessBuilder pb;
|
ProcessBuilder pb;
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
// rundll32 : ouverture d'URL fiable sans dependance graphique Java.
|
// « start » de cmd ; le "" est le titre de fenetre attendu avant l'URL.
|
||||||
pb = new ProcessBuilder("rundll32", "url.dll,FileProtocolHandler", url);
|
pb = new ProcessBuilder("cmd", "/c", "start", "", url);
|
||||||
} else if (os.contains("mac")) {
|
} else if (os.contains("mac")) {
|
||||||
pb = new ProcessBuilder("open", url);
|
pb = new ProcessBuilder("open", url);
|
||||||
} else {
|
} else {
|
||||||
@@ -122,6 +130,20 @@ public final class DesktopSingleInstance {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** {@link Desktop#browse} si disponible (jamais en headless) ; false = repli sur une commande. */
|
||||||
|
private static boolean browseWithJava(String url) {
|
||||||
|
try {
|
||||||
|
if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Desktop.getDesktop().browse(URI.create(url));
|
||||||
|
return true;
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
log.debug("[Desktop] Ouverture via Desktop.browse impossible ({}), repli sur une commande.", e.getMessage());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
|
/** Ouvre un dossier dans le gestionnaire de fichiers du systeme. */
|
||||||
public static void openFolder(Path dir) {
|
public static void openFolder(Path dir) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+43
-21
@@ -26,9 +26,16 @@ import java.util.concurrent.TimeUnit;
|
|||||||
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
|
* qu'aux réseaux PRIVÉS ; un Wi-Fi classé « Public » reste à basculer par l'utilisateur
|
||||||
* (réglage système, jamais modifié par l'application).
|
* (réglage système, jamais modifié par l'application).
|
||||||
* <p>
|
* <p>
|
||||||
* Les scripts sont passés en {@code -EncodedCommand} (UTF-16LE base64) : aucun problème de
|
* Les scripts sont passés EN CLAIR ({@code -Command}, une ligne) : un script encodé
|
||||||
* guillemets ni d'accents. Le seul paramètre variable est le chemin de l'exécutable,
|
* ({@code -EncodedCommand}) accompagné de {@code -ExecutionPolicy Bypass} est la signature
|
||||||
* fourni par le système (pas par l'utilisateur), et échappé pour une chaîne PowerShell.
|
* typique des logiciels malveillants, et faisait réagir des antivirus (Avast « IDP.Generic »).
|
||||||
|
* La politique d'exécution ne concerne que les fichiers .ps1 : inutile de la contourner.
|
||||||
|
* La ligne de commande Windows est en UTF-16 : accents et noms de réseau passent tels quels.
|
||||||
|
* Seule exception : le script relancé EN ADMINISTRATEUR (bouton « Autoriser »), encodé car
|
||||||
|
* {@code Start-Process -ArgumentList} ne sait pas transmettre un script avec espaces et
|
||||||
|
* guillemets ; il ne s'exécute que sur clic de l'utilisateur, derrière la confirmation UAC.
|
||||||
|
* Le seul paramètre variable est le chemin de l'exécutable, fourni par le système (pas par
|
||||||
|
* l'utilisateur), et échappé pour une chaîne PowerShell.
|
||||||
* <p>
|
* <p>
|
||||||
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
|
* Choisie au démarrage par {@code HostNetworkAccessConfig} sous Windows.
|
||||||
*/
|
*/
|
||||||
@@ -69,14 +76,8 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
public FirewallFixOutcome allowThroughFirewall() {
|
public FirewallFixOutcome allowThroughFirewall() {
|
||||||
String program = currentProgram();
|
String program = currentProgram();
|
||||||
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
|
if (!isWindows() || program == null) return FirewallFixOutcome.UNSUPPORTED;
|
||||||
String outer = "try {\n"
|
|
||||||
+ " $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
|
|
||||||
+ "-ArgumentList @('-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand','"
|
|
||||||
+ encode(allowScript(program)) + "')\n"
|
|
||||||
+ " exit $p.ExitCode\n"
|
|
||||||
+ "} catch { exit " + EXIT_CANCELLED + " }\n";
|
|
||||||
try {
|
try {
|
||||||
int exit = runPowerShell(outer, ELEVATION_TIMEOUT_S).exitCode();
|
int exit = runPowerShell(elevationScript(program), ELEVATION_TIMEOUT_S).exitCode();
|
||||||
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
|
FirewallFixOutcome outcome = exit == 0 ? FirewallFixOutcome.APPLIED
|
||||||
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
|
: exit == EXIT_CANCELLED ? FirewallFixOutcome.CANCELLED : FirewallFixOutcome.FAILED;
|
||||||
log.info("Accès distant : autorisation pare-feu → {}", outcome);
|
log.info("Accès distant : autorisation pare-feu → {}", outcome);
|
||||||
@@ -103,24 +104,37 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
|
|
||||||
// --- Scripts --------------------------------------------------------------------------
|
// --- Scripts --------------------------------------------------------------------------
|
||||||
|
|
||||||
/** Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris). */
|
/**
|
||||||
|
* Réseaux connectés + règles entrantes visant ce programme (chemins avec %VARIABLES% compris).
|
||||||
|
* Une seule ligne d'instructions séparées par « ; » : elle est passée telle quelle à {@code -Command}.
|
||||||
|
*/
|
||||||
static String inspectScript(String program) {
|
static String inspectScript(String program) {
|
||||||
return "$ErrorActionPreference = 'SilentlyContinue'\n"
|
return "$ErrorActionPreference = 'SilentlyContinue'; "
|
||||||
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
|
// Sortie en UTF-8 : sinon la page de codes de la console abîme les noms de réseau accentués.
|
||||||
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
|
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
|
||||||
+ "$p = '" + psQuote(program) + "'\n"
|
+ "$p = '" + psQuote(program) + "'; "
|
||||||
+ "$nets =@(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
+ "$nets = @(Get-NetConnectionProfile | ForEach-Object { [pscustomobject]@{ name = $_.Name; "
|
||||||
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } })\n"
|
+ "alias = $_.InterfaceAlias; category = $_.NetworkCategory.ToString() } }); "
|
||||||
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
+ "$rules = @(Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and "
|
||||||
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
+ "([Environment]::ExpandEnvironmentVariables($_.Program) -ieq $p) } | Get-NetFirewallRule | "
|
||||||
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
+ "Where-Object { $_.Direction.ToString() -eq 'Inbound' } | ForEach-Object { [pscustomobject]@{ "
|
||||||
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } })\n"
|
+ "action = $_.Action.ToString(); profile = $_.Profile.ToString(); enabled = $_.Enabled.ToString() } }); "
|
||||||
// Pare-feu TIERS déclarés au Centre de sécurité (le pare-feu Windows n'y figure pas) :
|
// Pare-feu TIERS déclarés au Centre de sécurité (le pare-feu Windows n'y figure pas) :
|
||||||
// ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire.
|
// ils filtrent en plus de Windows, avec des règles qu'on ne peut pas lire.
|
||||||
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
|
+ "$fw = @(Get-CimInstance -Namespace root/SecurityCenter2 -ClassName FirewallProduct | "
|
||||||
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' })\n"
|
+ "ForEach-Object { $_.displayName } | Where-Object { $_ -and $_ -notmatch 'Windows' }); "
|
||||||
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
+ "[pscustomobject]@{ networks = $nets; rules = $rules; thirdPartyFirewalls = $fw } | "
|
||||||
+ "ConvertTo-Json -Depth 4 -Compress\n";
|
+ "ConvertTo-Json -Depth 4 -Compress";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relance PowerShell EN ADMINISTRATEUR (confirmation UAC) avec {@link #allowScript}, et
|
||||||
|
* renvoie son code de sortie ; refus de l'UAC → {@value #EXIT_CANCELLED}. Une seule ligne.
|
||||||
|
*/
|
||||||
|
static String elevationScript(String program) {
|
||||||
|
return "try { $p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -Wait -PassThru "
|
||||||
|
+ "-ArgumentList @('-NoProfile','-NonInteractive','-EncodedCommand','"
|
||||||
|
+ encode(allowScript(program)) + "'); exit $p.ExitCode } catch { exit " + EXIT_CANCELLED + " }";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -183,9 +197,9 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
|
|
||||||
private record Result(int exitCode, String output) {}
|
private record Result(int exitCode, String output) {}
|
||||||
|
|
||||||
|
/** {@code script} : une ligne, sans guillemet double (chaînes PowerShell entre apostrophes). */
|
||||||
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
|
private static Result runPowerShell(String script, long timeoutSeconds) throws IOException, InterruptedException {
|
||||||
Process process = new ProcessBuilder("powershell.exe", "-NoProfile", "-NonInteractive",
|
Process process = new ProcessBuilder(command(script))
|
||||||
"-ExecutionPolicy", "Bypass", "-EncodedCommand", encode(script))
|
|
||||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||||
.start();
|
.start();
|
||||||
process.getOutputStream().close();
|
process.getOutputStream().close();
|
||||||
@@ -204,6 +218,14 @@ public class WindowsHostNetworkAccess implements HostNetworkAccess {
|
|||||||
return new Result(process.exitValue(), output.join());
|
return new Result(process.exitValue(), output.join());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Ligne de commande PowerShell : script en clair, ni encodage ni contournement de politique. */
|
||||||
|
static List<String> command(String script) {
|
||||||
|
if (script.indexOf('"') >= 0 || script.indexOf('\n') >= 0) {
|
||||||
|
throw new IllegalArgumentException("Script PowerShell : une ligne, sans guillemet double");
|
||||||
|
}
|
||||||
|
return List.of("powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script);
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean isWindows() {
|
private static boolean isWindows() {
|
||||||
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.loremind.infrastructure.persistence.entity;
|
|||||||
|
|
||||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -12,6 +13,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Arcs en base de données PostgreSQL.
|
* Entité JPA pour la persistance des Arcs en base de données PostgreSQL.
|
||||||
@@ -93,6 +96,12 @@ public class ArcJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
+13
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.infrastructure.persistence.entity;
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -10,6 +11,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Chapters en base de données PostgreSQL.
|
* Entité JPA pour la persistance des Chapters en base de données PostgreSQL.
|
||||||
@@ -51,6 +54,10 @@ public class ChapterJpaEntity {
|
|||||||
@Column(name = "narrative_stakes", columnDefinition = "TEXT")
|
@Column(name = "narrative_stakes", columnDefinition = "TEXT")
|
||||||
private String narrativeStakes;
|
private String narrativeStakes;
|
||||||
|
|
||||||
|
/** Méthode guidée suivie par le chapitre (V30), ou null. */
|
||||||
|
@Column(name = "guided_method", length = 64)
|
||||||
|
private String guidedMethod;
|
||||||
|
|
||||||
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
@Column(name = "related_page_ids", columnDefinition = "TEXT")
|
||||||
@Convert(converter = StringListJsonConverter.class)
|
@Convert(converter = StringListJsonConverter.class)
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
@@ -61,6 +68,12 @@ public class ChapterJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
+5
@@ -55,6 +55,11 @@ public class GameSystemJpaEntity {
|
|||||||
@Column(name = "enemy_template", columnDefinition = "TEXT")
|
@Column(name = "enemy_template", columnDefinition = "TEXT")
|
||||||
private List<TemplateField> enemyTemplate;
|
private List<TemplateField> enemyTemplate;
|
||||||
|
|
||||||
|
/** Modèle de sort (champs propres au système de chaque sort du catalogue), en JSON. Nullable. */
|
||||||
|
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||||
|
@Column(name = "spell_template", columnDefinition = "TEXT")
|
||||||
|
private List<TemplateField> spellTemplate;
|
||||||
|
|
||||||
/** Type d'acteur Foundry pour les ennemis maison (import de structure). Nullable. */
|
/** Type d'acteur Foundry pour les ennemis maison (import de structure). Nullable. */
|
||||||
@Column(name = "foundry_actor_type")
|
@Column(name = "foundry_actor_type")
|
||||||
private String foundryActorType;
|
private String foundryActorType;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
|||||||
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.PrerequisiteListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.QuestNodeListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.QuestNodeListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -14,6 +15,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Quests (table {@code quests}).
|
* Entité JPA pour la persistance des Quests (table {@code quests}).
|
||||||
@@ -83,6 +86,12 @@ public class QuestJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.loremind.infrastructure.persistence.converter.RoomListJsonConverter;
|
|||||||
import com.loremind.infrastructure.persistence.converter.SceneBattlemapListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.SceneBattlemapListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.SceneBranchListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.SceneBranchListJsonConverter;
|
||||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -17,6 +18,8 @@ import java.time.LocalDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Entité JPA pour la persistance des Scenes en base de données PostgreSQL.
|
* Entité JPA pour la persistance des Scenes en base de données PostgreSQL.
|
||||||
@@ -48,6 +51,10 @@ public class SceneJpaEntity {
|
|||||||
@Column
|
@Column
|
||||||
private String icon;
|
private String icon;
|
||||||
|
|
||||||
|
/** Rôle de la scène dans la méthode guidée du chapitre (V30), ou null. */
|
||||||
|
@Column(name = "guided_role", length = 64)
|
||||||
|
private String guidedRole;
|
||||||
|
|
||||||
/** Type narratif du nœud (Niveau 2). Défaut GENERIC ; colonne dotée d'un default SQL (V13). */
|
/** Type narratif du nœud (Niveau 2). Défaut GENERIC ; colonne dotée d'un default SQL (V13). */
|
||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
@Column(name = "scene_type", length = 32)
|
@Column(name = "scene_type", length = 32)
|
||||||
@@ -109,6 +116,12 @@ public class SceneJpaEntity {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private List<String> illustrationImageIds = new ArrayList<>();
|
private List<String> illustrationImageIds = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Placement de certaines illustrations dans le livret PDF (id d'image → placement). JSON dans colonne TEXT. */
|
||||||
|
@Column(name = "illustration_placements", columnDefinition = "TEXT")
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Builder.Default
|
||||||
|
private Map<String, String> illustrationPlacements = new HashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Battlemaps Foundry : liste de paires { media + sidecar } étiquetées
|
* Battlemaps Foundry : liste de paires { media + sidecar } étiquetées
|
||||||
* (variantes Jour/Nuit, étages…). JSON en TEXT via converter (V22).
|
* (variantes Jour/Nuit, étages…). JSON en TEXT via converter (V22).
|
||||||
|
|||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Index;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import jakarta.persistence.UniqueConstraint;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un sort connu d'une fiche (table {@code sheet_spells}, V33) : lien entre une fiche (PJ, PNJ
|
||||||
|
* ou ennemi, désignée par son type et son identifiant) et un sort du catalogue du système.
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "sheet_spells",
|
||||||
|
indexes = @Index(name = "ix_sheet_spells_owner", columnList = "owner_type, owner_id"),
|
||||||
|
uniqueConstraints = @UniqueConstraint(name = "uk_sheet_spells_owner_spell",
|
||||||
|
columnNames = {"owner_type", "owner_id", "spell_id"}))
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SheetSpellJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/** {@code character}, {@code npc} ou {@code enemy}. */
|
||||||
|
@Column(name = "owner_type", nullable = false, length = 16)
|
||||||
|
private String ownerType;
|
||||||
|
|
||||||
|
@Column(name = "owner_id", nullable = false)
|
||||||
|
private Long ownerId;
|
||||||
|
|
||||||
|
@Column(name = "spell_id", nullable = false)
|
||||||
|
private Long spellId;
|
||||||
|
|
||||||
|
@Column(name = "\"order\"", nullable = false)
|
||||||
|
private int order;
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.entity;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.converter.StringMapJsonConverter;
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Convert;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Index;
|
||||||
|
import jakarta.persistence.PrePersist;
|
||||||
|
import jakarta.persistence.PreUpdate;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entité JPA d'un sort du catalogue d'un système de jeu (table {@code spells}, V32).
|
||||||
|
* La suppression d'un système supprime ses sorts (clé étrangère en cascade).
|
||||||
|
*/
|
||||||
|
@Entity
|
||||||
|
@Table(name = "spells", indexes = {
|
||||||
|
@Index(name = "ix_spells_game_system", columnList = "game_system_id")
|
||||||
|
})
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SpellJpaEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(name = "game_system_id", nullable = false)
|
||||||
|
private Long gameSystemId;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Column(name = "level")
|
||||||
|
private String level;
|
||||||
|
|
||||||
|
@Column(name = "school")
|
||||||
|
private String school;
|
||||||
|
|
||||||
|
@Column(columnDefinition = "TEXT")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
/** Valeurs des champs du modèle de sort, en JSON. */
|
||||||
|
@Convert(converter = StringMapJsonConverter.class)
|
||||||
|
@Column(name = "field_values", columnDefinition = "TEXT")
|
||||||
|
private Map<String, String> values;
|
||||||
|
|
||||||
|
@Column(name = "\"order\"", nullable = false)
|
||||||
|
private int order;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at", nullable = false)
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
protected void onCreate() {
|
||||||
|
createdAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||||
|
updatedAt = createdAt;
|
||||||
|
if (values == null) values = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreUpdate
|
||||||
|
protected void onUpdate() {
|
||||||
|
updatedAt = LocalDateTime.now(ZoneId.systemDefault());
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SheetSpellJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface SheetSpellJpaRepository extends JpaRepository<SheetSpellJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<SheetSpellJpaEntity> findByOwnerTypeAndOwnerIdOrderByOrderAsc(String ownerType, Long ownerId);
|
||||||
|
|
||||||
|
/** Suppression directe en base : les liens suivants peuvent être réinsérés dans la même transaction. */
|
||||||
|
@Modifying(flushAutomatically = true, clearAutomatically = true)
|
||||||
|
@Query("delete from SheetSpellJpaEntity l where l.ownerType = :ownerType and l.ownerId = :ownerId")
|
||||||
|
void deleteByOwner(@Param("ownerType") String ownerType, @Param("ownerId") Long ownerId);
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.jpa;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SpellJpaEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface SpellJpaRepository extends JpaRepository<SpellJpaEntity, Long> {
|
||||||
|
|
||||||
|
List<SpellJpaEntity> findByGameSystemIdOrderByOrderAsc(Long gameSystemId);
|
||||||
|
}
|
||||||
+7
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,6 +87,9 @@ public class PostgresArcRepository implements ArcRepository {
|
|||||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(jpaEntity.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(jpaEntity.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(jpaEntity.getCreatedAt())
|
.createdAt(jpaEntity.getCreatedAt())
|
||||||
.updatedAt(jpaEntity.getUpdatedAt())
|
.updatedAt(jpaEntity.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
@@ -114,6 +118,9 @@ public class PostgresArcRepository implements ArcRepository {
|
|||||||
.illustrationImageIds(arc.getIllustrationImageIds() != null
|
.illustrationImageIds(arc.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(arc.getIllustrationImageIds())
|
? new ArrayList<>(arc.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(arc.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(arc.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(arc.getCreatedAt())
|
.createdAt(arc.getCreatedAt())
|
||||||
.updatedAt(arc.getUpdatedAt())
|
.updatedAt(arc.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
+9
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,12 +75,16 @@ public class PostgresChapterRepository implements ChapterRepository {
|
|||||||
.gmNotes(jpaEntity.getGmNotes())
|
.gmNotes(jpaEntity.getGmNotes())
|
||||||
.playerObjectives(jpaEntity.getPlayerObjectives())
|
.playerObjectives(jpaEntity.getPlayerObjectives())
|
||||||
.narrativeStakes(jpaEntity.getNarrativeStakes())
|
.narrativeStakes(jpaEntity.getNarrativeStakes())
|
||||||
|
.guidedMethod(jpaEntity.getGuidedMethod())
|
||||||
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
.relatedPageIds(jpaEntity.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
? new ArrayList<>(jpaEntity.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(jpaEntity.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(jpaEntity.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(jpaEntity.getCreatedAt())
|
.createdAt(jpaEntity.getCreatedAt())
|
||||||
.updatedAt(jpaEntity.getUpdatedAt())
|
.updatedAt(jpaEntity.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
@@ -97,12 +102,16 @@ public class PostgresChapterRepository implements ChapterRepository {
|
|||||||
.gmNotes(chapter.getGmNotes())
|
.gmNotes(chapter.getGmNotes())
|
||||||
.playerObjectives(chapter.getPlayerObjectives())
|
.playerObjectives(chapter.getPlayerObjectives())
|
||||||
.narrativeStakes(chapter.getNarrativeStakes())
|
.narrativeStakes(chapter.getNarrativeStakes())
|
||||||
|
.guidedMethod(chapter.getGuidedMethod())
|
||||||
.relatedPageIds(chapter.getRelatedPageIds() != null
|
.relatedPageIds(chapter.getRelatedPageIds() != null
|
||||||
? new ArrayList<>(chapter.getRelatedPageIds())
|
? new ArrayList<>(chapter.getRelatedPageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
.illustrationImageIds(chapter.getIllustrationImageIds() != null
|
.illustrationImageIds(chapter.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(chapter.getIllustrationImageIds())
|
? new ArrayList<>(chapter.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(chapter.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(chapter.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(chapter.getCreatedAt())
|
.createdAt(chapter.getCreatedAt())
|
||||||
.updatedAt(chapter.getUpdatedAt())
|
.updatedAt(chapter.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
+4
@@ -70,6 +70,9 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.enemyTemplate(e.getEnemyTemplate() != null
|
.enemyTemplate(e.getEnemyTemplate() != null
|
||||||
? new java.util.ArrayList<>(e.getEnemyTemplate())
|
? new java.util.ArrayList<>(e.getEnemyTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
.spellTemplate(e.getSpellTemplate() != null
|
||||||
|
? new java.util.ArrayList<>(e.getSpellTemplate())
|
||||||
|
: new java.util.ArrayList<>())
|
||||||
.foundryActorType(e.getFoundryActorType())
|
.foundryActorType(e.getFoundryActorType())
|
||||||
.author(e.getAuthor())
|
.author(e.getAuthor())
|
||||||
.isPublic(e.isPublic())
|
.isPublic(e.isPublic())
|
||||||
@@ -95,6 +98,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.enemyTemplate(g.getEnemyTemplate() != null
|
.enemyTemplate(g.getEnemyTemplate() != null
|
||||||
? new java.util.ArrayList<>(g.getEnemyTemplate())
|
? new java.util.ArrayList<>(g.getEnemyTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
.spellTemplate(new java.util.ArrayList<>(g.getSpellTemplate()))
|
||||||
.foundryActorType(g.getFoundryActorType())
|
.foundryActorType(g.getFoundryActorType())
|
||||||
.author(g.getAuthor())
|
.author(g.getAuthor())
|
||||||
.isPublic(g.isPublic())
|
.isPublic(g.isPublic())
|
||||||
|
|||||||
+7
@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -91,6 +92,9 @@ public class PostgresQuestRepository implements QuestRepository {
|
|||||||
.illustrationImageIds(e.getIllustrationImageIds() != null
|
.illustrationImageIds(e.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(e.getIllustrationImageIds())
|
? new ArrayList<>(e.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(e.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(e.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(e.getCreatedAt())
|
.createdAt(e.getCreatedAt())
|
||||||
.updatedAt(e.getUpdatedAt())
|
.updatedAt(e.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
@@ -121,6 +125,9 @@ public class PostgresQuestRepository implements QuestRepository {
|
|||||||
.illustrationImageIds(q.getIllustrationImageIds() != null
|
.illustrationImageIds(q.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(q.getIllustrationImageIds())
|
? new ArrayList<>(q.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(q.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(q.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.createdAt(q.getCreatedAt())
|
.createdAt(q.getCreatedAt())
|
||||||
.updatedAt(q.getUpdatedAt())
|
.updatedAt(q.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
+9
@@ -9,6 +9,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,6 +83,7 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
.combatDifficulty(jpaEntity.getCombatDifficulty())
|
||||||
.tactics(jpaEntity.getTactics())
|
.tactics(jpaEntity.getTactics())
|
||||||
.purpose(jpaEntity.getPurpose())
|
.purpose(jpaEntity.getPurpose())
|
||||||
|
.guidedRole(jpaEntity.getGuidedRole())
|
||||||
.enemies(jpaEntity.getEnemies())
|
.enemies(jpaEntity.getEnemies())
|
||||||
.enemyIds(jpaEntity.getEnemyIds() != null
|
.enemyIds(jpaEntity.getEnemyIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getEnemyIds())
|
? new ArrayList<>(jpaEntity.getEnemyIds())
|
||||||
@@ -92,6 +94,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
.illustrationImageIds(jpaEntity.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
? new ArrayList<>(jpaEntity.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(jpaEntity.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(jpaEntity.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.battlemaps(jpaEntity.getBattlemaps() != null
|
.battlemaps(jpaEntity.getBattlemaps() != null
|
||||||
? new ArrayList<>(jpaEntity.getBattlemaps())
|
? new ArrayList<>(jpaEntity.getBattlemaps())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
@@ -127,6 +132,7 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.combatDifficulty(scene.getCombatDifficulty())
|
.combatDifficulty(scene.getCombatDifficulty())
|
||||||
.tactics(scene.getTactics())
|
.tactics(scene.getTactics())
|
||||||
.purpose(scene.getPurpose())
|
.purpose(scene.getPurpose())
|
||||||
|
.guidedRole(scene.getGuidedRole())
|
||||||
.enemies(scene.getEnemies())
|
.enemies(scene.getEnemies())
|
||||||
.enemyIds(scene.getEnemyIds() != null
|
.enemyIds(scene.getEnemyIds() != null
|
||||||
? new ArrayList<>(scene.getEnemyIds())
|
? new ArrayList<>(scene.getEnemyIds())
|
||||||
@@ -137,6 +143,9 @@ public class PostgresSceneRepository implements SceneRepository {
|
|||||||
.illustrationImageIds(scene.getIllustrationImageIds() != null
|
.illustrationImageIds(scene.getIllustrationImageIds() != null
|
||||||
? new ArrayList<>(scene.getIllustrationImageIds())
|
? new ArrayList<>(scene.getIllustrationImageIds())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
.illustrationPlacements(scene.getIllustrationPlacements() != null
|
||||||
|
? new HashMap<>(scene.getIllustrationPlacements())
|
||||||
|
: new HashMap<>())
|
||||||
.battlemaps(scene.getBattlemaps() != null
|
.battlemaps(scene.getBattlemaps() != null
|
||||||
? new ArrayList<>(scene.getBattlemaps())
|
? new ArrayList<>(scene.getBattlemaps())
|
||||||
: new ArrayList<>())
|
: new ArrayList<>())
|
||||||
|
|||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.SheetKind;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SheetSpellRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SheetSpellJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.SheetSpellJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur JPA des sorts connus d'une fiche.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class PostgresSheetSpellRepository implements SheetSpellRepository {
|
||||||
|
|
||||||
|
private final SheetSpellJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresSheetSpellRepository(SheetSpellJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> findSpellIds(SheetKind kind, String ownerId) {
|
||||||
|
return jpaRepository.findByOwnerTypeAndOwnerIdOrderByOrderAsc(kind.wireName(), Long.parseLong(ownerId)).stream()
|
||||||
|
.map(link -> link.getSpellId().toString())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void replace(SheetKind kind, String ownerId, List<String> spellIds) {
|
||||||
|
Long owner = Long.parseLong(ownerId);
|
||||||
|
jpaRepository.deleteByOwner(kind.wireName(), owner);
|
||||||
|
List<SheetSpellJpaEntity> links = new ArrayList<>();
|
||||||
|
for (int i = 0; i < spellIds.size(); i++) {
|
||||||
|
links.add(SheetSpellJpaEntity.builder()
|
||||||
|
.ownerType(kind.wireName()).ownerId(owner)
|
||||||
|
.spellId(Long.parseLong(spellIds.get(i))).order(i)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
jpaRepository.saveAll(links);
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package com.loremind.infrastructure.persistence.postgres;
|
||||||
|
|
||||||
|
import com.loremind.domain.gamesystemcontext.Spell;
|
||||||
|
import com.loremind.domain.gamesystemcontext.ports.SpellRepository;
|
||||||
|
import com.loremind.infrastructure.persistence.entity.SpellJpaEntity;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.SpellJpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adaptateur JPA du catalogue de sorts.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class PostgresSpellRepository implements SpellRepository {
|
||||||
|
|
||||||
|
private final SpellJpaRepository jpaRepository;
|
||||||
|
|
||||||
|
public PostgresSpellRepository(SpellJpaRepository jpaRepository) {
|
||||||
|
this.jpaRepository = jpaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Spell save(Spell spell) {
|
||||||
|
return toDomainEntity(jpaRepository.save(toJpaEntity(spell)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Spell> findByGameSystemId(String gameSystemId) {
|
||||||
|
return jpaRepository.findByGameSystemIdOrderByOrderAsc(Long.parseLong(gameSystemId)).stream()
|
||||||
|
.map(this::toDomainEntity)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(String id) {
|
||||||
|
jpaRepository.deleteById(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> existingIds(List<String> ids) {
|
||||||
|
if (ids == null || ids.isEmpty()) return List.of();
|
||||||
|
return jpaRepository.findAllById(ids.stream().map(Long::parseLong).toList()).stream()
|
||||||
|
.map(e -> e.getId().toString())
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Spell toDomainEntity(SpellJpaEntity e) {
|
||||||
|
return Spell.builder()
|
||||||
|
.id(e.getId().toString())
|
||||||
|
.gameSystemId(e.getGameSystemId().toString())
|
||||||
|
.name(e.getName())
|
||||||
|
.level(e.getLevel())
|
||||||
|
.school(e.getSchool())
|
||||||
|
.description(e.getDescription())
|
||||||
|
.values(e.getValues() != null ? new HashMap<>(e.getValues()) : new HashMap<>())
|
||||||
|
.order(e.getOrder())
|
||||||
|
.createdAt(e.getCreatedAt())
|
||||||
|
.updatedAt(e.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private SpellJpaEntity toJpaEntity(Spell s) {
|
||||||
|
return SpellJpaEntity.builder()
|
||||||
|
.id(s.getId() != null ? Long.parseLong(s.getId()) : null)
|
||||||
|
.gameSystemId(Long.parseLong(s.getGameSystemId()))
|
||||||
|
.name(s.getName())
|
||||||
|
.level(s.getLevel())
|
||||||
|
.school(s.getSchool())
|
||||||
|
.description(s.getDescription())
|
||||||
|
.values(new HashMap<>(s.getValues()))
|
||||||
|
.order(s.getOrder())
|
||||||
|
.createdAt(s.getCreatedAt())
|
||||||
|
.updatedAt(s.getUpdatedAt())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user