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:
2026-11-14 10:45:55 +01:00
parent 6c1d74f9a5
commit 3c76762efc
71 changed files with 5974 additions and 368 deletions
+225
View File
@@ -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([]) == []
+618
View File
@@ -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
+41
View File
@@ -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
+203
View File
@@ -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
+376
View File
@@ -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.")
+191 -1
View File
@@ -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")
+121 -26
View File
@@ -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