Imports PDF fidèles au livre : règles, sorts et campagnes découpés par la structure du PDF
Le texte importé est celui du livre : l'appli découpe le PDF d'après sa table des matières (ou ses titres), sans IA, et l'IA ne fait plus que repérer, résumer à part et traduire. Mesuré en local avec Ollama et un petit modèle (contexte 8192). Lecture du PDF - Découpage par les signets du PDF, sinon par les titres repérés à la taille des caractères ; à défaut de structure, repli sur l'IA. - Tableaux rendus en markdown, colonnes relues dans l'ordre quand elles sont nettes, mots coupés en fin de ligne recollés. - En-têtes, numéros de page, titres courants, onglets de marge et titres dessinés deux fois retirés du texte. Import de règles - Sections tirées de la structure du livre pour tous les fournisseurs ; sans structure, l'IA ne fait que placer des repères : le texte n'est ni réécrit ni perdu. - Traduction en parallèle (une section à la fois en local), règles livrées dans leur langue si la traduction échoue, sections non traduites signalées. - Glossaire des termes de jeu donné au modèle pour traduire les blocs de statistiques. - Durée maximale d'un import (4 h) et message clair quand la connexion est coupée. - Sections lues mises en forme, édition à la demande. Sorts - Proposition : le modèle désigne le sort, sa description est recopiée du livre. - Niveaux et écoles harmonisés d'un clic. Import de campagne - Arcs, aventures, scènes et pièces tirés de la table des matières ; le texte de chaque scène est celui du livre, dans ses notes du MJ. - L'IA n'ajoute que le synopsis des scènes et les fiches des PNJ, puis traduit le texte en entier si le livre n'est pas dans la langue de l'interface. - Annexes (bestiaire, objets) dans un arc à part, en quelques scènes de lecture. - PNJ : des individus seulement — groupes, créatures génériques, profils de créature et personnes citées en préface écartés ; un rôle unique sans nom est gardé. - La campagne découpée est proposée même si l'IA échoue ; une note le dit à la révision. - Fiche de scène : notes du MJ et pièces mises en forme (sous-titres, tableaux). Ollama - Réflexion coupée pour les modèles à raisonnement, qui renvoyaient des réponses vides.
This commit is contained in:
+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,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -128,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()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from app.api.deps import get_llm_provider
|
|||||||
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.prompts import spell_extraction as spell_prompts
|
from app.application.prompts import spell_extraction as spell_prompts
|
||||||
|
from app.application.spell_location import locate_spells
|
||||||
from app.domain.ports import LLMProvider, LLMProviderError
|
from app.domain.ports import LLMProvider, LLMProviderError
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -21,15 +22,16 @@ _SPELLS_SCHEMA: dict = {
|
|||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "object",
|
"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": {
|
"properties": {
|
||||||
"name": {"type": "string"},
|
"name": {"type": "string"},
|
||||||
"level": {"type": "string"},
|
"level": {"type": "string"},
|
||||||
"school": {"type": "string"},
|
"school": {"type": "string"},
|
||||||
"description": {"type": "string"},
|
|
||||||
"values": {"type": "object"},
|
"values": {"type": "object"},
|
||||||
"excerpt": {"type": "string"},
|
"start": {"type": "string"},
|
||||||
},
|
},
|
||||||
"required": ["name", "description", "excerpt"],
|
"required": ["name", "start"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -55,7 +57,8 @@ class SpellExtractionRequestDTO(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ExtractedSpellDTO(BaseModel):
|
class ExtractedSpellDTO(BaseModel):
|
||||||
"""Un sort relevé. `excerpt` : passage du texte, que le Core vérifie mot pour mot."""
|
"""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
|
name: str
|
||||||
level: str = ""
|
level: str = ""
|
||||||
@@ -76,8 +79,10 @@ async def generate_spell_extraction(
|
|||||||
) -> SpellExtractionResponseDTO:
|
) -> SpellExtractionResponseDTO:
|
||||||
"""Relève les sorts décrits dans un morceau de règles. Rien n'est enregistré.
|
"""Relève les sorts décrits dans un morceau de règles. Rien n'est enregistré.
|
||||||
|
|
||||||
Le Core vérifie ensuite, pour chaque sort, que son nom et le passage cité se retrouvent
|
Le modèle désigne les sorts (nom, niveau, école, valeurs, premiers mots du bloc) ; la
|
||||||
dans le texte envoyé ; une liste vide signifie que le morceau ne décrit aucun sort.
|
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():
|
if not body.text.strip():
|
||||||
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
||||||
@@ -93,40 +98,8 @@ async def generate_spell_extraction(
|
|||||||
parsed, _ = load_json_object(raw)
|
parsed, _ = load_json_object(raw)
|
||||||
if not isinstance(parsed, dict):
|
if not isinstance(parsed, dict):
|
||||||
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de liste de sorts exploitable.")
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de liste de sorts exploitable.")
|
||||||
return SpellExtractionResponseDTO(spells=_clean_spells(parsed.get("spells")))
|
return SpellExtractionResponseDTO(spells=[
|
||||||
|
ExtractedSpellDTO(name=spell.name, level=spell.level, school=spell.school,
|
||||||
|
description=spell.description, values=spell.values, excerpt=spell.excerpt)
|
||||||
def _text(value: object) -> str:
|
for spell in locate_spells(parsed.get("spells"), body.text, body.section_title)
|
||||||
"""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 _clean_spells(raw: object) -> list[ExtractedSpellDTO]:
|
|
||||||
"""Garde les sorts complets (nom, description et passage cité non vides).
|
|
||||||
|
|
||||||
La vérification du nom et du passage contre les règles est faite par le Core.
|
|
||||||
"""
|
|
||||||
out: list[ExtractedSpellDTO] = []
|
|
||||||
if not isinstance(raw, list):
|
|
||||||
return out
|
|
||||||
for entry in raw:
|
|
||||||
if not isinstance(entry, dict):
|
|
||||||
continue
|
|
||||||
name, description, excerpt = (_text(entry.get(key)) for key in ("name", "description", "excerpt"))
|
|
||||||
if not name or not description or not excerpt:
|
|
||||||
continue
|
|
||||||
values = entry.get("values")
|
|
||||||
out.append(ExtractedSpellDTO(
|
|
||||||
name=name,
|
|
||||||
level=_text(entry.get("level")),
|
|
||||||
school=_text(entry.get("school")),
|
|
||||||
description=description,
|
|
||||||
values={str(k).strip(): _text(v) for k, v in values.items() if str(k).strip() and _text(v)}
|
|
||||||
if isinstance(values, dict) else {},
|
|
||||||
excerpt=excerpt,
|
|
||||||
))
|
|
||||||
return out
|
|
||||||
|
|||||||
@@ -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"])
|
||||||
|
|||||||
@@ -4,10 +4,9 @@ Le MJ a déjà les règles de son système ; il veut en tirer un catalogue de so
|
|||||||
retaper. Le Core envoie UN morceau de règles (borné) et les champs du modèle de sort ; ce
|
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.
|
module ne fait que formuler le prompt.
|
||||||
|
|
||||||
Un principe tient toute la fonction : le modèle RELÈVE, il n'écrit pas. Le nom du sort est
|
Un principe tient toute la fonction : le modèle DÉSIGNE, il n'écrit pas. Il rend le nom du
|
||||||
celui du texte, la description est recopiée, et chaque sort cite un passage MOT POUR MOT :
|
sort tel qu'il est dans le texte, son niveau, son école, et les premiers mots de son bloc ;
|
||||||
le Core vérifie que le nom et le passage se retrouvent dans le texte envoyé, et écarte le
|
la description, elle, est reprise du texte par le code (cf. spell_location), mot pour mot.
|
||||||
sort sinon.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -55,21 +54,28 @@ def spell_extraction_prompt(system_name: str, section_title: str, text: str,
|
|||||||
"Règles IMPÉRATIVES :\n"
|
"Règles IMPÉRATIVES :\n"
|
||||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
'- Format exact : {"spells": [{"name": "…", "level": "…", "school": "…", '
|
'- Format exact : {"spells": [{"name": "…", "level": "…", "school": "…", '
|
||||||
'"description": "…", "values": {"Champ": "valeur"}, "excerpt": "…"}]}\n'
|
'"values": {"Champ": "valeur"}, "start": "…"}]}\n'
|
||||||
'- "name" : le nom du sort, écrit EXACTEMENT comme dans le texte.\n'
|
'- "name" : le nom du sort, écrit EXACTEMENT comme dans le texte.\n'
|
||||||
'- "level" : son niveau, rang, cercle ou palier si le texte le donne (« 1 », « Tour de '
|
'- "level" : son niveau si le texte le donne, sinon "". Écris-le TOUJOURS de la même '
|
||||||
'magie », « Rang II »), sinon "".\n'
|
"façon : un niveau numéroté par son SEUL nombre (« 1 », jamais « Niveau 1 » ni "
|
||||||
'- "school" : son école, sa liste ou sa tradition si le texte la donne, sinon "".\n'
|
"« NIVEAU 1 ») ; un sort de niveau 0 (tour de magie, cantrip, sort mineur) par "
|
||||||
'- "description" : ce que fait le sort, RECOPIÉ depuis le texte, en entier. Ne résume '
|
"« Tour de magie » si le texte est en français, « Cantrip » s'il est en anglais ; un "
|
||||||
"pas, ne traduis pas, n'ajoute rien. Laisse de côté la ligne du nom et les valeurs déjà "
|
"autre palier par le terme du texte (« Rang II »). N'y ajoute rien d'autre (ni zone, ni "
|
||||||
'rangées dans "level", "school" ou "values".\n'
|
"type, ni durée).\n"
|
||||||
'- "excerpt" : UNE phrase de la description de ce sort, COPIÉE MOT POUR MOT depuis le '
|
'- "school" : son école, sa liste ou sa tradition si le texte la donne, sinon "". Donne '
|
||||||
"texte (au moins 25 caractères), sans points de suspension ni guillemets ajoutés.\n"
|
"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 "
|
"- 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"
|
"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 "
|
"- 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"
|
"magie) : seulement les sorts eux-mêmes.\n"
|
||||||
'- Si le texte ne décrit aucun sort, renvoie {"spells": []}.\n'
|
'- Si le texte ne décrit aucun sort, renvoie {"spells": []}.\n'
|
||||||
"- Garde la langue du texte : ne traduis ni les noms ni les descriptions.\n"
|
"- Garde la langue du texte : ne traduis pas les noms.\n"
|
||||||
"Renvoie maintenant le JSON."
|
"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,18 @@ 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
|
||||||
|
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||||
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 +229,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,141 @@
|
|||||||
|
"""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
|
||||||
|
_LEADING = " \t:—–-·|"
|
||||||
|
|
||||||
|
|
||||||
|
@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, sur sa première ligne : le passage que le Core retrouve dans
|
||||||
|
le texte envoyé."""
|
||||||
|
first = next((line.strip() for line in description.splitlines() if line.strip()), "")
|
||||||
|
first = first.lstrip("#>*- ").strip() or first
|
||||||
|
if len(first) <= EXCERPT_CHARS:
|
||||||
|
return first
|
||||||
|
cut = first.rfind(" ", 0, EXCERPT_CHARS)
|
||||||
|
return first[:cut if cut > 0 else EXCERPT_CHARS]
|
||||||
|
|
||||||
|
|
||||||
|
_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 ''."""
|
||||||
|
last = section_title.split("›")[-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 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."""
|
||||||
|
if not isinstance(entries, list):
|
||||||
|
return []
|
||||||
|
found: list[tuple[int, int, dict]] = [] # (début du bloc, fin du nom, entrée)
|
||||||
|
for entry in entries:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
name = _text(entry.get("name"))
|
||||||
|
if not 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])
|
||||||
|
found.append((block_start, 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_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))
|
||||||
|
description = text[name_end:max(name_end, block_end)].strip().lstrip(_LEADING).strip()
|
||||||
|
if not description:
|
||||||
|
continue
|
||||||
|
values = entry.get("values")
|
||||||
|
seen.add(name.lower())
|
||||||
|
out.append(LocatedSpell(
|
||||||
|
name=name,
|
||||||
|
level=_text(entry.get("level")),
|
||||||
|
school=_text(entry.get("school")) or fallback_school,
|
||||||
|
description=description,
|
||||||
|
excerpt=_excerpt(description),
|
||||||
|
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:
|
||||||
|
|||||||
@@ -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,335 @@
|
|||||||
|
"""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
|
||||||
|
|
||||||
|
|
||||||
|
@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)
|
||||||
|
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)."""
|
||||||
|
column = (_column_of(line, columns) if columns else 0) if single_row[block_rank] 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] = {}
|
||||||
|
for cells in groups:
|
||||||
|
if len(cells) < 2:
|
||||||
|
continue
|
||||||
|
cells.sort(key=lambda c: c[2].x0)
|
||||||
|
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
|
||||||
|
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 _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 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 = reading_order(_gather_rows(blocks, 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
|
||||||
@@ -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([]) == []
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
"""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, 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")),
|
||||||
|
]
|
||||||
|
placed = place_lines(blocks, WIDTH, HEIGHT)
|
||||||
|
assert placed[-1].text == "Wooden Buckler | +2 | 5 gp" and placed[-1].cells == 3
|
||||||
|
|
||||||
|
|
||||||
|
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")),
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
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.")
|
||||||
@@ -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,186 @@ 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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# --- 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")
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import pytest
|
|||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
from app.api.deps import get_llm_provider
|
from app.api.deps import get_llm_provider
|
||||||
from app.api.routers.spells import _clean_spells
|
from app.application.spell_location import locate_spells
|
||||||
from app.application.prompts.spell_extraction import spell_extraction_prompt
|
from app.application.prompts.spell_extraction import spell_extraction_prompt
|
||||||
from app.main import app
|
from app.main import app
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ def test_prompt_carries_text_fields_avoided_names_and_fidelity_rules():
|
|||||||
assert "- Voile de brume" in prompt
|
assert "- Voile de brume" in prompt
|
||||||
assert "MOT POUR MOT" in prompt
|
assert "MOT POUR MOT" in prompt
|
||||||
assert "EXACTEMENT comme dans le texte" in prompt
|
assert "EXACTEMENT comme dans le texte" in prompt
|
||||||
assert "Ne résume" in prompt
|
assert "Ne recopie PAS la description" in prompt
|
||||||
assert "ne traduis" in prompt
|
assert "ne traduis" in prompt
|
||||||
assert '{"spells": []}' in prompt
|
assert '{"spells": []}' in prompt
|
||||||
|
|
||||||
@@ -68,33 +68,116 @@ def test_prompt_without_field_title_or_avoided_name():
|
|||||||
assert "DÉJÀ relevés" not in prompt
|
assert "DÉJÀ relevés" not in prompt
|
||||||
|
|
||||||
|
|
||||||
def test_clean_spells_keeps_complete_entries_and_stringifies_values():
|
_BOOK = (
|
||||||
spells = _clean_spells([
|
"## Magic › Fire Spells\n\n"
|
||||||
{"name": " Éclair ", "level": 1, "school": None, "description": " Un trait. ",
|
"CANTRIP\n\n"
|
||||||
"values": {"Portée": " 18 m ", "Coût": 2, "Vide": " ", " ": "x", "Liste": ["a"]}, "excerpt": " Un trait. "},
|
"### Flame Dart 1 Action\n\n"
|
||||||
{"name": "Sans description", "description": " ", "excerpt": "Un passage."},
|
"Range: 10. Damage: 1d10. On crit: Smoldering.\n\n"
|
||||||
{"name": "Sans passage", "description": "Un effet."},
|
"High Levels: +5 damage every 5th level.\n\n"
|
||||||
{"name": "", "description": "Un effet.", "excerpt": "Un passage."},
|
"TIER 1\n\n"
|
||||||
{"name": "Valeurs mal formées", "description": "Un effet.", "excerpt": "Un passage.", "values": ["x"]},
|
"### 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, jusqu'à la ligne qui ouvre le sort suivant : rien n'est réécrit.
|
||||||
|
assert spells[0].description == (
|
||||||
|
"1 Action\n\nRange: 10. Damage: 1d10. On crit: Smoldering.\n\nHigh Levels: +5 damage every 5th level.")
|
||||||
|
assert spells[1].description == "2 Actions\n\nRange: 10. Damage: 4d10 to a Smoldering target.\n\nUpcast: +10 damage."
|
||||||
|
assert spells[2].description == "1 Action\n\nConcentration: 1 min. Reach: 8."
|
||||||
|
assert all(spell.description in _BOOK for spell in spells)
|
||||||
|
# Le passage cité est le début de la description : le Core le retrouve dans le texte.
|
||||||
|
assert [s.excerpt for s in spells] == ["1 Action", "2 Actions", "1 Action"]
|
||||||
|
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"]
|
||||||
|
# Sans la ligne du niveau comme repère, elle reste en fin de la description précédente.
|
||||||
|
assert spells[0].description.endswith("every 5th level.\n\nTIER 1")
|
||||||
|
assert spells[1].description.startswith("2 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",
|
"pas un objet",
|
||||||
])
|
], _BOOK)
|
||||||
|
assert [s.name for s in spells] == ["Flame Dart", "Ignite"]
|
||||||
assert [s.name for s in spells] == ["Éclair", "Valeurs mal formées"]
|
assert spells[0].level == "0"
|
||||||
assert spells[0].level == "1"
|
assert spells[0].values == {"Portée": "10", "Coût": "2"}
|
||||||
assert spells[0].school == ""
|
|
||||||
assert spells[0].description == "Un trait."
|
|
||||||
assert spells[0].values == {"Portée": "18 m", "Coût": "2"}
|
|
||||||
assert spells[1].values == {}
|
assert spells[1].values == {}
|
||||||
assert _clean_spells(None) == []
|
assert locate_spells(None, _BOOK) == []
|
||||||
assert _clean_spells({"name": "x"}) == []
|
assert locate_spells({"name": "x"}, _BOOK) == []
|
||||||
|
|
||||||
|
|
||||||
def test_route_returns_cleaned_spells_with_low_temperature(client):
|
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"]
|
||||||
|
|
||||||
|
|
||||||
|
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": [
|
llm = FakeLLM(json.dumps({"spells": [
|
||||||
{"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
{"name": "Éclair de givre", "level": "1", "school": "Évocation", "values": {"Portée": "18 m"},
|
||||||
"description": "Un trait de givre frappe une cible : 2d6 dégâts de froid.",
|
"start": "### Éclair de givre",
|
||||||
"values": {"Portée": "18 m"}, "excerpt": "Un trait de givre frappe une cible"},
|
# Un modèle qui écrirait quand même une description : elle est ignorée.
|
||||||
{"name": "Incomplet"},
|
"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
|
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||||
|
|
||||||
@@ -105,10 +188,11 @@ def test_route_returns_cleaned_spells_with_low_temperature(client):
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json() == {"spells": [{
|
assert response.json() == {"spells": [{
|
||||||
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||||
"description": "Un trait de givre frappe une cible : 2d6 dégâts de froid.",
|
"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": "Un trait de givre frappe une cible"}]}
|
"values": {"Portée": "18 m"}, "excerpt": "Niveau 1 — Évocation. Portée : 18 m."}]}
|
||||||
assert llm.temperature == 0.1
|
assert llm.temperature == 0.1
|
||||||
assert llm.output_format["required"] == ["spells"]
|
assert llm.output_format["required"] == ["spells"]
|
||||||
|
assert "description" not in llm.output_format["properties"]["spells"]["items"]["properties"]
|
||||||
assert "- Voile de brume" in llm.prompt
|
assert "- Voile de brume" in llm.prompt
|
||||||
|
|
||||||
|
|
||||||
@@ -131,3 +215,14 @@ def test_route_with_no_spell_returns_empty_list(client):
|
|||||||
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json() == {"spells": []}
|
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
|
||||||
|
|||||||
+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).
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -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)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+31
-23
@@ -6,6 +6,7 @@ import com.loremind.domain.campaigncontext.generation.CampaignImportProposal;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
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.core.task.TaskExecutor;
|
import org.springframework.core.task.TaskExecutor;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -31,22 +32,18 @@ public class CampaignImportController {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(CampaignImportController.class);
|
private static final Logger log = LoggerFactory.getLogger(CampaignImportController.class);
|
||||||
|
|
||||||
/**
|
|
||||||
* Timeout SSE = durée TOTALE maximale de l'import (pas un timeout d'inactivité :
|
|
||||||
* les heartbeats ne le réarment pas). Un livre entier sur un modèle local peut
|
|
||||||
* largement dépasser 15 min → 60 min. La déconnexion du client reste détectée
|
|
||||||
* immédiatement par ailleurs (échec d'envoi → interruption de l'import).
|
|
||||||
*/
|
|
||||||
private static final long IMPORT_SSE_TIMEOUT_MS = 60 * 60 * 1000L;
|
|
||||||
|
|
||||||
private final CampaignImportService campaignImportService;
|
private final CampaignImportService campaignImportService;
|
||||||
private final TaskExecutor taskExecutor;
|
private final TaskExecutor taskExecutor;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
/** Durée totale maximale d'un import (secondes), cf. {@link ImportDeadline}. */
|
||||||
|
private final long importMaxDurationSeconds;
|
||||||
|
|
||||||
public CampaignImportController(
|
public CampaignImportController(
|
||||||
CampaignImportService campaignImportService,
|
CampaignImportService campaignImportService,
|
||||||
@Qualifier("applicationTaskExecutor") TaskExecutor taskExecutor,
|
@Qualifier("applicationTaskExecutor") TaskExecutor taskExecutor,
|
||||||
ObjectMapper objectMapper) {
|
ObjectMapper objectMapper,
|
||||||
|
@Value("${loremind.import.max-duration-seconds:14400}") long importMaxDurationSeconds) {
|
||||||
|
this.importMaxDurationSeconds = importMaxDurationSeconds;
|
||||||
this.campaignImportService = campaignImportService;
|
this.campaignImportService = campaignImportService;
|
||||||
this.taskExecutor = taskExecutor;
|
this.taskExecutor = taskExecutor;
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
@@ -58,7 +55,8 @@ public class CampaignImportController {
|
|||||||
public SseEmitter importStream(
|
public SseEmitter importStream(
|
||||||
@PathVariable String campaignId,
|
@PathVariable String campaignId,
|
||||||
@RequestParam("file") MultipartFile file) throws IOException {
|
@RequestParam("file") MultipartFile file) throws IOException {
|
||||||
SseEmitter emitter = new SseEmitter(IMPORT_SSE_TIMEOUT_MS);
|
ImportDeadline deadline = new ImportDeadline(importMaxDurationSeconds);
|
||||||
|
SseEmitter emitter = new SseEmitter(deadline.emitterTimeoutMs());
|
||||||
if (file == null || file.isEmpty()) {
|
if (file == null || file.isEmpty()) {
|
||||||
sendError(emitter, new AtomicBoolean(false), "Fichier PDF vide.");
|
sendError(emitter, new AtomicBoolean(false), "Fichier PDF vide.");
|
||||||
return emitter;
|
return emitter;
|
||||||
@@ -71,25 +69,35 @@ public class CampaignImportController {
|
|||||||
// amont (ClientGoneException remonte dans le doOnNext du WebClient →
|
// amont (ClientGoneException remonte dans le doOnNext du WebClient →
|
||||||
// annule la souscription → le Brain voit la coupure et stoppe le LLM).
|
// annule la souscription → le Brain voit la coupure et stoppe le LLM).
|
||||||
AtomicBoolean clientGone = new AtomicBoolean(false);
|
AtomicBoolean clientGone = new AtomicBoolean(false);
|
||||||
emitter.onTimeout(() -> {
|
// Dernier recours seulement (plus rien à envoyer : l'emitter est déjà terminé) :
|
||||||
// Timeout = durée totale dépassée, mais la connexion est encore vivante :
|
// la durée maximale est vérifiée par `guard`, tant que le flux peut encore parler.
|
||||||
// on envoie une vraie erreur au navigateur AVANT de fermer (sinon le flux
|
emitter.onTimeout(() -> clientGone.set(true));
|
||||||
// se termine en silence et l'UI reste figée sur la barre de progression).
|
|
||||||
sendError(emitter, clientGone,
|
|
||||||
"L'import a dépassé la durée maximale autorisée et a été interrompu. "
|
|
||||||
+ "Réessayez avec un modèle plus rapide ou un PDF plus petit.");
|
|
||||||
clientGone.set(true);
|
|
||||||
});
|
|
||||||
emitter.onError(e -> clientGone.set(true));
|
emitter.onError(e -> clientGone.set(true));
|
||||||
|
Runnable guard = () -> {
|
||||||
|
if (!clientGone.get() && deadline.expired()) {
|
||||||
|
log.warn("Import campagne (stream) interrompu : durée maximale dépassée.");
|
||||||
|
sendError(emitter, clientGone, deadline.message());
|
||||||
|
clientGone.set(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
taskExecutor.execute(() -> {
|
taskExecutor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
campaignImportService.importStructureStreaming(
|
campaignImportService.importStructureStreaming(
|
||||||
bytes, filename,
|
bytes, filename,
|
||||||
progress -> sendEvent(emitter, clientGone, "progress", progress),
|
progress -> {
|
||||||
() -> sendHeartbeat(emitter, clientGone),
|
guard.run();
|
||||||
status -> sendEvent(emitter, clientGone, "status",
|
sendEvent(emitter, clientGone, "progress", progress);
|
||||||
Map.of("message", status != null ? status : "")),
|
},
|
||||||
|
() -> {
|
||||||
|
guard.run();
|
||||||
|
sendHeartbeat(emitter, clientGone);
|
||||||
|
},
|
||||||
|
status -> {
|
||||||
|
guard.run();
|
||||||
|
sendEvent(emitter, clientGone, "status",
|
||||||
|
Map.of("message", status != null ? status : ""));
|
||||||
|
},
|
||||||
proposal -> {
|
proposal -> {
|
||||||
sendEvent(emitter, clientGone, "done", proposal);
|
sendEvent(emitter, clientGone, "done", proposal);
|
||||||
emitter.complete();
|
emitter.complete();
|
||||||
|
|||||||
+31
-22
@@ -12,6 +12,7 @@ import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
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.core.task.TaskExecutor;
|
import org.springframework.core.task.TaskExecutor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
@@ -31,25 +32,22 @@ public class GameSystemController {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(GameSystemController.class);
|
private static final Logger log = LoggerFactory.getLogger(GameSystemController.class);
|
||||||
|
|
||||||
/**
|
|
||||||
* Timeout SSE = durée TOTALE maximale de l'import (pas un timeout d'inactivité :
|
|
||||||
* les heartbeats ne le réarment pas). Un livre entier sur un modèle local peut
|
|
||||||
* largement dépasser 15 min → 60 min. La déconnexion du client reste détectée
|
|
||||||
* immédiatement par ailleurs (échec d'envoi → interruption de l'import).
|
|
||||||
*/
|
|
||||||
private static final long IMPORT_SSE_TIMEOUT_MS = 60 * 60 * 1000L;
|
|
||||||
|
|
||||||
private final GameSystemService gameSystemService;
|
private final GameSystemService gameSystemService;
|
||||||
private final GameSystemMapper gameSystemMapper;
|
private final GameSystemMapper gameSystemMapper;
|
||||||
private final TemplateFieldMapper templateFieldMapper;
|
private final TemplateFieldMapper templateFieldMapper;
|
||||||
private final TaskExecutor taskExecutor;
|
private final TaskExecutor taskExecutor;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
/** Durée totale maximale d'un import (secondes), cf. {@link ImportDeadline}. */
|
||||||
|
private final long importMaxDurationSeconds;
|
||||||
|
|
||||||
public GameSystemController(GameSystemService gameSystemService,
|
public GameSystemController(GameSystemService gameSystemService,
|
||||||
GameSystemMapper gameSystemMapper,
|
GameSystemMapper gameSystemMapper,
|
||||||
TemplateFieldMapper templateFieldMapper,
|
TemplateFieldMapper templateFieldMapper,
|
||||||
@Qualifier("applicationTaskExecutor") TaskExecutor taskExecutor,
|
@Qualifier("applicationTaskExecutor") TaskExecutor taskExecutor,
|
||||||
ObjectMapper objectMapper) {
|
ObjectMapper objectMapper,
|
||||||
|
@Value("${loremind.import.max-duration-seconds:14400}") long importMaxDurationSeconds) {
|
||||||
|
this.importMaxDurationSeconds = importMaxDurationSeconds;
|
||||||
this.gameSystemService = gameSystemService;
|
this.gameSystemService = gameSystemService;
|
||||||
this.gameSystemMapper = gameSystemMapper;
|
this.gameSystemMapper = gameSystemMapper;
|
||||||
this.templateFieldMapper = templateFieldMapper;
|
this.templateFieldMapper = templateFieldMapper;
|
||||||
@@ -134,7 +132,8 @@ public class GameSystemController {
|
|||||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||||
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
public SseEmitter importRulesStream(@RequestParam("file") MultipartFile file) throws IOException {
|
public SseEmitter importRulesStream(@RequestParam("file") MultipartFile file) throws IOException {
|
||||||
SseEmitter emitter = new SseEmitter(IMPORT_SSE_TIMEOUT_MS);
|
ImportDeadline deadline = new ImportDeadline(importMaxDurationSeconds);
|
||||||
|
SseEmitter emitter = new SseEmitter(deadline.emitterTimeoutMs());
|
||||||
if (file == null || file.isEmpty()) {
|
if (file == null || file.isEmpty()) {
|
||||||
sendImportError(emitter, new AtomicBoolean(false), "Fichier PDF vide.");
|
sendImportError(emitter, new AtomicBoolean(false), "Fichier PDF vide.");
|
||||||
return emitter;
|
return emitter;
|
||||||
@@ -149,25 +148,35 @@ public class GameSystemController {
|
|||||||
// amont (l'exception ClientGone remonte dans le doOnNext du WebClient →
|
// amont (l'exception ClientGone remonte dans le doOnNext du WebClient →
|
||||||
// annule la souscription → le Brain voit la coupure et stoppe le LLM).
|
// annule la souscription → le Brain voit la coupure et stoppe le LLM).
|
||||||
AtomicBoolean clientGone = new AtomicBoolean(false);
|
AtomicBoolean clientGone = new AtomicBoolean(false);
|
||||||
emitter.onTimeout(() -> {
|
// Dernier recours seulement (plus rien à envoyer : l'emitter est déjà terminé) :
|
||||||
// Timeout = durée totale dépassée, mais la connexion est encore vivante :
|
// la durée maximale est vérifiée par `guard`, tant que le flux peut encore parler.
|
||||||
// on envoie une vraie erreur au navigateur AVANT de fermer (sinon le flux
|
emitter.onTimeout(() -> clientGone.set(true));
|
||||||
// se termine en silence et l'UI reste figée sur la barre de progression).
|
|
||||||
sendImportError(emitter, clientGone,
|
|
||||||
"L'import a dépassé la durée maximale autorisée et a été interrompu. "
|
|
||||||
+ "Réessayez avec un modèle plus rapide ou un PDF plus petit.");
|
|
||||||
clientGone.set(true);
|
|
||||||
});
|
|
||||||
emitter.onError(e -> clientGone.set(true));
|
emitter.onError(e -> clientGone.set(true));
|
||||||
|
Runnable guard = () -> {
|
||||||
|
if (!clientGone.get() && deadline.expired()) {
|
||||||
|
log.warn("Import de règles (stream) interrompu : durée maximale dépassée.");
|
||||||
|
sendImportError(emitter, clientGone, deadline.message());
|
||||||
|
clientGone.set(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
taskExecutor.execute(() -> {
|
taskExecutor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
gameSystemService.importRulesFromPdfStreaming(
|
gameSystemService.importRulesFromPdfStreaming(
|
||||||
bytes, filename,
|
bytes, filename,
|
||||||
progress -> sendImportEvent(emitter, clientGone, "progress", progress),
|
progress -> {
|
||||||
() -> sendImportHeartbeat(emitter, clientGone),
|
guard.run();
|
||||||
status -> sendImportEvent(emitter, clientGone, "status",
|
sendImportEvent(emitter, clientGone, "progress", progress);
|
||||||
Map.of("message", status != null ? status : "")),
|
},
|
||||||
|
() -> {
|
||||||
|
guard.run();
|
||||||
|
sendImportHeartbeat(emitter, clientGone);
|
||||||
|
},
|
||||||
|
status -> {
|
||||||
|
guard.run();
|
||||||
|
sendImportEvent(emitter, clientGone, "status",
|
||||||
|
Map.of("message", status != null ? status : ""));
|
||||||
|
},
|
||||||
result -> {
|
result -> {
|
||||||
sendImportEvent(emitter, clientGone, "done", result);
|
sendImportEvent(emitter, clientGone, "done", result);
|
||||||
emitter.complete();
|
emitter.complete();
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Durée totale maximale d'un import streamé (règles, campagne).
|
||||||
|
* <p>
|
||||||
|
* Le délai d'un {@code SseEmitter} ne peut pas servir à prévenir le navigateur : quand il
|
||||||
|
* expire, l'emitter est déjà marqué terminé et tout envoi lève « ResponseBodyEmitter has
|
||||||
|
* already completed » — le flux se coupait sans explication (« Error in input stream » côté
|
||||||
|
* navigateur). L'échéance est donc vérifiée par le contrôleur à chaque évènement reçu du
|
||||||
|
* Brain (au moins un keep-alive toutes les 15 s), tant que l'emitter peut encore envoyer.
|
||||||
|
* Le délai de l'emitter, un peu plus long, ne reste qu'en dernier recours.
|
||||||
|
*/
|
||||||
|
final class ImportDeadline {
|
||||||
|
|
||||||
|
/** Marge du délai de l'emitter par rapport à l'échéance vérifiée par le contrôleur. */
|
||||||
|
private static final long EMITTER_MARGIN_MS = TimeUnit.MINUTES.toMillis(5);
|
||||||
|
|
||||||
|
private final long startedAt = System.nanoTime();
|
||||||
|
private final long maxSeconds;
|
||||||
|
|
||||||
|
ImportDeadline(long maxSeconds) {
|
||||||
|
this.maxSeconds = Math.max(0, maxSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean expired() {
|
||||||
|
return System.nanoTime() - startedAt >= TimeUnit.SECONDS.toNanos(maxSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Délai à donner à l'emitter : l'échéance plus une marge. */
|
||||||
|
long emitterTimeoutMs() {
|
||||||
|
return TimeUnit.SECONDS.toMillis(maxSeconds) + EMITTER_MARGIN_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Message montré à l'utilisateur quand l'échéance est dépassée. */
|
||||||
|
String message() {
|
||||||
|
long minutes = Math.max(1, TimeUnit.SECONDS.toMinutes(maxSeconds));
|
||||||
|
String duration = minutes >= 120 ? (minutes / 60) + " h" : minutes + " min";
|
||||||
|
return "L'import a dépassé la durée maximale autorisée (" + duration + ") et a été interrompu. "
|
||||||
|
+ "Réessayez avec un modèle plus rapide ou un PDF plus petit.";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,9 @@ brain.timeout-seconds=${BRAIN_TIMEOUT_SECONDS:300}
|
|||||||
# Timeout dedie a l'import de PDF (regles/campagne) : map-reduce LLM sur un
|
# Timeout dedie a l'import de PDF (regles/campagne) : map-reduce LLM sur un
|
||||||
# livre entier => potentiellement plusieurs minutes. Surchargeable via env.
|
# livre entier => potentiellement plusieurs minutes. Surchargeable via env.
|
||||||
brain.import-timeout-seconds=${BRAIN_IMPORT_TIMEOUT_SECONDS:600}
|
brain.import-timeout-seconds=${BRAIN_IMPORT_TIMEOUT_SECONDS:600}
|
||||||
|
# Duree totale maximale d'un import de PDF (regles, campagne), en secondes. Garde-fou
|
||||||
|
# seulement : un livre entier sur un modele lent peut demander plus d'une heure.
|
||||||
|
loremind.import.max-duration-seconds=${IMPORT_MAX_DURATION_SECONDS:14400}
|
||||||
|
|
||||||
# Secret partage Core <-> Brain (auth inter-service via entete X-Internal-Secret).
|
# Secret partage Core <-> Brain (auth inter-service via entete X-Internal-Secret).
|
||||||
# OBLIGATOIRE en prod : si non defini, le Brain rejette toutes les requetes (fail-closed).
|
# OBLIGATOIRE en prod : si non defini, le Brain rejette toutes les requetes (fail-closed).
|
||||||
|
|||||||
@@ -382,6 +382,89 @@ class BrainCampaignImportClientTest {
|
|||||||
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
assertTrue(c.error.get().getMessage().contains("interrompu"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- filet : campagne découpée avant les passes de l'IA ----------
|
||||||
|
|
||||||
|
private static final String EXTRACTED = "event:extracted\ndata:{\"arcs\":[{\"name\":\"Aventure principale\","
|
||||||
|
+ "\"type\":\"LINEAR\",\"chapters\":[{\"name\":\"La crypte\",\"scenes\":[{\"name\":\"Entrée\","
|
||||||
|
+ "\"description\":\"Une grille.\",\"gm_notes\":\"Texte du livre.\",\"rooms\":[]}]}]}],"
|
||||||
|
+ "\"npcs\":[],\"split_method\":\"bookmarks\"}\n\n";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur_du_brain_apres_le_decoupage_livre_la_campagne_avec_le_texte_du_livre() {
|
||||||
|
String sse = EXTRACTED + "event:error\ndata:{\"message\":\"fournisseur en panne\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNull(c.error.get(), "le découpage est livré : pas d'erreur");
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
var scene = c.done.get().arcs().get(0).chapters().get(0).scenes().get(0);
|
||||||
|
assertEquals("Entrée", scene.name());
|
||||||
|
assertEquals("Texte du livre.", scene.gmNotes());
|
||||||
|
assertTrue(c.done.get().npcs().isEmpty());
|
||||||
|
// Le compte rendu dit que l'IA n'a pas abouti, et d'où vient le découpage.
|
||||||
|
assertTrue(c.done.get().outcome().aiInterrupted());
|
||||||
|
assertEquals("bookmarks", c.done.get().outcome().splitMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void done_porte_le_compte_rendu_de_l_import_par_la_structure() {
|
||||||
|
String sse = EXTRACTED + "event:done\ndata:{\"arcs\":[{\"name\":\"Solo\"}],\"npcs\":[],"
|
||||||
|
+ "\"split_method\":\"headings\",\"source_language\":\"en\",\"untranslated\":4,\"skipped\":2}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
var outcome = c.done.get().outcome();
|
||||||
|
assertEquals("headings", outcome.splitMethod());
|
||||||
|
assertEquals("en", outcome.sourceLanguage());
|
||||||
|
assertEquals(4, outcome.untranslated());
|
||||||
|
assertEquals(2, outcome.skippedAids());
|
||||||
|
assertFalse(outcome.aiInterrupted());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void done_sans_methode_de_decoupage_n_a_pas_de_compte_rendu() {
|
||||||
|
// Découpage par l'IA (PDF sans structure) : rien à signaler à la revue.
|
||||||
|
String sse = "event:done\ndata:" + doneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNull(c.done.get().outcome());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void flux_coupe_apres_le_decoupage_livre_la_campagne_avec_le_texte_du_livre() {
|
||||||
|
String sse = EXTRACTED + "event:progress\ndata:{\"current\":1,\"total\":3}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNull(c.error.get());
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertEquals("La crypte", c.done.get().arcs().get(0).chapters().get(0).name());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void done_remplace_le_decoupage_par_la_campagne_complete() {
|
||||||
|
String sse = EXTRACTED + "event:done\ndata:" + doneJson() + "\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNull(c.error.get());
|
||||||
|
assertEquals("Acte I", c.done.get().arcs().get(0).name());
|
||||||
|
assertEquals(1, c.done.get().npcs().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decoupage_vide_ne_sert_pas_de_filet() {
|
||||||
|
String sse = "event:extracted\ndata:{\"arcs\":[],\"npcs\":[]}\n\n"
|
||||||
|
+ "event:error\ndata:{\"message\":\"rien à livrer\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
c.invoke(clientReturning(sse));
|
||||||
|
|
||||||
|
assertNull(c.done.get());
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("rien à livrer"));
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- erreur de transport ----------------------------------------
|
// ---------- erreur de transport ----------------------------------------
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -370,6 +370,90 @@ class BrainRulesImportClientTest {
|
|||||||
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
|
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Règles extraites conservées si la traduction échoue ------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_carriesHowTheBookWasSplit() {
|
||||||
|
String sse = "event:extracted" + NL + "data:{" + Q + "sections" + Q + ":{" + Q + "Combat" + Q + ":" + Q + "d20" + Q + "},"
|
||||||
|
+ Q + "source_language" + Q + ":" + Q + "en" + Q + "," + Q + "split_method" + Q + ":" + Q + "bookmarks" + Q + "}" + NL + NL
|
||||||
|
+ "event:error" + NL + "data:{" + Q + "message" + Q + ":" + Q + "traduction KO" + Q + "}" + NL + NL;
|
||||||
|
Collector rescued = new Collector();
|
||||||
|
runStreaming(sse, rescued);
|
||||||
|
// Règles livrées sans traduction : la méthode de découpage est celle de l'extraction.
|
||||||
|
assertEquals("bookmarks", rescued.done.get().splitMethod());
|
||||||
|
|
||||||
|
String done = "event:done" + NL + "data:{" + Q + "sections" + Q + ":{" + Q + "Combat" + Q + ":" + Q + "d20" + Q + "},"
|
||||||
|
+ Q + "page_count" + Q + ":2," + Q + "ocr_page_count" + Q + ":0," + Q + "split_method" + Q + ":" + Q + "headings" + Q + "}" + NL + NL;
|
||||||
|
Collector finished = new Collector();
|
||||||
|
runStreaming(done, finished);
|
||||||
|
assertEquals("headings", finished.done.get().splitMethod());
|
||||||
|
|
||||||
|
// Brain antérieur : le champ est absent.
|
||||||
|
Collector old = new Collector();
|
||||||
|
runStreaming("event:done" + NL + "data:{" + Q + "sections" + Q + ":{}," + Q + "page_count" + Q + ":0," + Q + "ocr_page_count" + Q + ":0}" + NL + NL, old);
|
||||||
|
assertNull(old.done.get().splitMethod());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String NL = String.valueOf((char) 10);
|
||||||
|
private static final String Q = String.valueOf((char) 34);
|
||||||
|
|
||||||
|
private static final String EXTRACTED = "event:extracted\ndata:{\"sections\":{\"Combat\":\"d20 roll\"},"
|
||||||
|
+ "\"source_language\":\"en\",\"page_count\":29,\"ocr_page_count\":2}\n\n";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_brainErrorAfterExtraction_deliversTheRulesInTheirOwnLanguage() {
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(EXTRACTED + "event:error\ndata:{\"message\":\"traduction KO\"}\n\n", c);
|
||||||
|
|
||||||
|
assertNull(c.error.get());
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertEquals(Map.of("Combat", "d20 roll"), c.done.get().sections());
|
||||||
|
assertEquals(29, c.done.get().pageCount());
|
||||||
|
assertEquals(2, c.done.get().ocrPageCount());
|
||||||
|
assertEquals("en", c.done.get().sourceLanguage());
|
||||||
|
// Seule la langue du livre est fournie : l'autre onglet reste vide.
|
||||||
|
assertEquals(Map.of("en", Map.of("Combat", "d20 roll")), c.done.get().sectionsByLanguage());
|
||||||
|
assertTrue(c.done.get().untranslatedTitles().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_streamCutAfterExtraction_deliversTheRulesInTheirOwnLanguage() {
|
||||||
|
// Flux coupé pendant la traduction (ni done ni error) : les règles ne sont pas perdues.
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(EXTRACTED + "event:heartbeat\ndata:{}\n\n", c);
|
||||||
|
|
||||||
|
assertNull(c.error.get());
|
||||||
|
assertNotNull(c.done.get());
|
||||||
|
assertEquals(Map.of("Combat", "d20 roll"), c.done.get().sections());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_emptyExtraction_isNotARescue() {
|
||||||
|
String sse = "event:extracted\ndata:{\"sections\":{},\"source_language\":\"en\"}\n\n"
|
||||||
|
+ "event:error\ndata:{\"message\":\"rien d'exploitable\"}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertNull(c.done.get());
|
||||||
|
assertNotNull(c.error.get());
|
||||||
|
assertTrue(c.error.get().getMessage().contains("rien d'exploitable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void streaming_done_replacesTheExtractionAndListsTheUntranslatedSections() {
|
||||||
|
String sse = EXTRACTED + "event:done\ndata:{\"sections\":{\"Combat\":\"d20 roll\",\"Magic\":\"spells\"},"
|
||||||
|
+ "\"page_count\":29,\"ocr_page_count\":2,\"source_language\":\"en\","
|
||||||
|
+ "\"sections_by_language\":{\"en\":{\"Combat\":\"d20 roll\",\"Magic\":\"spells\"},"
|
||||||
|
+ "\"fr\":{\"Combat\":\"jet de d20\",\"Magic\":\"spells\"}},\"untranslated\":[\"Magic\"]}\n\n";
|
||||||
|
Collector c = new Collector();
|
||||||
|
runStreaming(sse, c);
|
||||||
|
|
||||||
|
assertNull(c.error.get());
|
||||||
|
assertEquals(2, c.done.get().sections().size());
|
||||||
|
assertEquals(List.of("Magic"), c.done.get().untranslatedTitles());
|
||||||
|
assertEquals("spells", c.done.get().sectionsByLanguage().get("fr").get("Magic"));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Livre entier en deux langues : l'évènement {@code done} dépasse largement les 256 Ko
|
* Livre entier en deux langues : l'évènement {@code done} dépasse largement les 256 Ko
|
||||||
* par défaut de WebClient. Vrai serveur HTTP local (une ExchangeFunction simulée ne
|
* par défaut de WebClient. Vrai serveur HTTP local (une ExchangeFunction simulée ne
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ class CampaignImportControllerUnitTest {
|
|||||||
/** Exécuteur synchrone : la tâche d'import tourne dans le thread du test. */
|
/** Exécuteur synchrone : la tâche d'import tourne dans le thread du test. */
|
||||||
private final TaskExecutor inlineExecutor = Runnable::run;
|
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||||
private final CampaignImportController controller =
|
private final CampaignImportController controller =
|
||||||
new CampaignImportController(service, inlineExecutor, new ObjectMapper());
|
new CampaignImportController(service, inlineExecutor, new ObjectMapper(), 3600);
|
||||||
|
|
||||||
private static CampaignImportProgress progress() {
|
private static CampaignImportProgress progress() {
|
||||||
return new CampaignImportProgress(1, 1, 0, 0, 0, 0, 0, 0);
|
return new CampaignImportProgress(1, 1, 0, 0, 0, 0, 0, 0);
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ class GameSystemControllerUnitTest {
|
|||||||
private final TaskExecutor inlineExecutor = Runnable::run;
|
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||||
private final GameSystemController controller = new GameSystemController(
|
private final GameSystemController controller = new GameSystemController(
|
||||||
service, mock(GameSystemMapper.class), mock(TemplateFieldMapper.class),
|
service, mock(GameSystemMapper.class), mock(TemplateFieldMapper.class),
|
||||||
inlineExecutor, new ObjectMapper());
|
inlineExecutor, new ObjectMapper(), 3600);
|
||||||
|
|
||||||
private static RulesImportProgress progress() {
|
private static RulesImportProgress progress() {
|
||||||
return new RulesImportProgress(1, 1, 0, 0, List.of());
|
return new RulesImportProgress(1, 1, 0, 0, List.of());
|
||||||
|
|||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.loremind.application.campaigncontext.CampaignImportService;
|
||||||
|
import com.loremind.application.gamesystemcontext.GameSystemService;
|
||||||
|
import com.loremind.domain.campaigncontext.generation.CampaignImportProgress;
|
||||||
|
import com.loremind.domain.gamesystemcontext.RulesImportProgress;
|
||||||
|
import com.loremind.infrastructure.web.mapper.GameSystemMapper;
|
||||||
|
import com.loremind.infrastructure.web.mapper.TemplateFieldMapper;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.core.task.TaskExecutor;
|
||||||
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.containsString;
|
||||||
|
import static org.hamcrest.Matchers.not;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Durée maximale d'un import streamé : le navigateur doit recevoir un évènement
|
||||||
|
* {@code error} lisible, pas une coupure brute du flux (« Error in input stream »), et
|
||||||
|
* l'import amont doit s'arrêter. Contrôleurs montés à la main avec une durée nulle :
|
||||||
|
* l'échéance est dépassée dès le premier évènement.
|
||||||
|
*/
|
||||||
|
class ImportDeadlineTest {
|
||||||
|
|
||||||
|
/** Exécuteur synchrone : la tâche d'import tourne dans le thread de la requête. */
|
||||||
|
private final TaskExecutor inlineExecutor = Runnable::run;
|
||||||
|
private final MockMultipartFile pdf = new MockMultipartFile(
|
||||||
|
"file", "livre.pdf", "application/pdf", new byte[]{1, 2, 3});
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rulesImport_pastTheMaximumDuration_tellsTheBrowserAndStopsTheImport() throws Exception {
|
||||||
|
GameSystemService service = mock(GameSystemService.class);
|
||||||
|
AtomicBoolean upstreamStopped = new AtomicBoolean(false);
|
||||||
|
doAnswer(inv -> {
|
||||||
|
Consumer<RulesImportProgress> onProgress = inv.getArgument(2);
|
||||||
|
Runnable onHeartbeat = inv.getArgument(3);
|
||||||
|
// Le premier évènement dépasse l'échéance : l'exception remonte au flux amont.
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> onProgress.accept(new RulesImportProgress(1, 4, 29, 0, List.of("Combat"))));
|
||||||
|
assertThrows(RuntimeException.class, onHeartbeat::run);
|
||||||
|
upstreamStopped.set(true);
|
||||||
|
return null;
|
||||||
|
}).when(service).importRulesFromPdfStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||||
|
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new GameSystemController(
|
||||||
|
service, mock(GameSystemMapper.class), mock(TemplateFieldMapper.class),
|
||||||
|
inlineExecutor, new ObjectMapper(), 0)).build();
|
||||||
|
|
||||||
|
MvcResult result = mockMvc.perform(multipart("/api/game-systems/import-rules/stream").file(pdf))
|
||||||
|
.andExpect(request().asyncStarted())
|
||||||
|
.andReturn();
|
||||||
|
|
||||||
|
mockMvc.perform(asyncDispatch(result))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().string(containsString("event:error")))
|
||||||
|
.andExpect(content().string(containsString("durée maximale")))
|
||||||
|
.andExpect(content().string(not(containsString("event:progress"))));
|
||||||
|
assertTrue(upstreamStopped.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void campaignImport_pastTheMaximumDuration_tellsTheBrowserAndStopsTheImport() throws Exception {
|
||||||
|
CampaignImportService service = mock(CampaignImportService.class);
|
||||||
|
AtomicBoolean upstreamStopped = new AtomicBoolean(false);
|
||||||
|
doAnswer(inv -> {
|
||||||
|
Consumer<CampaignImportProgress> onProgress = inv.getArgument(2);
|
||||||
|
Consumer<String> onStatus = inv.getArgument(4);
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> onProgress.accept(new CampaignImportProgress(1, 4, 0, 0, 0, 0, 0, 0)));
|
||||||
|
assertThrows(RuntimeException.class, () -> onStatus.accept("nouvel essai"));
|
||||||
|
upstreamStopped.set(true);
|
||||||
|
return null;
|
||||||
|
}).when(service).importStructureStreaming(any(), any(), any(), any(), any(), any(), any());
|
||||||
|
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new CampaignImportController(
|
||||||
|
service, inlineExecutor, new ObjectMapper(), 0)).build();
|
||||||
|
|
||||||
|
MvcResult result = mockMvc.perform(multipart("/api/campaigns/12/import-structure/stream").file(pdf))
|
||||||
|
.andExpect(request().asyncStarted())
|
||||||
|
.andReturn();
|
||||||
|
|
||||||
|
mockMvc.perform(asyncDispatch(result))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().string(containsString("event:error")))
|
||||||
|
.andExpect(content().string(containsString("durée maximale")));
|
||||||
|
assertTrue(upstreamStopped.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deadline_isNotReachedWithinTheAllowedDuration() {
|
||||||
|
ImportDeadline deadline = new ImportDeadline(14_400);
|
||||||
|
assertFalse(deadline.expired());
|
||||||
|
// Le délai de l'emitter reste au-delà de l'échéance : il ne sert qu'en dernier recours.
|
||||||
|
assertTrue(deadline.emitterTimeoutMs() > 14_400_000L);
|
||||||
|
assertTrue(deadline.message().contains("4 h"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deadline_messageGivesShortDurationsInMinutes() {
|
||||||
|
assertTrue(new ImportDeadline(1_800).message().contains("30 min"));
|
||||||
|
assertTrue(new ImportDeadline(-5).expired());
|
||||||
|
assertEquals(new ImportDeadline(0).emitterTimeoutMs(), new ImportDeadline(-5).emitterTimeoutMs());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { importOutcomeNotes } from './campaign-import-notes.util';
|
||||||
|
import { CampaignImportOutcome } from '../../../services/campaign-import.model';
|
||||||
|
|
||||||
|
const outcome = (over: Partial<CampaignImportOutcome> = {}): CampaignImportOutcome => ({
|
||||||
|
splitMethod: 'bookmarks', sourceLanguage: 'fr', untranslated: 0, skippedAids: 0, aiInterrupted: false, ...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('importOutcomeNotes', () => {
|
||||||
|
it("ne dit rien quand l'IA a fait le découpage (pas de compte rendu)", () => {
|
||||||
|
expect(importOutcomeNotes(null)).toEqual([]);
|
||||||
|
expect(importOutcomeNotes(undefined)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dit d'où vient le découpage", () => {
|
||||||
|
expect(importOutcomeNotes(outcome())).toEqual([{ key: 'campaignImport.noteSplitBookmarks' }]);
|
||||||
|
expect(importOutcomeNotes(outcome({ splitMethod: 'headings' })))
|
||||||
|
.toEqual([{ key: 'campaignImport.noteSplitHeadings' }]);
|
||||||
|
expect(importOutcomeNotes(outcome({ splitMethod: 'autre' }))).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('signale les aides manquantes et la traduction incomplète', () => {
|
||||||
|
expect(importOutcomeNotes(outcome({ skippedAids: 2, untranslated: 5 })).slice(1)).toEqual([
|
||||||
|
{ key: 'campaignImport.noteSkippedAids', params: { n: 2 } },
|
||||||
|
{ key: 'campaignImport.noteUntranslated', params: { n: 5 } },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('une IA interrompue se dit en une seule note', () => {
|
||||||
|
expect(importOutcomeNotes(outcome({ aiInterrupted: true, splitMethod: null, untranslated: 3 })))
|
||||||
|
.toEqual([{ key: 'campaignImport.noteAiInterrupted' }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { CampaignImportOutcome } from '../../../services/campaign-import.model';
|
||||||
|
|
||||||
|
/** Une note à afficher au-dessus de l'arbre : clé de traduction et ses paramètres. */
|
||||||
|
export interface ImportNote {
|
||||||
|
key: string;
|
||||||
|
params?: Record<string, number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SPLIT_NOTES: Record<string, string> = {
|
||||||
|
bookmarks: 'campaignImport.noteSplitBookmarks',
|
||||||
|
headings: 'campaignImport.noteSplitHeadings',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ce qu'il faut dire à l'utilisateur sur l'import qu'il s'apprête à réviser : d'où vient le
|
||||||
|
* découpage (et que le texte est celui du livre), puis ce que l'IA n'a pas pu faire.
|
||||||
|
* Aucune note quand l'IA a reconstruit elle-même l'arborescence (pas de compte rendu).
|
||||||
|
*/
|
||||||
|
export function importOutcomeNotes(outcome: CampaignImportOutcome | null | undefined): ImportNote[] {
|
||||||
|
if (!outcome) return [];
|
||||||
|
const notes: ImportNote[] = [];
|
||||||
|
const split = SPLIT_NOTES[outcome.splitMethod ?? ''];
|
||||||
|
if (split) notes.push({ key: split });
|
||||||
|
if (outcome.aiInterrupted) {
|
||||||
|
// Rien d'autre à détailler : ni aides ni traduction n'ont été gardées.
|
||||||
|
notes.push({ key: 'campaignImport.noteAiInterrupted' });
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
|
if (outcome.skippedAids > 0) {
|
||||||
|
notes.push({ key: 'campaignImport.noteSkippedAids', params: { n: outcome.skippedAids } });
|
||||||
|
}
|
||||||
|
if (outcome.untranslated > 0) {
|
||||||
|
notes.push({ key: 'campaignImport.noteUntranslated', params: { n: outcome.untranslated } });
|
||||||
|
}
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
@@ -51,6 +51,9 @@
|
|||||||
<p class="review-summary">
|
<p class="review-summary">
|
||||||
<span [innerHTML]="'campaignImport.summaryToCreate' | translate:{ arcs: arcCount, chapters: chapterCount, scenes: sceneCount }"></span>@if (npcs.length > 0) {<span [innerHTML]="'campaignImport.summaryNpcs' | translate:{ npcs: npcCount }"></span>}<span [innerHTML]="'campaignImport.summaryHint' | translate"></span>
|
<span [innerHTML]="'campaignImport.summaryToCreate' | translate:{ arcs: arcCount, chapters: chapterCount, scenes: sceneCount }"></span>@if (npcs.length > 0) {<span [innerHTML]="'campaignImport.summaryNpcs' | translate:{ npcs: npcCount }"></span>}<span [innerHTML]="'campaignImport.summaryHint' | translate"></span>
|
||||||
</p>
|
</p>
|
||||||
|
@for (note of importNotes; track note) {
|
||||||
|
<p class="import-note">{{ note }}</p>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="tree">
|
<div class="tree">
|
||||||
<!-- Arc -->
|
<!-- Arc -->
|
||||||
@@ -162,8 +165,9 @@
|
|||||||
<div class="room-row">
|
<div class="room-row">
|
||||||
<input type="text" class="room-name" [(ngModel)]="room.name"
|
<input type="text" class="room-name" [(ngModel)]="room.name"
|
||||||
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.roomPlaceholder' | translate" />
|
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.roomPlaceholder' | translate" />
|
||||||
<input type="text" class="room-field" [(ngModel)]="room.description"
|
<!-- Zone de texte : la description d'une salle est le texte du livre (plusieurs paragraphes). -->
|
||||||
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'common.description' | translate" />
|
<textarea class="room-field room-desc" [(ngModel)]="room.description" rows="1"
|
||||||
|
[name]="'room-desc-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'common.description' | translate"></textarea>
|
||||||
<input type="text" class="room-field" [(ngModel)]="room.enemies"
|
<input type="text" class="room-field" [(ngModel)]="room.enemies"
|
||||||
[name]="'room-en-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.enemiesPlaceholder' | translate" />
|
[name]="'room-en-' + ai + '-' + ci + '-' + si + '-' + ri" [placeholder]="'campaignImport.enemiesPlaceholder' | translate" />
|
||||||
<input type="text" class="room-field" [(ngModel)]="room.loot"
|
<input type="text" class="room-field" [(ngModel)]="room.loot"
|
||||||
|
|||||||
@@ -114,6 +114,17 @@
|
|||||||
// --- Revue (arbre) ----------------------------------------------------------
|
// --- Revue (arbre) ----------------------------------------------------------
|
||||||
.review-summary { margin: 0 0 1rem; color: #d1d5db; font-size: 0.9rem; strong { color: #fff; } em { color: #9ca3af; font-style: italic; } }
|
.review-summary { margin: 0 0 1rem; color: #d1d5db; font-size: 0.9rem; strong { color: #fff; } em { color: #9ca3af; font-style: italic; } }
|
||||||
|
|
||||||
|
.import-note {
|
||||||
|
margin: -0.4rem 0 1rem;
|
||||||
|
padding: 0.55rem 0.8rem;
|
||||||
|
background: rgba(108, 99, 255, 0.12);
|
||||||
|
border: 1px solid rgba(108, 99, 255, 0.35);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #c4b5fd;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
// Nœuds déjà présents dans la campagne : grisés, lecture seule.
|
// Nœuds déjà présents dans la campagne : grisés, lecture seule.
|
||||||
.existing-node {
|
.existing-node {
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
@@ -283,7 +294,7 @@
|
|||||||
|
|
||||||
.room-row {
|
.room-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: flex-start;
|
||||||
gap: 0.35rem;
|
gap: 0.35rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -300,6 +311,13 @@
|
|||||||
|
|
||||||
.room-name { flex: 0 0 22%; }
|
.room-name { flex: 0 0 22%; }
|
||||||
.room-field { flex: 1; min-width: 0; }
|
.room-field { flex: 1; min-width: 0; }
|
||||||
|
.room-desc {
|
||||||
|
flex: 2;
|
||||||
|
font-family: inherit;
|
||||||
|
line-height: 1.35;
|
||||||
|
min-height: 1.75rem;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
.scene-fields {
|
.scene-fields {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { CampaignSidebarService } from '../../../services/campaign-sidebar.servi
|
|||||||
import { PageTitleService } from '../../../services/page-title.service';
|
import { PageTitleService } from '../../../services/page-title.service';
|
||||||
import { ArcKind, ArcProposal, ChapterProposal, NpcProposal, SceneProposal } from '../../../services/campaign-import.model';
|
import { ArcKind, ArcProposal, ChapterProposal, NpcProposal, SceneProposal } from '../../../services/campaign-import.model';
|
||||||
import { CampaignImportProposal } from '../../../services/campaign-import.model';
|
import { CampaignImportProposal } from '../../../services/campaign-import.model';
|
||||||
|
import { importOutcomeNotes } from './campaign-import-notes.util';
|
||||||
import { loadCampaignTreeData, CampaignTreeData } from '../../campaign-tree.helper';
|
import { loadCampaignTreeData, CampaignTreeData } from '../../campaign-tree.helper';
|
||||||
import { of } from 'rxjs';
|
import { of } from 'rxjs';
|
||||||
import { catchError } from 'rxjs/operators';
|
import { catchError } from 'rxjs/operators';
|
||||||
@@ -97,6 +98,8 @@ export class CampaignImportComponent implements OnInit {
|
|||||||
importStatus: string | null = null;
|
importStatus: string | null = null;
|
||||||
importCounts: { arcs: number; chapters: number; scenes: number; npcs: number } | null = null;
|
importCounts: { arcs: number; chapters: number; scenes: number; npcs: number } | null = null;
|
||||||
importError: string | null = null;
|
importError: string | null = null;
|
||||||
|
/** Ce qu'il faut savoir sur l'import, affiché au-dessus de l'arbre (découpage, traduction…). */
|
||||||
|
importNotes: string[] = [];
|
||||||
/** Vrai une fois la proposition reçue (on affiche l'arbre éditable). */
|
/** Vrai une fois la proposition reçue (on affiche l'arbre éditable). */
|
||||||
reviewing = false;
|
reviewing = false;
|
||||||
|
|
||||||
@@ -161,6 +164,7 @@ export class CampaignImportComponent implements OnInit {
|
|||||||
this.importProgress = null;
|
this.importProgress = null;
|
||||||
this.importStatus = null;
|
this.importStatus = null;
|
||||||
this.importCounts = null;
|
this.importCounts = null;
|
||||||
|
this.importNotes = [];
|
||||||
this.tree = [];
|
this.tree = [];
|
||||||
|
|
||||||
this.service.importStructureStream(this.campaignId, file).subscribe({
|
this.service.importStructureStream(this.campaignId, file).subscribe({
|
||||||
@@ -192,6 +196,7 @@ export class CampaignImportComponent implements OnInit {
|
|||||||
} else {
|
} else {
|
||||||
this.tree = this.buildMergedTree(ev.arcs ?? []);
|
this.tree = this.buildMergedTree(ev.arcs ?? []);
|
||||||
this.npcs = this.buildNpcNodes(ev.npcs ?? []);
|
this.npcs = this.buildNpcNodes(ev.npcs ?? []);
|
||||||
|
this.importNotes = importOutcomeNotes(ev.outcome).map(note => this.translate.instant(note.key, note.params));
|
||||||
this.reviewing = true;
|
this.reviewing = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,7 +120,8 @@
|
|||||||
<span class="view-section-icon">🔒</span>
|
<span class="view-section-icon">🔒</span>
|
||||||
{{ 'sceneView.gmNotesSectionTitle' | translate }}
|
{{ 'sceneView.gmNotesSectionTitle' | translate }}
|
||||||
</h2>
|
</h2>
|
||||||
<p class="view-section-body">{{ scene.gmSecretNotes }}</p>
|
<!-- Markdown : une scène importée porte le texte du livre, avec ses sous-titres et ses tableaux. -->
|
||||||
|
<div class="view-md" [innerHTML]="scene.gmSecretNotes | markdown"></div>
|
||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
<!-- Pages Lore liées -->
|
<!-- Pages Lore liées -->
|
||||||
@@ -154,7 +155,7 @@
|
|||||||
}
|
}
|
||||||
</header>
|
</header>
|
||||||
@if (r.description?.trim()) {
|
@if (r.description?.trim()) {
|
||||||
<p class="room-readonly-desc">{{ r.description }}</p>
|
<div class="room-readonly-desc view-md" [innerHTML]="r.description | markdown"></div>
|
||||||
}
|
}
|
||||||
<div class="room-readonly-grid">
|
<div class="room-readonly-grid">
|
||||||
@if (r.enemies?.trim() || roomLinkedEnemies(r).length > 0) {
|
@if (r.enemies?.trim() || roomLinkedEnemies(r).length > 0) {
|
||||||
|
|||||||
@@ -45,7 +45,55 @@
|
|||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
color: var(--color-text, #333);
|
color: var(--color-text, #333);
|
||||||
white-space: pre-wrap;
|
}
|
||||||
|
|
||||||
|
// Texte rendu en markdown (notes du MJ, description d'une pièce) : paragraphes, sous-titres
|
||||||
|
// et tableaux du livre importé. Un texte saisi à la main garde ses sauts de ligne.
|
||||||
|
.view-md {
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
min-width: 0;
|
||||||
|
|
||||||
|
&.room-readonly-desc { font-size: 0.9rem; line-height: 1.5; color: var(--color-text, #333); }
|
||||||
|
|
||||||
|
::ng-deep {
|
||||||
|
> :first-child { margin-top: 0; }
|
||||||
|
> :last-child { margin-bottom: 0; }
|
||||||
|
|
||||||
|
p { margin: 0 0 0.7em; }
|
||||||
|
|
||||||
|
h1, h2, h3, h4, h5, h6 {
|
||||||
|
margin: 1.1em 0 0.4em;
|
||||||
|
color: #f3f4f6;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
h1, h2, h3 { font-size: 1.02rem; padding-bottom: 0.25em; border-bottom: 1px solid #1f2937; }
|
||||||
|
h4 { font-size: 0.95rem; color: #c4b5fd; }
|
||||||
|
h5, h6 { font-size: 0.9rem; color: #9ca3af; }
|
||||||
|
|
||||||
|
ul, ol { margin: 0.3em 0 0.7em; padding-left: 1.4em; }
|
||||||
|
li { margin: 0.2em 0; }
|
||||||
|
|
||||||
|
// Les tableaux défilent dans leur boîte : jamais de défilement horizontal de la page.
|
||||||
|
table {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin: 0.5em 0 0.8em;
|
||||||
|
font-size: 0.86rem;
|
||||||
|
}
|
||||||
|
th, td {
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
padding: 0.35em 0.65em;
|
||||||
|
text-align: left;
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
th { background: #0f172a; color: #f3f4f6; font-weight: 600; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.room-readonly-grid {
|
.room-readonly-grid {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { Enemy } from '../../../services/enemy.model';
|
|||||||
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
import { loadCampaignTreeData, buildCampaignSidebarConfig } from '../../campaign-tree.helper';
|
||||||
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
import { ImageGalleryComponent } from '../../../shared/image-gallery/image-gallery.component';
|
||||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||||
|
import { MarkdownPipe } from '../../../shared/markdown.pipe';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Écran de consultation d'une Scène (lecture seule).
|
* Écran de consultation d'une Scène (lecture seule).
|
||||||
@@ -28,7 +29,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
|||||||
*/
|
*/
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-scene-view',
|
selector: 'app-scene-view',
|
||||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedRoleHintComponent],
|
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent, TranslatePipe, GuidedRoleHintComponent, MarkdownPipe],
|
||||||
templateUrl: './scene-view.component.html',
|
templateUrl: './scene-view.component.html',
|
||||||
styleUrls: ['./scene-view.component.scss']
|
styleUrls: ['./scene-view.component.scss']
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -137,7 +137,7 @@
|
|||||||
|
|
||||||
<div class="section-list">
|
<div class="section-list">
|
||||||
@for (section of visibleSections; track section; let i = $index) {
|
@for (section of visibleSections; track section; let i = $index) {
|
||||||
<div class="section-card" [class.collapsed]="section.collapsed">
|
<div class="section-card" #card [class.collapsed]="section.collapsed" [class.editing]="section.editing">
|
||||||
<div class="section-head">
|
<div class="section-head">
|
||||||
<button type="button" class="btn-collapse" (click)="toggleCollapse(section)"
|
<button type="button" class="btn-collapse" (click)="toggleCollapse(section)"
|
||||||
[attr.aria-expanded]="!section.collapsed">
|
[attr.aria-expanded]="!section.collapsed">
|
||||||
@@ -153,18 +153,36 @@
|
|||||||
@if (section.collapsed && section.content.trim()) {
|
@if (section.collapsed && section.content.trim()) {
|
||||||
<span class="section-size">{{ 'gameSystemEdit.sectionSize' | translate:{ count: section.content.trim().length } }}</span>
|
<span class="section-size">{{ 'gameSystemEdit.sectionSize' | translate:{ count: section.content.trim().length } }}</span>
|
||||||
}
|
}
|
||||||
|
@if (!section.collapsed) {
|
||||||
|
<button type="button" class="btn-edit" [class.active]="section.editing"
|
||||||
|
[attr.aria-pressed]="section.editing" (click)="toggleEdit(section, card)">
|
||||||
|
<lucide-icon [img]="section.editing ? Check : Pencil" [size]="13"></lucide-icon>
|
||||||
|
{{ (section.editing ? 'gameSystemEdit.sectionDone' : 'gameSystemEdit.sectionEdit') | translate }}
|
||||||
|
</button>
|
||||||
|
}
|
||||||
<button type="button" class="btn-remove" (click)="removeSection(section)" [title]="'gameSystemEdit.removeSection' | translate">
|
<button type="button" class="btn-remove" (click)="removeSection(section)" [title]="'gameSystemEdit.removeSection' | translate">
|
||||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Lecture par défaut : le markdown est mis en forme. Le texte brut ne s'ouvre
|
||||||
|
que sur « Modifier » (ou d'office pour une section encore vide). -->
|
||||||
@if (!section.collapsed) {
|
@if (!section.collapsed) {
|
||||||
<textarea
|
@if (section.editing) {
|
||||||
class="section-content"
|
<textarea
|
||||||
[(ngModel)]="section.content"
|
class="section-content"
|
||||||
[name]="'content-' + i"
|
[(ngModel)]="section.content"
|
||||||
rows="6"
|
[name]="'content-' + i"
|
||||||
[placeholder]="'gameSystemEdit.sectionContentPlaceholder' | translate"
|
rows="14"
|
||||||
></textarea>
|
[placeholder]="'gameSystemEdit.sectionContentPlaceholder' | translate"
|
||||||
|
></textarea>
|
||||||
|
<p class="section-edit-hint">{{ 'gameSystemEdit.sectionEditHint' | translate }}</p>
|
||||||
|
} @else if (section.content.trim()) {
|
||||||
|
<div class="section-read" [innerHTML]="section.content | markdown"></div>
|
||||||
|
} @else {
|
||||||
|
<button type="button" class="section-empty" (click)="toggleEdit(section, card)">
|
||||||
|
{{ 'gameSystemEdit.sectionEmpty' | translate }}
|
||||||
|
</button>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -258,21 +258,143 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.section-content {
|
.section-content {
|
||||||
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
background: transparent;
|
background: #080d18;
|
||||||
border: none;
|
border: none;
|
||||||
border-top: 1px solid #1f2937;
|
border-top: 1px solid #1f2937;
|
||||||
color: #d1d5db;
|
color: #d1d5db;
|
||||||
padding: 0.75rem 1rem;
|
padding: 0.75rem 1rem;
|
||||||
font-size: 0.9rem;
|
font-size: 0.88rem;
|
||||||
font-family: inherit;
|
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||||
line-height: 1.5;
|
line-height: 1.55;
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
|
||||||
&:focus { outline: none; }
|
&:focus { outline: none; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bascule lecture / saisie d'une section.
|
||||||
|
.btn-edit {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.3rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: #9ca3af;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
padding: 0.2rem 0.55rem;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover { color: #e5e7eb; border-color: #374151; }
|
||||||
|
&.active { color: #c4b5fd; border-color: rgba(167, 139, 250, 0.45); background: rgba(167, 139, 250, 0.08); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-edit-hint {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.35rem 1rem 0.5rem;
|
||||||
|
background: #080d18;
|
||||||
|
color: #6b7280;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-empty {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid #1f2937;
|
||||||
|
color: #6b7280;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-style: italic;
|
||||||
|
text-align: left;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover { color: #d1d5db; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section en lecture : markdown mis en forme (HTML injecté → ::ng-deep, limité à ce bloc).
|
||||||
|
.section-read {
|
||||||
|
border-top: 1px solid #1f2937;
|
||||||
|
padding: 0.85rem 1.1rem 1rem;
|
||||||
|
color: #d1d5db;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
min-width: 0;
|
||||||
|
|
||||||
|
::ng-deep {
|
||||||
|
> :first-child { margin-top: 0; }
|
||||||
|
> :last-child { margin-bottom: 0; }
|
||||||
|
|
||||||
|
p { margin: 0 0 0.7em; }
|
||||||
|
|
||||||
|
h1, h2, h3, h4, h5, h6 {
|
||||||
|
margin: 1.15em 0 0.45em;
|
||||||
|
color: #f3f4f6;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
h1, h2, h3 { font-size: 1.02rem; padding-bottom: 0.25em; border-bottom: 1px solid #1f2937; }
|
||||||
|
h4 { font-size: 0.95rem; color: #c4b5fd; }
|
||||||
|
h5, h6 { font-size: 0.9rem; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.04em; }
|
||||||
|
|
||||||
|
strong { color: #f3f4f6; }
|
||||||
|
a { color: #a78bfa; }
|
||||||
|
ul, ol { margin: 0.3em 0 0.7em; padding-left: 1.4em; }
|
||||||
|
li { margin: 0.2em 0; }
|
||||||
|
li::marker { color: #6b7280; }
|
||||||
|
hr { border: 0; border-top: 1px solid #1f2937; margin: 1em 0; }
|
||||||
|
|
||||||
|
blockquote {
|
||||||
|
margin: 0.6em 0;
|
||||||
|
padding: 0.35em 0.9em;
|
||||||
|
border-left: 3px solid rgba(167, 139, 250, 0.5);
|
||||||
|
background: rgba(167, 139, 250, 0.05);
|
||||||
|
border-radius: 0 6px 6px 0;
|
||||||
|
color: #cbd5e1;
|
||||||
|
}
|
||||||
|
|
||||||
|
code {
|
||||||
|
background: #080d18;
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 0.3em;
|
||||||
|
font-size: 0.85em;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre {
|
||||||
|
background: #080d18;
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.6em 0.8em;
|
||||||
|
overflow-x: auto;
|
||||||
|
code { background: none; border: 0; padding: 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Les tableaux défilent dans leur boîte : jamais de défilement horizontal de la page.
|
||||||
|
table {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin: 0.5em 0 0.8em;
|
||||||
|
font-size: 0.86rem;
|
||||||
|
}
|
||||||
|
th, td {
|
||||||
|
border: 1px solid #1f2937;
|
||||||
|
padding: 0.35em 0.65em;
|
||||||
|
text-align: left;
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
th { background: #0f172a; color: #f3f4f6; font-weight: 600; }
|
||||||
|
tr:nth-child(even) td { background: rgba(255, 255, 255, 0.02); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.empty-hint {
|
.empty-hint {
|
||||||
color: #6b7280;
|
color: #6b7280;
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
|
|||||||
@@ -8,11 +8,14 @@ import {
|
|||||||
LucideAngularModule, LucideIconData, Save, ArrowLeft, Dices, Plus, Trash2, ChevronDown, ChevronRight, Upload,
|
LucideAngularModule, LucideIconData, Save, ArrowLeft, Dices, Plus, Trash2, ChevronDown, ChevronRight, Upload,
|
||||||
Sparkles, Info, BookOpen, LayoutTemplate, Search, WandSparkles
|
Sparkles, Info, BookOpen, LayoutTemplate, Search, WandSparkles
|
||||||
} from 'lucide-angular';
|
} from 'lucide-angular';
|
||||||
|
import { Check, Pencil } from 'lucide-angular';
|
||||||
|
import { MarkdownPipe } from '../../shared/markdown.pipe';
|
||||||
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
|
||||||
import { GameSystemService } from '../../services/game-system.service';
|
import { GameSystemService } from '../../services/game-system.service';
|
||||||
import { SheetFieldProposal, SheetKind } from '../../services/game-system.model';
|
import { SheetFieldProposal, SheetKind } from '../../services/game-system.model';
|
||||||
import { FieldType, TemplateField } from '../../services/template.model';
|
import { FieldType, TemplateField } from '../../services/template.model';
|
||||||
import { addProposedFields, isAlreadyInSheet, rulesForProposal } from '../sheet-proposal.util';
|
import { addProposedFields, isAlreadyInSheet, rulesForProposal } from '../sheet-proposal.util';
|
||||||
|
import { importTranslation } from '../rules-import.util';
|
||||||
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
|
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
|
||||||
import { SpellCatalogEditorComponent, SpellView } from '../spell-catalog-editor/spell-catalog-editor.component';
|
import { SpellCatalogEditorComponent, SpellView } from '../spell-catalog-editor/spell-catalog-editor.component';
|
||||||
import { SpellDraft, firstUnnamedSpell, hasInvalidField, toDraft, toPayload } from '../spell-catalog.util';
|
import { SpellDraft, firstUnnamedSpell, hasInvalidField, toDraft, toPayload } from '../spell-catalog.util';
|
||||||
@@ -36,6 +39,11 @@ interface RuleSection {
|
|||||||
title: string;
|
title: string;
|
||||||
content: string;
|
content: string;
|
||||||
collapsed: boolean;
|
collapsed: boolean;
|
||||||
|
/**
|
||||||
|
* Vrai : le texte brut (markdown) est ouvert dans une zone de saisie. Faux : la section se
|
||||||
|
* lit mise en forme. Une section qui a du texte s'ouvre en lecture, une section vide en saisie.
|
||||||
|
*/
|
||||||
|
editing: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -66,6 +74,11 @@ const SHEET_KINDS: SheetKind[] = ['character', 'npc', 'enemy'];
|
|||||||
|
|
||||||
/** Au-delà, les sections s'ouvrent repliées : un livre importé en compte vite cinquante. */
|
/** Au-delà, les sections s'ouvrent repliées : un livre importé en compte vite cinquante. */
|
||||||
const COLLAPSE_ABOVE = 5;
|
const COLLAPSE_ABOVE = 5;
|
||||||
|
/** Note d'import selon la façon dont le livre a été découpé (rien à dire quand c'est l'IA). */
|
||||||
|
const SPLIT_NOTES: Record<string, string> = {
|
||||||
|
bookmarks: 'gameSystemEdit.importSplitBookmarks',
|
||||||
|
headings: 'gameSystemEdit.importSplitHeadings'
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Proposition de champs pour une fiche, tirée des règles par l'IA. `fields` vaut null
|
* Proposition de champs pour une fiche, tirée des règles par l'IA. `fields` vaut null
|
||||||
@@ -86,7 +99,7 @@ const emptyProposal = (): SheetProposalState =>
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-game-system-edit',
|
selector: 'app-game-system-edit',
|
||||||
imports: [FormsModule, NgTemplateOutlet, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent,
|
imports: [FormsModule, NgTemplateOutlet, LucideAngularModule, TranslatePipe, MarkdownPipe, TemplateFieldsEditorComponent,
|
||||||
SpellCatalogEditorComponent],
|
SpellCatalogEditorComponent],
|
||||||
templateUrl: './game-system-edit.component.html',
|
templateUrl: './game-system-edit.component.html',
|
||||||
styleUrls: ['./game-system-edit.component.scss']
|
styleUrls: ['./game-system-edit.component.scss']
|
||||||
@@ -97,6 +110,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
readonly Dices = Dices;
|
readonly Dices = Dices;
|
||||||
readonly Plus = Plus;
|
readonly Plus = Plus;
|
||||||
readonly Trash2 = Trash2;
|
readonly Trash2 = Trash2;
|
||||||
|
readonly Pencil = Pencil;
|
||||||
|
readonly Check = Check;
|
||||||
readonly ChevronDown = ChevronDown;
|
readonly ChevronDown = ChevronDown;
|
||||||
readonly ChevronRight = ChevronRight;
|
readonly ChevronRight = ChevronRight;
|
||||||
readonly Upload = Upload;
|
readonly Upload = Upload;
|
||||||
@@ -298,13 +313,13 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
addSuggested(title: string): void {
|
addSuggested(title: string): void {
|
||||||
if (this.isSectionUsed(title)) return;
|
if (this.isSectionUsed(title)) return;
|
||||||
this.sectionFilter = '';
|
this.sectionFilter = '';
|
||||||
this.sections.push({ title, content: '', collapsed: false });
|
this.sections.push({ title, content: '', collapsed: false, editing: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ajoute une section vierge (titre à remplir). */
|
/** Ajoute une section vierge (titre à remplir). */
|
||||||
addBlank(): void {
|
addBlank(): void {
|
||||||
this.sectionFilter = '';
|
this.sectionFilter = '';
|
||||||
this.sections.push({ title: '', content: '', collapsed: false });
|
this.sections.push({ title: '', content: '', collapsed: false, editing: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Import d'un PDF de règles -------------------------------------------
|
// --- Import d'un PDF de règles -------------------------------------------
|
||||||
@@ -349,7 +364,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
} else if (ev.type === 'status') {
|
} else if (ev.type === 'status') {
|
||||||
this.importStatus = ev.message;
|
this.importStatus = ev.message;
|
||||||
} else if (ev.type === 'done') {
|
} else if (ev.type === 'done') {
|
||||||
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount, ev.sectionsByLanguage, ev.sourceLanguage);
|
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount, ev.sectionsByLanguage, ev.sourceLanguage,
|
||||||
|
ev.untranslatedTitles ?? [], ev.splitMethod);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: (err: Error) => {
|
error: (err: Error) => {
|
||||||
@@ -362,7 +378,8 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number,
|
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number,
|
||||||
byLanguage?: Record<string, Record<string, string>>, sourceLanguage?: string | null): void {
|
byLanguage?: Record<string, Record<string, string>>, sourceLanguage?: string | null,
|
||||||
|
untranslated: string[] = [], splitMethod?: string | null): void {
|
||||||
this.resetImportProgress();
|
this.resetImportProgress();
|
||||||
// Règles en deux langues (Brain récent) : chaque version va dans son onglet ; sinon,
|
// Règles en deux langues (Brain récent) : chaque version va dans son onglet ; sinon,
|
||||||
// les sections vont dans l'onglet affiché (comportement historique).
|
// les sections vont dans l'onglet affiché (comportement historique).
|
||||||
@@ -388,16 +405,35 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
pages: pageCount,
|
pages: pageCount,
|
||||||
ocr
|
ocr
|
||||||
});
|
});
|
||||||
const translatedLangs = this.rulesLangs.filter(l => l !== sourceLanguage && (byLanguage?.[l] && Object.keys(byLanguage[l]).length));
|
// Livre découpé par sa propre structure, sans IA : on le dit, les titres sont ceux du livre.
|
||||||
if (bilingual && sourceLanguage && translatedLangs.length) {
|
const splitKey = SPLIT_NOTES[splitMethod ?? ''];
|
||||||
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importTranslated', {
|
if (splitKey) this.importNote += ' ' + this.translate.instant(splitKey);
|
||||||
source: this.translate.instant('gameSystemEdit.lang.' + sourceLanguage),
|
const translationNote = this.importTranslationNote(byLanguage, sourceLanguage, untranslated);
|
||||||
target: translatedLangs.map(l => this.translate.instant('gameSystemEdit.lang.' + l)).join(', ')
|
if (translationNote) this.importNote += ' ' + translationNote;
|
||||||
});
|
|
||||||
}
|
|
||||||
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importSheetHint');
|
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importSheetHint');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ce que l'import dit de la traduction : faite, faite en partie (des sections gardent leur
|
||||||
|
* texte d'origine) ou non aboutie (seul l'onglet de la langue du livre est rempli).
|
||||||
|
*/
|
||||||
|
private importTranslationNote(byLanguage: Record<string, Record<string, string>> | undefined,
|
||||||
|
sourceLanguage: string | null | undefined, untranslated: string[]): string {
|
||||||
|
const outcome = importTranslation(byLanguage, sourceLanguage, untranslated, this.rulesLangs);
|
||||||
|
if (outcome.kind === 'none') return '';
|
||||||
|
const langName = (l: string) => this.translate.instant('gameSystemEdit.lang.' + l);
|
||||||
|
const source = langName(outcome.source);
|
||||||
|
const target = outcome.targets.map(langName).join(', ');
|
||||||
|
if (outcome.kind === 'failed') {
|
||||||
|
return this.translate.instant('gameSystemEdit.importNotTranslated', { source, target });
|
||||||
|
}
|
||||||
|
const translated = this.translate.instant('gameSystemEdit.importTranslated', { source, target });
|
||||||
|
if (outcome.kind === 'translated') return translated;
|
||||||
|
return translated + ' ' + this.translate.instant('gameSystemEdit.importPartlyTranslated', {
|
||||||
|
count: outcome.count, total: outcome.total, target, titles: outcome.titles
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** Nombre de sections non vides d'une langue (badge de l'onglet). */
|
/** Nombre de sections non vides d'une langue (badge de l'onglet). */
|
||||||
sectionCount(lang: RulesLang): number {
|
sectionCount(lang: RulesLang): number {
|
||||||
return this.sectionsByLang[lang].filter(s => s.title.trim() || s.content.trim()).length;
|
return this.sectionsByLang[lang].filter(s => s.title.trim() || s.content.trim()).length;
|
||||||
@@ -563,7 +599,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
|
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
|
||||||
existing.collapsed = false;
|
existing.collapsed = false;
|
||||||
} else {
|
} else {
|
||||||
target.push({ title, content, collapsed: false });
|
target.push({ title, content, collapsed: false, editing: false });
|
||||||
}
|
}
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
@@ -620,6 +656,18 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
section.collapsed = !section.collapsed;
|
section.collapsed = !section.collapsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Passe une section de la lecture à la saisie, ou l'inverse. En ouvrant la saisie, le
|
||||||
|
* curseur va dans la zone de texte de la carte.
|
||||||
|
*/
|
||||||
|
toggleEdit(section: RuleSection, card?: HTMLElement): void {
|
||||||
|
section.editing = !section.editing;
|
||||||
|
section.collapsed = false;
|
||||||
|
if (section.editing && card) {
|
||||||
|
setTimeout(() => card.querySelector<HTMLTextAreaElement>('textarea.section-content')?.focus());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
submit(): void {
|
submit(): void {
|
||||||
if (!this.name.trim() || this.saving) return;
|
if (!this.name.trim() || this.saving) return;
|
||||||
this.saveError = null;
|
this.saveError = null;
|
||||||
@@ -714,6 +762,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
const flush = () => {
|
const flush = () => {
|
||||||
if (current) {
|
if (current) {
|
||||||
current.content = buffer.join('\n').trim();
|
current.content = buffer.join('\n').trim();
|
||||||
|
current.editing = !current.content;
|
||||||
sections.push(current);
|
sections.push(current);
|
||||||
}
|
}
|
||||||
buffer.length = 0;
|
buffer.length = 0;
|
||||||
@@ -726,7 +775,7 @@ export class GameSystemEditComponent implements OnInit, OnDestroy {
|
|||||||
const match = line.match(/^##\s+(\S.*)$/);
|
const match = line.match(/^##\s+(\S.*)$/);
|
||||||
if (match) {
|
if (match) {
|
||||||
flush();
|
flush();
|
||||||
current = { title: match[1].trim(), content: '', collapsed: false };
|
current = { title: match[1].trim(), content: '', collapsed: false, editing: false };
|
||||||
} else if (current) {
|
} else if (current) {
|
||||||
buffer.push(line);
|
buffer.push(line);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { importTranslation, MAX_UNTRANSLATED_SHOWN } from './rules-import.util';
|
||||||
|
|
||||||
|
const LANGS = ['fr', 'en'] as const;
|
||||||
|
const EN = { Combat: 'd20 roll', Magic: 'spells' };
|
||||||
|
|
||||||
|
describe('importTranslation', () => {
|
||||||
|
it("ne dit rien d'un import dans une seule langue (langue du livre inconnue)", () => {
|
||||||
|
expect(importTranslation(undefined, null, [], LANGS)).toEqual({ kind: 'none' });
|
||||||
|
expect(importTranslation({ en: EN }, null, [], LANGS)).toEqual({ kind: 'none' });
|
||||||
|
expect(importTranslation({ de: EN }, 'de', [], LANGS)).toEqual({ kind: 'none' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('annonce une traduction complète', () => {
|
||||||
|
const fr = { Combat: 'jet de d20', Magie: 'sorts' };
|
||||||
|
expect(importTranslation({ en: EN, fr }, 'en', [], LANGS))
|
||||||
|
.toEqual({ kind: 'translated', source: 'en', targets: ['fr'] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("signale une traduction qui n'a pas abouti : seul l'onglet du livre est rempli", () => {
|
||||||
|
expect(importTranslation({ en: EN }, 'en', [], LANGS))
|
||||||
|
.toEqual({ kind: 'failed', source: 'en', targets: ['fr'] });
|
||||||
|
expect(importTranslation({ en: EN, fr: {} }, 'en', [], LANGS).kind).toBe('failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('compte et cite les sections restées dans la langue du livre', () => {
|
||||||
|
const fr = { Combat: 'jet de d20', Magic: 'spells' };
|
||||||
|
expect(importTranslation({ en: EN, fr }, 'en', ['Magic'], LANGS))
|
||||||
|
.toEqual({ kind: 'partial', source: 'en', targets: ['fr'], count: 1, total: 2, titles: 'Magic' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('abrège une longue liste de sections non traduites', () => {
|
||||||
|
const titles = Array.from({ length: MAX_UNTRANSLATED_SHOWN + 3 }, (_, i) => `S${i}`);
|
||||||
|
const all = Object.fromEntries(titles.map(t => [t, 'text']));
|
||||||
|
const outcome = importTranslation({ en: all, fr: all }, 'en', titles, LANGS);
|
||||||
|
expect(outcome).toMatchObject({ kind: 'partial', count: 8, total: 8, titles: 'S0, S1, S2, S3, S4…' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* Import d'un PDF de règles : ce qu'il faut dire de la traduction une fois l'import terminé.
|
||||||
|
*
|
||||||
|
* Le livre est extrait dans sa langue, puis traduit vers l'autre langue de l'application. La
|
||||||
|
* traduction peut aboutir, n'aboutir qu'en partie (des sections gardent leur texte d'origine)
|
||||||
|
* ou ne pas aboutir du tout (seul l'onglet de la langue du livre est rempli).
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Titres de sections non traduites cités dans la note (le reste est résumé par « … »). */
|
||||||
|
export const MAX_UNTRANSLATED_SHOWN = 5;
|
||||||
|
|
||||||
|
export type ImportTranslation =
|
||||||
|
/** Import dans une seule langue (langue du livre inconnue) : rien à dire. */
|
||||||
|
| { kind: 'none' }
|
||||||
|
/** Toutes les sections sont traduites vers `targets`. */
|
||||||
|
| { kind: 'translated'; source: string; targets: string[] }
|
||||||
|
/** `count` sections sur `total` gardent leur texte d'origine dans `targets`. */
|
||||||
|
| { kind: 'partial'; source: string; targets: string[]; count: number; total: number; titles: string }
|
||||||
|
/** Aucune traduction : seul l'onglet `source` est rempli ; `targets` restent vides. */
|
||||||
|
| { kind: 'failed'; source: string; targets: string[] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param byLanguage sections reçues, par langue
|
||||||
|
* @param sourceLanguage langue du livre
|
||||||
|
* @param untranslated titres des sections que la traduction n'a pas pu traiter
|
||||||
|
* @param languages langues de l'application, dans l'ordre des onglets
|
||||||
|
*/
|
||||||
|
export function importTranslation(
|
||||||
|
byLanguage: Record<string, Record<string, string>> | undefined,
|
||||||
|
sourceLanguage: string | null | undefined,
|
||||||
|
untranslated: string[],
|
||||||
|
languages: readonly string[]
|
||||||
|
): ImportTranslation {
|
||||||
|
if (!byLanguage || !sourceLanguage || !languages.includes(sourceLanguage)) return { kind: 'none' };
|
||||||
|
const others = languages.filter(l => l !== sourceLanguage);
|
||||||
|
const translated = others.filter(l => Object.keys(byLanguage[l] ?? {}).length > 0);
|
||||||
|
if (!translated.length) return { kind: 'failed', source: sourceLanguage, targets: others };
|
||||||
|
if (!untranslated.length) return { kind: 'translated', source: sourceLanguage, targets: translated };
|
||||||
|
const shown = untranslated.slice(0, MAX_UNTRANSLATED_SHOWN).join(', ');
|
||||||
|
return {
|
||||||
|
kind: 'partial',
|
||||||
|
source: sourceLanguage,
|
||||||
|
targets: translated,
|
||||||
|
count: untranslated.length,
|
||||||
|
total: Object.keys(byLanguage[sourceLanguage] ?? {}).length,
|
||||||
|
titles: untranslated.length > MAX_UNTRANSLATED_SHOWN ? `${shown}…` : shown
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -68,6 +68,13 @@
|
|||||||
</span>
|
</span>
|
||||||
@if (spells.length > 1) {
|
@if (spells.length > 1) {
|
||||||
<span class="spell-status-actions">
|
<span class="spell-status-actions">
|
||||||
|
@if (harmonizable > 0) {
|
||||||
|
<button type="button" class="link-button" (click)="harmonize()"
|
||||||
|
[title]="'spellCatalog.harmonizeTitle' | translate">
|
||||||
|
<lucide-icon [img]="WandSparkles" [size]="13"></lucide-icon>
|
||||||
|
{{ 'spellCatalog.harmonize' | translate:{ count: harmonizable } }}
|
||||||
|
</button>
|
||||||
|
}
|
||||||
<button type="button" class="link-button" (click)="sort()" [title]="'spellCatalog.sortTitle' | translate">
|
<button type="button" class="link-button" (click)="sort()" [title]="'spellCatalog.sortTitle' | translate">
|
||||||
<lucide-icon [img]="ArrowDownNarrowWide" [size]="13"></lucide-icon>
|
<lucide-icon [img]="ArrowDownNarrowWide" [size]="13"></lucide-icon>
|
||||||
{{ 'spellCatalog.sort' | translate }}
|
{{ 'spellCatalog.sort' | translate }}
|
||||||
@@ -79,6 +86,9 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
@if (harmonized !== null) {
|
||||||
|
<p class="spell-note" role="status">{{ 'spellCatalog.harmonized' | translate:{ count: harmonized } }}</p>
|
||||||
|
}
|
||||||
|
|
||||||
<div class="spell-list">
|
<div class="spell-list">
|
||||||
@for (spell of visibleSpells; track spell; let i = $index) {
|
@for (spell of visibleSpells; track spell; let i = $index) {
|
||||||
|
|||||||
@@ -224,7 +224,7 @@
|
|||||||
.spell-level {
|
.spell-level {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
min-width: 1.75rem;
|
min-width: 1.75rem;
|
||||||
max-width: 9rem;
|
max-width: 12rem;
|
||||||
padding: 0.15rem 0.5rem;
|
padding: 0.15rem 0.5rem;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: rgba(108, 99, 255, 0.2);
|
background: rgba(108, 99, 255, 0.2);
|
||||||
@@ -361,3 +361,14 @@
|
|||||||
.spell-title { max-width: none; flex: 1; }
|
.spell-title { max-width: none; flex: 1; }
|
||||||
.spell-toolbar-actions { margin-left: 0; }
|
.spell-toolbar-actions { margin-left: 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Confirmation de l'harmonisation des niveaux et des écoles.
|
||||||
|
.spell-note {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border: 1px solid rgba(167, 139, 250, 0.3);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: rgba(167, 139, 250, 0.06);
|
||||||
|
color: #c4b5fd;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { TranslatePipe } from '@ngx-translate/core';
|
|||||||
import {
|
import {
|
||||||
LucideAngularModule, ArrowDownNarrowWide, ChevronDown, ChevronRight, Plus, Search, Sparkles, Trash2, WandSparkles, X
|
LucideAngularModule, ArrowDownNarrowWide, ChevronDown, ChevronRight, Plus, Search, Sparkles, Trash2, WandSparkles, X
|
||||||
} from 'lucide-angular';
|
} from 'lucide-angular';
|
||||||
|
import { LanguageService } from '../../services/language.service';
|
||||||
import { ProposedSpell } from '../../services/spell.model';
|
import { ProposedSpell } from '../../services/spell.model';
|
||||||
import { TemplateField } from '../../services/template.model';
|
import { TemplateField } from '../../services/template.model';
|
||||||
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
|
import { TemplateFieldsEditorComponent } from '../../shared/template-fields-editor/template-fields-editor.component';
|
||||||
@@ -11,6 +12,7 @@ import {
|
|||||||
NO_FILTER, SpellDraft, SpellFilter, distinctValues, filterSpells, isFiltering, newSpell, sortByLevelThenName,
|
NO_FILTER, SpellDraft, SpellFilter, distinctValues, filterSpells, isFiltering, newSpell, sortByLevelThenName,
|
||||||
summary, usableFields
|
summary, usableFields
|
||||||
} from '../spell-catalog.util';
|
} from '../spell-catalog.util';
|
||||||
|
import { cantripLabel, harmonizeSpells } from '../spell-harmonize.util';
|
||||||
import { SpellProposalComponent } from '../spell-proposal/spell-proposal.component';
|
import { SpellProposalComponent } from '../spell-proposal/spell-proposal.component';
|
||||||
import { RuleText, addProposedSpells } from '../spell-proposal.util';
|
import { RuleText, addProposedSpells } from '../spell-proposal.util';
|
||||||
|
|
||||||
@@ -48,6 +50,7 @@ export class SpellCatalogEditorComponent {
|
|||||||
readonly fieldSuggestions = FIELD_SUGGESTIONS;
|
readonly fieldSuggestions = FIELD_SUGGESTIONS;
|
||||||
|
|
||||||
private readonly host: ElementRef<HTMLElement> = inject(ElementRef);
|
private readonly host: ElementRef<HTMLElement> = inject(ElementRef);
|
||||||
|
private readonly language = inject(LanguageService);
|
||||||
|
|
||||||
/** Sorts du catalogue. La liste est remplacée (jamais modifiée sur place) à chaque ajout, retrait ou tri. */
|
/** Sorts du catalogue. La liste est remplacée (jamais modifiée sur place) à chaque ajout, retrait ou tri. */
|
||||||
@Input() spells: SpellDraft[] = [];
|
@Input() spells: SpellDraft[] = [];
|
||||||
@@ -67,6 +70,10 @@ export class SpellCatalogEditorComponent {
|
|||||||
filter: SpellFilter = { ...NO_FILTER };
|
filter: SpellFilter = { ...NO_FILTER };
|
||||||
/** La proposition de sorts à partir des règles est-elle ouverte ? */
|
/** La proposition de sorts à partir des règles est-elle ouverte ? */
|
||||||
proposing = false;
|
proposing = false;
|
||||||
|
/** Nombre de sorts réécrits par la dernière harmonisation (message de confirmation). */
|
||||||
|
harmonized: number | null = null;
|
||||||
|
/** Dernier calcul de `harmonizable`, tant que niveaux et écoles n'ont pas bougé. */
|
||||||
|
private harmonizableCache: { signature: string; count: number } | null = null;
|
||||||
|
|
||||||
selectView(view: SpellView): void {
|
selectView(view: SpellView): void {
|
||||||
this.view = view;
|
this.view = view;
|
||||||
@@ -104,6 +111,33 @@ export class SpellCatalogEditorComponent {
|
|||||||
this.filter = { ...NO_FILTER };
|
this.filter = { ...NO_FILTER };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─────────────── Niveaux et écoles écrits de la même façon ───────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nombre de sorts dont le niveau ou l'école changerait à l'harmonisation (« Niveau 1 » →
|
||||||
|
* « 1 », « Cantrip » → « Tour de magie », « Sorts de foudre » → « Foudre »…). Le bouton
|
||||||
|
* n'apparaît que s'il y a quelque chose à faire.
|
||||||
|
*/
|
||||||
|
get harmonizable(): number {
|
||||||
|
const signature = this.language.current + '\u0001'
|
||||||
|
+ this.spells.map(s => `${s.level ?? ''}\u0002${s.school ?? ''}`).join('\u0001');
|
||||||
|
if (this.harmonizableCache?.signature !== signature) {
|
||||||
|
const count = harmonizeSpells(this.spells, cantripLabel(this.language.current)).changed;
|
||||||
|
this.harmonizableCache = { signature, count };
|
||||||
|
}
|
||||||
|
return this.harmonizableCache.count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réécrit niveaux et écoles d'une seule façon. Rien n'est enregistré avant l'enregistrement du système. */
|
||||||
|
harmonize(): void {
|
||||||
|
const { spells, changed } = harmonizeSpells(this.spells, cantripLabel(this.language.current));
|
||||||
|
if (!changed) return;
|
||||||
|
this.clearFilter();
|
||||||
|
this.spells = spells;
|
||||||
|
this.harmonized = changed;
|
||||||
|
this.spellsChange.emit(this.spells);
|
||||||
|
}
|
||||||
|
|
||||||
/** Nouveau sort en tête de liste, ouvert, le curseur dans son nom. */
|
/** Nouveau sort en tête de liste, ouvert, le curseur dans son nom. */
|
||||||
addSpell(): void {
|
addSpell(): void {
|
||||||
this.clearFilter();
|
this.clearFilter();
|
||||||
@@ -152,6 +186,7 @@ export class SpellCatalogEditorComponent {
|
|||||||
* présents ne sont pas touchés ; rien n'est enregistré avant l'enregistrement du système.
|
* présents ne sont pas touchés ; rien n'est enregistré avant l'enregistrement du système.
|
||||||
*/
|
*/
|
||||||
onProposed(proposals: ProposedSpell[]): void {
|
onProposed(proposals: ProposedSpell[]): void {
|
||||||
|
this.harmonized = null;
|
||||||
this.clearFilter();
|
this.clearFilter();
|
||||||
this.spells = addProposedSpells(this.spells, proposals);
|
this.spells = addProposedSpells(this.spells, proposals);
|
||||||
this.spellsChange.emit(this.spells);
|
this.spellsChange.emit(this.spells);
|
||||||
|
|||||||
@@ -68,7 +68,8 @@ describe('spell-catalog.util', () => {
|
|||||||
const spells = [spell('A', { level: '10' }), spell('B', { level: ' 2 ' }), spell('C', { level: '2', school: 'Illusion' }),
|
const spells = [spell('A', { level: '10' }), spell('B', { level: ' 2 ' }), spell('C', { level: '2', school: 'Illusion' }),
|
||||||
spell('D', { school: 'Abjuration' }), spell('E', { level: 'Tour de magie' })];
|
spell('D', { school: 'Abjuration' }), spell('E', { level: 'Tour de magie' })];
|
||||||
|
|
||||||
expect(distinctValues(spells, 'level')).toEqual(['2', '10', 'Tour de magie']);
|
// Les tours de magie passent avant le niveau 1.
|
||||||
|
expect(distinctValues(spells, 'level')).toEqual(['Tour de magie', '2', '10']);
|
||||||
expect(distinctValues(spells, 'school')).toEqual(['Abjuration', 'Illusion']);
|
expect(distinctValues(spells, 'school')).toEqual(['Abjuration', 'Illusion']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Spell } from '../services/spell.model';
|
import { Spell } from '../services/spell.model';
|
||||||
import { TemplateField } from '../services/template.model';
|
import { TemplateField } from '../services/template.model';
|
||||||
|
import { compareLevels } from './spell-harmonize.util';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Catalogue de sorts : logique pure de l'onglet « Sorts » (recherche, filtres, tri, contrôle
|
* Catalogue de sorts : logique pure de l'onglet « Sorts » (recherche, filtres, tri, contrôle
|
||||||
@@ -86,14 +87,18 @@ export function isFiltering(filter: SpellFilter): boolean {
|
|||||||
return !!(filter.text.trim() || filter.level || filter.school);
|
return !!(filter.text.trim() || filter.level || filter.school);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Niveaux (ou écoles) présents dans le catalogue, sans doublon, dans l'ordre naturel. */
|
/**
|
||||||
|
* Niveaux (ou écoles) présents dans le catalogue, sans doublon, dans l'ordre naturel ; pour
|
||||||
|
* les niveaux, les tours de magie passent avant le niveau 1.
|
||||||
|
*/
|
||||||
export function distinctValues(spells: Spell[], key: 'level' | 'school'): string[] {
|
export function distinctValues(spells: Spell[], key: 'level' | 'school'): string[] {
|
||||||
return [...new Set(spells.map(s => clean(s[key])).filter(Boolean))].sort(NATURAL.compare);
|
return [...new Set(spells.map(s => clean(s[key])).filter(Boolean))]
|
||||||
|
.sort(key === 'level' ? compareLevels : NATURAL.compare);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Catalogue rangé par niveau puis par nom (nouvelle liste). Les sorts sans niveau vont à la
|
* Catalogue rangé par niveau puis par nom (nouvelle liste). Les tours de magie viennent avant
|
||||||
* fin ; à égalité, l'ordre d'origine est gardé.
|
* le niveau 1 et les sorts sans niveau vont à la fin ; à égalité, l'ordre d'origine est gardé.
|
||||||
*/
|
*/
|
||||||
export function sortByLevelThenName<T extends Spell>(spells: T[]): T[] {
|
export function sortByLevelThenName<T extends Spell>(spells: T[]): T[] {
|
||||||
return spells
|
return spells
|
||||||
@@ -102,7 +107,7 @@ export function sortByLevelThenName<T extends Spell>(spells: T[]): T[] {
|
|||||||
const la = clean(a.spell.level);
|
const la = clean(a.spell.level);
|
||||||
const lb = clean(b.spell.level);
|
const lb = clean(b.spell.level);
|
||||||
if (!la !== !lb) return la ? -1 : 1;
|
if (!la !== !lb) return la ? -1 : 1;
|
||||||
return NATURAL.compare(la, lb) || NATURAL.compare(clean(a.spell.name), clean(b.spell.name)) || a.index - b.index;
|
return compareLevels(la, lb) || NATURAL.compare(clean(a.spell.name), clean(b.spell.name)) || a.index - b.index;
|
||||||
})
|
})
|
||||||
.map(entry => entry.spell);
|
.map(entry => entry.spell);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import {
|
||||||
|
cantripLabel, compareLevels, harmonizeSpells, isCantrip, normalizeLevel, tidySchool
|
||||||
|
} from './spell-harmonize.util';
|
||||||
|
import { Spell } from '../services/spell.model';
|
||||||
|
|
||||||
|
const FR = cantripLabel('fr');
|
||||||
|
const spell = (name: string, level: string, school = ''): Spell => ({ name, level, school, description: '', values: {} });
|
||||||
|
|
||||||
|
describe('normalizeLevel', () => {
|
||||||
|
it('écrit un niveau numéroté par son seul nombre', () => {
|
||||||
|
for (const raw of ['1', 'Niveau 1', 'NIVEAU 1', 'niveau 1', 'Niv. 1', 'Level 1', 'Sort de niveau 1',
|
||||||
|
'1er niveau', '1st level', '01']) {
|
||||||
|
expect(normalizeLevel(raw, FR), raw).toBe('1');
|
||||||
|
}
|
||||||
|
expect(normalizeLevel('3e niveau', FR)).toBe('3');
|
||||||
|
expect(normalizeLevel('Niveau 10', FR)).toBe('10');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('laisse de côté ce qui suit le niveau', () => {
|
||||||
|
expect(normalizeLevel('NIVEAU 3, ZONE', FR)).toBe('3');
|
||||||
|
expect(normalizeLevel('Niveau 9, Zone', FR)).toBe('9');
|
||||||
|
expect(normalizeLevel('5 (zone)', FR)).toBe('5');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('donne un seul nom aux sorts de niveau 0', () => {
|
||||||
|
for (const raw of ['Tour de magie', 'TOUR DE MAGIE', 'Tours de magie', 'Tour', 'TOUR', 'Cantrip', 'cantrips',
|
||||||
|
'Sort mineur']) {
|
||||||
|
expect(normalizeLevel(raw, FR), raw).toBe('Tour de magie');
|
||||||
|
}
|
||||||
|
expect(normalizeLevel('Tour de magie', cantripLabel('en'))).toBe('Cantrip');
|
||||||
|
expect(cantripLabel('de')).toBe('Tour de magie');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('garde la précision qui suit', () => {
|
||||||
|
expect(normalizeLevel('CANTRIP UTILITAIRE', FR)).toBe('Tour de magie utilitaire');
|
||||||
|
expect(normalizeLevel('Cantrip utilitaire', FR)).toBe('Tour de magie utilitaire');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ne prend pas pour un niveau 0 un mot qui commence pareil", () => {
|
||||||
|
expect(normalizeLevel('Tourmente', FR)).toBe('Tourmente');
|
||||||
|
expect(isCantrip('Tourmente')).toBe(false);
|
||||||
|
expect(isCantrip(' tour ')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("garde le vocabulaire d'un autre système, casse rangée", () => {
|
||||||
|
expect(normalizeLevel('Rang II', FR)).toBe('Rang II');
|
||||||
|
expect(normalizeLevel('RANG II', FR)).toBe('Rang II');
|
||||||
|
expect(normalizeLevel('Cercle 3', FR)).toBe('Cercle 3');
|
||||||
|
// Livre en anglais : « TIER 3, AOE » et « Tier 3 » sont le même palier.
|
||||||
|
expect(normalizeLevel('TIER 3, AOE', FR)).toBe('Tier 3');
|
||||||
|
expect(normalizeLevel('Tier 3', FR)).toBe('Tier 3');
|
||||||
|
expect(normalizeLevel('tier 1', FR)).toBe('Tier 1');
|
||||||
|
expect(normalizeLevel('RANG 2', FR)).toBe('Rang 2');
|
||||||
|
expect(normalizeLevel('RITUEL MAJEUR', FR)).toBe('Rituel majeur');
|
||||||
|
expect(normalizeLevel('1-3', FR)).toBe('1-3');
|
||||||
|
expect(normalizeLevel('1/2', FR)).toBe('1/2');
|
||||||
|
expect(normalizeLevel(' ', FR)).toBe('');
|
||||||
|
expect(normalizeLevel(null, FR)).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('tidySchool', () => {
|
||||||
|
it("retire l'habillage d'une école", () => {
|
||||||
|
expect(tidySchool('Sorts de foudre')).toBe('Foudre');
|
||||||
|
expect(tidySchool('Sorts radiants')).toBe('Radiants');
|
||||||
|
expect(tidySchool("École d'évocation")).toBe('Évocation');
|
||||||
|
expect(tidySchool('Magie du feu')).toBe('Feu');
|
||||||
|
expect(tidySchool('Fire spells')).toBe('Fire');
|
||||||
|
expect(tidySchool('School of Necromancy')).toBe('Necromancy');
|
||||||
|
expect(tidySchool('NÉCROTIQUE')).toBe('Nécrotique');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ne vide pas une école et ne coupe pas un nom qui se tient seul", () => {
|
||||||
|
expect(tidySchool('Magie blanche')).toBe('Magie blanche');
|
||||||
|
expect(tidySchool('Sorts')).toBe('Sorts');
|
||||||
|
expect(tidySchool('vent')).toBe('Vent');
|
||||||
|
expect(tidySchool('')).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('harmonizeSpells', () => {
|
||||||
|
it('rassemble les écritures relevées sur un vrai catalogue', () => {
|
||||||
|
const spells = [
|
||||||
|
spell('Arc Lightning', '1', 'Sorts de foudre'),
|
||||||
|
spell('Heal', 'NIVEAU 1', 'Sorts radiants'),
|
||||||
|
spell('Vampiric Greed', 'NIVEAU 3, ZONE', 'Sorts nécrotiques'),
|
||||||
|
spell('Beautify', 'Cantrip', 'Radiant'),
|
||||||
|
spell('False Face', 'Cantrip', 'Nécrotique'),
|
||||||
|
spell('Fire Step', 'CANTRIP UTILITAIRE', 'Feu'),
|
||||||
|
spell('Spark Buddy', 'CANTRIP UTILITAIRE', 'Foudre'),
|
||||||
|
spell('Razor Wind', 'Tour', 'Sorts de vent'),
|
||||||
|
spell('Rebuke', 'TOUR', 'Sorts radiants'),
|
||||||
|
spell('Flame Dart', 'Tour de magie', 'Sorts de feu'),
|
||||||
|
spell('Withering Touch', 'TOUR DE MAGIE', 'Sorts nécrotiques')
|
||||||
|
];
|
||||||
|
const { spells: out, changed } = harmonizeSpells(spells, FR);
|
||||||
|
expect(out.map(s => s.level)).toEqual(['1', '1', '3', 'Tour de magie', 'Tour de magie',
|
||||||
|
'Tour de magie utilitaire', 'Tour de magie utilitaire', 'Tour de magie', 'Tour de magie',
|
||||||
|
'Tour de magie', 'Tour de magie']);
|
||||||
|
expect(out.map(s => s.school)).toEqual(['Foudre', 'Radiant', 'Nécrotique', 'Radiant', 'Nécrotique',
|
||||||
|
'Feu', 'Foudre', 'Vent', 'Radiant', 'Feu', 'Nécrotique']);
|
||||||
|
expect(changed).toBe(11);
|
||||||
|
// Rien d'autre ne bouge, et l'entrée n'est pas modifiée.
|
||||||
|
expect(out.map(s => s.name)).toEqual(spells.map(s => s.name));
|
||||||
|
expect(spells[1].level).toBe('NIVEAU 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rend le même objet pour un sort déjà harmonisé', () => {
|
||||||
|
const tidy = spell('Zap', 'Tour de magie', 'Foudre');
|
||||||
|
const { spells: out, changed } = harmonizeSpells([tidy, spell('Heal', '1')], FR);
|
||||||
|
expect(changed).toBe(0);
|
||||||
|
expect(out[0]).toBe(tidy);
|
||||||
|
// Une seconde passe ne change plus rien.
|
||||||
|
const once = harmonizeSpells([spell('A', 'NIVEAU 2', 'Sorts de glace')], FR).spells;
|
||||||
|
expect(harmonizeSpells(once, FR).changed).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("aligne une proposition sur l'écriture du catalogue, sans toucher au catalogue", () => {
|
||||||
|
const catalogue = [spell('Zap', 'Tour de magie', 'Évocation'), spell('Bolt', '1', 'Évocation')];
|
||||||
|
const { spells: out } = harmonizeSpells([spell('Spark', 'cantrip', 'evocations')], FR, catalogue);
|
||||||
|
expect(out[0]).toMatchObject({ level: 'Tour de magie', school: 'Évocation' });
|
||||||
|
expect(catalogue[0].school).toBe('Évocation');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retient l’écriture la plus fréquente, sinon la plus courte', () => {
|
||||||
|
const out = harmonizeSpells([spell('A', 'Rituel'), spell('B', 'rituel'), spell('C', 'rituel'),
|
||||||
|
spell('D', '', 'Ombres'), spell('E', '', 'Ombre')], FR).spells;
|
||||||
|
expect(out.map(s => s.level)).toEqual(['rituel', 'rituel', 'rituel', '', '']);
|
||||||
|
expect(out.slice(3).map(s => s.school)).toEqual(['Ombre', 'Ombre']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('compareLevels', () => {
|
||||||
|
it('range les tours de magie avant le niveau 1, puis les nombres dans l’ordre', () => {
|
||||||
|
const levels = ['10', 'Rang II', '2', 'Tour de magie utilitaire', '1', 'Tour de magie'];
|
||||||
|
expect(levels.sort(compareLevels)).toEqual(
|
||||||
|
['Tour de magie', 'Tour de magie utilitaire', '1', '2', '10', 'Rang II']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import { Spell } from '../services/spell.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Harmonisation des niveaux et des écoles d'un catalogue de sorts.
|
||||||
|
*
|
||||||
|
* Les sorts proposés par l'IA sont relevés morceau par morceau : d'un morceau à l'autre, le
|
||||||
|
* même niveau sort écrit « 1 », « Niveau 1 » ou « NIVEAU 1, ZONE », le même palier « Tour de
|
||||||
|
* magie », « Tour » ou « Cantrip », la même école « Sorts de foudre » ou « Foudre ». Ici, une
|
||||||
|
* seule écriture par niveau et par école — sans rien demander à l'IA, donc toujours pareil :
|
||||||
|
*
|
||||||
|
* - un niveau numéroté s'écrit par son seul nombre (« Niveau 3, zone » → « 3 ») ; un palier
|
||||||
|
* propre au système garde son mot (« TIER 3, AOE » → « Tier 3 ») ;
|
||||||
|
* - les sorts de niveau 0 portent tous le même nom (« Tour de magie » en français, « Cantrip »
|
||||||
|
* en anglais), suivi de leur précision s'ils en ont une (« Cantrip utilitaire » → « Tour de
|
||||||
|
* magie utilitaire ») ;
|
||||||
|
* - une école perd son habillage (« Sorts de foudre » → « Foudre », « Fire spells » → « Fire ») ;
|
||||||
|
* - deux écritures qui ne diffèrent que par la casse, les accents ou un pluriel n'en font
|
||||||
|
* qu'une : pour un niveau la plus fréquente, pour une école la plus courte (le singulier).
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Nom des sorts de niveau 0, par langue de l'interface. */
|
||||||
|
export const CANTRIP_LABELS: Record<string, string> = { fr: 'Tour de magie', en: 'Cantrip' };
|
||||||
|
|
||||||
|
export function cantripLabel(language: string): string {
|
||||||
|
return CANTRIP_LABELS[language] ?? CANTRIP_LABELS['fr'];
|
||||||
|
}
|
||||||
|
|
||||||
|
const clean = (value: unknown): string => (value == null ? '' : String(value)).replace(/\s+/g, ' ').trim();
|
||||||
|
|
||||||
|
/** Comparaison sans casse ni accents. */
|
||||||
|
const fold = (text: string): string => text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
|
||||||
|
|
||||||
|
const isLetterOrDigit = (char: string): boolean => /[\p{L}\d]/u.test(char);
|
||||||
|
|
||||||
|
/** Début de `words` égal à l'une des suites de mots de `heads` (sans casse ni accents) : sa longueur, sinon 0. */
|
||||||
|
function leadingWords(words: string[], heads: string[][]): number {
|
||||||
|
const folded = words.map(fold);
|
||||||
|
const found = heads.find(head => head.every((word, i) => folded[i] === word));
|
||||||
|
return found ? found.length : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Noms donnés aux sorts de niveau 0, du plus long au plus court. */
|
||||||
|
const CANTRIP_NAMES = [
|
||||||
|
['tour', 'de', 'magie'], ['tours', 'de', 'magie'], ['sort', 'mineur'], ['sorts', 'mineurs'],
|
||||||
|
['minor', 'spell'], ['minor', 'spells'], ['cantrip'], ['cantrips'], ['tour'], ['tours']
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Mots d'un niveau, ponctuation de fin de mot mise de côté : « Cantrip, utilitaire » → Cantrip · utilitaire. */
|
||||||
|
const levelWords = (text: string): string[] => text.split(' ').map(withoutTrailingPunctuation).filter(Boolean);
|
||||||
|
|
||||||
|
const PUNCTUATION = new Set([',', ':', ';', '.']);
|
||||||
|
|
||||||
|
function withoutTrailingPunctuation(word: string): string {
|
||||||
|
let end = word.length;
|
||||||
|
while (end > 0 && PUNCTUATION.has(word.charAt(end - 1))) end--;
|
||||||
|
return word.slice(0, end);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de mots que prend le nom des sorts de niveau 0 en tête du niveau (0 : ce n'en est pas un). */
|
||||||
|
function cantripLead(text: string): number {
|
||||||
|
return leadingWords(levelWords(text), CANTRIP_NAMES);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mots qui annoncent un niveau numéroté : « Niveau 3 », « Niv. 3 », « Level 3 ». */
|
||||||
|
const LEVEL_WORDS = new Set(['niveau', 'niv', 'level', 'lvl']);
|
||||||
|
/** « Sort de niveau 3 », « Spell of level 3 ». */
|
||||||
|
const LEVEL_INTROS = [['sort', 'de'], ['sorts', 'de'], ['spell', 'of'], ['spells', 'of']];
|
||||||
|
/** « 1er », « 3e », « 1st »… */
|
||||||
|
const ORDINALS = new Set(['er', 're', 'e', 'eme', 'st', 'nd', 'rd', 'th']);
|
||||||
|
|
||||||
|
/** Le nombre en tête de `text`, s'il se lit comme un niveau : pas une plage (« 1-3 »), ni un dé (« 1d6 »). */
|
||||||
|
function leadingLevelNumber(text: string): number | null {
|
||||||
|
const digits = /^\d+/.exec(text)?.[0];
|
||||||
|
if (!digits) return null;
|
||||||
|
const after = text.slice(digits.length);
|
||||||
|
if (/^\s*[/–-]\s*\d/.test(after)) return null;
|
||||||
|
const suffix = /^\p{L}+/u.exec(after)?.[0] ?? '';
|
||||||
|
if (suffix && !ORDINALS.has(fold(suffix))) return null;
|
||||||
|
return Number(digits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Niveau numéroté : « 3 », « 3e niveau », « Niveau 3, zone », « Sort de niveau 3 » → 3. */
|
||||||
|
function numberedLevel(text: string): number | null {
|
||||||
|
const direct = leadingLevelNumber(text);
|
||||||
|
if (direct !== null) return direct;
|
||||||
|
let words = levelWords(text);
|
||||||
|
words = words.slice(leadingWords(words, LEVEL_INTROS));
|
||||||
|
if (!words.length || !LEVEL_WORDS.has(fold(words[0]))) return null;
|
||||||
|
return leadingLevelNumber(words.slice(1).join(' '));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paliers propres à un système, gardés avec leur mot : « Tier 3 », « Rang 2 », « Cercle 4 ». */
|
||||||
|
const TIER_WORDS = new Set(['tier', 'rang', 'rank', 'cercle', 'circle', 'palier']);
|
||||||
|
|
||||||
|
/** « TIER 3, AOE » → « Tier 3 » : le mot du système et son nombre, sans ce qui suit. */
|
||||||
|
function tieredLevel(text: string): string | null {
|
||||||
|
const words = levelWords(text);
|
||||||
|
if (words.length < 2 || !TIER_WORDS.has(fold(words[0]))) return null;
|
||||||
|
const number = leadingLevelNumber(words.slice(1).join(' '));
|
||||||
|
return number === null ? null : `${capitalize(words[0].toLowerCase())} ${number}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROMAN = /^[IVXLCDM]+$/;
|
||||||
|
|
||||||
|
/** « TOUR DE MAGIE » → « Tour de magie » ; un texte déjà en minuscules n'est pas touché. */
|
||||||
|
function tidyCase(text: string): string {
|
||||||
|
const letters = text.replace(/[^\p{L}]/gu, '');
|
||||||
|
if (letters.length < 4 || text !== text.toUpperCase()) return text;
|
||||||
|
const lowered = text.split(' ').map(word => (ROMAN.test(word) ? word : word.toLowerCase())).join(' ');
|
||||||
|
return lowered.charAt(0).toUpperCase() + lowered.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const capitalize = (text: string): string => text.charAt(0).toUpperCase() + text.slice(1);
|
||||||
|
|
||||||
|
/** Le niveau désigne-t-il les sorts de niveau 0 (tour de magie, cantrip…) ? */
|
||||||
|
export function isCantrip(level: string | null | undefined): boolean {
|
||||||
|
return cantripLead(clean(level)) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Écriture unique d'un niveau. `cantrip` : nom donné aux sorts de niveau 0. */
|
||||||
|
export function normalizeLevel(raw: string | null | undefined, cantrip: string): string {
|
||||||
|
const text = clean(raw);
|
||||||
|
if (!text) return '';
|
||||||
|
const lead = cantripLead(text);
|
||||||
|
if (lead) {
|
||||||
|
const rest = levelWords(text).slice(lead).join(' ');
|
||||||
|
return rest && isLetterOrDigit(rest.charAt(0)) ? `${cantrip} ${rest.toLowerCase()}` : cantrip;
|
||||||
|
}
|
||||||
|
const numbered = numberedLevel(text);
|
||||||
|
if (numbered !== null) return String(numbered);
|
||||||
|
return tieredLevel(text) ?? tidyCase(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** « Sorts de », « Sortilèges », « Spells of »… : toujours retirés en tête d'une école. */
|
||||||
|
const SCHOOL_HEADS = new Set(['sort', 'sorts', 'sortilege', 'sortileges', 'spell', 'spells']);
|
||||||
|
/** « École de », « Magie du », « School of »… : retirés seulement avec leur article. */
|
||||||
|
const SCHOOL_HEADS_LINKED = new Set(['ecole', 'ecoles', 'magie', 'magies', 'liste', 'listes', 'school', 'schools', 'magic']);
|
||||||
|
/** « Fire spells », « Fire magic » : retirés en fin d'école. */
|
||||||
|
const SCHOOL_TAILS = new Set(['spell', 'spells', 'magic', 'school']);
|
||||||
|
|
||||||
|
/** `words` sans l'article qui les ouvre (« de la », « du », « d' », « of the »…), ou null s'il n'y en a pas. */
|
||||||
|
function withoutLink(words: string[]): string[] | null {
|
||||||
|
if (!words.length) return null;
|
||||||
|
const first = fold(words[0]);
|
||||||
|
if (first === 'du' || first === 'des') return words.slice(1);
|
||||||
|
if (first.startsWith("d'") || first.startsWith('d’')) return [words[0].slice(2), ...words.slice(1)];
|
||||||
|
if (first !== 'de' && first !== 'of') return null;
|
||||||
|
const second = fold(words[1] ?? '');
|
||||||
|
if (second === 'la' || second === 'the') return words.slice(2);
|
||||||
|
if (second.startsWith("l'") || second.startsWith('l’')) return [words[1].slice(2), ...words.slice(2)];
|
||||||
|
return words.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Une école sans son habillage : « Sorts de foudre » → « Foudre ». */
|
||||||
|
export function tidySchool(raw: string | null | undefined): string {
|
||||||
|
const text = clean(raw);
|
||||||
|
if (!text) return '';
|
||||||
|
let words = text.split(' ');
|
||||||
|
const head = fold(words[0]);
|
||||||
|
if (SCHOOL_HEADS.has(head) || SCHOOL_HEADS_LINKED.has(head)) {
|
||||||
|
const linked = withoutLink(words.slice(1));
|
||||||
|
if (linked) words = linked;
|
||||||
|
else if (SCHOOL_HEADS.has(head)) words = words.slice(1);
|
||||||
|
}
|
||||||
|
if (words.length > 1 && SCHOOL_TAILS.has(fold(words[words.length - 1]))) words = words.slice(0, -1);
|
||||||
|
const bare = words.join(' ').trim();
|
||||||
|
return capitalize(tidyCase(bare || text));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deux écoles de même clé n'en font qu'une : casse, accents et pluriel ignorés. */
|
||||||
|
function schoolKey(tidy: string): string {
|
||||||
|
const key = fold(tidy);
|
||||||
|
return key.length > 4 && key.endsWith('s') ? key.slice(0, -1) : key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pour chaque clé, l'écriture retenue. Niveaux : la plus fréquente, sinon la plus courte.
|
||||||
|
* Écoles (`shortestFirst`) : la plus courte d'abord — entre « Radiants » et « Radiant », le
|
||||||
|
* singulier —, sinon la plus fréquente. À égalité, la première rencontrée.
|
||||||
|
*/
|
||||||
|
function canonicalForms(values: string[], keyOf: (value: string) => string, shortestFirst = false): Map<string, string> {
|
||||||
|
const counts = new Map<string, Map<string, number>>();
|
||||||
|
for (const value of values) {
|
||||||
|
if (!value) continue;
|
||||||
|
const forms = counts.get(keyOf(value)) ?? new Map<string, number>();
|
||||||
|
forms.set(value, (forms.get(value) ?? 0) + 1);
|
||||||
|
counts.set(keyOf(value), forms);
|
||||||
|
}
|
||||||
|
const better = (form: string, count: number, best: string, bestCount: number): boolean => {
|
||||||
|
const shorter = form.length < best.length;
|
||||||
|
const sameLength = form.length === best.length;
|
||||||
|
return shortestFirst
|
||||||
|
? shorter || (sameLength && count > bestCount)
|
||||||
|
: count > bestCount || (count === bestCount && shorter);
|
||||||
|
};
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
for (const [key, forms] of counts) {
|
||||||
|
let best = '';
|
||||||
|
let bestCount = 0;
|
||||||
|
for (const [form, count] of forms) {
|
||||||
|
if (!best || better(form, count, best, bestCount)) {
|
||||||
|
best = form;
|
||||||
|
bestCount = count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.set(key, best);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Harmonized<T> {
|
||||||
|
/** Les sorts, dans le même ordre ; un sort inchangé est le même objet qu'en entrée. */
|
||||||
|
spells: T[];
|
||||||
|
/** Nombre de sorts dont le niveau ou l'école a changé. */
|
||||||
|
changed: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Écrit de la même façon les niveaux et les écoles de `spells`.
|
||||||
|
*
|
||||||
|
* @param cantrip nom donné aux sorts de niveau 0 (cf. cantripLabel)
|
||||||
|
* @param reference sorts déjà là (catalogue, propositions précédentes) : ils ne sont pas
|
||||||
|
* modifiés, mais leurs écritures comptent pour choisir celle qui est retenue
|
||||||
|
*/
|
||||||
|
export function harmonizeSpells<T extends Spell>(spells: T[], cantrip: string, reference: Spell[] = []): Harmonized<T> {
|
||||||
|
const levelOf = (spell: Spell) => normalizeLevel(spell.level, cantrip);
|
||||||
|
const schoolOf = (spell: Spell) => tidySchool(spell.school);
|
||||||
|
const all = [...reference, ...spells];
|
||||||
|
const levels = canonicalForms(all.map(levelOf), fold);
|
||||||
|
const schools = canonicalForms(all.map(schoolOf), schoolKey, true);
|
||||||
|
|
||||||
|
let changed = 0;
|
||||||
|
const out = spells.map(spell => {
|
||||||
|
const level = levelOf(spell);
|
||||||
|
const school = schoolOf(spell);
|
||||||
|
const nextLevel = level ? levels.get(fold(level)) ?? level : '';
|
||||||
|
const nextSchool = school ? schools.get(schoolKey(school)) ?? school : '';
|
||||||
|
if (nextLevel === clean(spell.level) && nextSchool === clean(spell.school)) return spell;
|
||||||
|
changed++;
|
||||||
|
return { ...spell, level: nextLevel, school: nextSchool };
|
||||||
|
});
|
||||||
|
return { spells: out, changed };
|
||||||
|
}
|
||||||
|
|
||||||
|
const NATURAL = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
|
||||||
|
/** Ordre des niveaux : tours de magie d'abord, puis « 2 » avant « 10 », puis le reste. */
|
||||||
|
export function compareLevels(a: string, b: string): number {
|
||||||
|
const ca = isCantrip(a);
|
||||||
|
const cb = isCantrip(b);
|
||||||
|
if (ca !== cb) return ca ? -1 : 1;
|
||||||
|
return NATURAL.compare(a, b);
|
||||||
|
}
|
||||||
@@ -3,9 +3,11 @@ import { TranslatePipe } from '@ngx-translate/core';
|
|||||||
import { LucideAngularModule, Sparkles } from 'lucide-angular';
|
import { LucideAngularModule, Sparkles } from 'lucide-angular';
|
||||||
import { Subscription } from 'rxjs';
|
import { Subscription } from 'rxjs';
|
||||||
import { GameSystemService } from '../../services/game-system.service';
|
import { GameSystemService } from '../../services/game-system.service';
|
||||||
import { ProposedSpell } from '../../services/spell.model';
|
import { LanguageService } from '../../services/language.service';
|
||||||
|
import { ProposedSpell, Spell } from '../../services/spell.model';
|
||||||
import { TemplateField } from '../../services/template.model';
|
import { TemplateField } from '../../services/template.model';
|
||||||
import { summary } from '../spell-catalog.util';
|
import { summary } from '../spell-catalog.util';
|
||||||
|
import { cantripLabel, harmonizeSpells } from '../spell-harmonize.util';
|
||||||
import {
|
import {
|
||||||
ReadingChunk, RuleText, chunksFor, isInCatalogue, suggestedSections
|
ReadingChunk, RuleText, chunksFor, isInCatalogue, suggestedSections
|
||||||
} from '../spell-proposal.util';
|
} from '../spell-proposal.util';
|
||||||
@@ -40,14 +42,18 @@ export class SpellProposalComponent implements OnInit, OnDestroy {
|
|||||||
readonly Sparkles = Sparkles;
|
readonly Sparkles = Sparkles;
|
||||||
|
|
||||||
private readonly service = inject(GameSystemService);
|
private readonly service = inject(GameSystemService);
|
||||||
|
private readonly language = inject(LanguageService);
|
||||||
|
|
||||||
/** Règles affichées dans l'éditeur (enregistrées ou non). */
|
/** Règles affichées dans l'éditeur (enregistrées ou non). */
|
||||||
@Input() rules: RuleText[] = [];
|
@Input() rules: RuleText[] = [];
|
||||||
@Input() systemName = '';
|
@Input() systemName = '';
|
||||||
/** Champs du modèle de sort, que l'IA remplit quand le texte donne leur valeur. */
|
/** Champs du modèle de sort, que l'IA remplit quand le texte donne leur valeur. */
|
||||||
@Input() fields: TemplateField[] = [];
|
@Input() fields: TemplateField[] = [];
|
||||||
/** Sorts déjà dans le catalogue : jamais proposés une seconde fois. */
|
/**
|
||||||
@Input() catalogue: { name: string }[] = [];
|
* Sorts déjà dans le catalogue : jamais proposés une seconde fois. Leurs niveaux et leurs
|
||||||
|
* écoles servent aussi de modèle d'écriture aux sorts proposés.
|
||||||
|
*/
|
||||||
|
@Input() catalogue: Spell[] = [];
|
||||||
|
|
||||||
/** Sorts cochés que le parent ajoute au catalogue. */
|
/** Sorts cochés que le parent ajoute au catalogue. */
|
||||||
@Output() add = new EventEmitter<ProposedSpell[]>();
|
@Output() add = new EventEmitter<ProposedSpell[]>();
|
||||||
@@ -125,7 +131,12 @@ export class SpellProposalComponent implements OnInit, OnDestroy {
|
|||||||
avoid: [...this.catalogue.map(s => s.name), ...this.found.map(f => f.spell.name)].filter(n => n?.trim())
|
avoid: [...this.catalogue.map(s => s.name), ...this.found.map(f => f.spell.name)].filter(n => n?.trim())
|
||||||
}).subscribe({
|
}).subscribe({
|
||||||
next: response => {
|
next: response => {
|
||||||
for (const spell of response.spells ?? []) {
|
// D'un morceau à l'autre, l'IA n'écrit pas un niveau ou une école de la même façon
|
||||||
|
// (« 1 », « Niveau 1 » ; « Tour », « Cantrip ») : une seule écriture, alignée sur le
|
||||||
|
// catalogue et sur les sorts déjà relevés.
|
||||||
|
const incoming = harmonizeSpells(response.spells ?? [], cantripLabel(this.language.current),
|
||||||
|
[...this.catalogue, ...this.found.map(f => f.spell)]).spells;
|
||||||
|
for (const spell of incoming) {
|
||||||
if (this.found.some(f => this.key(f.spell.name) === this.key(spell.name))) continue;
|
if (this.found.some(f => this.key(f.spell.name) === this.key(spell.name))) continue;
|
||||||
this.found.push({ spell, source: chunk.title });
|
this.found.push({ spell, source: chunk.title });
|
||||||
if (!this.isInCatalogue(spell.name)) this.selected.add(this.key(spell.name));
|
if (!this.isInCatalogue(spell.name)) this.selected.add(this.key(spell.name));
|
||||||
|
|||||||
@@ -52,6 +52,22 @@ export interface CampaignImportProposal {
|
|||||||
npcs?: NpcProposal[];
|
npcs?: NpcProposal[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compte rendu d'un import découpé d'après la structure du livre (absent si l'IA a
|
||||||
|
* reconstruit l'arborescence).
|
||||||
|
*/
|
||||||
|
export interface CampaignImportOutcome {
|
||||||
|
/** 'bookmarks' (table des matières du PDF) ou 'headings' (titres repérés). */
|
||||||
|
splitMethod?: string | null;
|
||||||
|
sourceLanguage?: string | null;
|
||||||
|
/** Textes restés dans la langue du livre faute de traduction. */
|
||||||
|
untranslated: number;
|
||||||
|
/** Lots de scènes pour lesquels l'IA n'a pas rendu ses aides. */
|
||||||
|
skippedAids: number;
|
||||||
|
/** Les passes de l'IA n'ont pas abouti : campagne livrée avec le seul texte du livre. */
|
||||||
|
aiInterrupted: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
/** Récapitulatif renvoyé après création effective des entités. */
|
/** Récapitulatif renvoyé après création effective des entités. */
|
||||||
export interface CampaignImportApplyResult {
|
export interface CampaignImportApplyResult {
|
||||||
arcsCreated: number;
|
arcsCreated: number;
|
||||||
@@ -81,5 +97,5 @@ export type CampaignImportStreamEvent =
|
|||||||
sceneCount: number;
|
sceneCount: number;
|
||||||
npcCount: number;
|
npcCount: number;
|
||||||
}
|
}
|
||||||
| { type: 'done'; arcs: ArcProposal[]; npcs: NpcProposal[] }
|
| { type: 'done'; arcs: ArcProposal[]; npcs: NpcProposal[]; outcome?: CampaignImportOutcome | null }
|
||||||
| { type: 'error'; message: string };
|
| { type: 'error'; message: string };
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
CampaignImportStreamEvent
|
CampaignImportStreamEvent
|
||||||
} from './campaign-import.model';
|
} from './campaign-import.model';
|
||||||
import { LanguageService } from './language.service';
|
import { LanguageService } from './language.service';
|
||||||
import { parseSseStream, sseFetch } from '../shared/sse.util';
|
import { parseSseStream, replaceNetworkError, sseFetch } from '../shared/sse.util';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Service HTTP pour l'import d'un PDF de campagne.
|
* Service HTTP pour l'import d'un PDF de campagne.
|
||||||
@@ -32,7 +32,8 @@ export class CampaignImportService {
|
|||||||
body: form
|
body: form
|
||||||
},
|
},
|
||||||
(body, subscriber) => this.consumeSse(body, subscriber)
|
(body, subscriber) => this.consumeSse(body, subscriber)
|
||||||
);
|
// Connexion coupée : le navigateur ne donne qu'un texte brut (« Error in input stream »).
|
||||||
|
).pipe(replaceNetworkError(() => this.translate.instant('services.importInterrupted')));
|
||||||
}
|
}
|
||||||
|
|
||||||
applyStructure(campaignId: string, proposal: CampaignImportProposal): Observable<CampaignImportApplyResult> {
|
applyStructure(campaignId: string, proposal: CampaignImportProposal): Observable<CampaignImportApplyResult> {
|
||||||
@@ -68,7 +69,7 @@ export class CampaignImportService {
|
|||||||
const obj = JSON.parse(data);
|
const obj = JSON.parse(data);
|
||||||
if (event === 'done') {
|
if (event === 'done') {
|
||||||
terminated = true;
|
terminated = true;
|
||||||
subscriber.next({ type: 'done', arcs: obj.arcs ?? [], npcs: obj.npcs ?? [] });
|
subscriber.next({ type: 'done', arcs: obj.arcs ?? [], npcs: obj.npcs ?? [], outcome: obj.outcome ?? null });
|
||||||
subscriber.complete();
|
subscriber.complete();
|
||||||
} else {
|
} else {
|
||||||
subscriber.next({ type: 'progress', ...obj });
|
subscriber.next({ type: 'progress', ...obj });
|
||||||
|
|||||||
@@ -47,7 +47,11 @@ export type RulesImportStreamEvent =
|
|||||||
| { type: 'status'; message: string }
|
| { type: 'status'; message: string }
|
||||||
| { type: 'done'; sections: Record<string, string>; pageCount: number; ocrPageCount: number;
|
| { type: 'done'; sections: Record<string, string>; pageCount: number; ocrPageCount: number;
|
||||||
/** Règles en deux langues : {fr|en → sections} ; langue d'origine du livre. */
|
/** Règles en deux langues : {fr|en → sections} ; langue d'origine du livre. */
|
||||||
sectionsByLanguage?: Record<string, Record<string, string>>; sourceLanguage?: string | null }
|
sectionsByLanguage?: Record<string, Record<string, string>>; sourceLanguage?: string | null;
|
||||||
|
/** Titres des sections que la traduction n'a pas pu traiter (texte d'origine gardé). */
|
||||||
|
untranslatedTitles?: string[];
|
||||||
|
/** Découpage du livre : « bookmarks » ou « headings » (sans IA), « ai », ou absent. */
|
||||||
|
splitMethod?: string | null }
|
||||||
| { type: 'error'; message: string };
|
| { type: 'error'; message: string };
|
||||||
|
|
||||||
/** Payload de creation/mise a jour (sans id). */
|
/** Payload de creation/mise a jour (sans id). */
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
SheetFieldProposal, SheetProposalRequest
|
SheetFieldProposal, SheetProposalRequest
|
||||||
} from './game-system.model';
|
} from './game-system.model';
|
||||||
import { LanguageService } from './language.service';
|
import { LanguageService } from './language.service';
|
||||||
import { parseSseStream, sseFetch } from '../shared/sse.util';
|
import { parseSseStream, replaceNetworkError, sseFetch } from '../shared/sse.util';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Service HTTP pour les GameSystems (systèmes de JDR).
|
* Service HTTP pour les GameSystems (systèmes de JDR).
|
||||||
@@ -110,7 +110,8 @@ export class GameSystemService {
|
|||||||
body: form
|
body: form
|
||||||
},
|
},
|
||||||
(body, subscriber) => this.consumeImportSse(body, subscriber)
|
(body, subscriber) => this.consumeImportSse(body, subscriber)
|
||||||
);
|
// Connexion coupée : le navigateur ne donne qu'un texte brut (« Error in input stream »).
|
||||||
|
).pipe(replaceNetworkError(() => this.translate.instant('services.importInterrupted')));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mappe les évènements SSE bruts vers les évènements d'import typés. */
|
/** Mappe les évènements SSE bruts vers les évènements d'import typés. */
|
||||||
|
|||||||
@@ -37,7 +37,7 @@
|
|||||||
|
|
||||||
.spell-level {
|
.spell-level {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
max-width: 8rem;
|
max-width: 12rem;
|
||||||
padding: 0.1rem 0.45rem;
|
padding: 0.1rem 0.45rem;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: rgba(108, 99, 255, 0.2);
|
background: rgba(108, 99, 255, 0.2);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||||
import { parseSseStream, sseFetch, SseEvent } from './sse.util';
|
import { firstValueFrom, throwError } from 'rxjs';
|
||||||
|
import { isNetworkError, parseSseStream, replaceNetworkError, sseFetch, SseEvent } from './sse.util';
|
||||||
|
|
||||||
/** Construit un ReadableStream à partir d'une chaîne (un seul chunk). */
|
/** Construit un ReadableStream à partir d'une chaîne (un seul chunk). */
|
||||||
function streamFrom(text: string): ReadableStream<Uint8Array> {
|
function streamFrom(text: string): ReadableStream<Uint8Array> {
|
||||||
@@ -110,3 +111,23 @@ describe('sseFetch', () => {
|
|||||||
expect(abortedSignal?.aborted).toBe(true);
|
expect(abortedSignal?.aborted).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('replaceNetworkError', () => {
|
||||||
|
const readable = () => 'Import interrompu.';
|
||||||
|
|
||||||
|
it('reconnaît une coupure réseau quel que soit le texte du navigateur', () => {
|
||||||
|
expect(isNetworkError(new TypeError('Error in input stream'))).toBe(true);
|
||||||
|
expect(isNetworkError(new TypeError('Failed to fetch'))).toBe(true);
|
||||||
|
expect(isNetworkError(new Error('HTTP 502'))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('remplace le texte brut du navigateur par un message lisible', async () => {
|
||||||
|
const failing = throwError(() => new TypeError('Error in input stream')).pipe(replaceNetworkError(readable));
|
||||||
|
await expect(firstValueFrom(failing)).rejects.toThrow('Import interrompu.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("laisse passer une erreur déjà parlante (message du serveur)", async () => {
|
||||||
|
const failing = throwError(() => new Error('Le fournisseur IA a refusé la clé.')).pipe(replaceNetworkError(readable));
|
||||||
|
await expect(firstValueFrom(failing)).rejects.toThrow('Le fournisseur IA a refusé la clé.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Observable, Subscriber } from 'rxjs';
|
import { MonoTypeOperatorFunction, Observable, Subscriber, catchError, throwError } from 'rxjs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plumbing SSE mutualisé entre les services qui streament depuis le backend
|
* Plumbing SSE mutualisé entre les services qui streament depuis le backend
|
||||||
@@ -108,3 +108,21 @@ export function sseFetch<T>(
|
|||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vrai si l'erreur vient du réseau (connexion coupée, serveur injoignable). `fetch()` et la
|
||||||
|
* lecture de son flux lèvent alors un `TypeError` dont le texte dépend du navigateur
|
||||||
|
* (« Failed to fetch », « network error », « Error in input stream »…) : rien de lisible
|
||||||
|
* pour l'utilisateur.
|
||||||
|
*/
|
||||||
|
export function isNetworkError(err: unknown): boolean {
|
||||||
|
return err instanceof TypeError;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remplace une erreur réseau par un message lisible (fourni à la demande, pour être traduit
|
||||||
|
* dans la langue du moment). Les autres erreurs, déjà parlantes, passent telles quelles.
|
||||||
|
*/
|
||||||
|
export function replaceNetworkError<T>(message: () => string): MonoTypeOperatorFunction<T> {
|
||||||
|
return catchError((err: unknown) => throwError(() => (isNetworkError(err) ? new Error(message()) : err)));
|
||||||
|
}
|
||||||
|
|||||||
@@ -676,7 +676,7 @@
|
|||||||
"pageTitle": "Import a campaign",
|
"pageTitle": "Import a campaign",
|
||||||
"back": "Back to the campaign",
|
"back": "Back to the campaign",
|
||||||
"title": "Import a campaign PDF",
|
"title": "Import a campaign PDF",
|
||||||
"subtitle": "The AI proposes an arc → adventure → scene tree. You review and adjust it before creating anything.",
|
"subtitle": "The book is split into arcs, adventures and scenes from its table of contents, with its text as written. The AI adds a synopsis for each scene and the NPC sheets. You review and adjust before creating anything.",
|
||||||
"importing": "Import in progress…",
|
"importing": "Import in progress…",
|
||||||
"choosePdf": "Choose a campaign PDF",
|
"choosePdf": "Choose a campaign PDF",
|
||||||
"phaseExtracting": "Extracting text…",
|
"phaseExtracting": "Extracting text…",
|
||||||
@@ -719,9 +719,14 @@
|
|||||||
"chapter": "Adventure",
|
"chapter": "Adventure",
|
||||||
"addArc": "Add an arc",
|
"addArc": "Add an arc",
|
||||||
"npcReviewTitle": "Detected NPCs and creatures ({{n}})",
|
"npcReviewTitle": "Detected NPCs and creatures ({{n}})",
|
||||||
"npcReviewHint": "Check the ones to create in the campaign (description taken from the book). Those already present in the campaign are greyed out and will not be recreated.",
|
"npcReviewHint": "Check the ones to create in the campaign (sheet written by the AI from the book). Those already present in the campaign are greyed out and will not be recreated.",
|
||||||
"creating": "Creating…",
|
"creating": "Creating…",
|
||||||
"createInCampaign": "Create in the campaign"
|
"createInCampaign": "Create in the campaign",
|
||||||
|
"noteSplitBookmarks": "Split from the table of contents of the PDF. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
|
||||||
|
"noteSplitHeadings": "Split from the headings of the book. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
|
||||||
|
"noteAiInterrupted": "The AI could not finish its work. The campaign is proposed with the text of the book, without translation or NPC sheets; each synopsis is the beginning of the text of its scene.",
|
||||||
|
"noteSkippedAids": "The AI did not answer for {{n}} batch(es) of scenes: their synopsis is the beginning of their text.",
|
||||||
|
"noteUntranslated": "Incomplete translation: {{n}} text(s) stayed in the language of the book."
|
||||||
},
|
},
|
||||||
"chapterCreate": {
|
"chapterCreate": {
|
||||||
"titleQuest": "Create a new adventure",
|
"titleQuest": "Create a new adventure",
|
||||||
@@ -1266,7 +1271,7 @@
|
|||||||
"rulesHint": "One section = one theme. The AI will automatically inject the relevant sections based on what it generates (combat → Combat/Monsters, NPC → Classes, arc → Lore/Factions).",
|
"rulesHint": "One section = one theme. The AI will automatically inject the relevant sections based on what it generates (combat → Combat/Monsters, NPC → Classes, arc → Lore/Factions).",
|
||||||
"importButton": "Import a rules PDF",
|
"importButton": "Import a rules PDF",
|
||||||
"importInProgress": "Importing…",
|
"importInProgress": "Importing…",
|
||||||
"importHint": "The AI suggests a breakdown into sections — you review it before saving.",
|
"importHint": "The book is split into sections following its table of contents — you review it before saving.",
|
||||||
"sectionsFound": "Sections found: {{titles}}",
|
"sectionsFound": "Sections found: {{titles}}",
|
||||||
"sectionTitlePlaceholder": "Section name (e.g. Combat)",
|
"sectionTitlePlaceholder": "Section name (e.g. Combat)",
|
||||||
"removeSection": "Remove this section",
|
"removeSection": "Remove this section",
|
||||||
@@ -1337,7 +1342,15 @@
|
|||||||
"sectionSize": "{{count}} chars",
|
"sectionSize": "{{count}} chars",
|
||||||
"needsName": "Give the system a name to save it.",
|
"needsName": "Give the system a name to save it.",
|
||||||
"invalidFields": "This sheet has a field with no name or a duplicate: fix it to save.",
|
"invalidFields": "This sheet has a field with no name or a duplicate: fix it to save.",
|
||||||
"saveFailed": "Saving failed. Your changes are still on screen: try again."
|
"saveFailed": "Saving failed. Your changes are still on screen: try again.",
|
||||||
|
"importPartlyTranslated": "Translation incomplete: {{count}} of {{total}} section(s) could not be translated and keep their original text in the {{target}} tab ({{titles}}).",
|
||||||
|
"importNotTranslated": "The translation to the {{target}} tab did not complete: only the {{source}} tab is filled. The app and the AI use these rules in both languages.",
|
||||||
|
"sectionEdit": "Edit",
|
||||||
|
"sectionDone": "Done",
|
||||||
|
"sectionEmpty": "Empty section — click to write its rules.",
|
||||||
|
"sectionEditHint": "Markdown formatting: ### subheading, **bold**, - list, | table |. Click Done to read the result.",
|
||||||
|
"importSplitBookmarks": "Sections taken from the PDF's table of contents, without AI: their titles are those of the book.",
|
||||||
|
"importSplitHeadings": "Sections found from the book's headings, without AI: their titles are those of the book."
|
||||||
},
|
},
|
||||||
"ollamaModelManager": {
|
"ollamaModelManager": {
|
||||||
"installedModels": "Installed models",
|
"installedModels": "Installed models",
|
||||||
@@ -3611,13 +3624,16 @@
|
|||||||
"foundIntro": "Tick the spells to add to the catalogue. Existing spells are left untouched, and nothing is saved until you save the system.",
|
"foundIntro": "Tick the spells to add to the catalogue. Existing spells are left untouched, and nothing is saved until you save the system.",
|
||||||
"already": "already in the catalogue",
|
"already": "already in the catalogue",
|
||||||
"source": "from “{{section}}”",
|
"source": "from “{{section}}”",
|
||||||
"reviewHint": "The name and a passage of each spell were found in your rules. The description and values are picked out by the AI: review them after adding.",
|
"reviewHint": "The description of each spell is taken from your rules, word for word. The level, school and field values are picked out by the AI: review them after adding.",
|
||||||
"droppedOne": "1 spell was discarded: its name or the quoted passage was not found in your rules.",
|
"droppedOne": "1 spell was discarded: its name or the quoted passage was not found in your rules.",
|
||||||
"droppedMany": "{{count}} spells were discarded: their name or the quoted passage was not found in your rules.",
|
"droppedMany": "{{count}} spells were discarded: their name or the quoted passage was not found in your rules.",
|
||||||
"add": "Add the ticked spells ({{count}})",
|
"add": "Add the ticked spells ({{count}})",
|
||||||
"added": "{{count}} spell(s) added at the end of the catalogue. Review them, then save the system.",
|
"added": "{{count}} spell(s) added at the end of the catalogue. Review them, then save the system.",
|
||||||
"close": "Close the suggestion"
|
"close": "Close the suggestion"
|
||||||
}
|
},
|
||||||
|
"harmonize": "Harmonize levels and schools ({{count}})",
|
||||||
|
"harmonizeTitle": "Writes levels and schools one single way: “Level 1” becomes “1”, “Tour de magie” becomes “Cantrip”, “Fire spells” becomes “Fire”.",
|
||||||
|
"harmonized": "{{count}} spell(s) rewritten: levels and schools are now written one single way. Save to keep."
|
||||||
},
|
},
|
||||||
"sheetSpells": {
|
"sheetSpells": {
|
||||||
"title": "Known spells",
|
"title": "Known spells",
|
||||||
|
|||||||
@@ -676,7 +676,7 @@
|
|||||||
"pageTitle": "Importer une campagne",
|
"pageTitle": "Importer une campagne",
|
||||||
"back": "Retour à la campagne",
|
"back": "Retour à la campagne",
|
||||||
"title": "Importer un PDF de campagne",
|
"title": "Importer un PDF de campagne",
|
||||||
"subtitle": "L'IA propose une arborescence arc → aventure → scène. Vous la révisez et l'ajustez avant de créer quoi que ce soit.",
|
"subtitle": "Le livre est découpé en arcs, aventures et scènes d'après sa table des matières, avec son texte tel qu'il est écrit. L'IA y ajoute un synopsis par scène et les fiches des PNJ. Vous révisez et ajustez avant de créer quoi que ce soit.",
|
||||||
"importing": "Import en cours…",
|
"importing": "Import en cours…",
|
||||||
"choosePdf": "Choisir un PDF de campagne",
|
"choosePdf": "Choisir un PDF de campagne",
|
||||||
"phaseExtracting": "Extraction du texte…",
|
"phaseExtracting": "Extraction du texte…",
|
||||||
@@ -719,9 +719,14 @@
|
|||||||
"chapter": "Aventure",
|
"chapter": "Aventure",
|
||||||
"addArc": "Ajouter un arc",
|
"addArc": "Ajouter un arc",
|
||||||
"npcReviewTitle": "PNJ et créatures détectés ({{n}})",
|
"npcReviewTitle": "PNJ et créatures détectés ({{n}})",
|
||||||
"npcReviewHint": "Cochez ceux à créer dans la campagne (description issue du livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
|
"npcReviewHint": "Cochez ceux à créer dans la campagne (fiche rédigée par l'IA d'après le livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
|
||||||
"creating": "Création…",
|
"creating": "Création…",
|
||||||
"createInCampaign": "Créer dans la campagne"
|
"createInCampaign": "Créer dans la campagne",
|
||||||
|
"noteSplitBookmarks": "Découpage d'après la table des matières du PDF. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
|
||||||
|
"noteSplitHeadings": "Découpage d'après les titres du livre. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
|
||||||
|
"noteAiInterrupted": "L'IA n'a pas pu terminer son travail. La campagne est proposée avec le texte du livre, sans traduction ni fiches de PNJ ; chaque synopsis reprend le début du texte de sa scène.",
|
||||||
|
"noteSkippedAids": "L'IA n'a pas répondu pour {{n}} lot(s) de scènes : leur synopsis reprend le début de leur texte.",
|
||||||
|
"noteUntranslated": "Traduction incomplète : {{n}} texte(s) sont restés dans la langue du livre."
|
||||||
},
|
},
|
||||||
"chapterCreate": {
|
"chapterCreate": {
|
||||||
"titleQuest": "Créer une nouvelle aventure",
|
"titleQuest": "Créer une nouvelle aventure",
|
||||||
@@ -1266,7 +1271,7 @@
|
|||||||
"rulesHint": "Une section = un thème. L'IA injectera automatiquement les sections pertinentes selon ce qu'elle génère (combat → Combat/Monstres, PNJ → Classes, arc → Lore/Factions).",
|
"rulesHint": "Une section = un thème. L'IA injectera automatiquement les sections pertinentes selon ce qu'elle génère (combat → Combat/Monstres, PNJ → Classes, arc → Lore/Factions).",
|
||||||
"importButton": "Importer un PDF de règles",
|
"importButton": "Importer un PDF de règles",
|
||||||
"importInProgress": "Import en cours…",
|
"importInProgress": "Import en cours…",
|
||||||
"importHint": "L'IA propose un découpage en sections — vous révisez avant d'enregistrer.",
|
"importHint": "Le livre est découpé en sections d'après sa table des matières — vous révisez avant d'enregistrer.",
|
||||||
"sectionsFound": "Sections trouvées : {{titles}}",
|
"sectionsFound": "Sections trouvées : {{titles}}",
|
||||||
"sectionTitlePlaceholder": "Nom de la section (ex: Combat)",
|
"sectionTitlePlaceholder": "Nom de la section (ex: Combat)",
|
||||||
"removeSection": "Supprimer cette section",
|
"removeSection": "Supprimer cette section",
|
||||||
@@ -1337,7 +1342,15 @@
|
|||||||
"sectionSize": "{{count}} car.",
|
"sectionSize": "{{count}} car.",
|
||||||
"needsName": "Donnez un nom au système pour l'enregistrer.",
|
"needsName": "Donnez un nom au système pour l'enregistrer.",
|
||||||
"invalidFields": "Cette fiche contient un champ sans nom ou en double : corrigez-le pour enregistrer.",
|
"invalidFields": "Cette fiche contient un champ sans nom ou en double : corrigez-le pour enregistrer.",
|
||||||
"saveFailed": "L'enregistrement a échoué. Vos modifications sont toujours à l'écran : réessayez."
|
"saveFailed": "L'enregistrement a échoué. Vos modifications sont toujours à l'écran : réessayez.",
|
||||||
|
"importPartlyTranslated": "Traduction incomplète : {{count}} section(s) sur {{total}} n'ont pas pu être traduites et gardent leur texte d'origine dans l'onglet {{target}} ({{titles}}).",
|
||||||
|
"importNotTranslated": "La traduction vers l'onglet {{target}} n'a pas abouti : seul l'onglet {{source}} est rempli. L'appli et l'IA utilisent ces règles dans les deux langues.",
|
||||||
|
"sectionEdit": "Modifier",
|
||||||
|
"sectionDone": "Terminer",
|
||||||
|
"sectionEmpty": "Section vide — cliquez pour écrire ses règles.",
|
||||||
|
"sectionEditHint": "Mise en forme markdown : ### sous-titre, **gras**, - liste, | tableau |. Cliquez sur Terminer pour relire le résultat.",
|
||||||
|
"importSplitBookmarks": "Sections reprises de la table des matières du PDF, sans IA : leurs titres sont ceux du livre.",
|
||||||
|
"importSplitHeadings": "Sections repérées d'après les titres du livre, sans IA : leurs titres sont ceux du livre."
|
||||||
},
|
},
|
||||||
"ollamaModelManager": {
|
"ollamaModelManager": {
|
||||||
"installedModels": "Modèles installés",
|
"installedModels": "Modèles installés",
|
||||||
@@ -3611,13 +3624,16 @@
|
|||||||
"foundIntro": "Cochez les sorts à ajouter au catalogue. Les sorts existants ne sont pas modifiés, et rien n'est enregistré tant que vous n'enregistrez pas le système.",
|
"foundIntro": "Cochez les sorts à ajouter au catalogue. Les sorts existants ne sont pas modifiés, et rien n'est enregistré tant que vous n'enregistrez pas le système.",
|
||||||
"already": "déjà dans le catalogue",
|
"already": "déjà dans le catalogue",
|
||||||
"source": "d'après « {{section}} »",
|
"source": "d'après « {{section}} »",
|
||||||
"reviewHint": "Le nom et un passage de chaque sort ont été retrouvés dans vos règles. La description et les valeurs sont relevées par l'IA : relisez-les après l'ajout.",
|
"reviewHint": "La description de chaque sort est reprise de vos règles, mot pour mot. Le niveau, l'école et les valeurs des champs sont relevés par l'IA : relisez-les après l'ajout.",
|
||||||
"droppedOne": "1 sort a été écarté : son nom ou le passage cité ne figurait pas dans vos règles.",
|
"droppedOne": "1 sort a été écarté : son nom ou le passage cité ne figurait pas dans vos règles.",
|
||||||
"droppedMany": "{{count}} sorts ont été écartés : leur nom ou le passage cité ne figurait pas dans vos règles.",
|
"droppedMany": "{{count}} sorts ont été écartés : leur nom ou le passage cité ne figurait pas dans vos règles.",
|
||||||
"add": "Ajouter les sorts cochés ({{count}})",
|
"add": "Ajouter les sorts cochés ({{count}})",
|
||||||
"added": "{{count}} sort(s) ajouté(s) à la fin du catalogue. Relisez-les, puis enregistrez le système.",
|
"added": "{{count}} sort(s) ajouté(s) à la fin du catalogue. Relisez-les, puis enregistrez le système.",
|
||||||
"close": "Fermer la proposition"
|
"close": "Fermer la proposition"
|
||||||
}
|
},
|
||||||
|
"harmonize": "Harmoniser niveaux et écoles ({{count}})",
|
||||||
|
"harmonizeTitle": "Écrit les niveaux et les écoles d'une seule façon : « Niveau 1 » devient « 1 », « Cantrip » ou « Tour » devient « Tour de magie », « Sorts de foudre » devient « Foudre ».",
|
||||||
|
"harmonized": "{{count}} sort(s) réécrit(s) : niveaux et écoles s'écrivent maintenant d'une seule façon. Enregistrez pour conserver."
|
||||||
},
|
},
|
||||||
"sheetSpells": {
|
"sheetSpells": {
|
||||||
"title": "Sorts connus",
|
"title": "Sorts connus",
|
||||||
|
|||||||
@@ -130,7 +130,7 @@
|
|||||||
"pageTitle": "Import a campaign",
|
"pageTitle": "Import a campaign",
|
||||||
"back": "Back to the campaign",
|
"back": "Back to the campaign",
|
||||||
"title": "Import a campaign PDF",
|
"title": "Import a campaign PDF",
|
||||||
"subtitle": "The AI proposes an arc → adventure → scene tree. You review and adjust it before creating anything.",
|
"subtitle": "The book is split into arcs, adventures and scenes from its table of contents, with its text as written. The AI adds a synopsis for each scene and the NPC sheets. You review and adjust before creating anything.",
|
||||||
"importing": "Import in progress…",
|
"importing": "Import in progress…",
|
||||||
"choosePdf": "Choose a campaign PDF",
|
"choosePdf": "Choose a campaign PDF",
|
||||||
"phaseExtracting": "Extracting text…",
|
"phaseExtracting": "Extracting text…",
|
||||||
@@ -173,8 +173,13 @@
|
|||||||
"chapter": "Adventure",
|
"chapter": "Adventure",
|
||||||
"addArc": "Add an arc",
|
"addArc": "Add an arc",
|
||||||
"npcReviewTitle": "Detected NPCs and creatures ({{n}})",
|
"npcReviewTitle": "Detected NPCs and creatures ({{n}})",
|
||||||
"npcReviewHint": "Check the ones to create in the campaign (description taken from the book). Those already present in the campaign are greyed out and will not be recreated.",
|
"npcReviewHint": "Check the ones to create in the campaign (sheet written by the AI from the book). Those already present in the campaign are greyed out and will not be recreated.",
|
||||||
"creating": "Creating…",
|
"creating": "Creating…",
|
||||||
"createInCampaign": "Create in the campaign"
|
"createInCampaign": "Create in the campaign",
|
||||||
|
"noteSplitBookmarks": "Split from the table of contents of the PDF. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
|
||||||
|
"noteSplitHeadings": "Split from the headings of the book. The text of each scene is the text of the book, as written: you will find it in its GM notes.",
|
||||||
|
"noteAiInterrupted": "The AI could not finish its work. The campaign is proposed with the text of the book, without translation or NPC sheets; each synopsis is the beginning of the text of its scene.",
|
||||||
|
"noteSkippedAids": "The AI did not answer for {{n}} batch(es) of scenes: their synopsis is the beginning of their text.",
|
||||||
|
"noteUntranslated": "Incomplete translation: {{n}} text(s) stayed in the language of the book."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,7 +130,7 @@
|
|||||||
"pageTitle": "Importer une campagne",
|
"pageTitle": "Importer une campagne",
|
||||||
"back": "Retour à la campagne",
|
"back": "Retour à la campagne",
|
||||||
"title": "Importer un PDF de campagne",
|
"title": "Importer un PDF de campagne",
|
||||||
"subtitle": "L'IA propose une arborescence arc → aventure → scène. Vous la révisez et l'ajustez avant de créer quoi que ce soit.",
|
"subtitle": "Le livre est découpé en arcs, aventures et scènes d'après sa table des matières, avec son texte tel qu'il est écrit. L'IA y ajoute un synopsis par scène et les fiches des PNJ. Vous révisez et ajustez avant de créer quoi que ce soit.",
|
||||||
"importing": "Import en cours…",
|
"importing": "Import en cours…",
|
||||||
"choosePdf": "Choisir un PDF de campagne",
|
"choosePdf": "Choisir un PDF de campagne",
|
||||||
"phaseExtracting": "Extraction du texte…",
|
"phaseExtracting": "Extraction du texte…",
|
||||||
@@ -173,8 +173,13 @@
|
|||||||
"chapter": "Aventure",
|
"chapter": "Aventure",
|
||||||
"addArc": "Ajouter un arc",
|
"addArc": "Ajouter un arc",
|
||||||
"npcReviewTitle": "PNJ et créatures détectés ({{n}})",
|
"npcReviewTitle": "PNJ et créatures détectés ({{n}})",
|
||||||
"npcReviewHint": "Cochez ceux à créer dans la campagne (description issue du livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
|
"npcReviewHint": "Cochez ceux à créer dans la campagne (fiche rédigée par l'IA d'après le livre). Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.",
|
||||||
"creating": "Création…",
|
"creating": "Création…",
|
||||||
"createInCampaign": "Créer dans la campagne"
|
"createInCampaign": "Créer dans la campagne",
|
||||||
|
"noteSplitBookmarks": "Découpage d'après la table des matières du PDF. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
|
||||||
|
"noteSplitHeadings": "Découpage d'après les titres du livre. Le texte de chaque scène est celui du livre, tel qu'il est écrit : vous le trouvez dans ses Notes MJ.",
|
||||||
|
"noteAiInterrupted": "L'IA n'a pas pu terminer son travail. La campagne est proposée avec le texte du livre, sans traduction ni fiches de PNJ ; chaque synopsis reprend le début du texte de sa scène.",
|
||||||
|
"noteSkippedAids": "L'IA n'a pas répondu pour {{n}} lot(s) de scènes : leur synopsis reprend le début de leur texte.",
|
||||||
|
"noteUntranslated": "Traduction incomplète : {{n}} texte(s) sont restés dans la langue du livre."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,11 +26,15 @@
|
|||||||
"rulesHint": "One section = one theme. The AI will automatically inject the relevant sections based on what it generates (combat → Combat/Monsters, NPC → Classes, arc → Lore/Factions).",
|
"rulesHint": "One section = one theme. The AI will automatically inject the relevant sections based on what it generates (combat → Combat/Monsters, NPC → Classes, arc → Lore/Factions).",
|
||||||
"importButton": "Import a rules PDF",
|
"importButton": "Import a rules PDF",
|
||||||
"importInProgress": "Importing…",
|
"importInProgress": "Importing…",
|
||||||
"importHint": "The AI suggests a breakdown into sections — you review it before saving.",
|
"importHint": "The book is split into sections following its table of contents — you review it before saving.",
|
||||||
"sectionsFound": "Sections found: {{titles}}",
|
"sectionsFound": "Sections found: {{titles}}",
|
||||||
"sectionTitlePlaceholder": "Section name (e.g. Combat)",
|
"sectionTitlePlaceholder": "Section name (e.g. Combat)",
|
||||||
"removeSection": "Remove this section",
|
"removeSection": "Remove this section",
|
||||||
"sectionContentPlaceholder": "Describe the rules of this section...",
|
"sectionContentPlaceholder": "Describe the rules of this section...",
|
||||||
|
"sectionEdit": "Edit",
|
||||||
|
"sectionDone": "Done",
|
||||||
|
"sectionEmpty": "Empty section — click to write its rules.",
|
||||||
|
"sectionEditHint": "Markdown formatting: ### subheading, **bold**, - list, | table |. Click Done to read the result.",
|
||||||
"noSections": "No sections yet — add one with the buttons below.",
|
"noSections": "No sections yet — add one with the buttons below.",
|
||||||
"addSection": "Add a section:",
|
"addSection": "Add a section:",
|
||||||
"addOther": "Other…",
|
"addOther": "Other…",
|
||||||
@@ -62,6 +66,10 @@
|
|||||||
},
|
},
|
||||||
"langHint": "Rules exist in two versions: the app and the AI use the one matching the interface language (or the other if it's empty). Importing a PDF fills both, whatever its language.",
|
"langHint": "Rules exist in two versions: the app and the AI use the one matching the interface language (or the other if it's empty). Importing a PDF fills both, whatever its language.",
|
||||||
"importTranslated": "Book in {{source}}: the {{target}} version was translated automatically (proper names kept); review it in its tab.",
|
"importTranslated": "Book in {{source}}: the {{target}} version was translated automatically (proper names kept); review it in its tab.",
|
||||||
|
"importSplitBookmarks": "Sections taken from the PDF's table of contents, without AI: their titles are those of the book.",
|
||||||
|
"importSplitHeadings": "Sections found from the book's headings, without AI: their titles are those of the book.",
|
||||||
|
"importPartlyTranslated": "Translation incomplete: {{count}} of {{total}} section(s) could not be translated and keep their original text in the {{target}} tab ({{titles}}).",
|
||||||
|
"importNotTranslated": "The translation to the {{target}} tab did not complete: only the {{source}} tab is filled. The app and the AI use these rules in both languages.",
|
||||||
"importSheetHint": "You can then ask for suggested fields for each sheet, in the Sheet structure tab.",
|
"importSheetHint": "You can then ask for suggested fields for each sheet, in the Sheet structure tab.",
|
||||||
"sheetPropose": "Suggest fields from the rules",
|
"sheetPropose": "Suggest fields from the rules",
|
||||||
"sheetProposing": "Reading the rules…",
|
"sheetProposing": "Reading the rules…",
|
||||||
|
|||||||
@@ -26,11 +26,15 @@
|
|||||||
"rulesHint": "Une section = un thème. L'IA injectera automatiquement les sections pertinentes selon ce qu'elle génère (combat → Combat/Monstres, PNJ → Classes, arc → Lore/Factions).",
|
"rulesHint": "Une section = un thème. L'IA injectera automatiquement les sections pertinentes selon ce qu'elle génère (combat → Combat/Monstres, PNJ → Classes, arc → Lore/Factions).",
|
||||||
"importButton": "Importer un PDF de règles",
|
"importButton": "Importer un PDF de règles",
|
||||||
"importInProgress": "Import en cours…",
|
"importInProgress": "Import en cours…",
|
||||||
"importHint": "L'IA propose un découpage en sections — vous révisez avant d'enregistrer.",
|
"importHint": "Le livre est découpé en sections d'après sa table des matières — vous révisez avant d'enregistrer.",
|
||||||
"sectionsFound": "Sections trouvées : {{titles}}",
|
"sectionsFound": "Sections trouvées : {{titles}}",
|
||||||
"sectionTitlePlaceholder": "Nom de la section (ex: Combat)",
|
"sectionTitlePlaceholder": "Nom de la section (ex: Combat)",
|
||||||
"removeSection": "Supprimer cette section",
|
"removeSection": "Supprimer cette section",
|
||||||
"sectionContentPlaceholder": "Décrivez les règles de cette section...",
|
"sectionContentPlaceholder": "Décrivez les règles de cette section...",
|
||||||
|
"sectionEdit": "Modifier",
|
||||||
|
"sectionDone": "Terminer",
|
||||||
|
"sectionEmpty": "Section vide — cliquez pour écrire ses règles.",
|
||||||
|
"sectionEditHint": "Mise en forme markdown : ### sous-titre, **gras**, - liste, | tableau |. Cliquez sur Terminer pour relire le résultat.",
|
||||||
"noSections": "Aucune section pour l'instant — ajoutez-en une avec les boutons ci-dessous.",
|
"noSections": "Aucune section pour l'instant — ajoutez-en une avec les boutons ci-dessous.",
|
||||||
"addSection": "Ajouter une section :",
|
"addSection": "Ajouter une section :",
|
||||||
"addOther": "Autre…",
|
"addOther": "Autre…",
|
||||||
@@ -62,6 +66,10 @@
|
|||||||
},
|
},
|
||||||
"langHint": "Les règles existent en deux versions : l'appli et l'IA utilisent celle de la langue de l'interface (ou l'autre si elle est vide). Importer un PDF remplit les deux, dans n'importe quelle langue.",
|
"langHint": "Les règles existent en deux versions : l'appli et l'IA utilisent celle de la langue de l'interface (ou l'autre si elle est vide). Importer un PDF remplit les deux, dans n'importe quelle langue.",
|
||||||
"importTranslated": "Livre en {{source}} : version {{target}} traduite automatiquement (noms propres conservés), relis-la dans son onglet.",
|
"importTranslated": "Livre en {{source}} : version {{target}} traduite automatiquement (noms propres conservés), relis-la dans son onglet.",
|
||||||
|
"importSplitBookmarks": "Sections reprises de la table des matières du PDF, sans IA : leurs titres sont ceux du livre.",
|
||||||
|
"importSplitHeadings": "Sections repérées d'après les titres du livre, sans IA : leurs titres sont ceux du livre.",
|
||||||
|
"importPartlyTranslated": "Traduction incomplète : {{count}} section(s) sur {{total}} n'ont pas pu être traduites et gardent leur texte d'origine dans l'onglet {{target}} ({{titles}}).",
|
||||||
|
"importNotTranslated": "La traduction vers l'onglet {{target}} n'a pas abouti : seul l'onglet {{source}} est rempli. L'appli et l'IA utilisent ces règles dans les deux langues.",
|
||||||
"importSheetHint": "Vous pouvez ensuite demander une proposition de champs pour chaque fiche, dans l'onglet Structure des fiches.",
|
"importSheetHint": "Vous pouvez ensuite demander une proposition de champs pour chaque fiche, dans l'onglet Structure des fiches.",
|
||||||
"sheetPropose": "Proposer des champs à partir des règles",
|
"sheetPropose": "Proposer des champs à partir des règles",
|
||||||
"sheetProposing": "Lecture des règles…",
|
"sheetProposing": "Lecture des règles…",
|
||||||
|
|||||||
@@ -17,6 +17,9 @@
|
|||||||
"clearFilter": "Show all",
|
"clearFilter": "Show all",
|
||||||
"sort": "Sort by level",
|
"sort": "Sort by level",
|
||||||
"sortTitle": "Sorts the catalogue by level, then by name",
|
"sortTitle": "Sorts the catalogue by level, then by name",
|
||||||
|
"harmonize": "Harmonize levels and schools ({{count}})",
|
||||||
|
"harmonizeTitle": "Writes levels and schools one single way: “Level 1” becomes “1”, “Tour de magie” becomes “Cantrip”, “Fire spells” becomes “Fire”.",
|
||||||
|
"harmonized": "{{count}} spell(s) rewritten: levels and schools are now written one single way. Save to keep.",
|
||||||
"collapseAll": "Collapse all",
|
"collapseAll": "Collapse all",
|
||||||
"expandAll": "Expand all",
|
"expandAll": "Expand all",
|
||||||
"open": "Open the spell",
|
"open": "Open the spell",
|
||||||
@@ -65,7 +68,7 @@
|
|||||||
"foundIntro": "Tick the spells to add to the catalogue. Existing spells are left untouched, and nothing is saved until you save the system.",
|
"foundIntro": "Tick the spells to add to the catalogue. Existing spells are left untouched, and nothing is saved until you save the system.",
|
||||||
"already": "already in the catalogue",
|
"already": "already in the catalogue",
|
||||||
"source": "from “{{section}}”",
|
"source": "from “{{section}}”",
|
||||||
"reviewHint": "The name and a passage of each spell were found in your rules. The description and values are picked out by the AI: review them after adding.",
|
"reviewHint": "The description of each spell is taken from your rules, word for word. The level, school and field values are picked out by the AI: review them after adding.",
|
||||||
"droppedOne": "1 spell was discarded: its name or the quoted passage was not found in your rules.",
|
"droppedOne": "1 spell was discarded: its name or the quoted passage was not found in your rules.",
|
||||||
"droppedMany": "{{count}} spells were discarded: their name or the quoted passage was not found in your rules.",
|
"droppedMany": "{{count}} spells were discarded: their name or the quoted passage was not found in your rules.",
|
||||||
"add": "Add the ticked spells ({{count}})",
|
"add": "Add the ticked spells ({{count}})",
|
||||||
|
|||||||
@@ -17,6 +17,9 @@
|
|||||||
"clearFilter": "Tout afficher",
|
"clearFilter": "Tout afficher",
|
||||||
"sort": "Ranger par niveau",
|
"sort": "Ranger par niveau",
|
||||||
"sortTitle": "Range le catalogue par niveau, puis par nom",
|
"sortTitle": "Range le catalogue par niveau, puis par nom",
|
||||||
|
"harmonize": "Harmoniser niveaux et écoles ({{count}})",
|
||||||
|
"harmonizeTitle": "Écrit les niveaux et les écoles d'une seule façon : « Niveau 1 » devient « 1 », « Cantrip » ou « Tour » devient « Tour de magie », « Sorts de foudre » devient « Foudre ».",
|
||||||
|
"harmonized": "{{count}} sort(s) réécrit(s) : niveaux et écoles s'écrivent maintenant d'une seule façon. Enregistrez pour conserver.",
|
||||||
"collapseAll": "Tout replier",
|
"collapseAll": "Tout replier",
|
||||||
"expandAll": "Tout déplier",
|
"expandAll": "Tout déplier",
|
||||||
"open": "Ouvrir le sort",
|
"open": "Ouvrir le sort",
|
||||||
@@ -65,7 +68,7 @@
|
|||||||
"foundIntro": "Cochez les sorts à ajouter au catalogue. Les sorts existants ne sont pas modifiés, et rien n'est enregistré tant que vous n'enregistrez pas le système.",
|
"foundIntro": "Cochez les sorts à ajouter au catalogue. Les sorts existants ne sont pas modifiés, et rien n'est enregistré tant que vous n'enregistrez pas le système.",
|
||||||
"already": "déjà dans le catalogue",
|
"already": "déjà dans le catalogue",
|
||||||
"source": "d'après « {{section}} »",
|
"source": "d'après « {{section}} »",
|
||||||
"reviewHint": "Le nom et un passage de chaque sort ont été retrouvés dans vos règles. La description et les valeurs sont relevées par l'IA : relisez-les après l'ajout.",
|
"reviewHint": "La description de chaque sort est reprise de vos règles, mot pour mot. Le niveau, l'école et les valeurs des champs sont relevés par l'IA : relisez-les après l'ajout.",
|
||||||
"droppedOne": "1 sort a été écarté : son nom ou le passage cité ne figurait pas dans vos règles.",
|
"droppedOne": "1 sort a été écarté : son nom ou le passage cité ne figurait pas dans vos règles.",
|
||||||
"droppedMany": "{{count}} sorts ont été écartés : leur nom ou le passage cité ne figurait pas dans vos règles.",
|
"droppedMany": "{{count}} sorts ont été écartés : leur nom ou le passage cité ne figurait pas dans vos règles.",
|
||||||
"add": "Ajouter les sorts cochés ({{count}})",
|
"add": "Ajouter les sorts cochés ({{count}})",
|
||||||
|
|||||||
Reference in New Issue
Block a user