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.
251 lines
11 KiB
Python
251 lines
11 KiB
Python
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
|
|
import pytest
|
|
|
|
from app.application import rules_translation
|
|
from app.application.rules_translation import (
|
|
RulesTranslator, TranslatedRules, detect_language, other_languages, split_markdown,
|
|
translate_sections, unique_titles,
|
|
)
|
|
from app.domain.ports import LLMProviderError
|
|
|
|
|
|
class EchoLLM:
|
|
"""Traduit « en majuscules » et garde trace des prompts reçus."""
|
|
|
|
def __init__(self, titles_json: str = '{"titles": {}}') -> None:
|
|
self.prompts: list[str] = []
|
|
self._titles_json = titles_json
|
|
|
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
|
self.prompts.append(prompt)
|
|
if "Traduis ces titres" in prompt:
|
|
return self._titles_json
|
|
return prompt.split("Extrait :\n", 1)[1].upper()
|
|
|
|
|
|
def test_detect_language():
|
|
assert detect_language("Le joueur lance les dés et la partie est terminée pour vous.") == "fr"
|
|
assert detect_language("The player rolls the dice and the game is over for you.") == "en"
|
|
assert detect_language("", default="en") == "en"
|
|
assert other_languages("fr") == ["en"]
|
|
assert other_languages("en") == ["fr"]
|
|
|
|
|
|
def test_split_markdown_keeps_short_text_and_cuts_at_paragraphs():
|
|
assert split_markdown("court") == ["court"]
|
|
text = "\n\n".join(["a" * 40] * 10)
|
|
chunks = split_markdown(text, max_chars=100)
|
|
assert all(len(c) <= 100 for c in chunks)
|
|
assert "".join(chunks).replace("\n", "") == text.replace("\n", "")
|
|
|
|
|
|
def test_split_markdown_cuts_a_giant_paragraph():
|
|
chunks = split_markdown("x" * 250, max_chars=100)
|
|
assert [len(c) for c in chunks] == [100, 100, 50]
|
|
|
|
|
|
async def test_translate_content_keeps_names_instruction_and_joins_chunks():
|
|
llm = EchoLLM()
|
|
out = await RulesTranslator(llm).translate_content("## Combat\n\nChaque round.", "fr", "en")
|
|
assert out == "## COMBAT\n\nCHAQUE ROUND."
|
|
assert "noms propres" in llm.prompts[0]
|
|
assert "de la langue « français » vers la langue « anglais »" in llm.prompts[0]
|
|
|
|
|
|
async def test_translate_titles_falls_back_to_the_original_title():
|
|
llm = EchoLLM('{"titles": {"Combat": "Fighting"}}')
|
|
out = await RulesTranslator(llm).translate_titles(["Combat", "Magie"], "fr", "en")
|
|
assert out == {"Combat": "Fighting", "Magie": "Magie"}
|
|
|
|
|
|
def test_unique_titles_avoids_collisions():
|
|
assert unique_titles({"A": "Combat", "B": "Combat", "C": "Magie"}) == {
|
|
"A": "Combat", "B": "Combat (2)", "C": "Magie"}
|
|
|
|
|
|
# --- traduction des sections d'un livre ----------------------------------------
|
|
|
|
class SectionLLM:
|
|
"""Traduit « en majuscules ». `fail` : sous-chaînes dont la traduction échoue ;
|
|
`slow` : sous-chaînes dont la traduction ne se termine jamais. Mesure aussi le nombre
|
|
d'appels de contenu menés en même temps."""
|
|
|
|
def __init__(self, titles_json: str = '{"titles": {}}', fail=(), slow=()) -> None:
|
|
self._titles_json = titles_json
|
|
self._fail = tuple(fail)
|
|
self._slow = tuple(slow)
|
|
self.running = 0
|
|
self.max_running = 0
|
|
self.content_calls = 0
|
|
|
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
|
if "Traduis ces titres" in prompt:
|
|
if self._titles_json is None:
|
|
raise LLMProviderError("HTTP 401 clé refusée")
|
|
return self._titles_json
|
|
text = prompt.split("Extrait :\n", 1)[1]
|
|
self.content_calls += 1
|
|
self.running += 1
|
|
self.max_running = max(self.max_running, self.running)
|
|
try:
|
|
await asyncio.sleep(0) # laisse démarrer les traductions voisines
|
|
if any(mark in text for mark in self._fail):
|
|
raise LLMProviderError("HTTP 401 clé refusée")
|
|
if any(mark in text for mark in self._slow):
|
|
await asyncio.Event().wait()
|
|
return text.upper()
|
|
finally:
|
|
self.running -= 1
|
|
|
|
|
|
async def _run(llm, sections, **kwargs):
|
|
events = [e async for e in translate_sections(RulesTranslator(llm), sections, "fr", "en", **kwargs)]
|
|
assert events[-1][0] == "result"
|
|
return events, events[-1][1]
|
|
|
|
|
|
async def test_translate_sections_translates_several_at_once_and_keeps_the_book_order():
|
|
sections = {f"Titre {i}": f"texte {i}" for i in range(7)}
|
|
llm = SectionLLM('{"titles": {"Titre 0": "Title 0"}}')
|
|
events, result = await _run(llm, sections, concurrency=3)
|
|
assert llm.max_running == 3
|
|
assert list(result.sections) == ["Title 0"] + [f"Titre {i}" for i in range(1, 7)]
|
|
assert result.sections["Title 0"] == "TEXTE 0"
|
|
assert result.untranslated == []
|
|
statuses = [payload for kind, payload in events if kind == "status"]
|
|
assert statuses[0] == "Traduction (anglais) des titres…"
|
|
assert any(s.startswith("Traduction (anglais) : 7/7") for s in statuses)
|
|
|
|
|
|
async def test_translate_sections_one_at_a_time_for_a_local_model():
|
|
llm = SectionLLM()
|
|
await _run(llm, {"A": "a", "B": "b", "C": "c"}, concurrency=1)
|
|
assert llm.max_running == 1
|
|
|
|
|
|
async def test_translate_sections_keeps_the_original_text_of_a_failed_section(monkeypatch):
|
|
async def _noop(_d):
|
|
return None
|
|
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
|
llm = SectionLLM('{"titles": {"Combat": "Fighting", "Magie": "Magic"}}', fail=["sorts"])
|
|
_, result = await _run(llm, {"Combat": "les coups", "Magie": "les sorts"}, concurrency=1)
|
|
# La section en échec garde son titre et son texte d'origine : rien n'est perdu.
|
|
assert result == TranslatedRules({"Fighting": "LES COUPS", "Magie": "les sorts"}, ["Magie"])
|
|
|
|
|
|
async def test_translate_sections_stops_launching_after_repeated_failures(monkeypatch):
|
|
async def _noop(_d):
|
|
return None
|
|
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
|
sections = {"Ok": "bon"} | {f"S{i}": f"panne {i}" for i in range(8)}
|
|
llm = SectionLLM(fail=["panne"])
|
|
_, result = await _run(llm, sections, concurrency=1)
|
|
assert result.sections["Ok"] == "BON"
|
|
assert len(result.untranslated) == 8
|
|
# 1 réussite, puis 3 sections en échec (3 tentatives chacune) : les 5 autres ne partent pas.
|
|
assert llm.content_calls == 1 + rules_translation.MAX_FAILED_SECTIONS * 3
|
|
|
|
|
|
async def test_translate_sections_gives_up_the_running_ones_when_time_is_up():
|
|
llm = SectionLLM(slow=["lent"])
|
|
events, result = await _run(llm, {"Vite": "court", "Lent": "lent"},
|
|
concurrency=2, budget_seconds=0.2, heartbeat_seconds=0.05)
|
|
assert result == TranslatedRules({"Vite": "COURT", "Lent": "lent"}, ["Lent"])
|
|
assert any(kind == "heartbeat" for kind, _ in events)
|
|
assert llm.running == 0 # la traduction en cours a bien été annulée
|
|
|
|
|
|
async def test_translate_sections_fails_when_nothing_could_be_translated(monkeypatch):
|
|
async def _noop(_d):
|
|
return None
|
|
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
|
with pytest.raises(LLMProviderError, match="aucune section"):
|
|
await _run(SectionLLM(fail=["texte"]), {"A": "texte a", "B": "texte b"})
|
|
with pytest.raises(LLMProviderError, match="temps imparti"):
|
|
await _run(SectionLLM(slow=["texte"]), {"A": "texte a"}, budget_seconds=0.1, heartbeat_seconds=0.05)
|
|
with pytest.raises(LLMProviderError, match="401"):
|
|
await _run(SectionLLM(titles_json=None), {"A": "texte a"})
|
|
|
|
|
|
async def test_translate_sections_avoids_two_sections_under_the_same_title(monkeypatch):
|
|
async def _noop(_d):
|
|
return None
|
|
monkeypatch.setattr("app.application.llm_retry.asyncio.sleep", _noop)
|
|
# « Combat » est traduit en « Magie » alors que la section « Magie », en échec, garde son titre.
|
|
llm = SectionLLM('{"titles": {"Combat": "Magie"}}', fail=["sorts"])
|
|
_, result = await _run(llm, {"Combat": "les coups", "Magie": "les sorts"}, concurrency=1)
|
|
assert result.sections == {"Magie": "LES COUPS", "Magie (2)": "les sorts"}
|
|
|
|
|
|
async def test_translate_sections_of_nothing():
|
|
_, result = await _run(SectionLLM(), {})
|
|
assert result == TranslatedRules({})
|
|
|
|
|
|
async def test_translate_titles_sends_a_long_list_in_several_calls():
|
|
"""Un livre découpé par sa structure a des centaines de titres."""
|
|
titles = [f"Titre {i}" for i in range(rules_translation.TITLES_PER_CALL * 2 + 5)]
|
|
|
|
class BatchLLM:
|
|
def __init__(self) -> None:
|
|
self.sizes: list[int] = []
|
|
|
|
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
|
listed = [line[2:] for line in prompt.splitlines() if line.startswith("- Titre ")]
|
|
self.sizes.append(len(listed))
|
|
import json as _json
|
|
return _json.dumps({"titles": {t: t.replace("Titre", "Title") for t in listed}})
|
|
|
|
llm = BatchLLM()
|
|
out = await RulesTranslator(llm).translate_titles(titles, "fr", "en")
|
|
assert llm.sizes == [rules_translation.TITLES_PER_CALL, rules_translation.TITLES_PER_CALL, 5]
|
|
assert out["Titre 0"] == "Title 0" and out[titles[-1]] == titles[-1].replace("Titre", "Title")
|
|
assert list(out) == titles
|
|
|
|
|
|
|
|
# --- 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")
|