Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
007bcce8a7 | ||
|
|
a985bbd018 | ||
|
|
1c9ac524db | ||
|
|
abf66733fe | ||
|
|
763219412b |
@@ -9,6 +9,7 @@ from app.application.generate_page import GeneratePageUseCase
|
|||||||
from app.application.llm_json import load_json_object
|
from app.application.llm_json import load_json_object
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import conversation_title as title_prompts
|
from app.application.prompts import conversation_title as title_prompts
|
||||||
|
from app.application.prompts import guided_answers as guided_answers_prompts
|
||||||
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
from app.application.prompts import narrative_fields as narrative_fields_prompts
|
||||||
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
from app.application.prompts import scene_drafts as scene_drafts_prompts
|
||||||
from app.application.prompts import session_recap as session_recap_prompts
|
from app.application.prompts import session_recap as session_recap_prompts
|
||||||
@@ -290,3 +291,82 @@ async def generate_session_recap(
|
|||||||
if not recap:
|
if not recap:
|
||||||
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
raise HTTPException(status_code=502, detail="Le modèle n'a renvoyé aucun récit.")
|
||||||
return SessionRecapResponseDTO(recap=recap)
|
return SessionRecapResponseDTO(recap=recap)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Méthodes guidées : proposer des réponses à partir d'une idée (Mentor d'écriture) ----
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedOptionDTO(BaseModel):
|
||||||
|
"""Choix possible d'une question à choix : valeur technique + libellé lisible."""
|
||||||
|
|
||||||
|
value: str
|
||||||
|
label: str = Field(default="")
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedFieldDTO(BaseModel):
|
||||||
|
"""Une question de la méthode guidée (décrite par le front, relayée par le Core)."""
|
||||||
|
|
||||||
|
key: str
|
||||||
|
label: str = Field(default="")
|
||||||
|
hint: str = Field(default="")
|
||||||
|
step: str = Field(default="")
|
||||||
|
options: list[GuidedOptionDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedAnswersRequestDTO(BaseModel):
|
||||||
|
method_name: str = Field(default="")
|
||||||
|
method_principle: str = Field(default="")
|
||||||
|
idea: str = Field(default="")
|
||||||
|
context: str = Field(default="")
|
||||||
|
fields: list[GuidedFieldDTO] = Field(default_factory=list)
|
||||||
|
existing: dict[str, str] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class GuidedAnswersResponseDTO(BaseModel):
|
||||||
|
"""Une réponse proposée par clé (clés demandées uniquement, choix valides, non vides)."""
|
||||||
|
|
||||||
|
answers: dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/generate/guided-answers", response_model=GuidedAnswersResponseDTO)
|
||||||
|
async def generate_guided_answers(
|
||||||
|
body: GuidedAnswersRequestDTO,
|
||||||
|
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
|
) -> GuidedAnswersResponseDTO:
|
||||||
|
"""Propose des réponses aux questions d'une méthode guidée à partir de l'idée du MJ.
|
||||||
|
|
||||||
|
Rien n'est enregistré : le front remplit les champs vides, le MJ relit et corrige. Une
|
||||||
|
question à choix n'accepte qu'une des valeurs proposées ; le reste est ignoré.
|
||||||
|
"""
|
||||||
|
by_key = {f.key: f for f in body.fields if f.key}
|
||||||
|
prompt = guided_answers_prompts.guided_answers_prompt(
|
||||||
|
body.method_name, body.method_principle, body.idea, body.context,
|
||||||
|
[f.model_dump() for f in body.fields], body.existing, language)
|
||||||
|
try:
|
||||||
|
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.8)
|
||||||
|
except LLMProviderError as exc:
|
||||||
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
parsed, _ = load_json_object(raw)
|
||||||
|
if not isinstance(parsed, dict):
|
||||||
|
raise HTTPException(status_code=502, detail="Le modèle n'a pas renvoyé de réponses exploitables.")
|
||||||
|
return GuidedAnswersResponseDTO(answers=_clean_guided_answers(parsed.get("answers"), by_key))
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_guided_answers(raw: object, by_key: dict[str, GuidedFieldDTO]) -> dict[str, str]:
|
||||||
|
"""Garde les clés demandées, non vides ; une question à choix n'accepte qu'une valeur proposée."""
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return out
|
||||||
|
for key, value in raw.items():
|
||||||
|
field = by_key.get(str(key))
|
||||||
|
if field is None or not isinstance(value, (str, int, float)):
|
||||||
|
continue
|
||||||
|
text = str(value).strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
if field.options and text not in {o.value for o in field.options}:
|
||||||
|
continue
|
||||||
|
out[field.key] = text
|
||||||
|
return out
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ class RulesImportResponseDTO(BaseModel):
|
|||||||
sections: dict[str, str]
|
sections: dict[str, str]
|
||||||
page_count: int
|
page_count: int
|
||||||
ocr_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)
|
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||||
@@ -70,6 +73,8 @@ async def import_rules(
|
|||||||
sections=result.sections,
|
sections=result.sections,
|
||||||
page_count=result.page_count,
|
page_count=result.page_count,
|
||||||
ocr_page_count=result.ocr_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")
|
@router.post("/import/campaign/stream")
|
||||||
async def import_campaign_stream(
|
async def import_campaign_stream(
|
||||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||||
|
language: Annotated[str, Depends(get_user_language)],
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
) -> StreamingResponse:
|
) -> StreamingResponse:
|
||||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
"""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})
|
yield sse_event("error", {"message": upload_error})
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
async for ev in use_case.stream(content):
|
async for ev in use_case.stream(content, language=language):
|
||||||
event_type = ev.pop("type")
|
event_type = ev.pop("type")
|
||||||
yield sse_event(event_type, ev)
|
yield sse_event(event_type, ev)
|
||||||
except PdfExtractionError as exc:
|
except PdfExtractionError as exc:
|
||||||
|
|||||||
@@ -361,7 +361,7 @@ class ImportCampaignUseCase:
|
|||||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||||
self._map_concurrency = max(1, map_concurrency)
|
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."""
|
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||||
doc = self._extractor.extract(pdf_bytes)
|
doc = self._extractor.extract(pdf_bytes)
|
||||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
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):
|
for start in range(0, total, self._map_concurrency):
|
||||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||||
results = await asyncio.gather(*(
|
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 i, c in wave
|
||||||
))
|
))
|
||||||
for res in results:
|
for res in results:
|
||||||
@@ -386,7 +386,7 @@ class ImportCampaignUseCase:
|
|||||||
npcs=merger.npcs(),
|
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.
|
"""Variante streamée : yield des évènements d'avancement.
|
||||||
|
|
||||||
{"type":"extracting"}, puis {"type":"start", page_count, ocr_page_count,
|
{"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):
|
for start in range(0, total, self._map_concurrency):
|
||||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||||
gathered = asyncio.gather(
|
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),
|
for i, c in wave),
|
||||||
return_exceptions=True,
|
return_exceptions=True,
|
||||||
)
|
)
|
||||||
@@ -553,21 +553,23 @@ class ImportCampaignUseCase:
|
|||||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||||
|
|
||||||
async def _map_chunk(
|
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:
|
) -> dict:
|
||||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||||
return await self._extract_payload(
|
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(
|
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:
|
) -> dict:
|
||||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
"""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
|
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é)."""
|
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 ""
|
toc_section = prompts.TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||||
prompt = (
|
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
|
+ toc_section
|
||||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||||
"Renvoie maintenant le JSON de l'arborescence."
|
"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} : "
|
f"Le modèle est trop lent sur le morceau {index + 1} : "
|
||||||
"re-découpage en 2 moitiés plus digestes…")
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
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(
|
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"]}
|
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||||
payload, truncated = self._parse_payload(raw, index=index)
|
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} : "
|
f"Réponse du modèle coupée sur le morceau {index + 1} : "
|
||||||
"re-découpage en 2 moitiés plus digestes…")
|
"re-découpage en 2 moitiés plus digestes…")
|
||||||
a = await self._extract_payload(
|
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(
|
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"]}
|
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||||
if truncated:
|
if truncated:
|
||||||
logger.warning(
|
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_json import load_json_object, looks_like_truncated_json
|
||||||
from app.application.llm_retry import generate_with_retry
|
from app.application.llm_retry import generate_with_retry
|
||||||
from app.application.prompts import import_rules as prompts
|
from app.application.prompts import import_rules as prompts
|
||||||
|
from app.application.rules_translation import RulesTranslator, detect_language, other_languages, unique_titles
|
||||||
from app.application.streaming import with_heartbeat
|
from app.application.streaming import with_heartbeat
|
||||||
from app.core.language import DEFAULT as _DEFAULT_LANG, language_name
|
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:
|
class _SectionMerger:
|
||||||
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
"""Fusionne les sections issues des différents morceaux, ordre préservé.
|
||||||
|
|
||||||
@@ -250,10 +254,25 @@ class ImportRulesUseCase:
|
|||||||
merger = _SectionMerger()
|
merger = _SectionMerger()
|
||||||
for i, chunk in enumerate(chunks):
|
for i, chunk in enumerate(chunks):
|
||||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks), language=language))
|
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(
|
return RulesImportResult(
|
||||||
sections=merger.result(),
|
sections=sections,
|
||||||
page_count=doc.page_count,
|
page_count=doc.page_count,
|
||||||
ocr_page_count=doc.ocr_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):
|
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."}
|
"de contexte (num_ctx) ou essayez un autre modèle."}
|
||||||
return
|
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 {
|
yield {
|
||||||
"type": "done",
|
"type": "done",
|
||||||
"sections": sections,
|
"sections": sections,
|
||||||
|
"sections_by_language": by_language,
|
||||||
|
"source_language": source,
|
||||||
"page_count": doc.page_count,
|
"page_count": doc.page_count,
|
||||||
"ocr_page_count": doc.ocr_page_count,
|
"ocr_page_count": doc.ocr_page_count,
|
||||||
"skipped": skipped,
|
"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 -----------------------------------------
|
# --- MAP : un morceau → sections -----------------------------------------
|
||||||
|
|
||||||
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
async def _map_chunk(self, chunk: str, *, index: int, total: int,
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Prompt des méthodes guidées (Mentor d'écriture) : à partir de l'idée de départ du MJ,
|
||||||
|
proposer des réponses aux questions de la méthode (Donjon en 5 salles, Enquête en nœuds,
|
||||||
|
Plan du méchant…).
|
||||||
|
|
||||||
|
Générique : le front décrit la méthode (nom, principe) et ses questions (clé, libellé,
|
||||||
|
aide, étape, choix possibles) ; ce module ne fait que formuler le prompt. Les réponses
|
||||||
|
déjà écrites par le MJ sont fournies pour rester cohérent et ne jamais être contredites.
|
||||||
|
"""
|
||||||
|
from app.core.language import language_name
|
||||||
|
|
||||||
|
|
||||||
|
def _field_line(field: dict) -> str:
|
||||||
|
key = str(field.get("key") or "").strip()
|
||||||
|
label = str(field.get("label") or key).strip()
|
||||||
|
hint = str(field.get("hint") or "").strip()
|
||||||
|
step = str(field.get("step") or "").strip()
|
||||||
|
line = f'- "{key}"'
|
||||||
|
if step:
|
||||||
|
line += f" [{step}]"
|
||||||
|
line += f" : {label}"
|
||||||
|
if hint:
|
||||||
|
line += f" — {hint}"
|
||||||
|
options = field.get("options") or []
|
||||||
|
if options:
|
||||||
|
values = ", ".join(f'"{o.get("value")}" ({o.get("label")})' for o in options if o.get("value"))
|
||||||
|
line += f" — UNE valeur parmi : {values}"
|
||||||
|
return line
|
||||||
|
|
||||||
|
|
||||||
|
def guided_answers_prompt(method_name: str, method_principle: str, idea: str, context: str,
|
||||||
|
fields: list[dict], existing: dict[str, str], language: str) -> str:
|
||||||
|
"""Construit le prompt. `fields` = [{key, label, hint, step, options}] ; `existing` = réponses du MJ."""
|
||||||
|
fields_list = "\n".join(_field_line(f) for f in fields or [] if f.get("key"))
|
||||||
|
existing_lines = "\n".join(
|
||||||
|
f'- "{k}" : {v.strip()}' for k, v in (existing or {}).items() if isinstance(v, str) and v.strip())
|
||||||
|
existing_block = (
|
||||||
|
"\nCe que le MJ a DÉJÀ écrit (à respecter, ne le contredis jamais) :\n"
|
||||||
|
f"{existing_lines}\n" if existing_lines else ""
|
||||||
|
)
|
||||||
|
context_block = f"\nContexte de la campagne :\n{context.strip()}\n" if context and context.strip() else ""
|
||||||
|
principle = f" Principe : {method_principle.strip()}" if method_principle and method_principle.strip() else ""
|
||||||
|
return (
|
||||||
|
"Tu es un auteur expérimenté de scénarios de jeu de rôle, qui aide un MJ à écrire son aventure "
|
||||||
|
f"avec la méthode « {method_name.strip() or 'guidée'} ».{principle}\n\n"
|
||||||
|
f"Idée de départ du MJ : {idea.strip() or '(aucune : propose une aventure originale)'}\n"
|
||||||
|
f"{context_block}{existing_block}\n"
|
||||||
|
"Questions de la méthode auxquelles tu dois répondre (n'utilise QUE ces clés) :\n"
|
||||||
|
f"{fields_list}\n\n"
|
||||||
|
"Règles IMPÉRATIVES :\n"
|
||||||
|
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||||
|
'- Format exact : {"answers": {"cle": "réponse", ...}}\n'
|
||||||
|
"- N'inclus QUE des clés de la liste. Pour une question à choix, renvoie EXACTEMENT une des "
|
||||||
|
"valeurs proposées.\n"
|
||||||
|
"- Développe l'idée du MJ : toutes les réponses forment UNE aventure cohérente, concrète et jouable "
|
||||||
|
"(noms, lieux, motivations précises ; pas de généralités).\n"
|
||||||
|
"- Sois concis : un nom en quelques mots, une description en 2 à 4 phrases.\n"
|
||||||
|
"- Donne toujours aux joueurs de vrais choix et plusieurs façons de progresser.\n"
|
||||||
|
f"- Rédige les réponses en {language_name(language)}.\n"
|
||||||
|
"Renvoie maintenant le JSON."
|
||||||
|
)
|
||||||
@@ -1,7 +1,29 @@
|
|||||||
"""Prompts de l'import de campagne PDF (cf. import_campaign.py)."""
|
"""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.
|
# Nom de l'arc unique quand le livre n'est pas découpé en actes/parties.
|
||||||
DEFAULT_ARC_NAME = "Aventure principale"
|
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.
|
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).
|
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]
|
sections: dict[str, str]
|
||||||
page_count: int
|
page_count: int
|
||||||
ocr_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:
|
def to_markdown(self) -> str:
|
||||||
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
"""Assemble les sections en un markdown monolithique (## titre + contenu).
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Méthodes guidées : prompt de propositions et nettoyage des réponses du modèle."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.api.routers.generation import GuidedFieldDTO, GuidedOptionDTO, _clean_guided_answers
|
||||||
|
from app.application.prompts.guided_answers import guided_answers_prompt
|
||||||
|
|
||||||
|
|
||||||
|
def _fields() -> dict[str, GuidedFieldDTO]:
|
||||||
|
return {
|
||||||
|
"title": GuidedFieldDTO(key="title", label="Nom de l'enquête"),
|
||||||
|
"node1.nature": GuidedFieldDTO(key="node1.nature", label="Genre de scène", options=[
|
||||||
|
GuidedOptionDTO(value="location", label="Un lieu"), GuidedOptionDTO(value="npc", label="Une personne")]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_contains_idea_questions_choices_existing_answers_and_language():
|
||||||
|
prompt = guided_answers_prompt(
|
||||||
|
"Enquête en nœuds", "Trois pistes qui se recoupent.", "Une tour qui se rallume", "Campagne : Valfroide",
|
||||||
|
[{"key": "title", "label": "Nom de l'enquête", "hint": "Ex. : L'héritage", "step": "Le mystère"},
|
||||||
|
{"key": "node1.nature", "label": "Genre", "options": [{"value": "location", "label": "Un lieu"}]}],
|
||||||
|
{"truth": "Le notaire est coupable", "empty": " "}, "en")
|
||||||
|
|
||||||
|
assert "Une tour qui se rallume" in prompt
|
||||||
|
assert '"title" [Le mystère] : Nom de l\'enquête — Ex. : L\'héritage' in prompt
|
||||||
|
assert 'UNE valeur parmi : "location" (Un lieu)' in prompt
|
||||||
|
assert "Le notaire est coupable" in prompt
|
||||||
|
assert '"empty"' not in prompt, "une réponse vide n'est pas rappelée"
|
||||||
|
assert "Campagne : Valfroide" in prompt
|
||||||
|
assert "anglais" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_without_idea_asks_for_an_original_adventure():
|
||||||
|
prompt = guided_answers_prompt("Plan du méchant", "", " ", "", [{"key": "villain", "label": "Adversaire"}], {}, "fr")
|
||||||
|
assert "propose une aventure originale" in prompt
|
||||||
|
assert "français" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_keeps_requested_keys_and_valid_choices_only():
|
||||||
|
out = _clean_guided_answers({
|
||||||
|
"title": " L'héritage empoisonné ",
|
||||||
|
"node1.nature": "npc",
|
||||||
|
"unknown": "ignorée",
|
||||||
|
"empty": "",
|
||||||
|
}, _fields())
|
||||||
|
assert out == {"title": "L'héritage empoisonné", "node1.nature": "npc"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_clean_rejects_an_invalid_choice_and_non_text_values():
|
||||||
|
out = _clean_guided_answers({"node1.nature": "dragon", "title": ["liste"]}, _fields())
|
||||||
|
assert out == {}
|
||||||
|
assert _clean_guided_answers("pas un objet", _fields()) == {}
|
||||||
@@ -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",
|
monkeypatch.setattr("app.application.import_rules.chunk_text",
|
||||||
lambda *a, **k: ["AAA premier", "BBB second"])
|
lambda *a, **k: ["AAA premier", "BBB second"])
|
||||||
llm = ContentLLM([
|
llm = ContentLLM([
|
||||||
|
("Traduis ces titres", '{"titles": {"Magie": "Magic"}}'),
|
||||||
|
("Traduis cet extrait", "spells"),
|
||||||
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
("AAA premier", LLMProviderError("HTTP 503 saturé")),
|
||||||
("BBB second", '{"Magie":"sorts"}'),
|
("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["type"] == "done"
|
||||||
assert done["sections"] == {"Magie": "sorts"}
|
assert done["sections"] == {"Magie": "sorts"}
|
||||||
assert done["skipped"] == 1
|
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):
|
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()))
|
uc = ImportCampaignUseCase(ScriptedLLM([LLMProviderError("502")]), FakeExtractor(_doc()))
|
||||||
events = [e async for e in uc.stream(b"pdf")]
|
events = [e async for e in uc.stream(b"pdf")]
|
||||||
assert events[-1]["type"] == "error"
|
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"}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IA des méthodes guidées (Mentor d'écriture) : propose des réponses aux questions d'une
|
||||||
|
* méthode à partir de l'idée de départ du MJ et de la campagne. Rien n'est enregistré : le
|
||||||
|
* front remplit les champs vides et le MJ relit, corrige ou relance.
|
||||||
|
*
|
||||||
|
* <p>Garde-fous : nombre de questions et longueur des textes bornés (le prompt reste
|
||||||
|
* raisonnable) ; en retour, seules les clés demandées sont gardées, et une question à choix
|
||||||
|
* n'accepte qu'une des valeurs proposées.</p>
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class GuidedAssistService {
|
||||||
|
|
||||||
|
static final int MAX_QUESTIONS = 80;
|
||||||
|
static final int MAX_TEXT = 4_000;
|
||||||
|
|
||||||
|
private final GuidedMethodAssistant assistant;
|
||||||
|
private final CampaignContextFormatter contextFormatter;
|
||||||
|
|
||||||
|
public GuidedAssistService(GuidedMethodAssistant assistant, CampaignContextFormatter contextFormatter) {
|
||||||
|
this.assistant = assistant;
|
||||||
|
this.contextFormatter = contextFormatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Demande à proposer des réponses. @throws IllegalArgumentException aucune question valide */
|
||||||
|
public Map<String, String> suggest(String campaignId, String methodName, String principle, String idea,
|
||||||
|
List<Question> questions, Map<String, String> existing) {
|
||||||
|
List<Question> valid = questions == null ? List.of() : questions.stream()
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.filter(q -> q.key() != null && !q.key().isBlank())
|
||||||
|
.limit(MAX_QUESTIONS)
|
||||||
|
.toList();
|
||||||
|
if (valid.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("Aucune question à laquelle répondre.");
|
||||||
|
}
|
||||||
|
Map<String, String> answers = assistant.answer(cap(methodName), cap(principle), cap(idea),
|
||||||
|
contextFormatter.format(campaignId), valid, capAll(existing));
|
||||||
|
return keepValid(answers, valid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clés demandées uniquement, valeurs non vides ; choix limités aux valeurs proposées. */
|
||||||
|
static Map<String, String> keepValid(Map<String, String> answers, List<Question> questions) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (answers == null) return out;
|
||||||
|
Map<String, Question> byKey = questions.stream()
|
||||||
|
.collect(Collectors.toMap(Question::key, q -> q, (a, b) -> a, LinkedHashMap::new));
|
||||||
|
for (Map.Entry<String, String> e : answers.entrySet()) {
|
||||||
|
Question q = byKey.get(e.getKey());
|
||||||
|
String value = e.getValue() == null ? "" : e.getValue().trim();
|
||||||
|
if (q == null || value.isEmpty()) continue;
|
||||||
|
if (q.options() != null && !q.options().isEmpty()) {
|
||||||
|
Set<String> allowed = q.options().stream().map(Choice::value).collect(Collectors.toSet());
|
||||||
|
if (!allowed.contains(value)) continue;
|
||||||
|
}
|
||||||
|
out.put(q.key(), cap(value));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, String> capAll(Map<String, String> existing) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (existing == null) return out;
|
||||||
|
existing.forEach((k, v) -> {
|
||||||
|
if (k != null && v != null && !v.isBlank()) out.put(k, cap(v.trim()));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String cap(String s) {
|
||||||
|
if (s == null) return "";
|
||||||
|
return s.length() > MAX_TEXT ? s.substring(0, MAX_TEXT) : s;
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-2
@@ -1,6 +1,7 @@
|
|||||||
package com.loremind.application.gamesystemcontext;
|
package com.loremind.application.gamesystemcontext;
|
||||||
|
|
||||||
import com.loremind.domain.gamesystemcontext.GameSystem;
|
import com.loremind.domain.gamesystemcontext.GameSystem;
|
||||||
|
import com.loremind.domain.shared.ports.CurrentLanguage;
|
||||||
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
import com.loremind.domain.gamesystemcontext.GenerationIntent;
|
||||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||||
import com.loremind.domain.generationcontext.GameSystemContext;
|
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 static final Pattern H2_HEADER = Pattern.compile("(?m)^##\\s+(\\S.*)$");
|
||||||
|
|
||||||
private final GameSystemRepository gameSystemRepository;
|
private final GameSystemRepository gameSystemRepository;
|
||||||
|
private final CurrentLanguage currentLanguage;
|
||||||
|
|
||||||
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository) {
|
public GameSystemContextBuilder(GameSystemRepository gameSystemRepository, CurrentLanguage currentLanguage) {
|
||||||
this.gameSystemRepository = gameSystemRepository;
|
this.gameSystemRepository = gameSystemRepository;
|
||||||
|
this.currentLanguage = currentLanguage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
public Optional<GameSystemContext> buildOptional(String gameSystemId, GenerationIntent intent) {
|
||||||
@@ -48,7 +51,8 @@ public class GameSystemContextBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private GameSystemContext build(GameSystem gs, GenerationIntent intent) {
|
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);
|
Map<String, String> filtered = filterByIntent(allSections, intent);
|
||||||
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
return new GameSystemContext(gs.getName(), gs.getDescription(), filtered);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ public class GameSystemService {
|
|||||||
String name,
|
String name,
|
||||||
String description,
|
String description,
|
||||||
String rulesMarkdown,
|
String rulesMarkdown,
|
||||||
|
String rulesMarkdownEn,
|
||||||
List<TemplateField> characterTemplate,
|
List<TemplateField> characterTemplate,
|
||||||
List<TemplateField> npcTemplate,
|
List<TemplateField> npcTemplate,
|
||||||
List<TemplateField> enemyTemplate,
|
List<TemplateField> enemyTemplate,
|
||||||
@@ -72,6 +73,7 @@ public class GameSystemService {
|
|||||||
.name(data.name())
|
.name(data.name())
|
||||||
.description(data.description())
|
.description(data.description())
|
||||||
.rulesMarkdown(data.rulesMarkdown())
|
.rulesMarkdown(data.rulesMarkdown())
|
||||||
|
.rulesMarkdownEn(data.rulesMarkdownEn())
|
||||||
.foundryActorType(normalize(data.foundryActorType()))
|
.foundryActorType(normalize(data.foundryActorType()))
|
||||||
.author(normalize(data.author()))
|
.author(normalize(data.author()))
|
||||||
.isPublic(data.isPublic())
|
.isPublic(data.isPublic())
|
||||||
@@ -96,6 +98,7 @@ public class GameSystemService {
|
|||||||
existing.setName(data.name());
|
existing.setName(data.name());
|
||||||
existing.setDescription(data.description());
|
existing.setDescription(data.description());
|
||||||
existing.setRulesMarkdown(data.rulesMarkdown());
|
existing.setRulesMarkdown(data.rulesMarkdown());
|
||||||
|
existing.setRulesMarkdownEn(data.rulesMarkdownEn());
|
||||||
existing.replaceCharacterTemplate(data.characterTemplate());
|
existing.replaceCharacterTemplate(data.characterTemplate());
|
||||||
existing.replaceNpcTemplate(data.npcTemplate());
|
existing.replaceNpcTemplate(data.npcTemplate());
|
||||||
existing.replaceEnemyTemplate(data.enemyTemplate());
|
existing.replaceEnemyTemplate(data.enemyTemplate());
|
||||||
|
|||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.loremind.domain.campaigncontext.ports;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port de sortie (Mentor d'écriture) : demande à l'IA de proposer des réponses aux
|
||||||
|
* questions d'une méthode guidée à partir de l'idée de départ du MJ. Implémenté par un
|
||||||
|
* client du Brain. One-shot ; rien n'est enregistré (le MJ relit et corrige dans l'assistant).
|
||||||
|
*/
|
||||||
|
public interface GuidedMethodAssistant {
|
||||||
|
|
||||||
|
/** Choix possible d'une question à choix : valeur technique + libellé lisible. */
|
||||||
|
record Choice(String value, String label) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Une question de la méthode, décrite par le front (libellés dans la langue du MJ).
|
||||||
|
*
|
||||||
|
* @param key clé de réponse (ex. {@code node1.name})
|
||||||
|
* @param label libellé de la question
|
||||||
|
* @param hint aide (exemple de réponse attendue), optionnelle
|
||||||
|
* @param step titre de l'étape, optionnel
|
||||||
|
* @param options choix possibles (vide pour une question libre)
|
||||||
|
*/
|
||||||
|
record Question(String key, String label, String hint, String step, List<Choice> options) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param methodName nom de la méthode (« Enquête en nœuds »…)
|
||||||
|
* @param principle principe de la méthode, en une phrase
|
||||||
|
* @param idea idée de départ du MJ (peut être vide)
|
||||||
|
* @param context contexte de la campagne (nom, description, système)
|
||||||
|
* @param questions questions auxquelles répondre
|
||||||
|
* @param existing réponses déjà écrites par le MJ (à respecter)
|
||||||
|
* @return une réponse proposée par clé (clés demandées uniquement)
|
||||||
|
*/
|
||||||
|
Map<String, String> answer(String methodName, String principle, String idea, String context,
|
||||||
|
List<Question> questions, Map<String, String> existing);
|
||||||
|
}
|
||||||
@@ -35,6 +35,9 @@ public class GameSystem {
|
|||||||
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
/** Markdown monolithique. Sections découpées par titres H2 (## Combat, ## Classes, etc.). */
|
||||||
private String rulesMarkdown;
|
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.
|
* 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
|
* 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;
|
if (a == null || b == null) return a == null && b == null;
|
||||||
return a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT));
|
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(
|
public record RulesImportResult(
|
||||||
Map<String, String> sections,
|
Map<String, String> sections,
|
||||||
int pageCount,
|
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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.loremind.infrastructure.ai;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.ResourceAccessException;
|
||||||
|
import org.springframework.web.client.RestClientResponseException;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter de sortie : propositions de réponses aux méthodes guidées via le Brain
|
||||||
|
* ({@code POST /generate/guided-answers}, one-shot). La langue de l'interface est relayée par
|
||||||
|
* l'intercepteur du RestTemplate (en-tête {@code X-User-Language}).
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BrainGuidedAnswersClient implements GuidedMethodAssistant {
|
||||||
|
|
||||||
|
private static final String PATH = "/generate/guided-answers";
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public BrainGuidedAnswersClient(RestTemplate restTemplate, @Value("${brain.base-url}") String baseUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, String> answer(String methodName, String principle, String idea, String context,
|
||||||
|
List<Question> questions, Map<String, String> existing) {
|
||||||
|
Map<String, Object> req = new LinkedHashMap<>();
|
||||||
|
req.put("method_name", nz(methodName));
|
||||||
|
req.put("method_principle", nz(principle));
|
||||||
|
req.put("idea", nz(idea));
|
||||||
|
req.put("context", nz(context));
|
||||||
|
req.put("fields", toPayload(questions));
|
||||||
|
req.put("existing", existing == null ? Map.of() : existing);
|
||||||
|
return parse(call(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<Map<String, Object>> toPayload(List<Question> questions) {
|
||||||
|
List<Map<String, Object>> out = new ArrayList<>();
|
||||||
|
for (Question q : questions) {
|
||||||
|
Map<String, Object> f = new LinkedHashMap<>();
|
||||||
|
f.put("key", q.key());
|
||||||
|
f.put("label", nz(q.label()).isEmpty() ? q.key() : q.label());
|
||||||
|
f.put("hint", nz(q.hint()));
|
||||||
|
f.put("step", nz(q.step()));
|
||||||
|
List<Map<String, String>> options = new ArrayList<>();
|
||||||
|
if (q.options() != null) {
|
||||||
|
for (Choice c : q.options()) {
|
||||||
|
if (c != null && c.value() != null) options.add(Map.of("value", c.value(), "label", nz(c.label())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.put("options", options);
|
||||||
|
out.add(f);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> call(Map<String, Object> req) {
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
Map<String, Object> resp;
|
||||||
|
try {
|
||||||
|
resp = restTemplate.postForObject(baseUrl + PATH, new HttpEntity<>(req, headers), Map.class);
|
||||||
|
} catch (ResourceAccessException e) {
|
||||||
|
throw new NarrativeAssistException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||||
|
} catch (RestClientResponseException e) {
|
||||||
|
throw new NarrativeAssistException(
|
||||||
|
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new NarrativeAssistException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||||
|
}
|
||||||
|
if (resp == null) throw new NarrativeAssistException("Le Brain a renvoyé une réponse vide.");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, String> parse(Map<String, Object> resp) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>();
|
||||||
|
if (resp.get("answers") instanceof Map<?, ?> m) {
|
||||||
|
m.forEach((k, v) -> {
|
||||||
|
if (k != null && v != null) out.put(k.toString(), v.toString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String nz(String s) {
|
||||||
|
return s == null ? "" : s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,7 +106,9 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
return new RulesImportResult(
|
return new RulesImportResult(
|
||||||
Map.copyOf(response.getSections()),
|
Map.copyOf(response.getSections()),
|
||||||
response.getPageCount(),
|
response.getPageCount(),
|
||||||
response.getOcrPageCount());
|
response.getOcrPageCount(),
|
||||||
|
response.getSectionsByLanguage() != null ? response.getSectionsByLanguage() : Map.of(),
|
||||||
|
response.getSourceLanguage());
|
||||||
} catch (ResourceAccessException e) {
|
} catch (ResourceAccessException e) {
|
||||||
throw new RulesImportException(
|
throw new RulesImportException(
|
||||||
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
"Le Brain est injoignable (timeout ou service arrêté).", e);
|
||||||
@@ -218,12 +220,23 @@ public class BrainRulesImportClient implements RulesPdfImporter {
|
|||||||
callbacks.onDone().accept(new RulesImportResult(
|
callbacks.onDone().accept(new RulesImportResult(
|
||||||
toStringMap(node.path("sections")),
|
toStringMap(node.path("sections")),
|
||||||
node.path("page_count").asInt(),
|
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 -------------------------------------------------------------
|
// --- 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) {
|
private List<String> toStringList(JsonNode array) {
|
||||||
List<String> out = new ArrayList<>();
|
List<String> out = new ArrayList<>();
|
||||||
if (array != null && array.isArray()) {
|
if (array != null && array.isArray()) {
|
||||||
|
|||||||
@@ -23,4 +23,11 @@ class BrainRulesImportResponse {
|
|||||||
|
|
||||||
@JsonProperty("ocr_page_count")
|
@JsonProperty("ocr_page_count")
|
||||||
private int ocrPageCount;
|
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")
|
@Column(name = "rules_markdown", columnDefinition = "TEXT")
|
||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
|
|
||||||
|
@Column(name = "rules_markdown_en", columnDefinition = "TEXT")
|
||||||
|
private String rulesMarkdownEn;
|
||||||
|
|
||||||
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
/** Template PJ serialise en JSON via {@link TemplateFieldListJsonConverter}. */
|
||||||
@Convert(converter = TemplateFieldListJsonConverter.class)
|
@Convert(converter = TemplateFieldListJsonConverter.class)
|
||||||
@Column(name = "character_template", columnDefinition = "TEXT")
|
@Column(name = "character_template", columnDefinition = "TEXT")
|
||||||
|
|||||||
+2
@@ -60,6 +60,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.name(e.getName())
|
.name(e.getName())
|
||||||
.description(e.getDescription())
|
.description(e.getDescription())
|
||||||
.rulesMarkdown(e.getRulesMarkdown())
|
.rulesMarkdown(e.getRulesMarkdown())
|
||||||
|
.rulesMarkdownEn(e.getRulesMarkdownEn())
|
||||||
.characterTemplate(e.getCharacterTemplate() != null
|
.characterTemplate(e.getCharacterTemplate() != null
|
||||||
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
? new java.util.ArrayList<>(e.getCharacterTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
@@ -84,6 +85,7 @@ public class PostgresGameSystemRepository implements GameSystemRepository {
|
|||||||
.name(g.getName())
|
.name(g.getName())
|
||||||
.description(g.getDescription())
|
.description(g.getDescription())
|
||||||
.rulesMarkdown(g.getRulesMarkdown())
|
.rulesMarkdown(g.getRulesMarkdown())
|
||||||
|
.rulesMarkdownEn(g.getRulesMarkdownEn())
|
||||||
.characterTemplate(g.getCharacterTemplate() != null
|
.characterTemplate(g.getCharacterTemplate() != null
|
||||||
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
? new java.util.ArrayList<>(g.getCharacterTemplate())
|
||||||
: new java.util.ArrayList<>())
|
: new java.util.ArrayList<>())
|
||||||
|
|||||||
@@ -577,7 +577,8 @@ public class ExportService {
|
|||||||
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
private ContentExport.GameSystemDto toGameSystemDto(GameSystemJpaEntity e) {
|
||||||
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
return new ContentExport.GameSystemDto(e.getId(), e.getName(), e.getDescription(),
|
||||||
e.getRulesMarkdown(), e.getCharacterTemplate(), e.getNpcTemplate(),
|
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) {
|
private ContentExport.LoreDto toLoreDto(LoreJpaEntity e) {
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ class LoreContentInserter {
|
|||||||
e.setName(d.name());
|
e.setName(d.name());
|
||||||
e.setDescription(d.description());
|
e.setDescription(d.description());
|
||||||
e.setRulesMarkdown(d.rulesMarkdown());
|
e.setRulesMarkdown(d.rulesMarkdown());
|
||||||
|
e.setRulesMarkdownEn(d.rulesMarkdownEn());
|
||||||
e.setCharacterTemplate(d.characterTemplate());
|
e.setCharacterTemplate(d.characterTemplate());
|
||||||
e.setNpcTemplate(d.npcTemplate());
|
e.setNpcTemplate(d.npcTemplate());
|
||||||
e.setEnemyTemplate(d.enemyTemplate());
|
e.setEnemyTemplate(d.enemyTemplate());
|
||||||
|
|||||||
@@ -77,7 +77,9 @@ public record ContentExport(
|
|||||||
List<TemplateField> enemyTemplate,
|
List<TemplateField> enemyTemplate,
|
||||||
String foundryActorType,
|
String foundryActorType,
|
||||||
String author,
|
String author,
|
||||||
boolean isPublic
|
boolean isPublic,
|
||||||
|
/** Version anglaise des règles ; absente des bundles antérieurs (null). */
|
||||||
|
String rulesMarkdownEn
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public record LoreDto(
|
public record LoreDto(
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.loremind.domain.campaigncontext.bestiary.NpcStory;
|
|||||||
import com.loremind.domain.campaigncontext.quest.NodeType;
|
import com.loremind.domain.campaigncontext.quest.NodeType;
|
||||||
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
import com.loremind.domain.campaigncontext.quest.Prerequisite;
|
||||||
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
import com.loremind.domain.campaigncontext.quest.QuestNodeRef;
|
||||||
|
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||||
import com.loremind.domain.campaigncontext.structure.Room;
|
import com.loremind.domain.campaigncontext.structure.Room;
|
||||||
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
import com.loremind.domain.campaigncontext.structure.RoomBranch;
|
||||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||||
@@ -540,11 +541,12 @@ public class PdfExportService {
|
|||||||
List<ArcJpaEntity> arcs = st.visibleArcs;
|
List<ArcJpaEntity> arcs = st.visibleArcs;
|
||||||
if (arcs.isEmpty()) return;
|
if (arcs.isEmpty()) return;
|
||||||
|
|
||||||
// Mode plat (miroir de l'UI Niveau 0) : 1 arc d'UN SEUL chapitre → on masque les
|
// Mode plat (miroir de l'UI Niveau 0) : 1 arc linéaire d'UN SEUL chapitre, tous deux
|
||||||
// niveaux Arc/Chapitre et on présente les scènes À PLAT (cohérent avec la sidebar).
|
// VIDES (créés d'office) → on masque les niveaux Arc/Chapitre et on présente les
|
||||||
if (arcs.size() == 1) {
|
// scènes À PLAT. Un arc ou un chapitre écrit (méthode guidée…) garde ses en-têtes.
|
||||||
|
if (arcs.size() == 1 && arcs.get(0).getType() != ArcType.HUB) {
|
||||||
List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId());
|
List<ChapterJpaEntity> only = st.chaptersByArc.get(arcs.get(0).getId());
|
||||||
if (only.size() == 1) {
|
if (only.size() == 1 && isBare(arcs.get(0)) && isBare(only.get(0))) {
|
||||||
narrativeFlat(ctx, st, arcs.get(0), only.get(0));
|
narrativeFlat(ctx, st, arcs.get(0), only.get(0));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -561,6 +563,28 @@ public class PdfExportService {
|
|||||||
ctx.endColumns();
|
ctx.endColumns();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'ecriture dans l'arc (son nom ne compte pas : « Arc principal » est cree d'office). */
|
||||||
|
static boolean isBare(ArcJpaEntity arc) {
|
||||||
|
return allBlank(arc.getDescription(), arc.getThemes(), arc.getStakes(), arc.getRewards(),
|
||||||
|
arc.getResolution(), arc.getGmNotes(), arc.getHiddenTruth(), arc.getHooks())
|
||||||
|
&& isEmpty(arc.getIllustrationImageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'ecriture dans le chapitre (son nom ne compte pas : « Chapitre 1 » est cree d'office). */
|
||||||
|
static boolean isBare(ChapterJpaEntity ch) {
|
||||||
|
return allBlank(ch.getDescription(), ch.getPlayerObjectives(), ch.getNarrativeStakes(), ch.getGmNotes())
|
||||||
|
&& isEmpty(ch.getIllustrationImageIds());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean allBlank(String... values) {
|
||||||
|
for (String v : values) if (notBlank(v)) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isEmpty(List<String> list) {
|
||||||
|
return list == null || list.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
/** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */
|
/** Arborescence des signets Arc -> Chapitre pour la partie narrative complete (mode non plat). */
|
||||||
private void narrativeBookmarks(Ctx ctx, Structure st, List<ArcJpaEntity> arcs) {
|
private void narrativeBookmarks(Ctx ctx, Structure st, List<ArcJpaEntity> arcs) {
|
||||||
StringBuilder arcBms = new StringBuilder();
|
StringBuilder arcBms = new StringBuilder();
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.core.task.TaskDecorator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Langue de l'utilisateur dans les tâches de fond : Spring Boot applique ce décorateur unique
|
||||||
|
* à l'exécuteur auto-configuré ({@code applicationTaskExecutor}) utilisé par les flux SSE.
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class UserLanguageConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TaskDecorator userLanguageTaskDecorator() {
|
||||||
|
return new UserLanguageTaskDecorator();
|
||||||
|
}
|
||||||
|
}
|
||||||
+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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.springframework.core.task.TaskDecorator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relaie la langue de l'utilisateur ({@link UserLanguageHolder}, un ThreadLocal) du thread
|
||||||
|
* de la requête HTTP vers le thread de fond qui exécute la tâche.
|
||||||
|
* <p>
|
||||||
|
* Sans lui, les traitements longs lancés dans {@code applicationTaskExecutor} (imports de PDF,
|
||||||
|
* ateliers, chat IA en streaming…) lisaient la valeur par défaut du ThreadLocal sur leur
|
||||||
|
* propre thread : le Brain rédigeait toujours en français, même avec l'interface en anglais.
|
||||||
|
* Spring Boot associe automatiquement ce décorateur à l'exécuteur auto-configuré.
|
||||||
|
*/
|
||||||
|
public class UserLanguageTaskDecorator implements TaskDecorator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Runnable decorate(Runnable runnable) {
|
||||||
|
String language = UserLanguageHolder.get(); // lu sur le thread de la requête
|
||||||
|
return () -> {
|
||||||
|
String previous = UserLanguageHolder.get();
|
||||||
|
UserLanguageHolder.set(language);
|
||||||
|
try {
|
||||||
|
runnable.run();
|
||||||
|
} finally {
|
||||||
|
// Threads réutilisés par le pool : on ne laisse pas la langue fuir vers la tâche suivante.
|
||||||
|
UserLanguageHolder.set(previous);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -257,6 +257,7 @@ public class GameSystemController {
|
|||||||
dto.getName(),
|
dto.getName(),
|
||||||
dto.getDescription(),
|
dto.getDescription(),
|
||||||
dto.getRulesMarkdown(),
|
dto.getRulesMarkdown(),
|
||||||
|
dto.getRulesMarkdownEn(),
|
||||||
templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
|
templateFieldMapper.toDomainList(dto.getCharacterTemplate()),
|
||||||
templateFieldMapper.toDomainList(dto.getNpcTemplate()),
|
templateFieldMapper.toDomainList(dto.getNpcTemplate()),
|
||||||
templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
|
templateFieldMapper.toDomainList(dto.getEnemyTemplate()),
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.application.campaigncontext.GuidedAssistService;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IA des méthodes guidées : propose des réponses aux questions d'une méthode à partir de
|
||||||
|
* l'idée de départ du MJ. Rien n'est enregistré.
|
||||||
|
*
|
||||||
|
* <p>{@code POST /api/campaigns/{campaignId}/guided-assist} → {@code {answers: {cle: valeur}}} ;
|
||||||
|
* 400 sans question, 404 campagne inconnue, 502 si l'IA est indisponible.</p>
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/campaigns/{campaignId}/guided-assist")
|
||||||
|
public class GuidedAssistController {
|
||||||
|
|
||||||
|
/** Corps : la méthode (nom, principe), l'idée, les questions et les réponses déjà écrites. */
|
||||||
|
public record SuggestRequest(String methodName, String principle, String idea,
|
||||||
|
List<Question> questions, Map<String, String> existing) {}
|
||||||
|
|
||||||
|
public record SuggestResponse(Map<String, String> answers) {}
|
||||||
|
|
||||||
|
private final GuidedAssistService service;
|
||||||
|
private final CampaignRepository campaignRepository;
|
||||||
|
|
||||||
|
public GuidedAssistController(GuidedAssistService service, CampaignRepository campaignRepository) {
|
||||||
|
this.service = service;
|
||||||
|
this.campaignRepository = campaignRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public ResponseEntity<SuggestResponse> suggest(@PathVariable String campaignId, @RequestBody SuggestRequest body) {
|
||||||
|
if (!campaignRepository.existsById(campaignId)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return ResponseEntity.ok(new SuggestResponse(service.suggest(campaignId, body.methodName(),
|
||||||
|
body.principle(), body.idea(), body.questions(), body.existing())));
|
||||||
|
} catch (NarrativeAssistException e) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
@@ -17,6 +17,8 @@ public class GameSystemDTO {
|
|||||||
private String name;
|
private String name;
|
||||||
private String description;
|
private String description;
|
||||||
private String rulesMarkdown;
|
private String rulesMarkdown;
|
||||||
|
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||||
|
private String rulesMarkdownEn;
|
||||||
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> characterTemplate = new ArrayList<>();
|
||||||
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> npcTemplate = new ArrayList<>();
|
||||||
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
|
private List<TemplateFieldDTO> enemyTemplate = new ArrayList<>();
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ public class GameSystemMapper {
|
|||||||
dto.setName(g.getName());
|
dto.setName(g.getName());
|
||||||
dto.setDescription(g.getDescription());
|
dto.setDescription(g.getDescription());
|
||||||
dto.setRulesMarkdown(g.getRulesMarkdown());
|
dto.setRulesMarkdown(g.getRulesMarkdown());
|
||||||
|
dto.setRulesMarkdownEn(g.getRulesMarkdownEn());
|
||||||
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
|
dto.setCharacterTemplate(fieldMapper.toDTOList(g.getCharacterTemplate()));
|
||||||
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
|
dto.setNpcTemplate(fieldMapper.toDTOList(g.getNpcTemplate()));
|
||||||
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
|
dto.setEnemyTemplate(fieldMapper.toDTOList(g.getEnemyTemplate()));
|
||||||
@@ -36,6 +37,7 @@ public class GameSystemMapper {
|
|||||||
.name(dto.getName())
|
.name(dto.getName())
|
||||||
.description(dto.getDescription())
|
.description(dto.getDescription())
|
||||||
.rulesMarkdown(dto.getRulesMarkdown())
|
.rulesMarkdown(dto.getRulesMarkdown())
|
||||||
|
.rulesMarkdownEn(dto.getRulesMarkdownEn())
|
||||||
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
|
.characterTemplate(fieldMapper.toDomainList(dto.getCharacterTemplate()))
|
||||||
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
|
.npcTemplate(fieldMapper.toDomainList(dto.getNpcTemplate()))
|
||||||
.enemyTemplate(fieldMapper.toDomainList(dto.getEnemyTemplate()))
|
.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;
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
package com.loremind.application.campaigncontext;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Choice;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant.Question;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/** IA des méthodes guidées : questions validées, contexte de campagne transmis, réponses filtrées. */
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class GuidedAssistServiceTest {
|
||||||
|
|
||||||
|
@Mock private GuidedMethodAssistant assistant;
|
||||||
|
@Mock private CampaignContextFormatter contextFormatter;
|
||||||
|
@InjectMocks private GuidedAssistService service;
|
||||||
|
|
||||||
|
private static final Question TITLE = new Question("title", "Nom de l'enquête", "Ex. : L'héritage", "Le mystère", List.of());
|
||||||
|
private static final Question NATURE = new Question("node1.nature", "Genre de scène", null, "Première piste",
|
||||||
|
List.of(new Choice("location", "Un lieu"), new Choice("npc", "Une personne")));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_sendsCampaignContextAndExistingAnswers_andFiltersTheResult() {
|
||||||
|
when(contextFormatter.format("c1")).thenReturn("Campagne : Valfroide");
|
||||||
|
when(assistant.answer(eq("Enquête en nœuds"), any(), eq("Une tour se rallume"), eq("Campagne : Valfroide"),
|
||||||
|
anyList(), anyMap())).thenReturn(Map.of(
|
||||||
|
"title", " L'héritage empoisonné ",
|
||||||
|
"node1.nature", "dragon", // choix invalide -> écarté
|
||||||
|
"invented", "clé inventée", // clé non demandée -> écartée
|
||||||
|
"node1.name", ""));
|
||||||
|
|
||||||
|
Map<String, String> out = service.suggest("c1", "Enquête en nœuds", "Trois pistes",
|
||||||
|
"Une tour se rallume", List.of(TITLE, NATURE), Map.of("truth", " Le notaire ", "blank", " "));
|
||||||
|
|
||||||
|
assertEquals(Map.of("title", "L'héritage empoisonné"), out);
|
||||||
|
verify(assistant).answer(any(), any(), any(), any(), eq(List.of(TITLE, NATURE)), eq(Map.of("truth", "Le notaire")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_keepsAValidChoice() {
|
||||||
|
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap())).thenReturn(Map.of("node1.nature", "npc"));
|
||||||
|
assertEquals(Map.of("node1.nature", "npc"), service.suggest("c1", "M", "", "", List.of(NATURE), null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_withoutAnyValidQuestion_isRejected() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée", List.of(), Map.of()));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> service.suggest("c1", "M", "", "idée",
|
||||||
|
java.util.Arrays.asList(null, new Question(" ", "x", null, null, null)), Map.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -23,6 +23,9 @@ class GameSystemContextBuilderTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private GameSystemRepository gameSystemRepository;
|
private GameSystemRepository gameSystemRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private com.loremind.domain.shared.ports.CurrentLanguage currentLanguage;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private GameSystemContextBuilder builder;
|
private GameSystemContextBuilder builder;
|
||||||
|
|
||||||
@@ -71,4 +74,24 @@ class GameSystemContextBuilderTest {
|
|||||||
|
|
||||||
assertEquals("Règles de combat.", sections.get("Combat"));
|
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());
|
assertTrue(c.done.get().sections().isEmpty());
|
||||||
assertNull(c.error.get());
|
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"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package com.loremind.infrastructure.transfer.pdf;
|
||||||
|
|
||||||
|
import com.loremind.infrastructure.persistence.entity.*;
|
||||||
|
import com.loremind.infrastructure.persistence.jpa.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode plat du livret : un seul arc d'un seul chapitre n'est présenté « à plat » que si
|
||||||
|
* ces deux conteneurs sont vides. Un chapitre écrit (méthode guidée…) garde ses en-têtes.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
class PdfExportFlatModeTest {
|
||||||
|
|
||||||
|
@Autowired private PdfExportService service;
|
||||||
|
@Autowired private CampaignJpaRepository campaignRepo;
|
||||||
|
@Autowired private ArcJpaRepository arcRepo;
|
||||||
|
@Autowired private ChapterJpaRepository chapterRepo;
|
||||||
|
@Autowired private SceneJpaRepository sceneRepo;
|
||||||
|
|
||||||
|
private String campaign(String chapterGmNotes) {
|
||||||
|
CampaignJpaEntity camp = campaignRepo.save(CampaignJpaEntity.builder().name("C").arcsCount(1).build());
|
||||||
|
ArcJpaEntity arc = arcRepo.save(ArcJpaEntity.builder().name("Arc principal").campaignId(camp.getId()).order(0).build());
|
||||||
|
ChapterJpaEntity ch = chapterRepo.save(ChapterJpaEntity.builder().name("L'héritage empoisonné")
|
||||||
|
.arcId(arc.getId()).order(0).gmNotes(chapterGmNotes).build());
|
||||||
|
sceneRepo.save(SceneJpaEntity.builder().name("L'arrestation").chapterId(ch.getId()).order(0).build());
|
||||||
|
return String.valueOf(camp.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bareArcAndChapter_areFlattened() {
|
||||||
|
String x = service.xhtml(campaign(null), PdfExportOptions.defaults());
|
||||||
|
assertTrue(x.contains("id=\"part-narrative\">Scènes</h1>"));
|
||||||
|
assertFalse(x.contains("L'héritage empoisonné</div>"), "en-tête de chapitre masqué");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void writtenChapter_keepsItsHeaders() {
|
||||||
|
String x = service.xhtml(campaign("Le notaire est coupable."), PdfExportOptions.defaults());
|
||||||
|
assertTrue(x.contains("id=\"part-narrative\">Structure narrative</h1>"));
|
||||||
|
assertTrue(x.contains("L'héritage empoisonné"), "le chapitre de la méthode guidée reste visible");
|
||||||
|
assertTrue(x.contains("Le notaire est coupable."));
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package com.loremind.infrastructure.web.config;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.core.task.TaskExecutor;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* La langue de l'interface suit les traitements de fond : sans ce relais, les imports de PDF
|
||||||
|
* et les flux IA lancés dans l'exécuteur partaient toujours en français.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
class UserLanguageTaskDecoratorTest {
|
||||||
|
|
||||||
|
@Autowired @Qualifier("applicationTaskExecutor") private TaskExecutor taskExecutor;
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void clear() {
|
||||||
|
UserLanguageHolder.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void applicationTaskExecutor_runsTasksInTheRequestLanguage() throws Exception {
|
||||||
|
UserLanguageHolder.set("en");
|
||||||
|
CompletableFuture<String> seen = new CompletableFuture<>();
|
||||||
|
taskExecutor.execute(() -> seen.complete(UserLanguageHolder.get()));
|
||||||
|
assertEquals("en", seen.get(5, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decorator_restoresTheWorkerThreadLanguageAfterTheTask() {
|
||||||
|
UserLanguageHolder.set("en");
|
||||||
|
Runnable decorated = new UserLanguageTaskDecorator().decorate(() -> assertEquals("en", UserLanguageHolder.get()));
|
||||||
|
UserLanguageHolder.set("fr"); // le « thread de travail » avait une autre langue
|
||||||
|
decorated.run();
|
||||||
|
assertEquals("fr", UserLanguageHolder.get(), "pas de fuite vers la tâche suivante du pool");
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
package com.loremind.infrastructure.web.controller;
|
||||||
|
|
||||||
|
import com.loremind.domain.campaigncontext.Campaign;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.GuidedMethodAssistant;
|
||||||
|
import com.loremind.domain.campaigncontext.ports.exceptions.NarrativeAssistException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.*;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@AutoConfigureMockMvc
|
||||||
|
@Transactional
|
||||||
|
class GuidedAssistControllerTest {
|
||||||
|
|
||||||
|
@Autowired private MockMvc mockMvc;
|
||||||
|
@Autowired private CampaignRepository campaignRepository;
|
||||||
|
@MockitoBean private GuidedMethodAssistant assistant;
|
||||||
|
|
||||||
|
private static final String BODY = """
|
||||||
|
{"methodName":"Enquête en nœuds","principle":"Trois pistes","idea":"Une tour se rallume",
|
||||||
|
"questions":[{"key":"title","label":"Nom","hint":"","step":"Le mystère","options":[]}],
|
||||||
|
"existing":{}}""";
|
||||||
|
|
||||||
|
private String campaignId() {
|
||||||
|
return campaignRepository.save(Campaign.builder().name("C").description("").build()).getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_returnsTheFilteredAnswers() throws Exception {
|
||||||
|
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap()))
|
||||||
|
.thenReturn(Map.of("title", "L'héritage empoisonné", "other", "x"));
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.answers.title").value("L'héritage empoisonné"))
|
||||||
|
.andExpect(jsonPath("$.answers.other").doesNotExist());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_unknownCampaign_is404_andUnavailableAi_is502() throws Exception {
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", "999999999")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||||
|
.andExpect(status().isNotFound());
|
||||||
|
|
||||||
|
when(assistant.answer(any(), any(), any(), any(), anyList(), anyMap()))
|
||||||
|
.thenThrow(new NarrativeAssistException("Le Brain est injoignable"));
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||||
|
.andExpect(status().isBadGateway());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void suggest_withoutQuestions_is400() throws Exception {
|
||||||
|
mockMvc.perform(post("/api/campaigns/{id}/guided-assist", campaignId())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{\"idea\":\"x\",\"questions\":[]}"))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import { Npc } from '../services/npc.model';
|
|||||||
import { RandomTable } from '../services/random-table.model';
|
import { RandomTable } from '../services/random-table.model';
|
||||||
import { Enemy } from '../services/enemy.model';
|
import { Enemy } from '../services/enemy.model';
|
||||||
import { CampaignReadinessAssessment, ReadinessGap, ReadinessSeverity, ReadinessEntityType } from '../services/readiness.model';
|
import { CampaignReadinessAssessment, ReadinessGap, ReadinessSeverity, ReadinessEntityType } from '../services/readiness.model';
|
||||||
|
import { flatContainer } from './flat-structure';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper — charge l'arborescence complète d'une campagne (arcs -> chapitres -> scènes)
|
* Helper — charge l'arborescence complète d'une campagne (arcs -> chapitres -> scènes)
|
||||||
@@ -365,12 +366,13 @@ export function buildCampaignTree(
|
|||||||
// des scènes et l'ajout restent identiques (c'est le nœud chapitre, relabellisé
|
// des scènes et l'ajout restent identiques (c'est le nœud chapitre, relabellisé
|
||||||
// et remonté à la racine). Dès qu'un 2e arc OU un 2e chapitre existe, la
|
// et remonté à la racine). Dès qu'un 2e arc OU un 2e chapitre existe, la
|
||||||
// structure complète réapparaît automatiquement.
|
// structure complète réapparaît automatiquement.
|
||||||
const onlyArc = sortedArcs.length === 1 ? sortedArcs[0] : null;
|
// Mode plat seulement si l'arc et le chapitre uniques sont VIDES (cf. flatContainer) :
|
||||||
const onlyArcChapters = onlyArc ? (data.chaptersByArc[onlyArc.id!] ?? []) : [];
|
// un chapitre écrit par une méthode guidée doit rester visible.
|
||||||
|
const flat = flatContainer(sortedArcs, data.chaptersByArc);
|
||||||
|
const onlyArc = flat?.arc ?? null;
|
||||||
let narrationNodes: TreeItem[] = arcNodes;
|
let narrationNodes: TreeItem[] = arcNodes;
|
||||||
// Le mode plat ne s'applique PAS à un arc HUB (qui présente des quêtes, pas juste des scènes).
|
if (flat && onlyArc) {
|
||||||
if (onlyArc && onlyArc.type !== 'HUB' && onlyArcChapters.length === 1) {
|
const ch = flat.chapter;
|
||||||
const ch = onlyArcChapters[0];
|
|
||||||
const sortedScenes = [...(data.scenesByChapter[ch.id!] ?? [])].sort(byOrder);
|
const sortedScenes = [...(data.scenesByChapter[ch.id!] ?? [])].sort(byOrder);
|
||||||
const sceneItems: TreeItem[] = sortedScenes.map(sc => ({
|
const sceneItems: TreeItem[] = sortedScenes.map(sc => ({
|
||||||
id: `scene-${sc.id}`,
|
id: `scene-${sc.id}`,
|
||||||
|
|||||||
@@ -228,7 +228,7 @@
|
|||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@if (arcs.length > 0 && !showQuickAddScene) {
|
@if (arcs.length > 0 && !flatMode) {
|
||||||
<div class="arcs-grid" cdkDropList cdkDropListOrientation="mixed"
|
<div class="arcs-grid" cdkDropList cdkDropListOrientation="mixed"
|
||||||
(cdkDropListDropped)="dropArc($event)">
|
(cdkDropListDropped)="dropArc($event)">
|
||||||
@for (arc of arcs; track arc.id) {
|
@for (arc of arcs; track arc.id) {
|
||||||
@@ -242,7 +242,7 @@
|
|||||||
}
|
}
|
||||||
<!-- Mode plat (un seul arc d'un seul chapitre) : on masque la carte de
|
<!-- Mode plat (un seul arc d'un seul chapitre) : on masque la carte de
|
||||||
l'arc par défaut, comme dans la sidebar. Les scènes vivent dans le volet. -->
|
l'arc par défaut, comme dans la sidebar. Les scènes vivent dans le volet. -->
|
||||||
@if (arcs.length > 0 && showQuickAddScene) {
|
@if (arcs.length > 0 && flatMode) {
|
||||||
<div class="empty-state empty-state--compact">
|
<div class="empty-state empty-state--compact">
|
||||||
<p>{{ 'campaignDetail.flatModeHint' | translate }}</p>
|
<p>{{ 'campaignDetail.flatModeHint' | translate }}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import { CampaignPlayBlockComponent } from '../campaign-play-block/campaign-play
|
|||||||
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
import { FoundryExportDialogComponent } from '../foundry-export-dialog/foundry-export-dialog.component';
|
||||||
import { PdfExportDialogComponent } from '../pdf-export-dialog/pdf-export-dialog.component';
|
import { PdfExportDialogComponent } from '../pdf-export-dialog/pdf-export-dialog.component';
|
||||||
import { downloadBlob, safeFileName } from '../../../shared/download.util';
|
import { downloadBlob, safeFileName } from '../../../shared/download.util';
|
||||||
|
import { flatContainer } from '../../flat-structure';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-campaign-detail',
|
selector: 'app-campaign-detail',
|
||||||
@@ -212,6 +213,7 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
// L'arc SYSTEM (« Quêtes libres ») est de la plomberie : pas de carte d'arc pour lui.
|
// L'arc SYSTEM (« Quêtes libres ») est de la plomberie : pas de carte d'arc pour lui.
|
||||||
this.arcs = [...treeData.arcs].sort(byOrder).filter(a => a.type !== 'SYSTEM');
|
this.arcs = [...treeData.arcs].sort(byOrder).filter(a => a.type !== 'SYSTEM');
|
||||||
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
this.chapterCountByArc = this.computeChapterCounts(treeData);
|
||||||
|
this.flatMode = !!flatContainer(this.arcs, treeData.chaptersByArc);
|
||||||
this.showLayout(allCampaigns, treeData);
|
this.showLayout(allCampaigns, treeData);
|
||||||
this.pageTitleService.set(campaign.name);
|
this.pageTitleService.set(campaign.name);
|
||||||
this.openEditFromQueryParam();
|
this.openEditFromQueryParam();
|
||||||
@@ -348,6 +350,12 @@ export class CampaignDetailComponent implements OnInit, OnDestroy {
|
|||||||
// structure est simple (vide, ou un seul arc d'au plus un chapitre).
|
// structure est simple (vide, ou un seul arc d'au plus un chapitre).
|
||||||
quickSceneInFlight = false;
|
quickSceneInFlight = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode plat (arc et chapitre uniques encore vides) : les cartes d'arc sont masquées, les
|
||||||
|
* scènes vivent dans le volet. Dès qu'il y a du contenu écrit, la structure reste visible.
|
||||||
|
*/
|
||||||
|
flatMode = false;
|
||||||
|
|
||||||
get showQuickAddScene(): boolean {
|
get showQuickAddScene(): boolean {
|
||||||
if (this.arcs.length === 0) return true;
|
if (this.arcs.length === 0) return true;
|
||||||
if (this.arcs.length === 1) return (this.chapterCountByArc[this.arcs[0].id!] ?? 0) <= 1;
|
if (this.arcs.length === 1) return (this.chapterCountByArc[this.arcs[0].id!] ?? 0) <= 1;
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { flatContainer } from './flat-structure';
|
||||||
|
import { Arc, Chapter } from '../services/campaign.model';
|
||||||
|
|
||||||
|
describe('flatContainer (mode plat)', () => {
|
||||||
|
const arc = (extra: Partial<Arc> = {}): Arc => ({ id: 'a1', name: 'Arc principal', campaignId: 'c', type: 'LINEAR', ...extra } as Arc);
|
||||||
|
const chapter = (extra: Partial<Chapter> = {}): Chapter => ({ id: 'ch1', name: 'Chapitre 1', arcId: 'a1', ...extra } as Chapter);
|
||||||
|
|
||||||
|
it('flattens a single empty arc with a single empty chapter', () => {
|
||||||
|
expect(flatContainer([arc()], { a1: [chapter()] })?.chapter.id).toBe('ch1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the structure once the chapter or the arc has written content', () => {
|
||||||
|
expect(flatContainer([arc()], { a1: [chapter({ gmNotes: 'Le notaire est coupable' })] })).toBeNull();
|
||||||
|
expect(flatContainer([arc()], { a1: [chapter({ description: "L'affaire commence" })] })).toBeNull();
|
||||||
|
expect(flatContainer([arc({ hooks: '- Un ami disparaît' })], { a1: [chapter()] })).toBeNull();
|
||||||
|
expect(flatContainer([arc({ illustrationImageIds: ['img'] })], { a1: [chapter()] })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores names and blank text', () => {
|
||||||
|
expect(flatContainer([arc({ name: 'Ma campagne', stakes: ' ' })], { a1: [chapter({ name: 'Début' })] })).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never flattens a HUB arc, several chapters or several arcs (system arc ignored)', () => {
|
||||||
|
expect(flatContainer([arc({ type: 'HUB' })], { a1: [chapter()] })).toBeNull();
|
||||||
|
expect(flatContainer([arc()], { a1: [chapter(), chapter({ id: 'ch2' })] })).toBeNull();
|
||||||
|
expect(flatContainer([arc(), arc({ id: 'a2' })], { a1: [chapter()], a2: [] })).toBeNull();
|
||||||
|
expect(flatContainer([arc(), arc({ id: 'sys', type: 'SYSTEM' })], { a1: [chapter()] })).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { Arc, Chapter } from '../services/campaign.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode « plat » (Niveau 0) : une campagne d'un seul arc linéaire et d'un seul chapitre
|
||||||
|
* présente directement ses scènes, sans les niveaux arc et chapitre. Seulement si ces deux
|
||||||
|
* conteneurs sont VIDES (créés d'office pour poser une première scène) : dès que l'auteur y
|
||||||
|
* a écrit quelque chose — à la main ou via une méthode guidée (titre, accroche, vérité
|
||||||
|
* cachée, plan du méchant…) — on les montre, sinon ce contenu deviendrait introuvable.
|
||||||
|
* Même règle dans le volet, sur la page de la campagne et dans le livret PDF (core).
|
||||||
|
*/
|
||||||
|
export function flatContainer(arcs: Arc[], chaptersByArc: Record<string, Chapter[]>): { arc: Arc; chapter: Chapter } | null {
|
||||||
|
const visible = arcs.filter(a => a.type !== 'SYSTEM');
|
||||||
|
if (visible.length !== 1) return null;
|
||||||
|
const arc = visible[0];
|
||||||
|
if (arc.type === 'HUB') return null; // un arc HUB présente des quêtes, pas une simple liste de scènes
|
||||||
|
const chapters = chaptersByArc[arc.id!] ?? [];
|
||||||
|
if (chapters.length !== 1) return null;
|
||||||
|
const chapter = chapters[0];
|
||||||
|
return isBareArc(arc) && isBareChapter(chapter) ? { arc, chapter } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'écriture dans l'arc (le nom ne compte pas : « Arc principal » est créé d'office). */
|
||||||
|
export function isBareArc(arc: Arc): boolean {
|
||||||
|
return [arc.description, arc.themes, arc.stakes, arc.rewards, arc.resolution, arc.gmNotes, arc.hiddenTruth, arc.hooks]
|
||||||
|
.every(blank) && !(arc.illustrationImageIds?.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aucun contenu d'écriture dans le chapitre (le nom ne compte pas : « Chapitre 1 » est créé d'office). */
|
||||||
|
export function isBareChapter(chapter: Chapter): boolean {
|
||||||
|
return [chapter.description, chapter.playerObjectives, chapter.narrativeStakes, chapter.gmNotes]
|
||||||
|
.every(blank) && !(chapter.illustrationImageIds?.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
function blank(value: string | null | undefined): boolean {
|
||||||
|
return !value || !value.trim();
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { IDEA_KEY, applySuggestions, buildSuggestRequest, isFillable, markTouched } from './guided-assist';
|
||||||
|
import { INVESTIGATION_METHOD } from './methods/investigation.method';
|
||||||
|
import { GuidedField } from './guided-method.model';
|
||||||
|
|
||||||
|
/** Traduction factice : renvoie la clé, sauf les noms pré-remplis (valeurs d'office). */
|
||||||
|
const t = (key: string) => key.endsWith('defaults.node1.name') ? 'Première piste' : key;
|
||||||
|
const field = (key: string): GuidedField =>
|
||||||
|
INVESTIGATION_METHOD.steps.flatMap(s => s.fields ?? []).find(f => f.key === key)!;
|
||||||
|
|
||||||
|
describe('guided AI assist', () => {
|
||||||
|
it('treats empty fields and untouched defaults as free for the AI', () => {
|
||||||
|
expect(isFillable(INVESTIGATION_METHOD, field('truth'), {}, t)).toBe(true);
|
||||||
|
expect(isFillable(INVESTIGATION_METHOD, field('node1.name'), { 'node1.name': 'Première piste' }, t)).toBe(true);
|
||||||
|
expect(isFillable(INVESTIGATION_METHOD, field('node1.nature'), { 'node1.nature': 'location' }, t)).toBe(true);
|
||||||
|
expect(isFillable(INVESTIGATION_METHOD, field('node1.nature'), { 'node1.nature': 'npc' }, t)).toBe(false);
|
||||||
|
expect(isFillable(INVESTIGATION_METHOD, field('truth'), { truth: 'Le notaire' }, t)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never considers a field the GM touched as free, even at its default value', () => {
|
||||||
|
const answers = markTouched({ 'node1.name': 'Première piste' }, 'node1.name');
|
||||||
|
expect(isFillable(INVESTIGATION_METHOD, field('node1.name'), answers, t)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('asks only free fields, sends what the GM wrote as context, and passes the idea', () => {
|
||||||
|
const req = buildSuggestRequest(INVESTIGATION_METHOD, { [IDEA_KEY]: ' Une tour ', truth: 'Le notaire est coupable' }, t);
|
||||||
|
expect(req.idea).toBe('Une tour');
|
||||||
|
expect(req.existing).toEqual({ truth: 'Le notaire est coupable' });
|
||||||
|
expect(req.questions.some(q => q.key === 'truth')).toBe(false);
|
||||||
|
const nature = req.questions.find(q => q.key === 'node1.nature')!;
|
||||||
|
expect(nature.options.map(o => o.value)).toEqual(['location', 'npc', 'event']);
|
||||||
|
expect(nature.hint).toBe('');
|
||||||
|
expect(req.methodName).toBe('guided.investigation.name');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('limits the questions to the requested step', () => {
|
||||||
|
const req = buildSuggestRequest(INVESTIGATION_METHOD, {}, t, ['node2']);
|
||||||
|
expect(req.questions.length).toBeGreaterThan(0);
|
||||||
|
expect(req.questions.every(q => q.key.startsWith('node2.'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies proposals to free fields only, and only valid choices', () => {
|
||||||
|
const answers = { truth: 'Le notaire', 'node1.nature': 'location' };
|
||||||
|
const { answers: next, filled } = applySuggestions(INVESTIGATION_METHOD, answers, {
|
||||||
|
truth: 'Autre vérité', 'node1.nature': 'npc', 'node2.nature': 'dragon', title: "L'héritage", unknown: 'x'
|
||||||
|
}, t);
|
||||||
|
expect(next['truth']).toBe('Le notaire');
|
||||||
|
expect(next['node1.nature']).toBe('npc');
|
||||||
|
expect(next['node2.nature']).toBeUndefined();
|
||||||
|
expect(next['title']).toBe("L'héritage");
|
||||||
|
expect(next['unknown']).toBeUndefined();
|
||||||
|
expect(filled).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { GuidedAnswers, GuidedField, GuidedMethod, GuidedStep } from './guided-method.model';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IA des méthodes guidées (logique pure, testée sans Angular) : questions envoyées au modèle,
|
||||||
|
* champs que l'IA a le droit de remplir, et fusion des réponses proposées.
|
||||||
|
*
|
||||||
|
* Règle d'or : l'IA ne remplace JAMAIS ce que le MJ a écrit. Elle ne remplit qu'un champ
|
||||||
|
* vide, ou resté à sa valeur d'office (nom pré-rempli « Première piste », premier choix
|
||||||
|
* d'une question à choix) tant que le MJ n'y a pas touché.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Clé de réponse réservée : l'idée de départ du MJ (gardée dans le brouillon). */
|
||||||
|
export const IDEA_KEY = 'idea';
|
||||||
|
/** Clé de réponse réservée : champs modifiés à la main par le MJ (séparés par des virgules). */
|
||||||
|
export const TOUCHED_KEY = 'touched';
|
||||||
|
|
||||||
|
/** Traduction d'une clé i18n (injectée : TranslateService.instant côté composant). */
|
||||||
|
export type Translate = (key: string) => string;
|
||||||
|
|
||||||
|
export interface GuidedQuestion {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
hint: string;
|
||||||
|
step: string;
|
||||||
|
options: { value: string; label: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GuidedSuggestRequest {
|
||||||
|
methodName: string;
|
||||||
|
principle: string;
|
||||||
|
idea: string;
|
||||||
|
questions: GuidedQuestion[];
|
||||||
|
existing: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Préfixe i18n de la méthode (`guided.<i18nKey>.`). */
|
||||||
|
function k(method: GuidedMethod, path: string): string {
|
||||||
|
return `guided.${method.i18nKey}.${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valeur mise d'office par l'assistant (sans intervention du MJ), ou null. */
|
||||||
|
export function defaultValue(method: GuidedMethod, field: GuidedField, t: Translate): string | null {
|
||||||
|
if (field.kind === 'choice') return field.options?.[0] ?? null;
|
||||||
|
if (field.prefilled) return t(k(method, `defaults.${field.key}`));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function touchedKeys(answers: GuidedAnswers): Set<string> {
|
||||||
|
return new Set((answers[TOUCHED_KEY] ?? '').split(',').filter(Boolean));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Marque un champ comme modifié à la main (l'IA n'y touchera plus). */
|
||||||
|
export function markTouched(answers: GuidedAnswers, key: string): GuidedAnswers {
|
||||||
|
const touched = touchedKeys(answers);
|
||||||
|
if (touched.has(key)) return answers;
|
||||||
|
touched.add(key);
|
||||||
|
return { ...answers, [TOUCHED_KEY]: [...touched].join(',') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le champ est-il encore libre pour l'IA ? Vide, ou à sa valeur d'office et jamais touché. */
|
||||||
|
export function isFillable(method: GuidedMethod, field: GuidedField, answers: GuidedAnswers, t: Translate): boolean {
|
||||||
|
const value = (answers[field.key] ?? '').trim();
|
||||||
|
if (!value) return true;
|
||||||
|
return !touchedKeys(answers).has(field.key) && value === defaultValue(method, field, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formSteps(method: GuidedMethod, stepIds?: string[]): GuidedStep[] {
|
||||||
|
return method.steps.filter(s => s.kind === 'form' && (!stepIds || stepIds.includes(s.id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requête de propositions pour les étapes demandées (toutes si absent) : seuls les champs
|
||||||
|
* encore libres sont demandés ; tout ce que le MJ a déjà écrit est transmis comme contexte.
|
||||||
|
*/
|
||||||
|
export function buildSuggestRequest(method: GuidedMethod, answers: GuidedAnswers, t: Translate,
|
||||||
|
stepIds?: string[]): GuidedSuggestRequest {
|
||||||
|
const questions: GuidedQuestion[] = [];
|
||||||
|
const existing: Record<string, string> = {};
|
||||||
|
for (const step of formSteps(method)) {
|
||||||
|
for (const field of step.fields ?? []) {
|
||||||
|
if (!isFillable(method, field, answers, t)) {
|
||||||
|
existing[field.key] = answers[field.key];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (stepIds && !stepIds.includes(step.id)) continue;
|
||||||
|
questions.push({
|
||||||
|
key: field.key,
|
||||||
|
label: t(k(method, `fields.${field.key}.label`)),
|
||||||
|
hint: field.kind === 'choice' ? '' : t(k(method, `fields.${field.key}.placeholder`)),
|
||||||
|
step: t(k(method, `steps.${step.id}.title`)),
|
||||||
|
options: (field.options ?? []).map(o => ({ value: o, label: t(k(method, `options.${field.key}.${o}`)) }))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
methodName: t(k(method, 'name')),
|
||||||
|
principle: t(k(method, 'tagline')),
|
||||||
|
idea: (answers[IDEA_KEY] ?? '').trim(),
|
||||||
|
questions,
|
||||||
|
existing
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applique les propositions sur les seuls champs encore libres (jamais sur un champ du MJ). */
|
||||||
|
export function applySuggestions(method: GuidedMethod, answers: GuidedAnswers, suggestions: Record<string, string>,
|
||||||
|
t: Translate): { answers: GuidedAnswers; filled: number } {
|
||||||
|
const next = { ...answers };
|
||||||
|
let filled = 0;
|
||||||
|
for (const step of formSteps(method)) {
|
||||||
|
for (const field of step.fields ?? []) {
|
||||||
|
const proposal = suggestions[field.key]?.trim();
|
||||||
|
if (!proposal || !isFillable(method, field, answers, t)) continue;
|
||||||
|
if (field.kind === 'choice' && !field.options?.includes(proposal)) continue;
|
||||||
|
next[field.key] = proposal;
|
||||||
|
filled++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { answers: next, filled };
|
||||||
|
}
|
||||||
@@ -29,6 +29,40 @@
|
|||||||
</aside>
|
</aside>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<!-- IA : idée de départ du MJ, propositions pour toute la méthode ou pour l'étape. -->
|
||||||
|
@if (step.kind !== 'review') {
|
||||||
|
<section class="ai-idea" [attr.aria-label]="'guided.ai.title' | translate">
|
||||||
|
<label class="ai-idea-label" for="guided-idea">
|
||||||
|
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||||
|
{{ 'guided.ai.title' | translate }}
|
||||||
|
</label>
|
||||||
|
<textarea id="guided-idea" rows="2" [(ngModel)]="idea"
|
||||||
|
[placeholder]="'guided.ai.placeholder' | translate"></textarea>
|
||||||
|
<div class="ai-actions">
|
||||||
|
<button type="button" class="btn-ai" (click)="suggestAll()" [disabled]="!!suggesting">
|
||||||
|
{{ (suggesting === 'all' ? 'guided.ai.thinking' : 'guided.ai.suggestAll') | translate }}
|
||||||
|
</button>
|
||||||
|
@if (step.kind === 'form') {
|
||||||
|
<button type="button" class="btn-ai-secondary" (click)="suggestStep()" [disabled]="!!suggesting">
|
||||||
|
{{ (suggesting === 'step' ? 'guided.ai.thinking' : 'guided.ai.suggestStep') | translate }}
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
@if (canUndoSuggest && !suggesting) {
|
||||||
|
<button type="button" class="btn-link" (click)="undoSuggest()">{{ 'guided.ai.undo' | translate }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (suggestFilled !== null) {
|
||||||
|
<p class="ai-note" role="status">
|
||||||
|
{{ (suggestFilled > 0 ? 'guided.ai.filled' : 'guided.ai.nothingToFill') | translate:{ count: suggestFilled } }}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@if (suggestError) {
|
||||||
|
<p class="ai-error" role="alert">{{ suggestError }}</p>
|
||||||
|
}
|
||||||
|
<p class="ai-hint">{{ 'guided.ai.hint' | translate }}</p>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
<!-- Où ranger l'aventure -->
|
<!-- Où ranger l'aventure -->
|
||||||
@if (step.kind === 'placement') {
|
@if (step.kind === 'placement') {
|
||||||
<fieldset class="placement">
|
<fieldset class="placement">
|
||||||
|
|||||||
@@ -361,3 +361,68 @@
|
|||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.progress-fill { transition: none; }
|
.progress-fill { transition: none; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IA : idée de départ et propositions (ne remplit que les champs encore libres).
|
||||||
|
.ai-idea {
|
||||||
|
margin: 0 0 1.25rem;
|
||||||
|
padding: 0.8rem 0.9rem;
|
||||||
|
border: 1px solid rgba(251, 191, 36, 0.3);
|
||||||
|
background: rgba(251, 191, 36, 0.06);
|
||||||
|
border-radius: 10px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.55rem;
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
background: #1f2937;
|
||||||
|
border: 1px solid #374151;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 0.6rem 0.8rem;
|
||||||
|
color: white;
|
||||||
|
font: inherit;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-idea-label {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
color: #fde68a;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ai, .btn-ai-secondary {
|
||||||
|
padding: 0.45rem 0.9rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
cursor: pointer;
|
||||||
|
border: 1px solid rgba(251, 191, 36, 0.45);
|
||||||
|
|
||||||
|
&:disabled { opacity: 0.6; cursor: default; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ai { background: rgba(251, 191, 36, 0.18); color: #fde68a; font-weight: 600; }
|
||||||
|
.btn-ai-secondary { background: transparent; color: #fde68a; }
|
||||||
|
|
||||||
|
.btn-link {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: #a5b4fc;
|
||||||
|
text-decoration: underline;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-note { margin: 0; color: #c7d2fe; font-size: 0.85rem; }
|
||||||
|
.ai-error { margin: 0; color: #fca5a5; font-size: 0.85rem; }
|
||||||
|
.ai-hint { margin: 0; color: #9ca3af; font-size: 0.78rem; font-style: italic; }
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
|||||||
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
import { WritingCoachTriggerComponent } from '../../../shared/writing-coach/writing-coach-trigger.component';
|
||||||
import { GuidedAnswers, GuidedDraft, GuidedField, GuidedMethod, GuidedStep, answer } from '../guided-method.model';
|
import { GuidedAnswers, GuidedDraft, GuidedField, GuidedMethod, GuidedStep, answer } from '../guided-method.model';
|
||||||
import { findGuidedMethod } from '../guided-methods';
|
import { findGuidedMethod } from '../guided-methods';
|
||||||
|
import { IDEA_KEY, applySuggestions, buildSuggestRequest, markTouched } from '../guided-assist';
|
||||||
|
|
||||||
/** Clés de réponse réservées à l'assistant (placement + chaînage), communes à toutes les méthodes. */
|
/** Clés de réponse réservées à l'assistant (placement + chaînage), communes à toutes les méthodes. */
|
||||||
const PLACEMENT_MODE = 'placement.mode';
|
const PLACEMENT_MODE = 'placement.mode';
|
||||||
@@ -139,10 +140,82 @@ export class GuidedWizardComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setAnswer(key: string, value: string): void {
|
setAnswer(key: string, value: string): void {
|
||||||
this.answers = { ...this.answers, [key]: value };
|
// Un champ modifié par le MJ ne sera plus jamais remplacé par une proposition de l'IA.
|
||||||
|
this.answers = markTouched({ ...this.answers, [key]: value }, key);
|
||||||
this.saveDraft();
|
this.saveDraft();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- IA : propositions à partir de l'idée de départ ------------------------------------
|
||||||
|
|
||||||
|
/** Proposition en cours (anti double-clic) ; `all` = toute la méthode, sinon l'étape. */
|
||||||
|
suggesting: 'all' | 'step' | null = null;
|
||||||
|
suggestError: string | null = null;
|
||||||
|
/** Nombre de champs remplis par la dernière proposition (message de confirmation). */
|
||||||
|
suggestFilled: number | null = null;
|
||||||
|
/** Réponses avant la dernière proposition : « Annuler » les restaure. */
|
||||||
|
private beforeSuggest: GuidedAnswers | null = null;
|
||||||
|
|
||||||
|
get idea(): string {
|
||||||
|
return this.answers[IDEA_KEY] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
set idea(value: string) {
|
||||||
|
this.answers = { ...this.answers, [IDEA_KEY]: value };
|
||||||
|
this.saveDraft();
|
||||||
|
}
|
||||||
|
|
||||||
|
get canUndoSuggest(): boolean {
|
||||||
|
return this.beforeSuggest !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Propose des réponses pour tous les champs encore libres de la méthode. */
|
||||||
|
suggestAll(): void {
|
||||||
|
this.suggest('all');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Propose des réponses pour les champs encore libres de l'étape affichée. */
|
||||||
|
suggestStep(): void {
|
||||||
|
this.suggest('step');
|
||||||
|
}
|
||||||
|
|
||||||
|
undoSuggest(): void {
|
||||||
|
if (!this.beforeSuggest) return;
|
||||||
|
this.answers = this.beforeSuggest;
|
||||||
|
this.beforeSuggest = null;
|
||||||
|
this.suggestFilled = null;
|
||||||
|
this.saveDraft();
|
||||||
|
}
|
||||||
|
|
||||||
|
private suggest(scope: 'all' | 'step'): void {
|
||||||
|
const method = this.method;
|
||||||
|
if (!method || this.suggesting) return;
|
||||||
|
const t = (key: string) => this.translate.instant(key) as string;
|
||||||
|
const stepIds = scope === 'step' && this.step ? [this.step.id] : undefined;
|
||||||
|
const request = buildSuggestRequest(method, this.answers, t, stepIds);
|
||||||
|
this.suggestError = null;
|
||||||
|
this.suggestFilled = null;
|
||||||
|
if (request.questions.length === 0) {
|
||||||
|
this.suggestFilled = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.suggesting = scope;
|
||||||
|
this.skeletonService.suggest(this.campaignId, request).subscribe({
|
||||||
|
next: ({ answers }) => {
|
||||||
|
const before = this.answers;
|
||||||
|
const result = applySuggestions(method, this.answers, answers ?? {}, t);
|
||||||
|
this.answers = result.answers;
|
||||||
|
this.beforeSuggest = result.filled > 0 ? before : this.beforeSuggest;
|
||||||
|
this.suggestFilled = result.filled;
|
||||||
|
this.suggesting = null;
|
||||||
|
this.saveDraft();
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.suggesting = null;
|
||||||
|
this.suggestError = this.translate.instant('guided.ai.error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** Placement par défaut + valeurs pré-remplies + premier choix des champs `choice`. */
|
/** Placement par défaut + valeurs pré-remplies + premier choix des champs `choice`. */
|
||||||
private applyDefaults(): void {
|
private applyDefaults(): void {
|
||||||
const a = { ...this.answers };
|
const a = { ...this.answers };
|
||||||
|
|||||||
@@ -75,6 +75,18 @@
|
|||||||
<p class="import-error">{{ importError }}</p>
|
<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">
|
<div class="section-list">
|
||||||
@for (section of sections; track section; let i = $index) {
|
@for (section of sections; track section; let i = $index) {
|
||||||
<div class="section-card" [class.collapsed]="section.collapsed">
|
<div class="section-card" [class.collapsed]="section.collapsed">
|
||||||
|
|||||||
@@ -359,3 +359,32 @@
|
|||||||
|
|
||||||
&:hover { border-color: #374151; color: #e5e7eb; }
|
&: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. */
|
/** Suggestions de champs pour la fiche ENNEMI — stats de combat. */
|
||||||
const ENEMY_FIELD_SUGGESTIONS = ['Stats', 'Attaques', 'Capacités', 'Faiblesses', 'Butin', 'Tactique'];
|
const ENEMY_FIELD_SUGGESTIONS = ['Stats', 'Attaques', 'Capacités', 'Faiblesses', 'Butin', 'Tactique'];
|
||||||
|
|
||||||
|
/** Langue d'une version des règles. */
|
||||||
|
type RulesLang = 'fr' | 'en';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-game-system-edit',
|
selector: 'app-game-system-edit',
|
||||||
imports: [FormsModule, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent],
|
imports: [FormsModule, LucideAngularModule, TranslatePipe, TemplateFieldsEditorComponent],
|
||||||
@@ -83,7 +86,15 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
name = '';
|
name = '';
|
||||||
description = '';
|
description = '';
|
||||||
author = '';
|
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[] = [];
|
characterTemplate: TemplateField[] = [];
|
||||||
npcTemplate: TemplateField[] = [];
|
npcTemplate: TemplateField[] = [];
|
||||||
enemyTemplate: TemplateField[] = [];
|
enemyTemplate: TemplateField[] = [];
|
||||||
@@ -107,6 +118,8 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
ngOnInit(): void {
|
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');
|
this.id = this.route.snapshot.paramMap.get('id');
|
||||||
if (this.id) {
|
if (this.id) {
|
||||||
this.service.getById(this.id).subscribe({
|
this.service.getById(this.id).subscribe({
|
||||||
@@ -114,7 +127,10 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
this.name = gs.name;
|
this.name = gs.name;
|
||||||
this.description = gs.description ?? '';
|
this.description = gs.description ?? '';
|
||||||
this.author = gs.author ?? '';
|
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.characterTemplate = gs.characterTemplate ? [...gs.characterTemplate] : [];
|
||||||
this.npcTemplate = gs.npcTemplate ? [...gs.npcTemplate] : [];
|
this.npcTemplate = gs.npcTemplate ? [...gs.npcTemplate] : [];
|
||||||
this.enemyTemplate = gs.enemyTemplate ? [...gs.enemyTemplate] : [];
|
this.enemyTemplate = gs.enemyTemplate ? [...gs.enemyTemplate] : [];
|
||||||
@@ -181,7 +197,7 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
} else if (ev.type === 'status') {
|
} else if (ev.type === 'status') {
|
||||||
this.importStatus = ev.message;
|
this.importStatus = ev.message;
|
||||||
} else if (ev.type === 'done') {
|
} 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) => {
|
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();
|
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) {
|
if (added === 0) {
|
||||||
this.importError = this.translate.instant('gameSystemEdit.importNoRules');
|
this.importError = this.translate.instant('gameSystemEdit.importNoRules');
|
||||||
return;
|
return;
|
||||||
@@ -208,6 +236,18 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
pages: pageCount,
|
pages: pageCount,
|
||||||
ocr
|
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 {
|
private resetImportProgress(): void {
|
||||||
@@ -221,20 +261,20 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
* (insensible à la casse) → contenu ajouté à la suite ; sinon nouvelle carte.
|
* (insensible à la casse) → contenu ajouté à la suite ; sinon nouvelle carte.
|
||||||
* Retourne le nombre de sections effectivement intégrées.
|
* 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;
|
let count = 0;
|
||||||
for (const [rawTitle, rawContent] of Object.entries(sections ?? {})) {
|
for (const [rawTitle, rawContent] of Object.entries(sections ?? {})) {
|
||||||
const title = (rawTitle ?? '').trim();
|
const title = (rawTitle ?? '').trim();
|
||||||
const content = (rawContent ?? '').trim();
|
const content = (rawContent ?? '').trim();
|
||||||
if (!title || !content) continue;
|
if (!title || !content) continue;
|
||||||
const existing = this.sections.find(
|
const existing = target.find(
|
||||||
s => s.title.trim().toLowerCase() === title.toLowerCase()
|
s => s.title.trim().toLowerCase() === title.toLowerCase()
|
||||||
);
|
);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
|
existing.content = `${existing.content.trim()}\n\n${content}`.trim();
|
||||||
existing.collapsed = false;
|
existing.collapsed = false;
|
||||||
} else {
|
} else {
|
||||||
this.sections.push({ title, content, collapsed: false });
|
target.push({ title, content, collapsed: false });
|
||||||
}
|
}
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
@@ -300,7 +340,8 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
name: this.name.trim(),
|
name: this.name.trim(),
|
||||||
description: this.description.trim() || null,
|
description: this.description.trim() || null,
|
||||||
author: this.author.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,
|
characterTemplate: this.characterTemplate,
|
||||||
npcTemplate: this.npcTemplate,
|
npcTemplate: this.npcTemplate,
|
||||||
enemyTemplate: this.enemyTemplate,
|
enemyTemplate: this.enemyTemplate,
|
||||||
@@ -377,8 +418,8 @@ export class GameSystemEditComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Reconstruit le markdown à partir des sections (ignore les sections vides). */
|
/** Reconstruit le markdown à partir des sections (ignore les sections vides). */
|
||||||
private serializeMarkdown(): string | null {
|
private serializeMarkdown(sections: RuleSection[]): string | null {
|
||||||
const valid = this.sections.filter(s => s.title.trim() || s.content.trim());
|
const valid = sections.filter(s => s.title.trim() || s.content.trim());
|
||||||
if (valid.length === 0) return null;
|
if (valid.length === 0) return null;
|
||||||
return valid
|
return valid
|
||||||
.map(s => {
|
.map(s => {
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export interface GameSystem {
|
|||||||
name: string;
|
name: string;
|
||||||
description?: string | null;
|
description?: string | null;
|
||||||
rulesMarkdown?: string | null;
|
rulesMarkdown?: string | null;
|
||||||
|
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||||
|
rulesMarkdownEn?: string | null;
|
||||||
characterTemplate?: TemplateField[];
|
characterTemplate?: TemplateField[];
|
||||||
npcTemplate?: TemplateField[];
|
npcTemplate?: TemplateField[];
|
||||||
enemyTemplate?: TemplateField[];
|
enemyTemplate?: TemplateField[];
|
||||||
@@ -43,7 +45,9 @@ export interface RulesImportResponse {
|
|||||||
export type RulesImportStreamEvent =
|
export type RulesImportStreamEvent =
|
||||||
| { type: 'progress'; current: number; total: number; pageCount: number; ocrPageCount: number; newSectionTitles: string[] }
|
| { type: 'progress'; current: number; total: number; pageCount: number; ocrPageCount: number; newSectionTitles: string[] }
|
||||||
| { type: 'status'; message: 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 };
|
| { type: 'error'; message: string };
|
||||||
|
|
||||||
/** Payload de creation/mise a jour (sans id). */
|
/** Payload de creation/mise a jour (sans id). */
|
||||||
@@ -51,6 +55,8 @@ export interface GameSystemCreate {
|
|||||||
name: string;
|
name: string;
|
||||||
description?: string | null;
|
description?: string | null;
|
||||||
rulesMarkdown?: string | null;
|
rulesMarkdown?: string | null;
|
||||||
|
/** Version anglaise des règles (rulesMarkdown = version française). */
|
||||||
|
rulesMarkdownEn?: string | null;
|
||||||
characterTemplate?: TemplateField[];
|
characterTemplate?: TemplateField[];
|
||||||
npcTemplate?: TemplateField[];
|
npcTemplate?: TemplateField[];
|
||||||
enemyTemplate?: TemplateField[];
|
enemyTemplate?: TemplateField[];
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Injectable } from '@angular/core';
|
|||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable } from 'rxjs';
|
||||||
import { GuidedSkeleton, GuidedSkeletonResult } from './guided-skeleton.model';
|
import { GuidedSkeleton, GuidedSkeletonResult } from './guided-skeleton.model';
|
||||||
|
import { GuidedSuggestRequest } from '../campaigns/guided/guided-assist';
|
||||||
|
|
||||||
/** Service HTTP des méthodes guidées (Mentor d'écriture, phase M3). */
|
/** Service HTTP des méthodes guidées (Mentor d'écriture, phase M3). */
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
@@ -12,4 +13,9 @@ export class GuidedSkeletonService {
|
|||||||
create(campaignId: string, skeleton: GuidedSkeleton): Observable<GuidedSkeletonResult> {
|
create(campaignId: string, skeleton: GuidedSkeleton): Observable<GuidedSkeletonResult> {
|
||||||
return this.http.post<GuidedSkeletonResult>(`/api/campaigns/${campaignId}/guided-skeleton`, skeleton);
|
return this.http.post<GuidedSkeletonResult>(`/api/campaigns/${campaignId}/guided-skeleton`, skeleton);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** IA : réponses proposées aux questions d'une méthode, à partir de l'idée du MJ (rien n'est enregistré). */
|
||||||
|
suggest(campaignId: string, request: GuidedSuggestRequest): Observable<{ answers: Record<string, string> }> {
|
||||||
|
return this.http.post<{ answers: Record<string, string> }>(`/api/campaigns/${campaignId}/guided-assist`, request);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,7 +100,12 @@ export class SessionRulesPanelComponent implements OnChanges, OnDestroy {
|
|||||||
private applySystem(gs: GameSystem | null): void {
|
private applySystem(gs: GameSystem | null): void {
|
||||||
this.gameSystem = gs;
|
this.gameSystem = gs;
|
||||||
if (!gs) { this.state = 'noSystem'; return; }
|
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; }
|
if (this.sections.length === 0) { this.state = 'noRules'; return; }
|
||||||
this.pinned = this.readPins();
|
this.pinned = this.readPins();
|
||||||
this.opened = new Set(this.sections.filter(s => this.pinned.has(s.title)).map(s => s.id));
|
this.opened = new Set(this.sections.filter(s => this.pinned.has(s.title)).map(s => s.id));
|
||||||
|
|||||||
@@ -141,8 +141,15 @@ export class RemoteAccessSectionComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
formatDate(value?: string | null): string {
|
formatDate(value?: string | null): string {
|
||||||
if (!value) return '—';
|
if (!value) return '—';
|
||||||
const lang = this.translate.currentLang;
|
// getCurrentLang() et non `currentLang` : en ngx-translate 18, `currentLang` est un
|
||||||
return new Date(value).toLocaleString(lang ? String(lang) : undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
// signal ; le convertir en texte donnait une locale invalide → RangeError qui
|
||||||
|
// interrompait l'affichage de toute la page Paramètres dès qu'un appareil était appairé.
|
||||||
|
const lang = this.translate.getCurrentLang() === 'en' ? 'en-GB' : 'fr-FR';
|
||||||
|
try {
|
||||||
|
return new Date(value).toLocaleString(lang, { dateStyle: 'medium', timeStyle: 'short' });
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private apply(status: RemoteAccessStatus): void {
|
private apply(status: RemoteAccessStatus): void {
|
||||||
|
|||||||
@@ -1289,7 +1289,14 @@
|
|||||||
"importFailedReason": "Import failed: {{reason}}",
|
"importFailedReason": "Import failed: {{reason}}",
|
||||||
"importNoRules": "No usable rules could be extracted from this PDF (scan without OCR, or unrecognized content).",
|
"importNoRules": "No usable rules could be extracted from this PDF (scan without OCR, or unrecognized content).",
|
||||||
"importOcrSuffix": " (including {{count}} page(s) via OCR)",
|
"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": {
|
"ollamaModelManager": {
|
||||||
"installedModels": "Installed models",
|
"installedModels": "Installed models",
|
||||||
@@ -2613,7 +2620,7 @@
|
|||||||
"tagline": "A short adventure in five beats in a single place: a guardian, a challenge, a setback, the climax, the reward."
|
"tagline": "A short adventure in five beats in a single place: a guardian, a challenge, a setback, the climax, the reward."
|
||||||
},
|
},
|
||||||
"chooserTitle": "Write with a guided method",
|
"chooserTitle": "Write with a guided method",
|
||||||
"chooserIntro": "Pick a structure: the wizard asks you the right questions, step by step, then creates the chapter and its scenes. You write everything; nothing is generated.",
|
"chooserIntro": "Pick a structure: the wizard asks you the right questions, step by step, then creates the chapter and its scenes. You can write everything yourself, or start from an idea and let the AI suggest answers that you then edit.",
|
||||||
"chooserStart": "Start",
|
"chooserStart": "Start",
|
||||||
"chooserScenes": "{{count}} scenes",
|
"chooserScenes": "{{count}} scenes",
|
||||||
"reviewClock": "A \"{{name}}\" clock with {{segments}} segments will be created in each playthrough of the campaign.",
|
"reviewClock": "A \"{{name}}\" clock with {{segments}} segments will be created in each playthrough of the campaign.",
|
||||||
@@ -3113,6 +3120,18 @@
|
|||||||
},
|
},
|
||||||
"clockName": "The enemy's plan"
|
"clockName": "The enemy's plan"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"ai": {
|
||||||
|
"title": "Your starting idea",
|
||||||
|
"placeholder": "A few words are enough: a tower lighting up again, a forgotten pact, an autumn fair…",
|
||||||
|
"suggestAll": "Suggest the whole adventure",
|
||||||
|
"suggestStep": "Suggest for this step",
|
||||||
|
"thinking": "The AI is thinking…",
|
||||||
|
"undo": "Undo the suggestion",
|
||||||
|
"filled": "{{count}} field(s) filled by the AI: read them and change what you don't like.",
|
||||||
|
"nothingToFill": "Every field is already filled: clear the ones you want the AI to suggest.",
|
||||||
|
"error": "The AI didn't answer. Check the AI engine in Settings, then try again.",
|
||||||
|
"hint": "The AI only fills empty fields: it never touches what you wrote."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"remoteAccess": {
|
"remoteAccess": {
|
||||||
|
|||||||
@@ -1289,7 +1289,14 @@
|
|||||||
"importFailedReason": "Échec de l'import : {{reason}}",
|
"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).",
|
"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)",
|
"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": {
|
"ollamaModelManager": {
|
||||||
"installedModels": "Modèles installés",
|
"installedModels": "Modèles installés",
|
||||||
@@ -2613,7 +2620,7 @@
|
|||||||
"tagline": "Une aventure courte en cinq temps dans un même lieu : un gardien, une épreuve, un revers, le climax, la récompense."
|
"tagline": "Une aventure courte en cinq temps dans un même lieu : un gardien, une épreuve, un revers, le climax, la récompense."
|
||||||
},
|
},
|
||||||
"chooserTitle": "Écrire avec une méthode guidée",
|
"chooserTitle": "Écrire avec une méthode guidée",
|
||||||
"chooserIntro": "Choisissez une structure : l'assistant vous pose les bonnes questions, étape par étape, puis crée le chapitre et ses scènes. Vous écrivez tout ; rien n'est généré.",
|
"chooserIntro": "Choisissez une structure : l'assistant vous pose les bonnes questions, étape par étape, puis crée le chapitre et ses scènes. Vous pouvez tout écrire vous-même, ou partir d'une idée et laisser l'IA proposer des réponses que vous corrigez.",
|
||||||
"chooserStart": "Commencer",
|
"chooserStart": "Commencer",
|
||||||
"chooserScenes": "{{count}} scènes",
|
"chooserScenes": "{{count}} scènes",
|
||||||
"reviewClock": "Une horloge « {{name}} » de {{segments}} segments sera créée dans chaque partie de la campagne.",
|
"reviewClock": "Une horloge « {{name}} » de {{segments}} segments sera créée dans chaque partie de la campagne.",
|
||||||
@@ -3113,6 +3120,18 @@
|
|||||||
},
|
},
|
||||||
"clockName": "Le plan de l'adversaire"
|
"clockName": "Le plan de l'adversaire"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"ai": {
|
||||||
|
"title": "Ton idée de départ",
|
||||||
|
"placeholder": "Quelques mots suffisent : une tour qui se rallume, un pacte oublié, une foire d'automne…",
|
||||||
|
"suggestAll": "Proposer toute l'aventure",
|
||||||
|
"suggestStep": "Proposer pour cette étape",
|
||||||
|
"thinking": "L'IA réfléchit…",
|
||||||
|
"undo": "Annuler la proposition",
|
||||||
|
"filled": "{{count}} champ(s) rempli(s) par l'IA : relis-les et corrige ce qui ne te plaît pas.",
|
||||||
|
"nothingToFill": "Tous les champs sont déjà remplis : vide ceux que tu veux faire proposer par l'IA.",
|
||||||
|
"error": "L'IA n'a pas répondu. Vérifie le moteur IA dans les Paramètres, puis réessaie.",
|
||||||
|
"hint": "L'IA ne remplit que les champs vides : elle ne touche jamais à ce que tu as écrit."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"remoteAccess": {
|
"remoteAccess": {
|
||||||
|
|||||||
@@ -53,7 +53,14 @@
|
|||||||
"importFailedReason": "Import failed: {{reason}}",
|
"importFailedReason": "Import failed: {{reason}}",
|
||||||
"importNoRules": "No usable rules could be extracted from this PDF (scan without OCR, or unrecognized content).",
|
"importNoRules": "No usable rules could be extracted from this PDF (scan without OCR, or unrecognized content).",
|
||||||
"importOcrSuffix": " (including {{count}} page(s) via OCR)",
|
"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": {
|
"ollamaModelManager": {
|
||||||
"installedModels": "Installed models",
|
"installedModels": "Installed models",
|
||||||
|
|||||||
@@ -53,7 +53,14 @@
|
|||||||
"importFailedReason": "Échec de l'import : {{reason}}",
|
"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).",
|
"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)",
|
"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": {
|
"ollamaModelManager": {
|
||||||
"installedModels": "Modèles installés",
|
"installedModels": "Modèles installés",
|
||||||
|
|||||||
@@ -234,7 +234,7 @@
|
|||||||
"tagline": "A short adventure in five beats in a single place: a guardian, a challenge, a setback, the climax, the reward."
|
"tagline": "A short adventure in five beats in a single place: a guardian, a challenge, a setback, the climax, the reward."
|
||||||
},
|
},
|
||||||
"chooserTitle": "Write with a guided method",
|
"chooserTitle": "Write with a guided method",
|
||||||
"chooserIntro": "Pick a structure: the wizard asks you the right questions, step by step, then creates the chapter and its scenes. You write everything; nothing is generated.",
|
"chooserIntro": "Pick a structure: the wizard asks you the right questions, step by step, then creates the chapter and its scenes. You can write everything yourself, or start from an idea and let the AI suggest answers that you then edit.",
|
||||||
"chooserStart": "Start",
|
"chooserStart": "Start",
|
||||||
"chooserScenes": "{{count}} scenes",
|
"chooserScenes": "{{count}} scenes",
|
||||||
"reviewClock": "A \"{{name}}\" clock with {{segments}} segments will be created in each playthrough of the campaign.",
|
"reviewClock": "A \"{{name}}\" clock with {{segments}} segments will be created in each playthrough of the campaign.",
|
||||||
@@ -734,6 +734,18 @@
|
|||||||
},
|
},
|
||||||
"clockName": "The enemy's plan"
|
"clockName": "The enemy's plan"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"ai": {
|
||||||
|
"title": "Your starting idea",
|
||||||
|
"placeholder": "A few words are enough: a tower lighting up again, a forgotten pact, an autumn fair…",
|
||||||
|
"suggestAll": "Suggest the whole adventure",
|
||||||
|
"suggestStep": "Suggest for this step",
|
||||||
|
"thinking": "The AI is thinking…",
|
||||||
|
"undo": "Undo the suggestion",
|
||||||
|
"filled": "{{count}} field(s) filled by the AI: read them and change what you don't like.",
|
||||||
|
"nothingToFill": "Every field is already filled: clear the ones you want the AI to suggest.",
|
||||||
|
"error": "The AI didn't answer. Check the AI engine in Settings, then try again.",
|
||||||
|
"hint": "The AI only fills empty fields: it never touches what you wrote."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -234,7 +234,7 @@
|
|||||||
"tagline": "Une aventure courte en cinq temps dans un même lieu : un gardien, une épreuve, un revers, le climax, la récompense."
|
"tagline": "Une aventure courte en cinq temps dans un même lieu : un gardien, une épreuve, un revers, le climax, la récompense."
|
||||||
},
|
},
|
||||||
"chooserTitle": "Écrire avec une méthode guidée",
|
"chooserTitle": "Écrire avec une méthode guidée",
|
||||||
"chooserIntro": "Choisissez une structure : l'assistant vous pose les bonnes questions, étape par étape, puis crée le chapitre et ses scènes. Vous écrivez tout ; rien n'est généré.",
|
"chooserIntro": "Choisissez une structure : l'assistant vous pose les bonnes questions, étape par étape, puis crée le chapitre et ses scènes. Vous pouvez tout écrire vous-même, ou partir d'une idée et laisser l'IA proposer des réponses que vous corrigez.",
|
||||||
"chooserStart": "Commencer",
|
"chooserStart": "Commencer",
|
||||||
"chooserScenes": "{{count}} scènes",
|
"chooserScenes": "{{count}} scènes",
|
||||||
"reviewClock": "Une horloge « {{name}} » de {{segments}} segments sera créée dans chaque partie de la campagne.",
|
"reviewClock": "Une horloge « {{name}} » de {{segments}} segments sera créée dans chaque partie de la campagne.",
|
||||||
@@ -734,6 +734,18 @@
|
|||||||
},
|
},
|
||||||
"clockName": "Le plan de l'adversaire"
|
"clockName": "Le plan de l'adversaire"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"ai": {
|
||||||
|
"title": "Ton idée de départ",
|
||||||
|
"placeholder": "Quelques mots suffisent : une tour qui se rallume, un pacte oublié, une foire d'automne…",
|
||||||
|
"suggestAll": "Proposer toute l'aventure",
|
||||||
|
"suggestStep": "Proposer pour cette étape",
|
||||||
|
"thinking": "L'IA réfléchit…",
|
||||||
|
"undo": "Annuler la proposition",
|
||||||
|
"filled": "{{count}} champ(s) rempli(s) par l'IA : relis-les et corrige ce qui ne te plaît pas.",
|
||||||
|
"nothingToFill": "Tous les champs sont déjà remplis : vide ceux que tu veux faire proposer par l'IA.",
|
||||||
|
"error": "L'IA n'a pas répondu. Vérifie le moteur IA dans les Paramètres, puis réessaie.",
|
||||||
|
"hint": "L'IA ne remplit que les champs vides : elle ne touche jamais à ce que tu as écrit."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user