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)],
|
||||
) -> ImportRulesUseCase:
|
||||
"""Factory du use case d'import de règles PDF (extraction + structuration)."""
|
||||
# Modèle LOCAL → mode segmentation : le LLM ne renvoie que les frontières des
|
||||
# sections (~200 tokens) et le texte original est découpé localement. Réécrire
|
||||
# tout le contenu à ~100 tokens/s prendrait des dizaines de minutes par livre.
|
||||
# Les providers cloud (rapides, grand contexte) gardent la réécriture nettoyée.
|
||||
# Les règles importées doivent correspondre au texte du PDF : l'IA ne le réécrit jamais,
|
||||
# quel que soit le fournisseur.
|
||||
# - Le livre est d'abord découpé par sa propre structure (signets du PDF, sinon titres
|
||||
# repérés), sans IA : immédiat, fidèle, identique sur toutes les machines (mesuré sur
|
||||
# 159 livres).
|
||||
# - Un PDF sans structure passe par l'IA en mode SEGMENTATION : elle ne renvoie que les
|
||||
# frontières des sections (~200 tokens) et le texte original est découpé tel quel.
|
||||
# La réécriture du contenu par un fournisseur cloud (texte « nettoyé » mais remanié)
|
||||
# n'est plus utilisée.
|
||||
return ImportRulesUseCase(
|
||||
llm=llm, extractor=_PDF_EXTRACTOR,
|
||||
chunk_target_tokens=_effective_import_chunk_tokens(settings),
|
||||
segment_only=settings.llm_provider == "ollama")
|
||||
segment_only=True,
|
||||
structure_first=True)
|
||||
|
||||
|
||||
def get_import_campaign_use_case(
|
||||
@@ -126,11 +132,15 @@ def get_import_campaign_use_case(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> ImportCampaignUseCase:
|
||||
"""Factory du use case d'import de campagne PDF (extraction + arborescence)."""
|
||||
# Comme pour les règles : le livre est d'abord rangé d'après sa propre structure, sans IA,
|
||||
# et le texte des scènes est celui du livre. Un modèle local traite les demandes l'une
|
||||
# après l'autre : lui en envoyer plusieurs ne ferait qu'allonger leur attente.
|
||||
return ImportCampaignUseCase(
|
||||
llm=llm,
|
||||
extractor=_PDF_EXTRACTOR,
|
||||
chunk_target_tokens=_effective_import_chunk_tokens(settings),
|
||||
map_concurrency=settings.llm_map_concurrency,
|
||||
map_concurrency=1 if settings.llm_provider == "ollama" else settings.llm_map_concurrency,
|
||||
structure_first=True,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -128,6 +128,8 @@ async def import_campaign_stream(
|
||||
|
||||
Évènements : `extracting`, `start` {page_count, ocr_page_count, total},
|
||||
`progress` {current, total, arc_count, chapter_count, scene_count},
|
||||
`extracted` {arcs:[...], npcs:[], split_method} — campagne découpée d'après la structure
|
||||
du livre, livrée avant les passes de l'IA (aides, traduction) —,
|
||||
`done` {arcs:[...], page_count, ocr_page_count}, `error` {message}.
|
||||
"""
|
||||
content = await file.read()
|
||||
|
||||
@@ -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_retry import generate_with_retry
|
||||
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
|
||||
|
||||
router = APIRouter()
|
||||
@@ -21,15 +22,16 @@ _SPELLS_SCHEMA: dict = {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
# Pas de description : le modèle désigne le sort, le code reprend son texte
|
||||
# dans les règles (cf. spell_location).
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"level": {"type": "string"},
|
||||
"school": {"type": "string"},
|
||||
"description": {"type": "string"},
|
||||
"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):
|
||||
"""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
|
||||
level: str = ""
|
||||
@@ -76,8 +79,10 @@ async def generate_spell_extraction(
|
||||
) -> SpellExtractionResponseDTO:
|
||||
"""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
|
||||
dans le texte envoyé ; une liste vide signifie que le morceau ne décrit aucun sort.
|
||||
Le modèle désigne les sorts (nom, niveau, école, valeurs, premiers mots du bloc) ; la
|
||||
description de chacun est la tranche du texte qui suit son nom, reprise telle quelle. Le
|
||||
Core vérifie ensuite que le nom et le début de la description se retrouvent dans le texte
|
||||
envoyé ; une liste vide signifie que le morceau ne décrit aucun sort.
|
||||
"""
|
||||
if not body.text.strip():
|
||||
raise HTTPException(status_code=422, detail="Aucun texte de règles fourni.")
|
||||
@@ -93,40 +98,8 @@ async def generate_spell_extraction(
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
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")))
|
||||
|
||||
|
||||
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 _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
|
||||
return SpellExtractionResponseDTO(spells=[
|
||||
ExtractedSpellDTO(name=spell.name, level=spell.level, school=spell.school,
|
||||
description=spell.description, values=spell.values, excerpt=spell.excerpt)
|
||||
for spell in locate_spells(parsed.get("spells"), body.text, body.section_title)
|
||||
])
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Arbre d'un livre de campagne → arcs, aventures (chapitres), scènes et salles — sans IA.
|
||||
|
||||
Le livre dit lui-même comment il est découpé (cf. pdf_structure.book_outline). Ici on range
|
||||
cet arbre dans les entités de l'appli, sans réécrire un mot : le texte d'une scène est la
|
||||
tranche du livre qui lui correspond.
|
||||
|
||||
- Les chapitres du livre deviennent les AVENTURES (chapitres de l'appli). Si le livre est
|
||||
découpé en parties (« Part 1 », « Acte II », « Livre premier »), elles deviennent les ARCS ;
|
||||
sinon tout va dans un seul arc.
|
||||
- Les sections d'un chapitre deviennent ses SCÈNES. Une section trop longue est rendue par
|
||||
ses sous-sections ; le texte d'introduction d'un chapitre fait une scène de présentation.
|
||||
- Une section dont les sous-sections sont des lieux numérotés (« 1. Entrée », « A3. Poste
|
||||
de garde », « Area 4 ») est un lieu explorable : UNE scène, ses lieux en SALLES.
|
||||
- Couverture, crédits, sommaire, index et mentions légales ne sont pas repris.
|
||||
- Les ANNEXES (bestiaire, objets magiques, aides de jeu) ne sont pas des scènes à jouer :
|
||||
elles vont dans un arc à part, en ordre libre, regroupées en quelques scènes de lecture
|
||||
plutôt qu'en une scène par créature ou par objet.
|
||||
|
||||
Ce module ne remplit ni le synopsis d'une scène ni les fiches de PNJ : ce sont des aides
|
||||
écrites par l'IA, ajoutées ensuite (cf. import_campaign). Sans IA, le synopsis est le début du
|
||||
texte de la scène.
|
||||
|
||||
Logique pure : elle ne voit qu'un `BookOutline`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.application.pdf_structure import BookOutline, OutlineNode, outline_text
|
||||
|
||||
# Au-delà, une section qui a des sous-sections est rendue par elles : une scène se lit d'une
|
||||
# traite pendant la partie.
|
||||
MAX_SCENE_CHARS = 15_000
|
||||
# En-deçà, un texte d'introduction ne fait pas une scène à lui seul : il ouvre la suivante.
|
||||
MIN_TEXT_CHARS = 200
|
||||
SEPARATOR = " › "
|
||||
# Longueur du synopsis de repli (le début du texte de la scène).
|
||||
LEAD_CHARS = 240
|
||||
|
||||
# Titres de premier niveau qui ne sont pas de la matière de jeu.
|
||||
_SKIPPED_TITLES = {
|
||||
"cover", "couverture", "front cover", "back cover", "quatrieme de couverture", "title page",
|
||||
"page de titre", "credits", "credit", "contents", "table of contents", "table des matieres",
|
||||
"sommaire", "index", "legal", "legal appendix", "license", "licence", "open game license",
|
||||
"open game licence", "ogl", "copyright", "colophon", "mentions legales",
|
||||
}
|
||||
_SKIPPED_STARTS = ("table of contents", "table des matieres", "open game licen", "credits", "legal ")
|
||||
_FILE_NAME = re.compile(r"\.(pdf|indd|docx?|qxp)$", re.IGNORECASE)
|
||||
_COVER = re.compile(r"\b(cover|couverture)\b")
|
||||
_COVER_MAX_CHARS = 2_000
|
||||
# Un nœud est une enveloppe s'il porte au moins cette part du livre et assez de sous-sections.
|
||||
_WRAPPER_SHARE = 0.6
|
||||
_WRAPPER_CHILDREN = 3
|
||||
|
||||
# Annexes : « Appendix A », « Annexe 2 », et en fin de livre les titres de matière de référence.
|
||||
_APPENDIX = re.compile(r"^(?:appendix|appendices|appendice|annexe|annexes)\b")
|
||||
_REFERENCE_TITLES = (
|
||||
"new monsters", "new creatures", "new magic items", "new spells", "new items", "magic items",
|
||||
"monsters", "creatures", "bestiary", "handouts", "pregenerated characters", "glossary",
|
||||
"nouveaux monstres", "nouvelles creatures", "nouveaux objets", "nouveaux sorts", "objets magiques",
|
||||
"monstres", "bestiaire", "aides de jeu", "personnages pretires", "pretires", "glossaire",
|
||||
)
|
||||
_TITLE_CHARS = 40
|
||||
|
||||
# « Part 1 », « Partie II », « Act Three », « Livre premier », « Tome 2 ».
|
||||
_PART = re.compile(
|
||||
r"^(?:part|partie|act|acte|book|livre|tome|volume)\b[\s.:–—-]*"
|
||||
r"(?:\d+|[ivxlc]+|one|two|three|four|five|six|un|une|deux|trois|quatre|cinq|six|"
|
||||
r"premi[eè]re?|seconde?|deuxi[eè]me|troisi[eè]me|quatri[eè]me)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Lieu numéroté d'un donjon : « 1. Entrée », « A3. Poste de garde », « T-10. Antre »,
|
||||
# « 12 – Crypte », « Area 4: Hall », « Salle 2 ».
|
||||
_AREA = re.compile(
|
||||
r"^(?:(?:area|zone|salle|room|pi[eè]ce|location|lieu)\s+)?(?:[A-Za-z]{1,2}-?)?\d{1,3}[a-z]?\s*[.:)–—-]\s*\S"
|
||||
r"|^(?:area|zone|salle|room|pi[eè]ce)\s+[A-Za-z]?\d",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _fold(text: str) -> str:
|
||||
text = unicodedata.normalize("NFD", text)
|
||||
text = "".join(c for c in text if unicodedata.category(c) != "Mn").lower()
|
||||
return re.sub(r"[^a-z0-9]+", " ", text).strip()
|
||||
|
||||
|
||||
def is_skipped(title: str) -> bool:
|
||||
"""Le titre désigne-t-il une partie du livre qui n'est pas de la matière de jeu ?"""
|
||||
folded = _fold(title)
|
||||
return (not folded or folded in _SKIPPED_TITLES or folded.startswith(_SKIPPED_STARTS)
|
||||
or bool(_FILE_NAME.search(title.strip())))
|
||||
|
||||
|
||||
def lead(text: str, limit: int = LEAD_CHARS) -> str:
|
||||
"""Début du texte : son premier paragraphe ordinaire, coupé à la fin d'une phrase."""
|
||||
for paragraph in text.split("\n\n"):
|
||||
paragraph = " ".join(paragraph.split())
|
||||
if not paragraph or paragraph.startswith(("#", "|", "- ")):
|
||||
continue
|
||||
if len(paragraph) <= limit:
|
||||
return paragraph
|
||||
cut = max(paragraph.rfind(mark, 0, limit) for mark in (". ", "! ", "? ", "… "))
|
||||
if cut >= limit // 3:
|
||||
return paragraph[:cut + 1]
|
||||
cut = paragraph.rfind(" ", 0, limit)
|
||||
return paragraph[:cut if cut > 0 else limit] + "…"
|
||||
return ""
|
||||
|
||||
|
||||
def _content_nodes(outline: BookOutline) -> list[OutlineNode]:
|
||||
"""Nœuds de premier niveau qui portent la matière du livre.
|
||||
|
||||
Les signets d'un PDF sont souvent mal rangés : tout le livre sous un signet au nom de
|
||||
fichier (« Hall of the Rainbow Mage 5e.pdf »), ou sous « Crédits ». Un nœud qui contient
|
||||
l'essentiel du livre est donc une ENVELOPPE : ce sont ses enfants, les chapitres — même si
|
||||
son titre est de ceux qu'on ne reprend pas. Sont ensuite écartés la couverture, les
|
||||
crédits, le sommaire, l'index, les mentions légales, et les nœuds presque vides
|
||||
(légendes de cartes)."""
|
||||
nodes = list(outline.nodes)
|
||||
total = sum(node.chars for node in nodes)
|
||||
while True:
|
||||
# Un gros bestiaire en annexe n'est pas l'enveloppe du livre.
|
||||
wrapper = next((node for node in nodes
|
||||
if len(node.children) >= _WRAPPER_CHILDREN and node.chars >= _WRAPPER_SHARE * total
|
||||
and not _is_reference_title(node.title)), None)
|
||||
if wrapper is None:
|
||||
break
|
||||
position = nodes.index(wrapper)
|
||||
own: list[OutlineNode] = []
|
||||
if len(wrapper.text) >= MIN_TEXT_CHARS and not is_skipped(wrapper.title):
|
||||
own = [OutlineNode(wrapper.title, wrapper.level, wrapper.page, wrapper.text)]
|
||||
nodes[position:position + 1] = [*own, *wrapper.children]
|
||||
return [node for node in nodes if not _left_out(node)]
|
||||
|
||||
|
||||
def _left_out(node: OutlineNode) -> bool:
|
||||
if is_skipped(node.title) or node.chars < MIN_TEXT_CHARS:
|
||||
return True
|
||||
# « … Cover PDF », « Back Cover » : une couverture, tant qu'elle ne porte presque rien.
|
||||
return bool(_COVER.search(_fold(node.title))) and node.chars < _COVER_MAX_CHARS
|
||||
|
||||
|
||||
def _scene(name: str, notes: str, rooms: list[dict] | None = None) -> dict:
|
||||
return {"name": name, "description": "", "player_narration": "", "gm_notes": notes.strip(),
|
||||
"rooms": rooms or []}
|
||||
|
||||
|
||||
def _join(*parts: str) -> str:
|
||||
return "\n\n".join(part for part in parts if part and part.strip())
|
||||
|
||||
|
||||
def _areas(node: OutlineNode) -> list[OutlineNode]:
|
||||
"""Sous-sections qui sont des lieux numérotés — si elles sont au moins deux et la majorité."""
|
||||
areas = [child for child in node.children if _AREA.match(child.title)]
|
||||
return areas if len(areas) >= 2 and len(areas) * 2 >= len(node.children) else []
|
||||
|
||||
|
||||
def _explorable(node: OutlineNode, name: str, intro: str, path: list[str], out: list[dict]) -> None:
|
||||
"""Un lieu explorable : une scène, ses lieux numérotés en salles.
|
||||
|
||||
Ses autres sous-sections restent dans le texte de la scène — sauf celles qui sont
|
||||
elles-mêmes un lieu explorable, ou trop longues : elles font leurs propres scènes, à la
|
||||
suite (un donjon rangé sous la région qui y mène garde ainsi ses salles)."""
|
||||
areas = _areas(node)
|
||||
inside: list[OutlineNode] = []
|
||||
apart: list[OutlineNode] = []
|
||||
for child in node.children:
|
||||
if child in areas:
|
||||
continue
|
||||
on_its_own = bool(_areas(child)) or (bool(child.children) and child.chars > MAX_SCENE_CHARS)
|
||||
(apart if on_its_own else inside).append(child)
|
||||
notes = _join(intro, node.text, *(_join(f"### {child.title}", outline_text(child, 1)) for child in inside))
|
||||
rooms = [{"name": area.title, "description": outline_text(area), "enemies": "", "loot": ""} for area in areas]
|
||||
out.append(_scene(name, notes, rooms))
|
||||
for child in apart:
|
||||
_scenes(child, path, out)
|
||||
|
||||
|
||||
def _scenes(node: OutlineNode, path: list[str], out: list[dict], intro: str = "") -> None:
|
||||
"""Scènes que donne `node`, section d'un chapitre. `path` : ses ancêtres sous le chapitre."""
|
||||
name = SEPARATOR.join([*path, node.title][-2:])
|
||||
if _areas(node):
|
||||
_explorable(node, name, intro, [*path, node.title], out)
|
||||
return
|
||||
if node.children and node.chars > MAX_SCENE_CHARS:
|
||||
own = _join(intro, node.text)
|
||||
carry = ""
|
||||
if len(own) >= MIN_TEXT_CHARS:
|
||||
out.append(_scene(name, own))
|
||||
else:
|
||||
carry = own
|
||||
for position, child in enumerate(node.children):
|
||||
_scenes(child, [*path, node.title], out, carry if position == 0 else "")
|
||||
return
|
||||
out.append(_scene(name, _join(intro, outline_text(node))))
|
||||
|
||||
|
||||
def _reference_nodes(nodes: list[OutlineNode]) -> list[OutlineNode]:
|
||||
"""Nœuds de premier niveau qui sont des annexes : ceux qui s'appellent ainsi, et en fin de
|
||||
livre ceux dont le titre annonce de la matière de référence (« New Creatures »,
|
||||
« Bestiaire »). Aucun si tout le livre en serait : ce n'est alors pas une campagne."""
|
||||
found = [node for node in nodes if _APPENDIX.match(_fold(node.title))]
|
||||
for node in reversed(nodes):
|
||||
folded = _fold(node.title)
|
||||
if node in found:
|
||||
continue
|
||||
if folded in _REFERENCE_TITLES or folded.startswith(_REFERENCE_TITLES):
|
||||
found.append(node)
|
||||
else:
|
||||
break
|
||||
return [] if len(found) == len(nodes) else [node for node in nodes if node in found]
|
||||
|
||||
|
||||
def _is_reference_title(title: str) -> bool:
|
||||
folded = _fold(title)
|
||||
return bool(_APPENDIX.match(folded)) or folded in _REFERENCE_TITLES or folded.startswith(_REFERENCE_TITLES)
|
||||
|
||||
|
||||
def _entries(node: OutlineNode) -> list[OutlineNode]:
|
||||
"""Sous-sections d'une annexe, une trop longue étant rendue par les siennes."""
|
||||
out: list[OutlineNode] = []
|
||||
for child in node.children:
|
||||
if child.children and child.chars > MAX_SCENE_CHARS:
|
||||
if child.text.strip():
|
||||
out.append(OutlineNode(child.title, child.level, child.page, child.text))
|
||||
out.extend(_entries(child))
|
||||
else:
|
||||
out.append(child)
|
||||
return out
|
||||
|
||||
|
||||
def _reference_scene(group: list[OutlineNode], intro: str) -> dict:
|
||||
"""Une scène de lecture pour des entrées d'annexe qui se suivent."""
|
||||
if len(group) == 1:
|
||||
entry = group[0]
|
||||
scene = _scene(entry.title, _join(intro, outline_text(entry)))
|
||||
titles = [child.title for child in entry.children]
|
||||
else:
|
||||
first, last = group[0].title[:_TITLE_CHARS], group[-1].title[:_TITLE_CHARS]
|
||||
scene = _scene(f"{first} – {last}", _join(intro, *(
|
||||
_join(f"### {entry.title}", outline_text(entry, 1)) for entry in group)))
|
||||
titles = [entry.title for entry in group]
|
||||
# Synopsis : ce que la scène contient. L'IA n'en rédige pas pour une annexe.
|
||||
scene["description"] = ", ".join(titles)[:LEAD_CHARS]
|
||||
return scene
|
||||
|
||||
|
||||
def _reference_chapter(node: OutlineNode, overview_title: str) -> dict:
|
||||
"""Une annexe : ses entrées regroupées, dans l'ordre du livre, en scènes de lecture."""
|
||||
entries = _entries(node)
|
||||
scenes: list[dict] = []
|
||||
if not entries:
|
||||
scenes.append(_scene(node.title, node.text))
|
||||
else:
|
||||
intro = ""
|
||||
if len(node.text) >= MIN_TEXT_CHARS:
|
||||
scenes.append(_scene(overview_title, node.text))
|
||||
else:
|
||||
intro = node.text
|
||||
group: list[OutlineNode] = []
|
||||
size = 0
|
||||
for entry in entries:
|
||||
if group and size + entry.chars > MAX_SCENE_CHARS:
|
||||
scenes.append(_reference_scene(group, intro))
|
||||
group, size, intro = [], 0, ""
|
||||
group.append(entry)
|
||||
size += entry.chars
|
||||
scenes.append(_reference_scene(group, intro))
|
||||
return {"name": node.title, "description": "", "scenes": _unique(scenes)}
|
||||
|
||||
|
||||
def _unique(scenes: list[dict]) -> list[dict]:
|
||||
"""Scènes non vides, noms uniques dans le chapitre."""
|
||||
seen: dict[str, int] = {}
|
||||
out: list[dict] = []
|
||||
for scene in scenes:
|
||||
if not scene["gm_notes"] and not scene["rooms"]:
|
||||
continue
|
||||
count = seen.get(scene["name"], 0) + 1
|
||||
seen[scene["name"]] = count
|
||||
if count > 1:
|
||||
scene["name"] = f"{scene['name']} ({count})"
|
||||
scene["description"] = scene["description"] or lead(scene["gm_notes"])
|
||||
out.append(scene)
|
||||
return out
|
||||
|
||||
|
||||
def _chapter(node: OutlineNode, overview_title: str) -> dict:
|
||||
scenes: list[dict] = []
|
||||
if _areas(node):
|
||||
_explorable(node, node.title, "", [], scenes)
|
||||
elif not node.children:
|
||||
scenes.append(_scene(node.title, node.text))
|
||||
else:
|
||||
carry = ""
|
||||
if len(node.text) >= MIN_TEXT_CHARS:
|
||||
scenes.append(_scene(overview_title, node.text))
|
||||
else:
|
||||
carry = node.text
|
||||
for position, child in enumerate(node.children):
|
||||
_scenes(child, [], scenes, carry if position == 0 else "")
|
||||
return {"name": node.title, "description": "", "scenes": _unique(scenes)}
|
||||
|
||||
|
||||
def campaign_from_outline(
|
||||
outline: BookOutline,
|
||||
*,
|
||||
default_arc: str = "Aventure principale",
|
||||
overview_title: str = "Présentation",
|
||||
appendix_arc: str = "Annexes",
|
||||
) -> list[dict]:
|
||||
"""Arcs → chapitres → scènes → salles, au format du flux d'import (dicts).
|
||||
|
||||
Chaque scène porte son texte dans `gm_notes` (le livre, mot pour mot) et, en synopsis de
|
||||
repli, le début de ce texte dans `description`. Les annexes forment un dernier arc, marqué
|
||||
`reference` : de la lecture, pas des scènes à jouer. Liste vide si le livre n'a pas de matière."""
|
||||
nodes = _content_nodes(outline)
|
||||
reference = _reference_nodes(nodes)
|
||||
nodes = [node for node in nodes if node not in reference]
|
||||
parts = [node for node in nodes if _PART.match(node.title.strip())]
|
||||
arcs: list[dict] = []
|
||||
if len(parts) >= 2:
|
||||
# Livre découpé en parties : chacune est un arc, ses chapitres sont les aventures.
|
||||
for node in nodes:
|
||||
if node in parts and node.children:
|
||||
chapters = [_chapter(child, overview_title) for child in node.children]
|
||||
if len(node.text) >= MIN_TEXT_CHARS:
|
||||
chapters.insert(0, {"name": overview_title, "description": "",
|
||||
"scenes": _unique([_scene(overview_title, node.text)])})
|
||||
else:
|
||||
chapters = [_chapter(node, overview_title)]
|
||||
arcs.append({"name": node.title, "description": "", "type": "LINEAR", "chapters": chapters})
|
||||
else:
|
||||
arcs.append({"name": default_arc, "description": "", "type": "LINEAR",
|
||||
"chapters": [_chapter(node, overview_title) for node in nodes]})
|
||||
if reference:
|
||||
# Ordre libre : on consulte une annexe, on ne la joue pas à la suite.
|
||||
arcs.append({"name": appendix_arc, "description": "", "type": "HUB", "reference": True,
|
||||
"chapters": [_reference_chapter(node, overview_title) for node in reference]})
|
||||
|
||||
for arc in arcs:
|
||||
arc["chapters"] = [chapter for chapter in arc["chapters"] if chapter["scenes"]]
|
||||
return [arc for arc in arcs if arc["chapters"]]
|
||||
|
||||
|
||||
def counts(arcs: list[dict]) -> tuple[int, int, int, int]:
|
||||
"""(arcs, chapitres, scènes, salles)."""
|
||||
chapters = [chapter for arc in arcs for chapter in arc["chapters"]]
|
||||
scenes = [scene for chapter in chapters for scene in chapter["scenes"]]
|
||||
return len(arcs), len(chapters), len(scenes), sum(len(scene["rooms"]) for scene in scenes)
|
||||
|
||||
|
||||
def all_scenes(arcs: list[dict]) -> list[dict]:
|
||||
"""Toutes les scènes, dans l'ordre du livre."""
|
||||
return [scene for arc in arcs for chapter in arc["chapters"] for scene in chapter["scenes"]]
|
||||
|
||||
|
||||
def played_scenes(arcs: list[dict]) -> list[dict]:
|
||||
"""Scènes de l'aventure elle-même, sans celles des annexes."""
|
||||
return all_scenes([arc for arc in arcs if not arc.get("reference")])
|
||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.application.campaign_structure import all_scenes, campaign_from_outline, counts, played_scenes
|
||||
from app.application.chunking import chunk_text, split_in_half
|
||||
from app.application.import_status import (
|
||||
notify_status,
|
||||
@@ -21,8 +24,17 @@ from app.application.import_status import (
|
||||
)
|
||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.pdf_structure import BOOKMARKS, NONE, book_outline
|
||||
from app.application.prompts import import_campaign as prompts
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.application.rules_translation import (
|
||||
DEFAULT_CONCURRENCY,
|
||||
LANGUAGES,
|
||||
RulesTranslator,
|
||||
detect_language,
|
||||
translate_sections,
|
||||
)
|
||||
from app.application.streaming import HEARTBEAT_INTERVAL_SECONDS, with_heartbeat
|
||||
from app.core.language import language_name
|
||||
|
||||
# Repli anti-troncature : si la sortie d'un morceau est coupée, on le retraite en
|
||||
# 2 moitiés. Borné en profondeur (3 niveaux => jusqu'à 8 sous-blocs).
|
||||
@@ -52,6 +64,35 @@ _TEMPERATURE = 0.1
|
||||
# d'un coup et le structure de façon cohérente (1 scène par lieu) au lieu de le
|
||||
# fragmenter en dizaines de scènes. Adapté aux providers à grand contexte (1min.ai).
|
||||
_CHUNK_TARGET_TOKENS = 10000
|
||||
# Import par la structure du livre : conversion approchée tokens → caractères pour la taille
|
||||
# d'un lot d'aides, nombre de scènes par lot, longueur d'un synopsis, durée accordée aux aides.
|
||||
_CHARS_PER_TOKEN = 3
|
||||
_MAX_SCENES_PER_BATCH = 12
|
||||
_MAX_SYNOPSIS_CHARS = 400
|
||||
_ROOM_LIST_CHARS = 600
|
||||
AIDS_BUDGET_SECONDS = 30 * 60
|
||||
# Durée accordée à la traduction d'une campagne. Plus longue que pour des règles : un livre de
|
||||
# 200 pages compte des centaines de textes (50 minutes mesurées avec un petit modèle local sur
|
||||
# une carte rapide), et une campagne à moitié traduite sert peu. Reste sous la durée maximale
|
||||
# d'un import côté Core (4 heures).
|
||||
TRANSLATION_BUDGET_SECONDS = 3 * 60 * 60
|
||||
# Échantillon de texte utilisé pour reconnaître la langue du livre.
|
||||
_DETECT_CHARS = 20_000
|
||||
# Réponse attendue pour les aides : un synopsis par scène (repérée par son numéro), des PNJ.
|
||||
_AIDS_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"scenes": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"properties": {"n": {"type": "integer"}, "synopsis": {"type": "string"}},
|
||||
"required": ["n", "synopsis"]}},
|
||||
"npcs": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"properties": {"name": {"type": "string"}, "description": {"type": "string"}},
|
||||
"required": ["name"]}},
|
||||
},
|
||||
"required": ["scenes"],
|
||||
}
|
||||
|
||||
# Schéma de l'arbre attendu, passé aux providers à sorties structurées (Ollama
|
||||
# contraint la grammaire : un modèle local ne PEUT plus produire de clés
|
||||
@@ -352,10 +393,21 @@ class ImportCampaignUseCase:
|
||||
extractor: PdfTextExtractor,
|
||||
chunk_target_tokens: int = _CHUNK_TARGET_TOKENS,
|
||||
map_concurrency: int = 1,
|
||||
structure_first: bool = False,
|
||||
) -> None:
|
||||
self._llm = llm
|
||||
self._extractor = extractor
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
# `structure_first` : ranger d'abord le livre d'après SA structure (signets du PDF,
|
||||
# sinon titres repérés), sans IA. Le texte des scènes est alors celui du livre, mot
|
||||
# pour mot ; l'IA n'écrit que des aides (synopsis, fiches de PNJ) et la traduction.
|
||||
self._structure_first = structure_first
|
||||
# Taille (caractères) d'un lot de scènes confié à l'IA pour ses aides.
|
||||
self._aid_batch_chars = max(4_000, chunk_target_tokens * _CHARS_PER_TOKEN)
|
||||
self._translation_concurrency = DEFAULT_CONCURRENCY if map_concurrency > 1 else 1
|
||||
self._heartbeat_seconds = HEARTBEAT_INTERVAL_SECONDS
|
||||
self._aids_budget_seconds = AIDS_BUDGET_SECONDS
|
||||
self._translation_budget_seconds = TRANSLATION_BUDGET_SECONDS
|
||||
# Appels MAP par VAGUES de cette taille : l'ordre narratif est préservé
|
||||
# (fusion vague par vague, dans l'ordre du livre) mais le mur d'attente
|
||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||
@@ -364,6 +416,19 @@ class ImportCampaignUseCase:
|
||||
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
structured = self._structure(doc, language)
|
||||
if structured is not None:
|
||||
arcs, method = structured
|
||||
done: dict = {}
|
||||
async for event in self._structured_stream(doc, arcs, method, language):
|
||||
if event["type"] == "done":
|
||||
done = event
|
||||
return CampaignImportResult(
|
||||
arcs=_arcs_from_dicts(done.get("arcs", [])),
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
npcs=[NpcImportProposal(n["name"], n["description"]) for n in done.get("npcs", [])],
|
||||
)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
toc_block = _format_toc(doc.toc)
|
||||
merger = _TreeMerger()
|
||||
@@ -397,6 +462,12 @@ class ImportCampaignUseCase:
|
||||
yield {"type": "extracting"}
|
||||
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
structured = self._structure(doc, language)
|
||||
if structured is not None:
|
||||
arcs, method = structured
|
||||
async for event in self._structured_stream(doc, arcs, method, language):
|
||||
yield event
|
||||
return
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
toc_block = _format_toc(doc.toc)
|
||||
total = len(chunks)
|
||||
@@ -512,6 +583,147 @@ class ImportCampaignUseCase:
|
||||
finally:
|
||||
reset_status_queue(status_token)
|
||||
|
||||
# --- Import par la structure du livre ------------------------------------
|
||||
|
||||
def _structure(self, doc, language: str) -> tuple[list[dict], str] | None:
|
||||
"""Arbre de la campagne tiré de la structure du PDF, ou None s'il faut passer par
|
||||
l'IA (réglage coupé, PDF sans signets ni titres repérables, livre sans matière)."""
|
||||
if not self._structure_first:
|
||||
return None
|
||||
outline = book_outline(doc)
|
||||
if outline.method == NONE:
|
||||
logger.info("Import campagne : pas de structure exploitable dans ce PDF — découpage par l'IA.")
|
||||
return None
|
||||
arcs = campaign_from_outline(
|
||||
outline, default_arc=prompts.default_arc_name(language),
|
||||
overview_title=prompts.overview_title(language),
|
||||
appendix_arc=prompts.appendix_arc_name(language))
|
||||
if not arcs:
|
||||
return None
|
||||
return arcs, outline.method
|
||||
|
||||
async def _structured_stream(self, doc, arcs: list[dict], method: str, language: str):
|
||||
"""Campagne découpée par la structure du livre : le texte est déjà là. Deux passes de
|
||||
l'IA, toutes deux facultatives — un échec ne retire rien au texte : les AIDES (synopsis
|
||||
de chaque scène, fiches des PNJ nommés), puis la TRADUCTION si le livre n'est pas dans
|
||||
la langue de l'interface."""
|
||||
scenes = all_scenes(arcs)
|
||||
arc_count, chapter_count, scene_count, room_count = counts(arcs)
|
||||
# Les annexes (bestiaire, objets) ne reçoivent pas d'aides : leur synopsis est la liste
|
||||
# de ce qu'elles contiennent, et un profil de créature n'est pas un PNJ.
|
||||
batches = _aid_batches(played_scenes(arcs), self._aid_batch_chars)
|
||||
total = max(1, len(batches))
|
||||
logger.info("Import campagne : %s page(s), découpage par la structure du PDF (%s) : %s arc(s), "
|
||||
"%s aventure(s), %s scène(s), %s salle(s), sans IA ; %s lot(s) d'aides.",
|
||||
doc.page_count, method, arc_count, chapter_count, scene_count, room_count, len(batches))
|
||||
yield {"type": "start", "page_count": doc.page_count, "ocr_page_count": doc.ocr_page_count, "total": total}
|
||||
origin = "la table des matières du PDF" if method == BOOKMARKS else "les titres du livre"
|
||||
|
||||
def progress(current: int, npc_count: int, skipped: int) -> dict:
|
||||
return {"type": "progress", "current": current, "total": total, "arc_count": arc_count,
|
||||
"chapter_count": chapter_count, "scene_count": scene_count,
|
||||
"npc_count": npc_count, "skipped": skipped}
|
||||
|
||||
# L'avancement d'abord : à l'écran, il efface le message d'état en cours.
|
||||
yield progress(0, 0, 0)
|
||||
yield {"type": "status",
|
||||
"message": f"Découpage d'après {origin} : {chapter_count} aventure(s), "
|
||||
f"{scene_count} scène(s), sans IA."}
|
||||
|
||||
# L'arbre est livré AVANT les passes de l'IA : si le flux s'interrompt ensuite, le Core
|
||||
# a déjà la campagne, avec le texte du livre.
|
||||
yield {"type": "extracted", "arcs": arcs, "npcs": [], "page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count, "split_method": method}
|
||||
|
||||
# --- Aides : synopsis des scènes et fiches de PNJ --------------------------------
|
||||
npcs: dict[str, dict] = {}
|
||||
skipped = 0
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + self._aids_budget_seconds
|
||||
for index, batch in enumerate(batches):
|
||||
if loop.time() >= deadline:
|
||||
yield {"type": "status",
|
||||
"message": "Temps imparti aux aides de l'IA dépassé : les scènes restantes "
|
||||
"gardent le début de leur texte en guise de synopsis."}
|
||||
break
|
||||
yield {"type": "status",
|
||||
"message": f"Texte du livre repris tel quel ({scene_count} scène(s)). L'IA rédige les "
|
||||
f"synopsis et relève les PNJ : lot {index + 1}/{total}…"}
|
||||
try:
|
||||
parsed: dict | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._aids(batch, language), interval=self._heartbeat_seconds):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": index + 1, "total": total}
|
||||
elif kind == "result":
|
||||
parsed = payload
|
||||
_apply_aids(batch, parsed, npcs)
|
||||
except LLMProviderError as exc:
|
||||
skipped += 1
|
||||
logger.warning("Aides de l'IA : lot %s/%s ignoré : %s", index + 1, total, exc)
|
||||
yield {"type": "chunk_failed", "current": index + 1, "total": total, "message": str(exc)[:300]}
|
||||
yield progress(index + 1, len(npcs), skipped)
|
||||
|
||||
# Créatures génériques prises pour des PNJ : jugées sur tout le texte du livre, tant
|
||||
# qu'il est dans sa langue d'origine.
|
||||
played = played_scenes(arcs)
|
||||
book_text = "\n".join(_aid_text(scene, 10 ** 9) for scene in played)
|
||||
npcs = {key: npc for key, npc in npcs.items() if not _is_generic(npc["name"], book_text)}
|
||||
# Personnes réelles (auteurs, éditeurs) : citées seulement là où le livre parle de lui-même.
|
||||
npcs = _met_in_the_adventure(npcs, played)
|
||||
|
||||
# --- Traduction fidèle, si le livre n'est pas dans la langue de l'interface -------
|
||||
untranslated = 0
|
||||
sample = "\n".join(scene["gm_notes"] for scene in scenes)[:_DETECT_CHARS]
|
||||
source = detect_language(sample, default=language)
|
||||
if source != language and language in LANGUAGES:
|
||||
units, labels = _translation_units(scenes)
|
||||
try:
|
||||
async for kind, payload in translate_sections(
|
||||
RulesTranslator(self._llm), units, source, language,
|
||||
concurrency=self._translation_concurrency,
|
||||
budget_seconds=self._translation_budget_seconds,
|
||||
heartbeat_seconds=self._heartbeat_seconds,
|
||||
with_titles=False, labels=labels):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": total, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload}
|
||||
else:
|
||||
untranslated = len(payload.untranslated)
|
||||
_apply_translation(scenes, payload.sections)
|
||||
if untranslated:
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(language)}) incomplète : "
|
||||
f"{untranslated} texte(s) sur {len(units)} gardent la langue du livre."}
|
||||
except LLMProviderError as exc:
|
||||
untranslated = len(units)
|
||||
logger.warning("Traduction de la campagne (%s) impossible : %s", language, exc)
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(language)}) impossible : {str(exc)[:200]}"}
|
||||
|
||||
yield {
|
||||
"type": "done",
|
||||
"arcs": arcs,
|
||||
"npcs": list(npcs.values()),
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
"split_method": method,
|
||||
"source_language": source,
|
||||
"untranslated": untranslated,
|
||||
}
|
||||
|
||||
async def _aids(self, batch: list[tuple[int, dict]], language: str) -> dict | None:
|
||||
"""Un appel au modèle pour les aides d'un lot de scènes → JSON {scenes, npcs}."""
|
||||
listing = "\n\n".join(
|
||||
f"=== SCÈNE {number} : {scene['name']} ===\n{_aid_text(scene, self._aid_batch_chars // 2)}"
|
||||
for number, (_, scene) in enumerate(batch, start=1))
|
||||
prompt = prompts.AIDS_PROMPT.format(language_name=language_name(language), scenes=listing)
|
||||
raw = await generate_with_retry(self._llm, prompt, output_format=_AIDS_SCHEMA, temperature=_TEMPERATURE)
|
||||
parsed, _ = load_json_object(raw)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
|
||||
# --- Consolidation finale (fusion des quasi-doublons) ---------------------
|
||||
|
||||
async def _consolidate(self, merger: _TreeMerger) -> None:
|
||||
@@ -641,6 +853,281 @@ class ImportCampaignUseCase:
|
||||
return empty, recovered
|
||||
|
||||
|
||||
# --- Import par la structure du livre : lots d'aides, traduction ------------------------------
|
||||
|
||||
def _aid_text(scene: dict, limit: int) -> str:
|
||||
"""Texte d'une scène confié au modèle pour ses aides : ses notes et ses salles, borné.
|
||||
|
||||
Un lieu explorable s'ouvre sur la liste de ses pièces : son texte est surtout dans leurs
|
||||
descriptions, dont le modèle ne verra que le début."""
|
||||
names = "; ".join(room["name"] for room in scene["rooms"])[:_ROOM_LIST_CHARS]
|
||||
listing = f"[Lieu explorable, {len(scene['rooms'])} pièce(s) : {names}]" if names else ""
|
||||
rooms = "\n\n".join(f"{room['name']}\n{room['description']}" for room in scene["rooms"])
|
||||
return "\n\n".join(part for part in (listing, scene["gm_notes"], rooms) if part)[:limit]
|
||||
|
||||
|
||||
def _aid_batches(scenes: list[dict], budget_chars: int) -> list[list[tuple[int, dict]]]:
|
||||
"""Scènes regroupées en lots, dans l'ordre du livre, chacun sous `budget_chars`. Une
|
||||
scène plus longue que la moitié du budget y est bornée (cf. _aid_text) : seules les aides
|
||||
en dépendent, son texte reste entier."""
|
||||
batches: list[list[tuple[int, dict]]] = []
|
||||
current: list[tuple[int, dict]] = []
|
||||
size = 0
|
||||
for index, scene in enumerate(scenes):
|
||||
length = min(len(_aid_text(scene, budget_chars // 2)), budget_chars // 2) + len(scene["name"]) + 30
|
||||
if current and (size + length > budget_chars or len(current) >= _MAX_SCENES_PER_BATCH):
|
||||
batches.append(current)
|
||||
current, size = [], 0
|
||||
current.append((index, scene))
|
||||
size += length
|
||||
if current:
|
||||
batches.append(current)
|
||||
return batches
|
||||
|
||||
|
||||
def _fold(text: str) -> str:
|
||||
return " ".join("".join(c.lower() if c.isalnum() else " " for c in text).split())
|
||||
|
||||
|
||||
def _apply_aids(batch: list[tuple[int, dict]], parsed: dict | None, npcs: dict[str, dict]) -> None:
|
||||
"""Range les aides du modèle : le synopsis de chaque scène, et les PNJ dont le NOM figure
|
||||
bien dans le texte du lot (un PNJ inventé est écarté)."""
|
||||
if not parsed:
|
||||
return
|
||||
for item in parsed.get("scenes") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
number = int(item.get("n"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
synopsis = " ".join(str(item.get("synopsis") or "").split())
|
||||
if 1 <= number <= len(batch) and synopsis:
|
||||
batch[number - 1][1]["description"] = synopsis[:_MAX_SYNOPSIS_CHARS]
|
||||
haystack = _fold("\n".join(scene["name"] + "\n" + _aid_text(scene, 10 ** 9) for _, scene in batch))
|
||||
for item in parsed.get("npcs") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
# Appel de note collé au nom par la mise en page (« King RatII », « RidwikI »).
|
||||
name = _FOOTNOTE_MARK.sub("", " ".join(str(item.get("name") or "").split()))
|
||||
key = _fold(name)
|
||||
# Un nom sans majuscule (« ogre », « gobelins ») est une créature générique ; un nom
|
||||
# tout en capitales (« ZOMBIE SARGASSIEN ») est le titre d'un profil de créature.
|
||||
if len(key) < 3 or key not in haystack or not any(c.isupper() for c in name) or name.isupper():
|
||||
continue
|
||||
description = " ".join(str(item.get("description") or "").split())
|
||||
if _is_group(name, description):
|
||||
continue
|
||||
known = _same_npc(name, npcs)
|
||||
if known is None:
|
||||
npcs[key] = {"name": name, "description": description}
|
||||
continue
|
||||
# Déjà relevé, parfois sous un nom plus court (« Arumvel », « Arumvel the Wicked ») :
|
||||
# on garde le nom le plus complet et la fiche la plus fournie.
|
||||
if len(name) > len(known["name"]):
|
||||
known["name"] = name
|
||||
if len(description) > len(known["description"]):
|
||||
known["description"] = description
|
||||
|
||||
|
||||
# Titres placés devant un nom : « dame Cynaëlle » et « Cynaëlle de Tyrmallan » sont la même.
|
||||
_HONORIFICS = frozenset("""
|
||||
dame sire seigneur maitre maitresse capitaine lieutenant commandant commandante sergent general
|
||||
pere mere frere soeur sœur roi reine prince princesse baron baronne comte comtesse duc duchesse
|
||||
docteur professeur messire monsieur madame mademoiselle
|
||||
lord lady sir captain master mistress father mother brother sister king queen duke duchess
|
||||
count countess doctor dr professor mr mrs miss
|
||||
""".split())
|
||||
|
||||
|
||||
_ARTICLES = frozenset({"le", "la", "l", "les", "the"})
|
||||
|
||||
|
||||
def _bare_name(key: str) -> str:
|
||||
"""Nom sans l'article ni les titres qui le précèdent (au moins un mot est gardé)."""
|
||||
words = key.split()
|
||||
while len(words) > 1 and (words[0] in _ARTICLES or _strip_accents(words[0]) in _HONORIFICS):
|
||||
words.pop(0)
|
||||
return " ".join(words)
|
||||
|
||||
|
||||
def _strip_accents(text: str) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFD", text) if unicodedata.category(c) != "Mn")
|
||||
|
||||
|
||||
def _aliases(name: str) -> list[str]:
|
||||
"""Noms sous lesquels un PNJ est connu : « Arvell/Alezzandro » en porte deux."""
|
||||
return [alias for alias in (_bare_name(_fold(part)) for part in name.split("/")) if alias]
|
||||
|
||||
|
||||
def _same_npc(name: str, npcs: dict[str, dict]) -> dict | None:
|
||||
"""PNJ déjà relevé sous ce nom — à un titre près, à un tiret près (« Trois-Doigts »,
|
||||
« Troisdoigts ») — ou sous un nom dont celui-ci est le début (ou l'inverse)."""
|
||||
names = _aliases(name)
|
||||
for entry in npcs.values():
|
||||
for other in _aliases(entry["name"]):
|
||||
for mine in names:
|
||||
if (mine.replace(" ", "") == other.replace(" ", "")
|
||||
or mine.startswith(other + " ") or other.startswith(mine + " ")):
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
_FOOTNOTE_MARK = re.compile(r"(?<=[a-zà-ÿ])I{1,3}$")
|
||||
_FOOTNOTE_IN_TEXT = re.compile(r"(?<=[a-zà-ÿ])I{1,3}(?![^\W\d_])")
|
||||
# Mots qui désignent un groupe, en tête ou en fin de nom (« Rump family », « Légion noire »).
|
||||
_GROUP_NAME_WORDS = frozenset("""
|
||||
famille family clan guilde guild legion ordre order tribu tribe culte cult secte sect faction
|
||||
gardes guards soldats soldiers villageois villagers cultistes cultists pirates bandits milice militia
|
||||
""".split())
|
||||
# Début d'une fiche qui décrit un groupe : « Ce sont… », « C'est un clan… », « La famille… ».
|
||||
_GROUP_DESCRIPTION = re.compile(
|
||||
r"^(?:ce sont|ils sont|elles sont|they are|these are|those are)\b"
|
||||
r"|^(?:(?:c est|il s agit d|it is|this is)\s+)?(?:(?:un|une|le|la|l|ce|cet|cette|ces|d un|d une|a|an|the|this)\s+)?"
|
||||
r"(?:clan|guilde|guild|secte|sect|culte|cult|groupe|group|faction|organisation|organization|famille|family"
|
||||
r"|peuple|race|tribu|tribe|ordre|order|espece|species|bande|band|gang|compagnie|company)\b")
|
||||
|
||||
|
||||
_COUNT_WORDS = frozenset("""
|
||||
two three four five six seven eight nine ten eleven twelve several many some
|
||||
deux trois quatre cinq six sept huit neuf dix onze douze plusieurs quelques
|
||||
""".split())
|
||||
|
||||
|
||||
_LETTER = r"[^\W\d_]"
|
||||
_ELISION = re.compile(r"^l['’]", re.IGNORECASE)
|
||||
_INDEFINITE = "|".join(sorted({"un", "une", "des", "a", "an", *_COUNT_WORDS}, key=len, reverse=True))
|
||||
|
||||
|
||||
def _without_article(name: str) -> list[str]:
|
||||
"""Mots du nom sans l'article qui le précède : « La commandante », « L'aubergiste »."""
|
||||
words = name.split()
|
||||
if len(words) > 1 and words[0].lower() in _ARTICLES:
|
||||
words = words[1:]
|
||||
elif words and _ELISION.match(words[0]) and len(words[0]) > 2:
|
||||
words = [_ELISION.sub("", words[0]), *words[1:]]
|
||||
return words
|
||||
|
||||
|
||||
def _is_unique_role(phrase: str, book_text: str) -> bool:
|
||||
"""Le livre parle-t-il de CE personnage plutôt que d'une créature parmi d'autres ?
|
||||
|
||||
Un rôle unique sans nom est toujours désigné par l'article défini (« la commandante »,
|
||||
« the innkeeper ») ; une créature générique apparaît aussi avec un article indéfini, un
|
||||
nombre ou au pluriel (« a wraith », « deux gobelins », « ghosts »)."""
|
||||
target = re.escape(phrase)
|
||||
flags = re.IGNORECASE
|
||||
definite = re.findall(rf"(?<!{_LETTER})(?:le |la |l['’]|the ){target}(?!{_LETTER})", book_text, flags)
|
||||
indefinite = re.search(rf"(?<!{_LETTER})(?:{_INDEFINITE}|\d+) {target}", book_text, flags)
|
||||
plural = re.search(rf"(?<!{_LETTER}){target}(?:s|es|x)(?!{_LETTER})", book_text, flags)
|
||||
return len(definite) >= 2 and not indefinite and not plural
|
||||
|
||||
|
||||
def _is_generic(name: str, book_text: str) -> bool:
|
||||
"""Le nom est-il celui d'une créature générique plutôt que d'un personnage ?
|
||||
|
||||
« Nine ghouls » commence par un nombre. Sinon, pour un nom dont seul le premier mot porte
|
||||
une majuscule (« Wraith », « Giant rat »), on regarde comment le livre l'écrit : un nom
|
||||
commun y figure en minuscules (« a wraith ») et jamais avec une majuscule en cours de
|
||||
phrase ; un nom propre, si (« led by Key », « Paltuis le mage »). Un nom commun reste un
|
||||
PNJ quand il désigne un rôle unique (« la commandante » : cf. _is_unique_role)."""
|
||||
words = _without_article(name)
|
||||
if not words:
|
||||
return True
|
||||
first = words[0]
|
||||
if first[0].isdigit() or first.lower() in _COUNT_WORDS:
|
||||
return True
|
||||
if any(word[:1].isupper() for word in words[1:]):
|
||||
return False
|
||||
capital = first[:1].upper() + first[1:]
|
||||
common = re.search(rf"(?<!{_LETTER}){re.escape(first.lower())}(?!{_LETTER})", book_text)
|
||||
proper = re.search(rf"[a-zà-ÿ,;:] {re.escape(capital)}(?!{_LETTER})", book_text)
|
||||
if not common or proper:
|
||||
return False
|
||||
return not _is_unique_role(" ".join(words).lower(), book_text)
|
||||
|
||||
|
||||
# Titres des textes où le livre parle de lui-même : préface, note de l'auteur, mode d'emploi.
|
||||
_FRONT_MATTER = re.compile(
|
||||
r"^(?:foreword|preface|avant propos|a note from|note from|notes? de l auteur|notes? des auteurs"
|
||||
r"|mot de l auteur|about the authors?|a propos de l auteur|a propos des auteurs|acknowledg\w*"
|
||||
r"|remerciements|dedication|dedicace|how this book|how to use|using this"
|
||||
r"|about this (?:book|adventure|module)|comment utiliser|a propos de (?:ce|cet|cette))\b")
|
||||
# Une année de notre monde et un mot d'édition dans le même texte : l'histoire du livre, pas celle
|
||||
# de l'aventure (« First published in 1977… », « Financé sur Kickstarter en 2019 »).
|
||||
_REAL_YEAR = re.compile(r"(?<!\d)(?:19[7-9]\d|20[0-3]\d)(?!\d)")
|
||||
_PUBLISHING = re.compile(
|
||||
r"\b(?:publish\w*|publi[ée]e?s?|kickstarter|copyright|play-?test\w*|isbn|reprint\w*|r[ée][ée]dit\w*"
|
||||
r"|game designers?|role-?playing|jeux? de r[ôo]le)\b|©", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_about_the_book(scene: dict) -> bool:
|
||||
"""La scène parle-t-elle du livre (préface, historique de l'édition) plutôt que de l'aventure ?"""
|
||||
titles = [_strip_accents(_fold(part)) for part in scene["name"].split("›")]
|
||||
if any(_FRONT_MATTER.match(title) for title in titles):
|
||||
return True
|
||||
text = scene["gm_notes"]
|
||||
return bool(_REAL_YEAR.search(text) and _PUBLISHING.search(text))
|
||||
|
||||
|
||||
def _met_in_the_adventure(npcs: dict[str, dict], scenes: list[dict]) -> dict[str, dict]:
|
||||
"""PNJ dont le nom figure dans l'aventure elle-même. Une personne citée seulement dans une
|
||||
préface ou dans l'historique de l'édition (un auteur, un éditeur) est une personne réelle."""
|
||||
fiction = [scene for scene in scenes if not _is_about_the_book(scene)]
|
||||
if not fiction or len(fiction) == len(scenes):
|
||||
return npcs
|
||||
raw = "\n".join(scene["name"] + "\n" + _aid_text(scene, 10 ** 9) for scene in fiction)
|
||||
# Un appel de note collé au nom (« PandemagisticatorII ») ne doit pas le rendre introuvable.
|
||||
text = " " + _fold(_FOOTNOTE_IN_TEXT.sub("", raw)) + " "
|
||||
return {key: npc for key, npc in npcs.items()
|
||||
if any(f" {alias} " in text for alias in _aliases(npc["name"]))}
|
||||
|
||||
|
||||
def _is_group(name: str, description: str) -> bool:
|
||||
"""Le nom ou la fiche désigne-t-il un groupe (peuple, clan, gardes) plutôt qu'un individu ?"""
|
||||
words = _strip_accents(_fold(name)).split()
|
||||
if not words or words[0] in ("les", "des") or words[0] in _GROUP_NAME_WORDS or words[-1] in _GROUP_NAME_WORDS:
|
||||
return True
|
||||
return bool(_GROUP_DESCRIPTION.match(_strip_accents(_fold(description))))
|
||||
|
||||
|
||||
def _translation_units(scenes: list[dict]) -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""Textes à traduire (notes des scènes, descriptions des salles), repérés par une clé, et
|
||||
leur libellé pour les messages d'avancement."""
|
||||
units: dict[str, str] = {}
|
||||
labels: dict[str, str] = {}
|
||||
for index, scene in enumerate(scenes):
|
||||
if scene["gm_notes"].strip():
|
||||
units[f"s{index}"] = scene["gm_notes"]
|
||||
labels[f"s{index}"] = scene["name"]
|
||||
for rank, room in enumerate(scene["rooms"]):
|
||||
if room["description"].strip():
|
||||
units[f"s{index}r{rank}"] = room["description"]
|
||||
labels[f"s{index}r{rank}"] = f"{scene['name']} › {room['name']}"
|
||||
return units, labels
|
||||
|
||||
|
||||
def _apply_translation(scenes: list[dict], translated: dict[str, str]) -> None:
|
||||
"""Remet chaque texte traduit à sa place. Un texte non traduit revient tel quel."""
|
||||
for index, scene in enumerate(scenes):
|
||||
scene["gm_notes"] = translated.get(f"s{index}", scene["gm_notes"])
|
||||
for rank, room in enumerate(scene["rooms"]):
|
||||
room["description"] = translated.get(f"s{index}r{rank}", room["description"])
|
||||
|
||||
|
||||
def _arcs_from_dicts(arcs: list[dict]) -> list[ArcProposal]:
|
||||
return [
|
||||
ArcProposal(arc["name"], arc["description"], arc.get("type", "LINEAR"), [
|
||||
ChapterProposal(chapter["name"], chapter["description"], [
|
||||
SceneProposal(scene["name"], scene["description"], scene["player_narration"], scene["gm_notes"],
|
||||
[RoomProposal(r["name"], r["description"], r["enemies"], r["loot"])
|
||||
for r in scene["rooms"]])
|
||||
for scene in chapter["scenes"]])
|
||||
for chapter in arc["chapters"]])
|
||||
for arc in arcs
|
||||
]
|
||||
|
||||
|
||||
def _serialize_arcs(arcs: list[ArcProposal]) -> list[dict]:
|
||||
"""Sérialise l'arbre de dataclasses en dicts JSON pour le flux SSE."""
|
||||
return [
|
||||
|
||||
@@ -25,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_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.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.application.rules_translation import (
|
||||
DEFAULT_CONCURRENCY,
|
||||
RulesTranslator,
|
||||
detect_language,
|
||||
other_languages,
|
||||
translate_sections,
|
||||
)
|
||||
from app.application.streaming import HEARTBEAT_INTERVAL_SECONDS, with_heartbeat
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
|
||||
# Repli anti-troncature : si la SORTIE d'un morceau est coupée (le modèle ne peut
|
||||
@@ -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).
|
||||
_DETECT_CHARS = 20_000
|
||||
|
||||
# Mode segmentation : clé interne du texte d'un morceau que le modèle n'a pas su découper
|
||||
# (aucun repère retrouvé, réponse illisible, appel en échec). Le texte original est entre
|
||||
# nos mains : il n'est JAMAIS abandonné — la fusion le place à la suite de la section
|
||||
# précédente (cf. _SectionMerger). Un petit modèle local perdait ainsi, sans rien dire,
|
||||
# 1 morceau sur 15 d'un livre de 29 pages (mesuré le 2026-11-13).
|
||||
UNSORTED = "\x00unsorted"
|
||||
|
||||
class _SectionMerger:
|
||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||
|
||||
@@ -102,15 +121,22 @@ class _SectionMerger:
|
||||
morceau — sert au flux de progression pour annoncer les sections trouvées.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, unsorted_title: str = "") -> None:
|
||||
"""`unsorted_title` : titre donné au texte non découpé quand aucune section ne le
|
||||
précède (premier morceau du livre)."""
|
||||
self._merged: dict[str, list[str]] = {}
|
||||
self._canonical_key: dict[str, str] = {}
|
||||
self._last: str | None = None
|
||||
self._unsorted_title = unsorted_title or prompts.CANONICAL_SECTIONS[0]
|
||||
|
||||
def add(self, sections: dict[str, str]) -> list[str]:
|
||||
touched: list[str] = []
|
||||
for title, content in sections.items():
|
||||
title = title.strip()
|
||||
content = (content or "").strip()
|
||||
if title == UNSORTED:
|
||||
# Texte non découpé : suite de la dernière section rencontrée.
|
||||
title = self._last or self._unsorted_title
|
||||
title = title.strip()
|
||||
if not title or not content:
|
||||
continue
|
||||
key = title.lower()
|
||||
@@ -120,6 +146,7 @@ class _SectionMerger:
|
||||
canonical = self._canonical_key[key]
|
||||
self._merged[canonical].append(content)
|
||||
touched.append(canonical)
|
||||
self._last = canonical
|
||||
# Dé-duplication en préservant l'ordre d'apparition.
|
||||
seen: set[str] = set()
|
||||
return [t for t in touched if not (t in seen or seen.add(t))]
|
||||
@@ -215,6 +242,9 @@ def _combine_sections(a: dict[str, str], b: dict[str, str]) -> dict[str, str]:
|
||||
out = dict(a)
|
||||
by_lower = {k.lower(): k for k in out}
|
||||
for title, content in b.items():
|
||||
if title == UNSORTED and out:
|
||||
# Texte non découpé de la seconde moitié : suite de ce qui le précède.
|
||||
title = next(reversed(out))
|
||||
key = by_lower.get(title.lower())
|
||||
if key is not None:
|
||||
out[key] = f"{out[key]}\n\n{content}".strip()
|
||||
@@ -233,6 +263,7 @@ class ImportRulesUseCase:
|
||||
extractor: PdfTextExtractor,
|
||||
chunk_target_tokens: int = CHUNK_TARGET_TOKENS,
|
||||
segment_only: bool = False,
|
||||
structure_first: bool = False,
|
||||
) -> None:
|
||||
"""`segment_only=True` (modèles locaux) : le LLM ne renvoie que les
|
||||
frontières des sections (titre + premiers mots) et le texte original est
|
||||
@@ -242,29 +273,45 @@ class ImportRulesUseCase:
|
||||
self._extractor = extractor
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
self._segment_only = segment_only
|
||||
# `structure_first` : découper d'abord le livre par SA propre structure (signets du
|
||||
# PDF, sinon titres repérés à leur taille), sans IA — instantané, fidèle, identique
|
||||
# sur toutes les machines. L'IA ne sert plus qu'aux PDF sans structure.
|
||||
self._structure_first = structure_first
|
||||
# Intervalle des signaux de vie envoyés pendant la traduction (réglable pour les tests).
|
||||
self._heartbeat_seconds = HEARTBEAT_INTERVAL_SECONDS
|
||||
# Un modèle local traite les demandes l'une après l'autre : en envoyer plusieurs
|
||||
# ne ferait qu'allonger leur attente (et déclencher le délai maximal d'un appel).
|
||||
self._translation_concurrency = 1 if segment_only else DEFAULT_CONCURRENCY
|
||||
|
||||
async def execute(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG) -> RulesImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie le résultat complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
logger.info(
|
||||
"Import règles : %s page(s) (%s via OCR), %s morceau(x) à traiter.",
|
||||
doc.page_count, doc.ocr_page_count, len(chunks),
|
||||
)
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
sections = merger.result()
|
||||
structure = self._split_by_structure(doc, language)
|
||||
if structure is not None:
|
||||
sections = structure.sections
|
||||
else:
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
logger.info(
|
||||
"Import règles : %s page(s) (%s via OCR), %s morceau(x) à traiter.",
|
||||
doc.page_count, doc.ocr_page_count, len(chunks),
|
||||
)
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
try:
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
except LLMProviderError:
|
||||
if not self._segment_only:
|
||||
raise
|
||||
# Segmentation : le texte du morceau est gardé même si l'appel échoue.
|
||||
merger.add({UNSORTED: chunk})
|
||||
sections = merger.result()
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
by_language = {source: sections}
|
||||
translator = RulesTranslator(self._llm)
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
|
||||
by_language[target] = {
|
||||
titles.get(title, title): await translator.translate_content(content, source, target)
|
||||
for title, content in sections.items()
|
||||
}
|
||||
async for kind, payload in self._translate(sections, source, target):
|
||||
if kind == "result":
|
||||
by_language[target] = payload.sections
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
return RulesImportResult(
|
||||
@@ -288,92 +335,132 @@ class ImportRulesUseCase:
|
||||
yield {"type": "extracting"}
|
||||
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
total = len(chunks)
|
||||
logger.info(
|
||||
"Import règles (stream) : %s page(s) (%s via OCR), %s morceau(x).",
|
||||
doc.page_count, doc.ocr_page_count, total,
|
||||
)
|
||||
yield {
|
||||
"type": "start",
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
merger = _SectionMerger()
|
||||
structure = self._split_by_structure(doc, language)
|
||||
split_method = structure.method if structure is not None else AI_SPLIT
|
||||
skipped = 0
|
||||
last_error: str | None = None
|
||||
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
||||
status_queue: asyncio.Queue = asyncio.Queue()
|
||||
status_token = set_status_queue(status_queue)
|
||||
try:
|
||||
for i, chunk in enumerate(chunks):
|
||||
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
||||
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
||||
# HEARTBEAT : on émet des keep-alive pendant l'appel LLM (long sur un
|
||||
# provider lent) pour que le flux SSE ne soit jamais coupé par le Core.
|
||||
new_titles: list[str] = []
|
||||
try:
|
||||
sections: dict[str, str] | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._map_chunk(chunk, index=i, total=total, language=language),
|
||||
status_queue=status_queue,
|
||||
):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload,
|
||||
"current": i + 1, "total": total}
|
||||
else:
|
||||
sections = payload
|
||||
new_titles = merger.add(sections or {})
|
||||
except LLMProviderError as exc:
|
||||
skipped += 1
|
||||
last_error = str(exc)
|
||||
logger.warning("Morceau %s/%s ignoré (échec LLM) : %s", i + 1, total, exc)
|
||||
yield {"type": "chunk_failed", "current": i + 1, "total": total,
|
||||
"message": str(exc)[:300]}
|
||||
yield {
|
||||
"type": "progress",
|
||||
"current": i + 1,
|
||||
"total": total,
|
||||
"new_sections": new_titles,
|
||||
"skipped": skipped,
|
||||
}
|
||||
finally:
|
||||
reset_status_queue(status_token)
|
||||
if structure is not None:
|
||||
# Le livre porte son propre découpage : on le suit, sans appeler l'IA.
|
||||
sections = structure.sections
|
||||
total = 1
|
||||
yield {"type": "start", "page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count, "total": 1}
|
||||
origin = ("la table des matières du PDF" if structure.method == BOOKMARKS
|
||||
else "les titres du livre")
|
||||
yield {"type": "status",
|
||||
"message": f"Découpage d'après {origin} : {len(sections)} sections, sans IA."}
|
||||
yield {"type": "progress", "current": 1, "total": 1,
|
||||
"new_sections": list(sections)[:_ANNOUNCED_TITLES], "skipped": 0}
|
||||
else:
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
total = len(chunks)
|
||||
logger.info(
|
||||
"Import règles (stream) : %s page(s) (%s via OCR), %s morceau(x).",
|
||||
doc.page_count, doc.ocr_page_count, total,
|
||||
)
|
||||
yield {
|
||||
"type": "start",
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"total": total,
|
||||
}
|
||||
|
||||
if total > 0 and skipped == total:
|
||||
yield {"type": "error",
|
||||
"message": "Tous les morceaux ont échoué auprès du fournisseur IA. "
|
||||
f"Dernier message : {last_error or 'inconnu'}"}
|
||||
return
|
||||
merger = _SectionMerger()
|
||||
skipped = 0
|
||||
last_error: str | None = None
|
||||
# Canal de statut : les couches profondes (retry LLM, re-découpage) y
|
||||
# publient des messages destinés à l'UI — cf. import_status.notify_status.
|
||||
status_queue: asyncio.Queue = asyncio.Queue()
|
||||
status_token = set_status_queue(status_queue)
|
||||
try:
|
||||
for i, chunk in enumerate(chunks):
|
||||
# RÉSILIENCE : un morceau qui échoue est SAUTÉ, l'import continue.
|
||||
# Abandon seulement si AUCUN morceau ne passe (cf. après la boucle).
|
||||
# HEARTBEAT : on émet des keep-alive pendant l'appel LLM (long sur un
|
||||
# provider lent) pour que le flux SSE ne soit jamais coupé par le Core.
|
||||
new_titles: list[str] = []
|
||||
try:
|
||||
sections: dict[str, str] | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._map_chunk(chunk, index=i, total=total, language=language),
|
||||
status_queue=status_queue,
|
||||
):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload,
|
||||
"current": i + 1, "total": total}
|
||||
else:
|
||||
sections = payload
|
||||
new_titles = merger.add(sections or {})
|
||||
except LLMProviderError as exc:
|
||||
skipped += 1
|
||||
last_error = str(exc)
|
||||
logger.warning("Morceau %s/%s ignoré (échec LLM) : %s", i + 1, total, exc)
|
||||
yield {"type": "chunk_failed", "current": i + 1, "total": total,
|
||||
"message": str(exc)[:300]}
|
||||
if self._segment_only:
|
||||
# Segmentation : le texte original est là, on ne le perd pas. Si TOUS
|
||||
# les morceaux échouent, l'import reste une erreur (cf. plus bas).
|
||||
new_titles = merger.add({UNSORTED: chunk})
|
||||
yield {
|
||||
"type": "progress",
|
||||
"current": i + 1,
|
||||
"total": total,
|
||||
"new_sections": new_titles,
|
||||
"skipped": skipped,
|
||||
}
|
||||
finally:
|
||||
reset_status_queue(status_token)
|
||||
|
||||
sections = merger.result()
|
||||
if total > 0 and not sections:
|
||||
# Le texte a bien été extrait mais AUCUN morceau n'a produit de JSON
|
||||
# exploitable (sorties coupées/illisibles). Sans ce signal, l'UI reçoit
|
||||
# un `done` vide et l'utilisateur conclut à tort que le PDF est illisible.
|
||||
yield {"type": "error",
|
||||
"message": "Le texte du PDF a été extrait, mais le modèle n'a produit "
|
||||
"aucune section exploitable (réponses JSON vides ou coupées). "
|
||||
"Réduisez la taille des morceaux d'import, augmentez la fenêtre "
|
||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||
return
|
||||
if total > 0 and skipped == total:
|
||||
yield {"type": "error",
|
||||
"message": "Tous les morceaux ont échoué auprès du fournisseur IA. "
|
||||
f"Dernier message : {last_error or 'inconnu'}"}
|
||||
return
|
||||
|
||||
sections = merger.result()
|
||||
if total > 0 and not sections:
|
||||
# Le texte a bien été extrait mais AUCUN morceau n'a produit de JSON
|
||||
# exploitable (sorties coupées/illisibles). Sans ce signal, l'UI reçoit
|
||||
# un `done` vide et l'utilisateur conclut à tort que le PDF est illisible.
|
||||
yield {"type": "error",
|
||||
"message": "Le texte du PDF a été extrait, mais le modèle n'a produit "
|
||||
"aucune section exploitable (réponses JSON vides ou coupées). "
|
||||
"Réduisez la taille des morceaux d'import, augmentez la fenêtre "
|
||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||
return
|
||||
|
||||
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
|
||||
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
# L'extraction est livrée AVANT la traduction : si le flux s'interrompt pendant la
|
||||
# traduction (longue), le Core a déjà de quoi proposer les règles dans leur langue.
|
||||
yield {
|
||||
"type": "extracted",
|
||||
"sections": sections,
|
||||
"split_method": split_method,
|
||||
"source_language": source,
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||
untranslated: list[str] = []
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
async for ev in self._translate_events(sections, source, target):
|
||||
if ev["type"] == "_translated":
|
||||
by_language[target] = ev["sections"]
|
||||
async for kind, payload in self._translate(sections, source, target):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": total, "total": total}
|
||||
elif kind == "status":
|
||||
yield {"type": "status", "message": payload}
|
||||
else:
|
||||
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:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
yield {"type": "status",
|
||||
@@ -384,35 +471,32 @@ class ImportRulesUseCase:
|
||||
"sections": sections,
|
||||
"sections_by_language": by_language,
|
||||
"source_language": source,
|
||||
"split_method": split_method,
|
||||
"untranslated": untranslated,
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
|
||||
"""Évènements d'avancement de la traduction ; le dernier est
|
||||
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
|
||||
translator = RulesTranslator(self._llm)
|
||||
titles = list(sections)
|
||||
total = len(titles)
|
||||
label = language_name(target)
|
||||
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
|
||||
mapping: dict[str, str] = {}
|
||||
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": 0, "total": total}
|
||||
elif kind == "result":
|
||||
mapping = unique_titles(payload)
|
||||
out: dict[str, str] = {}
|
||||
for i, title in enumerate(titles):
|
||||
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
|
||||
"current": i + 1, "total": total}
|
||||
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
|
||||
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}
|
||||
def _split_by_structure(self, doc, language: str) -> StructureSplit | None:
|
||||
"""Découpage par la structure du PDF, ou None s'il faut passer par l'IA (réglage
|
||||
coupé, extracteur sans lignes, PDF sans signets ni titres repérables)."""
|
||||
if not self._structure_first:
|
||||
return None
|
||||
split = split_by_structure(
|
||||
doc, preamble_title="Front matter" if language == "en" else "Préambule")
|
||||
if split.method == NONE:
|
||||
logger.info("Import règles : pas de structure exploitable dans ce PDF — découpage par l'IA.")
|
||||
return None
|
||||
logger.info("Import règles : %s page(s), découpage par la structure du PDF (%s) : %s sections, "
|
||||
"%s titres, sans IA.", doc.page_count, split.method, len(split.sections), split.heading_count)
|
||||
return split
|
||||
|
||||
def _translate(self, sections: dict[str, str], source: str, target: str):
|
||||
"""Traduction des sections vers `target` (cf. rules_translation.translate_sections)."""
|
||||
return translate_sections(RulesTranslator(self._llm), sections, source, target,
|
||||
concurrency=self._translation_concurrency,
|
||||
heartbeat_seconds=self._heartbeat_seconds)
|
||||
|
||||
# --- MAP : un morceau → sections -----------------------------------------
|
||||
|
||||
@@ -479,6 +563,15 @@ class ImportRulesUseCase:
|
||||
if truncated:
|
||||
logger.warning(
|
||||
"Morceau %s : sortie tronquée, profondeur max atteinte — partiel conservé.", index)
|
||||
if self._segment_only and not sections and text.strip():
|
||||
# Aucun repère exploitable : le texte suit la section précédente au lieu de disparaître.
|
||||
logger.warning(
|
||||
"Morceau %s : aucune section repérée par le modèle — texte gardé à la suite de "
|
||||
"la section précédente (%s caractères).", index, len(text))
|
||||
notify_status(
|
||||
f"Le modèle n'a pas su découper le morceau {index + 1} : son texte est gardé "
|
||||
"à la suite de la section précédente.")
|
||||
return {UNSORTED: text}
|
||||
return sections
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -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",
|
||||
"merge": ["nom à fusionner", ...]}}]}}
|
||||
S'il n'y a RIEN à fusionner (cas le plus fréquent) : {{"chapter_merges": [], "scene_merges": []}}"""
|
||||
|
||||
|
||||
# --- Aides de l'IA sur une campagne découpée par la structure du livre ------------------------
|
||||
# Le texte des scènes vient du livre, mot pour mot, et n'est jamais confié au modèle pour
|
||||
# réécriture. Le modèle n'écrit que deux AIDES, courtes et séparées du texte : un synopsis par
|
||||
# scène, et les fiches des PNJ nommés.
|
||||
AIDS_PROMPT = """Tu aides un MJ à préparer une campagne de jeu de rôle. Voici des SCÈNES tirées
|
||||
d'un livre de campagne. Leur texte est celui du livre : il ne sera PAS modifié, et tu ne dois
|
||||
PAS le réécrire.
|
||||
|
||||
Ta tâche se limite à deux aides, courtes :
|
||||
1. Pour CHAQUE scène, un SYNOPSIS de 1 à 2 phrases : ce qui s'y passe, pour que le MJ la
|
||||
retrouve d'un coup d'œil.
|
||||
2. Les PNJ NOMMÉS et les créatures UNIQUES (boss) présents dans ces scènes, chacun avec une
|
||||
fiche de 2 à 4 phrases : rôle dans l'histoire, apparence, motivations, où on le rencontre.
|
||||
|
||||
Règles IMPÉRATIVES :
|
||||
- Ne t'appuie QUE sur le texte fourni. N'invente rien, ne complète pas avec ce que tu sais.
|
||||
- Un synopsis par scène, repéré par son numéro "n". Une scène sans matière narrative (bloc de
|
||||
statistiques, table, crédits) reçoit un synopsis vide "".
|
||||
- PNJ : écris leur nom EXACTEMENT comme dans le texte. Pas de monstres génériques sans nom
|
||||
(« 3 gobelins », « un loup »). Aucun PNJ nommé → "npcs": [].
|
||||
- Un PNJ est un INDIVIDU. Ne relève PAS les peuples, factions, organisations, groupes, lieux,
|
||||
objets, ni les profils de créature (« Légionnaire », « Zombie », « Garde »).
|
||||
- Chaque PNJ une seule fois, sous son nom le plus complet, sans son titre (« dame », « capitaine »).
|
||||
- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour :
|
||||
{{"scenes": [{{"n": 1, "synopsis": "…"}}], "npcs": [{{"name": "…", "description": "…"}}]}}
|
||||
- Rédige les synopsis et les fiches en {language_name}, quelle que soit la langue du texte.
|
||||
Garde tels quels les noms propres.
|
||||
|
||||
{scenes}
|
||||
|
||||
Renvoie maintenant le JSON."""
|
||||
|
||||
OVERVIEW_TITLES = {"fr": "Présentation", "en": "Overview"}
|
||||
APPENDIX_ARC_NAMES = {"fr": "Annexes", "en": "Appendices"}
|
||||
|
||||
|
||||
def appendix_arc_name(language: str) -> str:
|
||||
"""Nom de l'arc qui réunit les annexes du livre (bestiaire, objets, aides de jeu)."""
|
||||
return APPENDIX_ARC_NAMES.get(language, APPENDIX_ARC_NAMES["fr"])
|
||||
|
||||
|
||||
def overview_title(language: str) -> str:
|
||||
"""Nom de la scène qui porte le texte d'introduction d'une aventure."""
|
||||
return OVERVIEW_TITLES.get(language, OVERVIEW_TITLES["fr"])
|
||||
|
||||
@@ -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
|
||||
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
|
||||
celui du texte, la description est recopiée, et chaque sort cite un passage MOT POUR MOT :
|
||||
le Core vérifie que le nom et le passage se retrouvent dans le texte envoyé, et écarte le
|
||||
sort sinon.
|
||||
Un principe tient toute la fonction : le modèle DÉSIGNE, il n'écrit pas. Il rend le nom du
|
||||
sort tel qu'il est dans le texte, son niveau, son école, et les premiers mots de son bloc ;
|
||||
la description, elle, est reprise du texte par le code (cf. spell_location), mot pour mot.
|
||||
"""
|
||||
|
||||
|
||||
@@ -55,21 +54,28 @@ def spell_extraction_prompt(system_name: str, section_title: str, text: str,
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- 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'
|
||||
'- "level" : son niveau, rang, cercle ou palier si le texte le donne (« 1 », « Tour de '
|
||||
'magie », « Rang II »), sinon "".\n'
|
||||
'- "school" : son école, sa liste ou sa tradition si le texte la donne, sinon "".\n'
|
||||
'- "description" : ce que fait le sort, RECOPIÉ depuis le texte, en entier. Ne résume '
|
||||
"pas, ne traduis pas, n'ajoute rien. Laisse de côté la ligne du nom et les valeurs déjà "
|
||||
'rangées dans "level", "school" ou "values".\n'
|
||||
'- "excerpt" : UNE phrase de la description de ce sort, COPIÉE MOT POUR MOT depuis le '
|
||||
"texte (au moins 25 caractères), sans points de suspension ni guillemets ajoutés.\n"
|
||||
'- "level" : son niveau si le texte le donne, sinon "". Écris-le TOUJOURS de la même '
|
||||
"façon : un niveau numéroté par son SEUL nombre (« 1 », jamais « Niveau 1 » ni "
|
||||
"« NIVEAU 1 ») ; un sort de niveau 0 (tour de magie, cantrip, sort mineur) par "
|
||||
"« Tour de magie » si le texte est en français, « Cantrip » s'il est en anglais ; un "
|
||||
"autre palier par le terme du texte (« Rang II »). N'y ajoute rien d'autre (ni zone, ni "
|
||||
"type, ni durée).\n"
|
||||
'- "school" : son école, sa liste ou sa tradition si le texte la donne, sinon "". Donne '
|
||||
"son nom COURT, au singulier, sans « Sorts de » ni « École de » (« Foudre », pas « Sorts "
|
||||
"de foudre »), écrit de la même façon pour tous les sorts de cette école. Si le titre de "
|
||||
"la section ou un titre placé au-dessus du sort nomme l'école, c'est elle.\n"
|
||||
'- "start" : les 4 à 8 PREMIERS MOTS du bloc de ce sort, COPIÉS MOT POUR MOT depuis le '
|
||||
"texte, à partir de la ligne qui ouvre le sort (la ligne de son niveau si elle est juste "
|
||||
"au-dessus de son nom, sinon la ligne de son nom).\n"
|
||||
"- Ne recopie PAS la description du sort : l'application la reprend elle-même dans le "
|
||||
"texte, mot pour mot. Ne résume rien, ne traduis rien.\n"
|
||||
"- N'invente aucun sort et ne complète pas avec ce que tu sais d'un autre jeu. Un sort "
|
||||
"seulement cité, sans que le texte décrive son effet, n'est pas relevé.\n"
|
||||
"- Ne relève pas les règles générales de magie (comment lancer un sort, ce que coûte la "
|
||||
"magie) : seulement les sorts eux-mêmes.\n"
|
||||
'- 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."
|
||||
)
|
||||
|
||||
@@ -8,15 +8,34 @@ pour rester sous les limites de sortie des modèles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.streaming import HEARTBEAT_INTERVAL_SECONDS, with_heartbeat
|
||||
from app.core.language import language_name
|
||||
from app.domain.ports import LLMProvider
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LANGUAGES = ("fr", "en")
|
||||
|
||||
# Sections traduites en même temps (fournisseur distant). Traduites l'une après l'autre,
|
||||
# les sections d'un livre de 30 pages prenaient près d'une heure avec un modèle lent.
|
||||
DEFAULT_CONCURRENCY = 3
|
||||
# Durée maximale de la traduction. Au-delà, les sections restantes gardent le texte du livre.
|
||||
BUDGET_SECONDS = 60 * 60
|
||||
# Sections en échec à partir desquelles on n'en lance plus de nouvelles : le fournisseur est
|
||||
# en panne ou saturé, insister ferait attendre pour rien.
|
||||
MAX_FAILED_SECTIONS = 3
|
||||
|
||||
# Nombre de titres de section traduits par appel.
|
||||
TITLES_PER_CALL = 40
|
||||
|
||||
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||
CHUNK_CHARS = 6000
|
||||
|
||||
@@ -64,7 +83,79 @@ def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
||||
return chunks
|
||||
|
||||
|
||||
# Termes de jeu courants (vocabulaire des jeux « 5e »), anglais → français. Un petit modèle
|
||||
# les traduit au hasard (« WIS » → « SAGES », « Saving Throws » → « Sauvetages ») : on lui donne
|
||||
# ceux que l'extrait contient. Les abréviations (en capitales, ou monnaies) sont cherchées
|
||||
# telles quelles ; le reste sans tenir compte de la casse.
|
||||
_GLOSSARY_EN_FR: tuple[tuple[str, str], ...] = (
|
||||
("Armor Class", "Classe d'armure"), ("Hit Points", "Points de vie"), ("Speed", "Vitesse"),
|
||||
("Saving Throws", "Jets de sauvegarde"), ("saving throw", "jet de sauvegarde"),
|
||||
("Skills", "Compétences"), ("Senses", "Sens"), ("Languages", "Langues"), ("Challenge", "Puissance"),
|
||||
("Damage Resistances", "Résistances aux dégâts"), ("Damage Immunities", "Immunités aux dégâts"),
|
||||
("Damage Vulnerabilities", "Vulnérabilités aux dégâts"), ("Condition Immunities", "Immunités aux états"),
|
||||
("passive Perception", "Perception passive"), ("darkvision", "vision dans le noir"),
|
||||
("blindsight", "vision aveugle"), ("truesight", "vision véritable"),
|
||||
("tremorsense", "perception des vibrations"),
|
||||
("Legendary Actions", "Actions légendaires"), ("Reactions", "Réactions"), ("Multiattack", "Attaques multiples"),
|
||||
("Melee Weapon Attack", "Attaque au corps à corps avec une arme"),
|
||||
("Ranged Weapon Attack", "Attaque à distance avec une arme"),
|
||||
("Melee Spell Attack", "Attaque de sort au corps à corps"),
|
||||
("Ranged Spell Attack", "Attaque de sort à distance"),
|
||||
("to hit", "au toucher"), ("reach", "allonge"), ("one target", "une cible"),
|
||||
("Strength", "Force"), ("Dexterity", "Dextérité"), ("Wisdom", "Sagesse"), ("Charisma", "Charisme"),
|
||||
("STR", "FOR"), ("DEX", "DEX"), ("CON", "CON"), ("INT", "INT"), ("WIS", "SAG"), ("CHA", "CHA"),
|
||||
("AC", "CA"), ("DC", "DD"), ("HP", "PV"), ("XP", "PX"),
|
||||
("gp", "po"), ("sp", "pa"), ("cp", "pc"),
|
||||
("beast", "bête"), ("undead", "mort-vivant"), ("fiend", "fiélon"), ("fey", "fée"),
|
||||
("construct", "créature artificielle"), ("monstrosity", "monstruosité"), ("ooze", "vase"),
|
||||
("humanoid", "humanoïde"), ("unaligned", "non aligné"),
|
||||
("lawful good", "loyal bon"), ("lawful neutral", "loyal neutre"), ("lawful evil", "loyal mauvais"),
|
||||
("neutral good", "neutre bon"), ("neutral evil", "neutre mauvais"), ("chaotic good", "chaotique bon"),
|
||||
("chaotic neutral", "chaotique neutre"), ("chaotic evil", "chaotique mauvais"),
|
||||
("advantage", "avantage"), ("disadvantage", "désavantage"), ("short rest", "repos court"),
|
||||
("long rest", "repos long"), ("proficiency bonus", "bonus de maîtrise"),
|
||||
("spell slot", "emplacement de sort"), ("cantrip", "tour de magie"), ("Hit Dice", "dés de vie"),
|
||||
("bonus action", "action bonus"), ("difficult terrain", "terrain difficile"),
|
||||
("ability check", "test de caractéristique"), ("attack roll", "jet d'attaque"),
|
||||
("temporary hit points", "points de vie temporaires"), ("requires attunement", "nécessite un lien"),
|
||||
("Wondrous item", "Objet merveilleux"), ("very rare", "très rare"), ("uncommon", "peu commun"),
|
||||
("legendary", "légendaire"),
|
||||
("blinded", "aveuglé"), ("charmed", "charmé"), ("deafened", "assourdi"), ("frightened", "effrayé"),
|
||||
("grappled", "agrippé"), ("incapacitated", "neutralisé"), ("paralyzed", "paralysé"),
|
||||
("petrified", "pétrifié"), ("poisoned", "empoisonné"), ("prone", "à terre"), ("restrained", "entravé"),
|
||||
("stunned", "étourdi"), ("unconscious", "inconscient"), ("exhaustion", "épuisement"),
|
||||
("bludgeoning", "contondant"), ("piercing", "perforant"), ("slashing", "tranchant"),
|
||||
("necrotic", "nécrotique"), ("psychic", "psychique"), ("thunder", "tonnerre"), ("lightning", "foudre"),
|
||||
)
|
||||
_GLOSSARIES: dict[tuple[str, str], tuple[tuple[str, str], ...]] = {
|
||||
("en", "fr"): _GLOSSARY_EN_FR,
|
||||
("fr", "en"): tuple((french, english) for english, french in _GLOSSARY_EN_FR),
|
||||
}
|
||||
# Nombre maximal de termes donnés pour un extrait : le prompt d'un petit modèle reste court.
|
||||
GLOSSARY_TERMS = 45
|
||||
_EXACT_CASE = frozenset({"gp", "sp", "cp", "po", "pa", "pc"})
|
||||
|
||||
|
||||
def glossary(text: str, source: str, target: str, limit: int = GLOSSARY_TERMS) -> list[tuple[str, str]]:
|
||||
"""Termes de jeu présents dans `text`, avec leur traduction attendue (dans l'ordre du
|
||||
glossaire, `limit` au plus). Liste vide pour un couple de langues sans glossaire."""
|
||||
found: list[tuple[str, str]] = []
|
||||
for term, translation in _GLOSSARIES.get((source, target), ()):
|
||||
exact = term.isupper() or term in _EXACT_CASE
|
||||
pattern = rf"(?<![^\W\d_]){re.escape(term)}(?![^\W\d_])"
|
||||
if re.search(pattern, text, 0 if exact else re.IGNORECASE):
|
||||
found.append((term, translation))
|
||||
if len(found) >= limit:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def content_prompt(text: str, source: str, target: str) -> str:
|
||||
terms = glossary(text, source, target)
|
||||
block = ""
|
||||
if terms:
|
||||
block = ("Glossaire — pour ces termes de jeu, emploie EXACTEMENT la traduction indiquée :\n"
|
||||
+ "\n".join(f"- {term} → {translation}" for term, translation in terms) + "\n\n")
|
||||
return (
|
||||
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
||||
f"vers la langue « {language_name(target)} ».\n\n"
|
||||
@@ -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"
|
||||
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||
"objets nommés.\n"
|
||||
"- Garde TELS QUELS les nombres, les dés (2d6 + 3) et les unités : ne convertis rien.\n"
|
||||
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
|
||||
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||
f"{block}"
|
||||
"Extrait :\n"
|
||||
f"{text}"
|
||||
)
|
||||
@@ -98,16 +191,18 @@ class RulesTranslator:
|
||||
|
||||
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."""
|
||||
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] = {}
|
||||
for title in titles:
|
||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||
# Par lots : un livre découpé par sa structure a des centaines de titres, trop pour
|
||||
# une seule réponse JSON d'un petit modèle.
|
||||
for start in range(0, len(titles), TITLES_PER_CALL):
|
||||
batch = titles[start:start + TITLES_PER_CALL]
|
||||
raw = await generate_with_retry(self._llm, titles_prompt(batch, source, target),
|
||||
output_format="json", temperature=0.2)
|
||||
parsed, _ = load_json_object(raw)
|
||||
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||
for title in batch:
|
||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||
return out
|
||||
|
||||
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
|
||||
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class TranslatedRules:
|
||||
"""Règles dans la langue cible, dans l'ordre du livre.
|
||||
|
||||
`untranslated` liste les titres (d'origine) des sections qui n'ont pas pu être traduites :
|
||||
elles figurent dans `sections` avec leur titre et leur texte d'origine, pour que la
|
||||
version traduite reste complète.
|
||||
"""
|
||||
|
||||
sections: dict[str, str]
|
||||
untranslated: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _free_key(key: str, taken: dict[str, str]) -> str:
|
||||
"""`key`, ou `key (2)`, `key (3)`… si une section porte déjà ce titre."""
|
||||
if key not in taken:
|
||||
return key
|
||||
n = 2
|
||||
while f"{key} ({n})" in taken:
|
||||
n += 1
|
||||
return f"{key} ({n})"
|
||||
|
||||
|
||||
async def translate_sections(
|
||||
translator: RulesTranslator,
|
||||
sections: dict[str, str],
|
||||
source: str,
|
||||
target: str,
|
||||
*,
|
||||
concurrency: int = DEFAULT_CONCURRENCY,
|
||||
budget_seconds: float = BUDGET_SECONDS,
|
||||
heartbeat_seconds: float = HEARTBEAT_INTERVAL_SECONDS,
|
||||
with_titles: bool = True,
|
||||
labels: dict[str, str] | None = None,
|
||||
) -> AsyncIterator[tuple[str, Any]]:
|
||||
"""Traduit des sections {titre: markdown} et rend compte de l'avancement.
|
||||
|
||||
`with_titles=False` : les clés ne sont pas des titres à traduire mais de simples repères
|
||||
(scènes d'une campagne, dont les noms restent ceux du livre) ; `labels` donne alors le
|
||||
libellé de chacune pour les messages d'avancement.
|
||||
|
||||
Émet ('status', message) à chaque section terminée, ('heartbeat', None) tant que rien ne
|
||||
se termine, puis ('result', TranslatedRules).
|
||||
|
||||
- Les sections sont traduites `concurrency` à la fois.
|
||||
- Une section en échec garde son titre et son texte d'origine ; au bout de
|
||||
MAX_FAILED_SECTIONS échecs on n'en lance plus de nouvelles.
|
||||
- Passé `budget_seconds`, les traductions en cours sont abandonnées de la même façon.
|
||||
|
||||
Lève LLMProviderError si les titres ne peuvent pas être traduits (premier appel : le
|
||||
fournisseur ne répond pas) ou si aucune section n'a pu l'être.
|
||||
"""
|
||||
titles = list(sections)
|
||||
if not titles:
|
||||
yield ("result", TranslatedRules({}))
|
||||
return
|
||||
total = len(titles)
|
||||
label = language_name(target)
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
deadline = started + budget_seconds
|
||||
logger.info("Traduction des règles (%s → %s) : %s section(s), %s à la fois.",
|
||||
source, target, total, max(1, concurrency))
|
||||
|
||||
mapping: dict[str, str] = {}
|
||||
if with_titles:
|
||||
yield ("status", f"Traduction ({label}) des titres…")
|
||||
async for kind, payload in with_heartbeat(
|
||||
translator.translate_titles(titles, source, target), interval=heartbeat_seconds):
|
||||
if kind == "heartbeat":
|
||||
yield ("heartbeat", None)
|
||||
elif kind == "result":
|
||||
mapping = unique_titles(payload)
|
||||
|
||||
semaphore = asyncio.Semaphore(max(1, concurrency))
|
||||
failures: list[str] = []
|
||||
|
||||
async def translate_one(title: str) -> tuple[str, str | None]:
|
||||
async with semaphore:
|
||||
if len(failures) >= MAX_FAILED_SECTIONS:
|
||||
return title, None
|
||||
try:
|
||||
return title, await translator.translate_content(sections[title], source, target)
|
||||
except LLMProviderError as exc:
|
||||
failures.append(str(exc))
|
||||
logger.warning("Traduction (%s) de la section « %s » impossible : %s", target, title, exc)
|
||||
return title, None
|
||||
|
||||
tasks = [asyncio.ensure_future(translate_one(title)) for title in titles]
|
||||
translated: dict[str, str] = {}
|
||||
finished = 0
|
||||
out_of_time = False
|
||||
try:
|
||||
pending: set[asyncio.Future] = set(tasks)
|
||||
while pending:
|
||||
remaining = deadline - loop.time()
|
||||
if remaining <= 0:
|
||||
out_of_time = True
|
||||
break
|
||||
done, pending = await asyncio.wait(
|
||||
pending, timeout=min(heartbeat_seconds, remaining), return_when=asyncio.FIRST_COMPLETED)
|
||||
if not done:
|
||||
yield ("heartbeat", None)
|
||||
continue
|
||||
last = ""
|
||||
for task in done:
|
||||
title, text = task.result()
|
||||
finished += 1
|
||||
last = title
|
||||
# Une réponse vide pour un texte non vide n'est pas une traduction.
|
||||
if text is not None and (text.strip() or not sections[title].strip()):
|
||||
translated[title] = text
|
||||
yield ("status", f"Traduction ({label}) : {finished}/{total} — {(labels or {}).get(last, last)}")
|
||||
finally:
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
# Laisse les traductions abandonnées se défaire (appels au fournisseur refermés).
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
untranslated = [title for title in titles if title not in translated]
|
||||
elapsed = int(loop.time() - started)
|
||||
if not translated:
|
||||
if out_of_time:
|
||||
reason = "temps imparti dépassé"
|
||||
else:
|
||||
reason = failures[-1] if failures else "aucune réponse exploitable"
|
||||
raise LLMProviderError(f"aucune section n'a pu être traduite ({reason})")
|
||||
|
||||
out: dict[str, str] = {}
|
||||
for title in titles:
|
||||
if title in translated:
|
||||
out[_free_key(mapping.get(title, title), out)] = translated[title]
|
||||
else:
|
||||
out[_free_key(title, out)] = sections[title]
|
||||
logger.info("Traduction des règles (%s → %s) terminée en %ss : %s section(s) traduite(s), %s non traduite(s)%s.",
|
||||
source, target, elapsed, len(translated), len(untranslated),
|
||||
" (temps imparti dépassé)" if out_of_time else "")
|
||||
yield ("result", TranslatedRules(out, untranslated))
|
||||
|
||||
@@ -0,0 +1,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
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TextLine:
|
||||
"""Une ligne de texte du PDF, dans l'ordre de lecture, avec ce que la mise en page en dit.
|
||||
|
||||
`block` : rang du bloc de texte dans sa page (un bloc ≈ un paragraphe). `size` : taille de
|
||||
caractères dominante de la ligne, en points ; 0 quand elle est inconnue (page passée à
|
||||
l'OCR). C'est la taille qui distingue un titre du corps du texte, sans IA.
|
||||
`edge` : la ligne est tout en haut ou tout en bas de sa page (en-tête, pied, numéro de
|
||||
page). `cells` : nombre de cellules d'une rangée de tableau réunies dans cette ligne,
|
||||
séparées par « | » (1 = ligne ordinaire).
|
||||
"""
|
||||
|
||||
page: int # 0-based
|
||||
block: int
|
||||
text: str
|
||||
size: float
|
||||
edge: bool = False
|
||||
cells: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedDocument:
|
||||
"""Résultat brut de l'extraction d'un PDF : une entrée par page."""
|
||||
@@ -340,6 +360,9 @@ class ExtractedDocument:
|
||||
# Table des matières (bookmarks PDF). Vide si le PDF n'en a pas — fréquent
|
||||
# pour les scans ; les livres born-digital en ont presque toujours une.
|
||||
toc: list[TocEntry] = field(default_factory=list)
|
||||
# Lignes du livre avec leur taille de caractères (cf. TextLine). Vide quand l'extracteur
|
||||
# ne les fournit pas : le découpage par la structure du PDF est alors impossible.
|
||||
lines: list[TextLine] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
|
||||
@@ -16,6 +16,10 @@ from app.domain.ports import LLMGenerationTimeout, LLMProviderError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Modèles dont Ollama a refusé le paramètre `think` (modèle sans mode « réflexion » sur une
|
||||
# version d'Ollama qui le signale par une erreur) : on ne le leur renvoie plus.
|
||||
_THINK_PARAM_REFUSED: set[str] = set()
|
||||
|
||||
|
||||
class OllamaLLMProvider:
|
||||
"""Implémentation des ports LLM — appelle un serveur Ollama via HTTP.
|
||||
@@ -64,20 +68,40 @@ class OllamaLLMProvider:
|
||||
# clés "thought" bavardes ou de texte hors JSON.
|
||||
if output_format is not None:
|
||||
payload["format"] = output_format
|
||||
# Réflexion COUPÉE pour ces appels uniques (relevés, découpages, traductions). Un
|
||||
# modèle à « réflexion » (qwen3.x…) rend sinon une réponse VIDE dès qu'un format
|
||||
# JSON est imposé — l'import concluait « aucune section exploitable » — et met plus
|
||||
# de deux fois plus de temps sur le reste (mesuré le 2026-11-13).
|
||||
if self._model not in _THINK_PARAM_REFUSED:
|
||||
payload["think"] = False
|
||||
|
||||
response = await self._post_generate(url, payload)
|
||||
if response.status_code == 400 and "think" in payload and "think" in response.text.lower():
|
||||
# Ce modèle n'a pas de mode « réflexion » et cette version d'Ollama refuse le
|
||||
# paramètre : on réessaie sans lui, et on s'en souvient.
|
||||
_THINK_PARAM_REFUSED.add(self._model)
|
||||
payload.pop("think")
|
||||
response = await self._post_generate(url, payload)
|
||||
if response.status_code >= 400:
|
||||
body = response.text
|
||||
try:
|
||||
err_obj = json.loads(body)
|
||||
err_msg = err_obj.get("error") or body
|
||||
except json.JSONDecodeError:
|
||||
err_msg = body
|
||||
raise LLMProviderError(
|
||||
f"Ollama HTTP {response.status_code} : {err_msg.strip()[:500]}"
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
return self._checked_response(data)
|
||||
|
||||
async def _post_generate(self, url: str, payload: dict[str, object]) -> httpx.Response:
|
||||
"""Envoie l'appel et rend la réponse HTTP telle quelle ; les pannes de transport
|
||||
deviennent des erreurs du domaine."""
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
response = await client.post(url, json=payload)
|
||||
if response.status_code >= 400:
|
||||
body = response.text
|
||||
try:
|
||||
err_obj = json.loads(body)
|
||||
err_msg = err_obj.get("error") or body
|
||||
except json.JSONDecodeError:
|
||||
err_msg = body
|
||||
raise LLMProviderError(
|
||||
f"Ollama HTTP {response.status_code} : {err_msg.strip()[:500]}"
|
||||
)
|
||||
return await client.post(url, json=payload)
|
||||
except httpx.ConnectTimeout as exc:
|
||||
# Serveur injoignable : erreur d'infrastructure, pas de lenteur.
|
||||
raise LLMProviderError(
|
||||
@@ -99,7 +123,8 @@ class OllamaLLMProvider:
|
||||
f"Erreur lors de l'appel à Ollama : {exc}"
|
||||
) from exc
|
||||
|
||||
data = response.json()
|
||||
def _checked_response(self, data: dict) -> str:
|
||||
"""Texte de la réponse, après le diagnostic d'une génération interrompue."""
|
||||
# Diagnostic crucial pour les imports : `done_reason` != "stop" signifie que
|
||||
# la génération a été INTERROMPUE (fenêtre de contexte pleine, num_predict…)
|
||||
# et non terminée par le modèle. Sans ce log, on ne voit qu'un JSON coupé
|
||||
|
||||
@@ -17,13 +17,15 @@ et le diagnostic le signale (used_ocr reste False, texte vide).
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
import pymupdf as fitz # PyMuPDF — on importe par le nom canonique `pymupdf`
|
||||
# (et NON `import fitz`) pour éviter la collision avec le faux paquet PyPI "fitz"
|
||||
# qui échoue sur `from frontend import *`.
|
||||
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage, TocEntry
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage, TextLine, TocEntry
|
||||
from app.domain.ports import PdfExtractionError
|
||||
from app.infrastructure.pdf_layout import CELL_SEPARATOR, LayoutBlock, LayoutLine, place_lines, split_cells
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -41,6 +43,15 @@ _OCR_DPI = 300
|
||||
_OCR_LANGS = "fra+eng"
|
||||
|
||||
|
||||
# Caractères de contrôle laissés par certaines mises en page (tabulations, retours arrière…).
|
||||
_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]+")
|
||||
|
||||
|
||||
def _clean(text: str) -> str:
|
||||
"""Texte d'une ligne sans caractères de contrôle ni espaces en trop."""
|
||||
return " ".join(_CONTROL_CHARS.sub(" ", text).split())
|
||||
|
||||
|
||||
class PyMuPdfTextExtractor:
|
||||
"""Extracteur PDF basé sur PyMuPDF, avec repli OCR Tesseract optionnel."""
|
||||
|
||||
@@ -73,6 +84,7 @@ class PyMuPdfTextExtractor:
|
||||
|
||||
pages: list[ExtractedPage] = []
|
||||
toc: list[TocEntry] = []
|
||||
lines: list[TextLine] = []
|
||||
try:
|
||||
# Bookmarks/outline du PDF : structure officielle du livre, gratuite
|
||||
# (pas d'appel LLM). Sert de squelette de référence aux imports.
|
||||
@@ -93,10 +105,61 @@ class PyMuPdfTextExtractor:
|
||||
text = ocr_text.strip()
|
||||
used_ocr = True
|
||||
pages.append(ExtractedPage(index=index, text=text, used_ocr=used_ocr))
|
||||
lines.extend(self._ocr_lines(index, text) if used_ocr else self._page_lines(index, page))
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
return ExtractedDocument(pages=pages, toc=toc)
|
||||
return ExtractedDocument(pages=pages, toc=toc, lines=lines)
|
||||
|
||||
@staticmethod
|
||||
def _page_lines(index: int, page: "fitz.Page") -> list[TextLine]:
|
||||
"""Lignes d'une page à couche texte, avec leur taille de caractères dominante.
|
||||
|
||||
Best-effort : une page dont la mise en page ne se lit pas ne rend aucune ligne,
|
||||
sans faire échouer l'extraction."""
|
||||
out: list[TextLine] = []
|
||||
try:
|
||||
blocks = page.get_text("dict").get("blocks", [])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Lecture de la mise en page impossible (page %s) : %s", index + 1, exc)
|
||||
return out
|
||||
layout: list[LayoutBlock] = []
|
||||
for block in blocks:
|
||||
lines: list[LayoutLine] = []
|
||||
for line in block.get("lines", []):
|
||||
spans = [s for s in line.get("spans", []) if _clean(str(s.get("text", "")))]
|
||||
if not spans:
|
||||
continue
|
||||
dominant = max(spans, key=lambda s: len(s["text"]))
|
||||
# Arrondi au demi-point : deux lignes d'un même style ont la même taille.
|
||||
size = round(float(dominant.get("size", 0)) * 2) / 2
|
||||
x0, y0, x1, y1 = line.get("bbox", block.get("bbox", (0, 0, 0, 0)))
|
||||
# Un grand blanc dans la ligne sépare deux cellules d'un tableau.
|
||||
cells = split_cells(
|
||||
[(s["bbox"][0], s["bbox"][2], _CONTROL_CHARS.sub(" ", str(s.get("text", ""))).replace("|", "/"))
|
||||
for s in line["spans"] if "bbox" in s], size)
|
||||
if not cells:
|
||||
continue
|
||||
lines.append(LayoutLine(x0, y0, x1, y1, CELL_SEPARATOR.join(cells), size, len(cells)))
|
||||
if lines:
|
||||
bx0, by0, bx1, by1 = block.get("bbox", (0, 0, 0, 0))
|
||||
layout.append(LayoutBlock(bx0, by0, bx1, by1, lines))
|
||||
# Ordre de lecture par colonnes et rangées de tableau réunies : cf. pdf_layout.
|
||||
for placed in place_lines(layout, float(page.rect.width), float(page.rect.height)):
|
||||
out.append(TextLine(index, placed.block, placed.text, placed.size, placed.edge, placed.cells))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _ocr_lines(index: int, text: str) -> list[TextLine]:
|
||||
"""Lignes d'une page passée à l'OCR : taille inconnue (0), un bloc par paragraphe."""
|
||||
out: list[TextLine] = []
|
||||
block_no = 0
|
||||
for raw in text.split("\n"):
|
||||
if not raw.strip():
|
||||
block_no += 1
|
||||
continue
|
||||
out.append(TextLine(index, block_no, raw.strip(), 0.0))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _ocr_page(page: "fitz.Page") -> str:
|
||||
|
||||
@@ -0,0 +1,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)
|
||||
|
||||
|
||||
async def test_rules_stream_hands_over_the_extraction_before_translating(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_doc())).stream(b"pdf")]
|
||||
types = [e["type"] for e in events]
|
||||
extracted = events[types.index("extracted")]
|
||||
assert extracted["sections"] == {"Magie": "sorts"}
|
||||
assert extracted["source_language"] == "fr"
|
||||
assert extracted["page_count"] == 1
|
||||
# L'extraction part avant le premier message de traduction.
|
||||
first_translation = next(i for i, e in enumerate(events)
|
||||
if e["type"] == "status" and "Traduction" in e["message"])
|
||||
assert types.index("extracted") < first_translation
|
||||
assert events[-1]["untranslated"] == []
|
||||
|
||||
|
||||
async def test_rules_stream_reports_the_sections_left_untranslated(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic", "Combat": "Fighting"}}'),
|
||||
("Extrait :\nles sorts", LLMProviderError("HTTP 503 saturé")),
|
||||
("Extrait :\nles coups", "blows"),
|
||||
("BBB second", '{"Magie":"les sorts","Combat":"les coups"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_doc())).stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["untranslated"] == ["Magie"]
|
||||
assert done["sections_by_language"]["en"] == {"Magie": "les sorts", "Fighting": "blows"}
|
||||
assert any(e["type"] == "status" and "incomplète" in e["message"] for e in events)
|
||||
|
||||
|
||||
def test_rules_translation_runs_one_at_a_time_on_a_local_model():
|
||||
local = ImportRulesUseCase(ScriptedLLM(["{}"]), FakeExtractor(_doc()), segment_only=True)
|
||||
remote = ImportRulesUseCase(ScriptedLLM(["{}"]), FakeExtractor(_doc()))
|
||||
assert local._translation_concurrency == 1
|
||||
assert remote._translation_concurrency > 1
|
||||
|
||||
|
||||
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||
llm = ScriptedLLM([LLMProviderError("HTTP 500 panne")])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()))
|
||||
@@ -207,3 +250,578 @@ async def test_campaign_import_defaults_to_french():
|
||||
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||
assert "en français" in llm.prompts[0]
|
||||
assert '"Aventure principale"' in llm.prompts[0]
|
||||
|
||||
|
||||
# --- mode segmentation (modèle local) : le texte n'est jamais perdu -------------------------
|
||||
|
||||
def _anchors(*pairs) -> str:
|
||||
import json as _json
|
||||
return _json.dumps({"sections": [{"titre": t, "debut": d} for t, d in pairs]})
|
||||
|
||||
|
||||
async def test_local_import_keeps_the_text_of_a_chunk_the_model_could_not_split(monkeypatch, no_sleep):
|
||||
"""Un petit modèle rend parfois des repères introuvables : 1 morceau sur 15 disparaissait."""
|
||||
chunks = ["AAA le combat se joue en tours.", "BBB suite du combat, sans repère.", "CCC la magie coûte du mana."]
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: chunks)
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA le combat", _anchors(("Combat", "AAA le combat"))),
|
||||
("BBB suite", _anchors(("Combat", "un début qui n'est pas dans le texte"))),
|
||||
("CCC la magie", _anchors(("Magie", "CCC la magie"))),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
# Le morceau sans repère suit la section précédente : rien n'est perdu.
|
||||
assert extracted["sections"] == {
|
||||
"Combat": "AAA le combat se joue en tours.\n\nBBB suite du combat, sans repère.",
|
||||
"Magie": "CCC la magie coûte du mana.",
|
||||
}
|
||||
assert sum(len(c) for c in extracted["sections"].values()) >= sum(len(c) for c in chunks)
|
||||
assert any(e["type"] == "status" and "gardé" in e["message"] for e in events)
|
||||
assert extracted["skipped"] == 0
|
||||
|
||||
|
||||
async def test_local_import_puts_an_unsplit_first_chunk_under_the_general_rules(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA préambule illisible pour le modèle.", "BBB le combat."])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA préambule", "je ne sais pas"), # pas de JSON du tout
|
||||
("BBB le combat", _anchors(("Combat", "BBB le combat"))),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
result = await uc.execute(b"pdf")
|
||||
assert result.sections == {"Règles générales": "AAA préambule illisible pour le modèle.",
|
||||
"Combat": "BBB le combat."}
|
||||
|
||||
|
||||
async def test_local_import_keeps_the_text_of_a_chunk_whose_call_failed(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA le combat.", "BBB la suite."])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA le combat", _anchors(("Combat", "AAA le combat"))),
|
||||
("BBB la suite", LLMProviderError("Ollama HTTP 500 : prediction aborted")),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["sections"] == {"Combat": "AAA le combat.\n\nBBB la suite."}
|
||||
# L'échec reste signalé : le MJ sait qu'un morceau n'a pas été découpé.
|
||||
assert any(e["type"] == "chunk_failed" for e in events)
|
||||
assert extracted["skipped"] == 1
|
||||
|
||||
|
||||
async def test_local_import_still_fails_when_every_call_fails(one_chunk, no_sleep):
|
||||
llm = ScriptedLLM([LLMProviderError("Ollama injoignable")])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
assert events[-1]["type"] == "error"
|
||||
assert all(e["type"] != "extracted" for e in events)
|
||||
|
||||
|
||||
async def test_cloud_import_does_not_keep_the_raw_text_of_a_failed_chunk(monkeypatch, no_sleep):
|
||||
"""Hors segmentation, le texte brut du PDF n'est pas une section : comportement inchangé."""
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_doc())).stream(b"pdf")]
|
||||
assert next(e for e in events if e["type"] == "extracted")["sections"] == {"Magie": "sorts"}
|
||||
|
||||
|
||||
def test_combining_the_two_halves_keeps_unsplit_text_after_what_precedes_it():
|
||||
from app.application.import_rules import UNSORTED, _combine_sections, _SectionMerger
|
||||
combined = _combine_sections({"Combat": "a"}, {UNSORTED: "b", "Magie": "c"})
|
||||
assert combined == {"Combat": "a\n\nb", "Magie": "c"}
|
||||
merger = _SectionMerger()
|
||||
merger.add({"Combat": "a"})
|
||||
assert merger.add({UNSORTED: "suite"}) == ["Combat"]
|
||||
assert merger.result() == {"Combat": "a\n\nsuite"}
|
||||
|
||||
|
||||
# --- découpage par la structure du PDF, sans IA ---------------------------------------------
|
||||
|
||||
def _structured_doc():
|
||||
"""Livre de 3 pages : signets et gros titres, comme un PDF d'éditeur."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
lines, toc = [], []
|
||||
for page, (title, text) in enumerate([("Combat", "Each round, you roll the dice and the heroes act."),
|
||||
("Magic", "Casting a spell costs mana for the caster."),
|
||||
("Rest", "A night of rest restores all the wounds.")]):
|
||||
lines += [TextLine(page, 0, title, 24.0), TextLine(page, 1, text, 10.0)]
|
||||
toc.append(TocEntry(level=1, title=title, page=page + 1))
|
||||
pages = [ExtractedPage(index=p, text=f"{lines[2 * p].text}\n{lines[2 * p + 1].text}", used_ocr=False)
|
||||
for p in range(3)]
|
||||
return ExtractedDocument(pages=pages, toc=toc, lines=lines)
|
||||
|
||||
|
||||
class CountingLLM(ContentLLM):
|
||||
def __init__(self, rules: list) -> None:
|
||||
super().__init__(rules)
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
return await super().generate(prompt, output_format=output_format, temperature=temperature)
|
||||
|
||||
|
||||
async def test_local_import_follows_the_structure_of_the_pdf_without_the_ai(no_sleep):
|
||||
llm = CountingLLM([("Traduis ces titres", LLMProviderError("pas de traduction dans ce test"))])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_structured_doc()), segment_only=True, structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["split_method"] == "bookmarks"
|
||||
assert extracted["sections"] == {
|
||||
"Combat": "Each round, you roll the dice and the heroes act.",
|
||||
"Magic": "Casting a spell costs mana for the caster.",
|
||||
"Rest": "A night of rest restores all the wounds.",
|
||||
}
|
||||
assert extracted["source_language"] == "en"
|
||||
# Aucun appel à l'IA pour découper : le seul prompt envoyé est celui de la traduction.
|
||||
assert all("Traduis" in prompt for prompt in llm.prompts)
|
||||
assert any(e["type"] == "status" and "table des matières du PDF" in e["message"]
|
||||
and "sans IA" in e["message"] for e in events)
|
||||
progress = next(e for e in events if e["type"] == "progress")
|
||||
assert progress["new_sections"] == ["Combat", "Magic", "Rest"]
|
||||
assert events[-1]["type"] == "done" and events[-1]["split_method"] == "bookmarks"
|
||||
|
||||
|
||||
async def test_local_import_falls_back_on_the_ai_when_the_pdf_has_no_structure(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["AAA le combat."])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("AAA le combat", _anchors(("Combat", "AAA le combat"))),
|
||||
])
|
||||
# Document sans lignes ni signets (scan, ou extracteur qui ne les fournit pas).
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc()), segment_only=True, structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["split_method"] == "ai"
|
||||
assert extracted["sections"] == {"Combat": "AAA le combat."}
|
||||
|
||||
|
||||
async def test_cloud_import_does_not_use_the_structure_unless_asked(one_chunk, no_sleep):
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("pas de traduction dans ce test")),
|
||||
("chunk", '{"Combat":"réécrit par le modèle"}'),
|
||||
])
|
||||
events = [e async for e in ImportRulesUseCase(llm, FakeExtractor(_structured_doc())).stream(b"pdf")]
|
||||
extracted = next(e for e in events if e["type"] == "extracted")
|
||||
assert extracted["split_method"] == "ai"
|
||||
assert extracted["sections"] == {"Combat": "réécrit par le modèle"}
|
||||
|
||||
|
||||
async def test_execute_follows_the_structure_too(no_sleep):
|
||||
llm = ContentLLM([("Traduis ces titres", LLMProviderError("pas de traduction dans ce test"))])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_structured_doc()), segment_only=True, structure_first=True)
|
||||
result = await uc.execute(b"pdf")
|
||||
assert list(result.sections) == ["Combat", "Magic", "Rest"]
|
||||
|
||||
|
||||
async def test_local_import_by_structure_survives_a_slow_translation(no_sleep):
|
||||
"""Un signal de vie émis pendant la traduction faisait planter le chemin sans IA."""
|
||||
import asyncio
|
||||
|
||||
class SlowTitles:
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
if "Traduis ces titres" in prompt:
|
||||
await asyncio.Event().wait() # ne répond jamais : seuls des signaux de vie partent
|
||||
return "traduit"
|
||||
|
||||
uc = ImportRulesUseCase(SlowTitles(), FakeExtractor(_structured_doc()), segment_only=True, structure_first=True)
|
||||
uc._heartbeat_seconds = 0.01
|
||||
seen: list[str] = []
|
||||
stream = uc.stream(b"pdf")
|
||||
async for event in stream:
|
||||
seen.append(event["type"])
|
||||
if seen.count("heartbeat") >= 2:
|
||||
break
|
||||
await stream.aclose()
|
||||
assert "extracted" in seen and seen.count("heartbeat") >= 2
|
||||
|
||||
|
||||
def test_no_provider_ever_rewrites_the_text_of_the_book():
|
||||
"""Les règles doivent correspondre au PDF : structure d'abord, sinon l'IA ne fait que
|
||||
repérer les frontières — en local comme avec un fournisseur cloud."""
|
||||
from app.api.deps import get_import_rules_use_case
|
||||
from app.core.config import Settings
|
||||
|
||||
for provider in ("ollama", "mistral", "gemini", "openrouter"):
|
||||
settings = Settings(_env_file=None, llm_provider=provider)
|
||||
uc = get_import_rules_use_case(ScriptedLLM(["{}"]), settings)
|
||||
assert uc._structure_first is True
|
||||
assert uc._segment_only is True
|
||||
|
||||
|
||||
|
||||
# --- import de campagne par la structure du livre ---------------------------------------------
|
||||
|
||||
def _campaign_doc(language: str = "fr"):
|
||||
"""Petit livre de campagne : 2 aventures, 3 scènes, signets et gros titres."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
if language == "fr":
|
||||
book = [("L'aventure", [("La foire", "Le marchand Aldric vend des reliques volées dans la foire du village. " * 4),
|
||||
("La crypte", "Sous l'autel, la crypte abrite le spectre de Dame Ysolde et ses gardes. " * 4)]),
|
||||
("Épilogue", [("Le retour", "Les héros rentrent au village avec la relique et le maire les récompense. " * 4)])]
|
||||
else:
|
||||
book = [("The Adventure", [("The Fair", "The merchant Aldric sells stolen relics at the fair of the village for you. " * 4),
|
||||
("The Crypt", "Under the altar, the crypt is the home of the ghost of Lady Ysolde and of the guards. " * 4)]),
|
||||
("Epilogue", [("The Return", "The heroes are back in the village with the relic and the mayor rewards you. " * 4)])]
|
||||
lines, toc, pages = [], [], []
|
||||
for page, (chapter, scenes) in enumerate(book):
|
||||
toc.append(TocEntry(level=1, title=chapter, page=page + 1))
|
||||
lines.append(TextLine(page, 0, chapter, 24.0))
|
||||
for block, (title, text) in enumerate(scenes, start=1):
|
||||
toc.append(TocEntry(level=2, title=title, page=page + 1))
|
||||
lines += [TextLine(page, 2 * block, title, 16.0), TextLine(page, 2 * block + 1, text.strip(), 10.0)]
|
||||
pages.append(ExtractedPage(index=page, text="texte", used_ocr=False))
|
||||
return ExtractedDocument(pages=pages, toc=toc, lines=lines)
|
||||
|
||||
|
||||
class AidsLLM:
|
||||
"""Répond aux demandes d'aides et de traduction ; garde les prompts reçus."""
|
||||
|
||||
def __init__(self, aids: object, translate=str.upper) -> None:
|
||||
self._aids = aids
|
||||
self._translate = translate
|
||||
self.prompts: list[str] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
self.prompts.append(prompt)
|
||||
if "SYNOPSIS" in prompt:
|
||||
if isinstance(self._aids, Exception):
|
||||
raise self._aids
|
||||
return self._aids
|
||||
if "Traduis cet extrait" in prompt:
|
||||
if self._translate is None:
|
||||
raise LLMProviderError("HTTP 503 saturé")
|
||||
return self._translate(prompt.split("Extrait :\n", 1)[1])
|
||||
raise AssertionError(f"prompt inattendu : {prompt[:60]!r}")
|
||||
|
||||
|
||||
_AIDS = ('{"scenes": [{"n": 1, "synopsis": "Aldric écoule des reliques volées."}, {"n": 2, "synopsis": ""},'
|
||||
' {"n": 3, "synopsis": "Retour au village."}, {"n": 9, "synopsis": "hors lot"}],'
|
||||
' "npcs": [{"name": "Aldric", "description": "Marchand receleur."},'
|
||||
' {"name": "Gandalf", "description": "Absent du livre."}, {"name": "Dame Ysolde"}]}')
|
||||
_NO_AIDS = '{"scenes": [], "npcs": []}'
|
||||
|
||||
|
||||
async def test_campaign_import_keeps_the_text_of_the_book_and_adds_only_aids(no_sleep):
|
||||
llm = AidsLLM(_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and done["split_method"] == "bookmarks"
|
||||
chapters = done["arcs"][0]["chapters"]
|
||||
assert [(c["name"], [s["name"] for s in c["scenes"]]) for c in chapters] == [
|
||||
("L'aventure", ["La foire", "La crypte"]), ("Épilogue", ["Le retour"])]
|
||||
fair, crypt = chapters[0]["scenes"]
|
||||
# Le texte de la scène est celui du livre, mot pour mot.
|
||||
assert fair["gm_notes"] == ("Le marchand Aldric vend des reliques volées dans la foire du village. " * 4).strip()
|
||||
# Le synopsis vient de l'IA ; une scène sans synopsis garde le début de son texte.
|
||||
assert fair["description"] == "Aldric écoule des reliques volées."
|
||||
assert crypt["description"].startswith("Sous l'autel, la crypte abrite le spectre")
|
||||
# PNJ : seuls ceux dont le nom figure dans le texte sont gardés.
|
||||
assert done["npcs"] == [{"name": "Aldric", "description": "Marchand receleur."},
|
||||
{"name": "Dame Ysolde", "description": ""}]
|
||||
# Livre déjà dans la langue de l'interface : aucune traduction.
|
||||
assert done["source_language"] == "fr" and done["untranslated"] == 0
|
||||
assert all("Traduis" not in p for p in llm.prompts)
|
||||
assert any(e["type"] == "status" and "sans IA" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_campaign_import_hands_over_the_tree_before_the_ai_passes(no_sleep):
|
||||
uc = ImportCampaignUseCase(AidsLLM(_AIDS), FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
types = [e["type"] for e in events]
|
||||
extracted = events[types.index("extracted")]
|
||||
assert len(extracted["arcs"][0]["chapters"]) == 2 and extracted["npcs"] == []
|
||||
assert types.index("extracted") < types.index("done")
|
||||
progress = [e for e in events if e["type"] == "progress"]
|
||||
assert (progress[0]["current"], progress[0]["scene_count"], progress[-1]["npc_count"]) == (0, 3, 2)
|
||||
|
||||
|
||||
async def test_campaign_import_survives_a_failure_of_the_aids(no_sleep):
|
||||
uc = ImportCampaignUseCase(AidsLLM(LLMProviderError("HTTP 503 saturé")), FakeExtractor(_campaign_doc()),
|
||||
structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and done["skipped"] == 1 and done["npcs"] == []
|
||||
assert any(e["type"] == "chunk_failed" for e in events)
|
||||
# Sans aides, le synopsis est le début du texte : la campagne est entière.
|
||||
scene = done["arcs"][0]["chapters"][0]["scenes"][0]
|
||||
assert scene["description"].startswith("Le marchand Aldric vend des reliques volées")
|
||||
assert scene["gm_notes"]
|
||||
|
||||
|
||||
async def test_campaign_import_translates_a_book_in_another_language(no_sleep):
|
||||
llm = AidsLLM(_NO_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc("en")), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["source_language"] == "en" and done["untranslated"] == 0
|
||||
chapters = done["arcs"][0]["chapters"]
|
||||
# Les noms restent ceux du livre ; le texte de chaque scène est traduit en entier.
|
||||
assert [s["name"] for s in chapters[0]["scenes"]] == ["The Fair", "The Crypt"]
|
||||
assert chapters[0]["scenes"][0]["gm_notes"].startswith("THE MERCHANT ALDRIC SELLS STOLEN RELICS")
|
||||
assert any(e["type"] == "status" and e["message"].startswith("Traduction (français) : 3/3") for e in events)
|
||||
assert sum(1 for p in llm.prompts if "Traduis cet extrait" in p) == 3
|
||||
assert all("Traduis ces titres" not in p for p in llm.prompts)
|
||||
|
||||
|
||||
async def test_campaign_import_keeps_the_book_text_when_the_translation_fails(no_sleep):
|
||||
llm = AidsLLM(_NO_AIDS, translate=None)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc("en")), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and done["untranslated"] == 3
|
||||
assert done["arcs"][0]["chapters"][0]["scenes"][0]["gm_notes"].startswith("The merchant Aldric sells")
|
||||
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_campaign_translation_stops_when_its_time_is_up(no_sleep):
|
||||
llm = AidsLLM(_NO_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc("en")), structure_first=True)
|
||||
assert uc._translation_budget_seconds == 3 * 60 * 60
|
||||
uc._translation_budget_seconds = 0
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
done = events[-1]
|
||||
# Rien n'a pu être traduit dans le temps imparti : la campagne garde le texte du livre.
|
||||
assert done["type"] == "done" and done["untranslated"] == 3
|
||||
assert done["arcs"][0]["chapters"][0]["scenes"][0]["gm_notes"].startswith("The merchant Aldric sells")
|
||||
|
||||
|
||||
async def test_campaign_import_stops_the_aids_when_time_is_up(no_sleep):
|
||||
llm = AidsLLM(_AIDS)
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
uc._aids_budget_seconds = 0
|
||||
events = [e async for e in uc.stream(b"pdf", language="fr")]
|
||||
assert events[-1]["type"] == "done" and llm.prompts == []
|
||||
assert any(e["type"] == "status" and "Temps imparti" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_campaign_import_falls_back_on_the_ai_without_structure(one_chunk, no_sleep):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([_TREE]), FakeExtractor(_doc()), structure_first=True)
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done" and "split_method" not in done
|
||||
assert done["arcs"][0]["name"] == "Acte I"
|
||||
|
||||
|
||||
async def test_campaign_execute_follows_the_structure_too(no_sleep):
|
||||
uc = ImportCampaignUseCase(AidsLLM(_AIDS), FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
result = await uc.execute(b"pdf", language="fr")
|
||||
assert [c.name for c in result.arcs[0].chapters] == ["L'aventure", "Épilogue"]
|
||||
assert result.arcs[0].chapters[0].scenes[0].description == "Aldric écoule des reliques volées."
|
||||
assert [n.name for n in result.npcs] == ["Aldric", "Dame Ysolde"]
|
||||
|
||||
|
||||
def test_campaign_npcs_are_named_characters_listed_once():
|
||||
from app.application.import_campaign import _apply_aids
|
||||
|
||||
scene = {"name": "Le temple", "gm_notes": "Arumvel the Wicked attend avec un ogre. Jylagura veille.", "rooms": []}
|
||||
npcs: dict[str, dict] = {}
|
||||
_apply_aids([(0, scene)], {"scenes": [], "npcs": [
|
||||
{"name": "Arumvel", "description": "Un acolyte possédé par le démon."},
|
||||
{"name": "ogre", "description": "Une brute."},
|
||||
{"name": "Arumvel the Wicked", "description": "Possédé."},
|
||||
{"name": "Jylagura", "description": "Garde."},
|
||||
]}, npcs)
|
||||
assert list(npcs.values()) == [
|
||||
{"name": "Arumvel the Wicked", "description": "Un acolyte possédé par le démon."},
|
||||
{"name": "Jylagura", "description": "Garde."}]
|
||||
# Le même personnage revu dans un autre lot ne fait pas une seconde fiche.
|
||||
_apply_aids([(0, scene)], {"npcs": [{"name": "Arumvel", "description": "x"}]}, npcs)
|
||||
assert len(npcs) == 2
|
||||
|
||||
|
||||
def test_campaign_npcs_ignore_titles_hyphens_and_stat_block_names():
|
||||
from app.application.import_campaign import _apply_aids
|
||||
|
||||
scene = {"name": "Sanctepierre", "rooms": [], "gm_notes": (
|
||||
"Dame Cynaëlle de Tyrmallan reçoit le capitaine Dranand. Maître Domin et Finnlor Trois-Doigts "
|
||||
"(Finnlor Troisdoigts sur l'enseigne) se méfient de Dranand. ZOMBIE SARGASSIEN : NC 1.")}
|
||||
npcs: dict[str, dict] = {}
|
||||
_apply_aids([(0, scene)], {"npcs": [
|
||||
{"name": "dame Cynaëlle"}, {"name": "Cynaëlle de Tyrmallan"}, {"name": "capitaine Dranand"},
|
||||
{"name": "Dranand"}, {"name": "Maître Domin"}, {"name": "Domin"}, {"name": "Finnlor Trois-Doigts"},
|
||||
{"name": "Finnlor Troisdoigts"}, {"name": "ZOMBIE SARGASSIEN"},
|
||||
]}, npcs)
|
||||
assert [n["name"] for n in npcs.values()] == [
|
||||
"Cynaëlle de Tyrmallan", "capitaine Dranand", "Maître Domin", "Finnlor Trois-Doigts"]
|
||||
|
||||
|
||||
def test_campaign_npcs_are_individuals_not_groups():
|
||||
from app.application.import_campaign import _apply_aids
|
||||
|
||||
scene = {"name": "Calice", "rooms": [], "gm_notes": (
|
||||
"Les Talïns et les Vanams vivent sur la Couronne. Les Capeorns et La Main se disputent le port. Céles, de l'Ordre "
|
||||
"déchu, veille. Rump family owns the manor; Guards watch the door. King RatII rules the nest. "
|
||||
"Arvell/Alezzandro ment sur son nom. Brand est un prêtre nain.")}
|
||||
npcs: dict[str, dict] = {}
|
||||
_apply_aids([(0, scene)], {"npcs": [
|
||||
{"name": "Talïns", "description": "Ce sont les habitants qui vivent sur la Couronne."},
|
||||
{"name": "Vanams", "description": "Ce groupe est le seul à profiter du labeur des gratteux."},
|
||||
{"name": "Les Capeorns", "description": "Un clan criminel familial."},
|
||||
{"name": "La Main", "description": "C'est une guilde d'assassins qui est également une secte."},
|
||||
{"name": "Ordre déchu", "description": "Anciens gardiens."},
|
||||
{"name": "Rump family", "description": "Owners of the manor."},
|
||||
{"name": "Guards", "description": "They are guards posted at the door."},
|
||||
{"name": "Céles", "description": "Il fut un membre très actif de l'Ordre déchu."},
|
||||
{"name": "King RatII", "description": "Il est le maître de la faction de rats."},
|
||||
{"name": "Arvell/Alezzandro", "description": "Un passager."},
|
||||
{"name": "Alezzandro", "description": "Un passager qui voyage sous un faux nom."},
|
||||
{"name": "Brand", "description": "C'est un prêtre nain de Thor."},
|
||||
]}, npcs)
|
||||
assert [n["name"] for n in npcs.values()] == ["Céles", "King Rat", "Arvell/Alezzandro", "Brand"]
|
||||
assert npcs["arvell alezzandro"]["description"] == "Un passager qui voyage sous un faux nom."
|
||||
|
||||
|
||||
def test_generic_creatures_are_told_from_named_characters_by_the_way_the_book_writes_them():
|
||||
from app.application.import_campaign import _is_generic
|
||||
|
||||
book = ("A wraith sits in a great leather chair. Wraith. Medium undead. The pirates are led by Key, who holds "
|
||||
"the key of the vault. Nine ghouls wait below with a giant rat. Giant rat. Small beast. "
|
||||
"Le vieux Paltuis le mage vit ici ; on y croise Dodi la pieuvre. Ruang the Ripper sleeps in B12.")
|
||||
assert _is_generic("Wraith", book) and _is_generic("Giant rat", book) and _is_generic("Nine ghouls", book)
|
||||
assert _is_generic("3 gobelins", book)
|
||||
# « Key » est aussi un nom commun, mais le livre l'écrit avec une majuscule en cours de phrase.
|
||||
assert not _is_generic("Key", book)
|
||||
assert not _is_generic("Paltuis le mage", book) and not _is_generic("Dodi la pieuvre", book)
|
||||
assert not _is_generic("Ruang the Ripper", book) and not _is_generic("Brand", book)
|
||||
|
||||
|
||||
def test_a_unique_role_without_a_name_is_still_a_character():
|
||||
from app.application.import_campaign import _is_generic
|
||||
|
||||
book = ("La commandante garde la clé du Dédale. Les PJ préviennent la commandante, qui fait ouvrir le "
|
||||
"cercueil. Plus tard, la commandante les convoque. Un spectre surgit ; le spectre attaque, puis "
|
||||
"deux spectres le rejoignent. L’aubergiste se méfie, mais l’aubergiste parle volontiers. "
|
||||
"The innkeeper pours ale and the innkeeper listens. A ghost appears; the ghost wails, the ghost flees.")
|
||||
# Toujours « la commandante », jamais « une commandante » ni au pluriel : un personnage.
|
||||
assert not _is_generic("La commandante", book) and not _is_generic("Commandante", book)
|
||||
assert not _is_generic("L’aubergiste", book) and not _is_generic("Innkeeper", book)
|
||||
# « un spectre », « deux spectres », « a ghost » : une créature parmi d'autres.
|
||||
assert _is_generic("Spectre", book) and _is_generic("Le spectre", book) and _is_generic("Ghost", book)
|
||||
# Cité une seule fois avec l'article défini : pas assez pour en faire un personnage.
|
||||
assert _is_generic("Cercueil", book)
|
||||
|
||||
|
||||
def test_scenes_about_the_book_itself_are_recognized():
|
||||
from app.application.import_campaign import _is_about_the_book
|
||||
|
||||
def scene(name, notes):
|
||||
return {"name": name, "gm_notes": notes, "rooms": []}
|
||||
|
||||
assert _is_about_the_book(scene("A note from Bill Webb on Tegel Manor", "That little kid was me."))
|
||||
assert _is_about_the_book(scene("Introduction › Avant-propos", "Bienvenue."))
|
||||
assert _is_about_the_book(scene("Overview", "First published in 1977, Tegel Manor is the oldest adventure."))
|
||||
assert _is_about_the_book(scene("Historique", "Ce module a été financé sur Kickstarter en 2019."))
|
||||
# Une année seule, ou un mot d'édition seul, ne suffit pas ; une date du monde de jeu non plus.
|
||||
assert not _is_about_the_book(scene("Le journal", "Le journal, publié par la guilde, date de l'an 1372."))
|
||||
assert not _is_about_the_book(scene("La crypte", "En 1985, le professeur disparut dans la crypte."))
|
||||
assert not _is_about_the_book(scene("How the Demon Rose", "Arumvel touched the jar."))
|
||||
|
||||
|
||||
async def test_real_people_named_only_in_the_preface_are_not_npcs(no_sleep):
|
||||
"""« Bill Webb » n'est cité que dans la préface ; « Aldric » y est cité aussi, mais on le croise
|
||||
dans l'aventure."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
doc = _campaign_doc()
|
||||
page = doc.page_count
|
||||
preface = ("Publié pour la première fois en 1977 par Bill Webb, ce module doit beaucoup à ses joueurs. "
|
||||
"Le marchand Aldric est né à sa table. ") * 3
|
||||
doc.toc.insert(0, TocEntry(level=1, title="Préface", page=page + 1))
|
||||
doc.lines.extend([TextLine(page, 0, "Préface", 24.0), TextLine(page, 1, preface.strip(), 10.0)])
|
||||
doc.pages.append(ExtractedPage(index=page, text="texte", used_ocr=False))
|
||||
aids = ('{"scenes": [], "npcs": [{"name": "Bill Webb", "description": "Auteur du module."},'
|
||||
' {"name": "Aldric", "description": "Marchand receleur."}]}')
|
||||
uc = ImportCampaignUseCase(AidsLLM(aids), FakeExtractor(doc), structure_first=True)
|
||||
done = [e async for e in uc.stream(b"pdf", language="fr")][-1]
|
||||
assert any(scene["name"] == "Préface" for arc in done["arcs"] for ch in arc["chapters"] for scene in ch["scenes"])
|
||||
assert [n["name"] for n in done["npcs"]] == ["Aldric"]
|
||||
|
||||
|
||||
async def test_campaign_import_leaves_generic_creatures_out_of_the_npcs(no_sleep):
|
||||
aids = ('{"scenes": [], "npcs": [{"name": "Aldric", "description": "Marchand receleur."},'
|
||||
' {"name": "Reliques", "description": "Objets."}, {"name": "La Dame Ysolde", "description": "Spectre."},'
|
||||
' {"name": "Dame Ysolde", "description": "Le spectre de la crypte, gardé par ses fidèles."}]}')
|
||||
uc = ImportCampaignUseCase(AidsLLM(aids), FakeExtractor(_campaign_doc()), structure_first=True)
|
||||
done = [e async for e in uc.stream(b"pdf", language="fr")][-1]
|
||||
# « reliques » est un nom commun du livre ; « La Dame Ysolde » n'y figure pas sous cette forme.
|
||||
assert done["npcs"] == [{"name": "Aldric", "description": "Marchand receleur."},
|
||||
{"name": "Dame Ysolde", "description": "Le spectre de la crypte, gardé par ses fidèles."}]
|
||||
|
||||
|
||||
async def test_campaign_appendices_get_no_aids_from_the_ai(no_sleep):
|
||||
"""Le bestiaire en annexe : ni synopsis rédigé, ni PNJ — mais traduit comme le reste."""
|
||||
from app.domain.models import TextLine, TocEntry
|
||||
doc = _campaign_doc()
|
||||
page = doc.page_count
|
||||
profile = "Le spectre Vorlak est une créature mort-vivante qui hante la crypte et draine la vie. " * 4
|
||||
doc.toc.append(TocEntry(level=1, title="Annexe : Créatures", page=page + 1))
|
||||
doc.toc.append(TocEntry(level=2, title="Spectre", page=page + 1))
|
||||
doc.lines.extend([TextLine(page, 0, "Annexe : Créatures", 24.0), TextLine(page, 1, "Spectre", 16.0),
|
||||
TextLine(page, 2, profile.strip(), 10.0)])
|
||||
doc.pages.append(ExtractedPage(index=page, text="texte", used_ocr=False))
|
||||
llm = AidsLLM(_AIDS.replace('"Dame Ysolde"}', '"Dame Ysolde"}, {"name": "Vorlak", "description": "Spectre."}'))
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(doc), structure_first=True)
|
||||
done = [e async for e in uc.stream(b"pdf", language="fr")][-1]
|
||||
assert [(arc["name"], arc["type"]) for arc in done["arcs"]] == [("Aventure principale", "LINEAR"), ("Annexes", "HUB")]
|
||||
appendix = done["arcs"][1]["chapters"][0]["scenes"][0]
|
||||
assert appendix["name"] == "Spectre" and appendix["gm_notes"] == profile.strip()
|
||||
# Le texte de l'annexe n'est pas montré au modèle : il n'en tire ni synopsis ni PNJ.
|
||||
assert all("Vorlak" not in prompt for prompt in llm.prompts)
|
||||
assert [n["name"] for n in done["npcs"]] == ["Aldric", "Dame Ysolde"]
|
||||
|
||||
|
||||
def test_the_model_sees_the_list_of_rooms_of_an_explorable_place_first():
|
||||
from app.application.import_campaign import _aid_text
|
||||
|
||||
dungeon = {"name": "Crypte", "gm_notes": "Conclusion.", "rooms": [
|
||||
{"name": "1. Entrée", "description": "Une grille."}, {"name": "2. Tombeau", "description": "Un roi."}]}
|
||||
text = _aid_text(dungeon, 10_000)
|
||||
assert text.startswith("[Lieu explorable, 2 pièce(s) : 1. Entrée; 2. Tombeau]\n\nConclusion.\n\n1. Entrée\nUne grille.")
|
||||
assert _aid_text({"name": "Route", "gm_notes": "Une route.", "rooms": []}, 10_000) == "Une route."
|
||||
|
||||
|
||||
def test_campaign_rooms_are_translated_and_put_back_in_place():
|
||||
from app.application.import_campaign import _apply_translation, _translation_units
|
||||
|
||||
scenes = [{"name": "Crypt", "gm_notes": "Notes.", "rooms": [
|
||||
{"name": "1. Gate", "description": "A gate.", "enemies": "", "loot": ""},
|
||||
{"name": "2. Empty", "description": " ", "enemies": "", "loot": ""}]},
|
||||
{"name": "Road", "gm_notes": "", "rooms": []}]
|
||||
units, labels = _translation_units(scenes)
|
||||
assert units == {"s0": "Notes.", "s0r0": "A gate."}
|
||||
assert labels == {"s0": "Crypt", "s0r0": "Crypt › 1. Gate"}
|
||||
_apply_translation(scenes, {"s0r0": "Une grille."})
|
||||
assert scenes[0]["gm_notes"] == "Notes." and scenes[0]["rooms"][0]["description"] == "Une grille."
|
||||
|
||||
|
||||
def test_campaign_aids_are_asked_by_batches_in_the_order_of_the_book():
|
||||
from app.application.import_campaign import _aid_batches
|
||||
|
||||
scenes = [{"name": f"Scène {i}", "gm_notes": "x" * 3_000, "rooms": []} for i in range(5)]
|
||||
batches = _aid_batches(scenes, 8_000)
|
||||
assert [[index for index, _ in batch] for batch in batches] == [[0, 1], [2, 3], [4]]
|
||||
# Une scène très longue est bornée pour les aides : elle ne fait pas déborder le lot.
|
||||
assert len(_aid_batches([{"name": "Longue", "gm_notes": "x" * 50_000, "rooms": []}], 8_000)) == 1
|
||||
assert len(_aid_batches([{"name": f"S{i}", "gm_notes": "x", "rooms": []} for i in range(30)], 8_000)) == 3
|
||||
|
||||
|
||||
def test_campaign_import_uses_the_structure_and_one_call_at_a_time_locally():
|
||||
from app.api.deps import get_import_campaign_use_case
|
||||
from app.core.config import Settings
|
||||
|
||||
local = get_import_campaign_use_case(ScriptedLLM(["{}"]), Settings(_env_file=None, llm_provider="ollama"))
|
||||
cloud = get_import_campaign_use_case(ScriptedLLM(["{}"]), Settings(_env_file=None, llm_provider="mistral"))
|
||||
assert local._structure_first and cloud._structure_first
|
||||
assert local._map_concurrency == 1 and local._translation_concurrency == 1
|
||||
assert cloud._map_concurrency > 1 and cloud._translation_concurrency > 1
|
||||
|
||||
@@ -93,3 +93,44 @@ async def test_stream_chat_prepends_system_prompt():
|
||||
body = json.loads(route.calls.last.request.content)
|
||||
assert body["messages"][0] == {"role": "system", "content": "SYS"}
|
||||
assert body["messages"][-1] == {"role": "user", "content": "Q"}
|
||||
|
||||
|
||||
# --- Réflexion coupée (modèles qwen3.x… : réponse vide dès qu'un JSON est attendu) ---------
|
||||
|
||||
@pytest.fixture
|
||||
def forget_refused_models():
|
||||
from app.infrastructure import ollama_adapter
|
||||
ollama_adapter._THINK_PARAM_REFUSED.clear()
|
||||
yield
|
||||
ollama_adapter._THINK_PARAM_REFUSED.clear()
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_turns_thinking_off(forget_refused_models):
|
||||
route = respx.post(_GEN).mock(return_value=httpx.Response(200, json={"response": "{}"}))
|
||||
await _svc().generate("p", output_format={"type": "object"})
|
||||
assert json.loads(route.calls.last.request.content)["think"] is False
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_retries_without_think_when_ollama_refuses_it(forget_refused_models):
|
||||
route = respx.post(_GEN).mock(side_effect=[
|
||||
httpx.Response(400, json={"error": '"gemma" does not support thinking'}),
|
||||
httpx.Response(200, json={"response": "ok"}),
|
||||
httpx.Response(200, json={"response": "encore"}),
|
||||
])
|
||||
assert await _svc().generate("p") == "ok"
|
||||
assert "think" in json.loads(route.calls[0].request.content)
|
||||
assert "think" not in json.loads(route.calls[1].request.content)
|
||||
# Le refus est retenu : l'appel suivant n'envoie plus le paramètre (un seul aller-retour).
|
||||
assert await _svc().generate("p") == "encore"
|
||||
assert "think" not in json.loads(route.calls[2].request.content)
|
||||
assert route.call_count == 3
|
||||
|
||||
|
||||
@respx.mock
|
||||
async def test_generate_does_not_retry_another_bad_request(forget_refused_models):
|
||||
route = respx.post(_GEN).mock(return_value=httpx.Response(400, json={"error": "invalid format schema"}))
|
||||
with pytest.raises(LLMProviderError, match="invalid format schema"):
|
||||
await _svc().generate("p")
|
||||
assert route.call_count == 1
|
||||
|
||||
@@ -0,0 +1,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."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from app.application import rules_translation
|
||||
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:
|
||||
@@ -58,3 +65,186 @@ async def test_translate_titles_falls_back_to_the_original_title():
|
||||
def test_unique_titles_avoids_collisions():
|
||||
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
||||
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
|
||||
|
||||
|
||||
# --- traduction des sections d'un livre ----------------------------------------
|
||||
|
||||
class SectionLLM:
|
||||
"""Traduit « en majuscules ». `fail` : sous-chaînes dont la traduction échoue ;
|
||||
`slow` : sous-chaînes dont la traduction ne se termine jamais. Mesure aussi le nombre
|
||||
d'appels de contenu menés en même temps."""
|
||||
|
||||
def __init__(self, titles_json: str = '{"titles": {}}', fail=(), slow=()) -> None:
|
||||
self._titles_json = titles_json
|
||||
self._fail = tuple(fail)
|
||||
self._slow = tuple(slow)
|
||||
self.running = 0
|
||||
self.max_running = 0
|
||||
self.content_calls = 0
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
if "Traduis ces titres" in prompt:
|
||||
if self._titles_json is None:
|
||||
raise LLMProviderError("HTTP 401 clé refusée")
|
||||
return self._titles_json
|
||||
text = prompt.split("Extrait :\n", 1)[1]
|
||||
self.content_calls += 1
|
||||
self.running += 1
|
||||
self.max_running = max(self.max_running, self.running)
|
||||
try:
|
||||
await asyncio.sleep(0) # laisse démarrer les traductions voisines
|
||||
if any(mark in text for mark in self._fail):
|
||||
raise LLMProviderError("HTTP 401 clé refusée")
|
||||
if any(mark in text for mark in self._slow):
|
||||
await asyncio.Event().wait()
|
||||
return text.upper()
|
||||
finally:
|
||||
self.running -= 1
|
||||
|
||||
|
||||
async def _run(llm, sections, **kwargs):
|
||||
events = [e async for e in translate_sections(RulesTranslator(llm), sections, "fr", "en", **kwargs)]
|
||||
assert events[-1][0] == "result"
|
||||
return events, events[-1][1]
|
||||
|
||||
|
||||
async def test_translate_sections_translates_several_at_once_and_keeps_the_book_order():
|
||||
sections = {f"Titre {i}": f"texte {i}" for i in range(7)}
|
||||
llm = SectionLLM('{"titles": {"Titre 0": "Title 0"}}')
|
||||
events, result = await _run(llm, sections, concurrency=3)
|
||||
assert llm.max_running == 3
|
||||
assert list(result.sections) == ["Title 0"] + [f"Titre {i}" for i in range(1, 7)]
|
||||
assert result.sections["Title 0"] == "TEXTE 0"
|
||||
assert result.untranslated == []
|
||||
statuses = [payload for kind, payload in events if kind == "status"]
|
||||
assert statuses[0] == "Traduction (anglais) des titres…"
|
||||
assert any(s.startswith("Traduction (anglais) : 7/7") for s in statuses)
|
||||
|
||||
|
||||
async def test_translate_sections_one_at_a_time_for_a_local_model():
|
||||
llm = SectionLLM()
|
||||
await _run(llm, {"A": "a", "B": "b", "C": "c"}, concurrency=1)
|
||||
assert llm.max_running == 1
|
||||
|
||||
|
||||
async def test_translate_sections_keeps_the_original_text_of_a_failed_section(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
llm = SectionLLM('{"titles": {"Combat": "Fighting", "Magie": "Magic"}}', fail=["sorts"])
|
||||
_, result = await _run(llm, {"Combat": "les coups", "Magie": "les sorts"}, concurrency=1)
|
||||
# La section en échec garde son titre et son texte d'origine : rien n'est perdu.
|
||||
assert result == TranslatedRules({"Fighting": "LES COUPS", "Magie": "les sorts"}, ["Magie"])
|
||||
|
||||
|
||||
async def test_translate_sections_stops_launching_after_repeated_failures(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
sections = {"Ok": "bon"} | {f"S{i}": f"panne {i}" for i in range(8)}
|
||||
llm = SectionLLM(fail=["panne"])
|
||||
_, result = await _run(llm, sections, concurrency=1)
|
||||
assert result.sections["Ok"] == "BON"
|
||||
assert len(result.untranslated) == 8
|
||||
# 1 réussite, puis 3 sections en échec (3 tentatives chacune) : les 5 autres ne partent pas.
|
||||
assert llm.content_calls == 1 + rules_translation.MAX_FAILED_SECTIONS * 3
|
||||
|
||||
|
||||
async def test_translate_sections_gives_up_the_running_ones_when_time_is_up():
|
||||
llm = SectionLLM(slow=["lent"])
|
||||
events, result = await _run(llm, {"Vite": "court", "Lent": "lent"},
|
||||
concurrency=2, budget_seconds=0.2, heartbeat_seconds=0.05)
|
||||
assert result == TranslatedRules({"Vite": "COURT", "Lent": "lent"}, ["Lent"])
|
||||
assert any(kind == "heartbeat" for kind, _ in events)
|
||||
assert llm.running == 0 # la traduction en cours a bien été annulée
|
||||
|
||||
|
||||
async def test_translate_sections_fails_when_nothing_could_be_translated(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
with pytest.raises(LLMProviderError, match="aucune section"):
|
||||
await _run(SectionLLM(fail=["texte"]), {"A": "texte a", "B": "texte b"})
|
||||
with pytest.raises(LLMProviderError, match="temps imparti"):
|
||||
await _run(SectionLLM(slow=["texte"]), {"A": "texte a"}, budget_seconds=0.1, heartbeat_seconds=0.05)
|
||||
with pytest.raises(LLMProviderError, match="401"):
|
||||
await _run(SectionLLM(titles_json=None), {"A": "texte a"})
|
||||
|
||||
|
||||
async def test_translate_sections_avoids_two_sections_under_the_same_title(monkeypatch):
|
||||
async def _noop(_d):
|
||||
return None
|
||||
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
||||
# « Combat » est traduit en « Magie » alors que la section « Magie », en échec, garde son titre.
|
||||
llm = SectionLLM('{"titles": {"Combat": "Magie"}}', fail=["sorts"])
|
||||
_, result = await _run(llm, {"Combat": "les coups", "Magie": "les sorts"}, concurrency=1)
|
||||
assert result.sections == {"Magie": "LES COUPS", "Magie (2)": "les sorts"}
|
||||
|
||||
|
||||
async def test_translate_sections_of_nothing():
|
||||
_, result = await _run(SectionLLM(), {})
|
||||
assert result == TranslatedRules({})
|
||||
|
||||
|
||||
async def test_translate_titles_sends_a_long_list_in_several_calls():
|
||||
"""Un livre découpé par sa structure a des centaines de titres."""
|
||||
titles = [f"Titre {i}" for i in range(rules_translation.TITLES_PER_CALL * 2 + 5)]
|
||||
|
||||
class BatchLLM:
|
||||
def __init__(self) -> None:
|
||||
self.sizes: list[int] = []
|
||||
|
||||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||||
listed = [line[2:] for line in prompt.splitlines() if line.startswith("- Titre ")]
|
||||
self.sizes.append(len(listed))
|
||||
import json as _json
|
||||
return _json.dumps({"titles": {t: t.replace("Titre", "Title") for t in listed}})
|
||||
|
||||
llm = BatchLLM()
|
||||
out = await RulesTranslator(llm).translate_titles(titles, "fr", "en")
|
||||
assert llm.sizes == [rules_translation.TITLES_PER_CALL, rules_translation.TITLES_PER_CALL, 5]
|
||||
assert out["Titre 0"] == "Title 0" and out[titles[-1]] == titles[-1].replace("Titre", "Title")
|
||||
assert list(out) == titles
|
||||
|
||||
|
||||
|
||||
# --- 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 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.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 "MOT POUR MOT" 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 '{"spells": []}' in prompt
|
||||
|
||||
@@ -68,33 +68,116 @@ def test_prompt_without_field_title_or_avoided_name():
|
||||
assert "DÉJÀ relevés" not in prompt
|
||||
|
||||
|
||||
def test_clean_spells_keeps_complete_entries_and_stringifies_values():
|
||||
spells = _clean_spells([
|
||||
{"name": " Éclair ", "level": 1, "school": None, "description": " Un trait. ",
|
||||
"values": {"Portée": " 18 m ", "Coût": 2, "Vide": " ", " ": "x", "Liste": ["a"]}, "excerpt": " Un trait. "},
|
||||
{"name": "Sans description", "description": " ", "excerpt": "Un passage."},
|
||||
{"name": "Sans passage", "description": "Un effet."},
|
||||
{"name": "", "description": "Un effet.", "excerpt": "Un passage."},
|
||||
{"name": "Valeurs mal formées", "description": "Un effet.", "excerpt": "Un passage.", "values": ["x"]},
|
||||
_BOOK = (
|
||||
"## Magic › Fire Spells\n\n"
|
||||
"CANTRIP\n\n"
|
||||
"### Flame Dart 1 Action\n\n"
|
||||
"Range: 10. Damage: 1d10. On crit: Smoldering.\n\n"
|
||||
"High Levels: +5 damage every 5th level.\n\n"
|
||||
"TIER 1\n\n"
|
||||
"### Ignite 2 Actions\n\n"
|
||||
"Range: 10. Damage: 4d10 to a Smoldering target.\n\n"
|
||||
"Upcast: +10 damage.\n\n"
|
||||
"TIER 2\n\n"
|
||||
"### Enchant Weapon 1 Action\n\n"
|
||||
"Concentration: 1 min. Reach: 8."
|
||||
)
|
||||
|
||||
|
||||
def test_the_description_of_a_spell_is_the_slice_of_the_book_that_follows_its_name():
|
||||
spells = locate_spells([
|
||||
{"name": "Flame Dart", "level": "Cantrip", "school": "Fire", "start": "CANTRIP"},
|
||||
{"name": "Ignite", "level": 1, "school": "Fire", "start": "TIER 1"},
|
||||
{"name": "Enchant Weapon", "level": "2", "school": None, "start": "TIER 2"},
|
||||
], _BOOK)
|
||||
|
||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite", "Enchant Weapon"]
|
||||
# Mot pour mot, 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",
|
||||
])
|
||||
|
||||
assert [s.name for s in spells] == ["Éclair", "Valeurs mal formées"]
|
||||
assert spells[0].level == "1"
|
||||
assert spells[0].school == ""
|
||||
assert spells[0].description == "Un trait."
|
||||
assert spells[0].values == {"Portée": "18 m", "Coût": "2"}
|
||||
], _BOOK)
|
||||
assert [s.name for s in spells] == ["Flame Dart", "Ignite"]
|
||||
assert spells[0].level == "0"
|
||||
assert spells[0].values == {"Portée": "10", "Coût": "2"}
|
||||
assert spells[1].values == {}
|
||||
assert _clean_spells(None) == []
|
||||
assert _clean_spells({"name": "x"}) == []
|
||||
assert locate_spells(None, _BOOK) == []
|
||||
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": [
|
||||
{"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||
"description": "Un 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"},
|
||||
{"name": "Incomplet"},
|
||||
{"name": "Éclair de givre", "level": "1", "school": "Évocation", "values": {"Portée": "18 m"},
|
||||
"start": "### Éclair de givre",
|
||||
# Un modèle qui écrirait quand même une description : elle est ignorée.
|
||||
"description": "Un rayon glacé inventé par le modèle.", "excerpt": "Un rayon glacé"},
|
||||
{"name": "Sort absent du texte", "start": "nulle part"},
|
||||
]}))
|
||||
app.dependency_overrides[get_llm_provider] = lambda: llm
|
||||
|
||||
@@ -105,10 +188,11 @@ def test_route_returns_cleaned_spells_with_low_temperature(client):
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"spells": [{
|
||||
"name": "Éclair de givre", "level": "1", "school": "Évocation",
|
||||
"description": "Un 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"}]}
|
||||
"description": "Niveau 1 — Évocation. Portée : 18 m.\nUn trait de givre frappe une cible : 2d6 dégâts de froid.",
|
||||
"values": {"Portée": "18 m"}, "excerpt": "Niveau 1 — Évocation. Portée : 18 m."}]}
|
||||
assert llm.temperature == 0.1
|
||||
assert llm.output_format["required"] == ["spells"]
|
||||
assert "description" not in llm.output_format["properties"]["spells"]["items"]["properties"]
|
||||
assert "- Voile de brume" in llm.prompt
|
||||
|
||||
|
||||
@@ -131,3 +215,14 @@ def test_route_with_no_spell_returns_empty_list(client):
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"spells": []}
|
||||
|
||||
|
||||
def test_prompt_asks_for_one_way_to_write_levels_and_schools():
|
||||
"""D'un morceau à l'autre, l'IA écrivait « 1 », « Niveau 1 », « Tour », « Cantrip »…"""
|
||||
from app.application.prompts.spell_extraction import spell_extraction_prompt
|
||||
|
||||
prompt = spell_extraction_prompt("Nimble", "Magie", "Zap. Portée 8.", [], [])
|
||||
assert "par son SEUL nombre" in prompt
|
||||
assert "jamais « Niveau 1 »" in prompt
|
||||
assert "« Tour de magie » si le texte est en français" in prompt
|
||||
assert "sans « Sorts de »" in prompt
|
||||
|
||||
Reference in New Issue
Block a user