Règles des systèmes en deux langues ; import de campagne dans la langue de l'UI
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 35s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 50s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m26s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 35s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 50s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Failing after 1m26s
- Règles d'un système de jeu stockées en français et en anglais (migration V28, rules_markdown_en). L'import d'un PDF garde l'extraction fidèle dans la langue du livre (détectée) et traduit section par section vers l'autre langue, noms propres conservés ; la progression de la traduction s'affiche. Un échec de traduction n'annule pas l'import. - Éditeur du système : onglets Français / English ; l'import remplit les deux. Règles en séance et contexte de l'IA : version de la langue de l'interface, avec repli sur l'autre si elle est vide. - Import de campagne : textes rédigés (ou traduits) dans la langue de l'interface ; titres et noms propres conservés tels quels ; arc par défaut nommé dans la bonne langue. - Les règles anglaises suivent l'export/import de sauvegarde. Vérifié : brain (détection, découpe, traduction, flux d'import, langue de l'import de campagne), core clean verify (1299 tests), web build + vitest + lint. Traduction non essayée avec un vrai modèle.
This commit is contained in:
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# Règles en deux langues : {code langue → sections} et langue d'origine du livre.
|
||||
sections_by_language: dict[str, dict[str, str]] = {}
|
||||
source_language: str = ""
|
||||
|
||||
|
||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||
@@ -70,6 +73,8 @@ async def import_rules(
|
||||
sections=result.sections,
|
||||
page_count=result.page_count,
|
||||
ocr_page_count=result.ocr_page_count,
|
||||
sections_by_language=result.sections_by_language,
|
||||
source_language=result.source_language,
|
||||
)
|
||||
|
||||
|
||||
@@ -115,6 +120,7 @@ async def import_rules_stream(
|
||||
@router.post("/import/campaign/stream")
|
||||
async def import_campaign_stream(
|
||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||
language: Annotated[str, Depends(get_user_language)],
|
||||
file: UploadFile = File(...),
|
||||
) -> StreamingResponse:
|
||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
||||
@@ -131,7 +137,7 @@ async def import_campaign_stream(
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(content):
|
||||
async for ev in use_case.stream(content, language=language):
|
||||
event_type = ev.pop("type")
|
||||
yield sse_event(event_type, ev)
|
||||
except PdfExtractionError as exc:
|
||||
|
||||
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
|
||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||
self._map_concurrency = max(1, map_concurrency)
|
||||
|
||||
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
|
||||
async def execute(self, pdf_bytes: bytes, language: str = "fr") -> CampaignImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
@@ -371,7 +371,7 @@ class ImportCampaignUseCase:
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
results = await asyncio.gather(*(
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||
for i, c in wave
|
||||
))
|
||||
for res in results:
|
||||
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
|
||||
npcs=merger.npcs(),
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes):
|
||||
async def stream(self, pdf_bytes: bytes, language: str = "fr"):
|
||||
"""Variante streamée : yield des évènements d'avancement.
|
||||
|
||||
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
||||
@@ -432,7 +432,7 @@ class ImportCampaignUseCase:
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
gathered = asyncio.gather(
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block, language=language)
|
||||
for i, c in wave),
|
||||
return_exceptions=True,
|
||||
)
|
||||
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
|
||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||
|
||||
async def _map_chunk(
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = ""
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = "", language: str = "fr"
|
||||
) -> dict:
|
||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||
return await self._extract_payload(
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block)
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block, language=language)
|
||||
|
||||
async def _extract_payload(
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = "",
|
||||
language: str = "fr",
|
||||
) -> dict:
|
||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||
prompt = (
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.DEFAULT_ARC_NAME)
|
||||
prompts.MAP_SYSTEM.format(default_arc=prompts.default_arc_name(language))
|
||||
+ prompts.language_block(language)
|
||||
+ toc_section
|
||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||
"Renvoie maintenant le JSON de l'arborescence."
|
||||
@@ -591,9 +593,9 @@ class ImportCampaignUseCase:
|
||||
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||
"re-découpage en 2 moitiés plus digestes…")
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
payload, truncated = self._parse_payload(raw, index=index)
|
||||
|
||||
@@ -607,9 +609,9 @@ class ImportCampaignUseCase:
|
||||
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||
"re-découpage en 2 moitiés plus digestes…")
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block, language=language)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
if truncated:
|
||||
logger.warning(
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.application.import_status import (
|
||||
from app.application.llm_json import load_json_object, looks_like_truncated_json
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.prompts import import_rules as prompts
|
||||
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
||||
from app.application.streaming import with_heartbeat
|
||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
||||
|
||||
@@ -90,6 +91,9 @@ _ANCHORS_SCHEMA: dict = {
|
||||
}
|
||||
|
||||
|
||||
# Échantillon de texte utilisé pour détecter la langue du livre (début du PDF).
|
||||
_DETECT_CHARS = 20_000
|
||||
|
||||
class _SectionMerger:
|
||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||
|
||||
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
|
||||
merger = _SectionMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
||||
sections = merger.result()
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
by_language = {source: sections}
|
||||
translator = RulesTranslator(self._llm)
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
titles = unique_titles(await translator.translate_titles(list(sections), source, target))
|
||||
by_language[target] = {
|
||||
titles.get(title, title): await translator.translate_content(content, source, target)
|
||||
for title, content in sections.items()
|
||||
}
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
return RulesImportResult(
|
||||
sections=merger.result(),
|
||||
sections=sections,
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
sections_by_language=by_language,
|
||||
source_language=source,
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes, language: str = _DEFAULT_LANG):
|
||||
@@ -344,14 +363,57 @@ class ImportRulesUseCase:
|
||||
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||
return
|
||||
|
||||
# Règles en deux langues : l'extraction est fidèle au livre ; on traduit vers l'autre
|
||||
# langue de l'application. Un échec de traduction n'annule pas l'import.
|
||||
source = detect_language(doc.full_text[:_DETECT_CHARS], default=language)
|
||||
by_language: dict[str, dict[str, str]] = {source: sections}
|
||||
for target in other_languages(source):
|
||||
try:
|
||||
async for ev in self._translate_events(sections, source, target):
|
||||
if ev["type"] == "_translated":
|
||||
by_language[target] = ev["sections"]
|
||||
else:
|
||||
yield ev
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Traduction des règles (%s) impossible : %s", target, exc)
|
||||
yield {"type": "status",
|
||||
"message": f"Traduction ({language_name(target)}) impossible : {str(exc)[:200]}"}
|
||||
|
||||
yield {
|
||||
"type": "done",
|
||||
"sections": sections,
|
||||
"sections_by_language": by_language,
|
||||
"source_language": source,
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
async def _translate_events(self, sections: dict[str, str], source: str, target: str):
|
||||
"""Évènements d'avancement de la traduction ; le dernier est
|
||||
{"type": "_translated", "sections": {...}} (consommé par `stream`, jamais relayé)."""
|
||||
translator = RulesTranslator(self._llm)
|
||||
titles = list(sections)
|
||||
total = len(titles)
|
||||
label = language_name(target)
|
||||
yield {"type": "status", "message": f"Traduction ({label}) des titres…", "current": 0, "total": total}
|
||||
mapping: dict[str, str] = {}
|
||||
async for kind, payload in with_heartbeat(translator.translate_titles(titles, source, target)):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": 0, "total": total}
|
||||
elif kind == "result":
|
||||
mapping = unique_titles(payload)
|
||||
out: dict[str, str] = {}
|
||||
for i, title in enumerate(titles):
|
||||
yield {"type": "status", "message": f"Traduction ({label}) : {i + 1}/{total} — {title}",
|
||||
"current": i + 1, "total": total}
|
||||
async for kind, payload in with_heartbeat(translator.translate_content(sections[title], source, target)):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
elif kind == "result":
|
||||
out[mapping.get(title, title)] = payload
|
||||
yield {"type": "_translated", "sections": out}
|
||||
|
||||
# --- MAP : un morceau → sections -----------------------------------------
|
||||
|
||||
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
||||
|
||||
@@ -1,7 +1,29 @@
|
||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
||||
from app.core.language import language_name
|
||||
|
||||
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||
DEFAULT_ARC_NAME = "Aventure principale"
|
||||
DEFAULT_ARC_NAMES = {"fr": DEFAULT_ARC_NAME, "en": "Main adventure"}
|
||||
|
||||
|
||||
def default_arc_name(language: str) -> str:
|
||||
"""Nom de l'arc unique, dans la langue de l'interface."""
|
||||
return DEFAULT_ARC_NAMES.get(language, DEFAULT_ARC_NAME)
|
||||
|
||||
|
||||
def language_block(language: str) -> str:
|
||||
"""Consigne de langue : les textes sont écrits dans la langue de l'interface, quelle que
|
||||
soit celle du livre (traduits fidèlement s'il le faut). Les TITRES et noms propres restent
|
||||
ceux du livre : la fusion des morceaux se fait par nom exact, et un nom ne se traduit pas."""
|
||||
name = language_name(language)
|
||||
return (
|
||||
"\n\nLANGUE DE SORTIE :\n"
|
||||
f"- Rédige TOUS les textes (description, player_narration, gm_notes, salles, PNJ) en {name}, "
|
||||
f"quelle que soit la langue du livre. Si le livre est dans une autre langue, TRADUIS ces textes "
|
||||
"fidèlement, sans les résumer davantage.\n"
|
||||
"- Garde TELS QUELS les noms propres (personnages, lieux, divinités, sorts, objets nommés) "
|
||||
"et les noms d'arcs, de chapitres, de scènes, de salles et de PNJ (titres du livre)."
|
||||
)
|
||||
|
||||
MAP_SYSTEM = """Tu es un assistant qui structure un livre de campagne de jeu de rôle.
|
||||
On te donne un EXTRAIT brut d'un PDF de campagne (texte parfois mal coupé par la mise en page).
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Règles en deux langues : détection de la langue d'un livre de règles et traduction de
|
||||
ses sections (titre + contenu markdown) vers l'autre langue de l'application.
|
||||
|
||||
L'extraction reste FIDÈLE au livre (langue d'origine) ; la traduction produit la seconde
|
||||
version. Les noms propres (lieux, personnages, divinités, sorts, objets nommés) sont
|
||||
conservés tels quels. Un contenu long est traduit par morceaux coupés aux paragraphes,
|
||||
pour rester sous les limites de sortie des modèles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.core.language import language_name
|
||||
from app.domain.ports import LLMProvider
|
||||
|
||||
LANGUAGES = ("fr", "en")
|
||||
|
||||
# Taille maximale d'un morceau de contenu envoyé en traduction (caractères).
|
||||
CHUNK_CHARS = 6000
|
||||
|
||||
_FR_WORDS = {"le", "la", "les", "des", "une", "est", "et", "du", "dans", "pour", "que", "qui",
|
||||
"sur", "avec", "vous", "votre", "sont", "pas", "par", "au", "aux", "ce", "cette", "il"}
|
||||
_EN_WORDS = {"the", "and", "of", "to", "is", "in", "you", "your", "for", "with", "that", "are",
|
||||
"on", "as", "be", "this", "it", "an", "by", "or", "can", "if", "each", "when"}
|
||||
|
||||
|
||||
def detect_language(text: str, default: str = "fr") -> str:
|
||||
"""Langue dominante (« fr » ou « en ») par comptage de mots-outils ; `default` si indécis."""
|
||||
words = re.findall(r"[a-zàâçéèêëîïôûùüÿœ']+", (text or "").lower())
|
||||
fr = sum(1 for w in words if w in _FR_WORDS)
|
||||
en = sum(1 for w in words if w in _EN_WORDS)
|
||||
if fr == en:
|
||||
return default if default in LANGUAGES else "fr"
|
||||
return "fr" if fr > en else "en"
|
||||
|
||||
|
||||
def other_languages(source: str) -> list[str]:
|
||||
return [lang for lang in LANGUAGES if lang != source]
|
||||
|
||||
|
||||
def split_markdown(text: str, max_chars: int = CHUNK_CHARS) -> list[str]:
|
||||
"""Coupe un markdown en morceaux ≤ max_chars, aux limites de paragraphes (puis de lignes)."""
|
||||
if len(text) <= max_chars:
|
||||
return [text]
|
||||
chunks: list[str] = []
|
||||
current = ""
|
||||
for para in re.split(r"(\n\s*\n)", text):
|
||||
if len(current) + len(para) <= max_chars:
|
||||
current += para
|
||||
continue
|
||||
if current.strip():
|
||||
chunks.append(current)
|
||||
current = ""
|
||||
while len(para) > max_chars: # paragraphe géant : coupe aux lignes, sinon brutalement
|
||||
cut = para.rfind("\n", 0, max_chars)
|
||||
cut = cut if cut > 0 else max_chars
|
||||
chunks.append(para[:cut])
|
||||
para = para[cut:]
|
||||
current = para
|
||||
if current.strip():
|
||||
chunks.append(current)
|
||||
return chunks
|
||||
|
||||
|
||||
def content_prompt(text: str, source: str, target: str) -> str:
|
||||
return (
|
||||
f"Traduis cet extrait de livre de règles de jeu de rôle de la langue « {language_name(source)} » "
|
||||
f"vers la langue « {language_name(target)} ».\n\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Conserve EXACTEMENT la mise en forme markdown (titres, listes, tableaux, gras).\n"
|
||||
"- Garde TELS QUELS les noms propres : lieux, personnages, divinités, peuples, sorts et "
|
||||
"objets nommés.\n"
|
||||
"- Traduis les termes de jeu de façon cohérente (une même notion = un même mot).\n"
|
||||
"- Ne résume pas, n'ajoute rien, ne commente pas : renvoie UNIQUEMENT la traduction.\n\n"
|
||||
"Extrait :\n"
|
||||
f"{text}"
|
||||
)
|
||||
|
||||
|
||||
def titles_prompt(titles: list[str], source: str, target: str) -> str:
|
||||
listing = "\n".join(f"- {t}" for t in titles)
|
||||
return (
|
||||
f"Traduis ces titres de sections d'un livre de règles de jeu de rôle de la langue "
|
||||
f"« {language_name(source)} » vers la langue « {language_name(target)} ». "
|
||||
"Garde les noms propres tels quels.\n"
|
||||
'Réponds UNIQUEMENT par un objet JSON : {"titles": {"titre d\'origine": "titre traduit", ...}}\n\n'
|
||||
f"{listing}"
|
||||
)
|
||||
|
||||
|
||||
class RulesTranslator:
|
||||
"""Traduit des sections de règles {titre: markdown} d'une langue vers une autre."""
|
||||
|
||||
def __init__(self, llm: LLMProvider) -> None:
|
||||
self._llm = llm
|
||||
|
||||
async def translate_titles(self, titles: list[str], source: str, target: str) -> dict[str, str]:
|
||||
"""{titre d'origine: titre traduit} ; un titre non traduit garde son libellé d'origine."""
|
||||
if not titles:
|
||||
return {}
|
||||
raw = await generate_with_retry(self._llm, titles_prompt(titles, source, target),
|
||||
output_format="json", temperature=0.2)
|
||||
parsed, _ = load_json_object(raw)
|
||||
mapping = parsed.get("titles") if isinstance(parsed, dict) else None
|
||||
out: dict[str, str] = {}
|
||||
for title in titles:
|
||||
value = mapping.get(title) if isinstance(mapping, dict) else None
|
||||
out[title] = str(value).strip() if isinstance(value, str) and value.strip() else title
|
||||
return out
|
||||
|
||||
async def translate_content(self, text: str, source: str, target: str) -> str:
|
||||
"""Traduit un contenu markdown (morceau par morceau s'il est long)."""
|
||||
if not text or not text.strip():
|
||||
return text
|
||||
parts = []
|
||||
for chunk in split_markdown(text):
|
||||
if not chunk.strip():
|
||||
parts.append(chunk)
|
||||
continue
|
||||
translated = await generate_with_retry(self._llm, content_prompt(chunk, source, target),
|
||||
temperature=0.2)
|
||||
parts.append(translated.strip())
|
||||
return "\n\n".join(p for p in parts if p.strip())
|
||||
|
||||
|
||||
def unique_titles(titles: dict[str, str]) -> dict[str, str]:
|
||||
"""Évite deux sections traduites sous le même titre (sinon l'une écraserait l'autre)."""
|
||||
seen: dict[str, int] = {}
|
||||
out: dict[str, str] = {}
|
||||
for original, translated in titles.items():
|
||||
count = seen.get(translated, 0)
|
||||
seen[translated] = count + 1
|
||||
out[original] = translated if count == 0 else f"{translated} ({count + 1})"
|
||||
return out
|
||||
@@ -367,6 +367,10 @@ class RulesImportResult:
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# Règles en deux langues : {code langue → sections}. La langue d'origine du livre
|
||||
# (`source_language`) contient l'extraction fidèle ; l'autre, sa traduction.
|
||||
sections_by_language: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||
source_language: str = ""
|
||||
|
||||
def to_markdown(self) -> str:
|
||||
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
||||
|
||||
@@ -100,6 +100,8 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||
("Traduis cet extrait", "spells"),
|
||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||
("BBB second", '{"Magie":"sorts"}'),
|
||||
])
|
||||
@@ -111,6 +113,25 @@ async def test_rules_stream_skips_failed_chunk_but_continues(monkeypatch, no_sle
|
||||
assert done["type"] == "done"
|
||||
assert done["sections"] == {"Magie": "sorts"}
|
||||
assert done["skipped"] == 1
|
||||
# Règles en deux langues : livre en français (« Texte du PDF. ») → traduction anglaise.
|
||||
assert done["source_language"] == "fr"
|
||||
assert done["sections_by_language"] == {"fr": {"Magie": "sorts"}, "en": {"Magic": "spells"}}
|
||||
assert any(e["type"] == "status" and "anglais" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_rules_stream_keeps_the_source_language_when_translation_fails(monkeypatch, no_sleep):
|
||||
monkeypatch.setattr("app.application.import_rules.chunk_text", lambda *a, **k: ["The rules of the game"])
|
||||
llm = ContentLLM([
|
||||
("Traduis ces titres", LLMProviderError("HTTP 503 saturé")),
|
||||
("The rules of the game", '{"Combat":"Each round, you roll the dice."}'),
|
||||
])
|
||||
uc = ImportRulesUseCase(llm, FakeExtractor(_doc("The rules of the game are simple and you can play.")))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
done = events[-1]
|
||||
assert done["type"] == "done"
|
||||
assert done["source_language"] == "en"
|
||||
assert done["sections_by_language"] == {"en": {"Combat": "Each round, you roll the dice."}}
|
||||
assert any(e["type"] == "status" and "impossible" in e["message"] for e in events)
|
||||
|
||||
|
||||
async def test_rules_stream_all_chunks_fail_emits_error(one_chunk, no_sleep):
|
||||
@@ -155,3 +176,34 @@ async def test_campaign_stream_all_fail_emits_error(one_chunk, no_sleep):
|
||||
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf")]
|
||||
assert events[-1]["type"] == "error"
|
||||
|
||||
|
||||
class _RecordingLLM(ScriptedLLM):
|
||||
"""ScriptedLLM qui garde les prompts reçus."""
|
||||
|
||||
def __init__(self, responses: list) -> None:
|
||||
super().__init__(responses)
|
||||
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_campaign_import_writes_in_the_interface_language_and_keeps_names():
|
||||
llm = _RecordingLLM([_TREE])
|
||||
uc = ImportCampaignUseCase(llm, FakeExtractor(_doc()))
|
||||
events = [e async for e in uc.stream(b"pdf", language="en")]
|
||||
assert events[-1]["type"] == "done"
|
||||
prompt = llm.prompts[0]
|
||||
assert "LANGUE DE SORTIE" in prompt
|
||||
assert "en anglais" in prompt
|
||||
assert "noms propres" in prompt
|
||||
assert '"Main adventure"' in prompt, "arc par défaut dans la langue de l'interface"
|
||||
|
||||
|
||||
async def test_campaign_import_defaults_to_french():
|
||||
llm = _RecordingLLM([_TREE])
|
||||
await ImportCampaignUseCase(llm, FakeExtractor(_doc())).execute(b"pdf")
|
||||
assert "en français" in llm.prompts[0]
|
||||
assert '"Aventure principale"' in llm.prompts[0]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Règles en deux langues : détection de la langue, découpe des longs contenus, traduction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.application.rules_translation import (
|
||||
RulesTranslator, detect_language, other_languages, split_markdown, unique_titles,
|
||||
)
|
||||
|
||||
|
||||
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"}
|
||||
+6
-2
@@ -1,6 +1,7 @@
|
||||
package com.loremind.application.gamesystemcontext;
|
||||
|
||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
||||
@@ -36,9 +37,11 @@ public class GameSystemContextBuilder {
|
||||
private static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
||||
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
private final CurrentLanguage currentLanguage;
|
||||
|
||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
this.currentLanguage = currentLanguage;
|
||||
}
|
||||
|
||||
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
|
||||
}
|
||||
|
||||
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
||||
Map<String, String> allSections = parseH2Sections(gs.getRulesMarkdown());
|
||||
// Règles dans la langue de l'interface (repli sur l'autre version si celle-ci est vide).
|
||||
Map<String, String> allSections = parseH2Sections(gs.rulesFor(currentLanguage.get()));
|
||||
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ public class GameSystemService {
|
||||
String name,
|
||||
String description,
|
||||
String rulesMarkdown,
|
||||
String rulesMarkdownEn,
|
||||
List<TemplateField> characterTemplate,
|
||||
List<TemplateField> npcTemplate,
|
||||
List<TemplateField> enemyTemplate,
|
||||
@@ -72,6 +73,7 @@ public class GameSystemService {
|
||||
.name(data.name())
|
||||
.description(data.description())
|
||||
.rulesMarkdown(data.rulesMarkdown())
|
||||
.rulesMarkdownEn(data.rulesMarkdownEn())
|
||||
.foundryActorType(normalize(data.foundryActorType()))
|
||||
.author(normalize(data.author()))
|
||||
.isPublic(data.isPublic())
|
||||
@@ -96,6 +98,7 @@ public class GameSystemService {
|
||||
existing.setName(data.name());
|
||||
existing.setDescription(data.description());
|
||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
|
||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||
existing.replaceNpcTemplate(data.npcTemplate());
|
||||
existing.replaceEnemyTemplate(data.enemyTemplate());
|
||||
|
||||
@@ -35,6 +35,9 @@ public class GameSystem {
|
||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||
private String rulesMarkdown;
|
||||
|
||||
/** Version anglaise des règles ({@code rulesMarkdown} = version française). Nullable. */
|
||||
private String rulesMarkdownEn;
|
||||
|
||||
/**
|
||||
* Template de fiche PJ : champs typés affichés pour chaque personnage joueur.
|
||||
* Hors champs universels hard-codés (nom, portrait, header). Jamais null après
|
||||
@@ -161,4 +164,15 @@ public class GameSystem {
|
||||
if (a == null || b == null) return a == null && b == null;
|
||||
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/**
|
||||
* Règles dans la langue demandée ({@code en} → anglais, sinon français), avec repli sur
|
||||
* l'autre version si celle-ci est vide : un système importé dans une seule langue reste lisible.
|
||||
*/
|
||||
public String rulesFor(String language) {
|
||||
boolean english = "en".equalsIgnoreCase(language);
|
||||
String preferred = english ? rulesMarkdownEn : rulesMarkdown;
|
||||
String fallback = english ? rulesMarkdown : rulesMarkdownEn;
|
||||
return preferred != null && !preferred.isBlank() ? preferred : fallback;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,5 +16,14 @@ import java.util.Map;
|
||||
public record RulesImportResult(
|
||||
Map<String, String> sections,
|
||||
int pageCount,
|
||||
int ocrPageCount) {
|
||||
int ocrPageCount,
|
||||
/** Règles en deux langues : {code langue → sections} (« fr », « en »). */
|
||||
Map<String, Map<String, String>> sectionsByLanguage,
|
||||
/** Langue d'origine du livre (extraction fidèle) ; l'autre version est traduite. */
|
||||
String sourceLanguage) {
|
||||
|
||||
/** Résultat dans une seule langue (Brain antérieur, ou traduction indisponible). */
|
||||
public RulesImportResult(Map<String, String> sections, int pageCount, int ocrPageCount) {
|
||||
this(sections, pageCount, ocrPageCount, Map.of(), null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.loremind.domain.shared.ports;
|
||||
|
||||
/**
|
||||
* Port : langue de l'interface de l'utilisateur courant ({@code fr} ou {@code en}), pour les
|
||||
* contenus qui existent en deux langues (règles d'un système de jeu). Implémenté côté web.
|
||||
*/
|
||||
public interface CurrentLanguage {
|
||||
|
||||
/** Code court de la langue courante ({@code fr} par défaut). */
|
||||
String get();
|
||||
}
|
||||
@@ -106,7 +106,9 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
return new RulesImportResult(
|
||||
Map.copyOf(response.getSections()),
|
||||
response.getPageCount(),
|
||||
response.getOcrPageCount());
|
||||
response.getOcrPageCount(),
|
||||
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
|
||||
response.getSourceLanguage());
|
||||
} catch (ResourceAccessException e) {
|
||||
throw new RulesImportException(
|
||||
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
||||
@@ -218,12 +220,23 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
||||
callbacks.onDone().accept(new RulesImportResult(
|
||||
toStringMap(node.path("sections")),
|
||||
node.path("page_count").asInt(),
|
||||
node.path("ocr_page_count").asInt()));
|
||||
node.path("ocr_page_count").asInt(),
|
||||
toLanguageMap(node.path("sections_by_language")),
|
||||
node.path("source_language").asText(null)));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers -------------------------------------------------------------
|
||||
|
||||
/** {code langue → sections} : règles en deux langues (vide si le Brain ne les fournit pas). */
|
||||
private Map<String, Map<String, String>> toLanguageMap(JsonNode node) {
|
||||
Map<String, Map<String, String>> out = new java.util.LinkedHashMap<>();
|
||||
if (node != null && node.isObject()) {
|
||||
node.fields().forEachRemaining(e -> out.put(e.getKey(), toStringMap(e.getValue())));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<String> toStringList(JsonNode array) {
|
||||
List<String> out = new ArrayList<>();
|
||||
if (array != null && array.isArray()) {
|
||||
|
||||
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
|
||||
|
||||
@JsonProperty("ocr_page_count")
|
||||
private int ocrPageCount;
|
||||
|
||||
/** Règles en deux langues : {code langue → sections} (absent d'un Brain antérieur). */
|
||||
@JsonProperty("sections_by_language")
|
||||
private Map<String, Map<String, String>> sectionsByLanguage;
|
||||
|
||||
@JsonProperty("source_language")
|
||||
private String sourceLanguage;
|
||||
}
|
||||
|
||||
+3
@@ -37,6 +37,9 @@ public class GameSystemJpaEntity {
|
||||
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||
private String rulesMarkdown;
|
||||
|
||||
@Column(name = "rules_markdown_en", columnDefinition = "TEXT")
|
||||
private String rulesMarkdownEn;
|
||||
|
||||
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
||||
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||
@Column(name = "character_template", columnDefinition = "TEXT")
|
||||
|
||||
+2
@@ -60,6 +60,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
.name(e.getName())
|
||||
.description(e.getDescription())
|
||||
.rulesMarkdown(e.getRulesMarkdown())
|
||||
.rulesMarkdownEn(e.getRulesMarkdownEn())
|
||||
.characterTemplate(e.getCharacterTemplate() != null
|
||||
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
@@ -84,6 +85,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
||||
.name(g.getName())
|
||||
.description(g.getDescription())
|
||||
.rulesMarkdown(g.getRulesMarkdown())
|
||||
.rulesMarkdownEn(g.getRulesMarkdownEn())
|
||||
.characterTemplate(g.getCharacterTemplate() != null
|
||||
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
||||
: new java.util.ArrayList<>())
|
||||
|
||||
@@ -577,7 +577,8 @@ public class ExportService {
|
||||
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
||||
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
||||
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic());
|
||||
e.getEnemyTemplate(), e.getFoundryActorType(), e.getAuthor(), e.isPublic(),
|
||||
e.getRulesMarkdownEn());
|
||||
}
|
||||
|
||||
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||
|
||||
@@ -49,6 +49,7 @@ class LoreContentInserter {
|
||||
e.setName(d.name());
|
||||
e.setDescription(d.description());
|
||||
e.setRulesMarkdown(d.rulesMarkdown());
|
||||
e.setRulesMarkdownEn(d.rulesMarkdownEn());
|
||||
e.setCharacterTemplate(d.characterTemplate());
|
||||
e.setNpcTemplate(d.npcTemplate());
|
||||
e.setEnemyTemplate(d.enemyTemplate());
|
||||
|
||||
@@ -77,7 +77,9 @@ public record ContentExport(
|
||||
List<TemplateField> enemyTemplate,
|
||||
String foundryActorType,
|
||||
String author,
|
||||
boolean isPublic
|
||||
boolean isPublic,
|
||||
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
|
||||
String rulesMarkdownEn
|
||||
) {}
|
||||
|
||||
public record LoreDto(
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.loremind.infrastructure.web.config;
|
||||
|
||||
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Langue courante lue dans {@link UserLanguageHolder} (requête HTTP, ou tâche de fond décorée). */
|
||||
@Component
|
||||
public class UserLanguageCurrentLanguage implements CurrentLanguage {
|
||||
|
||||
@Override
|
||||
public String get() {
|
||||
return UserLanguageHolder.get();
|
||||
}
|
||||
}
|
||||
+1
@@ -257,6 +257,7 @@ public class GameSystemController {
|
||||
dto.getName(),
|
||||
dto.getDescription(),
|
||||
dto.getRulesMarkdown(),
|
||||
dto.getRulesMarkdownEn(),
|
||||
templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
|
||||
templateFieldMapper.toDomainList(dto.getNpcTemplate()),
|
||||
templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
|
||||
|
||||
+2
@@ -17,6 +17,8 @@ public class GameSystemDTO {
|
||||
private String name;
|
||||
private String description;
|
||||
private String rulesMarkdown;
|
||||
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||
private String rulesMarkdownEn;
|
||||
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
||||
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
||||
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
|
||||
|
||||
@@ -20,6 +20,7 @@ public class GameSystemMapper {
|
||||
dto.setName(g.getName());
|
||||
dto.setDescription(g.getDescription());
|
||||
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||
dto.setRulesMarkdownEn(g.getRulesMarkdownEn());
|
||||
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
|
||||
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
|
||||
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
|
||||
@@ -36,6 +37,7 @@ public class GameSystemMapper {
|
||||
.name(dto.getName())
|
||||
.description(dto.getDescription())
|
||||
.rulesMarkdown(dto.getRulesMarkdown())
|
||||
.rulesMarkdownEn(dto.getRulesMarkdownEn())
|
||||
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
|
||||
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
|
||||
.enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate()))
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Règles d'un système de jeu en deux langues : rules_markdown = version française,
|
||||
-- rules_markdown_en = version anglaise (remplie à l'import d'un PDF par traduction).
|
||||
ALTER TABLE game_systems ADD COLUMN rules_markdown_en TEXT;
|
||||
+23
@@ -23,6 +23,9 @@ class GameSystemContextBuilderTest {
|
||||
@Mock
|
||||
private GameSystemRepository gameSystemRepository;
|
||||
|
||||
@Mock
|
||||
private com.loremind.domain.shared.ports.CurrentLanguage currentLanguage;
|
||||
|
||||
@InjectMocks
|
||||
private GameSystemContextBuilder builder;
|
||||
|
||||
@@ -71,4 +74,24 @@ class GameSystemContextBuilderTest {
|
||||
|
||||
assertEquals("Règles de combat.", sections.get("Combat"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void build_usesTheRulesOfTheInterfaceLanguage_withFallback() {
|
||||
com.loremind.domain.gamesystemcontext.GameSystem gs = com.loremind.domain.gamesystemcontext.GameSystem.builder()
|
||||
.id("gs").name("Nimble").rulesMarkdown("## Combat\nJet de d20").rulesMarkdownEn("## Fighting\nRoll a d20").build();
|
||||
org.mockito.Mockito.when(gameSystemRepository.findById("gs")).thenReturn(java.util.Optional.of(gs));
|
||||
|
||||
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
|
||||
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
|
||||
.orElseThrow().toString().contains("Roll a d20"));
|
||||
|
||||
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("fr");
|
||||
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
|
||||
.orElseThrow().toString().contains("Jet de d20"));
|
||||
|
||||
gs.setRulesMarkdownEn(null); // pas de version anglaise : repli sur le français
|
||||
org.mockito.Mockito.when(currentLanguage.get()).thenReturn("en");
|
||||
assertTrue(builder.buildOptional("gs", com.loremind.domain.gamesystemcontext.GenerationIntent.GENERIC)
|
||||
.orElseThrow().toString().contains("Jet de d20"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,4 +347,26 @@ class BrainRulesImportClientTest {
|
||||
assertTrue(c.done.get().sections().isEmpty());
|
||||
assertNull(c.error.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming_done_carriesBothLanguages() {
|
||||
String sse = "event:done\ndata:{\"sections\":{\"Combat\":\"d20\"},\"page_count\":2,\"ocr_page_count\":0,"
|
||||
+ "\"source_language\":\"fr\",\"sections_by_language\":{\"fr\":{\"Combat\":\"d20\"},"
|
||||
+ "\"en\":{\"Fighting\":\"d20 roll\"}}}\n\n";
|
||||
Collector c = new Collector();
|
||||
ExchangeFunction ef = req -> Mono.just(
|
||||
ClientResponse.create(HttpStatus.OK)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
.body(sse)
|
||||
.build());
|
||||
client(ef).importRulesStreaming(
|
||||
new byte[]{1}, "r.pdf",
|
||||
c.progress::add, c.heartbeats::incrementAndGet, c.statuses::add,
|
||||
c.done::set, c.error::set);
|
||||
|
||||
assertNotNull(c.done.get());
|
||||
assertEquals("fr", c.done.get().sourceLanguage());
|
||||
assertEquals(java.util.Map.of("Fighting", "d20 roll"), c.done.get().sectionsByLanguage().get("en"));
|
||||
assertEquals(java.util.Map.of("Combat", "d20"), c.done.get().sectionsByLanguage().get("fr"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,18 @@
|
||||
<p class="import-error">{{ importError }}</p>
|
||||
}
|
||||
|
||||
<!-- Règles en deux langues : un onglet par version (l'import d'un PDF remplit les deux). -->
|
||||
<div class="rules-langs" role="tablist" [attr.aria-label]="'gameSystemEdit.langTabs' | translate">
|
||||
@for (lang of rulesLangs; track lang) {
|
||||
<button type="button" role="tab" class="rules-lang" [class.active]="rulesLang === lang"
|
||||
[attr.aria-selected]="rulesLang === lang" (click)="rulesLang = lang">
|
||||
{{ ('gameSystemEdit.lang.' + lang) | translate }}
|
||||
<span class="rules-lang-count">{{ sectionCount(lang) }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<p class="sections-hint">{{ 'gameSystemEdit.langHint' | translate }}</p>
|
||||
|
||||
<div class="section-list">
|
||||
@for (section of sections; track section; let i = $index) {
|
||||
<div class="section-card" [class.collapsed]="section.collapsed">
|
||||
|
||||
@@ -359,3 +359,32 @@
|
||||
|
||||
&:hover { border-color: #374151; color: #e5e7eb; }
|
||||
}
|
||||
|
||||
// Règles en deux langues : onglets Français / English au-dessus des sections.
|
||||
.rules-langs {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
margin: 0.75rem 0 0.35rem;
|
||||
}
|
||||
|
||||
.rules-lang {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.4rem 0.85rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid #374151;
|
||||
background: transparent;
|
||||
color: #d1d5db;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
|
||||
&.active { border-color: #6c63ff; background: rgba(108, 99, 255, 0.15); color: white; }
|
||||
}
|
||||
|
||||
.rules-lang-count {
|
||||
font-size: 0.72rem;
|
||||
padding: 0 0.4rem;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
@@ -43,6 +43,9 @@ const NPC_FIELD_SUGGESTIONS = ['Motivation', 'Apparence', 'Faction', 'Notes MJ']
|
||||
/** Suggestions de champs pour la fiche ENNEMI — stats de combat. */
|
||||
const ENEMY_FIELD_SUGGESTIONS = ['Stats', 'Attaques', 'Capacités', 'Faiblesses', 'Butin', 'Tactique'];
|
||||
|
||||
/** Langue d'une version des règles. */
|
||||
type RulesLang = 'fr' | 'en';
|
||||
|
||||
@Component({
|
||||
selector: 'app-game-system-edit',
|
||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent],
|
||||
@@ -83,7 +86,15 @@ export class GameSystemEditComponent implements OnInit {
|
||||
name = '';
|
||||
description = '';
|
||||
author = '';
|
||||
sections: RuleSection[] = [];
|
||||
/** Règles en deux langues : sections par langue ; l'onglet affiché est `rulesLang`. */
|
||||
sectionsByLang: Record<RulesLang, RuleSection[]> = { fr: [], en: [] };
|
||||
rulesLang: RulesLang = 'fr';
|
||||
readonly rulesLangs: RulesLang[] = ['fr', 'en'];
|
||||
|
||||
/** Sections de l'onglet affiché (même tableau : push/splice modifient la bonne langue). */
|
||||
get sections(): RuleSection[] {
|
||||
return this.sectionsByLang[this.rulesLang];
|
||||
}
|
||||
characterTemplate: TemplateField[] = [];
|
||||
npcTemplate: TemplateField[] = [];
|
||||
enemyTemplate: TemplateField[] = [];
|
||||
@@ -107,6 +118,8 @@ export class GameSystemEditComponent implements OnInit {
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
// Onglet de règles par défaut : la langue de l'interface.
|
||||
this.rulesLang = this.translate.getCurrentLang() === 'en' ? 'en' : 'fr';
|
||||
this.id = this.route.snapshot.paramMap.get('id');
|
||||
if (this.id) {
|
||||
this.service.getById(this.id).subscribe({
|
||||
@@ -114,7 +127,10 @@ export class GameSystemEditComponent implements OnInit {
|
||||
this.name = gs.name;
|
||||
this.description = gs.description ?? '';
|
||||
this.author = gs.author ?? '';
|
||||
this.sections = this.parseMarkdown(gs.rulesMarkdown ?? '');
|
||||
this.sectionsByLang = {
|
||||
fr: this.parseMarkdown(gs.rulesMarkdown ?? ''),
|
||||
en: this.parseMarkdown(gs.rulesMarkdownEn ?? '')
|
||||
};
|
||||
this.characterTemplate = gs.characterTemplate ? [...gs.characterTemplate] : [];
|
||||
this.npcTemplate = gs.npcTemplate ? [...gs.npcTemplate] : [];
|
||||
this.enemyTemplate = gs.enemyTemplate ? [...gs.enemyTemplate] : [];
|
||||
@@ -181,7 +197,7 @@ export class GameSystemEditComponent implements OnInit {
|
||||
} else if (ev.type === 'status') {
|
||||
this.importStatus = ev.message;
|
||||
} else if (ev.type === 'done') {
|
||||
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount);
|
||||
this.finishImport(ev.sections, ev.pageCount, ev.ocrPageCount, ev.sectionsByLanguage, ev.sourceLanguage);
|
||||
}
|
||||
},
|
||||
error: (err: Error) => {
|
||||
@@ -193,9 +209,21 @@ export class GameSystemEditComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number): void {
|
||||
private finishImport(sections: Record<string, string>, pageCount: number, ocrPageCount: number,
|
||||
byLanguage?: Record<string, Record<string, string>>, sourceLanguage?: string | null): void {
|
||||
this.resetImportProgress();
|
||||
const added = this.mergeImportedSections(sections);
|
||||
// Règles en deux langues (Brain récent) : chaque version va dans son onglet ; sinon,
|
||||
// les sections vont dans l'onglet affiché (comportement historique).
|
||||
const bilingual = !!byLanguage && Object.keys(byLanguage).some(l => l === 'fr' || l === 'en');
|
||||
let added = 0;
|
||||
if (bilingual) {
|
||||
for (const lang of this.rulesLangs) {
|
||||
const merged = this.mergeImportedSections(byLanguage![lang] ?? {}, this.sectionsByLang[lang]);
|
||||
if (lang === this.rulesLang || added === 0) added = Math.max(added, merged);
|
||||
}
|
||||
} else {
|
||||
added = this.mergeImportedSections(sections, this.sections);
|
||||
}
|
||||
if (added === 0) {
|
||||
this.importError = this.translate.instant('gameSystemEdit.importNoRules');
|
||||
return;
|
||||
@@ -208,6 +236,18 @@ export class GameSystemEditComponent implements OnInit {
|
||||
pages: pageCount,
|
||||
ocr
|
||||
});
|
||||
const translatedLangs = this.rulesLangs.filter(l => l !== sourceLanguage && (byLanguage?.[l] && Object.keys(byLanguage[l]).length));
|
||||
if (bilingual && sourceLanguage && translatedLangs.length) {
|
||||
this.importNote += ' ' + this.translate.instant('gameSystemEdit.importTranslated', {
|
||||
source: this.translate.instant('gameSystemEdit.lang.' + sourceLanguage),
|
||||
target: translatedLangs.map(l => this.translate.instant('gameSystemEdit.lang.' + l)).join(', ')
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Nombre de sections non vides d'une langue (badge de l'onglet). */
|
||||
sectionCount(lang: RulesLang): number {
|
||||
return this.sectionsByLang[lang].filter(s => s.title.trim() || s.content.trim()).length;
|
||||
}
|
||||
|
||||
private resetImportProgress(): void {
|
||||
@@ -221,20 +261,20 @@ export class GameSystemEditComponent implements OnInit {
|
||||
* (insensible à la casse) → contenu ajouté à la suite ; sinon nouvelle carte.
|
||||
* Retourne le nombre de sections effectivement intégrées.
|
||||
*/
|
||||
private mergeImportedSections(sections: Record<string, string>): number {
|
||||
private mergeImportedSections(sections: Record<string, string>, target: RuleSection[]): number {
|
||||
let count = 0;
|
||||
for (const [rawTitle, rawContent] of Object.entries(sections ?? {})) {
|
||||
const title = (rawTitle ?? '').trim();
|
||||
const content = (rawContent ?? '').trim();
|
||||
if (!title || !content) continue;
|
||||
const existing = this.sections.find(
|
||||
const existing = target.find(
|
||||
s => s.title.trim().toLowerCase() === title.toLowerCase()
|
||||
);
|
||||
if (existing) {
|
||||
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
|
||||
existing.collapsed = false;
|
||||
} else {
|
||||
this.sections.push({ title, content, collapsed: false });
|
||||
target.push({ title, content, collapsed: false });
|
||||
}
|
||||
count++;
|
||||
}
|
||||
@@ -300,7 +340,8 @@ export class GameSystemEditComponent implements OnInit {
|
||||
name: this.name.trim(),
|
||||
description: this.description.trim() || null,
|
||||
author: this.author.trim() || null,
|
||||
rulesMarkdown: this.serializeMarkdown(),
|
||||
rulesMarkdown: this.serializeMarkdown(this.sectionsByLang.fr),
|
||||
rulesMarkdownEn: this.serializeMarkdown(this.sectionsByLang.en),
|
||||
characterTemplate: this.characterTemplate,
|
||||
npcTemplate: this.npcTemplate,
|
||||
enemyTemplate: this.enemyTemplate,
|
||||
@@ -377,8 +418,8 @@ export class GameSystemEditComponent implements OnInit {
|
||||
}
|
||||
|
||||
/** Reconstruit le markdown à partir des sections (ignore les sections vides). */
|
||||
private serializeMarkdown(): string | null {
|
||||
const valid = this.sections.filter(s => s.title.trim() || s.content.trim());
|
||||
private serializeMarkdown(sections: RuleSection[]): string | null {
|
||||
const valid = sections.filter(s => s.title.trim() || s.content.trim());
|
||||
if (valid.length === 0) return null;
|
||||
return valid
|
||||
.map(s => {
|
||||
|
||||
@@ -12,6 +12,8 @@ export interface GameSystem {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
rulesMarkdown?: string | null;
|
||||
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||
rulesMarkdownEn?: string | null;
|
||||
characterTemplate?: TemplateField[];
|
||||
npcTemplate?: TemplateField[];
|
||||
enemyTemplate?: TemplateField[];
|
||||
@@ -43,7 +45,9 @@ export interface RulesImportResponse {
|
||||
export type RulesImportStreamEvent =
|
||||
| { type: 'progress'; current: number; total: number; pageCount: number; ocrPageCount: number; newSectionTitles: string[] }
|
||||
| { type: 'status'; message: string }
|
||||
| { type: 'done'; sections: Record<string, string>; pageCount: number; ocrPageCount: number }
|
||||
| { type: 'done'; sections: Record<string, string>; pageCount: number; ocrPageCount: number;
|
||||
/** Règles en deux langues : {fr|en → sections} ; langue d'origine du livre. */
|
||||
sectionsByLanguage?: Record<string, Record<string, string>>; sourceLanguage?: string | null }
|
||||
| { type: 'error'; message: string };
|
||||
|
||||
/** Payload de creation/mise a jour (sans id). */
|
||||
@@ -51,6 +55,8 @@ export interface GameSystemCreate {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
rulesMarkdown?: string | null;
|
||||
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||
rulesMarkdownEn?: string | null;
|
||||
characterTemplate?: TemplateField[];
|
||||
npcTemplate?: TemplateField[];
|
||||
enemyTemplate?: TemplateField[];
|
||||
|
||||
@@ -100,7 +100,12 @@ export class SessionRulesPanelComponent implements OnChanges, OnDestroy {
|
||||
private applySystem(gs: GameSystem | null): void {
|
||||
this.gameSystem = gs;
|
||||
if (!gs) { this.state = 'noSystem'; return; }
|
||||
this.sections = parseRuleSections(gs.rulesMarkdown, this.translate.instant('sessionRules.preamble'));
|
||||
// Règles dans la langue de l'interface, avec repli sur l'autre version si elle est vide.
|
||||
const english = this.translate.getCurrentLang() === 'en';
|
||||
const preferred = english ? gs.rulesMarkdownEn : gs.rulesMarkdown;
|
||||
const fallback = english ? gs.rulesMarkdown : gs.rulesMarkdownEn;
|
||||
const rules = preferred?.trim() ? preferred : fallback;
|
||||
this.sections = parseRuleSections(rules, this.translate.instant('sessionRules.preamble'));
|
||||
if (this.sections.length === 0) { this.state = 'noRules'; return; }
|
||||
this.pinned = this.readPins();
|
||||
this.opened = new Set(this.sections.filter(s => this.pinned.has(s.title)).map(s => s.id));
|
||||
|
||||
@@ -53,7 +53,14 @@
|
||||
"importFailedReason": "Import failed: {{reason}}",
|
||||
"importNoRules": "No usable rules could be extracted from this PDF (scan without OCR, or unrecognized content).",
|
||||
"importOcrSuffix": " (including {{count}} page(s) via OCR)",
|
||||
"importNote": "{{added}} section(s) suggested from {{pages}} page(s){{ocr}}. Review and adjust below before saving."
|
||||
"importNote": "{{added}} section(s) suggested from {{pages}} page(s){{ocr}}. Review and adjust below before saving.",
|
||||
"langTabs": "Rules language",
|
||||
"lang": {
|
||||
"fr": "Français",
|
||||
"en": "English"
|
||||
},
|
||||
"langHint": "Rules exist in two versions: the app and the AI use the one matching the interface language (or the other if it's empty). Importing a PDF fills both, whatever its language.",
|
||||
"importTranslated": "Book in {{source}}: the {{target}} version was translated automatically (proper names kept); review it in its tab."
|
||||
},
|
||||
"ollamaModelManager": {
|
||||
"installedModels": "Installed models",
|
||||
|
||||
@@ -53,7 +53,14 @@
|
||||
"importFailedReason": "Échec de l'import : {{reason}}",
|
||||
"importNoRules": "Aucune règle exploitable n'a été extraite de ce PDF (scan sans OCR, ou contenu non reconnu).",
|
||||
"importOcrSuffix": " (dont {{count}} page(s) via OCR)",
|
||||
"importNote": "{{added}} section(s) proposée(s) depuis {{pages}} page(s){{ocr}}. Relisez et ajustez ci-dessous avant d'enregistrer."
|
||||
"importNote": "{{added}} section(s) proposée(s) depuis {{pages}} page(s){{ocr}}. Relisez et ajustez ci-dessous avant d'enregistrer.",
|
||||
"langTabs": "Langue des règles",
|
||||
"lang": {
|
||||
"fr": "Français",
|
||||
"en": "English"
|
||||
},
|
||||
"langHint": "Les règles existent en deux versions : l'appli et l'IA utilisent celle de la langue de l'interface (ou l'autre si elle est vide). Importer un PDF remplit les deux, dans n'importe quelle langue.",
|
||||
"importTranslated": "Livre en {{source}} : version {{target}} traduite automatiquement (noms propres conservés), relis-la dans son onglet."
|
||||
},
|
||||
"ollamaModelManager": {
|
||||
"installedModels": "Modèles installés",
|
||||
|
||||
Reference in New Issue
Block a user