Compare commits
25 Commits
v0.11.2-be
...
v0.12.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
| cff2ceb0b9 | |||
| d1a11823bc | |||
| e1da369cfa | |||
| 177bf6e781 | |||
| 0303786aef | |||
| 7dec288829 | |||
| e26d11a99f | |||
| 3d1cf6e495 | |||
| 0e4820a2f8 | |||
| 092898e379 | |||
| 5061457f76 | |||
| c1811b0040 | |||
| 8369886f42 | |||
| e7aa67bc42 | |||
| 91069525a5 | |||
| 23878f1c63 | |||
| 6acad41672 | |||
| 05bbe64841 | |||
| d772e969ea | |||
| 04816ae9df | |||
| 49a94bb73e | |||
| b0e8fade03 | |||
| 341f6a5aae | |||
| 6c7dbff6a0 | |||
| 833280c784 |
5
brain/app/api/__init__.py
Normal file
5
brain/app/api/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Adapter web (architecture hexagonale) : routers FastAPI, DTOs et factories DI.
|
||||
|
||||
C'est la FRONTIÈRE HTTP du Brain : validation Pydantic, mapping DTO ↔ domaine,
|
||||
traduction des erreurs domaine → HTTP. Aucune logique métier ici.
|
||||
"""
|
||||
215
brain/app/api/chat_dto.py
Normal file
215
brain/app/api/chat_dto.py
Normal file
@@ -0,0 +1,215 @@
|
||||
"""DTOs Pydantic du chat contextuel — frontière HTTP avec le Core Java.
|
||||
|
||||
C'est ici (et seulement ici, avec les autres modules de `app.api`) qu'on
|
||||
utilise Pydantic : le domaine ne voit que des dataclasses (voir chat_mapping).
|
||||
"""
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ChatMessageDTO(BaseModel):
|
||||
"""Un message de la conversation. Rôles acceptés : user, assistant, system."""
|
||||
|
||||
role: str = Field(pattern="^(user|assistant|system)$")
|
||||
content: str
|
||||
|
||||
|
||||
class PageSummaryDTO(BaseModel):
|
||||
"""Résumé enrichi d'une page : identité + contenu + interconnexions.
|
||||
|
||||
Depuis b9 : values/tags/related_page_titles sont optionnels côté JSON —
|
||||
le Core Java ne les sérialise que s'ils sont non-vides (payload léger
|
||||
pour un Lore avec beaucoup de pages vierges).
|
||||
"""
|
||||
|
||||
title: str
|
||||
template_name: str
|
||||
values: dict[str, str] = Field(default_factory=dict)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
related_page_titles: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class LoreContextDTO(BaseModel):
|
||||
"""Carte structurelle du Lore avec contenu des pages (b9+)."""
|
||||
|
||||
lore_name: str
|
||||
lore_description: str | None = None
|
||||
folders: dict[str, list[PageSummaryDTO]] = Field(default_factory=dict)
|
||||
tags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PageContextDTO(BaseModel):
|
||||
"""Contexte d'une page spécifique pour focaliser le chat (optionnel)."""
|
||||
|
||||
title: str
|
||||
template_name: str
|
||||
template_fields: list[str] = Field(default_factory=list)
|
||||
values: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class SceneBranchHintDTO(BaseModel):
|
||||
"""Indice d'une branche narrative (le Core a deja resolu le nom cible)."""
|
||||
|
||||
label: str
|
||||
target_scene_name: str
|
||||
condition: str | None = None
|
||||
|
||||
|
||||
class RoomBranchHintDTO(BaseModel):
|
||||
"""Sortie d'une pièce vers une autre pièce du même lieu (donjon)."""
|
||||
|
||||
label: str
|
||||
target_room_name: str
|
||||
condition: str | None = None
|
||||
|
||||
|
||||
class RoomSummaryDTO(BaseModel):
|
||||
"""Pièce d'un lieu explorable. Omise par le Core si la scène est classique."""
|
||||
|
||||
name: str
|
||||
floor: int | None = None
|
||||
description: str | None = None
|
||||
enemies: str | None = None
|
||||
branches: list[RoomBranchHintDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SceneSummaryDTO(BaseModel):
|
||||
"""Résumé d'une scène : nom + description courte (synopsis)."""
|
||||
|
||||
name: str
|
||||
description: str | None = None
|
||||
# Optionnel : le Core Java ne serialise illustration_count QUE si > 0
|
||||
# (payload plus leger). Defaut 0 = pas d'illustrations ou champ absent.
|
||||
illustration_count: int = 0
|
||||
# Branches narratives sortantes, omises cote Core si vides.
|
||||
branches: list[SceneBranchHintDTO] = Field(default_factory=list)
|
||||
# Pièces du lieu explorable, omises par Core si scène classique.
|
||||
rooms: list[RoomSummaryDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ChapterSummaryDTO(BaseModel):
|
||||
"""Résumé d'un chapitre : nom + description courte + ses scènes."""
|
||||
|
||||
name: str
|
||||
description: str | None = None
|
||||
scenes: list[SceneSummaryDTO] = Field(default_factory=list)
|
||||
illustration_count: int = 0
|
||||
|
||||
|
||||
class ArcSummaryDTO(BaseModel):
|
||||
"""Résumé d'un arc narratif : nom + description courte + ses chapitres."""
|
||||
|
||||
name: str
|
||||
description: str | None = None
|
||||
chapters: list[ChapterSummaryDTO] = Field(default_factory=list)
|
||||
illustration_count: int = 0
|
||||
|
||||
|
||||
class CharacterSummaryDTO(BaseModel):
|
||||
"""Résumé d'un PJ : nom + snippet. Pas de fiche complète au niveau résumé."""
|
||||
|
||||
name: str
|
||||
snippet: str = ""
|
||||
|
||||
|
||||
class NpcSummaryDTO(BaseModel):
|
||||
"""Résumé d'un PNJ : symétrique à CharacterSummaryDTO."""
|
||||
|
||||
name: str
|
||||
snippet: str = ""
|
||||
|
||||
|
||||
class CampaignContextDTO(BaseModel):
|
||||
"""Carte narrative enrichie : arcs → chapitres → scènes avec synopsis."""
|
||||
|
||||
campaign_name: str
|
||||
campaign_description: str | None = None
|
||||
arcs: list[ArcSummaryDTO] = Field(default_factory=list)
|
||||
characters: list[CharacterSummaryDTO] = Field(default_factory=list)
|
||||
npcs: list[NpcSummaryDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class NarrativeEntityDTO(BaseModel):
|
||||
"""Entité narrative (arc/chapter/scene/character) en cours d'édition — focus optionnel."""
|
||||
|
||||
entity_type: str = Field(pattern="^(arc|chapter|scene|character|npc)$")
|
||||
title: str
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class GameSystemContextDTO(BaseModel):
|
||||
"""Règles de JDR présélectionnées par le Core (filtrées par intent).
|
||||
|
||||
Les sections sont un dict titre_H2 → contenu_markdown. Peuvent être
|
||||
vides si aucune section ne matchait l'intent de génération courant.
|
||||
"""
|
||||
|
||||
system_name: str
|
||||
system_description: str | None = None
|
||||
sections: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class JournalEntrySummaryDTO(BaseModel):
|
||||
"""Une entrée du journal de session.
|
||||
|
||||
`source_session_name` est présent uniquement pour les évènements issus
|
||||
des sessions précédentes — sert à ancrer temporellement dans le prompt.
|
||||
"""
|
||||
|
||||
type: str
|
||||
content: str
|
||||
occurred_at: str | None = None
|
||||
source_session_name: str | None = None
|
||||
|
||||
|
||||
class QuestSummaryDTO(BaseModel):
|
||||
"""Résumé d'une quête (Chapter dans un Arc HUB). Voir QuestSummary côté domaine."""
|
||||
|
||||
name: str
|
||||
arc_name: str
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class SessionContextDTO(BaseModel):
|
||||
"""Contexte d'une Session de jeu en cours (Play Context).
|
||||
|
||||
Combine le journal complet (`entries`), les EVENTs des sessions précédentes
|
||||
(`previous_events`), et — depuis l'ajout du mode Hub — l'état des quêtes
|
||||
Hub de la campagne (disponibles / en cours / verrouillées) plus les flags
|
||||
narratifs actuellement actifs.
|
||||
"""
|
||||
|
||||
session_name: str
|
||||
active: bool
|
||||
started_at: str | None = None
|
||||
entries: list[JournalEntrySummaryDTO] = Field(default_factory=list)
|
||||
previous_events: list[JournalEntrySummaryDTO] = Field(default_factory=list)
|
||||
available_quests: list[QuestSummaryDTO] = Field(default_factory=list)
|
||||
in_progress_quests: list[QuestSummaryDTO] = Field(default_factory=list)
|
||||
locked_quest_titles: list[str] = Field(default_factory=list)
|
||||
active_flags: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ChatStreamRequestDTO(BaseModel):
|
||||
"""Requête de chat streamé : historique + contextes structurels.
|
||||
|
||||
Les contextes (lore, page, campaign, narrative_entity, session) sont
|
||||
optionnels, mais au moins l'un des contextes "racines" (lore_context,
|
||||
campaign_context ou session_context) doit être fourni. Le validateur
|
||||
`check_scope` applique cette règle à la frontière HTTP.
|
||||
"""
|
||||
|
||||
messages: list[ChatMessageDTO] = Field(min_length=1)
|
||||
lore_context: LoreContextDTO | None = None
|
||||
page_context: PageContextDTO | None = None
|
||||
campaign_context: CampaignContextDTO | None = None
|
||||
narrative_entity: NarrativeEntityDTO | None = None
|
||||
game_system_context: GameSystemContextDTO | None = None
|
||||
session_context: SessionContextDTO | None = None
|
||||
|
||||
def has_scope(self) -> bool:
|
||||
"""Vrai si au moins un contexte racine (Lore, Campagne ou Session) est fourni."""
|
||||
return (
|
||||
self.lore_context is not None
|
||||
or self.campaign_context is not None
|
||||
or self.session_context is not None
|
||||
)
|
||||
192
brain/app/api/chat_mapping.py
Normal file
192
brain/app/api/chat_mapping.py
Normal file
@@ -0,0 +1,192 @@
|
||||
"""Mapping DTO → domaine (couche anti-corruption de la frontière HTTP).
|
||||
|
||||
Traduit les DTOs Pydantic du chat contextuel en dataclasses du domaine :
|
||||
le cœur métier ne dépend ainsi jamais de Pydantic ni du format JSON du Core.
|
||||
"""
|
||||
from app.api.chat_dto import (
|
||||
CampaignContextDTO,
|
||||
GameSystemContextDTO,
|
||||
JournalEntrySummaryDTO,
|
||||
LoreContextDTO,
|
||||
NarrativeEntityDTO,
|
||||
PageContextDTO,
|
||||
PageSummaryDTO,
|
||||
QuestSummaryDTO,
|
||||
SessionContextDTO,
|
||||
)
|
||||
from app.domain.models import (
|
||||
ArcSummary,
|
||||
CampaignStructuralContext,
|
||||
ChapterSummary,
|
||||
CharacterSummary,
|
||||
GameSystemContext,
|
||||
JournalEntrySummary,
|
||||
LoreStructuralContext,
|
||||
NarrativeEntityContext,
|
||||
NpcSummary,
|
||||
PageContext,
|
||||
PageSummary,
|
||||
QuestSummary,
|
||||
RoomBranchHint,
|
||||
RoomSummary,
|
||||
SceneBranchHint,
|
||||
SceneSummary,
|
||||
SessionContext,
|
||||
)
|
||||
|
||||
|
||||
def to_lore_context(dto: LoreContextDTO | None) -> LoreStructuralContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
return LoreStructuralContext(
|
||||
lore_name=dto.lore_name,
|
||||
lore_description=dto.lore_description,
|
||||
folders={
|
||||
folder: [_to_page_summary(p) for p in pages]
|
||||
for folder, pages in dto.folders.items()
|
||||
},
|
||||
tags=dto.tags,
|
||||
)
|
||||
|
||||
|
||||
def _to_page_summary(dto: PageSummaryDTO) -> PageSummary:
|
||||
return PageSummary(
|
||||
title=dto.title,
|
||||
template_name=dto.template_name,
|
||||
values=dict(dto.values),
|
||||
tags=list(dto.tags),
|
||||
related_page_titles=list(dto.related_page_titles),
|
||||
)
|
||||
|
||||
|
||||
def to_page_context(dto: PageContextDTO | None) -> PageContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
return PageContext(
|
||||
title=dto.title,
|
||||
template_name=dto.template_name,
|
||||
template_fields=dto.template_fields,
|
||||
values=dto.values,
|
||||
)
|
||||
|
||||
|
||||
def to_campaign_context(dto: CampaignContextDTO | None) -> CampaignStructuralContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
arcs = [
|
||||
ArcSummary(
|
||||
name=arc.name,
|
||||
description=arc.description,
|
||||
illustration_count=arc.illustration_count,
|
||||
chapters=[
|
||||
ChapterSummary(
|
||||
name=ch.name,
|
||||
description=ch.description,
|
||||
illustration_count=ch.illustration_count,
|
||||
scenes=[
|
||||
SceneSummary(
|
||||
name=sc.name,
|
||||
description=sc.description,
|
||||
illustration_count=sc.illustration_count,
|
||||
branches=[
|
||||
SceneBranchHint(
|
||||
label=br.label,
|
||||
target_scene_name=br.target_scene_name,
|
||||
condition=br.condition,
|
||||
)
|
||||
for br in sc.branches
|
||||
],
|
||||
rooms=[
|
||||
RoomSummary(
|
||||
name=room.name,
|
||||
floor=room.floor,
|
||||
description=room.description,
|
||||
enemies=room.enemies,
|
||||
branches=[
|
||||
RoomBranchHint(
|
||||
label=rb.label,
|
||||
target_room_name=rb.target_room_name,
|
||||
condition=rb.condition,
|
||||
)
|
||||
for rb in room.branches
|
||||
],
|
||||
)
|
||||
for room in sc.rooms
|
||||
],
|
||||
)
|
||||
for sc in ch.scenes
|
||||
],
|
||||
)
|
||||
for ch in arc.chapters
|
||||
],
|
||||
)
|
||||
for arc in dto.arcs
|
||||
]
|
||||
characters = [
|
||||
CharacterSummary(name=c.name, snippet=c.snippet)
|
||||
for c in dto.characters
|
||||
]
|
||||
npcs = [
|
||||
NpcSummary(name=n.name, snippet=n.snippet)
|
||||
for n in dto.npcs
|
||||
]
|
||||
return CampaignStructuralContext(
|
||||
campaign_name=dto.campaign_name,
|
||||
campaign_description=dto.campaign_description,
|
||||
arcs=arcs,
|
||||
characters=characters,
|
||||
npcs=npcs,
|
||||
)
|
||||
|
||||
|
||||
def to_narrative_entity(dto: NarrativeEntityDTO | None) -> NarrativeEntityContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
return NarrativeEntityContext(
|
||||
entity_type=dto.entity_type,
|
||||
title=dto.title,
|
||||
fields=dict(dto.fields),
|
||||
)
|
||||
|
||||
|
||||
def to_game_system_context(dto: GameSystemContextDTO | None) -> GameSystemContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
return GameSystemContext(
|
||||
system_name=dto.system_name,
|
||||
system_description=dto.system_description,
|
||||
sections=dict(dto.sections),
|
||||
)
|
||||
|
||||
|
||||
def to_session_context(dto: SessionContextDTO | None) -> SessionContext | None:
|
||||
if dto is None:
|
||||
return None
|
||||
return SessionContext(
|
||||
session_name=dto.session_name,
|
||||
active=dto.active,
|
||||
started_at=dto.started_at,
|
||||
entries=[_to_journal_entry(e) for e in dto.entries],
|
||||
previous_events=[_to_journal_entry(e) for e in dto.previous_events],
|
||||
available_quests=[_to_quest_summary(q) for q in dto.available_quests],
|
||||
in_progress_quests=[_to_quest_summary(q) for q in dto.in_progress_quests],
|
||||
locked_quest_titles=list(dto.locked_quest_titles),
|
||||
active_flags=list(dto.active_flags),
|
||||
)
|
||||
|
||||
|
||||
def _to_quest_summary(dto: QuestSummaryDTO) -> QuestSummary:
|
||||
return QuestSummary(
|
||||
name=dto.name,
|
||||
arc_name=dto.arc_name,
|
||||
description=dto.description,
|
||||
)
|
||||
|
||||
|
||||
def _to_journal_entry(dto: JournalEntrySummaryDTO) -> JournalEntrySummary:
|
||||
return JournalEntrySummary(
|
||||
type=dto.type,
|
||||
content=dto.content,
|
||||
occurred_at=dto.occurred_at,
|
||||
source_session_name=dto.source_session_name,
|
||||
)
|
||||
26
brain/app/api/common.py
Normal file
26
brain/app/api/common.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""Utilitaires partagés des routers : encodage SSE + garde-fous d'upload PDF."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
# Garde-fou taille : un livre de règles dépasse rarement quelques dizaines de Mo.
|
||||
# Au-delà, on refuse (probable erreur d'upload) plutôt que d'OOM le conteneur.
|
||||
MAX_PDF_BYTES = 60 * 1024 * 1024 # 60 Mo
|
||||
|
||||
|
||||
def sse_event(event: str, data: dict) -> str:
|
||||
"""Encode un évènement Server-Sent Events (accents préservés)."""
|
||||
return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def pdf_upload_error(content: bytes) -> str | None:
|
||||
"""Message d'erreur si l'upload PDF est invalide (vide / trop gros), sinon None.
|
||||
|
||||
Utilisé par les flux SSE, où l'erreur doit partir en évènement `error`
|
||||
plutôt qu'en HTTPException (le flux est déjà ouvert en 200).
|
||||
"""
|
||||
if not content:
|
||||
return "Fichier PDF vide."
|
||||
if len(content) > MAX_PDF_BYTES:
|
||||
return f"PDF trop volumineux (> {MAX_PDF_BYTES // (1024 * 1024)} Mo)."
|
||||
return None
|
||||
156
brain/app/api/deps.py
Normal file
156
brain/app/api/deps.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""Factories d'injection de dépendance — le point d'inversion de l'hexagone.
|
||||
|
||||
C'est ICI (et seulement ici) qu'on choisit QUEL adapter concret incarne chaque
|
||||
port (LLM, embeddings, extracteur PDF), en fonction des Settings — modifiables
|
||||
à chaud depuis l'écran Paramètres de l'UI. Les routers ne connaissent que les
|
||||
ports et les use cases, jamais Ollama/Mistral/etc.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
|
||||
from app.application.adapt_campaign import AdaptCampaignUseCase
|
||||
from app.application.chat import ChatUseCase
|
||||
from app.application.embeddings import EmbeddingError
|
||||
from app.application.generate_page import GeneratePageUseCase
|
||||
from app.application.import_campaign import ImportCampaignUseCase
|
||||
from app.application.import_rules import ImportRulesUseCase
|
||||
from app.application.notebook_chat import NotebookChatUseCase
|
||||
from app.application.notebook_deep import NotebookDeepUseCase
|
||||
from app.application.notebook_rag import NotebookRagUseCase
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
from app.infrastructure.gemini_adapter import GeminiLLMProvider
|
||||
from app.infrastructure.mistral_adapter import MistralLLMProvider
|
||||
from app.infrastructure.mistral_embedding_adapter import MistralEmbeddingProvider
|
||||
from app.infrastructure.ollama_adapter import OllamaLLMProvider
|
||||
from app.infrastructure.ollama_embedding_adapter import OllamaEmbeddingProvider
|
||||
from app.infrastructure.onemin_adapter import OneMinAiLLMProvider
|
||||
from app.infrastructure.openrouter_adapter import OpenRouterLLMProvider
|
||||
from app.infrastructure.pdf_extractor import PyMuPdfTextExtractor
|
||||
|
||||
# Extracteur PDF partagé : la détection OCR (version Tesseract) a un coût
|
||||
# (subprocess) qu'on ne veut pas payer à chaque requête → singleton module.
|
||||
_PDF_EXTRACTOR = PyMuPdfTextExtractor()
|
||||
|
||||
|
||||
def get_llm_provider(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> LLMProvider:
|
||||
"""Factory d'adapter — point d'inversion de dépendance.
|
||||
|
||||
C'est ici (et uniquement ici) qu'on choisit QUEL adapter concret
|
||||
incarne le port, en fonction du champ `llm_provider` des Settings
|
||||
(modifiable a chaud depuis l'ecran Parametres de l'UI).
|
||||
"""
|
||||
try:
|
||||
if settings.llm_provider == "onemin":
|
||||
return OneMinAiLLMProvider(settings)
|
||||
if settings.llm_provider == "openrouter":
|
||||
return OpenRouterLLMProvider(settings)
|
||||
if settings.llm_provider == "mistral":
|
||||
return MistralLLMProvider(settings)
|
||||
if settings.llm_provider == "gemini":
|
||||
return GeminiLLMProvider(settings)
|
||||
return OllamaLLMProvider(settings)
|
||||
except LLMProviderError as exc:
|
||||
# Ex : cle 1min.ai manquante. On renvoie du 400 plutot que du 500
|
||||
# pour que le frontend puisse afficher un message actionnable.
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def get_generate_page_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> GeneratePageUseCase:
|
||||
"""Factory du use case — injecte le port LLMProvider sans connaître l'adapter."""
|
||||
return GeneratePageUseCase(llm=llm)
|
||||
|
||||
|
||||
def get_chat_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> ChatUseCase:
|
||||
"""Factory du use case chat.
|
||||
|
||||
L'adapter OllamaLLMProvider satisfait les deux protocoles (LLMProvider
|
||||
et LLMChatProvider) par duck typing ; on lui passe la même instance.
|
||||
"""
|
||||
return ChatUseCase(llm=llm) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def get_import_rules_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> ImportRulesUseCase:
|
||||
"""Factory du use case d'import de règles PDF (extraction + structuration)."""
|
||||
return ImportRulesUseCase(
|
||||
llm=llm, extractor=_PDF_EXTRACTOR, chunk_target_tokens=settings.import_chunk_tokens)
|
||||
|
||||
|
||||
def get_import_campaign_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> ImportCampaignUseCase:
|
||||
"""Factory du use case d'import de campagne PDF (extraction + arborescence)."""
|
||||
return ImportCampaignUseCase(
|
||||
llm=llm,
|
||||
extractor=_PDF_EXTRACTOR,
|
||||
chunk_target_tokens=settings.import_chunk_tokens,
|
||||
map_concurrency=settings.llm_map_concurrency,
|
||||
)
|
||||
|
||||
|
||||
def get_adapt_campaign_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> AdaptCampaignUseCase:
|
||||
"""Factory du use case d'adaptation d'un PDF à une campagne (conseils streamés)."""
|
||||
# L'adapter satisfait aussi LLMChatProvider (stream_chat) par duck typing.
|
||||
# Budget d'entrée = taille de morceau configurée (qui passe déjà côté provider).
|
||||
return AdaptCampaignUseCase( # type: ignore[arg-type]
|
||||
llm=llm, extractor=_PDF_EXTRACTOR, max_input_tokens=settings.import_chunk_tokens)
|
||||
|
||||
|
||||
def get_embedding_provider(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
):
|
||||
"""Factory de l'adapter d'embeddings (RAG) selon `embedding_provider`."""
|
||||
try:
|
||||
if settings.embedding_provider == "mistral":
|
||||
return MistralEmbeddingProvider(settings)
|
||||
return OllamaEmbeddingProvider(settings)
|
||||
except EmbeddingError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def get_notebook_rag_use_case(
|
||||
embedder: Annotated[object, Depends(get_embedding_provider)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> NotebookRagUseCase:
|
||||
return NotebookRagUseCase(
|
||||
extractor=_PDF_EXTRACTOR,
|
||||
embedder=embedder, # type: ignore[arg-type]
|
||||
min_score=settings.rag_min_score,
|
||||
)
|
||||
|
||||
|
||||
def get_notebook_chat_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
rag: Annotated[NotebookRagUseCase, Depends(get_notebook_rag_use_case)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> NotebookChatUseCase:
|
||||
return NotebookChatUseCase(
|
||||
rag=rag, llm=llm, rerank_enabled=settings.rag_rerank) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def get_notebook_deep_use_case(
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
embedder: Annotated[object, Depends(get_embedding_provider)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> NotebookDeepUseCase:
|
||||
return NotebookDeepUseCase(
|
||||
llm=llm,
|
||||
batch_tokens=settings.import_chunk_tokens,
|
||||
map_concurrency=settings.llm_map_concurrency,
|
||||
embedder=embedder,
|
||||
summary_filter=settings.deep_summary_filter,
|
||||
)
|
||||
5
brain/app/api/routers/__init__.py
Normal file
5
brain/app/api/routers/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Routers FastAPI du Brain, un par responsabilité métier.
|
||||
|
||||
Chemins inchangés par rapport à l'ancien main.py monolithique : le Core Java
|
||||
et le frontend ne voient AUCUNE différence.
|
||||
"""
|
||||
119
brain/app/api/routers/chat.py
Normal file
119
brain/app/api/routers/chat.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Endpoint du chat contextuel (/chat/stream) : Structural Context + jauge tokens."""
|
||||
import json
|
||||
from typing import Annotated, AsyncIterator
|
||||
|
||||
import tiktoken
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from app.api.chat_dto import ChatStreamRequestDTO
|
||||
from app.api.chat_mapping import (
|
||||
to_campaign_context,
|
||||
to_game_system_context,
|
||||
to_lore_context,
|
||||
to_narrative_entity,
|
||||
to_page_context,
|
||||
to_session_context,
|
||||
)
|
||||
from app.api.deps import get_chat_use_case
|
||||
from app.application.chat import ChatUseCase
|
||||
from app.core.config import get_settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Encodeur tiktoken partagé — chargé une fois pour éviter le coût de lookup
|
||||
# à chaque requête. On utilise cl100k_base (GPT-3.5/4) comme tokenizer
|
||||
# universel approximatif : ±10% d'écart avec Llama/Gemma mais largement
|
||||
# suffisant pour une jauge visuelle à l'utilisateur.
|
||||
_TOKEN_ENCODER: tiktoken.Encoding | None = None
|
||||
|
||||
|
||||
def _count_tokens(text: str | None) -> int:
|
||||
"""Compte les tokens d'un texte via tiktoken. Null/empty → 0."""
|
||||
if not text:
|
||||
return 0
|
||||
global _TOKEN_ENCODER
|
||||
if _TOKEN_ENCODER is None:
|
||||
_TOKEN_ENCODER = tiktoken.get_encoding("cl100k_base")
|
||||
return len(_TOKEN_ENCODER.encode(text))
|
||||
|
||||
|
||||
@router.post("/chat/stream")
|
||||
async def chat_stream(
|
||||
body: ChatStreamRequestDTO,
|
||||
use_case: Annotated[ChatUseCase, Depends(get_chat_use_case)],
|
||||
) -> StreamingResponse:
|
||||
"""Chat streamé (Server-Sent Events) avec Structural Context.
|
||||
|
||||
Accepte jusqu'à 4 contextes optionnels (Lore, Page focalisée, Campagne,
|
||||
entité narrative focalisée). Au moins un contexte racine (Lore ou
|
||||
Campagne) est requis pour que la requête ait du sens.
|
||||
|
||||
Format de flux :
|
||||
- Chaque token : `data: {"token": "..."}\\n\\n`
|
||||
- Fin normale : `event: done\\ndata: {}\\n\\n`
|
||||
- Erreur LLM : `event: error\\ndata: {"message": "..."}\\n\\n`
|
||||
"""
|
||||
if not body.has_scope():
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="Au moins un des deux contextes racines (lore_context ou campaign_context) est requis.",
|
||||
)
|
||||
|
||||
messages = [ChatMessage(role=m.role, content=m.content) for m in body.messages]
|
||||
lore_context = to_lore_context(body.lore_context)
|
||||
page_context = to_page_context(body.page_context)
|
||||
campaign_context = to_campaign_context(body.campaign_context)
|
||||
narrative_entity = to_narrative_entity(body.narrative_entity)
|
||||
game_system_context = to_game_system_context(body.game_system_context)
|
||||
session_context = to_session_context(body.session_context)
|
||||
|
||||
# --- Comptage tokens pour la jauge de contexte frontend ---
|
||||
# On construit le system prompt une fois ici pour le compter — le use case
|
||||
# le reconstruira à l'identique en interne (coût négligeable : concat de str).
|
||||
# Cette duplication évite de complexifier le contrat stream() avec un
|
||||
# paramètre optionnel system_prompt précalculé.
|
||||
system_prompt_preview = use_case.build_system_prompt(
|
||||
lore_context=lore_context,
|
||||
page_context=page_context,
|
||||
campaign_context=campaign_context,
|
||||
narrative_entity=narrative_entity,
|
||||
game_system_context=game_system_context,
|
||||
session_context=session_context,
|
||||
)
|
||||
# Dernier message = "current" (souvent user), le reste = historique accumulé.
|
||||
current_msg = messages[-1] if messages else None
|
||||
history_msgs = messages[:-1] if messages else []
|
||||
settings = get_settings()
|
||||
usage_payload = {
|
||||
"system": _count_tokens(system_prompt_preview),
|
||||
"history": sum(_count_tokens(m.content) for m in history_msgs),
|
||||
"current": _count_tokens(current_msg.content) if current_msg else 0,
|
||||
# Plafond connu seulement pour Ollama (num_ctx). Pour le cloud (1min/OpenRouter)
|
||||
# on ne connaît pas la fenêtre réelle → 0 = "pas de max" (jauge sans dénominateur).
|
||||
"max": settings.llm_num_ctx if settings.llm_provider == "ollama" else 0,
|
||||
}
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
# Event 'usage' émis en tout premier : le frontend peut afficher la
|
||||
# jauge avant même le premier token de réponse.
|
||||
yield f"event: usage\ndata: {json.dumps(usage_payload, ensure_ascii=False)}\n\n"
|
||||
try:
|
||||
async for token in use_case.stream(
|
||||
messages,
|
||||
lore_context=lore_context,
|
||||
page_context=page_context,
|
||||
campaign_context=campaign_context,
|
||||
narrative_entity=narrative_entity,
|
||||
game_system_context=game_system_context,
|
||||
session_context=session_context,
|
||||
):
|
||||
# json.dumps avec ensure_ascii=False pour préserver les accents
|
||||
yield f"data: {json.dumps({'token': token}, ensure_ascii=False)}\n\n"
|
||||
yield "event: done\ndata: {}\n\n"
|
||||
except LLMProviderError as exc:
|
||||
yield f"event: error\ndata: {json.dumps({'message': str(exc)})}\n\n"
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
137
brain/app/api/routers/generation.py
Normal file
137
brain/app/api/routers/generation.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""Endpoints de génération « simple » : prompt libre, page de Lore, auto-titre."""
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_generate_page_use_case, get_llm_provider
|
||||
from app.application.generate_page import GeneratePageUseCase
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.domain.models import PageGenerationContext
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class GenerateRequest(BaseModel):
|
||||
prompt: str
|
||||
|
||||
|
||||
class GenerateResponse(BaseModel):
|
||||
model: str
|
||||
response: str
|
||||
|
||||
|
||||
@router.post("/generate", response_model=GenerateResponse)
|
||||
async def generate(
|
||||
body: GenerateRequest,
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> GenerateResponse:
|
||||
"""Endpoint libre : prompt → texte brut. Utile pour debug et exploration."""
|
||||
try:
|
||||
text = await llm.generate(body.prompt)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
return GenerateResponse(model=settings.llm_model, response=text)
|
||||
|
||||
|
||||
class GeneratePageRequestDTO(BaseModel):
|
||||
"""Contexte envoyé par le Core Java pour remplir une page via le LLM."""
|
||||
|
||||
lore_name: str
|
||||
folder_name: str
|
||||
template_name: str
|
||||
template_fields: list[str] = Field(min_length=1)
|
||||
page_title: str
|
||||
lore_description: str | None = None
|
||||
|
||||
|
||||
class GeneratePageResponseDTO(BaseModel):
|
||||
"""Retour : une valeur textuelle par champ du template (clé = field name)."""
|
||||
|
||||
values: dict[str, str]
|
||||
|
||||
|
||||
@router.post("/generate-page", response_model=GeneratePageResponseDTO)
|
||||
async def generate_page(
|
||||
body: GeneratePageRequestDTO,
|
||||
use_case: Annotated[
|
||||
GeneratePageUseCase, Depends(get_generate_page_use_case)
|
||||
],
|
||||
) -> GeneratePageResponseDTO:
|
||||
"""Endpoint métier : contexte LoreMind → valeurs structurées par champ.
|
||||
|
||||
Branche tout le use case `GeneratePageUseCase`. Ce controller ne fait
|
||||
que le mapping DTO ↔ dataclass et la traduction d'erreur domaine → HTTP.
|
||||
"""
|
||||
context = PageGenerationContext(
|
||||
lore_name=body.lore_name,
|
||||
lore_description=body.lore_description,
|
||||
folder_name=body.folder_name,
|
||||
template_name=body.template_name,
|
||||
template_fields=body.template_fields,
|
||||
page_title=body.page_title,
|
||||
)
|
||||
|
||||
try:
|
||||
result = await use_case.execute(context)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
return GeneratePageResponseDTO(values=result.values)
|
||||
|
||||
|
||||
# --- Auto-titre d'une conversation persistee --------------------------------
|
||||
|
||||
|
||||
class SummarizeTitleMessageDTO(BaseModel):
|
||||
role: Literal["user", "assistant", "system"]
|
||||
content: str
|
||||
|
||||
|
||||
class SummarizeTitleRequestDTO(BaseModel):
|
||||
"""Premiers messages d'une conversation pour auto-generer un titre court."""
|
||||
|
||||
messages: list[SummarizeTitleMessageDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SummarizeTitleResponseDTO(BaseModel):
|
||||
title: str
|
||||
|
||||
|
||||
_TITLE_SYSTEM_PROMPT = (
|
||||
"Tu generes un titre court (4 a 7 mots max) qui resume le sujet de la "
|
||||
"conversation ci-dessous. Reponds UNIQUEMENT par le titre, sans guillemets, "
|
||||
"sans ponctuation finale, sans prefixe type 'Titre :'. Le titre doit etre "
|
||||
"en francais et capturer le sujet metier (pas 'Conversation IA')."
|
||||
)
|
||||
|
||||
|
||||
@router.post("/summarize/conversation-title", response_model=SummarizeTitleResponseDTO)
|
||||
async def summarize_conversation_title(
|
||||
body: SummarizeTitleRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> SummarizeTitleResponseDTO:
|
||||
"""Genere un titre court a partir des premiers echanges de la conversation.
|
||||
|
||||
Appele par le core apres le 1er couple user/assistant, pour remplacer le
|
||||
titre provisoire "Nouvelle conversation" par quelque chose de parlant.
|
||||
"""
|
||||
if not body.messages:
|
||||
raise HTTPException(status_code=422, detail="Au moins un message requis")
|
||||
|
||||
transcript = "\n".join(f"{m.role.upper()}: {m.content}" for m in body.messages[:6])
|
||||
prompt = f"{_TITLE_SYSTEM_PROMPT}\n\nConversation :\n{transcript}\n\nTitre :"
|
||||
try:
|
||||
raw = await llm.generate(prompt)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
title = raw.strip().splitlines()[0].strip().strip('"').strip("'").rstrip(".")
|
||||
if len(title) > 80:
|
||||
title = title[:80].rstrip()
|
||||
if not title:
|
||||
title = "Nouvelle conversation"
|
||||
return SummarizeTitleResponseDTO(title=title)
|
||||
184
brain/app/api/routers/imports.py
Normal file
184
brain/app/api/routers/imports.py
Normal file
@@ -0,0 +1,184 @@
|
||||
"""Endpoints d'import/adaptation de PDF (règles, campagne) — REST + flux SSE."""
|
||||
import json
|
||||
import logging
|
||||
from typing import Annotated, AsyncIterator
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.api.common import MAX_PDF_BYTES, pdf_upload_error, sse_event
|
||||
from app.api.deps import (
|
||||
get_adapt_campaign_use_case,
|
||||
get_import_campaign_use_case,
|
||||
get_import_rules_use_case,
|
||||
)
|
||||
from app.application.adapt_campaign import AdaptCampaignUseCase
|
||||
from app.application.import_campaign import ImportCampaignUseCase
|
||||
from app.application.import_rules import ImportRulesUseCase
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError, PdfExtractionError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class RulesImportResponseDTO(BaseModel):
|
||||
"""Proposition de sections de règles extraites d'un PDF.
|
||||
|
||||
`sections` = {titre → contenu markdown}. C'est une PROPOSITION : le Core
|
||||
et l'UI laissent l'utilisateur réviser/éditer avant toute persistance.
|
||||
`ocr_page_count` permet d'indiquer si le PDF était un scan (OCR utilisé).
|
||||
"""
|
||||
|
||||
sections: dict[str, str]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
|
||||
|
||||
@router.post("/import/rules", response_model=RulesImportResponseDTO)
|
||||
async def import_rules(
|
||||
use_case: Annotated[ImportRulesUseCase, Depends(get_import_rules_use_case)],
|
||||
file: UploadFile = File(...),
|
||||
) -> RulesImportResponseDTO:
|
||||
"""Import d'un PDF de règles → sections markdown structurées (proposition).
|
||||
|
||||
Extrait le texte (couche texte + repli OCR par page pour les scans), découpe,
|
||||
et demande au LLM de répartir les règles en sections thématiques. Ne persiste
|
||||
rien : renvoie la proposition au Core, qui la présente pour révision.
|
||||
"""
|
||||
content = await file.read()
|
||||
if not content:
|
||||
raise HTTPException(status_code=422, detail="Fichier PDF vide.")
|
||||
if len(content) > MAX_PDF_BYTES:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"PDF trop volumineux (> {MAX_PDF_BYTES // (1024 * 1024)} Mo).",
|
||||
)
|
||||
|
||||
try:
|
||||
result = await use_case.execute(content)
|
||||
except PdfExtractionError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
return RulesImportResponseDTO(
|
||||
sections=result.sections,
|
||||
page_count=result.page_count,
|
||||
ocr_page_count=result.ocr_page_count,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/import/rules/stream")
|
||||
async def import_rules_stream(
|
||||
use_case: Annotated[ImportRulesUseCase, Depends(get_import_rules_use_case)],
|
||||
file: UploadFile = File(...),
|
||||
) -> StreamingResponse:
|
||||
"""Import streamé : émet l'avancement (SSE) puis le résultat final.
|
||||
|
||||
Évènements SSE :
|
||||
- `event: extracting` → data: {} (extraction en cours)
|
||||
- `event: start` → data: {page_count, ocr_page_count, total}
|
||||
- `event: progress` → data: {current, total, new_sections:[...]}
|
||||
- `event: done` → data: {sections, page_count, ocr_page_count}
|
||||
- `event: error` → data: {message}
|
||||
"""
|
||||
content = await file.read()
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
upload_error = pdf_upload_error(content)
|
||||
if upload_error:
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(content):
|
||||
event_type = ev.pop("type")
|
||||
yield sse_event(event_type, ev)
|
||||
except PdfExtractionError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except LLMProviderError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — filet : une erreur inattendue ne doit
|
||||
# PAS casser le flux SSE brutalement (sinon le Core n'a qu'un message générique
|
||||
# sans détail). On la transforme en évènement `error` propre + log avec trace.
|
||||
logger.exception("Import règles : erreur inattendue dans le flux.")
|
||||
yield sse_event("error", {"message": f"Erreur inattendue du Brain : {type(exc).__name__} : {exc}"})
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/import/campaign/stream")
|
||||
async def import_campaign_stream(
|
||||
use_case: Annotated[ImportCampaignUseCase, Depends(get_import_campaign_use_case)],
|
||||
file: UploadFile = File(...),
|
||||
) -> StreamingResponse:
|
||||
"""Import streamé d'un PDF de campagne → arbre arc→chapitre→scène (SSE).
|
||||
|
||||
Évènements : `extracting`, `start` {page_count, ocr_page_count, total},
|
||||
`progress` {current, total, arc_count, chapter_count, scene_count},
|
||||
`done` {arcs:[...], page_count, ocr_page_count}, `error` {message}.
|
||||
"""
|
||||
content = await file.read()
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
upload_error = pdf_upload_error(content)
|
||||
if upload_error:
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(content):
|
||||
event_type = ev.pop("type")
|
||||
yield sse_event(event_type, ev)
|
||||
except PdfExtractionError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except LLMProviderError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — voir import règles : on ne laisse pas
|
||||
# une erreur inattendue casser le flux sans détail.
|
||||
logger.exception("Import campagne : erreur inattendue dans le flux.")
|
||||
yield sse_event("error", {"message": f"Erreur inattendue du Brain : {type(exc).__name__} : {exc}"})
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/adapt/campaign/stream")
|
||||
async def adapt_campaign_stream(
|
||||
use_case: Annotated[AdaptCampaignUseCase, Depends(get_adapt_campaign_use_case)],
|
||||
file: UploadFile = File(...),
|
||||
brief: str = Form(""),
|
||||
messages: str = Form("[]"),
|
||||
) -> StreamingResponse:
|
||||
"""Adaptation CONVERSATIONNELLE d'un PDF à une campagne (SSE markdown).
|
||||
|
||||
`brief` = description de la campagne (Core). `messages` = JSON de l'échange
|
||||
([{role, content}, …]) ; vide au 1er tour. Évènements : `token`, `done`, `error`.
|
||||
"""
|
||||
content = await file.read()
|
||||
|
||||
try:
|
||||
raw_messages = json.loads(messages) if messages else []
|
||||
except json.JSONDecodeError:
|
||||
raw_messages = []
|
||||
convo = [
|
||||
ChatMessage(role=str(m.get("role", "user")), content=str(m.get("content", "")))
|
||||
for m in raw_messages
|
||||
if isinstance(m, dict) and str(m.get("content", "")).strip()
|
||||
]
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
upload_error = pdf_upload_error(content)
|
||||
if upload_error:
|
||||
yield sse_event("error", {"message": upload_error})
|
||||
return
|
||||
try:
|
||||
async for token in use_case.stream(content, brief, convo):
|
||||
yield sse_event("token", {"token": token})
|
||||
yield sse_event("done", {})
|
||||
except PdfExtractionError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except LLMProviderError as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
365
brain/app/api/routers/models.py
Normal file
365
brain/app/api/routers/models.py
Normal file
@@ -0,0 +1,365 @@
|
||||
"""Endpoints de catalogue de modèles (Ollama, OpenRouter, Mistral, Gemini, 1min.ai).
|
||||
|
||||
Proxifie les APIs des providers pour que l'UI propose des listes de modèles ;
|
||||
repli statique quand l'API est injoignable ou la clé absente (pas de 500 à l'UI).
|
||||
"""
|
||||
import json
|
||||
from typing import Annotated, AsyncIterator
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.core.config import Settings, get_settings
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/models/ollama")
|
||||
async def list_ollama_models(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> dict[str, list[str]]:
|
||||
"""Liste les modeles disponibles sur le serveur Ollama configure.
|
||||
|
||||
Retourne une liste vide si Ollama est injoignable — l'UI affichera un
|
||||
message plutot qu'une 500.
|
||||
"""
|
||||
url = f"{settings.ollama_base_url}/api/tags"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except httpx.HTTPError:
|
||||
return {"models": []}
|
||||
models = [m.get("name", "") for m in data.get("models", []) if m.get("name")]
|
||||
return {"models": sorted(models)}
|
||||
|
||||
|
||||
class OllamaModelInfoDTO(BaseModel):
|
||||
"""Info utile extraite de /api/show pour un modele Ollama donne.
|
||||
|
||||
`context_length` = fenetre de contexte max supportee par le modele
|
||||
(extraite des metadonnees GGUF). 0 si inconnue. Le frontend s'en sert
|
||||
pour borner le slider de num_ctx dans les Parametres.
|
||||
"""
|
||||
|
||||
context_length: int = 0
|
||||
|
||||
|
||||
@router.post("/models/ollama/info", response_model=OllamaModelInfoDTO)
|
||||
async def get_ollama_model_info(
|
||||
body: dict[str, str],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> OllamaModelInfoDTO:
|
||||
"""Retourne les metadonnees d'un modele Ollama via /api/show.
|
||||
|
||||
On passe par POST (et pas GET /models/ollama/{name}) parce que les noms
|
||||
Ollama contiennent souvent un `:` (ex: `gemma3:e2b`) qui se segmente
|
||||
mal dans une URL — le body JSON evite le probleme d'escaping.
|
||||
|
||||
Le champ qui nous interesse est `model_info["<arch>.context_length"]`
|
||||
(ex: `gemma3.context_length: 131072`). L'arch varie selon le modele, on
|
||||
scanne donc tous les champs finissant par `.context_length`.
|
||||
"""
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="name requis")
|
||||
url = f"{settings.ollama_base_url}/api/show"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5) as client:
|
||||
response = await client.post(url, json={"model": name})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except httpx.HTTPError:
|
||||
return OllamaModelInfoDTO(context_length=0)
|
||||
model_info = data.get("model_info") or {}
|
||||
for key, value in model_info.items():
|
||||
if key.endswith(".context_length") and isinstance(value, int):
|
||||
return OllamaModelInfoDTO(context_length=value)
|
||||
return OllamaModelInfoDTO(context_length=0)
|
||||
|
||||
|
||||
@router.post("/models/ollama/pull")
|
||||
async def pull_ollama_model(
|
||||
body: dict[str, str],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> StreamingResponse:
|
||||
"""Telecharge un modele depuis Ollama et streame la progression.
|
||||
|
||||
Proxifie l'endpoint `/api/pull` d'Ollama qui renvoie du JSON ligne par
|
||||
ligne (NDJSON) avec le statut de chaque etape : manifest, layers,
|
||||
digest, success. On reemet ce flux tel quel au client (le front
|
||||
parsera les lignes et affichera une barre de progression).
|
||||
|
||||
Le timeout est intentionnellement tres long (60 min) car certains
|
||||
modeles font 30+ Go.
|
||||
"""
|
||||
name = (body.get("name") or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="name requis")
|
||||
url = f"{settings.ollama_base_url}/api/pull"
|
||||
|
||||
async def stream() -> AsyncIterator[bytes]:
|
||||
# On utilise un timeout long pour la lecture (60 min) mais court pour
|
||||
# la connexion (10s) — si Ollama n'est pas joignable, on echoue vite.
|
||||
timeout = httpx.Timeout(connect=10, read=3600, write=10, pool=10)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||
async with client.stream("POST", url, json={"model": name, "stream": True}) as r:
|
||||
if r.status_code != 200:
|
||||
# Ollama renvoie un message JSON d'erreur. On le passe
|
||||
# tel quel au client en preservant le code HTTP.
|
||||
body_text = await r.aread()
|
||||
yield body_text
|
||||
return
|
||||
async for chunk in r.aiter_bytes():
|
||||
yield chunk
|
||||
except httpx.HTTPError as e:
|
||||
# Erreur reseau : on emet une ligne JSON d'erreur compatible
|
||||
# avec le format NDJSON d'Ollama.
|
||||
err = json.dumps({"error": f"Connexion a Ollama impossible : {e}"}) + "\n"
|
||||
yield err.encode("utf-8")
|
||||
|
||||
# application/x-ndjson : un objet JSON par ligne, pas de wrapping SSE.
|
||||
# C'est le format natif d'Ollama, le front le parsera ligne par ligne.
|
||||
return StreamingResponse(stream(), media_type="application/x-ndjson")
|
||||
|
||||
|
||||
@router.delete("/models/ollama/{name:path}")
|
||||
async def delete_ollama_model(
|
||||
name: str,
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> dict[str, str]:
|
||||
"""Supprime un modele du serveur Ollama.
|
||||
|
||||
Le `:path` dans le pattern autorise les `:` du nom (ex: `gemma4:e4b`)
|
||||
sans avoir besoin de URL-encoder cote client.
|
||||
"""
|
||||
if not name.strip():
|
||||
raise HTTPException(status_code=400, detail="name requis")
|
||||
url = f"{settings.ollama_base_url}/api/delete"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
response = await client.request("DELETE", url, json={"model": name})
|
||||
if response.status_code == 404:
|
||||
raise HTTPException(status_code=404, detail=f"Modele '{name}' introuvable")
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Ollama injoignable : {e}")
|
||||
return {"status": "deleted", "name": name}
|
||||
|
||||
|
||||
@router.get("/models/openrouter")
|
||||
async def list_openrouter_models() -> dict[str, list[dict[str, object]]]:
|
||||
"""Catalogue DYNAMIQUE des modeles OpenRouter (API publique, sans cle).
|
||||
|
||||
Renvoie {models: [{id, name, context_length, free}]}, trie gratuits d'abord
|
||||
puis contexte decroissant. `free` = id finissant par ':free' OU prix nul.
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
response = await client.get("https://openrouter.ai/api/v1/models")
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter injoignable : {exc}")
|
||||
|
||||
def _is_zero(value: object) -> bool:
|
||||
try:
|
||||
return float(value) == 0.0 # type: ignore[arg-type]
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
models: list[dict[str, object]] = []
|
||||
for m in data.get("data", []) or []:
|
||||
mid = str(m.get("id") or "")
|
||||
if not mid:
|
||||
continue
|
||||
pricing = m.get("pricing") or {}
|
||||
is_free = mid.endswith(":free") or (
|
||||
_is_zero(pricing.get("prompt")) and _is_zero(pricing.get("completion"))
|
||||
)
|
||||
try:
|
||||
ctx = int(m.get("context_length") or 0)
|
||||
except (TypeError, ValueError):
|
||||
ctx = 0
|
||||
models.append({
|
||||
"id": mid,
|
||||
"name": str(m.get("name") or mid),
|
||||
"context_length": ctx,
|
||||
"free": is_free,
|
||||
})
|
||||
|
||||
models.sort(key=lambda x: (not x["free"], -int(x["context_length"]))) # type: ignore[index]
|
||||
return {"models": models}
|
||||
|
||||
|
||||
# Repli statique si la cle Mistral n'est pas (encore) configuree ou si l'API est
|
||||
# injoignable — l'utilisateur peut quand meme choisir un modele. Liste curee
|
||||
# (juin 2026) ; pour l'extraction de PDF, prefere `large` (fidele, 128k) ou `small`.
|
||||
_MISTRAL_FALLBACK_MODELS = [
|
||||
"mistral-large-latest",
|
||||
"mistral-medium-latest",
|
||||
"mistral-small-latest",
|
||||
"open-mistral-nemo",
|
||||
"ministral-8b-latest",
|
||||
"ministral-3b-latest",
|
||||
"magistral-medium-latest",
|
||||
"magistral-small-latest",
|
||||
"pixtral-large-latest",
|
||||
"codestral-latest",
|
||||
]
|
||||
|
||||
|
||||
@router.get("/models/mistral")
|
||||
async def list_mistral_models(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> dict[str, list[dict[str, object]]]:
|
||||
"""Catalogue des modeles Mistral. Dynamique si une cle est configuree
|
||||
(GET /v1/models, qui requiert l'auth), sinon repli statique.
|
||||
|
||||
Renvoie {models: [{id}]} (tous accessibles sur le tier gratuit Experiment)."""
|
||||
key = settings.mistral_api_key
|
||||
if not key:
|
||||
return {"models": [{"id": m} for m in _MISTRAL_FALLBACK_MODELS]}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
response = await client.get(
|
||||
"https://api.mistral.ai/v1/models",
|
||||
headers={"Authorization": f"Bearer {key}"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except httpx.HTTPError:
|
||||
# Cle invalide / API down : on ne casse pas l'UI, on propose le repli.
|
||||
return {"models": [{"id": m} for m in _MISTRAL_FALLBACK_MODELS]}
|
||||
|
||||
ids = sorted({str(m.get("id")) for m in data.get("data", []) or [] if m.get("id")})
|
||||
if not ids:
|
||||
ids = _MISTRAL_FALLBACK_MODELS
|
||||
return {"models": [{"id": i} for i in ids]}
|
||||
|
||||
|
||||
# Repli statique Gemini (juin 2026). Pour l'extraction, prefere un Flash a grand
|
||||
# contexte ; `gemini-2.0-flash` a le quota gratuit le plus genereux.
|
||||
_GEMINI_FALLBACK_MODELS = [
|
||||
"gemini-2.0-flash",
|
||||
"gemini-2.0-flash-lite",
|
||||
"gemini-2.5-flash",
|
||||
"gemini-2.5-flash-lite",
|
||||
"gemini-2.5-pro",
|
||||
"gemini-1.5-flash",
|
||||
"gemini-1.5-pro",
|
||||
]
|
||||
|
||||
|
||||
@router.get("/models/gemini")
|
||||
async def list_gemini_models(
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> dict[str, list[dict[str, object]]]:
|
||||
"""Catalogue des modeles Gemini. Dynamique si une cle est configuree (endpoint
|
||||
OpenAI-compatible /openai/models), sinon repli statique. Renvoie {models:[{id}]}."""
|
||||
key = settings.gemini_api_key
|
||||
if not key:
|
||||
return {"models": [{"id": m} for m in _GEMINI_FALLBACK_MODELS]}
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20) as client:
|
||||
response = await client.get(
|
||||
"https://generativelanguage.googleapis.com/v1beta/openai/models",
|
||||
headers={"Authorization": f"Bearer {key}"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except httpx.HTTPError:
|
||||
return {"models": [{"id": m} for m in _GEMINI_FALLBACK_MODELS]}
|
||||
|
||||
# Les ids peuvent arriver prefixes "models/" → on nettoie pour que la valeur
|
||||
# selectionnee soit directement utilisable dans l'appel chat. On garde les
|
||||
# modeles "gemini-*" (hors embeddings/aqa) pour ne pas noyer la liste.
|
||||
ids: set[str] = set()
|
||||
for m in data.get("data", []) or []:
|
||||
mid = str(m.get("id") or "")
|
||||
if mid.startswith("models/"):
|
||||
mid = mid[len("models/"):]
|
||||
if mid.startswith("gemini-"):
|
||||
ids.add(mid)
|
||||
clean = sorted(ids) if ids else _GEMINI_FALLBACK_MODELS
|
||||
return {"models": [{"id": i} for i in clean]}
|
||||
|
||||
|
||||
@router.get("/models/onemin")
|
||||
def list_onemin_models() -> dict[str, list[dict[str, object]]]:
|
||||
"""Catalogue statique des modeles 1min.ai, groupes par fournisseur.
|
||||
|
||||
Liste construite par probing direct de l'endpoint chat-with-ai avec
|
||||
une vraie cle API (avril 2026) : chaque ID renvoie 200, les IDs
|
||||
absents renvoient 400 UNSUPPORTED_MODEL.
|
||||
|
||||
Nota : les IDs Anthropic utilisent la nomenclature propre a 1min.ai
|
||||
(`claude-<family>-<version>`), pas la convention officielle Anthropic.
|
||||
"""
|
||||
return {
|
||||
"groups": [
|
||||
{
|
||||
"provider": "Anthropic",
|
||||
"models": ["claude-opus-4-6", "claude-sonnet-4-6"],
|
||||
},
|
||||
{
|
||||
"provider": "OpenAI",
|
||||
"models": [
|
||||
"gpt-5",
|
||||
"gpt-5-mini",
|
||||
"gpt-5-nano",
|
||||
"gpt-4.1",
|
||||
"gpt-4.1-mini",
|
||||
"gpt-4.1-nano",
|
||||
"gpt-4o",
|
||||
"gpt-4o-mini",
|
||||
"gpt-4-turbo",
|
||||
"gpt-3.5-turbo",
|
||||
"o3",
|
||||
"o3-pro",
|
||||
"o3-mini",
|
||||
"o4-mini",
|
||||
],
|
||||
},
|
||||
{
|
||||
"provider": "Google",
|
||||
"models": ["gemini-2.5-pro", "gemini-2.5-flash"],
|
||||
},
|
||||
{
|
||||
"provider": "Mistral",
|
||||
"models": [
|
||||
"mistral-large-latest",
|
||||
"mistral-medium-latest",
|
||||
"mistral-small-latest",
|
||||
"open-mistral-nemo",
|
||||
],
|
||||
},
|
||||
{
|
||||
"provider": "DeepSeek",
|
||||
"models": ["deepseek-chat", "deepseek-reasoner"],
|
||||
},
|
||||
{
|
||||
"provider": "xAI",
|
||||
"models": ["grok-3", "grok-3-mini"],
|
||||
},
|
||||
{
|
||||
"provider": "Meta",
|
||||
"models": [
|
||||
"meta/meta-llama-3.1-405b-instruct",
|
||||
"meta/meta-llama-3-70b-instruct",
|
||||
],
|
||||
},
|
||||
{
|
||||
"provider": "Alibaba",
|
||||
"models": ["qwen-plus", "qwen3-max"],
|
||||
},
|
||||
{
|
||||
"provider": "Perplexity",
|
||||
"models": ["sonar", "sonar-pro"],
|
||||
},
|
||||
]
|
||||
}
|
||||
130
brain/app/api/routers/notebooks.py
Normal file
130
brain/app/api/routers/notebooks.py
Normal file
@@ -0,0 +1,130 @@
|
||||
"""Endpoints des notebooks (atelier RAG) : indexation des sources + chats ancrés."""
|
||||
import logging
|
||||
from typing import Annotated, AsyncIterator
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.common import MAX_PDF_BYTES, sse_event
|
||||
from app.api.deps import (
|
||||
get_notebook_chat_use_case,
|
||||
get_notebook_deep_use_case,
|
||||
get_notebook_rag_use_case,
|
||||
)
|
||||
from app.application.embeddings import EmbeddingError
|
||||
from app.application.notebook_chat import NotebookChatUseCase
|
||||
from app.application.notebook_deep import NotebookDeepUseCase
|
||||
from app.application.notebook_rag import NotebookRagUseCase
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMProviderError, PdfExtractionError
|
||||
from app.infrastructure import vector_store
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class IndexSourceResponseDTO(BaseModel):
|
||||
chunks: int
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
|
||||
|
||||
@router.post("/index/notebook-source", response_model=IndexSourceResponseDTO)
|
||||
async def index_notebook_source(
|
||||
rag: Annotated[NotebookRagUseCase, Depends(get_notebook_rag_use_case)],
|
||||
source_id: str = Form(...),
|
||||
file: UploadFile = File(...),
|
||||
) -> IndexSourceResponseDTO:
|
||||
"""Indexe une source PDF (extraction + embeddings + stockage vectoriel)."""
|
||||
content = await file.read()
|
||||
if not content:
|
||||
raise HTTPException(status_code=422, detail="Fichier PDF vide.")
|
||||
if len(content) > MAX_PDF_BYTES:
|
||||
raise HTTPException(
|
||||
status_code=413, detail=f"PDF trop volumineux (> {MAX_PDF_BYTES // (1024 * 1024)} Mo).")
|
||||
try:
|
||||
recap = await rag.index_source(source_id, content)
|
||||
except PdfExtractionError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
except EmbeddingError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
return IndexSourceResponseDTO(**recap)
|
||||
|
||||
|
||||
@router.delete("/index/notebook-source/{source_id}")
|
||||
def delete_notebook_source(source_id: str) -> dict[str, str]:
|
||||
"""Supprime les vecteurs d'une source (au DELETE d'une source/notebook)."""
|
||||
vector_store.delete(source_id)
|
||||
return {"status": "deleted", "source_id": source_id}
|
||||
|
||||
|
||||
class NotebookChatMessageDTO(BaseModel):
|
||||
role: str
|
||||
content: str
|
||||
|
||||
|
||||
class NotebookChatRequestDTO(BaseModel):
|
||||
source_ids: list[str] = Field(default_factory=list)
|
||||
messages: list[NotebookChatMessageDTO] = Field(default_factory=list)
|
||||
context: str = Field(default="")
|
||||
|
||||
|
||||
@router.post("/chat/notebook/stream")
|
||||
async def chat_notebook_stream(
|
||||
body: NotebookChatRequestDTO,
|
||||
use_case: Annotated[NotebookChatUseCase, Depends(get_notebook_chat_use_case)],
|
||||
settings: Annotated[Settings, Depends(get_settings)],
|
||||
) -> StreamingResponse:
|
||||
"""Chat ANCRÉ sur les sources (RAG) : récupère les passages pertinents puis
|
||||
streame la réponse. Évènements SSE : `token` {token}, `done` {}, `error` {message}."""
|
||||
messages = [ChatMessage(role=m.role, content=m.content) for m in body.messages]
|
||||
top_k = max(1, min(settings.rag_top_k, 200))
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
try:
|
||||
async for ev in use_case.stream(body.source_ids, messages, context=body.context, top_k=top_k):
|
||||
if ev["type"] == "token":
|
||||
if ev.get("token"):
|
||||
yield sse_event("token", {"token": ev["token"]})
|
||||
else:
|
||||
# 'sources' (et tout futur évènement typé) : relayé tel quel.
|
||||
ev_type = ev.pop("type")
|
||||
yield sse_event(ev_type, ev)
|
||||
yield sse_event("done", {})
|
||||
except (LLMProviderError, EmbeddingError) as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale du flux.
|
||||
logger.exception("Chat notebook : erreur inattendue.")
|
||||
yield sse_event("error", {"message": f"Erreur inattendue du Brain : {type(exc).__name__} : {exc}"})
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/chat/notebook/deep/stream")
|
||||
async def chat_notebook_deep_stream(
|
||||
body: NotebookChatRequestDTO,
|
||||
use_case: Annotated[NotebookDeepUseCase, Depends(get_notebook_deep_use_case)],
|
||||
) -> StreamingResponse:
|
||||
"""Analyse APPROFONDIE (map-reduce sur tout le document). Évènements SSE :
|
||||
`progress` {current,total} pendant la lecture, puis `token` {token}, puis `done`."""
|
||||
messages = [ChatMessage(role=m.role, content=m.content) for m in body.messages]
|
||||
question = next((m.content for m in reversed(messages) if m.role == "user"), "")
|
||||
|
||||
async def event_stream() -> AsyncIterator[str]:
|
||||
if not question.strip():
|
||||
yield sse_event("error", {"message": "Question vide."})
|
||||
return
|
||||
try:
|
||||
async for ev in use_case.stream(body.source_ids, messages, context=body.context):
|
||||
ev_type = ev.pop("type")
|
||||
yield sse_event(ev_type, ev)
|
||||
except (LLMProviderError, EmbeddingError) as exc:
|
||||
yield sse_event("error", {"message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — filet : pas de coupure brutale.
|
||||
logger.exception("Analyse approfondie : erreur inattendue.")
|
||||
yield sse_event("error", {"message": f"Erreur inattendue du Brain : {type(exc).__name__} : {exc}"})
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
115
brain/app/api/routers/settings.py
Normal file
115
brain/app/api/routers/settings.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""Endpoints de paramétrage runtime (écran Paramètres de l'UI)."""
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.settings_store import save_overrides
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class SettingsDTO(BaseModel):
|
||||
"""Vue serialisable des settings modifiables depuis l'UI.
|
||||
|
||||
Expose uniquement les champs que l'utilisateur peut changer a chaud.
|
||||
Les secrets (onemin_api_key) sont masques en lecture.
|
||||
"""
|
||||
|
||||
llm_provider: Literal["ollama", "onemin", "openrouter", "mistral", "gemini"]
|
||||
ollama_base_url: str
|
||||
llm_model: str
|
||||
onemin_model: str
|
||||
# True si une cle 1min.ai est deja configuree — pas de leak de la cle elle-meme.
|
||||
onemin_api_key_set: bool
|
||||
openrouter_model: str
|
||||
# True si une cle OpenRouter est deja configuree (cle elle-meme jamais renvoyee).
|
||||
openrouter_api_key_set: bool
|
||||
mistral_model: str
|
||||
# True si une cle Mistral est deja configuree (cle elle-meme jamais renvoyee).
|
||||
mistral_api_key_set: bool
|
||||
gemini_model: str
|
||||
# True si une cle Gemini est deja configuree (cle elle-meme jamais renvoyee).
|
||||
gemini_api_key_set: bool
|
||||
# Embeddings (RAG des ateliers) : provider + modeles + auto-pull Ollama.
|
||||
embedding_provider: Literal["ollama", "mistral"]
|
||||
ollama_embedding_model: str
|
||||
mistral_embedding_model: str
|
||||
auto_pull_embedding_model: bool
|
||||
rag_top_k: int
|
||||
# Fenetre de contexte effective passee au modele (num_ctx Ollama) — sert
|
||||
# aussi de plafond a la jauge de contexte UI.
|
||||
llm_num_ctx: int
|
||||
# Taille cible d'un morceau (tokens) pour l'import de PDF (regles/campagne).
|
||||
import_chunk_tokens: int
|
||||
# Timeout HTTP des appels LLM (s). A monter si les imports lourds expirent.
|
||||
llm_timeout_seconds: int
|
||||
|
||||
|
||||
class SettingsUpdateDTO(BaseModel):
|
||||
"""Patch partiel des settings. Tous les champs sont optionnels."""
|
||||
|
||||
llm_provider: Literal["ollama", "onemin", "openrouter", "mistral", "gemini"] | None = None
|
||||
ollama_base_url: str | None = None
|
||||
llm_model: str | None = None
|
||||
onemin_model: str | None = None
|
||||
# Chaine vide => on efface la cle. None => pas de changement.
|
||||
onemin_api_key: str | None = None
|
||||
openrouter_model: str | None = None
|
||||
openrouter_api_key: str | None = None
|
||||
mistral_model: str | None = None
|
||||
mistral_api_key: str | None = None
|
||||
gemini_model: str | None = None
|
||||
gemini_api_key: str | None = None
|
||||
embedding_provider: Literal["ollama", "mistral"] | None = None
|
||||
ollama_embedding_model: str | None = None
|
||||
mistral_embedding_model: str | None = None
|
||||
auto_pull_embedding_model: bool | None = None
|
||||
rag_top_k: int | None = None
|
||||
llm_num_ctx: int | None = None
|
||||
import_chunk_tokens: int | None = None
|
||||
llm_timeout_seconds: int | None = None
|
||||
|
||||
|
||||
def _to_settings_dto(s: Settings) -> SettingsDTO:
|
||||
return SettingsDTO(
|
||||
llm_provider=s.llm_provider,
|
||||
ollama_base_url=s.ollama_base_url,
|
||||
llm_model=s.llm_model,
|
||||
onemin_model=s.onemin_model,
|
||||
onemin_api_key_set=bool(s.onemin_api_key),
|
||||
openrouter_model=s.openrouter_model,
|
||||
openrouter_api_key_set=bool(s.openrouter_api_key),
|
||||
mistral_model=s.mistral_model,
|
||||
mistral_api_key_set=bool(s.mistral_api_key),
|
||||
gemini_model=s.gemini_model,
|
||||
gemini_api_key_set=bool(s.gemini_api_key),
|
||||
embedding_provider=s.embedding_provider,
|
||||
ollama_embedding_model=s.ollama_embedding_model,
|
||||
mistral_embedding_model=s.mistral_embedding_model,
|
||||
auto_pull_embedding_model=s.auto_pull_embedding_model,
|
||||
rag_top_k=s.rag_top_k,
|
||||
llm_num_ctx=s.llm_num_ctx,
|
||||
import_chunk_tokens=s.import_chunk_tokens,
|
||||
llm_timeout_seconds=s.llm_timeout_seconds,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/settings", response_model=SettingsDTO)
|
||||
def read_settings(settings: Annotated[Settings, Depends(get_settings)]) -> SettingsDTO:
|
||||
"""Retourne la config courante (secrets masques)."""
|
||||
return _to_settings_dto(settings)
|
||||
|
||||
|
||||
@router.put("/settings", response_model=SettingsDTO)
|
||||
def update_settings(patch: SettingsUpdateDTO) -> SettingsDTO:
|
||||
"""Applique un patch partiel aux settings et persiste les overrides.
|
||||
|
||||
Toute requete HTTP suivante verra les nouvelles valeurs (pas de cache).
|
||||
"""
|
||||
overrides = {k: v for k, v in patch.model_dump().items() if v is not None}
|
||||
if overrides:
|
||||
save_overrides(overrides)
|
||||
# Relit .env + overrides fusionnes pour confirmation.
|
||||
return _to_settings_dto(get_settings())
|
||||
216
brain/app/api/routers/tables.py
Normal file
216
brain/app/api/routers/tables.py
Normal file
@@ -0,0 +1,216 @@
|
||||
"""Endpoints « outils de table » : tables aléatoires, improvisation, catalogues d'objets."""
|
||||
import re
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import get_llm_provider
|
||||
from app.application.llm_json import load_json_object
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.domain.ports import LLMProvider, LLMProviderError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_DICE_FORMULA_RE = re.compile(r"^\s*(\d*)\s*[dD]\s*(\d+)\s*$")
|
||||
|
||||
|
||||
def _dice_total_range(formula: str) -> tuple[int, int] | None:
|
||||
"""(min, max) des totaux possibles d'une formule NdM, ou None si invalide."""
|
||||
match = _DICE_FORMULA_RE.match(formula or "")
|
||||
if not match:
|
||||
return None
|
||||
count = int(match.group(1)) if match.group(1) else 1
|
||||
faces = int(match.group(2))
|
||||
if count < 1 or count > 100 or faces < 2 or faces > 10000:
|
||||
return None
|
||||
return count, count * faces
|
||||
|
||||
|
||||
class GenerateTableRequestDTO(BaseModel):
|
||||
description: str
|
||||
dice_formula: str = Field(default="1d20")
|
||||
# Contexte libre assemblé par le Core (nom de campagne, système, ambiance…).
|
||||
context: str = Field(default="")
|
||||
|
||||
|
||||
class GeneratedTableEntryDTO(BaseModel):
|
||||
min_roll: int
|
||||
max_roll: int
|
||||
label: str
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class GenerateTableResponseDTO(BaseModel):
|
||||
name: str
|
||||
description: str = ""
|
||||
entries: list[GeneratedTableEntryDTO]
|
||||
|
||||
|
||||
@router.post("/generate/random-table", response_model=GenerateTableResponseDTO)
|
||||
async def generate_random_table(
|
||||
body: GenerateTableRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> GenerateTableResponseDTO:
|
||||
"""Génère une table aléatoire (entrées par plage) couvrant la formule de dé."""
|
||||
rng = _dice_total_range(body.dice_formula)
|
||||
if rng is None:
|
||||
raise HTTPException(status_code=422, detail="Formule de dé invalide (ex. 1d20, 2d6, d100).")
|
||||
lo, hi = rng
|
||||
context_block = f"\nContexte de la campagne :\n{body.context.strip()}\n" if body.context.strip() else ""
|
||||
prompt = (
|
||||
"Tu es un assistant de jeu de rôle. Génère une TABLE ALÉATOIRE évocatrice.\n"
|
||||
f"Dé : {body.dice_formula} (résultats possibles de {lo} à {hi}).\n"
|
||||
f"Sujet : {body.description.strip()}\n"
|
||||
f"{context_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format : {"name": "...", "description": "...", "entries": '
|
||||
'[{"min_roll": N, "max_roll": M, "label": "résultat court", "detail": "1-2 phrases"}]}\n'
|
||||
f"- Les plages (min_roll..max_roll) doivent COUVRIR EXACTEMENT {lo}..{hi}, "
|
||||
"sans trou ni chevauchement, dans l'ordre croissant.\n"
|
||||
"- Des résultats variés, cohérents avec le sujet (et le contexte s'il est fourni).\n"
|
||||
"- En français. 'label' = résultat bref ; 'detail' = description/effet concret.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.7)
|
||||
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 table exploitable.")
|
||||
|
||||
entries: list[GeneratedTableEntryDTO] = []
|
||||
for e in parsed.get("entries", []) or []:
|
||||
if not isinstance(e, dict):
|
||||
continue
|
||||
try:
|
||||
mn = int(e["min_roll"])
|
||||
mx = int(e["max_roll"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
label = str(e.get("label") or "").strip()
|
||||
if not label:
|
||||
continue
|
||||
entries.append(GeneratedTableEntryDTO(
|
||||
min_roll=mn, max_roll=max(mn, mx), label=label[:200],
|
||||
detail=str(e.get("detail") or "").strip(),
|
||||
))
|
||||
if not entries:
|
||||
raise HTTPException(status_code=502, detail="Aucune entrée générée — réessaie ou reformule.")
|
||||
|
||||
name = str(parsed.get("name") or body.description).strip()[:120] or "Table générée"
|
||||
return GenerateTableResponseDTO(
|
||||
name=name,
|
||||
description=str(parsed.get("description") or "").strip(),
|
||||
entries=entries,
|
||||
)
|
||||
|
||||
|
||||
class ImproviseRollRequestDTO(BaseModel):
|
||||
table_name: str
|
||||
result_label: str
|
||||
result_detail: str = Field(default="")
|
||||
context: str = Field(default="")
|
||||
|
||||
|
||||
class ImproviseRollResponseDTO(BaseModel):
|
||||
narration: str
|
||||
|
||||
|
||||
@router.post("/improvise/table-roll", response_model=ImproviseRollResponseDTO)
|
||||
async def improvise_table_roll(
|
||||
body: ImproviseRollRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> ImproviseRollResponseDTO:
|
||||
"""Brode un court récit (2-3 phrases) sur un résultat tiré, pour lancer la scène."""
|
||||
detail = f" ({body.result_detail.strip()})" if body.result_detail.strip() else ""
|
||||
context_block = f"\nContexte : {body.context.strip()}" if body.context.strip() else ""
|
||||
prompt = (
|
||||
"Tu es le Maître du Jeu. Les joueurs viennent de tirer sur la table "
|
||||
f"« {body.table_name.strip()} » et ont obtenu : « {body.result_label.strip()} »{detail}."
|
||||
f"{context_block}\n\n"
|
||||
"Décris en 2-3 phrases vivantes et immédiates ce qui se passe, pour lancer la scène. "
|
||||
"Pas de méta, pas d'options : juste la narration, en français."
|
||||
)
|
||||
try:
|
||||
raw = await llm.generate(prompt, temperature=0.8)
|
||||
except LLMProviderError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
return ImproviseRollResponseDTO(narration=raw.strip())
|
||||
|
||||
|
||||
# --- Catalogues d'objets (boutiques) : génération IA -------------------------
|
||||
|
||||
|
||||
class GenerateCatalogRequestDTO(BaseModel):
|
||||
description: str
|
||||
context: str = Field(default="")
|
||||
|
||||
|
||||
class GeneratedCatalogItemDTO(BaseModel):
|
||||
name: str
|
||||
price: str = ""
|
||||
category: str = ""
|
||||
description: str = ""
|
||||
|
||||
|
||||
class GenerateCatalogResponseDTO(BaseModel):
|
||||
name: str
|
||||
description: str = ""
|
||||
items: list[GeneratedCatalogItemDTO]
|
||||
|
||||
|
||||
@router.post("/generate/item-catalog", response_model=GenerateCatalogResponseDTO)
|
||||
async def generate_item_catalog(
|
||||
body: GenerateCatalogRequestDTO,
|
||||
llm: Annotated[LLMProvider, Depends(get_llm_provider)],
|
||||
) -> GenerateCatalogResponseDTO:
|
||||
"""Génère un catalogue d'objets (boutique, butin…) — nom, prix, catégorie, description."""
|
||||
context_block = f"\nContexte de la campagne :\n{body.context.strip()}\n" if body.context.strip() else ""
|
||||
prompt = (
|
||||
"Tu es un assistant de jeu de rôle. Génère un CATALOGUE D'OBJETS (boutique, butin, trésor…).\n"
|
||||
f"Sujet : {body.description.strip()}\n"
|
||||
f"{context_block}\n"
|
||||
"Règles IMPÉRATIVES :\n"
|
||||
"- Réponds UNIQUEMENT par un objet JSON valide, sans texte autour.\n"
|
||||
'- Format : {"name": "...", "description": "...", "items": '
|
||||
'[{"name": "Objet", "price": "ex. 50 po", "category": "ex. Armes", "description": "effet/détails"}]}\n'
|
||||
"- Des objets variés et cohérents avec le sujet (et le contexte s'il est fourni).\n"
|
||||
"- 'price' = prix court dans la monnaie du jeu ; 'category' = regroupement (Armes, Potions…) ; "
|
||||
"'description' = effet/détails en une phrase. En français.\n"
|
||||
"Renvoie maintenant le JSON."
|
||||
)
|
||||
try:
|
||||
raw = await generate_with_retry(llm, prompt, output_format="json", temperature=0.7)
|
||||
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 catalogue exploitable.")
|
||||
|
||||
items: list[GeneratedCatalogItemDTO] = []
|
||||
for it in parsed.get("items", []) or []:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
name = str(it.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
items.append(GeneratedCatalogItemDTO(
|
||||
name=name[:200],
|
||||
price=str(it.get("price") or "").strip(),
|
||||
category=str(it.get("category") or "").strip(),
|
||||
description=str(it.get("description") or "").strip(),
|
||||
))
|
||||
if not items:
|
||||
raise HTTPException(status_code=502, detail="Aucun objet généré — réessaie ou reformule.")
|
||||
|
||||
name = str(parsed.get("name") or body.description).strip()[:120] or "Catalogue généré"
|
||||
return GenerateCatalogResponseDTO(
|
||||
name=name,
|
||||
description=str(parsed.get("description") or "").strip(),
|
||||
items=items,
|
||||
)
|
||||
@@ -13,8 +13,19 @@ from __future__ import annotations
|
||||
CHUNK_TARGET_TOKENS = 6000
|
||||
|
||||
|
||||
def chunk_text(full_text: str, target_tokens: int = CHUNK_TARGET_TOKENS) -> list[str]:
|
||||
"""Découpe `full_text` en morceaux ~`target_tokens` tokens (frontières de §)."""
|
||||
def chunk_text(
|
||||
full_text: str,
|
||||
target_tokens: int = CHUNK_TARGET_TOKENS,
|
||||
overlap_tokens: int = 0,
|
||||
) -> list[str]:
|
||||
"""Découpe `full_text` en morceaux ~`target_tokens` tokens (frontières de §).
|
||||
|
||||
`overlap_tokens` > 0 : chaque morceau reprend la fin du précédent (les derniers
|
||||
paragraphes, jusqu'à ~`overlap_tokens` tokens). Utile pour le RAG : une phrase-clé
|
||||
à cheval sur deux morceaux reste retrouvable dans au moins l'un des deux. À
|
||||
laisser à 0 pour les imports (recopie) : un overlap y DUPLIQUERAIT du texte.
|
||||
Un morceau peut légèrement dépasser la cible (jusqu'à target + overlap).
|
||||
"""
|
||||
if not full_text.strip():
|
||||
return []
|
||||
|
||||
@@ -26,32 +37,65 @@ def chunk_text(full_text: str, target_tokens: int = CHUNK_TARGET_TOKENS) -> list
|
||||
chunks: list[str] = []
|
||||
current: list[str] = []
|
||||
current_tokens = 0
|
||||
fresh = False # `current` contient-il du contenu pas encore émis ? (évite de
|
||||
# ré-émettre un morceau composé uniquement de l'overlap en fin de texte)
|
||||
for para in paragraphs:
|
||||
para_tokens = len(enc.encode(para))
|
||||
# Un paragraphe seul plus gros que la cible : on le coupe en sous-blocs.
|
||||
if para_tokens > target_tokens:
|
||||
if current:
|
||||
if current and fresh:
|
||||
chunks.append("\n\n".join(current))
|
||||
current, current_tokens = [], 0
|
||||
chunks.extend(_split_oversized(para, enc, target_tokens))
|
||||
current, current_tokens, fresh = [], 0, False
|
||||
chunks.extend(_split_oversized(para, enc, target_tokens, overlap_tokens))
|
||||
continue
|
||||
if current_tokens + para_tokens > target_tokens and current:
|
||||
if fresh:
|
||||
chunks.append("\n\n".join(current))
|
||||
current, current_tokens = [], 0
|
||||
current, current_tokens = _overlap_tail(current, enc, overlap_tokens)
|
||||
fresh = False
|
||||
current.append(para)
|
||||
current_tokens += para_tokens
|
||||
fresh = True
|
||||
|
||||
if current:
|
||||
if current and fresh:
|
||||
chunks.append("\n\n".join(current))
|
||||
return chunks
|
||||
|
||||
|
||||
def _split_oversized(paragraph: str, enc, target_tokens: int) -> list[str]:
|
||||
"""Coupe un paragraphe géant en sous-blocs ~`target_tokens` tokens."""
|
||||
def _overlap_tail(parts: list[str], enc, overlap_tokens: int) -> tuple[list[str], int]:
|
||||
"""Derniers paragraphes de `parts` totalisant au plus `overlap_tokens` tokens —
|
||||
le « rappel » recopié en tête du morceau suivant."""
|
||||
if overlap_tokens <= 0 or not parts:
|
||||
return [], 0
|
||||
tail: list[str] = []
|
||||
total = 0
|
||||
for para in reversed(parts):
|
||||
para_tokens = len(enc.encode(para))
|
||||
if total + para_tokens > overlap_tokens:
|
||||
break
|
||||
tail.insert(0, para)
|
||||
total += para_tokens
|
||||
if not tail:
|
||||
# Aucun paragraphe entier ne tient dans le budget (paragraphes longs) :
|
||||
# on reprend la FIN du dernier paragraphe pour garantir le recouvrement.
|
||||
tokens = enc.encode(parts[-1])
|
||||
tail = [enc.decode(tokens[-overlap_tokens:])]
|
||||
total = min(overlap_tokens, len(tokens))
|
||||
return tail, total
|
||||
|
||||
|
||||
def _split_oversized(paragraph: str, enc, target_tokens: int, overlap_tokens: int = 0) -> list[str]:
|
||||
"""Coupe un paragraphe géant en sous-blocs ~`target_tokens` tokens (fenêtre
|
||||
glissante avec recouvrement si `overlap_tokens` > 0)."""
|
||||
tokens = enc.encode(paragraph)
|
||||
step = max(1, target_tokens - overlap_tokens)
|
||||
out: list[str] = []
|
||||
for i in range(0, len(tokens), target_tokens):
|
||||
i = 0
|
||||
while i < len(tokens):
|
||||
out.append(enc.decode(tokens[i : i + target_tokens]))
|
||||
if i + target_tokens >= len(tokens):
|
||||
break
|
||||
i += step
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,13 @@ class EmbeddingError(Exception):
|
||||
|
||||
|
||||
class EmbeddingProvider(Protocol):
|
||||
"""Calcule les vecteurs d'une liste de textes (ordre préservé)."""
|
||||
"""Calcule les vecteurs d'une liste de textes (ordre préservé).
|
||||
|
||||
async def embed(self, texts: list[str]) -> list[list[float]]:
|
||||
`kind` distingue les DOCUMENTS indexés ("document") de la QUESTION posée
|
||||
("query") : certains modèles (nomic-embed-text) sont entraînés avec des
|
||||
préfixes de tâche distincts et perdent en pertinence sans eux. Les adapters
|
||||
qui n'en ont pas besoin (mistral-embed) ignorent simplement le paramètre.
|
||||
"""
|
||||
|
||||
async def embed(self, texts: list[str], kind: str = "document") -> list[list[float]]:
|
||||
...
|
||||
|
||||
@@ -10,6 +10,7 @@ PROPOSITION non persistée : le Core crée les entités seulement après revue.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from app.application.chunking import chunk_text, split_in_half
|
||||
@@ -24,6 +25,7 @@ from app.domain.models import (
|
||||
ArcProposal,
|
||||
CampaignImportResult,
|
||||
ChapterProposal,
|
||||
NpcImportProposal,
|
||||
RoomProposal,
|
||||
SceneProposal,
|
||||
)
|
||||
@@ -82,6 +84,14 @@ PIÈCES (rooms) — uniquement pour les scènes qui sont des lieux explorables :
|
||||
- `enemies` = créatures/boss de la salle (vide si aucune). `loot` = trésor/récompense (vide si aucun).
|
||||
- Pour une scène narrative classique (pas un donjon), "rooms" est un tableau vide [].
|
||||
|
||||
PNJ ET CRÉATURES NOTABLES ("npcs", tableau au niveau racine) :
|
||||
- Recense les PNJ NOMMÉS (alliés, marchands, antagonistes) et les créatures UNIQUES
|
||||
(boss, monstre récurrent) présents dans l'extrait.
|
||||
- `description` = courte fiche utile au MJ : rôle dans l'histoire, apparence,
|
||||
motivations, où on le rencontre. 2 à 4 phrases, fidèles au livre.
|
||||
- N'inclus PAS les monstres génériques sans nom (« 3 gobelins », « un loup »).
|
||||
- Aucun PNJ nommé dans l'extrait → "npcs": [].
|
||||
|
||||
Format de réponse :
|
||||
- Tu réponds UNIQUEMENT par un objet JSON valide, sans markdown ni commentaire autour.
|
||||
- Schéma EXACT :
|
||||
@@ -90,12 +100,61 @@ Format de réponse :
|
||||
{{"name": "...", "description": "...", "player_narration": "...", "gm_notes": "...",
|
||||
"rooms": [{{"name": "...", "description": "...", "enemies": "...", "loot": "..."}}]}}
|
||||
]}}]}}
|
||||
]}}
|
||||
],
|
||||
"npcs": [{{"name": "...", "description": "..."}}]}}
|
||||
- Utilise les VRAIS titres du livre pour les noms (pas de paraphrase).
|
||||
- Si le livre n'est PAS découpé en actes/parties, regroupe tout sous un seul arc nommé "{default_arc}".
|
||||
- N'invente pas de contenu : tu réorganises et recopies ce qui est présent dans l'extrait.
|
||||
- Si l'extrait ne contient aucune matière narrative, renvoie {{"arcs": []}}."""
|
||||
|
||||
# Bloc TOC injecté quand le PDF a des bookmarks : les morceaux étant traités
|
||||
# séparément, c'est CE référentiel commun qui garantit que tous nomment les
|
||||
# mêmes chapitres à l'identique → la fusion par nom du _TreeMerger recolle
|
||||
# les chapitres coupés au lieu de créer des doublons.
|
||||
_TOC_BLOCK = """
|
||||
|
||||
--- STRUCTURE OFFICIELLE DU LIVRE (table des matières du PDF) ---
|
||||
{toc}
|
||||
--- FIN DE LA STRUCTURE ---
|
||||
IMPORTANT : pour nommer les arcs et chapitres, reprends EXACTEMENT les titres
|
||||
de cette structure (caractère pour caractère). Rattache le contenu de l'extrait
|
||||
au bon chapitre de la structure, même si son titre n'apparaît pas dans l'extrait."""
|
||||
|
||||
# Garde-fou prompt : une TOC de gros livre peut compter des centaines d'entrées
|
||||
# (sous-sous-sections). On la limite aux niveaux hauts et à un nombre raisonnable.
|
||||
_TOC_MAX_LEVEL = 2
|
||||
_TOC_MAX_ENTRIES = 80
|
||||
|
||||
|
||||
# Consolidation finale : le squelette (noms seuls) est minuscule, donc l'appel
|
||||
# est quasi gratuit comparé aux MAP. Température 0 et consigne CONSERVATRICE :
|
||||
# ne fusionner que les doublons évidents, jamais des entités distinctes.
|
||||
_CONSOLIDATE_PROMPT = """Voici le squelette d'une arborescence arc → chapitre → scène issue d'une
|
||||
fusion AUTOMATIQUE de morceaux d'un livre de campagne de jeu de rôle. La fusion par nom exact
|
||||
peut avoir laissé des QUASI-DOUBLONS : le même chapitre ou la même scène sous deux libellés
|
||||
légèrement différents (ex: "La Crypte" et "Crypte de Karrak", "3. Salle des gardes" et
|
||||
"Salle des gardes").
|
||||
|
||||
{skeleton}
|
||||
|
||||
Identifie UNIQUEMENT les fusions ÉVIDENTES (même entité du livre sous deux noms). Sois
|
||||
CONSERVATEUR : dans le doute, ne fusionne PAS. Deux lieux/évènements distincts ne doivent
|
||||
JAMAIS être fusionnés.
|
||||
|
||||
Réponds UNIQUEMENT par un objet JSON valide :
|
||||
{{"chapter_merges": [{{"into": "nom du chapitre à garder", "merge": ["nom à fusionner", ...]}}],
|
||||
"scene_merges": [{{"chapter": "nom du chapitre", "into": "nom de la scène à garder",
|
||||
"merge": ["nom à fusionner", ...]}}]}}
|
||||
S'il n'y a RIEN à fusionner (cas le plus fréquent) : {{"chapter_merges": [], "scene_merges": []}}"""
|
||||
|
||||
|
||||
def _format_toc(toc) -> str:
|
||||
"""Formate la TOC du PDF en liste indentée, bornée (niveaux hauts d'abord)."""
|
||||
entries = [e for e in toc if e.level <= _TOC_MAX_LEVEL][:_TOC_MAX_ENTRIES]
|
||||
if not entries:
|
||||
return ""
|
||||
return "\n".join(f"{' ' * (e.level - 1)}- {e.title} (p. {e.page})" for e in entries)
|
||||
|
||||
|
||||
class _TreeMerger:
|
||||
"""Fusionne les sous-arbres des morceaux en un seul arbre, ordre préservé.
|
||||
@@ -108,6 +167,8 @@ class _TreeMerger:
|
||||
def __init__(self) -> None:
|
||||
# arc_key -> {"name", "description", "chapters": {chap_key -> {...}}}
|
||||
self._arcs: dict[str, dict] = {}
|
||||
# npc_key (nom en minuscules) -> {"name", "description"}
|
||||
self._npcs: dict[str, dict] = {}
|
||||
|
||||
def add(self, arcs_json: list[dict]) -> None:
|
||||
for arc in arcs_json or []:
|
||||
@@ -136,8 +197,12 @@ class _TreeMerger:
|
||||
{"name": sname, "description": "", "player_narration": "",
|
||||
"gm_notes": "", "rooms": {}})
|
||||
self._fill_desc(s, sc)
|
||||
self._fill_field(s, sc, "player_narration")
|
||||
self._fill_field(s, sc, "gm_notes")
|
||||
# Narration/notes : CONCATÉNATION (pas premier-gagne) — une
|
||||
# scène coupée entre deux morceaux apporte la suite de son
|
||||
# contenu dans le morceau suivant ; la jeter perdrait la
|
||||
# moitié du donjon. Le doublon exact (overlap) est filtré.
|
||||
self._append_field(s, sc, "player_narration")
|
||||
self._append_field(s, sc, "gm_notes")
|
||||
for rm in sc.get("rooms", []) or []:
|
||||
rname = str(rm.get("name", "")).strip()
|
||||
if not rname:
|
||||
@@ -149,6 +214,22 @@ class _TreeMerger:
|
||||
self._fill_field(r, rm, "enemies")
|
||||
self._fill_field(r, rm, "loot")
|
||||
|
||||
def add_npcs(self, npcs_json: list[dict]) -> None:
|
||||
"""Accumule les PNJ détectés. Un PNJ revu dans un autre morceau garde la
|
||||
description la plus COMPLÈTE (la plus longue) — un PNJ récurrent est
|
||||
souvent décrit en détail une seule fois."""
|
||||
for npc in npcs_json or []:
|
||||
name = str(npc.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
desc = str(npc.get("description") or "").strip()
|
||||
entry = self._npcs.setdefault(name.lower(), {"name": name, "description": ""})
|
||||
if len(desc) > len(entry["description"]):
|
||||
entry["description"] = desc
|
||||
|
||||
def npcs(self) -> list[NpcImportProposal]:
|
||||
return [NpcImportProposal(n["name"], n["description"]) for n in self._npcs.values()]
|
||||
|
||||
@staticmethod
|
||||
def _fill_desc(node: dict, src: dict) -> None:
|
||||
if not node["description"]:
|
||||
@@ -159,6 +240,23 @@ class _TreeMerger:
|
||||
if not node[field_name]:
|
||||
node[field_name] = str(src.get(field_name) or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def _append_field(node: dict, src: dict, field_name: str) -> None:
|
||||
"""Accumule la valeur de `src` à la suite de l'existante (scène coupée
|
||||
entre deux morceaux). Ignore le vide et le contenu déjà présent (un
|
||||
morceau redondant — relecture d'overlap — ne duplique rien)."""
|
||||
new = str(src.get(field_name) or "").strip()
|
||||
if not new:
|
||||
return
|
||||
current = node[field_name]
|
||||
if not current:
|
||||
node[field_name] = new
|
||||
elif new not in current and current not in new:
|
||||
node[field_name] = current + "\n\n" + new
|
||||
elif current in new:
|
||||
# Le nouveau contenu ENGLOBE l'ancien (version plus complète) → on le prend.
|
||||
node[field_name] = new
|
||||
|
||||
def result(self) -> list[ArcProposal]:
|
||||
arcs: list[ArcProposal] = []
|
||||
for a in self._arcs.values():
|
||||
@@ -182,6 +280,79 @@ class _TreeMerger:
|
||||
scenes = sum(len(c["scenes"]) for a in self._arcs.values() for c in a["chapters"].values())
|
||||
return arcs, chapters, scenes
|
||||
|
||||
# --- Consolidation : fusion des quasi-doublons détectés par le LLM ---------
|
||||
|
||||
def skeleton_text(self) -> str:
|
||||
"""Squelette de l'arbre (noms seuls) — entrée compacte de la consolidation."""
|
||||
lines: list[str] = []
|
||||
for a in self._arcs.values():
|
||||
lines.append(f"ARC: {a['name']}")
|
||||
for c in a["chapters"].values():
|
||||
lines.append(f" CHAPITRE: {c['name']}")
|
||||
for s in c["scenes"].values():
|
||||
lines.append(f" SCENE: {s['name']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
def merge_chapters(self, into_name: str, merge_names: list[str]) -> bool:
|
||||
"""Fusionne les chapitres `merge_names` dans `into_name` (tous arcs).
|
||||
|
||||
Best-effort : les noms inconnus sont ignorés. Renvoie True si modifié.
|
||||
"""
|
||||
target = self._find_chapter(into_name)
|
||||
if target is None:
|
||||
return False
|
||||
changed = False
|
||||
for mname in merge_names:
|
||||
key = str(mname).strip().lower()
|
||||
if not key or key == str(into_name).strip().lower():
|
||||
continue
|
||||
for a in self._arcs.values():
|
||||
src = a["chapters"].pop(key, None)
|
||||
if src is None or src is target:
|
||||
continue
|
||||
self._fill_desc(target, src)
|
||||
for skey, sdict in src["scenes"].items():
|
||||
if skey in target["scenes"]:
|
||||
self._merge_scene_into(target["scenes"][skey], sdict)
|
||||
else:
|
||||
target["scenes"][skey] = sdict
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
def merge_scenes(self, chapter_name: str, into_name: str, merge_names: list[str]) -> bool:
|
||||
"""Fusionne les scènes `merge_names` dans `into_name` au sein du chapitre."""
|
||||
chapter = self._find_chapter(chapter_name)
|
||||
if chapter is None:
|
||||
return False
|
||||
target = chapter["scenes"].get(str(into_name).strip().lower())
|
||||
if target is None:
|
||||
return False
|
||||
changed = False
|
||||
for mname in merge_names:
|
||||
key = str(mname).strip().lower()
|
||||
if not key or key == str(into_name).strip().lower():
|
||||
continue
|
||||
src = chapter["scenes"].pop(key, None)
|
||||
if src is None or src is target:
|
||||
continue
|
||||
self._merge_scene_into(target, src)
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
def _find_chapter(self, name: str) -> dict | None:
|
||||
key = str(name).strip().lower()
|
||||
for a in self._arcs.values():
|
||||
if key in a["chapters"]:
|
||||
return a["chapters"][key]
|
||||
return None
|
||||
|
||||
def _merge_scene_into(self, target: dict, src: dict) -> None:
|
||||
self._fill_desc(target, src)
|
||||
self._append_field(target, src, "player_narration")
|
||||
self._append_field(target, src, "gm_notes")
|
||||
for rkey, rdict in src.get("rooms", {}).items():
|
||||
target["rooms"].setdefault(rkey, rdict)
|
||||
|
||||
|
||||
class ImportCampaignUseCase:
|
||||
"""Transforme un PDF de campagne en proposition d'arbre arc→chapitre→scène."""
|
||||
@@ -191,22 +362,39 @@ class ImportCampaignUseCase:
|
||||
llm: LLMProvider,
|
||||
extractor: PdfTextExtractor,
|
||||
chunk_target_tokens: int = _CHUNK_TARGET_TOKENS,
|
||||
map_concurrency: int = 1,
|
||||
) -> None:
|
||||
self._llm = llm
|
||||
self._extractor = extractor
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
# Appels MAP par VAGUES de cette taille : l'ordre narratif est préservé
|
||||
# (fusion vague par vague, dans l'ordre du livre) mais le mur d'attente
|
||||
# des appels LLM est divisé d'autant. 1 = comportement séquentiel.
|
||||
self._map_concurrency = max(1, map_concurrency)
|
||||
|
||||
async def execute(self, pdf_bytes: bytes) -> CampaignImportResult:
|
||||
"""Variante non-streamée : traite tout puis renvoie l'arbre complet."""
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
toc_block = _format_toc(doc.toc)
|
||||
merger = _TreeMerger()
|
||||
for i, chunk in enumerate(chunks):
|
||||
merger.add(await self._map_chunk(chunk, index=i, total=len(chunks)))
|
||||
total = len(chunks)
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
results = await asyncio.gather(*(
|
||||
self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
for i, c in wave
|
||||
))
|
||||
for res in results:
|
||||
merger.add(res["arcs"])
|
||||
merger.add_npcs(res["npcs"])
|
||||
if total > 1:
|
||||
await self._consolidate(merger)
|
||||
return CampaignImportResult(
|
||||
arcs=merger.result(),
|
||||
page_count=doc.page_count,
|
||||
ocr_page_count=doc.ocr_page_count,
|
||||
npcs=merger.npcs(),
|
||||
)
|
||||
|
||||
async def stream(self, pdf_bytes: bytes):
|
||||
@@ -221,10 +409,12 @@ class ImportCampaignUseCase:
|
||||
|
||||
doc = self._extractor.extract(pdf_bytes)
|
||||
chunks = chunk_text(doc.full_text, self._chunk_target_tokens)
|
||||
toc_block = _format_toc(doc.toc)
|
||||
total = len(chunks)
|
||||
logger.info(
|
||||
"Import campagne (stream) : %s page(s) (%s via OCR), %s morceau(x).",
|
||||
"Import campagne (stream) : %s page(s) (%s via OCR), %s morceau(x), TOC %s.",
|
||||
doc.page_count, doc.ocr_page_count, total,
|
||||
"présente" if toc_block else "absente",
|
||||
)
|
||||
yield {
|
||||
"type": "start",
|
||||
@@ -236,36 +426,50 @@ class ImportCampaignUseCase:
|
||||
merger = _TreeMerger()
|
||||
skipped = 0
|
||||
last_error: str | None = None
|
||||
for i, chunk in enumerate(chunks):
|
||||
done_count = 0
|
||||
# PARALLÉLISME : les morceaux sont traités par VAGUES de `map_concurrency`
|
||||
# appels simultanés. L'ordre narratif est préservé : la fusion se fait
|
||||
# vague par vague, dans l'ordre du livre.
|
||||
# RÉSILIENCE : un morceau qui échoue (provider saturé, quota, etc.) est
|
||||
# SAUTÉ — on ne perd pas tout l'import pour autant. On n'abandonne que
|
||||
# si AUCUN morceau ne passe (cf. après la boucle).
|
||||
# HEARTBEAT : keep-alive pendant l'appel LLM pour ne jamais laisser le
|
||||
# flux SSE silencieux (sinon le Core coupe sur timeout d'inactivité).
|
||||
try:
|
||||
arcs_payload: list[dict] | None = None
|
||||
async for kind, payload in with_heartbeat(
|
||||
self._map_chunk(chunk, index=i, total=total)
|
||||
):
|
||||
# HEARTBEAT : keep-alive pendant la vague d'appels LLM pour ne jamais
|
||||
# laisser le flux SSE silencieux (sinon le Core coupe sur inactivité).
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
wave = list(enumerate(chunks))[start:start + self._map_concurrency]
|
||||
gathered = asyncio.gather(
|
||||
*(self._map_chunk(c, index=i, total=total, toc_block=toc_block)
|
||||
for i, c in wave),
|
||||
return_exceptions=True,
|
||||
)
|
||||
results: list | None = None
|
||||
async for kind, payload in with_heartbeat(gathered):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": i + 1, "total": total}
|
||||
yield {"type": "heartbeat", "current": done_count + 1, "total": total}
|
||||
else:
|
||||
arcs_payload = payload
|
||||
merger.add(arcs_payload or [])
|
||||
except LLMProviderError as exc:
|
||||
results = payload
|
||||
for (i, _), res in zip(wave, results or []):
|
||||
done_count += 1
|
||||
if isinstance(res, LLMProviderError):
|
||||
skipped += 1
|
||||
last_error = str(exc)
|
||||
logger.warning("Morceau %s/%s ignoré (échec LLM) : %s", i + 1, total, exc)
|
||||
last_error = str(res)
|
||||
logger.warning("Morceau %s/%s ignoré (échec LLM) : %s", i + 1, total, res)
|
||||
yield {"type": "chunk_failed", "current": i + 1, "total": total,
|
||||
"message": str(exc)[:300]}
|
||||
"message": str(res)[:300]}
|
||||
elif isinstance(res, BaseException):
|
||||
raise res # bug inattendu : ne pas l'avaler en silence
|
||||
else:
|
||||
merger.add((res or {}).get("arcs") or [])
|
||||
merger.add_npcs((res or {}).get("npcs") or [])
|
||||
arcs, chapters, scenes = merger.counts()
|
||||
yield {
|
||||
"type": "progress",
|
||||
"current": i + 1,
|
||||
"current": done_count,
|
||||
"total": total,
|
||||
"arc_count": arcs,
|
||||
"chapter_count": chapters,
|
||||
"scene_count": scenes,
|
||||
"npc_count": len(merger.npcs()),
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
@@ -276,33 +480,86 @@ class ImportCampaignUseCase:
|
||||
f"Dernier message : {last_error or 'inconnu'}"}
|
||||
return
|
||||
|
||||
# Consolidation finale : fusion des quasi-doublons inter-morceaux
|
||||
# (best-effort, voir _consolidate). Inutile sur un import mono-morceau.
|
||||
if total > 1:
|
||||
yield {"type": "consolidating", "total": total}
|
||||
async for kind, _ in with_heartbeat(self._consolidate(merger)):
|
||||
if kind == "heartbeat":
|
||||
yield {"type": "heartbeat", "current": total, "total": total}
|
||||
|
||||
yield {
|
||||
"type": "done",
|
||||
"arcs": _serialize_arcs(merger.result()),
|
||||
"npcs": [{"name": n.name, "description": n.description} for n in merger.npcs()],
|
||||
"page_count": doc.page_count,
|
||||
"ocr_page_count": doc.ocr_page_count,
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
# --- Consolidation finale (fusion des quasi-doublons) ---------------------
|
||||
|
||||
async def _consolidate(self, merger: _TreeMerger) -> None:
|
||||
"""Une passe LLM sur le squelette pour fusionner les quasi-doublons.
|
||||
|
||||
BEST-EFFORT : toute erreur (LLM indisponible, JSON invalide, noms
|
||||
inconnus) laisse l'arbre tel quel — la consolidation ne peut qu'améliorer,
|
||||
jamais bloquer un import.
|
||||
"""
|
||||
_, chapters, scenes = merger.counts()
|
||||
if chapters + scenes < 3:
|
||||
return # rien à dédoublonner sur un arbre minuscule
|
||||
skeleton = merger.skeleton_text()
|
||||
try:
|
||||
raw = await generate_with_retry(
|
||||
self._llm, _CONSOLIDATE_PROMPT.format(skeleton=skeleton),
|
||||
output_format="json", temperature=0.0)
|
||||
except Exception as exc: # noqa: BLE001 — best-effort STRICT : une erreur ici
|
||||
# (LLM, réseau, bug) ne doit JAMAIS faire perdre un import terminé.
|
||||
logger.warning("Consolidation ignorée (échec) : %s", exc)
|
||||
return
|
||||
parsed, _ = load_json_object(raw)
|
||||
if not isinstance(parsed, dict):
|
||||
logger.warning("Consolidation ignorée (réponse non-JSON).")
|
||||
return
|
||||
merged = 0
|
||||
for cm in parsed.get("chapter_merges") or []:
|
||||
if isinstance(cm, dict) and merger.merge_chapters(
|
||||
str(cm.get("into") or ""), list(cm.get("merge") or [])):
|
||||
merged += 1
|
||||
for sm in parsed.get("scene_merges") or []:
|
||||
if isinstance(sm, dict) and merger.merge_scenes(
|
||||
str(sm.get("chapter") or ""), str(sm.get("into") or ""),
|
||||
list(sm.get("merge") or [])):
|
||||
merged += 1
|
||||
if merged:
|
||||
logger.info("Consolidation : %s fusion(s) de quasi-doublons appliquée(s).", merged)
|
||||
|
||||
# --- MAP : un morceau → sous-arbre ---------------------------------------
|
||||
|
||||
async def _map_chunk(self, chunk: str, *, index: int, total: int) -> list[dict]:
|
||||
return await self._extract_arcs(chunk, index=index, total=total, depth=0)
|
||||
async def _map_chunk(
|
||||
self, chunk: str, *, index: int, total: int, toc_block: str = ""
|
||||
) -> dict:
|
||||
"""Phase MAP d'un morceau → {"arcs": [...], "npcs": [...]}."""
|
||||
return await self._extract_payload(
|
||||
chunk, index=index, total=total, depth=0, toc_block=toc_block)
|
||||
|
||||
async def _extract_arcs(
|
||||
self, text: str, *, index: int, total: int, depth: int
|
||||
) -> list[dict]:
|
||||
"""Extrait l'arborescence d'un texte. Si la SORTIE est tronquée, retraite le
|
||||
texte en DEUX moitiés et concatène — le `_TreeMerger` final dédoublonne par
|
||||
nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||
async def _extract_payload(
|
||||
self, text: str, *, index: int, total: int, depth: int, toc_block: str = ""
|
||||
) -> dict:
|
||||
"""Extrait l'arborescence + les PNJ d'un texte. Si la SORTIE est tronquée,
|
||||
retraite le texte en DEUX moitiés et concatène — le `_TreeMerger` final
|
||||
dédoublonne par nom (un arc/chapitre coupé entre les moitiés est recollé)."""
|
||||
toc_section = _TOC_BLOCK.format(toc=toc_block) if toc_block else ""
|
||||
prompt = (
|
||||
_MAP_SYSTEM.format(default_arc=_DEFAULT_ARC_NAME)
|
||||
+ toc_section
|
||||
+ f"\n\n--- EXTRAIT {index + 1}/{total} ---\n{text}\n\n"
|
||||
"Renvoie maintenant le JSON de l'arborescence."
|
||||
)
|
||||
raw = await generate_with_retry(
|
||||
self._llm, prompt, output_format="json", temperature=_TEMPERATURE)
|
||||
arcs, truncated = self._parse_arcs(raw, index=index)
|
||||
payload, truncated = self._parse_payload(raw, index=index)
|
||||
|
||||
if truncated and depth < _MAX_SPLIT_DEPTH:
|
||||
left, right = split_in_half(text)
|
||||
@@ -310,17 +567,20 @@ class ImportCampaignUseCase:
|
||||
logger.info(
|
||||
"Morceau %s : sortie tronquée → re-découpage en 2 moitiés (niveau %s).",
|
||||
index, depth + 1)
|
||||
a = await self._extract_arcs(left, index=index, total=total, depth=depth + 1)
|
||||
b = await self._extract_arcs(right, index=index, total=total, depth=depth + 1)
|
||||
return a + b
|
||||
a = await self._extract_payload(
|
||||
left, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
b = await self._extract_payload(
|
||||
right, index=index, total=total, depth=depth + 1, toc_block=toc_block)
|
||||
return {"arcs": a["arcs"] + b["arcs"], "npcs": a["npcs"] + b["npcs"]}
|
||||
if truncated:
|
||||
logger.warning(
|
||||
"Morceau %s : sortie tronquée, profondeur max atteinte — partiel conservé.", index)
|
||||
return arcs
|
||||
return payload
|
||||
|
||||
@staticmethod
|
||||
def _parse_arcs(raw: str, *, index: int) -> tuple[list[dict], bool]:
|
||||
"""Parse robuste → (arcs, tronqué). `tronqué`=True si récupération partielle."""
|
||||
def _parse_payload(raw: str, *, index: int) -> tuple[dict, bool]:
|
||||
"""Parse robuste → ({"arcs", "npcs"}, tronqué). `tronqué`=True si partiel."""
|
||||
empty = {"arcs": [], "npcs": []}
|
||||
parsed, recovered = load_json_object(raw)
|
||||
if parsed is None:
|
||||
truncated = looks_like_truncated_json(raw)
|
||||
@@ -329,11 +589,15 @@ class ImportCampaignUseCase:
|
||||
"Morceau %s : aucun objet JSON exploitable, ignoré. "
|
||||
"Début de la réponse du modèle : %r",
|
||||
index, (raw or "").strip()[:300] or "(réponse VIDE)")
|
||||
return [], truncated
|
||||
return empty, truncated
|
||||
if isinstance(parsed, dict):
|
||||
arcs = parsed.get("arcs", [])
|
||||
return (arcs if isinstance(arcs, list) else []), recovered
|
||||
return [], recovered
|
||||
npcs = parsed.get("npcs", [])
|
||||
return {
|
||||
"arcs": arcs if isinstance(arcs, list) else [],
|
||||
"npcs": npcs if isinstance(npcs, list) else [],
|
||||
}, recovered
|
||||
return empty, recovered
|
||||
|
||||
|
||||
def _serialize_arcs(arcs: list[ArcProposal]) -> list[dict]:
|
||||
|
||||
@@ -9,6 +9,8 @@ from __future__ import annotations
|
||||
from typing import AsyncIterator
|
||||
|
||||
from app.application.notebook_rag import NotebookRagUseCase
|
||||
from app.application.query_rewrite import standalone_question
|
||||
from app.application.rerank import pool_size, rerank
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMChatProvider
|
||||
|
||||
@@ -57,9 +59,13 @@ Réponds en français, de façon utile et concise. Mets le texte explicatif AVAN
|
||||
|
||||
|
||||
class NotebookChatUseCase:
|
||||
def __init__(self, rag: NotebookRagUseCase, llm: LLMChatProvider) -> None:
|
||||
def __init__(
|
||||
self, rag: NotebookRagUseCase, llm: LLMChatProvider, rerank_enabled: bool = False
|
||||
) -> None:
|
||||
self._rag = rag
|
||||
self._llm = llm
|
||||
# Reranking LLM d'un pool élargi avant injection (voir app.application.rerank).
|
||||
self._rerank_enabled = rerank_enabled
|
||||
|
||||
async def stream(
|
||||
self,
|
||||
@@ -67,9 +73,32 @@ class NotebookChatUseCase:
|
||||
messages: list[ChatMessage],
|
||||
context: str = "",
|
||||
top_k: int = 6,
|
||||
) -> AsyncIterator[str]:
|
||||
last_user = next((m.content for m in reversed(messages) if m.role == "user"), "")
|
||||
passages = await self._rag.retrieve(source_ids, last_user, top_k=top_k)
|
||||
) -> AsyncIterator[dict]:
|
||||
"""Yield des évènements : {type:'sources', sources:[…]} (une fois, avant la
|
||||
réponse — transparence sur les passages utilisés), puis {type:'token', token}."""
|
||||
# Question AUTONOME pour la recherche : sur une relance (« et ses
|
||||
# faiblesses ? »), l'embedding du dernier message seul ne contient pas
|
||||
# le sujet → on le résout depuis l'historique (best-effort, 1 appel léger,
|
||||
# uniquement à partir du 2e tour). La réponse, elle, voit tout l'historique.
|
||||
search_query = await standalone_question(self._llm, messages)
|
||||
if self._rerank_enabled:
|
||||
# Pool élargi → notation LLM → top_k final (meilleure précision sur
|
||||
# les questions ambiguës, au prix d'un appel avant le premier token).
|
||||
pool = await self._rag.retrieve(
|
||||
source_ids, search_query, top_k=pool_size(top_k))
|
||||
passages = await rerank(self._llm, search_query, pool, top_k)
|
||||
else:
|
||||
passages = await self._rag.retrieve(source_ids, search_query, top_k=top_k)
|
||||
# Évènement 'sources' AVANT le premier token : l'UI peut afficher les
|
||||
# pages utilisées (« 📖 p. 12, 47 ») dès le début de la réponse.
|
||||
yield {"type": "sources", "sources": [
|
||||
{
|
||||
"source_id": p.get("source_id"),
|
||||
"page": p.get("page"),
|
||||
"score": round(float(p.get("score") or 0.0), 3),
|
||||
}
|
||||
for p in passages
|
||||
]}
|
||||
sources_block = (
|
||||
"\n\n".join(self._format_passage(p) for p in passages)
|
||||
if passages else "(aucun passage pertinent trouvé dans les sources)"
|
||||
@@ -81,7 +110,7 @@ class NotebookChatUseCase:
|
||||
system_prompt = _SYSTEM_PROMPT.format(
|
||||
context_block=context_block, sources_block=sources_block)
|
||||
async for token in self._llm.stream_chat(messages, system_prompt=system_prompt):
|
||||
yield token
|
||||
yield {"type": "token", "token": token}
|
||||
|
||||
@staticmethod
|
||||
def _format_passage(p: dict) -> str:
|
||||
|
||||
@@ -13,12 +13,14 @@ lots ; avec un petit modèle local, plus de lots (mais ça reste exhaustif).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import AsyncIterator
|
||||
|
||||
import tiktoken
|
||||
|
||||
from app.application.llm_retry import generate_with_retry
|
||||
from app.application.query_rewrite import standalone_question
|
||||
from app.domain.models import ChatMessage
|
||||
from app.domain.ports import LLMChatProvider, LLMProvider, LLMProviderError
|
||||
from app.infrastructure import vector_store
|
||||
@@ -28,6 +30,28 @@ logger = logging.getLogger(__name__)
|
||||
_NO_MATCH = "RAS"
|
||||
_MAP_TEMPERATURE = 0.2
|
||||
|
||||
# --- Index de résumés (pré-filtrage des lots) --------------------------------
|
||||
# Sans index : CHAQUE question relit TOUT le document (1 appel LLM par lot).
|
||||
# Avec : les résumés de lots (construits UNE fois, cache disque) sont comparés
|
||||
# à la question par embedding, et seuls les lots plausiblement pertinents sont
|
||||
# relus. Sélection volontairement CONSERVATRICE (on préfère relire un lot de
|
||||
# trop que rater une mention) ; désactivable via deep_summary_filter=False.
|
||||
_SUMMARY_PROMPT = """Résume l'EXTRAIT ci-dessous en 4 à 8 puces factuelles : lieux, PNJ et
|
||||
créatures nommés, objets notables, évènements, règles particulières. Pas d'analyse, pas
|
||||
d'introduction — uniquement les puces, pour servir d'index de recherche.
|
||||
|
||||
--- EXTRAIT ---
|
||||
{excerpt}
|
||||
--- FIN EXTRAIT ---
|
||||
|
||||
Résumé :"""
|
||||
|
||||
# Un lot est gardé si son score est proche du meilleur (marge) OU bon dans
|
||||
# l'absolu ; et on garde toujours au moins _MIN_KEPT lots.
|
||||
_SELECT_MARGIN = 0.10
|
||||
_SELECT_FLOOR = 0.5
|
||||
_MIN_KEPT = 3
|
||||
|
||||
_MAP_PROMPT = """Voici un EXTRAIT d'un document. Extrais UNIQUEMENT les informations
|
||||
pertinentes pour répondre à la question ci-dessous. Conserve les détails utiles et
|
||||
indique les numéros de page (format « p. X »). Si l'extrait ne contient RIEN de
|
||||
@@ -41,11 +65,17 @@ QUESTION : {question}
|
||||
|
||||
Informations pertinentes (ou « {no_match} ») :"""
|
||||
|
||||
_REDUCE_SYSTEM = """Tu réponds à la question d'un MJ à partir de NOTES extraites de
|
||||
l'ENSEMBLE d'un document source (donc tu as une vue COMPLÈTE, pas un simple extrait).
|
||||
Synthétise ces notes en une réponse claire et structurée, cite les pages (« p. X »),
|
||||
et n'invente rien qui n'y figure pas. Si une CAMPAGNE est fournie ci-dessous, relie ta
|
||||
réponse à sa structure / ses PNJ pour des adaptations cohérentes.
|
||||
_REDUCE_SYSTEM = """Tu es l'assistant-MJ d'un jeu de rôle. Tu réponds à la demande du MJ en
|
||||
t'appuyant sur TROIS sources : (1) des NOTES extraites de l'ENSEMBLE du document source (vue
|
||||
complète — mais POSSIBLEMENT VIDE si rien d'utile n'y figure), (2) le contexte de sa CAMPAGNE,
|
||||
(3) la conversation ci-dessous.
|
||||
|
||||
- Si les notes contiennent des éléments utiles : exploite-les et CITE les pages (« p. X »).
|
||||
- Si les notes sont VIDES ou pauvres (cas fréquent d'une demande CRÉATIVE portant sur des
|
||||
éléments INVENTÉS par le MJ) : ne te bloque surtout PAS. Aide-le quand même en t'appuyant
|
||||
sur sa CAMPAGNE, la CONVERSATION et ta connaissance du genre — propose des adaptations
|
||||
concrètes (arcs, chapitres, scènes, PNJ), structurées et jouables.
|
||||
- Sois concret et utile. N'affirme rien de FAUX sur le contenu du document.
|
||||
|
||||
{context_block}
|
||||
--- NOTES EXTRAITES DE TOUT LE DOCUMENT ---
|
||||
@@ -56,9 +86,22 @@ Réponds en français."""
|
||||
|
||||
|
||||
class NotebookDeepUseCase:
|
||||
def __init__(self, llm: LLMProvider, batch_tokens: int = 10000) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
llm: LLMProvider,
|
||||
batch_tokens: int = 10000,
|
||||
map_concurrency: int = 1,
|
||||
embedder=None,
|
||||
summary_filter: bool = True,
|
||||
) -> None:
|
||||
self._llm = llm
|
||||
self._batch_tokens = max(2000, batch_tokens)
|
||||
# Lots MAP traités par vagues de cette taille (parallélisme LLM).
|
||||
self._map_concurrency = max(1, map_concurrency)
|
||||
# EmbeddingProvider (duck typing) pour l'index de résumés ; None = pas
|
||||
# de pré-filtrage (plein scan, comportement historique).
|
||||
self._embedder = embedder
|
||||
self._summary_filter = summary_filter
|
||||
|
||||
async def stream(
|
||||
self,
|
||||
@@ -74,33 +117,57 @@ class NotebookDeepUseCase:
|
||||
SYNTHÈSE (reduce) reçoit les `history_limit` derniers messages → les relances
|
||||
conversationnelles (« et pour les autres ? ») fonctionnent aussi en approfondi.
|
||||
"""
|
||||
question = next((m.content for m in reversed(messages) if m.role == "user"), "")
|
||||
chunks: list[dict] = []
|
||||
# Question autonome : la phase MAP lit chaque lot avec LA question — sur
|
||||
# une relance conversationnelle, il faut y résoudre les références
|
||||
# implicites, sinon les lots sont filtrés sur un texte sans sujet.
|
||||
question = await standalone_question(self._llm, messages)
|
||||
# Lots PAR SOURCE (l'index de résumés est caché par source).
|
||||
per_source: list[tuple[str, list[dict]]] = []
|
||||
for sid in source_ids:
|
||||
chunks.extend(vector_store.all_chunks(sid))
|
||||
if not chunks:
|
||||
chunks = vector_store.all_chunks(sid)
|
||||
for batch in self._group(chunks):
|
||||
per_source.append((sid, batch))
|
||||
if not per_source:
|
||||
yield {"type": "token", "token": "Aucune source indexée à analyser."}
|
||||
yield {"type": "done"}
|
||||
return
|
||||
|
||||
batches = self._group(chunks)
|
||||
total = len(batches)
|
||||
notes: list[str] = []
|
||||
for i, batch in enumerate(batches):
|
||||
yield {"type": "progress", "current": i, "total": total}
|
||||
excerpt = "\n\n".join(
|
||||
f"(p. {c['page']}) {c['text'].strip()}" if c.get("page") else c["text"].strip()
|
||||
for c in batch
|
||||
)
|
||||
prompt = _MAP_PROMPT.format(no_match=_NO_MATCH, question=question, excerpt=excerpt)
|
||||
# Pré-filtrage par index de résumés (best-effort : tout échec → plein scan).
|
||||
selected: set[int] | None = None
|
||||
if self._summary_filter and self._embedder is not None:
|
||||
try:
|
||||
raw = await generate_with_retry(self._llm, prompt, temperature=_MAP_TEMPERATURE)
|
||||
except LLMProviderError as exc:
|
||||
logger.warning("Analyse approfondie : lot %s/%s ignoré : %s", i + 1, total, exc)
|
||||
continue
|
||||
answer = raw.strip()
|
||||
if answer and answer.upper().rstrip(".") != _NO_MATCH:
|
||||
notes.append(answer)
|
||||
async for ev_or_result in self._select_batches(per_source, question):
|
||||
if isinstance(ev_or_result, dict):
|
||||
yield ev_or_result # progress de construction de l'index
|
||||
else:
|
||||
selected = ev_or_result
|
||||
except Exception as exc: # noqa: BLE001 — le filtre ne doit jamais bloquer
|
||||
logger.warning("Index de résumés ignoré (échec) : %s", exc)
|
||||
selected = None
|
||||
if selected is not None:
|
||||
logger.info(
|
||||
"Analyse approfondie : %s/%s lot(s) retenus via l'index de résumés.",
|
||||
len(selected), len(per_source))
|
||||
|
||||
indices = sorted(selected) if selected is not None else list(range(len(per_source)))
|
||||
total = len(indices)
|
||||
notes: list[str] = []
|
||||
# Lots traités par VAGUES parallèles ; les notes restent dans l'ordre du
|
||||
# document (gather préserve l'ordre des tâches de la vague).
|
||||
for start in range(0, total, self._map_concurrency):
|
||||
yield {"type": "progress", "current": start, "total": total}
|
||||
wave = indices[start:start + self._map_concurrency]
|
||||
results = await asyncio.gather(
|
||||
*(self._map_batch(question, per_source[i][1]) for i in wave),
|
||||
return_exceptions=True)
|
||||
for j, res in enumerate(results):
|
||||
if isinstance(res, LLMProviderError):
|
||||
logger.warning(
|
||||
"Analyse approfondie : lot %s/%s ignoré : %s", start + j + 1, total, res)
|
||||
elif isinstance(res, BaseException):
|
||||
raise res # bug inattendu : ne pas l'avaler
|
||||
elif res:
|
||||
notes.append(res)
|
||||
yield {"type": "progress", "current": total, "total": total}
|
||||
|
||||
notes_block = "\n\n".join(notes) if notes else "(aucune information pertinente trouvée dans le document)"
|
||||
@@ -113,10 +180,93 @@ class NotebookDeepUseCase:
|
||||
# dernier message est bien la question courante.
|
||||
reduce_messages = messages[-history_limit:] if messages else [ChatMessage(role="user", content=question)]
|
||||
llm_chat: LLMChatProvider = self._llm # type: ignore[assignment]
|
||||
produced = False
|
||||
async for token in llm_chat.stream_chat(reduce_messages, system_prompt=system_prompt):
|
||||
if token:
|
||||
produced = True
|
||||
yield {"type": "token", "token": token}
|
||||
if not produced:
|
||||
# Jamais de bulle vide : message de repli + orientation vers le mode rapide,
|
||||
# mieux adapté aux demandes créatives (et qui propose des cartes d'action).
|
||||
yield {"type": "token", "token": (
|
||||
"Je n'ai pas trouvé d'éléments pertinents dans le document pour cette demande "
|
||||
"(elle porte sans doute sur des éléments que tu as inventés). Pour une "
|
||||
"**adaptation créative** — proposer des arcs, chapitres, scènes ou PNJ — "
|
||||
"utilise plutôt le bouton **« Envoyer »** (mode rapide) : il est conversationnel, "
|
||||
"voit ta campagne, et te propose des cartes « Créer dans la campagne »."
|
||||
)}
|
||||
yield {"type": "done"}
|
||||
|
||||
# --- Index de résumés ------------------------------------------------------
|
||||
|
||||
async def _select_batches(self, per_source: list[tuple[str, list[dict]]], question: str):
|
||||
"""Générateur : yield des évènements `progress` pendant la construction de
|
||||
l'index (1ère analyse d'une source), puis le set des indices retenus —
|
||||
ou None si le filtre n'apporte rien (tous retenus)."""
|
||||
# 1. Charge/construit les résumés par source (cache disque).
|
||||
by_sid: dict[str, list[int]] = {}
|
||||
for i, (sid, _) in enumerate(per_source):
|
||||
by_sid.setdefault(sid, []).append(i)
|
||||
vectors: list[list[float] | None] = [None] * len(per_source)
|
||||
|
||||
to_build = []
|
||||
for sid, idxs in by_sid.items():
|
||||
cached = vector_store.load_summaries(sid, self._batch_tokens)
|
||||
if cached is not None and len(cached) == len(idxs):
|
||||
for i, entry in zip(idxs, cached):
|
||||
vectors[i] = entry.get("vector")
|
||||
else:
|
||||
to_build.append((sid, idxs))
|
||||
|
||||
total_build = sum(len(idxs) for _, idxs in to_build)
|
||||
done_build = 0
|
||||
for sid, idxs in to_build:
|
||||
summaries: list[str] = []
|
||||
for start in range(0, len(idxs), self._map_concurrency):
|
||||
yield {"type": "progress", "current": done_build, "total": total_build}
|
||||
wave = idxs[start:start + self._map_concurrency]
|
||||
results = await asyncio.gather(
|
||||
*(self._summarize_batch(per_source[i][1]) for i in wave))
|
||||
summaries.extend(results)
|
||||
done_build += len(wave)
|
||||
vecs = await self._embedder.embed(summaries, kind="document")
|
||||
entries = [{"summary": s, "vector": v} for s, v in zip(summaries, vecs)]
|
||||
vector_store.save_summaries(sid, self._batch_tokens, entries)
|
||||
for i, entry in zip(idxs, entries):
|
||||
vectors[i] = entry["vector"]
|
||||
|
||||
# 2. Score de chaque lot face à la question, sélection conservatrice.
|
||||
qv = (await self._embedder.embed([question], kind="query"))[0]
|
||||
scores = [
|
||||
vector_store.cosine_similarity(qv, v) if v else 0.0
|
||||
for v in vectors
|
||||
]
|
||||
best = max(scores)
|
||||
keep = {i for i, s in enumerate(scores) if s >= best - _SELECT_MARGIN or s >= _SELECT_FLOOR}
|
||||
floor = min(_MIN_KEPT, len(scores))
|
||||
if len(keep) < floor:
|
||||
keep = set(sorted(range(len(scores)), key=lambda i: -scores[i])[:floor])
|
||||
yield keep if len(keep) < len(scores) else None
|
||||
|
||||
async def _summarize_batch(self, batch: list[dict]) -> str:
|
||||
excerpt = "\n\n".join(c.get("text", "").strip() for c in batch)
|
||||
raw = await generate_with_retry(
|
||||
self._llm, _SUMMARY_PROMPT.format(excerpt=excerpt), temperature=_MAP_TEMPERATURE)
|
||||
return (raw or "").strip()
|
||||
|
||||
async def _map_batch(self, question: str, batch: list[dict]) -> str:
|
||||
"""Phase MAP d'un lot : extrait les infos pertinentes ('' si RAS)."""
|
||||
excerpt = "\n\n".join(
|
||||
f"(p. {c['page']}) {c['text'].strip()}" if c.get("page") else c["text"].strip()
|
||||
for c in batch
|
||||
)
|
||||
prompt = _MAP_PROMPT.format(no_match=_NO_MATCH, question=question, excerpt=excerpt)
|
||||
raw = await generate_with_retry(self._llm, prompt, temperature=_MAP_TEMPERATURE)
|
||||
answer = raw.strip()
|
||||
if answer and answer.upper().rstrip(".") != _NO_MATCH:
|
||||
return answer
|
||||
return ""
|
||||
|
||||
def _group(self, chunks: list[dict]) -> list[list[dict]]:
|
||||
"""Regroupe les extraits en lots ~`batch_tokens` (compte tiktoken)."""
|
||||
enc = tiktoken.get_encoding("cl100k_base")
|
||||
|
||||
@@ -20,6 +20,9 @@ from app.infrastructure import vector_store
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_RAG_CHUNK_TOKENS = 600
|
||||
# Recouvrement entre extraits consécutifs (~13% de la cible) : une phrase-clé à
|
||||
# cheval sur deux extraits reste retrouvable dans au moins l'un des deux.
|
||||
_RAG_OVERLAP_TOKENS = 80
|
||||
# Un extrait avec quasi aucun texte réel (en-tête/pied de page, fragment de numéro
|
||||
# de page isolé « 249 250 ») ne sert à rien en RAG → on l'écarte. Seuil bas et
|
||||
# conservateur : on ne coupe QUE les fragments quasi-vides, jamais une vraie phrase.
|
||||
@@ -36,10 +39,14 @@ class NotebookRagUseCase:
|
||||
extractor: PdfTextExtractor,
|
||||
embedder: EmbeddingProvider,
|
||||
chunk_target_tokens: int = _RAG_CHUNK_TOKENS,
|
||||
min_score: float = 0.0,
|
||||
) -> None:
|
||||
self._extractor = extractor
|
||||
self._embedder = embedder
|
||||
self._chunk_target_tokens = chunk_target_tokens
|
||||
# Cosinus minimal pour qu'un extrait soit injecté dans le prompt : sous ce
|
||||
# seuil, l'extrait n'a aucun rapport avec la question → bruit. 0 = désactivé.
|
||||
self._min_score = min_score
|
||||
|
||||
async def index_source(self, source_id: str, pdf_bytes: bytes) -> dict:
|
||||
"""Extrait, découpe PAR PAGE (pour garder le n° de page → citations), embed
|
||||
@@ -48,7 +55,9 @@ class NotebookRagUseCase:
|
||||
chunks: list[str] = []
|
||||
pages: list[int] = []
|
||||
for page in doc.pages:
|
||||
for piece in chunk_text(page.text, self._chunk_target_tokens):
|
||||
for piece in chunk_text(
|
||||
page.text, self._chunk_target_tokens, overlap_tokens=_RAG_OVERLAP_TOKENS
|
||||
):
|
||||
if not _has_enough_text(piece):
|
||||
continue # fragment quasi-vide (en-tête/pied/numéro) → ignoré
|
||||
chunks.append(piece)
|
||||
@@ -69,11 +78,17 @@ class NotebookRagUseCase:
|
||||
}
|
||||
|
||||
async def retrieve(self, source_ids: list[str], query: str, top_k: int = 6) -> list[dict]:
|
||||
"""Passages les plus pertinents (toutes sources) pour `query`."""
|
||||
"""Passages les plus pertinents (toutes sources) pour `query`.
|
||||
|
||||
Recherche hybride (cosinus + bonus lexical sur les mots de la question) ;
|
||||
peut renvoyer moins de `top_k` passages si le seuil de pertinence écarte
|
||||
les extraits hors-sujet."""
|
||||
ids = [s for s in source_ids if vector_store.exists(s)]
|
||||
if not ids or not query.strip():
|
||||
return []
|
||||
query_vectors = await self._embedder.embed([query])
|
||||
query_vectors = await self._embedder.embed([query], kind="query")
|
||||
if not query_vectors:
|
||||
return []
|
||||
return vector_store.search(ids, query_vectors[0], top_k)
|
||||
return vector_store.search(
|
||||
ids, query_vectors[0], top_k, query_text=query, min_score=self._min_score
|
||||
)
|
||||
|
||||
66
brain/app/application/query_rewrite.py
Normal file
66
brain/app/application/query_rewrite.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""Réécriture de la question courante en question AUTONOME (chat des ateliers).
|
||||
|
||||
Problème : le retrieval (embedding) et la phase MAP de l'analyse approfondie ne
|
||||
voient que le DERNIER message. Une relance comme « et ses faiblesses ? » ne
|
||||
contient pas le sujet (Strahd) → recherche aveugle. La parade standard
|
||||
(conversational query rewriting) : un appel LLM léger condense la conversation
|
||||
en une question autonome, utilisée UNIQUEMENT pour la recherche — la réponse
|
||||
finale, elle, voit toujours l'historique complet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from app.domain.models import ChatMessage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Nombre de messages récents fournis au réécrivain (assez pour résoudre les
|
||||
# pronoms, pas plus — la latence de cet appel doit rester négligeable).
|
||||
_MAX_HISTORY = 6
|
||||
|
||||
# Garde-fou : une « question » réécrite anormalement longue est suspecte (le
|
||||
# modèle a divagué) → on retombe sur la question brute.
|
||||
_MAX_REWRITE_CHARS = 400
|
||||
|
||||
_REWRITE_PROMPT = """Voici la fin d'une conversation entre un Maître de Jeu et son assistant.
|
||||
Réécris le DERNIER message de l'utilisateur en une question AUTONOME et complète :
|
||||
remplace les pronoms et références implicites (« il », « ses », « ce lieu », « et pour
|
||||
les autres ? ») par ce qu'ils désignent dans la conversation.
|
||||
|
||||
Règles :
|
||||
- Réponds UNIQUEMENT par la question réécrite, sans guillemets ni préfixe.
|
||||
- Conserve la langue et l'intention d'origine. N'ajoute RIEN qui n'est pas demandé.
|
||||
- Si le dernier message est déjà autonome, recopie-le tel quel.
|
||||
|
||||
--- CONVERSATION ---
|
||||
{conversation}
|
||||
--- FIN ---
|
||||
|
||||
Question autonome :"""
|
||||
|
||||
|
||||
async def standalone_question(llm, messages: list[ChatMessage]) -> str:
|
||||
"""Condense `messages` en une question autonome pour la RECHERCHE.
|
||||
|
||||
Best-effort : premier message de la conversation, échec LLM ou réponse
|
||||
suspecte → on renvoie simplement la dernière question brute (comportement
|
||||
historique). `llm` doit exposer `generate()` (duck typing des adapters).
|
||||
"""
|
||||
last_user = next((m.content for m in reversed(messages) if m.role == "user"), "")
|
||||
user_turns = sum(1 for m in messages if m.role == "user" and m.content.strip())
|
||||
if user_turns <= 1 or not last_user.strip():
|
||||
return last_user # pas d'historique à résoudre → appel LLM inutile
|
||||
|
||||
recent = [m for m in messages if m.content.strip()][-_MAX_HISTORY:]
|
||||
conversation = "\n".join(f"{m.role.upper()}: {m.content.strip()}" for m in recent)
|
||||
try:
|
||||
raw = await llm.generate(
|
||||
_REWRITE_PROMPT.format(conversation=conversation), temperature=0.0)
|
||||
except Exception as exc: # noqa: BLE001 — la recherche dégradée vaut mieux que pas de réponse
|
||||
logger.warning("Réécriture de question ignorée (échec LLM) : %s", exc)
|
||||
return last_user
|
||||
rewritten = (raw or "").strip().strip('"').strip()
|
||||
if not rewritten or len(rewritten) > _MAX_REWRITE_CHARS:
|
||||
return last_user
|
||||
return rewritten
|
||||
73
brain/app/application/rerank.py
Normal file
73
brain/app/application/rerank.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""Reranking LLM des passages RAG (chat des ateliers).
|
||||
|
||||
Le cosinus classe par similarité de SURFACE ; sur les questions ambiguës, des
|
||||
passages proches lexicalement mais inutiles passent devant l'extrait qui répond
|
||||
vraiment. Le reranking récupère un POOL élargi (ex. 3× top_k), fait noter la
|
||||
pertinence de chaque extrait par le LLM en UN appel, et garde les top_k mieux
|
||||
notés. Coût : ~1 appel LLM avant le premier token — opt-in via RAG_RERANK.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from app.application.llm_json import load_json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Taille du pool élargi : multiple du top_k demandé, plafonné (le prompt de
|
||||
# notation doit rester raisonnable même avec rag_top_k élevé).
|
||||
POOL_FACTOR = 3
|
||||
POOL_MAX = 24
|
||||
|
||||
# Un extrait long n'a pas besoin d'être noté en entier : tronquer borne le
|
||||
# prompt sans changer le jugement de pertinence.
|
||||
_EXCERPT_CHARS = 600
|
||||
|
||||
_RERANK_PROMPT = """Tu évalues la PERTINENCE d'extraits d'un document pour répondre à une question.
|
||||
Note chaque extrait de 0 (sans rapport) à 10 (répond directement), indépendamment des autres.
|
||||
|
||||
QUESTION : {question}
|
||||
|
||||
{passages}
|
||||
|
||||
Réponds UNIQUEMENT par un objet JSON : {{"scores": [note_extrait_1, note_extrait_2, ...]}}
|
||||
Le tableau doit contenir EXACTEMENT {count} notes, dans l'ordre des extraits."""
|
||||
|
||||
|
||||
def pool_size(top_k: int) -> int:
|
||||
"""Taille du pool à récupérer avant reranking."""
|
||||
return min(max(top_k * POOL_FACTOR, top_k), POOL_MAX)
|
||||
|
||||
|
||||
async def rerank(llm, question: str, passages: list[dict], top_k: int) -> list[dict]:
|
||||
"""Renvoie les `top_k` passages les mieux notés par le LLM (tri stable :
|
||||
à note égale, l'ordre cosinus d'origine est préservé).
|
||||
|
||||
BEST-EFFORT : échec LLM, JSON invalide ou nombre de notes incohérent →
|
||||
on renvoie simplement les `top_k` premiers du classement cosinus.
|
||||
"""
|
||||
if len(passages) <= top_k:
|
||||
return passages
|
||||
numbered = "\n\n".join(
|
||||
f"--- EXTRAIT {i + 1} ---\n{(p.get('text') or '')[:_EXCERPT_CHARS]}"
|
||||
for i, p in enumerate(passages)
|
||||
)
|
||||
prompt = _RERANK_PROMPT.format(
|
||||
question=question, passages=numbered, count=len(passages))
|
||||
try:
|
||||
raw = await llm.generate(prompt, temperature=0.0)
|
||||
except Exception as exc: # noqa: BLE001 — un chat dégradé vaut mieux que pas de chat
|
||||
logger.warning("Reranking ignoré (échec LLM) : %s", exc)
|
||||
return passages[:top_k]
|
||||
parsed, _ = load_json_object(raw)
|
||||
scores = parsed.get("scores") if isinstance(parsed, dict) else None
|
||||
if not isinstance(scores, list) or len(scores) != len(passages):
|
||||
logger.warning("Reranking ignoré (notes inexploitables).")
|
||||
return passages[:top_k]
|
||||
try:
|
||||
scored = [(float(s), i) for i, s in enumerate(scores)]
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("Reranking ignoré (notes non numériques).")
|
||||
return passages[:top_k]
|
||||
order = sorted(range(len(passages)), key=lambda i: (-scored[i][0], i))
|
||||
return [passages[i] for i in order[:top_k]]
|
||||
@@ -83,6 +83,32 @@ class Settings(BaseSettings):
|
||||
# mais prompt plus long. 8 par défaut (montable jusqu'à ~20 sur grand contexte).
|
||||
rag_top_k: int = 8
|
||||
|
||||
# Analyse approfondie : pré-filtrage des lots via un index de résumés
|
||||
# (construit une fois par source, cache disque). Les questions ciblées ne
|
||||
# relisent que les lots plausiblement pertinents (3-5x moins d'appels) ;
|
||||
# False = relire TOUT le document à chaque question (exhaustivité maximale).
|
||||
deep_summary_filter: bool = True
|
||||
|
||||
# Reranking LLM du chat atelier : recupere un pool elargi (3x top_k, max 24)
|
||||
# puis fait NOTER la pertinence de chaque extrait par le LLM avant d'injecter
|
||||
# les top_k meilleurs. Meilleure precision sur les questions ambigues, MAIS
|
||||
# +1 appel LLM avant le premier token (quelques secondes sur un petit modele
|
||||
# local). Desactive par defaut ; recommande avec un provider cloud rapide.
|
||||
rag_rerank: bool = False
|
||||
|
||||
# Cosinus minimal pour qu'un extrait soit injecté dans le prompt du chat
|
||||
# atelier : en dessous, l'extrait n'a aucun rapport avec la question → mieux
|
||||
# vaut moins d'extraits que du bruit. Défaut conservateur (0.30) : les paires
|
||||
# pertinentes scorent typiquement 0.6+ avec nomic-embed-text/mistral-embed,
|
||||
# les hors-sujet 0.2-0.4. Montable à ~0.4 si trop de bruit, 0 = désactivé.
|
||||
rag_min_score: float = 0.30
|
||||
|
||||
# Nombre d'appels LLM MAP menes EN PARALLELE (import de campagne, analyse
|
||||
# approfondie). 3 = bon defaut cloud (divise le temps d'un gros livre par ~3).
|
||||
# Ollama local sequence les requetes de toute facon (pas de gain, pas de mal).
|
||||
# Baisser a 1 si un provider gratuit rate-limite agressivement.
|
||||
llm_map_concurrency: int = 3
|
||||
|
||||
# Taille cible d'un morceau (en tokens) pour l'import de PDF (regles/campagne).
|
||||
# Plus c'est gros, moins il y a de morceaux => moins de fragmentation et un
|
||||
# import plus rapide, MAIS il faut que ca tienne dans la fenetre du modele.
|
||||
|
||||
@@ -320,11 +320,26 @@ class ExtractedPage:
|
||||
used_ocr: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TocEntry:
|
||||
"""Une entrée de la table des matières (bookmarks/outline) du PDF.
|
||||
|
||||
`level` : profondeur 1-based (1 = chapitre, 2 = section…). `page` : 1-based.
|
||||
"""
|
||||
|
||||
level: int
|
||||
title: str
|
||||
page: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedDocument:
|
||||
"""Résultat brut de l'extraction d'un PDF : une entrée par page."""
|
||||
|
||||
pages: list[ExtractedPage]
|
||||
# Table des matières (bookmarks PDF). Vide si le PDF n'en a pas — fréquent
|
||||
# pour les scans ; les livres born-digital en ont presque toujours une.
|
||||
toc: list[TocEntry] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
@@ -409,6 +424,18 @@ class ArcProposal:
|
||||
chapters: list[ChapterProposal] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NpcImportProposal:
|
||||
"""PNJ/créature notable détecté à l'import d'un PDF de campagne.
|
||||
|
||||
PNJ NOMMÉS et créatures uniques (boss) — pas les monstres génériques.
|
||||
`description` = courte fiche (rôle, apparence, motivations, où on le croise).
|
||||
"""
|
||||
|
||||
name: str
|
||||
description: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CampaignImportResult:
|
||||
"""Proposition d'arborescence narrative extraite d'un PDF de campagne.
|
||||
@@ -420,6 +447,9 @@ class CampaignImportResult:
|
||||
arcs: list[ArcProposal]
|
||||
page_count: int
|
||||
ocr_page_count: int
|
||||
# PNJ/créatures notables détectés au fil des morceaux (proposition, à cocher
|
||||
# dans l'écran de revue avant création).
|
||||
npcs: list[NpcImportProposal] = field(default_factory=list)
|
||||
|
||||
def counts(self) -> tuple[int, int, int]:
|
||||
"""(nb arcs, nb chapitres, nb scènes) — pour le diagnostic / la progression."""
|
||||
|
||||
@@ -28,7 +28,8 @@ class MistralEmbeddingProvider:
|
||||
self._model = settings.mistral_embedding_model
|
||||
self._timeout = settings.llm_timeout_seconds
|
||||
|
||||
async def embed(self, texts: list[str]) -> list[list[float]]:
|
||||
async def embed(self, texts: list[str], kind: str = "document") -> list[list[float]]:
|
||||
# `kind` ignoré : mistral-embed n'utilise pas de préfixe de tâche.
|
||||
if not texts:
|
||||
return []
|
||||
out: list[list[float]] = []
|
||||
|
||||
@@ -11,6 +11,14 @@ from app.application.embeddings import EmbeddingError
|
||||
from app.core.config import Settings
|
||||
|
||||
|
||||
# Préfixes de tâche des modèles nomic-embed : le modèle est ENTRAÎNÉ avec
|
||||
# (search_document pour le corpus, search_query pour la question). Sans eux,
|
||||
# la pertinence du retrieval est mesurablement dégradée. Ne s'applique qu'aux
|
||||
# modèles nomic — les autres (mxbai, bge…) ont leurs propres conventions ou
|
||||
# aucune ; on reste neutre pour eux.
|
||||
_NOMIC_PREFIXES = {"document": "search_document: ", "query": "search_query: "}
|
||||
|
||||
|
||||
class OllamaEmbeddingProvider:
|
||||
"""Implémente EmbeddingProvider via Ollama /api/embed (batch)."""
|
||||
|
||||
@@ -19,11 +27,22 @@ class OllamaEmbeddingProvider:
|
||||
self._model = settings.ollama_embedding_model
|
||||
self._timeout = settings.llm_timeout_seconds
|
||||
|
||||
async def embed(self, texts: list[str]) -> list[list[float]]:
|
||||
def _prepare(self, texts: list[str], kind: str) -> list[str]:
|
||||
"""Applique le préfixe de tâche si le modèle est de la famille nomic-embed.
|
||||
|
||||
NB : les sources indexées AVANT l'introduction des préfixes doivent être
|
||||
ré-uploadées pour que documents et questions vivent dans le même espace.
|
||||
"""
|
||||
if "nomic-embed" not in self._model:
|
||||
return texts
|
||||
prefix = _NOMIC_PREFIXES.get(kind, _NOMIC_PREFIXES["document"])
|
||||
return [prefix + t for t in texts]
|
||||
|
||||
async def embed(self, texts: list[str], kind: str = "document") -> list[list[float]]:
|
||||
if not texts:
|
||||
return []
|
||||
url = f"{self._base_url}/api/embed"
|
||||
payload = {"model": self._model, "input": texts}
|
||||
payload = {"model": self._model, "input": self._prepare(texts, kind)}
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
try:
|
||||
response = await client.post(url, json=payload)
|
||||
|
||||
51
brain/app/infrastructure/ollama_model_installer.py
Normal file
51
brain/app/infrastructure/ollama_model_installer.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""Auto-installation du modèle d'embeddings Ollama au démarrage du Brain.
|
||||
|
||||
Adapter d'infrastructure : parle directement à l'API HTTP d'Ollama. Best-effort
|
||||
(Ollama peut être absent / la connexion limitée) — n'empêche jamais le démarrage.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def ensure_ollama_embedding_model(base_url: str, model: str) -> None:
|
||||
"""Télécharge `model` sur le serveur Ollama s'il n'y est pas déjà.
|
||||
|
||||
Attend qu'Ollama soit joignable (ordre de démarrage des conteneurs), puis
|
||||
vérifie la présence du modèle avant de le tirer.
|
||||
"""
|
||||
for attempt in range(10):
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
tags = await client.get(f"{base_url}/api/tags")
|
||||
tags.raise_for_status()
|
||||
names = [m.get("name", "") for m in tags.json().get("models", [])]
|
||||
if any(n == model or n.startswith(model + ":") for n in names):
|
||||
logger.info("Modèle d'embedding '%s' déjà présent.", model)
|
||||
return
|
||||
break # Ollama joignable, modèle absent → on tire (ci-dessous)
|
||||
except httpx.HTTPError:
|
||||
await asyncio.sleep(min(5 * (attempt + 1), 30))
|
||||
else:
|
||||
logger.warning(
|
||||
"Ollama injoignable au démarrage — modèle d'embedding '%s' non auto-installé "
|
||||
"(il sera tirable manuellement : ollama pull %s).", model, model)
|
||||
return
|
||||
|
||||
logger.info("Téléchargement automatique du modèle d'embedding '%s'…", model)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=None) as client:
|
||||
async with client.stream("POST", f"{base_url}/api/pull", json={"name": model}) as resp:
|
||||
resp.raise_for_status()
|
||||
async for _line in resp.aiter_lines():
|
||||
pass # on draine la progression NDJSON jusqu'à la fin
|
||||
logger.info("Modèle d'embedding '%s' prêt.", model)
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning(
|
||||
"Auto-installation du modèle d'embedding '%s' échouée : %s "
|
||||
"(tirage manuel possible : ollama pull %s).", model, exc, model)
|
||||
@@ -22,7 +22,7 @@ import pymupdf as fitz # PyMuPDF — on importe par le nom canonique `pymupdf`
|
||||
# (et NON `import fitz`) pour éviter la collision avec le faux paquet PyPI "fitz"
|
||||
# qui échoue sur `from frontend import *`.
|
||||
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage
|
||||
from app.domain.models import ExtractedDocument, ExtractedPage, TocEntry
|
||||
from app.domain.ports import PdfExtractionError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -72,7 +72,18 @@ class PyMuPdfTextExtractor:
|
||||
raise PdfExtractionError(f"PDF illisible ou corrompu : {exc}") from exc
|
||||
|
||||
pages: list[ExtractedPage] = []
|
||||
toc: list[TocEntry] = []
|
||||
try:
|
||||
# Bookmarks/outline du PDF : structure officielle du livre, gratuite
|
||||
# (pas d'appel LLM). Sert de squelette de référence aux imports.
|
||||
try:
|
||||
for level, title, page_no in doc.get_toc(simple=True) or []:
|
||||
title = str(title or "").strip()
|
||||
if title:
|
||||
toc.append(TocEntry(level=int(level), title=title, page=int(page_no)))
|
||||
except Exception as exc: # noqa: BLE001 — TOC best-effort, jamais bloquante
|
||||
logger.warning("Lecture de la table des matières impossible : %s", exc)
|
||||
|
||||
for index, page in enumerate(doc):
|
||||
text = (page.get_text() or "").strip()
|
||||
used_ocr = False
|
||||
@@ -85,7 +96,7 @@ class PyMuPdfTextExtractor:
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
return ExtractedDocument(pages=pages)
|
||||
return ExtractedDocument(pages=pages, toc=toc)
|
||||
|
||||
@staticmethod
|
||||
def _ocr_page(page: "fitz.Page") -> str:
|
||||
|
||||
@@ -5,6 +5,12 @@ Chaque SOURCE est persistée en un fichier JSON sur le volume `data/` du Brain :
|
||||
|
||||
À l'échelle d'un livre (quelques centaines d'extraits), une recherche cosinus en
|
||||
Python pur est instantanée — inutile d'ajouter numpy/pgvector/une base vectorielle.
|
||||
Les fichiers sont mis en cache mémoire (invalidation par mtime) : le coûteux est
|
||||
le re-parse JSON des vecteurs, pas le cosinus.
|
||||
|
||||
Recherche HYBRIDE : score = cosinus + bonus lexical (mots significatifs de la
|
||||
question présents dans l'extrait). Sur du JdR, les requêtes sont souvent des noms
|
||||
propres exacts (« Strahd », « Barovia ») où le lexical bat l'embedding.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,6 +22,27 @@ from pathlib import Path
|
||||
_STORE_DIR = Path("data/notebooks")
|
||||
_SAFE_ID = re.compile(r"[^A-Za-z0-9_-]")
|
||||
|
||||
# Cache mémoire {source_id: (mtime_ns, chunks)} — évite de relire/re-parser le JSON
|
||||
# (vecteurs = gros) à chaque question. Invalidé si le fichier change (mtime).
|
||||
_CACHE: dict[str, tuple[int, list[dict]]] = {}
|
||||
_CACHE_MAX_SOURCES = 32 # garde-fou mémoire : ~10 Mo par gros livre en cache
|
||||
|
||||
# Poids du bonus lexical dans le score hybride. Le cosinus reste dominant ; le
|
||||
# bonus (0..0.15) sert surtout à départager / repêcher les correspondances exactes.
|
||||
_LEX_WEIGHT = 0.15
|
||||
_WORD_RE = re.compile(r"[a-z0-9àâäçéèêëîïôöùûüœæ]{3,}")
|
||||
# Mots-outils FR/EN fréquents (≥3 lettres) : sans eux, le bonus lexical serait
|
||||
# dominé par « les », « pour », « the »… au lieu des termes porteurs de sens.
|
||||
_STOPWORDS = frozenset({
|
||||
"les", "des", "une", "est", "son", "ses", "aux", "par", "pour", "dans",
|
||||
"sur", "avec", "qui", "que", "quoi", "dont", "mais", "comme", "plus",
|
||||
"pas", "tout", "tous", "toute", "toutes", "ils", "elles", "leur", "leurs",
|
||||
"nous", "vous", "cette", "ces", "cet", "ont", "sont", "fait", "etre",
|
||||
"être", "avoir", "peut", "quel", "quelle", "quels", "quelles", "ainsi",
|
||||
"the", "and", "for", "with", "this", "that", "are", "was", "has", "have",
|
||||
"not", "you", "his", "her", "its", "they", "them", "from", "what", "which",
|
||||
})
|
||||
|
||||
|
||||
def _path(source_id: str) -> Path:
|
||||
safe = _SAFE_ID.sub("_", str(source_id))
|
||||
@@ -42,6 +69,7 @@ def save(
|
||||
items.append(item)
|
||||
payload = {"dim": len(vectors[0]) if vectors else 0, "chunks": items}
|
||||
_path(source_id).write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
_CACHE.pop(source_id, None) # le mtime suffirait, mais soyons explicites
|
||||
return len(chunks)
|
||||
|
||||
|
||||
@@ -50,18 +78,65 @@ def exists(source_id: str) -> bool:
|
||||
|
||||
|
||||
def delete(source_id: str) -> None:
|
||||
_CACHE.pop(source_id, None)
|
||||
_path(source_id).unlink(missing_ok=True)
|
||||
_summaries_path(source_id).unlink(missing_ok=True)
|
||||
|
||||
|
||||
# --- Index de résumés (analyse approfondie) ----------------------------------
|
||||
# Cache disque des résumés PAR LOT d'une source : construit paresseusement à la
|
||||
# première analyse approfondie, réutilisé ensuite pour ne relire que les lots
|
||||
# pertinents. Invalidé avec la source (delete) et si batch_tokens change.
|
||||
|
||||
|
||||
def _summaries_path(source_id: str) -> Path:
|
||||
safe = _SAFE_ID.sub("_", str(source_id))
|
||||
return _STORE_DIR / f"{safe}.summaries.json"
|
||||
|
||||
|
||||
def save_summaries(source_id: str, batch_tokens: int, entries: list[dict]) -> None:
|
||||
"""Persiste les résumés de lots ({"summary": str, "vector": [...]})."""
|
||||
_STORE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
payload = {"batch_tokens": int(batch_tokens), "entries": entries}
|
||||
_summaries_path(source_id).write_text(
|
||||
json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def load_summaries(source_id: str, batch_tokens: int) -> list[dict] | None:
|
||||
"""Résumés de lots d'une source, ou None si absents / construits avec une
|
||||
autre taille de lot (le découpage ne correspondrait plus)."""
|
||||
p = _summaries_path(source_id)
|
||||
if not p.exists():
|
||||
return None
|
||||
try:
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
if not isinstance(data, dict) or data.get("batch_tokens") != int(batch_tokens):
|
||||
return None
|
||||
entries = data.get("entries")
|
||||
return entries if isinstance(entries, list) else None
|
||||
|
||||
|
||||
def _load(source_id: str) -> list[dict]:
|
||||
p = _path(source_id)
|
||||
if not p.exists():
|
||||
try:
|
||||
mtime = p.stat().st_mtime_ns
|
||||
except OSError:
|
||||
_CACHE.pop(source_id, None)
|
||||
return []
|
||||
cached = _CACHE.get(source_id)
|
||||
if cached is not None and cached[0] == mtime:
|
||||
return cached[1]
|
||||
try:
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return []
|
||||
return data.get("chunks", []) if isinstance(data, dict) else []
|
||||
chunks = data.get("chunks", []) if isinstance(data, dict) else []
|
||||
if len(_CACHE) >= _CACHE_MAX_SOURCES:
|
||||
_CACHE.pop(next(iter(_CACHE))) # éviction FIFO simple
|
||||
_CACHE[source_id] = (mtime, chunks)
|
||||
return chunks
|
||||
|
||||
|
||||
def all_chunks(source_id: str) -> list[dict]:
|
||||
@@ -85,20 +160,54 @@ def _cosine(a: list[float], b: list[float]) -> float:
|
||||
return dot / (math.sqrt(na) * math.sqrt(nb))
|
||||
|
||||
|
||||
def _significant_words(text: str) -> frozenset[str]:
|
||||
"""Mots porteurs de sens d'un texte (minuscules, ≥3 lettres, hors mots-outils)."""
|
||||
return frozenset(w for w in _WORD_RE.findall(text.lower()) if w not in _STOPWORDS)
|
||||
|
||||
|
||||
def _chunk_words(chunk: dict) -> frozenset[str]:
|
||||
"""Mots significatifs d'un extrait, mémoïsés sur le dict caché (calculés à la
|
||||
1ère recherche, réutilisés tant que la source reste en cache)."""
|
||||
words = chunk.get("_words")
|
||||
if words is None:
|
||||
words = _significant_words(chunk.get("text", ""))
|
||||
chunk["_words"] = words
|
||||
return words
|
||||
|
||||
|
||||
# Alias public du cosinus (réutilisé par l'index de résumés de l'analyse
|
||||
# approfondie — même métrique que la recherche).
|
||||
cosine_similarity = _cosine
|
||||
|
||||
|
||||
def search(
|
||||
source_ids: list[str],
|
||||
query_vector: list[float],
|
||||
top_k: int = 6,
|
||||
query_text: str = "",
|
||||
min_score: float = 0.0,
|
||||
) -> list[dict]:
|
||||
"""Renvoie les `top_k` extraits les plus proches, toutes sources confondues.
|
||||
|
||||
Chaque résultat : {"text": str, "score": float, "source_id": str}.
|
||||
Score HYBRIDE : cosinus + `_LEX_WEIGHT` × (part des mots significatifs de
|
||||
`query_text` présents dans l'extrait). Les extraits dont le cosinus est sous
|
||||
`min_score` sont écartés (peut donc renvoyer MOINS de `top_k` résultats —
|
||||
mieux vaut aucun extrait que du bruit injecté dans le prompt).
|
||||
|
||||
Chaque résultat : {"text": str, "score": float, "source_id": str, "page": int|None}.
|
||||
"""
|
||||
query_words = _significant_words(query_text) if query_text else frozenset()
|
||||
scored: list[dict] = []
|
||||
for sid in source_ids:
|
||||
for chunk in _load(sid):
|
||||
vector = chunk.get("vector") or []
|
||||
score = _cosine(query_vector, vector)
|
||||
cos = _cosine(query_vector, vector)
|
||||
if cos < min_score:
|
||||
continue
|
||||
score = cos
|
||||
if query_words:
|
||||
overlap = len(query_words & _chunk_words(chunk)) / len(query_words)
|
||||
score += _LEX_WEIGHT * overlap
|
||||
scored.append({
|
||||
"text": chunk.get("text", ""),
|
||||
"score": score,
|
||||
|
||||
1709
brain/app/main.py
1709
brain/app/main.py
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,8 @@
|
||||
fastapi==0.115.*
|
||||
fastapi==0.136.*
|
||||
# Pin EXPLICITE : fastapi n'exige que starlette>=0.46.0 — sans ce pin, un
|
||||
# environnement existant peut garder une starlette vulnérable.
|
||||
# >= 0.49.1 : corrige CVE-2025-54121 et CVE-2025-62727.
|
||||
starlette>=0.49.1,<1.0
|
||||
uvicorn[standard]==0.32.*
|
||||
httpx==0.27.*
|
||||
pydantic-settings==2.6.*
|
||||
@@ -20,4 +24,6 @@ tiktoken==0.8.*
|
||||
# (le binaire tesseract-ocr est installe dans le Dockerfile, langues fra+eng)
|
||||
pymupdf==1.24.*
|
||||
pytesseract==0.3.*
|
||||
Pillow==11.*
|
||||
# 12.2+ : corrige 6 CVE de parsing d'images (surface critique : pages de PDF
|
||||
# uploadés par l'utilisateur rasterisées puis passées à l'OCR).
|
||||
Pillow==12.2.*
|
||||
|
||||
84
brain/scripts/sanity_rag_check.py
Normal file
84
brain/scripts/sanity_rag_check.py
Normal file
@@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Sanity check temporaire : overlap du chunking + recherche hybride du vector store."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from app.application.chunking import chunk_text
|
||||
|
||||
# --- 1. Chunking avec overlap ---
|
||||
paras = [f"Paragraphe {i} : " + ("lorem ipsum dolor sit amet " * 8) for i in range(12)]
|
||||
text = "\n\n".join(paras)
|
||||
|
||||
no_overlap = chunk_text(text, target_tokens=200)
|
||||
with_overlap = chunk_text(text, target_tokens=200, overlap_tokens=40)
|
||||
|
||||
assert len(with_overlap) >= len(no_overlap), "l'overlap ne doit pas réduire le nb de chunks"
|
||||
# Chaque chunk (sauf le 1er) doit commencer par la fin du précédent
|
||||
overlapped = 0
|
||||
for prev, cur in zip(with_overlap, with_overlap[1:]):
|
||||
first_para = cur.split("\n\n")[0]
|
||||
if first_para in prev:
|
||||
overlapped += 1
|
||||
assert overlapped >= len(with_overlap) - 2, f"overlap absent: {overlapped}/{len(with_overlap)-1}"
|
||||
# Pas de chunk composé uniquement de l'overlap (dernier chunk dupliqué)
|
||||
assert with_overlap[-1] != with_overlap[-2], "dernier chunk = pur overlap (dupliqué)"
|
||||
# overlap_tokens=0 → comportement identique à l'ancien
|
||||
assert no_overlap == chunk_text(text, target_tokens=200, overlap_tokens=0)
|
||||
print(f"[OK] chunking : {len(no_overlap)} chunks sans overlap, {len(with_overlap)} avec ({overlapped} recouvrements)")
|
||||
|
||||
# --- Paragraphe géant ---
|
||||
giant = "mot " * 2000
|
||||
sub = chunk_text(giant, target_tokens=300, overlap_tokens=50)
|
||||
assert len(sub) > 1
|
||||
print(f"[OK] paragraphe géant coupé en {len(sub)} sous-blocs")
|
||||
|
||||
# --- 2. Vector store : hybride + seuil + cache ---
|
||||
import tempfile, os
|
||||
from app.infrastructure import vector_store
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
vector_store._STORE_DIR = Path(tmp)
|
||||
chunks = [
|
||||
"Strahd von Zarovich règne sur la sombre vallée de Barovia depuis son château.",
|
||||
"Les règles de combat utilisent un d20 plus le modificateur de caractéristique.",
|
||||
"La taverne du village sert un ragoût de navets aux voyageurs fatigués.",
|
||||
]
|
||||
# Vecteurs factices : chunk 0 et 1 proches de la query, chunk 2 orthogonal
|
||||
vectors = [[1.0, 0.1, 0.0], [0.9, 0.4, 0.1], [0.0, 0.0, 1.0]]
|
||||
vector_store.save("src1", chunks, vectors, pages=[10, 20, 30])
|
||||
|
||||
q = [1.0, 0.2, 0.0]
|
||||
# Sans seuil ni texte : 3 résultats, ordre cosinus
|
||||
r = vector_store.search(["src1"], q, top_k=10)
|
||||
assert len(r) == 3 and r[0]["page"] == 10
|
||||
|
||||
# Avec seuil : le chunk orthogonal (cos~0) est écarté
|
||||
r = vector_store.search(["src1"], q, top_k=10, min_score=0.30)
|
||||
assert len(r) == 2, f"seuil non appliqué: {len(r)}"
|
||||
print(f"[OK] seuil : 2/3 extraits gardés (orthogonal écarté)")
|
||||
|
||||
# Bonus lexical : la query mentionne « Strahd Barovia » → chunk 0 doit dominer
|
||||
r = vector_store.search(["src1"], q, top_k=10, query_text="Parle-moi de Strahd et de Barovia", min_score=0.30)
|
||||
assert r[0]["text"].startswith("Strahd"), r[0]["text"]
|
||||
assert r[0]["score"] > vector_store._cosine(q, vectors[0]), "bonus lexical absent"
|
||||
print(f"[OK] hybride : bonus lexical appliqué (score={r[0]['score']:.3f})")
|
||||
|
||||
# Le set "_words" mémoïsé ne doit PAS fuiter dans les résultats
|
||||
assert all("_words" not in res for res in r)
|
||||
|
||||
# Cache : 2e recherche sert depuis la mémoire (même objet liste)
|
||||
c1 = vector_store._load("src1")
|
||||
c2 = vector_store._load("src1")
|
||||
assert c1 is c2, "cache mtime inopérant"
|
||||
# save() invalide le cache
|
||||
vector_store.save("src1", chunks[:1], vectors[:1], pages=[10])
|
||||
c3 = vector_store._load("src1")
|
||||
assert len(c3) == 1, "cache non invalidé après save"
|
||||
# delete() purge cache + fichier
|
||||
vector_store.delete("src1")
|
||||
assert vector_store._load("src1") == []
|
||||
print("[OK] cache mémoire : hit, invalidation save, purge delete")
|
||||
|
||||
print("\nTous les sanity checks passent.")
|
||||
41
core/pom.xml
41
core/pom.xml
@@ -8,18 +8,22 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.2.12</version>
|
||||
<version>3.5.14</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.loremind</groupId>
|
||||
<artifactId>loremind-core</artifactId>
|
||||
<version>0.11.2-beta</version>
|
||||
<version>0.12.0-beta</version>
|
||||
<name>LoreMind Core</name>
|
||||
<description>Backend Core - Architecture Hexagonale</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<!-- Override de la transitive minio → commons-compress → commons-lang3 3.17.
|
||||
>= 3.18 : corrige CVE-2025-48924 (recursion infinie ClassUtils.getClass).
|
||||
Propriete reconnue par le BOM Spring Boot → s'applique partout. -->
|
||||
<commons-lang3.version>3.20.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -77,33 +81,52 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- MinIO — client S3-compatible pour le stockage d'images (Shared Kernel images). -->
|
||||
<!-- MinIO — client S3-compatible pour le stockage d'images (Shared Kernel images).
|
||||
8.6.x = derniere ligne 8.x (la 9.x change l'API) ; transitives a jour. -->
|
||||
<dependency>
|
||||
<groupId>io.minio</groupId>
|
||||
<artifactId>minio</artifactId>
|
||||
<version>8.5.11</version>
|
||||
<version>8.6.0</version>
|
||||
<exclusions>
|
||||
<!-- OkHttp 5 : l'artefact `okhttp` est un alias multiplateforme dont la
|
||||
resolution vers les classes JVM passe par les metadonnees Gradle —
|
||||
que Maven ignore. On exclut l'alias et on declare `okhttp-jvm`
|
||||
(les vraies classes) explicitement ci-dessous. -->
|
||||
<exclusion>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp-jvm</artifactId>
|
||||
<version>5.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Nimbus JOSE+JWT — verification des JWT Ed25519 (EdDSA) emis par le relais
|
||||
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle. -->
|
||||
Patreon. Supporte nativement les cles Ed25519 via BouncyCastle.
|
||||
>= 10.0.2 : corrige CVE-2025-53864 (DoS par JSON profondement imbrique
|
||||
dans le claim set — surface critique : JWT colle par l'utilisateur). -->
|
||||
<dependency>
|
||||
<groupId>com.nimbusds</groupId>
|
||||
<artifactId>nimbus-jose-jwt</artifactId>
|
||||
<version>9.40</version>
|
||||
<version>10.9.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
<version>1.84</version>
|
||||
</dependency>
|
||||
<!-- Google Tink : runtime requis par com.nimbusds.jose.crypto.Ed25519Verifier
|
||||
(depuis Nimbus 9.x, la verification EdDSA delegue a Tink.subtle.Ed25519Verify).
|
||||
Tink n'est PAS une dependance transitive de nimbus-jose-jwt → il faut
|
||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify(). -->
|
||||
l'ajouter explicitement, sinon NoClassDefFoundError au premier verify().
|
||||
>= 1.15 : embarque un protobuf-java corrige (CVE-2024-7254). -->
|
||||
<dependency>
|
||||
<groupId>com.google.crypto.tink</groupId>
|
||||
<artifactId>tink</artifactId>
|
||||
<version>1.14.1</version>
|
||||
<version>1.21.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.ArcProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.ChapterProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.NpcProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.RoomProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.SceneProposal;
|
||||
import com.loremind.domain.campaigncontext.Chapter;
|
||||
@@ -37,22 +38,26 @@ public class CampaignImportService {
|
||||
private final ArcService arcService;
|
||||
private final ChapterService chapterService;
|
||||
private final SceneService sceneService;
|
||||
private final NpcService npcService;
|
||||
|
||||
public CampaignImportService(
|
||||
CampaignPdfImporter campaignPdfImporter,
|
||||
CampaignService campaignService,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService) {
|
||||
SceneService sceneService,
|
||||
NpcService npcService) {
|
||||
this.campaignPdfImporter = campaignPdfImporter;
|
||||
this.campaignService = campaignService;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
this.npcService = npcService;
|
||||
}
|
||||
|
||||
/** Résumé de ce qui a été créé par {@link #applyStructure}. */
|
||||
public record ApplyResult(int arcsCreated, int chaptersCreated, int scenesCreated) {}
|
||||
public record ApplyResult(
|
||||
int arcsCreated, int chaptersCreated, int scenesCreated, int npcsCreated) {}
|
||||
|
||||
/** Génère la proposition d'arbre (streamée). Ne persiste rien. */
|
||||
public void importStructureStreaming(
|
||||
@@ -130,7 +135,36 @@ public class CampaignImportService {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ApplyResult(arcsCreated, chaptersCreated, scenesCreated);
|
||||
|
||||
int npcsCreated = createNpcs(campaignId, proposal.npcs());
|
||||
return new ApplyResult(arcsCreated, chaptersCreated, scenesCreated, npcsCreated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée les PNJ proposés (description → values["Description"], même convention
|
||||
* que les cartes d'action des ateliers). Les PNJ portant un nom déjà présent
|
||||
* dans la campagne sont ignorés (ré-import sans doublon).
|
||||
*/
|
||||
private int createNpcs(String campaignId, List<NpcProposal> proposals) {
|
||||
if (proposals == null || proposals.isEmpty()) return 0;
|
||||
java.util.Set<String> existingNames = new java.util.HashSet<>();
|
||||
for (var npc : npcService.getNpcsByCampaignId(campaignId)) {
|
||||
existingNames.add(npc.getName().trim().toLowerCase());
|
||||
}
|
||||
int created = 0;
|
||||
for (NpcProposal p : proposals) {
|
||||
if (isBlank(p.name()) || !existingNames.add(p.name().trim().toLowerCase())) {
|
||||
continue;
|
||||
}
|
||||
npcService.createNpc(new NpcService.NpcData(
|
||||
p.name().trim(), null, null,
|
||||
isBlank(p.description())
|
||||
? java.util.Map.of()
|
||||
: java.util.Map.of("Description", p.description().trim()),
|
||||
null, null, campaignId, null, null));
|
||||
created++;
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
/** Compte les nœuds déjà présents (existingId non vide) d'une liste. */
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogRepository;
|
||||
import com.loremind.domain.gamesystemcontext.ports.GameSystemRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Service d'application des catalogues d'objets (campagne) : CRUD + génération IA.
|
||||
*/
|
||||
@Service
|
||||
public class ItemCatalogService {
|
||||
|
||||
private final ItemCatalogRepository repository;
|
||||
private final ItemCatalogGenerator generator;
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final GameSystemRepository gameSystemRepository;
|
||||
|
||||
public ItemCatalogService(
|
||||
ItemCatalogRepository repository,
|
||||
ItemCatalogGenerator generator,
|
||||
CampaignRepository campaignRepository,
|
||||
GameSystemRepository gameSystemRepository) {
|
||||
this.repository = repository;
|
||||
this.generator = generator;
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.gameSystemRepository = gameSystemRepository;
|
||||
}
|
||||
|
||||
public record CatalogData(
|
||||
String name,
|
||||
String description,
|
||||
String icon,
|
||||
List<CatalogItem> items,
|
||||
String campaignId,
|
||||
Integer order
|
||||
) {}
|
||||
|
||||
public ItemCatalog createCatalog(CatalogData data) {
|
||||
int order = data.order() != null ? data.order() : nextOrderFor(data.campaignId());
|
||||
ItemCatalog catalog = ItemCatalog.builder()
|
||||
.name(data.name())
|
||||
.description(data.description())
|
||||
.icon(data.icon())
|
||||
.items(copyItems(data.items()))
|
||||
.campaignId(data.campaignId())
|
||||
.order(order)
|
||||
.build();
|
||||
return repository.save(catalog);
|
||||
}
|
||||
|
||||
public Optional<ItemCatalog> getCatalogById(String id) {
|
||||
return repository.findById(id);
|
||||
}
|
||||
|
||||
public List<ItemCatalog> getCatalogsByCampaignId(String campaignId) {
|
||||
return repository.findByCampaignId(campaignId);
|
||||
}
|
||||
|
||||
public ItemCatalog updateCatalog(String id, CatalogData data) {
|
||||
ItemCatalog existing = repository.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Catalogue d'objets introuvable: " + id));
|
||||
existing.setName(data.name());
|
||||
existing.setDescription(data.description());
|
||||
existing.setIcon(data.icon());
|
||||
existing.setItems(copyItems(data.items()));
|
||||
if (data.order() != null) {
|
||||
existing.setOrder(data.order());
|
||||
}
|
||||
return repository.save(existing);
|
||||
}
|
||||
|
||||
public void deleteCatalog(String id) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
|
||||
/** Génère une PROPOSITION de catalogue (non persistée) via l'IA, contextualisée campagne. */
|
||||
public ItemCatalog generateProposal(String campaignId, String description) {
|
||||
ItemCatalogGenerator.GeneratedCatalog g = generator.generate(description, buildContext(campaignId));
|
||||
return ItemCatalog.builder()
|
||||
.name(g.name())
|
||||
.description(g.description())
|
||||
.campaignId(campaignId)
|
||||
.items(g.items() != null ? new ArrayList<>(g.items()) : new ArrayList<>())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static List<CatalogItem> copyItems(List<CatalogItem> items) {
|
||||
return items != null ? new ArrayList<>(items) : new ArrayList<>();
|
||||
}
|
||||
|
||||
private String buildContext(String campaignId) {
|
||||
if (campaignId == null) return "";
|
||||
Campaign campaign = campaignRepository.findById(campaignId).orElse(null);
|
||||
if (campaign == null) return "";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Campagne : ").append(campaign.getName());
|
||||
if (campaign.getDescription() != null && !campaign.getDescription().isBlank()) {
|
||||
sb.append(" — ").append(campaign.getDescription().trim());
|
||||
}
|
||||
if (campaign.getGameSystemId() != null && !campaign.getGameSystemId().isBlank()) {
|
||||
gameSystemRepository.findById(campaign.getGameSystemId())
|
||||
.ifPresent(gs -> sb.append("\nSystème de jeu : ").append(gs.getName()));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private int nextOrderFor(String campaignId) {
|
||||
return repository.findByCampaignId(campaignId).stream()
|
||||
.mapToInt(ItemCatalog::getOrder)
|
||||
.max()
|
||||
.orElse(-1) + 1;
|
||||
}
|
||||
}
|
||||
@@ -14,5 +14,6 @@ public record CampaignImportProgress(
|
||||
int ocrPageCount,
|
||||
int arcCount,
|
||||
int chapterCount,
|
||||
int sceneCount) {
|
||||
int sceneCount,
|
||||
int npcCount) {
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import java.util.List;
|
||||
* PROPOSITION non persistée : l'UI laisse l'utilisateur réviser/éditer l'arbre
|
||||
* avant la création effective des arcs/chapitres/scènes. Records purs (domaine).
|
||||
*/
|
||||
public record CampaignImportProposal(List<ArcProposal> arcs) {
|
||||
public record CampaignImportProposal(List<ArcProposal> arcs, List<NpcProposal> npcs) {
|
||||
|
||||
/**
|
||||
* {@code existingId} (nullable) : si présent, le nœud existe DÉJÀ dans la
|
||||
@@ -37,4 +37,14 @@ public record CampaignImportProposal(List<ArcProposal> arcs) {
|
||||
|
||||
public record RoomProposal(String name, String description, String enemies, String loot) {
|
||||
}
|
||||
|
||||
/**
|
||||
* PNJ/creature notable detecte dans le PDF (PNJ nommes, boss). Propose a la
|
||||
* revue (coche par defaut) ; cree comme Npc de la campagne a l''apply avec
|
||||
* sa description dans values["Description"] (meme convention que les cartes
|
||||
* d''action des ateliers).
|
||||
*/
|
||||
public record NpcProposal(String name, String description) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.loremind.domain.campaigncontext;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* Un objet d'un {@link ItemCatalog} (boutique, butin, trésor…).
|
||||
* Value object possédé par le catalogue : remplacé en bloc à chaque mise à jour.
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogItem {
|
||||
|
||||
private String name;
|
||||
|
||||
/** Prix libre (ex. « 50 po », « 2 pa »). Nullable. */
|
||||
private String price;
|
||||
|
||||
/** Catégorie de regroupement (ex. « Armes », « Potions »). Nullable. */
|
||||
private String category;
|
||||
|
||||
/** Description / effet (markdown). Nullable. */
|
||||
private String description;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.loremind.domain.campaigncontext;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Catalogue d'objets prédéfinis d'une campagne : une boutique, un butin, un trésor…
|
||||
* Le MJ le remplit à la main ou via l'IA, et le consulte (notamment en session) quand
|
||||
* les joueurs visitent une échoppe. Scope campagne (cross-aggregate via ID).
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class ItemCatalog {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
/** Description libre (à quoi sert ce catalogue / cette boutique). Nullable. */
|
||||
private String description;
|
||||
|
||||
/** Clé d'icône (lucide) pour la sidebar/fiche. Nullable. */
|
||||
private String icon;
|
||||
|
||||
/** Référence vers la Campaign parente (cross-aggregate via ID). */
|
||||
private String campaignId;
|
||||
|
||||
/** Ordre d'affichage dans la liste des catalogues de la campagne. */
|
||||
private int order;
|
||||
|
||||
/** Objets ordonnés du catalogue. Jamais null après construction. */
|
||||
private List<CatalogItem> items;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
public List<CatalogItem> getItems() {
|
||||
if (items == null) items = new ArrayList<>();
|
||||
return items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.loremind.domain.campaigncontext.ports;
|
||||
|
||||
/**
|
||||
* Échec de génération IA d'un catalogue d'objets (Brain injoignable, erreur du
|
||||
* modèle, réponse inexploitable…). Mappée en HTTP 502 par le contrôleur.
|
||||
*/
|
||||
public class ItemCatalogGenerationException extends RuntimeException {
|
||||
public ItemCatalogGenerationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ItemCatalogGenerationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.loremind.domain.campaigncontext.ports;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Port de sortie : génération IA d'un catalogue d'objets. Implémenté par un client
|
||||
* du Brain (service IA Python).
|
||||
*/
|
||||
public interface ItemCatalogGenerator {
|
||||
|
||||
/** Catalogue proposé (non persisté) à partir d'une description. */
|
||||
record GeneratedCatalog(String name, String description, List<CatalogItem> items) {}
|
||||
|
||||
/**
|
||||
* Génère une proposition de catalogue (objets) sur le sujet donné, en s'appuyant
|
||||
* sur le contexte (campagne, système…) s'il est fourni.
|
||||
*/
|
||||
GeneratedCatalog generate(String description, String context);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.loremind.domain.campaigncontext.ports;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Port de sortie pour la persistance des {@link ItemCatalog}.
|
||||
*/
|
||||
public interface ItemCatalogRepository {
|
||||
|
||||
ItemCatalog save(ItemCatalog catalog);
|
||||
|
||||
Optional<ItemCatalog> findById(String id);
|
||||
|
||||
List<ItemCatalog> findByCampaignId(String campaignId);
|
||||
|
||||
void deleteById(String id);
|
||||
|
||||
boolean existsById(String id);
|
||||
}
|
||||
@@ -17,9 +17,10 @@ public interface NotebookChatStreamer {
|
||||
|
||||
/**
|
||||
* Streame la réponse ancrée sur les sources. Les callbacks sont invoqués au fil
|
||||
* de l'eau : {@code onToken} par fragment, {@code onProgress} (mode approfondi
|
||||
* uniquement) pendant la lecture du document, {@code onDone} à la fin,
|
||||
* {@code onError} en cas d'échec.
|
||||
* de l'eau : {@code onSourcesJson} UNE fois avant le premier token (JSON brut des
|
||||
* passages utilisés — transparence UI), {@code onToken} par fragment,
|
||||
* {@code onProgress} (mode approfondi uniquement) pendant la lecture du document,
|
||||
* {@code onDone} à la fin, {@code onError} en cas d'échec.
|
||||
*
|
||||
* @param deep true = analyse approfondie (map-reduce sur tout le document) ;
|
||||
* false = chat RAG (top-k).
|
||||
@@ -29,6 +30,7 @@ public interface NotebookChatStreamer {
|
||||
List<Msg> messages,
|
||||
String context,
|
||||
boolean deep,
|
||||
Consumer<String> onSourcesJson,
|
||||
Consumer<String> onToken,
|
||||
Consumer<Progress> onProgress,
|
||||
Runnable onDone,
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.loremind.domain.campaigncontext.CampaignImportProgress;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.ArcProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.ChapterProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.NpcProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.RoomProposal;
|
||||
import com.loremind.domain.campaigncontext.CampaignImportProposal.SceneProposal;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignImportException;
|
||||
@@ -119,7 +120,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
return;
|
||||
}
|
||||
if ("extracting".equals(event)) {
|
||||
onProgress.accept(new CampaignImportProgress(0, 0, 0, 0, 0, 0, 0));
|
||||
onProgress.accept(new CampaignImportProgress(0, 0, 0, 0, 0, 0, 0, 0));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -130,7 +131,7 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
pageCount[0] = node.path("page_count").asInt();
|
||||
ocrPageCount[0] = node.path("ocr_page_count").asInt();
|
||||
onProgress.accept(new CampaignImportProgress(
|
||||
0, node.path("total").asInt(), pageCount[0], ocrPageCount[0], 0, 0, 0));
|
||||
0, node.path("total").asInt(), pageCount[0], ocrPageCount[0], 0, 0, 0, 0));
|
||||
} else if ("progress".equals(event)) {
|
||||
onProgress.accept(new CampaignImportProgress(
|
||||
node.path("current").asInt(),
|
||||
@@ -139,10 +140,12 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
ocrPageCount[0],
|
||||
node.path("arc_count").asInt(),
|
||||
node.path("chapter_count").asInt(),
|
||||
node.path("scene_count").asInt()));
|
||||
node.path("scene_count").asInt(),
|
||||
node.path("npc_count").asInt()));
|
||||
} else if ("done".equals(event)) {
|
||||
terminated[0] = true;
|
||||
onDone.accept(new CampaignImportProposal(toArcs(node.path("arcs"))));
|
||||
onDone.accept(new CampaignImportProposal(
|
||||
toArcs(node.path("arcs")), toNpcs(node.path("npcs"))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +205,16 @@ public class BrainCampaignImportClient implements CampaignPdfImporter {
|
||||
return rooms;
|
||||
}
|
||||
|
||||
private List<NpcProposal> toNpcs(JsonNode npcsNode) {
|
||||
List<NpcProposal> npcs = new ArrayList<>();
|
||||
if (npcsNode != null && npcsNode.isArray()) {
|
||||
for (JsonNode n : npcsNode) {
|
||||
npcs.add(new NpcProposal(text(n, "name"), text(n, "description")));
|
||||
}
|
||||
}
|
||||
return npcs;
|
||||
}
|
||||
|
||||
// --- Helpers -------------------------------------------------------------
|
||||
|
||||
private ByteArrayResource filePart(byte[] pdfBytes, String filename) {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.loremind.infrastructure.ai;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerationException;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerator;
|
||||
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 : génère un catalogue d'objets via le Brain (POST one-shot).
|
||||
*/
|
||||
@Component
|
||||
public class BrainItemCatalogClient implements ItemCatalogGenerator {
|
||||
|
||||
private static final String GENERATE_PATH = "/generate/item-catalog";
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final String baseUrl;
|
||||
|
||||
public BrainItemCatalogClient(
|
||||
RestTemplate restTemplate,
|
||||
@Value("${brain.base-url}") String baseUrl) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public GeneratedCatalog generate(String description, String context) {
|
||||
Map<String, Object> req = new LinkedHashMap<>();
|
||||
req.put("description", description == null ? "" : description);
|
||||
req.put("context", context == null ? "" : context);
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(req, headers);
|
||||
|
||||
Map<String, Object> resp;
|
||||
try {
|
||||
resp = restTemplate.postForObject(baseUrl + GENERATE_PATH, entity, Map.class);
|
||||
} catch (ResourceAccessException e) {
|
||||
throw new ItemCatalogGenerationException("Le Brain est injoignable (timeout ou arrêté).", e);
|
||||
} catch (RestClientResponseException e) {
|
||||
throw new ItemCatalogGenerationException(
|
||||
"Le Brain a répondu HTTP " + e.getStatusCode().value() + " : " + e.getResponseBodyAsString(), e);
|
||||
} catch (Exception e) {
|
||||
throw new ItemCatalogGenerationException("Erreur inattendue lors de l'appel au Brain.", e);
|
||||
}
|
||||
if (resp == null) {
|
||||
throw new ItemCatalogGenerationException("Le Brain a renvoyé une réponse vide.");
|
||||
}
|
||||
|
||||
List<CatalogItem> items = new ArrayList<>();
|
||||
Object rawItems = resp.get("items");
|
||||
if (rawItems instanceof List<?> list) {
|
||||
for (Object item : list) {
|
||||
if (!(item instanceof Map<?, ?> m)) continue;
|
||||
String name = asString(m.get("name"));
|
||||
if (name == null || name.isBlank()) continue;
|
||||
items.add(CatalogItem.builder()
|
||||
.name(name)
|
||||
.price(asString(m.get("price")))
|
||||
.category(asString(m.get("category")))
|
||||
.description(asString(m.get("description")))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
throw new ItemCatalogGenerationException("Aucun objet généré — réessaie ou reformule.");
|
||||
}
|
||||
String name = asString(resp.get("name"));
|
||||
return new GeneratedCatalog(
|
||||
name != null && !name.isBlank() ? name : description,
|
||||
asString(resp.get("description")),
|
||||
items);
|
||||
}
|
||||
|
||||
private static String asString(Object o) {
|
||||
return o != null ? o.toString() : null;
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||
List<Msg> messages,
|
||||
String context,
|
||||
boolean deep,
|
||||
Consumer<String> onSourcesJson,
|
||||
Consumer<String> onToken,
|
||||
Consumer<Progress> onProgress,
|
||||
Runnable onDone,
|
||||
@@ -75,7 +76,8 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||
try {
|
||||
flux
|
||||
.timeout(Duration.ofSeconds(timeoutSeconds))
|
||||
.doOnNext(sse -> handleEvent(sse, terminated, onToken, onProgress, onDone, onError))
|
||||
.doOnNext(sse -> handleEvent(
|
||||
sse, terminated, onSourcesJson, onToken, onProgress, onDone, onError))
|
||||
.blockLast();
|
||||
if (!terminated[0]) {
|
||||
onDone.run(); // flux terminé sans event done explicite
|
||||
@@ -93,6 +95,7 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||
private void handleEvent(
|
||||
ServerSentEvent<String> sse,
|
||||
boolean[] terminated,
|
||||
Consumer<String> onSourcesJson,
|
||||
Consumer<String> onToken,
|
||||
Consumer<Progress> onProgress,
|
||||
Runnable onDone,
|
||||
@@ -103,6 +106,10 @@ public class BrainNotebookChatClient implements NotebookChatStreamer {
|
||||
if ("token".equals(event)) {
|
||||
String token = readField(data, "token");
|
||||
if (token != null && !token.isEmpty()) onToken.accept(token);
|
||||
} else if ("sources".equals(event)) {
|
||||
// Passages utilisés par le RAG : relayés tels quels (JSON brut) — le
|
||||
// Core n'a pas besoin de les comprendre, seulement de les transmettre.
|
||||
onSourcesJson.accept(data);
|
||||
} else if ("progress".equals(event)) {
|
||||
onProgress.accept(new Progress(readInt(data, "current"), readInt(data, "total")));
|
||||
} else if ("done".equals(event)) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.loremind.infrastructure.persistence.entity;
|
||||
import com.loremind.domain.campaigncontext.ArcType;
|
||||
import com.loremind.infrastructure.persistence.converter.StringListJsonConverter;
|
||||
import jakarta.persistence.*;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -42,8 +43,12 @@ public class ArcJpaEntity {
|
||||
* Type structurel de l'arc (LINEAR par défaut).
|
||||
* Stocké en STRING pour rester lisible en DB et résistant aux refactos d'ordre.
|
||||
*/
|
||||
// length + @ColumnDefault (PAS columnDefinition brut) : Hibernate 6.6 recopie
|
||||
// columnDefinition tel quel dans son ALTER ... SET DATA TYPE de migration, et
|
||||
// PostgreSQL refuse DEFAULT à cet endroit (erreur à chaque démarrage).
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, columnDefinition = "VARCHAR(16) DEFAULT 'LINEAR'")
|
||||
@Column(nullable = false, length = 16)
|
||||
@ColumnDefault("'LINEAR'")
|
||||
@Builder.Default
|
||||
private ArcType type = ArcType.LINEAR;
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
|
||||
/**
|
||||
* Entité JPA d'un objet de catalogue (enfant de {@link ItemCatalogJpaEntity}).
|
||||
* Ordonné par {@code position}. Référence parente exclue de toString/equals.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "catalog_items", indexes = {
|
||||
@Index(name = "idx_catalog_items_catalog_id", columnList = "catalog_id")
|
||||
})
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CatalogItemJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(length = 64)
|
||||
private String price;
|
||||
|
||||
@Column(length = 128)
|
||||
private String category;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String description;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int position;
|
||||
|
||||
@ManyToOne(optional = false, fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "catalog_id", nullable = false)
|
||||
@ToString.Exclude
|
||||
@EqualsAndHashCode.Exclude
|
||||
private ItemCatalogJpaEntity catalog;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.loremind.infrastructure.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Entité JPA d'un catalogue d'objets (parent) avec ses objets ordonnés (enfants).
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "item_catalogs", indexes = {
|
||||
@Index(name = "idx_item_catalogs_campaign_id", columnList = "campaign_id")
|
||||
})
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ItemCatalogJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String description;
|
||||
|
||||
@Column(length = 64)
|
||||
private String icon;
|
||||
|
||||
@Column(name = "campaign_id", nullable = false)
|
||||
private Long campaignId;
|
||||
|
||||
@Column(name = "\"order\"", nullable = false)
|
||||
private int order;
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "catalog",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true,
|
||||
fetch = FetchType.LAZY
|
||||
)
|
||||
@OrderBy("position ASC")
|
||||
@Builder.Default
|
||||
private List<CatalogItemJpaEntity> items = new ArrayList<>();
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = LocalDateTime.now();
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
protected void onUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.loremind.infrastructure.persistence.jpa;
|
||||
|
||||
import com.loremind.infrastructure.persistence.entity.ItemCatalogJpaEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface ItemCatalogJpaRepository extends JpaRepository<ItemCatalogJpaEntity, Long> {
|
||||
|
||||
List<ItemCatalogJpaEntity> findByCampaignIdOrderByOrderAsc(Long campaignId);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.loremind.infrastructure.persistence.postgres;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogRepository;
|
||||
import com.loremind.infrastructure.persistence.entity.CatalogItemJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.entity.ItemCatalogJpaEntity;
|
||||
import com.loremind.infrastructure.persistence.jpa.ItemCatalogJpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Repository
|
||||
public class PostgresItemCatalogRepository implements ItemCatalogRepository {
|
||||
|
||||
private final ItemCatalogJpaRepository jpaRepository;
|
||||
|
||||
public PostgresItemCatalogRepository(ItemCatalogJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ItemCatalog save(ItemCatalog catalog) {
|
||||
ItemCatalogJpaEntity entity = (catalog.getId() != null)
|
||||
? jpaRepository.findById(Long.parseLong(catalog.getId())).orElseGet(ItemCatalogJpaEntity::new)
|
||||
: new ItemCatalogJpaEntity();
|
||||
|
||||
entity.setName(catalog.getName());
|
||||
entity.setDescription(catalog.getDescription());
|
||||
entity.setIcon(catalog.getIcon());
|
||||
entity.setCampaignId(Long.parseLong(catalog.getCampaignId()));
|
||||
entity.setOrder(catalog.getOrder());
|
||||
|
||||
// Remplacement en bloc des objets (orphanRemoval supprime les anciens).
|
||||
entity.getItems().clear();
|
||||
int position = 0;
|
||||
for (CatalogItem it : catalog.getItems()) {
|
||||
entity.getItems().add(CatalogItemJpaEntity.builder()
|
||||
.name(it.getName())
|
||||
.price(it.getPrice())
|
||||
.category(it.getCategory())
|
||||
.description(it.getDescription())
|
||||
.position(position++)
|
||||
.catalog(entity)
|
||||
.build());
|
||||
}
|
||||
|
||||
return toDomainEntity(jpaRepository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<ItemCatalog> findById(String id) {
|
||||
return jpaRepository.findById(Long.parseLong(id)).map(this::toDomainEntity);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<ItemCatalog> findByCampaignId(String campaignId) {
|
||||
return jpaRepository.findByCampaignIdOrderByOrderAsc(Long.parseLong(campaignId)).stream()
|
||||
.map(this::toDomainEntity)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteById(String id) {
|
||||
jpaRepository.deleteById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsById(String id) {
|
||||
return jpaRepository.existsById(Long.parseLong(id));
|
||||
}
|
||||
|
||||
private ItemCatalog toDomainEntity(ItemCatalogJpaEntity e) {
|
||||
List<CatalogItem> items = e.getItems().stream()
|
||||
.map(c -> CatalogItem.builder()
|
||||
.name(c.getName())
|
||||
.price(c.getPrice())
|
||||
.category(c.getCategory())
|
||||
.description(c.getDescription())
|
||||
.build())
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
return ItemCatalog.builder()
|
||||
.id(e.getId().toString())
|
||||
.name(e.getName())
|
||||
.description(e.getDescription())
|
||||
.icon(e.getIcon())
|
||||
.campaignId(e.getCampaignId().toString())
|
||||
.order(e.getOrder())
|
||||
.items(items)
|
||||
.createdAt(e.getCreatedAt())
|
||||
.updatedAt(e.getUpdatedAt())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,11 @@ public class MinioConfig {
|
||||
|
||||
@Bean
|
||||
public MinioClient minioClient() {
|
||||
return buildClient();
|
||||
}
|
||||
|
||||
/** Fabrique directe (sans proxy Spring) — voir ensureBucketExists. */
|
||||
private MinioClient buildClient() {
|
||||
return MinioClient.builder()
|
||||
.endpoint(endpoint)
|
||||
.credentials(accessKey, secretKey)
|
||||
@@ -42,11 +47,16 @@ public class MinioConfig {
|
||||
* Garantit l'existence du bucket au demarrage. Si MinIO n'est pas joignable,
|
||||
* on loggue juste l'erreur sans planter l'application : le developpeur
|
||||
* recevra une erreur claire au premier upload plutot qu'au boot.
|
||||
* <p>
|
||||
* NB : on construit un client LOCAL au lieu d'appeler {@code minioClient()} —
|
||||
* depuis Spring 6.2, appeler une methode @Bean proxifiee pendant le
|
||||
* @PostConstruct de sa propre @Configuration leve "Requested bean is
|
||||
* currently in creation" et la verification ne tournait plus jamais.
|
||||
*/
|
||||
@PostConstruct
|
||||
public void ensureBucketExists() {
|
||||
try {
|
||||
MinioClient client = minioClient();
|
||||
MinioClient client = buildClient();
|
||||
boolean exists = client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
|
||||
if (!exists) {
|
||||
client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.ItemCatalogService;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.domain.campaigncontext.ports.ItemCatalogGenerationException;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ItemCatalogDTO;
|
||||
import com.loremind.infrastructure.web.mapper.ItemCatalogMapper;
|
||||
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.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/item-catalogs")
|
||||
public class ItemCatalogController {
|
||||
|
||||
private final ItemCatalogService service;
|
||||
private final ItemCatalogMapper mapper;
|
||||
|
||||
public ItemCatalogController(ItemCatalogService service, ItemCatalogMapper mapper) {
|
||||
this.service = service;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<ItemCatalogDTO> create(@RequestBody ItemCatalogDTO dto) {
|
||||
ItemCatalog created = service.createCatalog(toData(dto, null));
|
||||
return ResponseEntity.ok(mapper.toDTO(created));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<ItemCatalogDTO> getById(@PathVariable String id) {
|
||||
return service.getCatalogById(id)
|
||||
.map(c -> ResponseEntity.ok(mapper.toDTO(c)))
|
||||
.orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/campaign/{campaignId}")
|
||||
public ResponseEntity<List<ItemCatalogDTO>> getByCampaign(@PathVariable String campaignId) {
|
||||
List<ItemCatalogDTO> dtos = service.getCatalogsByCampaignId(campaignId).stream()
|
||||
.map(mapper::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
return ResponseEntity.ok(dtos);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<ItemCatalogDTO> update(@PathVariable String id, @RequestBody ItemCatalogDTO dto) {
|
||||
ItemCatalog updated = service.updateCatalog(id, toData(dto, dto.getOrder()));
|
||||
return ResponseEntity.ok(mapper.toDTO(updated));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable String id) {
|
||||
service.deleteCatalog(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** Génère une PROPOSITION de catalogue via l'IA (non persistée) — l'UI préremplit le formulaire. */
|
||||
@PostMapping("/generate")
|
||||
public ResponseEntity<ItemCatalogDTO> generate(@RequestBody GenerateRequest req) {
|
||||
try {
|
||||
ItemCatalog proposal = service.generateProposal(req.campaignId(), req.description());
|
||||
return ResponseEntity.ok(mapper.toDTO(proposal));
|
||||
} catch (ItemCatalogGenerationException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private ItemCatalogService.CatalogData toData(ItemCatalogDTO dto, Integer order) {
|
||||
return new ItemCatalogService.CatalogData(
|
||||
dto.getName(),
|
||||
dto.getDescription(),
|
||||
dto.getIcon(),
|
||||
mapper.toDomainItems(dto.getItems()),
|
||||
dto.getCampaignId(),
|
||||
order
|
||||
);
|
||||
}
|
||||
|
||||
public record GenerateRequest(String campaignId, String description) {}
|
||||
}
|
||||
@@ -132,6 +132,7 @@ public class NotebookController {
|
||||
StringBuilder assistant = new StringBuilder();
|
||||
chatStreamer.stream(
|
||||
sourceIds, history, context, deep,
|
||||
sourcesJson -> sendSources(emitter, sourcesJson),
|
||||
token -> { assistant.append(token); sendToken(emitter, token); },
|
||||
progress -> sendProgress(emitter, progress),
|
||||
() -> {
|
||||
@@ -161,6 +162,15 @@ public class NotebookController {
|
||||
}
|
||||
}
|
||||
|
||||
private void sendSources(SseEmitter emitter, String sourcesJson) {
|
||||
try {
|
||||
// JSON brut du Brain ({"sources":[{source_id,page,score},…]}), relayé tel quel.
|
||||
emitter.send(SseEmitter.event().name("sources").data(sourcesJson));
|
||||
} catch (IOException | IllegalStateException e) {
|
||||
// flux fermé/expiré : on cesse d'écrire
|
||||
}
|
||||
}
|
||||
|
||||
private void sendProgress(SseEmitter emitter, NotebookChatStreamer.Progress p) {
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name("progress")
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* DTO d'un objet de catalogue.
|
||||
*/
|
||||
@Data
|
||||
public class CatalogItemDTO {
|
||||
private String name;
|
||||
private String price;
|
||||
private String category;
|
||||
private String description;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.loremind.infrastructure.web.dto.campaigncontext;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DTO d'un catalogue d'objets (avec ses objets).
|
||||
*/
|
||||
@Data
|
||||
public class ItemCatalogDTO {
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String icon;
|
||||
private String campaignId;
|
||||
private int order;
|
||||
private List<CatalogItemDTO> items = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.loremind.infrastructure.web.mapper;
|
||||
|
||||
import com.loremind.domain.campaigncontext.CatalogItem;
|
||||
import com.loremind.domain.campaigncontext.ItemCatalog;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.CatalogItemDTO;
|
||||
import com.loremind.infrastructure.web.dto.campaigncontext.ItemCatalogDTO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class ItemCatalogMapper {
|
||||
|
||||
public ItemCatalogDTO toDTO(ItemCatalog c) {
|
||||
if (c == null) return null;
|
||||
ItemCatalogDTO dto = new ItemCatalogDTO();
|
||||
dto.setId(c.getId());
|
||||
dto.setName(c.getName());
|
||||
dto.setDescription(c.getDescription());
|
||||
dto.setIcon(c.getIcon());
|
||||
dto.setCampaignId(c.getCampaignId());
|
||||
dto.setOrder(c.getOrder());
|
||||
dto.setItems(c.getItems().stream().map(this::toItemDTO).collect(Collectors.toList()));
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<CatalogItem> toDomainItems(List<CatalogItemDTO> dtos) {
|
||||
if (dtos == null) return List.of();
|
||||
return dtos.stream().map(this::toDomainItem).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private CatalogItemDTO toItemDTO(CatalogItem i) {
|
||||
CatalogItemDTO dto = new CatalogItemDTO();
|
||||
dto.setName(i.getName());
|
||||
dto.setPrice(i.getPrice());
|
||||
dto.setCategory(i.getCategory());
|
||||
dto.setDescription(i.getDescription());
|
||||
return dto;
|
||||
}
|
||||
|
||||
private CatalogItem toDomainItem(CatalogItemDTO dto) {
|
||||
return CatalogItem.builder()
|
||||
.name(dto.getName())
|
||||
.price(dto.getPrice())
|
||||
.category(dto.getCategory())
|
||||
.description(dto.getDescription())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
# Configuration de test : vraie base PostgreSQL loremind_test.
|
||||
#
|
||||
# La base `loremind_test` doit exister sur l'instance locale (port 5432).
|
||||
# Les credentials sont ceux de `.env` a la racine du projet ; on les duplique
|
||||
# ici car les tests Maven ne chargent pas le .env.
|
||||
#
|
||||
# Surchargables via variables d'environnement (CI) :
|
||||
# AUCUN credential reel ici (fichier versionne !) : definissez les variables
|
||||
# d'environnement en local (IDE ou shell) comme en CI :
|
||||
# SPRING_DATASOURCE_URL, SPRING_DATASOURCE_USERNAME, SPRING_DATASOURCE_PASSWORD
|
||||
spring.datasource.url=${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/loremind_test}
|
||||
spring.datasource.username=${SPRING_DATASOURCE_USERNAME:loremind_test}
|
||||
|
||||
@@ -66,5 +66,31 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"type": "component"
|
||||
},
|
||||
"@schematics/angular:directive": {
|
||||
"type": "directive"
|
||||
},
|
||||
"@schematics/angular:service": {
|
||||
"type": "service"
|
||||
},
|
||||
"@schematics/angular:guard": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:interceptor": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:module": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:pipe": {
|
||||
"typeSeparator": "."
|
||||
},
|
||||
"@schematics/angular:resolver": {
|
||||
"typeSeparator": "."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11692
web/package-lock.json
generated
11692
web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "loremind-web",
|
||||
"version": "0.11.2-beta",
|
||||
"version": "0.12.0-beta",
|
||||
"description": "LoreMind Frontend - Angular",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
@@ -15,26 +15,28 @@
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^17.0.0",
|
||||
"@angular/common": "^17.0.0",
|
||||
"@angular/compiler": "^17.0.0",
|
||||
"@angular/core": "^17.0.0",
|
||||
"@angular/forms": "^17.0.0",
|
||||
"@angular/platform-browser": "^17.0.0",
|
||||
"@angular/platform-browser-dynamic": "^17.0.0",
|
||||
"@angular/router": "^17.0.0",
|
||||
"@angular/animations": "^21.2.16",
|
||||
"@angular/common": "^21.2.16",
|
||||
"@angular/compiler": "^21.2.16",
|
||||
"@angular/core": "^21.2.16",
|
||||
"@angular/forms": "^21.2.16",
|
||||
"@angular/platform-browser": "^21.2.16",
|
||||
"@angular/platform-browser-dynamic": "^21.2.16",
|
||||
"@angular/router": "^21.2.16",
|
||||
"dompurify": "^3.4.1",
|
||||
"lucide-angular": "^1.0.0",
|
||||
"marked": "^18.0.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
"zone.js": "~0.14.2"
|
||||
"zone.js": "~0.15.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular-devkit/build-angular": "^17.0.0",
|
||||
"@angular/cli": "^17.0.0",
|
||||
"@angular/compiler-cli": "^17.0.0",
|
||||
"@angular-devkit/build-angular": "^21.2.14",
|
||||
"@angular/cli": "^21.2.14",
|
||||
"@angular/compiler-cli": "^21.2.16",
|
||||
"@emnapi/core": "^1.11.0",
|
||||
"@emnapi/runtime": "^1.11.0",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"typescript": "~5.2.2"
|
||||
"typescript": "~5.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<div class="app-container">
|
||||
<app-sidebar></app-sidebar>
|
||||
|
||||
<ng-container *ngIf="sidebarConfig$ | async as config">
|
||||
@if (sidebarConfig$ | async; as config) {
|
||||
<app-secondary-sidebar
|
||||
[title]="config.title"
|
||||
[titleRoute]="config.titleRoute || null"
|
||||
@@ -11,7 +11,7 @@
|
||||
[createActions]="config.createActions"
|
||||
[bottomPanel]="config.bottomPanel || null">
|
||||
</app-secondary-sidebar>
|
||||
</ng-container>
|
||||
}
|
||||
|
||||
<main class="main-content">
|
||||
<router-outlet></router-outlet>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, HostListener } from '@angular/core';
|
||||
import { AsyncPipe, NgIf } from '@angular/common';
|
||||
import { AsyncPipe } from '@angular/common';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { SidebarComponent } from './sidebar/sidebar.component';
|
||||
import { SecondarySidebarComponent } from './shared/secondary-sidebar/secondary-sidebar.component';
|
||||
@@ -12,7 +12,6 @@ import { VersionCheckerService } from './services/version-checker.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
standalone: true,
|
||||
imports: [
|
||||
RouterOutlet,
|
||||
SidebarComponent,
|
||||
@@ -20,8 +19,7 @@ import { VersionCheckerService } from './services/version-checker.service';
|
||||
GlobalSearchComponent,
|
||||
UpdateBannerComponent,
|
||||
ConfirmDialogHostComponent,
|
||||
AsyncPipe,
|
||||
NgIf,
|
||||
AsyncPipe
|
||||
],
|
||||
templateUrl: './app.component.html',
|
||||
styleUrls: ['./app.component.scss']
|
||||
|
||||
@@ -27,6 +27,10 @@ export const routes: Routes = [
|
||||
{ path: 'campaigns/:campaignId/npcs/:npcId', loadComponent: () => import('./campaigns/npc/npc-view/npc-view.component').then(m => m.NpcViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/notebooks', loadComponent: () => import('./campaigns/notebook/notebook-list/notebook-list.component').then(m => m.NotebookListComponent) },
|
||||
{ path: 'campaigns/:campaignId/notebooks/:notebookId', loadComponent: () => import('./campaigns/notebook/notebook-detail/notebook-detail.component').then(m => m.NotebookDetailComponent) },
|
||||
{ path: 'campaigns/:campaignId/item-catalogs', loadComponent: () => import('./campaigns/item-catalog/item-catalog-list/item-catalog-list.component').then(m => m.ItemCatalogListComponent) },
|
||||
{ path: 'campaigns/:campaignId/item-catalogs/create', loadComponent: () => import('./campaigns/item-catalog/item-catalog-edit/item-catalog-edit.component').then(m => m.ItemCatalogEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/item-catalogs/:catalogId/edit', loadComponent: () => import('./campaigns/item-catalog/item-catalog-edit/item-catalog-edit.component').then(m => m.ItemCatalogEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/item-catalogs/:catalogId', loadComponent: () => import('./campaigns/item-catalog/item-catalog-view/item-catalog-view.component').then(m => m.ItemCatalogViewComponent) },
|
||||
{ path: 'campaigns/:campaignId/random-tables/create', loadComponent: () => import('./campaigns/random-table/random-table-edit/random-table-edit.component').then(m => m.RandomTableEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId/edit', loadComponent: () => import('./campaigns/random-table/random-table-edit/random-table-edit.component').then(m => m.RandomTableEditComponent) },
|
||||
{ path: 'campaigns/:campaignId/random-tables/:tableId', loadComponent: () => import('./campaigns/random-table/random-table-view/random-table-view.component').then(m => m.RandomTableViewComponent) },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
@@ -20,8 +20,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-create',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, LucideAngularModule, IconPickerComponent],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent],
|
||||
templateUrl: './arc-create.component.html',
|
||||
styleUrls: ['./arc-create.component.scss']
|
||||
})
|
||||
|
||||
@@ -145,7 +145,8 @@
|
||||
</div>
|
||||
|
||||
<!-- ===== Pages Lore associées (phase B2 cross-context) ===== -->
|
||||
<div class="field" *ngIf="loreId">
|
||||
@if (loreId) {
|
||||
<div class="field">
|
||||
<label>Pages Lore associées</label>
|
||||
<app-lore-link-picker
|
||||
[value]="relatedPageIds"
|
||||
@@ -157,13 +158,16 @@
|
||||
Liez cet arc à des PNJ, lieux ou éléments du Lore. Cliquez sur un chip pour ouvrir la page associée.
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="field lore-hint" *ngIf="!loreId">
|
||||
@if (!loreId) {
|
||||
<div class="field lore-hint">
|
||||
<small class="field-hint">
|
||||
💡 Cette campagne n'est associée à aucun univers. Associez-la à un Lore dans l'écran de la campagne
|
||||
pour pouvoir lier cet arc à des pages du Lore (PNJ, lieux, etc.).
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
|
||||
</form>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
@@ -33,8 +33,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-edit',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, LoreLinkPickerComponent, AiChatDrawerComponent, ImageGalleryComponent, IconPickerComponent],
|
||||
templateUrl: './arc-edit.component.html',
|
||||
styleUrls: ['./arc-edit.component.scss']
|
||||
})
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<div class="view-page" *ngIf="arc">
|
||||
|
||||
@if (arc) {
|
||||
<div class="view-page">
|
||||
<header class="view-header">
|
||||
<div>
|
||||
<h1>
|
||||
<lucide-icon *ngIf="arc.icon" [img]="resolveCampaignIcon(arc.icon)" [size]="22" class="title-icon"></lucide-icon>
|
||||
@if (arc.icon) {
|
||||
<lucide-icon [img]="resolveCampaignIcon(arc.icon)" [size]="22" class="title-icon"></lucide-icon>
|
||||
}
|
||||
{{ arc.name }}
|
||||
</h1>
|
||||
<p class="view-subtitle">
|
||||
@@ -21,103 +23,128 @@
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Illustrations (rendu editorial magazine) -->
|
||||
<section class="view-section" *ngIf="(arc.illustrationImageIds?.length ?? 0) > 0">
|
||||
@if ((arc.illustrationImageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<app-image-gallery [imageIds]="arc.illustrationImageIds ?? []" [layout]="'EDITORIAL'"></app-image-gallery>
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- Cartes & plans -->
|
||||
<section class="view-section" *ngIf="(arc.mapImageIds?.length ?? 0) > 0">
|
||||
@if ((arc.mapImageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Cartes & plans</h2>
|
||||
<app-image-gallery [imageIds]="arc.mapImageIds ?? []" [layout]="'MAPS'"></app-image-gallery>
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- Vue Hub (scénario) : liste les quêtes et leurs conditions, sans statut.
|
||||
Le statut effectif et les actions de jeu vivent dans l'écran d'une Partie. -->
|
||||
<section class="view-section" *ngIf="arc.type === 'HUB'">
|
||||
@if (arc.type === 'HUB') {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Quêtes du hub (scénario)</h2>
|
||||
|
||||
<p class="view-section-empty" *ngIf="hubQuests.length === 0">
|
||||
@if (hubQuests.length === 0) {
|
||||
<p class="view-section-empty">
|
||||
Aucune quête pour ce hub. Créez-en une pour démarrer.
|
||||
</p>
|
||||
|
||||
<div class="hub-quest-grid" *ngIf="hubQuests.length > 0">
|
||||
}
|
||||
@if (hubQuests.length > 0) {
|
||||
<div class="hub-quest-grid">
|
||||
@for (q of hubQuests; track q) {
|
||||
<button type="button"
|
||||
class="hub-quest-card"
|
||||
*ngFor="let q of hubQuests"
|
||||
(click)="openQuest(q)">
|
||||
<div class="hub-quest-card-head">
|
||||
<span class="hub-quest-card-icon" *ngIf="q.icon">
|
||||
@if (q.icon) {
|
||||
<span class="hub-quest-card-icon">
|
||||
<lucide-icon [img]="resolveCampaignIcon(q.icon)" [size]="18"></lucide-icon>
|
||||
</span>
|
||||
}
|
||||
<span class="hub-quest-card-name">{{ q.name }}</span>
|
||||
</div>
|
||||
|
||||
<p class="hub-quest-card-desc" *ngIf="q.description?.trim()">{{ q.description }}</p>
|
||||
|
||||
<div class="hub-quest-card-locked-hint" *ngIf="(q.prerequisites?.length ?? 0) > 0">
|
||||
@if (q.description?.trim()) {
|
||||
<p class="hub-quest-card-desc">{{ q.description }}</p>
|
||||
}
|
||||
@if ((q.prerequisites?.length ?? 0) > 0) {
|
||||
<div class="hub-quest-card-locked-hint">
|
||||
<lucide-icon [img]="AlertCircle" [size]="13"></lucide-icon>
|
||||
<span>{{ q.prerequisites!.length }} condition(s) de déblocage</span>
|
||||
<ul class="hub-quest-card-prereq-list">
|
||||
<li *ngFor="let p of q.prerequisites">{{ describePrerequisite(p) }}</li>
|
||||
@for (p of q.prerequisites; track p) {
|
||||
<li>{{ describePrerequisite(p) }}</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
}
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">📜</span> Synopsis</h2>
|
||||
<p class="view-section-body" *ngIf="arc.description?.trim(); else emptyDesc">{{ arc.description }}</p>
|
||||
<ng-template #emptyDesc><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (arc.description?.trim()) {
|
||||
<p class="view-section-body">{{ arc.description }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="view-row">
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">✨</span> Thèmes principaux</h2>
|
||||
<p class="view-section-body" *ngIf="arc.themes?.trim(); else emptyThemes">{{ arc.themes }}</p>
|
||||
<ng-template #emptyThemes><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (arc.themes?.trim()) {
|
||||
<p class="view-section-body">{{ arc.themes }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">⚖️</span> Enjeux globaux</h2>
|
||||
<p class="view-section-body" *ngIf="arc.stakes?.trim(); else emptyStakes">{{ arc.stakes }}</p>
|
||||
<ng-template #emptyStakes><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (arc.stakes?.trim()) {
|
||||
<p class="view-section-body">{{ arc.stakes }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎁</span> Récompenses et progression</h2>
|
||||
<p class="view-section-body" *ngIf="arc.rewards?.trim(); else emptyRewards">{{ arc.rewards }}</p>
|
||||
<ng-template #emptyRewards><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (arc.rewards?.trim()) {
|
||||
<p class="view-section-body">{{ arc.rewards }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎬</span> Dénouement prévu</h2>
|
||||
<p class="view-section-body" *ngIf="arc.resolution?.trim(); else emptyResolution">{{ arc.resolution }}</p>
|
||||
<ng-template #emptyResolution><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (arc.resolution?.trim()) {
|
||||
<p class="view-section-body">{{ arc.resolution }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<!-- Notes MJ (bloc privé rouge discret) -->
|
||||
<section class="view-section view-section--private" *ngIf="arc.gmNotes?.trim()">
|
||||
@if (arc.gmNotes?.trim()) {
|
||||
<section class="view-section view-section--private">
|
||||
<h2 class="view-section-title">
|
||||
<span class="view-section-icon">🔒</span>
|
||||
Notes et planification du MJ
|
||||
</h2>
|
||||
<p class="view-section-body">{{ arc.gmNotes }}</p>
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- Pages Lore liées (chips cliquables) -->
|
||||
<section class="view-section" *ngIf="loreId && (arc.relatedPageIds?.length ?? 0) > 0">
|
||||
@if (loreId && (arc.relatedPageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔗</span> Pages Lore associées</h2>
|
||||
<div class="view-chips">
|
||||
@for (relId of arc.relatedPageIds; track relId) {
|
||||
<a class="view-chip"
|
||||
*ngFor="let relId of arc.relatedPageIds"
|
||||
[routerLink]="['/lore', loreId, 'pages', relId]">
|
||||
{{ titleOfRelated(relId) }}
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
@@ -25,8 +25,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-arc-view',
|
||||
standalone: true,
|
||||
imports: [CommonModule, RouterModule, LucideAngularModule, ImageGalleryComponent],
|
||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent],
|
||||
templateUrl: './arc-view.component.html',
|
||||
styleUrls: ['./arc-view.component.scss']
|
||||
})
|
||||
|
||||
@@ -225,6 +225,14 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
route: `/campaigns/${campaignId}/notebooks`
|
||||
};
|
||||
|
||||
// Catalogues d'objets (boutiques, butins…) → page de liste (outil).
|
||||
const catalogsNode: TreeItem = {
|
||||
id: 'item-catalogs-root',
|
||||
label: 'Catalogues d\'objets',
|
||||
iconKey: 'package',
|
||||
route: `/campaigns/${campaignId}/item-catalogs`
|
||||
};
|
||||
|
||||
// Importer un PDF de campagne → arborescence (outil, comme tables & ateliers).
|
||||
const importNode: TreeItem = {
|
||||
id: 'import-pdf-root',
|
||||
@@ -233,7 +241,7 @@ export function buildCampaignTree(campaignId: string, data: CampaignTreeData): T
|
||||
route: `/campaigns/${campaignId}/import`
|
||||
};
|
||||
|
||||
return [...arcNodes, npcsNode, tablesNode, notebooksNode, importNode];
|
||||
return [...arcNodes, npcsNode, tablesNode, notebooksNode, catalogsNode, importNode];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -40,7 +40,9 @@
|
||||
<label for="campaign-lore">Univers associé</label>
|
||||
<select id="campaign-lore" formControlName="loreId">
|
||||
<option value="">— Aucun univers (campagne libre) —</option>
|
||||
<option *ngFor="let lore of availableLores" [value]="lore.id">{{ lore.name }}</option>
|
||||
@for (lore of availableLores; track lore) {
|
||||
<option [value]="lore.id">{{ lore.name }}</option>
|
||||
}
|
||||
</select>
|
||||
<p class="hint">
|
||||
Optionnel. Si associée, vous pourrez lier arcs, chapitres et scènes aux pages du Lore.
|
||||
@@ -50,14 +52,19 @@
|
||||
|
||||
<div class="field">
|
||||
<label for="campaign-game-system">Système de JDR</label>
|
||||
<select *ngIf="!creatingGameSystem" id="campaign-game-system" formControlName="gameSystemId">
|
||||
@if (!creatingGameSystem) {
|
||||
<select id="campaign-game-system" formControlName="gameSystemId">
|
||||
<option value="">— Aucun (campagne générique) —</option>
|
||||
<option *ngFor="let gs of availableGameSystems" [value]="gs.id">{{ gs.name }}</option>
|
||||
@for (gs of availableGameSystems; track gs) {
|
||||
<option [value]="gs.id">{{ gs.name }}</option>
|
||||
}
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">+ Créer un nouveau système…</option>
|
||||
</select>
|
||||
}
|
||||
|
||||
<!-- Mode creation inline : remplace temporairement le select. -->
|
||||
<div *ngIf="creatingGameSystem" class="inline-create">
|
||||
@if (creatingGameSystem) {
|
||||
<div class="inline-create">
|
||||
<input
|
||||
type="text"
|
||||
[(ngModel)]="newGameSystemName"
|
||||
@@ -83,17 +90,22 @@
|
||||
et le reste depuis la section "Systèmes" plus tard.
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<p *ngIf="!creatingGameSystem" class="hint">
|
||||
@if (!creatingGameSystem) {
|
||||
<p class="hint">
|
||||
Optionnel. Si défini, l'IA injectera les règles du système (classes, combat, lore...)
|
||||
dans ses suggestions pour respecter les mécaniques du JDR.
|
||||
</p>
|
||||
<p *ngIf="!creatingGameSystem" class="hint hint-warning">
|
||||
}
|
||||
@if (!creatingGameSystem) {
|
||||
<p class="hint hint-warning">
|
||||
⚠️ Le système de jeu choisi détermine aussi le <strong>template des fiches de PJ et PNJ</strong>.
|
||||
Le changer plus tard rendra les champs des fiches existantes invisibles
|
||||
(les données restent stockées mais ne s'afficheront qu'en revenant à l'ancien système).
|
||||
Choisissez bien dès le départ si possible.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="info-box">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, BookCopy, X, Plus, Check } from 'lucide-angular';
|
||||
@@ -22,8 +22,7 @@ export interface CampaignCreatePayload {
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-create',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, FormsModule, LucideAngularModule],
|
||||
imports: [ReactiveFormsModule, FormsModule, LucideAngularModule],
|
||||
templateUrl: './campaign-create.component.html',
|
||||
styleUrls: ['./campaign-create.component.scss']
|
||||
})
|
||||
|
||||
@@ -1,27 +1,30 @@
|
||||
<div class="campaign-detail" *ngIf="campaign">
|
||||
|
||||
@if (campaign) {
|
||||
<div class="campaign-detail">
|
||||
<!-- ============ Header : mode lecture ============ -->
|
||||
<div class="detail-header" *ngIf="!editing">
|
||||
@if (!editing) {
|
||||
<div class="detail-header">
|
||||
<div class="header-texts">
|
||||
<h1>{{ campaign.name }}</h1>
|
||||
<p class="description">{{ campaign.description }}</p>
|
||||
<div class="meta">
|
||||
<span class="badge">{{ campaign.playerCount || 0 }} joueurs</span>
|
||||
|
||||
<!-- Badge "Univers" : lien vers le Lore associé si présent -->
|
||||
<a *ngIf="linkedLore"
|
||||
@if (linkedLore) {
|
||||
<a
|
||||
class="badge badge-lore"
|
||||
[routerLink]="['/lore', linkedLore.id]"
|
||||
title="Ouvrir l'univers associé">
|
||||
<lucide-icon [img]="Globe" [size]="12"></lucide-icon>
|
||||
{{ linkedLore.name }}
|
||||
</a>
|
||||
|
||||
}
|
||||
<!-- Campagne liée à un Lore qui n'existe plus (supprimé ailleurs) -->
|
||||
<span *ngIf="campaign.loreId && !linkedLore" class="badge badge-lore-missing" title="L'univers associé est introuvable">
|
||||
@if (campaign.loreId && !linkedLore) {
|
||||
<span class="badge badge-lore-missing" title="L'univers associé est introuvable">
|
||||
<lucide-icon [img]="Globe" [size]="12"></lucide-icon>
|
||||
Univers introuvable
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
@@ -35,9 +38,10 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
}
|
||||
<!-- ============ Header : mode édition inline ============ -->
|
||||
<div class="detail-header edit-mode" *ngIf="editing">
|
||||
@if (editing) {
|
||||
<div class="detail-header edit-mode">
|
||||
<div class="field">
|
||||
<label>Nom</label>
|
||||
<input type="text" [(ngModel)]="editName" name="editName" required />
|
||||
@@ -50,21 +54,27 @@
|
||||
<label>Univers associé</label>
|
||||
<select [(ngModel)]="editLoreId" name="editLoreId">
|
||||
<option value="">— Aucun univers (campagne libre) —</option>
|
||||
<option *ngFor="let lore of availableLores" [value]="lore.id">{{ lore.name }}</option>
|
||||
@for (lore of availableLores; track lore) {
|
||||
<option [value]="lore.id">{{ lore.name }}</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Système de JDR</label>
|
||||
<select *ngIf="!creatingGameSystem"
|
||||
@if (!creatingGameSystem) {
|
||||
<select
|
||||
[(ngModel)]="editGameSystemId"
|
||||
name="editGameSystemId"
|
||||
(ngModelChange)="onEditGameSystemChange($event)">
|
||||
<option value="">— Aucun (générique) —</option>
|
||||
<option *ngFor="let gs of availableGameSystems" [value]="gs.id">{{ gs.name }}</option>
|
||||
@for (gs of availableGameSystems; track gs) {
|
||||
<option [value]="gs.id">{{ gs.name }}</option>
|
||||
}
|
||||
<option [value]="CREATE_GAMESYSTEM_SENTINEL">+ Créer un nouveau système…</option>
|
||||
</select>
|
||||
|
||||
<div *ngIf="creatingGameSystem" class="inline-create">
|
||||
}
|
||||
@if (creatingGameSystem) {
|
||||
<div class="inline-create">
|
||||
<input
|
||||
type="text"
|
||||
[(ngModel)]="newGameSystemName"
|
||||
@@ -86,6 +96,7 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn-primary" (click)="saveEdit()" [disabled]="!editName.trim()">
|
||||
@@ -96,51 +107,57 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="detail-section personas-section" *ngIf="!editing">
|
||||
}
|
||||
@if (!editing) {
|
||||
<section class="detail-section personas-section">
|
||||
<div class="section-header">
|
||||
<h2>Personnages</h2>
|
||||
</div>
|
||||
|
||||
<!-- Les PJ ne sont plus rattachés à la campagne mais à une Partie (Playthrough) :
|
||||
ils se gèrent depuis la page d'une Partie. Ici on ne liste que les PNJ
|
||||
(donnée de scénario, partagée par toutes les Parties). -->
|
||||
|
||||
<!-- Sous-section : Personnages non-joueurs (PNJ) -->
|
||||
<div class="persona-subsection">
|
||||
<div class="subsection-header">
|
||||
<h3>
|
||||
<lucide-icon [img]="Drama" [size]="16"></lucide-icon>
|
||||
Personnages non-joueurs
|
||||
<span class="count-badge" *ngIf="npcs.length > 0">{{ npcs.length }}</span>
|
||||
@if (npcs.length > 0) {
|
||||
<span class="count-badge">{{ npcs.length }}</span>
|
||||
}
|
||||
</h3>
|
||||
<button class="btn-add" (click)="createNpc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Nouveau PNJ
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="characters-grid" *ngIf="npcs.length > 0">
|
||||
<div class="character-card" *ngFor="let npc of npcs" (click)="viewNpc(npc)">
|
||||
@if (npcs.length > 0) {
|
||||
<div class="characters-grid">
|
||||
@for (npc of npcs; track npc) {
|
||||
<div class="character-card" (click)="viewNpc(npc)">
|
||||
<lucide-icon [img]="Drama" [size]="20" class="character-icon character-icon--npc"></lucide-icon>
|
||||
<div class="character-info">
|
||||
<span class="character-name">{{ npc.name }}</span>
|
||||
<span class="character-snippet">{{ personaSnippet(npc) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="empty-state empty-state--compact" *ngIf="npcs.length === 0">
|
||||
}
|
||||
@if (npcs.length === 0) {
|
||||
<div class="empty-state empty-state--compact">
|
||||
<p>Aucun PNJ pour le moment.</p>
|
||||
<button class="btn-add-first" (click)="createNpc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon>
|
||||
Créer votre premier PNJ
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail-section arcs-section" *ngIf="!editing">
|
||||
}
|
||||
@if (!editing) {
|
||||
<section class="detail-section arcs-section">
|
||||
<div class="section-header">
|
||||
<h2>Arcs narratifs</h2>
|
||||
<div class="section-header-actions">
|
||||
@@ -150,16 +167,19 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="arcs-grid" *ngIf="arcs.length > 0">
|
||||
<div class="arc-card" *ngFor="let arc of arcs" (click)="openArc(arc)">
|
||||
@if (arcs.length > 0) {
|
||||
<div class="arcs-grid">
|
||||
@for (arc of arcs; track arc) {
|
||||
<div class="arc-card" (click)="openArc(arc)">
|
||||
<lucide-icon [img]="Swords" [size]="24" class="arc-icon"></lucide-icon>
|
||||
<span class="arc-name">{{ arc.name }}</span>
|
||||
<span class="arc-meta">{{ chapterCountByArc[arc.id!] || 0 }} chapitres</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="empty-state" *ngIf="arcs.length === 0">
|
||||
}
|
||||
@if (arcs.length === 0) {
|
||||
<div class="empty-state">
|
||||
<lucide-icon [img]="Swords" [size]="40" class="empty-icon"></lucide-icon>
|
||||
<p>Aucun arc narratif pour le moment.</p>
|
||||
<button class="btn-add-first" (click)="createArc()">
|
||||
@@ -167,10 +187,12 @@
|
||||
Créer votre premier arc
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- ============ Parties (Playthroughs) ============ -->
|
||||
<section class="detail-section playthroughs-section" *ngIf="!editing">
|
||||
@if (!editing) {
|
||||
<section class="detail-section playthroughs-section">
|
||||
<div class="section-header">
|
||||
<h2>
|
||||
<lucide-icon [img]="Dices" [size]="18"></lucide-icon>
|
||||
@@ -181,26 +203,31 @@
|
||||
Nouvelle partie
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="playthroughs-grid" *ngIf="playthroughs.length > 0">
|
||||
@if (playthroughs.length > 0) {
|
||||
<div class="playthroughs-grid">
|
||||
@for (p of playthroughs; track p) {
|
||||
<div class="playthrough-card"
|
||||
*ngFor="let p of playthroughs"
|
||||
(click)="openPlaythrough(p)">
|
||||
<lucide-icon [img]="Dices" [size]="22" class="playthrough-icon"></lucide-icon>
|
||||
<div class="playthrough-info">
|
||||
<span class="playthrough-name">{{ p.name }}</span>
|
||||
<span class="playthrough-meta" *ngIf="p.description">{{ p.description }}</span>
|
||||
@if (p.description) {
|
||||
<span class="playthrough-meta">{{ p.description }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="empty-state empty-state--compact" *ngIf="playthroughs.length === 0">
|
||||
}
|
||||
@if (playthroughs.length === 0) {
|
||||
<div class="empty-state empty-state--compact">
|
||||
<p>Aucune partie. Créez-en une pour démarrer une session avec une table.</p>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- Sessions retirées : elles vivent désormais dans une Partie.
|
||||
Les faits narratifs sont définis dans les conditions de chaque quête
|
||||
(chapter-edit > « Conditions de déblocage »). -->
|
||||
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Swords, Plus, Globe, Pencil, Trash2, Dices, Drama, Check, Play, Upload, Sparkles } from 'lucide-angular';
|
||||
@@ -27,8 +27,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaign-detail',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, LucideAngularModule, RouterLink],
|
||||
imports: [FormsModule, LucideAngularModule, RouterLink],
|
||||
templateUrl: './campaign-detail.component.html',
|
||||
styleUrls: ['./campaign-detail.component.scss']
|
||||
})
|
||||
|
||||
@@ -13,44 +13,54 @@
|
||||
</div>
|
||||
|
||||
<!-- Étape 1 : upload (masqué une fois en revue) -->
|
||||
<section class="upload-area" *ngIf="!reviewing">
|
||||
@if (!reviewing) {
|
||||
<section class="upload-area">
|
||||
<input #pdfInput type="file" accept="application/pdf,.pdf" hidden (change)="onPdfSelected($event)" />
|
||||
<button type="button" class="btn-primary big" [disabled]="importing" (click)="pdfInput.click()">
|
||||
<lucide-icon [img]="Upload" [size]="16"></lucide-icon>
|
||||
{{ importing ? 'Import en cours…' : 'Choisir un PDF de campagne' }}
|
||||
</button>
|
||||
|
||||
<!-- Progression live -->
|
||||
<div class="import-progress" *ngIf="importing">
|
||||
@if (importing) {
|
||||
<div class="import-progress">
|
||||
<p class="import-phase">{{ importPhase }}</p>
|
||||
<div class="progress-bar" *ngIf="importProgress">
|
||||
@if (importProgress) {
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill"
|
||||
[style.width.%]="importProgress.total ? (importProgress.current / importProgress.total) * 100 : 0">
|
||||
</div>
|
||||
</div>
|
||||
<p class="import-counts" *ngIf="importCounts">
|
||||
Trouvé jusqu'ici : {{ importCounts.arcs }} arc(s) · {{ importCounts.chapters }} chapitre(s) · {{ importCounts.scenes }} scène(s)
|
||||
}
|
||||
@if (importCounts) {
|
||||
<p class="import-counts">
|
||||
Trouvé jusqu'ici : {{ importCounts.arcs }} arc(s) · {{ importCounts.chapters }} chapitre(s) · {{ importCounts.scenes }} scène(s) · {{ importCounts.npcs }} PNJ
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<p class="import-error" *ngIf="importError">{{ importError }}</p>
|
||||
}
|
||||
@if (importError) {
|
||||
<p class="import-error">{{ importError }}</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
<!-- Étape 2 : revue de l'arbre éditable -->
|
||||
<section class="review-area" *ngIf="reviewing">
|
||||
@if (reviewing) {
|
||||
<section class="review-area">
|
||||
<div class="review-header">
|
||||
<p class="review-summary">
|
||||
À créer : <strong>{{ arcCount }}</strong> nouvel(s) arc(s),
|
||||
<strong>{{ chapterCount }}</strong> chapitre(s),
|
||||
<strong>{{ sceneCount }}</strong> scène(s).
|
||||
<strong>{{ sceneCount }}</strong> scène(s)@if (npcs.length > 0) {<span>,
|
||||
<strong>{{ npcCount }}</strong> PNJ</span>}.
|
||||
Les éléments <em>« déjà présent »</em> (grisés) sont affichés pour situer les ajouts ;
|
||||
ils ne seront pas recréés. Modifiez les nouveaux, puis créez.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="tree">
|
||||
<!-- Arc -->
|
||||
<div class="arc-card" *ngFor="let arc of tree; let ai = index">
|
||||
@for (arc of tree; track arc; let ai = $index) {
|
||||
<div class="arc-card">
|
||||
<div class="node-head arc-head" [class.existing-node]="arc.existing">
|
||||
<button type="button" class="btn-collapse" (click)="toggleArc(arc)">
|
||||
<lucide-icon [img]="arc.collapsed ? ChevronRight : ChevronDown" [size]="16"></lucide-icon>
|
||||
@@ -58,26 +68,33 @@
|
||||
<lucide-icon [img]="Swords" [size]="16" class="node-icon"></lucide-icon>
|
||||
<input type="text" class="node-name" [(ngModel)]="arc.name" [name]="'arc-' + ai"
|
||||
[readonly]="arc.existing" placeholder="Nom de l'arc" />
|
||||
<span class="badge-existing" *ngIf="arc.existing">déjà présent</span>
|
||||
<button type="button" class="btn-remove" *ngIf="!arc.existing" (click)="removeArc(ai)" title="Supprimer l'arc">
|
||||
@if (arc.existing) {
|
||||
<span class="badge-existing">déjà présent</span>
|
||||
}
|
||||
@if (!arc.existing) {
|
||||
<button type="button" class="btn-remove" (click)="removeArc(ai)" title="Supprimer l'arc">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="node-body" *ngIf="!arc.collapsed">
|
||||
<div class="arc-type-toggle" *ngIf="!arc.existing">
|
||||
@if (!arc.collapsed) {
|
||||
<div class="node-body">
|
||||
@if (!arc.existing) {
|
||||
<div class="arc-type-toggle">
|
||||
<span class="toggle-label">Type :</span>
|
||||
<button type="button" class="type-btn" [class.active]="arc.type === 'LINEAR'"
|
||||
(click)="setArcType(arc, 'LINEAR')">Linéaire</button>
|
||||
<button type="button" class="type-btn" [class.active]="arc.type === 'HUB'"
|
||||
(click)="setArcType(arc, 'HUB')">Hub (quêtes)</button>
|
||||
</div>
|
||||
|
||||
<textarea class="node-desc" *ngIf="!arc.existing" [(ngModel)]="arc.description" [name]="'arc-desc-' + ai"
|
||||
}
|
||||
@if (!arc.existing) {
|
||||
<textarea class="node-desc" [(ngModel)]="arc.description" [name]="'arc-desc-' + ai"
|
||||
rows="2" placeholder="Synopsis de l'arc (optionnel)"></textarea>
|
||||
|
||||
}
|
||||
<!-- Chapitres -->
|
||||
<div class="chapter-card" *ngFor="let chapter of arc.chapters; let ci = index">
|
||||
@for (chapter of arc.chapters; track chapter; let ci = $index) {
|
||||
<div class="chapter-card">
|
||||
<div class="node-head chapter-head" [class.existing-node]="chapter.existing">
|
||||
<button type="button" class="btn-collapse" (click)="toggleChapter(chapter)">
|
||||
<lucide-icon [img]="chapter.collapsed ? ChevronRight : ChevronDown" [size]="14"></lucide-icon>
|
||||
@@ -85,18 +102,24 @@
|
||||
<lucide-icon [img]="BookOpen" [size]="14" class="node-icon"></lucide-icon>
|
||||
<input type="text" class="node-name" [(ngModel)]="chapter.name" [name]="'chap-' + ai + '-' + ci"
|
||||
[readonly]="chapter.existing" placeholder="Nom du chapitre" />
|
||||
<span class="badge-existing" *ngIf="chapter.existing">déjà présent</span>
|
||||
<button type="button" class="btn-remove" *ngIf="!chapter.existing" (click)="removeChapter(arc, ci)" title="Supprimer le chapitre">
|
||||
@if (chapter.existing) {
|
||||
<span class="badge-existing">déjà présent</span>
|
||||
}
|
||||
@if (!chapter.existing) {
|
||||
<button type="button" class="btn-remove" (click)="removeChapter(arc, ci)" title="Supprimer le chapitre">
|
||||
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="node-body" *ngIf="!chapter.collapsed">
|
||||
<textarea class="node-desc" *ngIf="!chapter.existing" [(ngModel)]="chapter.description" [name]="'chap-desc-' + ai + '-' + ci"
|
||||
@if (!chapter.collapsed) {
|
||||
<div class="node-body">
|
||||
@if (!chapter.existing) {
|
||||
<textarea class="node-desc" [(ngModel)]="chapter.description" [name]="'chap-desc-' + ai + '-' + ci"
|
||||
rows="2" placeholder="Synopsis du chapitre (optionnel)"></textarea>
|
||||
|
||||
}
|
||||
<!-- Scènes -->
|
||||
<div class="scene-card" *ngFor="let scene of chapter.scenes; let si = index"
|
||||
@for (scene of chapter.scenes; track scene; let si = $index) {
|
||||
<div class="scene-card"
|
||||
[class.existing-node]="scene.existing">
|
||||
<div class="scene-row">
|
||||
<lucide-icon [img]="MapPin" [size]="13" class="node-icon scene-icon"></lucide-icon>
|
||||
@@ -104,35 +127,44 @@
|
||||
<input type="text" class="node-name" [(ngModel)]="scene.name"
|
||||
[name]="'scene-' + ai + '-' + ci + '-' + si" [readonly]="scene.existing"
|
||||
placeholder="Nom de la scène" />
|
||||
<input type="text" class="node-desc-inline" *ngIf="!scene.existing" [(ngModel)]="scene.description"
|
||||
@if (!scene.existing) {
|
||||
<input type="text" class="node-desc-inline" [(ngModel)]="scene.description"
|
||||
[name]="'scene-desc-' + ai + '-' + ci + '-' + si" placeholder="Synopsis (optionnel)" />
|
||||
}
|
||||
</div>
|
||||
<span class="badge-existing" *ngIf="scene.existing">déjà présent</span>
|
||||
<button type="button" class="btn-details" *ngIf="!scene.existing" (click)="toggleDetails(scene)"
|
||||
@if (scene.existing) {
|
||||
<span class="badge-existing">déjà présent</span>
|
||||
}
|
||||
@if (!scene.existing) {
|
||||
<button type="button" class="btn-details" (click)="toggleDetails(scene)"
|
||||
title="Narration joueurs, notes MJ, pièces">
|
||||
<lucide-icon [img]="scene.detailsOpen ? ChevronDown : ChevronRight" [size]="12"></lucide-icon>
|
||||
Détails<span *ngIf="scene.rooms.length"> · {{ scene.rooms.length }} pièce(s)</span>
|
||||
Détails@if (scene.rooms.length) {
|
||||
<span> · {{ scene.rooms.length }} pièce(s)</span>
|
||||
}
|
||||
</button>
|
||||
<button type="button" class="btn-remove" *ngIf="!scene.existing" (click)="removeScene(chapter, si)" title="Supprimer la scène">
|
||||
}
|
||||
@if (!scene.existing) {
|
||||
<button type="button" class="btn-remove" (click)="removeScene(chapter, si)" title="Supprimer la scène">
|
||||
<lucide-icon [img]="Trash2" [size]="13"></lucide-icon>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="scene-details" *ngIf="scene.detailsOpen && !scene.existing">
|
||||
@if (scene.detailsOpen && !scene.existing) {
|
||||
<div class="scene-details">
|
||||
<label class="field-label">À lire aux joueurs</label>
|
||||
<textarea class="node-desc" [(ngModel)]="scene.playerNarration"
|
||||
[name]="'scene-pn-' + ai + '-' + ci + '-' + si" rows="3"
|
||||
placeholder="Texte d'encadré lu aux joueurs (optionnel)"></textarea>
|
||||
|
||||
<label class="field-label">Notes MJ</label>
|
||||
<textarea class="node-desc" [(ngModel)]="scene.gmNotes"
|
||||
[name]="'scene-gm-' + ai + '-' + ci + '-' + si" rows="3"
|
||||
placeholder="Secrets, développement, conséquences (optionnel)"></textarea>
|
||||
|
||||
<!-- Pièces (donjon) : vide = scène narrative classique -->
|
||||
<span class="field-label">Pièces (lieu explorable)</span>
|
||||
<div class="rooms">
|
||||
<div class="room-row" *ngFor="let room of scene.rooms; let ri = index">
|
||||
@for (room of scene.rooms; track room; let ri = $index) {
|
||||
<div class="room-row">
|
||||
<input type="text" class="room-name" [(ngModel)]="room.name"
|
||||
[name]="'room-' + ai + '-' + ci + '-' + si + '-' + ri" placeholder="Pièce" />
|
||||
<input type="text" class="room-field" [(ngModel)]="room.description"
|
||||
@@ -145,32 +177,64 @@
|
||||
<lucide-icon [img]="Trash2" [size]="12"></lucide-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
<button type="button" class="btn-add-inline" (click)="addRoom(scene)">
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Pièce
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
}
|
||||
<button type="button" class="btn-add-inline" (click)="addScene(chapter)">
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Scène
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
}
|
||||
<button type="button" class="btn-add-inline" (click)="addChapter(arc)">
|
||||
<lucide-icon [img]="Plus" [size]="12"></lucide-icon> Chapitre
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
}
|
||||
<button type="button" class="btn-add" (click)="addArc()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Ajouter un arc
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="apply-error" *ngIf="applyError">{{ applyError }}</p>
|
||||
<!-- PNJ détectés dans le PDF : revue par cases à cocher -->
|
||||
@if (npcs.length > 0) {
|
||||
<div class="npc-review">
|
||||
<h3>PNJ et créatures détectés ({{ npcs.length }})</h3>
|
||||
<p class="hint">
|
||||
Cochez ceux à créer dans la campagne (description issue du livre).
|
||||
Ceux déjà présents dans la campagne sont grisés et ne seront pas recréés.
|
||||
</p>
|
||||
<ul class="npc-list">
|
||||
@for (npc of npcs; track npc.name) {
|
||||
<li class="npc-row" [class.npc-existing]="npc.existing">
|
||||
<label class="npc-check">
|
||||
<input type="checkbox" [(ngModel)]="npc.selected" [disabled]="npc.existing">
|
||||
<strong>{{ npc.name }}</strong>
|
||||
@if (npc.existing) {
|
||||
<em class="npc-tag">déjà présent</em>
|
||||
}
|
||||
</label>
|
||||
@if (npc.description) {
|
||||
<p class="npc-desc">{{ npc.description }}</p>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (applyError) {
|
||||
<p class="apply-error">{{ applyError }}</p>
|
||||
}
|
||||
<div class="review-actions">
|
||||
<button type="button" class="btn-primary" [disabled]="applying || !hasNewContent" (click)="apply()">
|
||||
<lucide-icon [img]="Check" [size]="16"></lucide-icon>
|
||||
@@ -179,5 +243,6 @@
|
||||
<button type="button" class="btn-secondary" (click)="cancel()">Annuler</button>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
</div>
|
||||
|
||||
@@ -321,3 +321,49 @@
|
||||
gap: 0.6rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
// --- Revue des PNJ détectés dans le PDF ------------------------------------
|
||||
.npc-review {
|
||||
margin-top: 1.25rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--border-color, #2e2e3a);
|
||||
border-radius: 8px;
|
||||
|
||||
h3 { margin: 0 0 0.25rem; font-size: 1rem; }
|
||||
.hint { margin: 0 0 0.75rem; font-size: 0.85rem; opacity: 0.75; }
|
||||
}
|
||||
|
||||
.npc-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.npc-row {
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
|
||||
&.npc-existing { opacity: 0.55; }
|
||||
|
||||
.npc-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.npc-tag {
|
||||
font-size: 0.75rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.npc-desc {
|
||||
margin: 0.3rem 0 0 1.6rem;
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import {
|
||||
@@ -13,7 +13,7 @@ import { NpcService } from '../../../services/npc.service';
|
||||
import { RandomTableService } from '../../../services/random-table.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { PageTitleService } from '../../../services/page-title.service';
|
||||
import { ArcKind, ArcProposal, ChapterProposal, SceneProposal } from '../../../services/campaign-import.model';
|
||||
import { ArcKind, ArcProposal, ChapterProposal, NpcProposal, SceneProposal } from '../../../services/campaign-import.model';
|
||||
import { CampaignImportProposal } from '../../../services/campaign-import.model';
|
||||
import { loadCampaignTreeData, CampaignTreeData } from '../../campaign-tree.helper';
|
||||
import { of } from 'rxjs';
|
||||
@@ -37,6 +37,11 @@ interface ArcNode {
|
||||
name: string; description: string; type: ArcKind; chapters: ChapterNode[]; collapsed: boolean;
|
||||
existing: boolean; existingId?: string;
|
||||
}
|
||||
/**
|
||||
* PNJ détecté dans le PDF, à cocher à la revue. `existing` = un PNJ du même nom
|
||||
* existe déjà dans la campagne (décoché et non créable, anti-doublon).
|
||||
*/
|
||||
interface NpcNode { name: string; description: string; selected: boolean; existing: boolean; }
|
||||
|
||||
/**
|
||||
* Page d'import d'un PDF de campagne → arbre arc/chapitre/scène.
|
||||
@@ -47,8 +52,7 @@ interface ArcNode {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-campaign-import',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, LucideAngularModule],
|
||||
imports: [FormsModule, LucideAngularModule],
|
||||
templateUrl: './campaign-import.component.html',
|
||||
styleUrls: ['./campaign-import.component.scss']
|
||||
})
|
||||
@@ -70,7 +74,7 @@ export class CampaignImportComponent implements OnInit {
|
||||
importing = false;
|
||||
importPhase = '';
|
||||
importProgress: { current: number; total: number } | null = null;
|
||||
importCounts: { arcs: number; chapters: number; scenes: number } | null = null;
|
||||
importCounts: { arcs: number; chapters: number; scenes: number; npcs: number } | null = null;
|
||||
importError: string | null = null;
|
||||
/** Vrai une fois la proposition reçue (on affiche l'arbre éditable). */
|
||||
reviewing = false;
|
||||
@@ -78,6 +82,9 @@ export class CampaignImportComponent implements OnInit {
|
||||
// --- Arbre éditable ---
|
||||
tree: ArcNode[] = [];
|
||||
|
||||
/** PNJ détectés dans le PDF (revue par cases à cocher). */
|
||||
npcs: NpcNode[] = [];
|
||||
|
||||
/** Structure actuelle de la campagne (chargée pour la fusion à la revue). */
|
||||
private existingData: CampaignTreeData | null = null;
|
||||
|
||||
@@ -137,17 +144,21 @@ export class CampaignImportComponent implements OnInit {
|
||||
} else {
|
||||
this.importPhase = `Analyse de la campagne… (${ev.current}/${ev.total})`;
|
||||
this.importProgress = { current: ev.current, total: ev.total };
|
||||
this.importCounts = { arcs: ev.arcCount, chapters: ev.chapterCount, scenes: ev.sceneCount };
|
||||
this.importCounts = {
|
||||
arcs: ev.arcCount, chapters: ev.chapterCount,
|
||||
scenes: ev.sceneCount, npcs: ev.npcCount ?? 0
|
||||
};
|
||||
}
|
||||
} else if (ev.type === 'done') {
|
||||
this.importing = false;
|
||||
this.importPhase = '';
|
||||
this.importProgress = null;
|
||||
if ((ev.arcs ?? []).length === 0) {
|
||||
if ((ev.arcs ?? []).length === 0 && (ev.npcs ?? []).length === 0) {
|
||||
this.importError = "Aucune structure narrative détectée dans ce PDF.";
|
||||
this.reviewing = false;
|
||||
} else {
|
||||
this.tree = this.buildMergedTree(ev.arcs);
|
||||
this.tree = this.buildMergedTree(ev.arcs ?? []);
|
||||
this.npcs = this.buildNpcNodes(ev.npcs ?? []);
|
||||
this.reviewing = true;
|
||||
}
|
||||
}
|
||||
@@ -233,6 +244,21 @@ export class CampaignImportComponent implements OnInit {
|
||||
return (a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit la liste de revue des PNJ : cochés par défaut, sauf ceux dont le
|
||||
* nom existe déjà dans la campagne (anti-doublon, affichés grisés).
|
||||
*/
|
||||
private buildNpcNodes(proposals: NpcProposal[]): NpcNode[] {
|
||||
const existingNames = new Set(
|
||||
(this.existingData?.npcs ?? []).map(n => (n.name ?? '').trim().toLowerCase()));
|
||||
return proposals
|
||||
.filter(p => (p.name ?? '').trim())
|
||||
.map(p => {
|
||||
const existing = existingNames.has(p.name.trim().toLowerCase());
|
||||
return { name: p.name.trim(), description: p.description ?? '', selected: !existing, existing };
|
||||
});
|
||||
}
|
||||
|
||||
// --- Mappers proposition → nœud NEUF -------------------------------------
|
||||
|
||||
private newArcNode(a: ArcProposal): ArcNode {
|
||||
@@ -311,9 +337,14 @@ export class CampaignImportComponent implements OnInit {
|
||||
n + a.chapters.reduce((m, c) => m + c.scenes.filter(s => !s.existing && s.name.trim()).length, 0), 0);
|
||||
}
|
||||
|
||||
/** Nombre de PNJ cochés (= qui seront créés). */
|
||||
get npcCount(): number {
|
||||
return this.npcs.filter(n => n.selected && !n.existing).length;
|
||||
}
|
||||
|
||||
/** Vrai s'il y a au moins un nœud nouveau à créer (sinon « Créer » désactivé). */
|
||||
get hasNewContent(): boolean {
|
||||
return this.arcCount > 0 || this.chapterCount > 0 || this.sceneCount > 0;
|
||||
return this.arcCount > 0 || this.chapterCount > 0 || this.sceneCount > 0 || this.npcCount > 0;
|
||||
}
|
||||
|
||||
// --- Application (création) ----------------------------------------------
|
||||
@@ -358,7 +389,10 @@ export class CampaignImportComponent implements OnInit {
|
||||
}))
|
||||
}))
|
||||
}))
|
||||
}))
|
||||
})),
|
||||
npcs: this.npcs
|
||||
.filter(n => n.selected && !n.existing && n.name.trim())
|
||||
.map(n => ({ name: n.name.trim(), description: n.description.trim() }))
|
||||
};
|
||||
|
||||
this.service.applyStructure(this.campaignId, proposal).subscribe({
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
|
||||
<div class="campaigns-grid">
|
||||
|
||||
<div class="campaign-card" *ngFor="let campaign of campaigns" (click)="navigateToDetail(campaign.id!)">
|
||||
@for (campaign of campaigns; track campaign) {
|
||||
<div class="campaign-card" (click)="navigateToDetail(campaign.id!)">
|
||||
<div class="card-header">
|
||||
<span class="status-badge en-cours">En cours</span>
|
||||
<span class="card-date">{{ campaign.playerCount }} joueurs</span>
|
||||
@@ -20,6 +21,7 @@
|
||||
<span>📖 {{ campaign.chapterCount || 0 }} chapitres</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="campaign-card card-new" (click)="openCreateModal()">
|
||||
<div class="new-icon">
|
||||
@@ -35,8 +37,9 @@
|
||||
|
||||
</div>
|
||||
|
||||
@if (showCreateModal) {
|
||||
<app-campaign-create
|
||||
*ngIf="showCreateModal"
|
||||
(close)="onModalClose()"
|
||||
(created)="onCampaignCreated($event)">
|
||||
</app-campaign-create>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { Router } from '@angular/router';
|
||||
import { LucideAngularModule, Map, Plus } from 'lucide-angular';
|
||||
import { CampaignService } from '../services/campaign.service';
|
||||
@@ -9,8 +9,7 @@ import { CampaignCreateComponent, CampaignCreatePayload } from './campaign/campa
|
||||
|
||||
@Component({
|
||||
selector: 'app-campaigns',
|
||||
standalone: true,
|
||||
imports: [CommonModule, LucideAngularModule, CampaignCreateComponent],
|
||||
imports: [LucideAngularModule, CampaignCreateComponent],
|
||||
templateUrl: './campaigns.component.html',
|
||||
styleUrls: ['./campaigns.component.scss']
|
||||
})
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
<div class="page-header">
|
||||
<h1>{{ isHub ? 'Créer une nouvelle quête' : 'Créer un nouveau chapitre' }}</h1>
|
||||
<p class="arc-ref" *ngIf="arcName">{{ isHub ? 'Hub' : 'Arc' }} : {{ arcName }}</p>
|
||||
@if (arcName) {
|
||||
<p class="arc-ref">{{ isHub ? 'Hub' : 'Arc' }} : {{ arcName }}</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="submit()" class="chapter-form">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
@@ -19,8 +19,7 @@ import { CAMPAIGN_ICON_OPTIONS } from '../../campaign-icons';
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-create',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, LucideAngularModule, IconPickerComponent],
|
||||
imports: [ReactiveFormsModule, LucideAngularModule, IconPickerComponent],
|
||||
templateUrl: './chapter-create.component.html',
|
||||
styleUrls: ['./chapter-create.component.scss']
|
||||
})
|
||||
|
||||
@@ -129,7 +129,8 @@
|
||||
</div>
|
||||
|
||||
<!-- ===== Pages Lore associées (B2 cross-context) ===== -->
|
||||
<div class="field" *ngIf="loreId">
|
||||
@if (loreId) {
|
||||
<div class="field">
|
||||
<label>Pages Lore associées</label>
|
||||
<app-lore-link-picker
|
||||
[value]="relatedPageIds"
|
||||
@@ -141,13 +142,16 @@
|
||||
Liez ce chapitre à des PNJ, lieux ou éléments du Lore qui y apparaissent.
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="field" *ngIf="!loreId">
|
||||
@if (!loreId) {
|
||||
<div class="field">
|
||||
<small class="field-hint">
|
||||
💡 Cette campagne n'est associée à aucun univers. Associez-la à un Lore dans l'écran de la campagne
|
||||
pour pouvoir lier ce chapitre à des pages du Lore.
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
|
||||
</form>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
@@ -33,9 +33,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-edit',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
LucideAngularModule,
|
||||
LoreLinkPickerComponent,
|
||||
|
||||
@@ -11,11 +11,14 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="graph-empty" *ngIf="scenes.length === 0">
|
||||
@if (scenes.length === 0) {
|
||||
<div class="graph-empty">
|
||||
<p>Ce chapitre n'a aucune scène. Créez-en pour voir apparaître la carte.</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="graph-container" *ngIf="scenes.length > 0">
|
||||
@if (scenes.length > 0) {
|
||||
<div class="graph-container">
|
||||
<svg #svgEl
|
||||
[attr.width]="svgWidth" [attr.height]="svgHeight"
|
||||
class="graph-svg"
|
||||
@@ -28,14 +31,15 @@
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#b8c0cc" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<g class="edges">
|
||||
<g class="edge" *ngFor="let edge of edges">
|
||||
@for (edge of edges; track edge) {
|
||||
<g class="edge">
|
||||
<line [attr.x1]="edge.x1" [attr.y1]="edge.y1"
|
||||
[attr.x2]="edge.x2" [attr.y2]="edge.y2"
|
||||
stroke="#b8c0cc" stroke-width="2"
|
||||
marker-end="url(#arrowhead)" />
|
||||
<text *ngIf="edge.label"
|
||||
@if (edge.label) {
|
||||
<text
|
||||
[attr.x]="edge.labelX"
|
||||
[attr.y]="edge.labelY"
|
||||
text-anchor="middle"
|
||||
@@ -44,13 +48,14 @@
|
||||
(pointerdown)="onLabelPointerDown($event, edge)">
|
||||
{{ edge.label }}
|
||||
</text>
|
||||
}
|
||||
</g>
|
||||
}
|
||||
</g>
|
||||
|
||||
<g class="nodes">
|
||||
@for (node of nodes; track node) {
|
||||
<g class="node"
|
||||
[class.dragging]="draggingId === node.id"
|
||||
*ngFor="let node of nodes"
|
||||
(pointerdown)="onPointerDown($event, node)">
|
||||
<title>{{ node.name }}</title>
|
||||
<rect [attr.x]="node.x" [attr.y]="node.y"
|
||||
@@ -63,12 +68,13 @@
|
||||
{{ node.displayName }}
|
||||
</text>
|
||||
</g>
|
||||
}
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
<small class="graph-hint">
|
||||
💡 Cliquez sur une scène pour l'ouvrir, ou glissez-la pour réorganiser la carte. Les scènes non reliées au point d'entrée (scène d'ordre 1) apparaissent en bas.
|
||||
</small>
|
||||
</div>
|
||||
}
|
||||
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { LucideAngularModule, ArrowLeft } from 'lucide-angular';
|
||||
@@ -21,8 +21,7 @@ interface GraphEdge { key: string; label: string; x1: number; y1: number; x2: nu
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-graph',
|
||||
standalone: true,
|
||||
imports: [CommonModule, RouterModule, LucideAngularModule],
|
||||
imports: [RouterModule, LucideAngularModule],
|
||||
templateUrl: './chapter-graph.component.html',
|
||||
styleUrls: ['./chapter-graph.component.scss']
|
||||
})
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
<div class="view-page" *ngIf="chapter">
|
||||
|
||||
@if (chapter) {
|
||||
<div class="view-page">
|
||||
<header class="view-header">
|
||||
<div>
|
||||
<h1>
|
||||
<lucide-icon *ngIf="chapter.icon" [img]="resolveCampaignIcon(chapter.icon)" [size]="22" class="title-icon"></lucide-icon>
|
||||
@if (chapter.icon) {
|
||||
<lucide-icon [img]="resolveCampaignIcon(chapter.icon)" [size]="22" class="title-icon"></lucide-icon>
|
||||
}
|
||||
{{ chapter.name }}
|
||||
</h1>
|
||||
<p class="view-subtitle">
|
||||
{{ parentArc?.type === 'HUB' ? 'Quête (Hub)' : 'Chapitre' }}
|
||||
<span class="cond-badge" *ngIf="(chapter.prerequisites?.length ?? 0) > 0"
|
||||
@if ((chapter.prerequisites?.length ?? 0) > 0) {
|
||||
<span class="cond-badge"
|
||||
title="Ce chapitre a des conditions de déblocage : il se débloque en Partie quand elles sont remplies.">
|
||||
<lucide-icon [img]="Lock" [size]="12"></lucide-icon>
|
||||
Conditionnel
|
||||
</span>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
<div class="view-actions">
|
||||
@@ -31,24 +35,23 @@
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Conditions de déblocage (scénario, read-only). Visible pour un arc HUB (quête)
|
||||
OU dès qu'un chapitre linéaire porte des conditions. -->
|
||||
<section class="view-section" *ngIf="parentArc?.type === 'HUB' || (chapter.prerequisites?.length ?? 0) > 0">
|
||||
@if (parentArc?.type === 'HUB' || (chapter.prerequisites?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔒</span> Conditions de déblocage</h2>
|
||||
|
||||
<ng-container *ngIf="(chapter.prerequisites?.length ?? 0) > 0; else noPrereqs">
|
||||
@if ((chapter.prerequisites?.length ?? 0) > 0) {
|
||||
<ul class="view-section-body">
|
||||
<li *ngFor="let p of chapter.prerequisites">{{ describePrerequisite(p) }}</li>
|
||||
@for (p of chapter.prerequisites; track p) {
|
||||
<li>{{ describePrerequisite(p) }}</li>
|
||||
}
|
||||
</ul>
|
||||
<small class="view-section-empty">
|
||||
Pendant une partie, {{ parentArc?.type === 'HUB' ? 'la quête' : 'ce chapitre' }} se débloque
|
||||
dès que toutes ces conditions sont remplies. Le toggle des faits se fait dans l'écran
|
||||
« Faits » de la Partie.
|
||||
</small>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #noPrereqs>
|
||||
} @else {
|
||||
<p class="view-section-empty">
|
||||
Aucune condition — cette quête est disponible dès le début dans chaque Partie.
|
||||
</p>
|
||||
@@ -56,57 +59,69 @@
|
||||
Cliquez sur <strong>Modifier</strong> pour ajouter des conditions
|
||||
(« quête précédente terminée », « à partir de la session N », « quand un fait est vrai »).
|
||||
</p>
|
||||
</ng-template>
|
||||
}
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- Illustrations (rendu editorial magazine) -->
|
||||
<section class="view-section" *ngIf="(chapter.illustrationImageIds?.length ?? 0) > 0">
|
||||
@if ((chapter.illustrationImageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<app-image-gallery [imageIds]="chapter.illustrationImageIds ?? []" [layout]="'EDITORIAL'"></app-image-gallery>
|
||||
</section>
|
||||
|
||||
}
|
||||
<!-- Cartes & plans -->
|
||||
<section class="view-section" *ngIf="(chapter.mapImageIds?.length ?? 0) > 0">
|
||||
@if ((chapter.mapImageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🗺️</span> Cartes & plans</h2>
|
||||
<app-image-gallery [imageIds]="chapter.mapImageIds ?? []" [layout]="'MAPS'"></app-image-gallery>
|
||||
</section>
|
||||
|
||||
}
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">📖</span> Synopsis</h2>
|
||||
<p class="view-section-body" *ngIf="chapter.description?.trim(); else emptyDesc">{{ chapter.description }}</p>
|
||||
<ng-template #emptyDesc><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (chapter.description?.trim()) {
|
||||
<p class="view-section-body">{{ chapter.description }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="view-row">
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🎯</span> Objectifs des joueurs</h2>
|
||||
<p class="view-section-body" *ngIf="chapter.playerObjectives?.trim(); else emptyObj">{{ chapter.playerObjectives }}</p>
|
||||
<ng-template #emptyObj><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (chapter.playerObjectives?.trim()) {
|
||||
<p class="view-section-body">{{ chapter.playerObjectives }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">⚡</span> Enjeux narratifs</h2>
|
||||
<p class="view-section-body" *ngIf="chapter.narrativeStakes?.trim(); else emptyNs">{{ chapter.narrativeStakes }}</p>
|
||||
<ng-template #emptyNs><p class="view-section-empty">Non renseigné</p></ng-template>
|
||||
@if (chapter.narrativeStakes?.trim()) {
|
||||
<p class="view-section-body">{{ chapter.narrativeStakes }}</p>
|
||||
} @else {
|
||||
<p class="view-section-empty">Non renseigné</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="view-section view-section--private" *ngIf="chapter.gmNotes?.trim()">
|
||||
@if (chapter.gmNotes?.trim()) {
|
||||
<section class="view-section view-section--private">
|
||||
<h2 class="view-section-title">
|
||||
<span class="view-section-icon">🔒</span>
|
||||
Notes du Maître de Jeu
|
||||
</h2>
|
||||
<p class="view-section-body">{{ chapter.gmNotes }}</p>
|
||||
</section>
|
||||
|
||||
<section class="view-section" *ngIf="loreId && (chapter.relatedPageIds?.length ?? 0) > 0">
|
||||
}
|
||||
@if (loreId && (chapter.relatedPageIds?.length ?? 0) > 0) {
|
||||
<section class="view-section">
|
||||
<h2 class="view-section-title"><span class="view-section-icon">🔗</span> Pages Lore associées</h2>
|
||||
<div class="view-chips">
|
||||
@for (relId of chapter.relatedPageIds; track relId) {
|
||||
<a class="view-chip"
|
||||
*ngFor="let relId of chapter.relatedPageIds"
|
||||
[routerLink]="['/lore', loreId, 'pages', relId]">
|
||||
{{ titleOfRelated(relId) }}
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { forkJoin, of } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
@@ -24,8 +24,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-chapter-view',
|
||||
standalone: true,
|
||||
imports: [CommonModule, RouterModule, LucideAngularModule, ImageGalleryComponent],
|
||||
imports: [RouterModule, LucideAngularModule, ImageGalleryComponent],
|
||||
templateUrl: './chapter-view.component.html',
|
||||
styleUrls: ['./chapter-view.component.scss']
|
||||
})
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
<lucide-icon [img]="User" [size]="22"></lucide-icon>
|
||||
{{ characterId ? 'Éditer la fiche' : 'Nouveau personnage' }}
|
||||
</h1>
|
||||
@if (characterId) {
|
||||
<button
|
||||
*ngIf="characterId"
|
||||
type="button"
|
||||
class="btn-ai"
|
||||
(click)="toggleChat()"
|
||||
@@ -20,6 +20,7 @@
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -76,22 +77,23 @@
|
||||
</button>
|
||||
<button type="button" class="btn-secondary" (click)="back()">Annuler</button>
|
||||
<span class="spacer"></span>
|
||||
@if (characterId) {
|
||||
<button
|
||||
*ngIf="characterId"
|
||||
type="button"
|
||||
class="btn-danger"
|
||||
(click)="deleteCharacter()">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
Supprimer
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@if (characterId && campaignId) {
|
||||
<app-ai-chat-drawer
|
||||
*ngIf="characterId && campaignId"
|
||||
[campaignId]="campaignId"
|
||||
entityType="character"
|
||||
[entityId]="characterId"
|
||||
@@ -100,3 +102,4 @@
|
||||
[quickSuggestions]="chatQuickSuggestions"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LucideAngularModule, Save, ArrowLeft, User, Trash2, Sparkles } from 'lucide-angular';
|
||||
@@ -26,8 +26,7 @@ import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dia
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-character-edit',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, LucideAngularModule, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
imports: [FormsModule, LucideAngularModule, AiChatDrawerComponent, DynamicFieldsFormComponent, SingleImagePickerComponent],
|
||||
templateUrl: './character-edit.component.html',
|
||||
styleUrls: ['./character-edit.component.scss']
|
||||
})
|
||||
|
||||
@@ -5,10 +5,12 @@
|
||||
Retour
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-ai" (click)="toggleChat()" [class.active]="chatOpen" *ngIf="characterId">
|
||||
@if (characterId) {
|
||||
<button class="btn-ai" (click)="toggleChat()" [class.active]="chatOpen">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
Assistant IA
|
||||
</button>
|
||||
}
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon>
|
||||
Editer
|
||||
@@ -18,11 +20,12 @@
|
||||
<app-persona-view [persona]="character" [templateFields]="templateFields"></app-persona-view>
|
||||
</div>
|
||||
|
||||
@if (characterId && campaignId) {
|
||||
<app-ai-chat-drawer
|
||||
*ngIf="characterId && campaignId"
|
||||
[campaignId]="campaignId"
|
||||
entityType="character"
|
||||
[entityId]="characterId"
|
||||
[isOpen]="chatOpen"
|
||||
(close)="chatOpen = false">
|
||||
</app-ai-chat-drawer>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Edit3, Sparkles } from 'lucide-angular';
|
||||
import { CharacterService } from '../../../services/character.service';
|
||||
@@ -17,8 +17,7 @@ import { AiChatDrawerComponent } from '../../../shared/ai-chat-drawer/ai-chat-dr
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-character-view',
|
||||
standalone: true,
|
||||
imports: [CommonModule, LucideAngularModule, PersonaViewComponent, AiChatDrawerComponent],
|
||||
imports: [LucideAngularModule, PersonaViewComponent, AiChatDrawerComponent],
|
||||
templateUrl: './character-view.component.html',
|
||||
styleUrls: ['./character-view.component.scss']
|
||||
})
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<div class="ice-page">
|
||||
<div class="ice-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-save" (click)="save()" [disabled]="saving">
|
||||
<lucide-icon [img]="Save" [size]="14"></lucide-icon>
|
||||
{{ saving ? 'Enregistrement…' : 'Enregistrer' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<h1>{{ catalogId ? 'Éditer le catalogue' : 'Nouveau catalogue d\'objets' }}</h1>
|
||||
|
||||
@if (errorMessage) {
|
||||
<div class="error">{{ errorMessage }}</div>
|
||||
}
|
||||
|
||||
<div class="form-row">
|
||||
<label for="ic-name">Nom *</label>
|
||||
<input id="ic-name" type="text" [(ngModel)]="name" placeholder="Ex: Échoppe de l'armurier nain">
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label for="ic-desc">Description</label>
|
||||
<textarea id="ic-desc" rows="2" [(ngModel)]="description" placeholder="À quoi sert ce catalogue / cette boutique ?"></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Génération IA -->
|
||||
<div class="ai-box">
|
||||
<div class="ai-title"><lucide-icon [img]="Sparkles" [size]="15"></lucide-icon> Générer avec l'IA</div>
|
||||
<p class="ai-hint">Décris la boutique/le butin ; l'IA propose les objets (revois-les avant d'enregistrer). Contextualisé avec ta campagne.</p>
|
||||
<textarea rows="2" [(ngModel)]="aiPrompt"
|
||||
placeholder="Ex: boutique d'alchimiste dans une cité portuaire, objets exotiques"></textarea>
|
||||
<div class="ai-actions">
|
||||
<button class="btn-ai" (click)="generateWithAI()" [disabled]="generating">
|
||||
<lucide-icon [img]="Sparkles" [size]="14"></lucide-icon>
|
||||
{{ generating ? 'Génération…' : 'Générer' }}
|
||||
</button>
|
||||
@if (aiError) {
|
||||
<span class="ai-error">{{ aiError }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="items-head">
|
||||
<h2>Objets</h2>
|
||||
<button class="btn-mini" (click)="addItem()">
|
||||
<lucide-icon [img]="Plus" [size]="13"></lucide-icon> Ajouter
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="item-row head">
|
||||
<span class="c-name">Nom</span>
|
||||
<span class="c-price">Prix</span>
|
||||
<span class="c-cat">Catégorie</span>
|
||||
<span class="c-desc">Description</span>
|
||||
<span class="c-del"></span>
|
||||
</div>
|
||||
|
||||
@for (it of items; track it; let i = $index) {
|
||||
<div class="item-row">
|
||||
<input class="c-name" type="text" [(ngModel)]="it.name" placeholder="Objet">
|
||||
<input class="c-price" type="text" [(ngModel)]="it.price" placeholder="50 po">
|
||||
<input class="c-cat" type="text" [(ngModel)]="it.category" placeholder="Armes">
|
||||
<input class="c-desc" type="text" [(ngModel)]="it.description" placeholder="Effet / détails">
|
||||
<button class="c-del btn-del" (click)="removeItem(i)" title="Supprimer">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (items.length === 0) {
|
||||
<p class="empty-hint">Aucun objet — clique « Ajouter ».</p>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,87 @@
|
||||
.ice-page { max-width: 980px; margin: 0 auto; padding: 1rem 1.5rem 3rem; }
|
||||
|
||||
.ice-toolbar {
|
||||
display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem;
|
||||
.spacer { flex: 1; }
|
||||
button {
|
||||
display: inline-flex; align-items: center; gap: 0.35rem;
|
||||
padding: 0.4rem 0.8rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.04);
|
||||
color: inherit; cursor: pointer; font-size: 0.85rem;
|
||||
&:hover { background: rgba(255,255,255,0.09); }
|
||||
&:disabled { opacity: 0.5; cursor: default; }
|
||||
}
|
||||
.btn-save { background: #667eea; border-color: #667eea; color: #fff; }
|
||||
.btn-save:hover:not(:disabled) { background: #5568d3; }
|
||||
}
|
||||
|
||||
h1 { font-size: 1.4rem; margin: 0 0 1rem; }
|
||||
h2 { font-size: 1rem; margin: 0; }
|
||||
|
||||
.error {
|
||||
padding: 0.6rem 0.9rem; border-radius: 6px; margin-bottom: 1rem;
|
||||
background: rgba(224,90,90,0.12); border: 1px solid rgba(224,90,90,0.4); color: #e88;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex; flex-direction: column; gap: 0.3rem; margin-bottom: 1rem;
|
||||
label { font-size: 0.85rem; color: var(--color-text-muted, #9aa0aa); }
|
||||
input, textarea {
|
||||
padding: 0.5rem 0.7rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.04);
|
||||
color: inherit; font: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.ai-box {
|
||||
margin: 1rem 0; padding: 0.85rem 1rem; border-radius: 10px;
|
||||
background: rgba(168,130,255,0.08); border: 1px solid rgba(168,130,255,0.28);
|
||||
.ai-title { display: flex; align-items: center; gap: 0.4rem; font-weight: 600; color: #c4a8ff; }
|
||||
.ai-hint { margin: 0.3rem 0 0.5rem; font-size: 0.8rem; color: var(--color-text-muted, #9aa0aa); }
|
||||
textarea {
|
||||
width: 100%; padding: 0.5rem 0.7rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.04); color: inherit; font: inherit;
|
||||
}
|
||||
.ai-actions { display: flex; align-items: center; gap: 0.7rem; margin-top: 0.5rem; }
|
||||
.btn-ai {
|
||||
display: inline-flex; align-items: center; gap: 0.4rem;
|
||||
padding: 0.45rem 0.9rem; border: none; border-radius: 7px;
|
||||
background: #8a6dff; color: #fff; font-weight: 600; cursor: pointer;
|
||||
&:hover:not(:disabled) { background: #7a5cf0; }
|
||||
&:disabled { opacity: 0.55; cursor: default; }
|
||||
}
|
||||
.ai-error { color: #e88; font-size: 0.82rem; }
|
||||
}
|
||||
|
||||
.items-head {
|
||||
display: flex; align-items: center; justify-content: space-between; margin: 1.25rem 0 0.5rem;
|
||||
.btn-mini {
|
||||
display: inline-flex; align-items: center; gap: 0.3rem;
|
||||
padding: 0.3rem 0.6rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.04);
|
||||
color: inherit; cursor: pointer; font-size: 0.8rem;
|
||||
&:hover { background: rgba(255,255,255,0.09); }
|
||||
}
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: grid; grid-template-columns: 1.4fr 80px 1fr 1.8fr 36px;
|
||||
gap: 0.5rem; align-items: center; margin-bottom: 0.4rem;
|
||||
&.head {
|
||||
font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.04em;
|
||||
color: var(--color-text-muted, #9aa0aa); margin-bottom: 0.3rem;
|
||||
}
|
||||
input {
|
||||
padding: 0.4rem 0.55rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.04);
|
||||
color: inherit; font: inherit; width: 100%;
|
||||
}
|
||||
.btn-del {
|
||||
display: inline-flex; align-items: center; justify-content: center; padding: 0.35rem;
|
||||
border-radius: 6px; border: 1px solid rgba(224,90,90,0.3);
|
||||
background: rgba(224,90,90,0.08); color: #e88; cursor: pointer;
|
||||
&:hover { background: rgba(224,90,90,0.18); }
|
||||
}
|
||||
}
|
||||
|
||||
.empty-hint { color: var(--color-text-muted, #9aa0aa); font-style: italic; }
|
||||
@@ -0,0 +1,151 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Save, Plus, Trash2, Sparkles } from 'lucide-angular';
|
||||
import { ItemCatalogService } from '../../../services/item-catalog.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { ItemCatalog, CatalogItem, ItemCatalogCreate } from '../../../services/item-catalog.model';
|
||||
|
||||
/**
|
||||
* Création/édition d'un catalogue d'objets (boutique, butin…).
|
||||
* Routes : /campaigns/:campaignId/item-catalogs/create
|
||||
* /campaigns/:campaignId/item-catalogs/:catalogId/edit
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-item-catalog-edit',
|
||||
imports: [FormsModule, LucideAngularModule],
|
||||
templateUrl: './item-catalog-edit.component.html',
|
||||
styleUrls: ['./item-catalog-edit.component.scss']
|
||||
})
|
||||
export class ItemCatalogEditComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Save = Save;
|
||||
readonly Plus = Plus;
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Sparkles = Sparkles;
|
||||
|
||||
campaignId: string | null = null;
|
||||
catalogId: string | null = null;
|
||||
|
||||
name = '';
|
||||
description = '';
|
||||
items: CatalogItem[] = [];
|
||||
|
||||
saving = false;
|
||||
errorMessage = '';
|
||||
|
||||
aiPrompt = '';
|
||||
generating = false;
|
||||
aiError = '';
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private service: ItemCatalogService,
|
||||
private campaignSidebar: CampaignSidebarService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
const params = this.route.snapshot.paramMap;
|
||||
this.campaignId = params.get('campaignId');
|
||||
this.catalogId = params.get('catalogId');
|
||||
if (this.campaignId) this.campaignSidebar.show(this.campaignId);
|
||||
|
||||
if (this.catalogId) {
|
||||
this.service.getById(this.catalogId).subscribe({
|
||||
next: (c: ItemCatalog) => {
|
||||
this.name = c.name;
|
||||
this.description = c.description ?? '';
|
||||
this.items = c.items.map(i => ({ ...i }));
|
||||
},
|
||||
error: () => this.back()
|
||||
});
|
||||
} else {
|
||||
this.addItem();
|
||||
}
|
||||
}
|
||||
|
||||
addItem(): void {
|
||||
this.items.push({ name: '', price: '', category: '', description: '' });
|
||||
}
|
||||
|
||||
removeItem(i: number): void {
|
||||
this.items.splice(i, 1);
|
||||
}
|
||||
|
||||
generateWithAI(): void {
|
||||
if (!this.campaignId) return;
|
||||
if (!this.aiPrompt.trim()) { this.aiError = 'Décris le catalogue à générer.'; return; }
|
||||
this.generating = true;
|
||||
this.aiError = '';
|
||||
this.service.generate(this.campaignId, this.aiPrompt.trim()).subscribe({
|
||||
next: (c) => {
|
||||
this.generating = false;
|
||||
if (c.name && !this.name.trim()) this.name = c.name;
|
||||
if (c.description) this.description = c.description;
|
||||
this.items = (c.items ?? []).map(i => ({ ...i }));
|
||||
},
|
||||
error: (err) => {
|
||||
this.generating = false;
|
||||
this.aiError = err?.error?.message || 'Échec de la génération IA. Réessaie ou reformule.';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
save(): void {
|
||||
if (!this.campaignId) return;
|
||||
if (!this.name.trim()) { this.errorMessage = 'Le nom est requis.'; return; }
|
||||
this.saving = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
const cleanItems = this.items
|
||||
.filter(i => i.name.trim())
|
||||
.map(i => ({
|
||||
name: i.name.trim(),
|
||||
price: i.price?.trim() || undefined,
|
||||
category: i.category?.trim() || undefined,
|
||||
description: i.description?.trim() || undefined
|
||||
}));
|
||||
|
||||
if (this.catalogId) {
|
||||
const payload: ItemCatalog = {
|
||||
id: this.catalogId,
|
||||
name: this.name.trim(),
|
||||
description: this.description.trim() || undefined,
|
||||
campaignId: this.campaignId,
|
||||
items: cleanItems
|
||||
};
|
||||
this.service.update(this.catalogId, payload).subscribe({
|
||||
next: () => this.goToView(this.catalogId!),
|
||||
error: (e) => this.fail(e)
|
||||
});
|
||||
} else {
|
||||
const payload: ItemCatalogCreate = {
|
||||
name: this.name.trim(),
|
||||
description: this.description.trim() || undefined,
|
||||
campaignId: this.campaignId,
|
||||
items: cleanItems
|
||||
};
|
||||
this.service.create(payload).subscribe({
|
||||
next: (c) => this.goToView(c.id!),
|
||||
error: (e) => this.fail(e)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private goToView(id: string): void {
|
||||
this.saving = false;
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'item-catalogs', id]);
|
||||
}
|
||||
|
||||
private fail(err: unknown): void {
|
||||
this.saving = false;
|
||||
this.errorMessage = 'Échec de l\'enregistrement.';
|
||||
console.error('ItemCatalog save failed', err);
|
||||
}
|
||||
|
||||
back(): void {
|
||||
this.router.navigate(this.campaignId ? ['/campaigns', this.campaignId] : ['/campaigns']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<div class="icl-page">
|
||||
<div class="icl-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-create" (click)="create()">
|
||||
<lucide-icon [img]="Plus" [size]="14"></lucide-icon> Nouveau catalogue
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="icl-header">
|
||||
<h1><lucide-icon [img]="Package" [size]="22"></lucide-icon> Catalogues d'objets</h1>
|
||||
<p class="icl-hint">
|
||||
Boutiques, butins, trésors… à remplir à la main ou via l'IA. Consultables en session
|
||||
quand les joueurs visitent une échoppe.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="icl-list">
|
||||
@if (catalogs.length === 0) {
|
||||
<p class="empty">Aucun catalogue pour l'instant.</p>
|
||||
}
|
||||
@for (c of catalogs; track c) {
|
||||
<button class="icl-item" (click)="open(c)">
|
||||
<lucide-icon [img]="Package" [size]="16"></lucide-icon>
|
||||
<span class="icl-item-name">{{ c.name }}</span>
|
||||
<span class="icl-item-count">{{ c.items.length }} objet(s)</span>
|
||||
<span class="icl-del" (click)="remove(c, $event)" title="Supprimer">
|
||||
<lucide-icon [img]="Trash2" [size]="14"></lucide-icon>
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,36 @@
|
||||
.icl-page { max-width: 760px; margin: 0 auto; padding: 1rem 1.5rem 3rem; }
|
||||
|
||||
.icl-toolbar {
|
||||
display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem;
|
||||
.spacer { flex: 1; }
|
||||
button {
|
||||
display: inline-flex; align-items: center; gap: 0.35rem;
|
||||
padding: 0.4rem 0.8rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.04);
|
||||
color: inherit; cursor: pointer; font-size: 0.85rem;
|
||||
&:hover { background: rgba(255,255,255,0.09); }
|
||||
}
|
||||
.btn-create { background: #667eea; border-color: #667eea; color: #fff; }
|
||||
.btn-create:hover { background: #5568d3; }
|
||||
}
|
||||
|
||||
.icl-header {
|
||||
margin-bottom: 1.25rem;
|
||||
h1 { display: flex; align-items: center; gap: 0.5rem; margin: 0 0 0.35rem; font-size: 1.5rem; }
|
||||
.icl-hint { margin: 0; color: var(--color-text-muted, #9aa0aa); font-size: 0.9rem; }
|
||||
}
|
||||
|
||||
.icl-list { display: flex; flex-direction: column; gap: 0.4rem; }
|
||||
.empty { color: var(--color-text-muted, #9aa0aa); font-style: italic; }
|
||||
|
||||
.icl-item {
|
||||
display: flex; align-items: center; gap: 0.55rem;
|
||||
padding: 0.7rem 0.85rem; border-radius: 8px;
|
||||
border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.03);
|
||||
color: inherit; cursor: pointer; text-align: left;
|
||||
&:hover { background: rgba(255,255,255,0.07); }
|
||||
.icl-item-name { flex: 1; font-weight: 500; }
|
||||
.icl-item-count { font-size: 0.78rem; color: var(--color-text-muted, #9aa0aa); }
|
||||
.icl-del { display: inline-flex; padding: 0.25rem; border-radius: 5px; color: #e88;
|
||||
&:hover { background: rgba(224,90,90,0.15); } }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Plus, Trash2, Package } from 'lucide-angular';
|
||||
import { ItemCatalogService } from '../../../services/item-catalog.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { ItemCatalog } from '../../../services/item-catalog.model';
|
||||
import { ConfirmDialogService } from '../../../shared/confirm-dialog/confirm-dialog.service';
|
||||
|
||||
/**
|
||||
* Liste des catalogues d'objets d'une campagne + création.
|
||||
* Route : /campaigns/:campaignId/item-catalogs
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-item-catalog-list',
|
||||
imports: [LucideAngularModule],
|
||||
templateUrl: './item-catalog-list.component.html',
|
||||
styleUrls: ['./item-catalog-list.component.scss']
|
||||
})
|
||||
export class ItemCatalogListComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Plus = Plus;
|
||||
readonly Trash2 = Trash2;
|
||||
readonly Package = Package;
|
||||
|
||||
campaignId = '';
|
||||
catalogs: ItemCatalog[] = [];
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private service: ItemCatalogService,
|
||||
private campaignSidebar: CampaignSidebarService,
|
||||
private confirmDialog: ConfirmDialogService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.campaignId = this.route.snapshot.paramMap.get('campaignId') ?? '';
|
||||
if (this.campaignId) {
|
||||
this.campaignSidebar.show(this.campaignId);
|
||||
this.load();
|
||||
}
|
||||
}
|
||||
|
||||
load(): void {
|
||||
this.service.getByCampaign(this.campaignId).subscribe({
|
||||
next: (list) => this.catalogs = list,
|
||||
error: () => this.catalogs = []
|
||||
});
|
||||
}
|
||||
|
||||
create(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'item-catalogs', 'create']);
|
||||
}
|
||||
|
||||
open(c: ItemCatalog): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'item-catalogs', c.id]);
|
||||
}
|
||||
|
||||
remove(c: ItemCatalog, ev: Event): void {
|
||||
ev.stopPropagation();
|
||||
this.confirmDialog.confirm({
|
||||
title: 'Supprimer le catalogue',
|
||||
message: `Supprimer « ${c.name} » ?`,
|
||||
confirmLabel: 'Supprimer',
|
||||
variant: 'danger'
|
||||
}).then(ok => {
|
||||
if (!ok) return;
|
||||
this.service.delete(c.id!).subscribe(() => this.load());
|
||||
});
|
||||
}
|
||||
|
||||
back(): void {
|
||||
this.router.navigate(['/campaigns', this.campaignId]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
@if (catalog) {
|
||||
<div class="ic-page">
|
||||
<div class="ic-toolbar">
|
||||
<button class="btn-back" (click)="back()">
|
||||
<lucide-icon [img]="ArrowLeft" [size]="14"></lucide-icon> Retour
|
||||
</button>
|
||||
<span class="spacer"></span>
|
||||
<button class="btn-edit" (click)="edit()">
|
||||
<lucide-icon [img]="Edit3" [size]="14"></lucide-icon> Éditer
|
||||
</button>
|
||||
</div>
|
||||
<header class="ic-header">
|
||||
<h1><lucide-icon [img]="Package" [size]="22"></lucide-icon> {{ catalog.name }}</h1>
|
||||
@if (catalog.description) {
|
||||
<p class="ic-desc">{{ catalog.description }}</p>
|
||||
}
|
||||
</header>
|
||||
@if (catalog.items.length === 0) {
|
||||
<p class="ic-empty">
|
||||
Aucun objet — édite le catalogue pour en ajouter.
|
||||
</p>
|
||||
}
|
||||
@for (g of groups; track g) {
|
||||
<section class="ic-group">
|
||||
@if (g.category !== '—') {
|
||||
<h2>{{ g.category }}</h2>
|
||||
}
|
||||
<table>
|
||||
<tbody>
|
||||
@for (it of g.items; track it) {
|
||||
<tr>
|
||||
<td class="col-name">{{ it.name }}</td>
|
||||
<td class="col-price">{{ it.price }}</td>
|
||||
<td class="col-desc">{{ it.description }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
.ic-page { max-width: 880px; margin: 0 auto; padding: 1rem 1.5rem 3rem; }
|
||||
|
||||
.ic-toolbar {
|
||||
display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem;
|
||||
.spacer { flex: 1; }
|
||||
button {
|
||||
display: inline-flex; align-items: center; gap: 0.35rem;
|
||||
padding: 0.4rem 0.7rem; border-radius: 6px;
|
||||
border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.04);
|
||||
color: inherit; cursor: pointer; font-size: 0.85rem;
|
||||
&:hover { background: rgba(255,255,255,0.09); }
|
||||
}
|
||||
}
|
||||
|
||||
.ic-header {
|
||||
margin-bottom: 1.25rem;
|
||||
h1 { display: flex; align-items: center; gap: 0.5rem; margin: 0 0 0.35rem; font-size: 1.5rem; }
|
||||
.ic-desc { margin: 0; color: var(--color-text-muted, #9aa0aa); }
|
||||
}
|
||||
|
||||
.ic-empty { color: var(--color-text-muted, #9aa0aa); font-style: italic; }
|
||||
|
||||
.ic-group {
|
||||
margin-bottom: 1.25rem;
|
||||
h2 {
|
||||
font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.05em;
|
||||
color: #c4a8ff; margin: 0 0 0.4rem; padding-bottom: 0.25rem;
|
||||
border-bottom: 1px solid rgba(168,130,255,0.2);
|
||||
}
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
td {
|
||||
padding: 0.45rem 0.6rem; border-bottom: 1px solid rgba(255,255,255,0.06); vertical-align: top;
|
||||
}
|
||||
.col-name { font-weight: 500; white-space: nowrap; }
|
||||
.col-price {
|
||||
white-space: nowrap; color: #e0c074; font-variant-numeric: tabular-nums;
|
||||
text-align: right; width: 90px;
|
||||
}
|
||||
.col-desc { color: var(--color-text-muted, #cfd3da); font-size: 0.9rem; }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LucideAngularModule, ArrowLeft, Edit3, Package } from 'lucide-angular';
|
||||
import { ItemCatalogService } from '../../../services/item-catalog.service';
|
||||
import { CampaignSidebarService } from '../../../services/campaign-sidebar.service';
|
||||
import { ItemCatalog, CatalogItem } from '../../../services/item-catalog.model';
|
||||
|
||||
interface ItemGroup { category: string; items: CatalogItem[]; }
|
||||
|
||||
/**
|
||||
* Vue d'un catalogue d'objets : liste (groupée par catégorie).
|
||||
* Route : /campaigns/:campaignId/item-catalogs/:catalogId
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-item-catalog-view',
|
||||
imports: [LucideAngularModule],
|
||||
templateUrl: './item-catalog-view.component.html',
|
||||
styleUrls: ['./item-catalog-view.component.scss']
|
||||
})
|
||||
export class ItemCatalogViewComponent implements OnInit {
|
||||
readonly ArrowLeft = ArrowLeft;
|
||||
readonly Edit3 = Edit3;
|
||||
readonly Package = Package;
|
||||
|
||||
campaignId: string | null = null;
|
||||
catalogId: string | null = null;
|
||||
catalog: ItemCatalog | null = null;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private service: ItemCatalogService,
|
||||
private campaignSidebar: CampaignSidebarService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
const params = this.route.snapshot.paramMap;
|
||||
this.campaignId = params.get('campaignId');
|
||||
this.catalogId = params.get('catalogId');
|
||||
if (this.catalogId) {
|
||||
this.service.getById(this.catalogId).subscribe({
|
||||
next: c => this.catalog = c,
|
||||
error: () => this.back()
|
||||
});
|
||||
}
|
||||
if (this.campaignId) this.campaignSidebar.show(this.campaignId);
|
||||
}
|
||||
|
||||
/** Objets groupés par catégorie (non catégorisés en dernier). */
|
||||
get groups(): ItemGroup[] {
|
||||
const map = new Map<string, CatalogItem[]>();
|
||||
for (const it of this.catalog?.items ?? []) {
|
||||
const cat = (it.category ?? '').trim() || '—';
|
||||
if (!map.has(cat)) map.set(cat, []);
|
||||
map.get(cat)!.push(it);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.sort(([a], [b]) => (a === '—' ? 1 : b === '—' ? -1 : a.localeCompare(b, 'fr')))
|
||||
.map(([category, items]) => ({ category, items }));
|
||||
}
|
||||
|
||||
edit(): void {
|
||||
if (this.campaignId && this.catalogId) {
|
||||
this.router.navigate(['/campaigns', this.campaignId, 'item-catalogs', this.catalogId, 'edit']);
|
||||
}
|
||||
}
|
||||
|
||||
back(): void {
|
||||
this.router.navigate(this.campaignId ? ['/campaigns', this.campaignId] : ['/campaigns']);
|
||||
}
|
||||
}
|
||||
@@ -5,37 +5,55 @@
|
||||
<span class="nac-name">{{ action.name }}</span>
|
||||
</div>
|
||||
|
||||
<p class="nac-desc" *ngIf="action.description">{{ action.description }}</p>
|
||||
@if (action.description) {
|
||||
<p class="nac-desc">{{ action.description }}</p>
|
||||
}
|
||||
|
||||
<!-- Cibles -->
|
||||
<div class="nac-targets" *ngIf="status !== 'created' && needsArc">
|
||||
@if (status !== 'created' && needsArc) {
|
||||
<div class="nac-targets">
|
||||
<label>
|
||||
Arc
|
||||
<select [(ngModel)]="selectedArcId" (ngModelChange)="syncChapter()">
|
||||
<option *ngFor="let a of arcs" [value]="a.id">{{ a.name }}</option>
|
||||
@for (a of arcs; track a) {
|
||||
<option [value]="a.id">{{ a.name }}</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label *ngIf="needsChapter">
|
||||
@if (needsChapter) {
|
||||
<label>
|
||||
Chapitre
|
||||
<select [(ngModel)]="selectedChapterId">
|
||||
<option *ngFor="let c of targetChapters" [value]="c.id">{{ c.name }}</option>
|
||||
@for (c of targetChapters; track c) {
|
||||
<option [value]="c.id">{{ c.name }}</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<p class="nac-warn" *ngIf="needsArc && arcs.length === 0">
|
||||
@if (needsArc && arcs.length === 0) {
|
||||
<p class="nac-warn">
|
||||
Crée d'abord un arc {{ needsChapter ? 'et un chapitre ' : '' }}dans la campagne pour pouvoir y rattacher cet élément.
|
||||
</p>
|
||||
}
|
||||
|
||||
<div class="nac-foot">
|
||||
<button class="nac-create" *ngIf="status !== 'created'" (click)="create()" [disabled]="!canCreate">
|
||||
@if (status !== 'created') {
|
||||
<button class="nac-create" (click)="create()" [disabled]="!canCreate">
|
||||
<lucide-icon [img]="Plus" [size]="13"></lucide-icon>
|
||||
{{ status === 'creating' ? 'Création…' : 'Créer dans la campagne' }}
|
||||
</button>
|
||||
<button class="nac-open" *ngIf="status === 'created'" (click)="openCreated()">
|
||||
}
|
||||
@if (status === 'created') {
|
||||
<button class="nac-open" (click)="openCreated()">
|
||||
<lucide-icon [img]="Check" [size]="13"></lucide-icon> Créé — ouvrir
|
||||
<lucide-icon [img]="ExternalLink" [size]="12"></lucide-icon>
|
||||
</button>
|
||||
<span class="nac-error" *ngIf="status === 'error'">{{ errorMsg }}</span>
|
||||
}
|
||||
@if (status === 'error') {
|
||||
<span class="nac-error">{{ errorMsg }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user