Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 2m18s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 2m49s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m10s
Presque tous les sorts proposés étaient écartés : la description reprise du livre commençait par une ligne trop courte (« 1 Action ») pour servir de passage cité. Relevé de sorts - Le passage cité prend le début de la description sur plusieurs lignes quand la première est trop courte. - La ligne de niveau placée au-dessus du nom (« TIER 2 ») ouvre la description du sort au lieu de finir celle du précédent ; le niveau y est lu avant celui du modèle. - Un objet magique n'est pas un sort : texte qui s'ouvre sur une rareté, « nom » qui n'est qu'un niveau, consigne au modèle ; les sections d'équipement ne sont plus cochées d'office. - Le modèle est relancé quand des titres de sorts restent sans réponse. - L'école se lit aussi dans un titre traduit ; la traduction des titres garde « › ». Lecture du PDF - Un grand titre dessiné après le texte qu'il coiffe est remis à sa place : les sorts d'une école n'étaient plus rangés sous le titre de l'école précédente. - Des lignes de blocs différents ne forment une rangée de tableau que si leurs cellules se touchent presque ou si une rangée voisine est alignée ; deux intertitres à la même hauteur ne sont pas une rangée.
263 lines
12 KiB
Python
263 lines
12 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
|
||
|
||
|
||
|
||
async def test_translated_titles_keep_the_path_separator():
|
||
class TitlesLLM:
|
||
async def generate(self, prompt: str, *, output_format=None, temperature=None) -> str:
|
||
return ('{"titles": {"Magic › Fire Spells": "Magie > Sorts de feu", "Combat": "Combat",'
|
||
' "Gear › A > B": "Équipement › A > B"}}')
|
||
|
||
titles = await rules_translation.RulesTranslator(TitlesLLM()).translate_titles(
|
||
["Magic › Fire Spells", "Combat", "Gear › A > B"], "en", "fr")
|
||
assert titles == {"Magic › Fire Spells": "Magie › Sorts de feu", "Combat": "Combat",
|
||
"Gear › A > B": "Équipement › A > B"}
|
||
|
||
|
||
# --- glossaire des termes de jeu ---------------------------------------------------------------
|
||
|
||
_STAT_BLOCK = ("Tiny beast, unaligned\n\nArmor Class 12 Hit Points 22 (4d6 + 8) Speed 10 ft., fly 40 ft.\n\n"
|
||
"| STR | DEX | CON | INT | WIS | CHA |\n| --- | --- | --- | --- | --- | --- |\n"
|
||
"Saving Throws CON +4 Senses darkvision 60 ft., passive Perception 11 Challenge 1/4 (50 XP)")
|
||
|
||
|
||
def test_the_glossary_gives_the_game_terms_found_in_the_text():
|
||
from app.application.rules_translation import glossary
|
||
|
||
terms = dict(glossary(_STAT_BLOCK, "en", "fr"))
|
||
assert terms["Saving Throws"] == "Jets de sauvegarde" and terms["WIS"] == "SAG" and terms["STR"] == "FOR"
|
||
assert terms["Armor Class"] == "Classe d'armure" and terms["darkvision"] == "vision dans le noir"
|
||
assert terms["beast"] == "bête" and terms["XP"] == "PX"
|
||
# Rien que ce que le texte contient ; une abréviation n'est pas cherchée dans un mot.
|
||
assert "Wisdom" not in terms and "AC" not in terms and "sp" not in terms
|
||
assert glossary("The acolyte whispers in the dark.", "en", "fr") == []
|
||
assert glossary("You win 25 gp and the DC is 13.", "en", "fr") == [("DC", "DD"), ("gp", "po")]
|
||
|
||
|
||
def test_the_glossary_works_both_ways_and_is_bounded():
|
||
from app.application.rules_translation import GLOSSARY_TERMS, _GLOSSARY_EN_FR, glossary
|
||
|
||
assert glossary("Jets de sauvegarde +4, vision dans le noir 18 m.", "fr", "en") == [
|
||
("Jets de sauvegarde", "Saving Throws"), ("vision dans le noir", "darkvision")]
|
||
everything = " ".join(term for term, _ in _GLOSSARY_EN_FR)
|
||
assert len(glossary(everything, "en", "fr")) == GLOSSARY_TERMS
|
||
# Pas de glossaire pour un autre couple de langues.
|
||
assert glossary(_STAT_BLOCK, "en", "de") == []
|
||
|
||
|
||
def test_the_translation_prompt_carries_the_glossary_only_when_needed():
|
||
from app.application.rules_translation import content_prompt
|
||
|
||
prompt = content_prompt(_STAT_BLOCK, "en", "fr")
|
||
assert "- Saving Throws → Jets de sauvegarde\n" in prompt and "- WIS → SAG\n" in prompt
|
||
assert prompt.index("Glossaire") < prompt.index("Extrait :\n")
|
||
assert prompt.endswith("Extrait :\n" + _STAT_BLOCK)
|
||
assert "ne convertis rien" in prompt
|
||
assert "Glossaire" not in content_prompt("The road goes north through the pines.", "en", "fr")
|