Spaces:
Sleeping

File size: 6,089 Bytes
60a07be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1bfaa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""
Walkthrough Step-Expander
==========================
Lädt Walkthrough-Definitionen und expandiert einzelne Steps
via RAG + Claude zu natürlichem Sprechtext.

Verwendung:
    from src.expert.walkthrough import load_walkthrough, expand_step
    wt = load_walkthrough("stalker")
    text = expand_step("stalker", "campaign", "overview", "welcome", "de")
"""
import json
import os
import re

import anthropic
from dotenv import load_dotenv

from src.rag.vectorstore import retrieve

load_dotenv()

WALKTHROUGH_DIR = os.path.join(
    os.path.dirname(__file__), "..", "..", "data", "walkthrough"
)
PROMPTS_DIR = os.path.join(
    os.path.dirname(__file__), "..", "..", "prompts"
)
MODEL = "claude-sonnet-4-20250514"

GAME_DISPLAY_NAMES = {
    "stalker": "S.T.A.L.K.E.R. The Board Game",
}

_client = None


def _get_client() -> anthropic.Anthropic:
    global _client
    if _client is None:
        _client = anthropic.Anthropic()
    return _client


def load_walkthrough(game: str) -> dict:
    """Lädt die Walkthrough-Definition für ein Spiel."""
    path = os.path.join(WALKTHROUGH_DIR, f"{game}.json")
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def _load_prompt_template(template_name: str) -> str:
    """Lädt ein Prompt-Template aus prompts/."""
    path = os.path.join(PROMPTS_DIR, f"{template_name}.md")
    with open(path, "r", encoding="utf-8") as f:
        return f.read()


def _find_step(walkthrough: dict, mode: str, phase_id: str, step_id: str) -> dict | None:
    """Findet einen Step in der Walkthrough-Definition."""
    mode_data = walkthrough.get("modes", {}).get(mode)
    if not mode_data:
        return None
    for phase in mode_data.get("phases", []):
        if phase["id"] == phase_id:
            for step in phase.get("steps", []):
                if step["id"] == step_id:
                    return step
    return None


def _format_rag_context(chunks: list[dict]) -> str:
    """Formatiert RAG-Chunks als Kontext."""
    parts = []
    for i, chunk in enumerate(chunks, 1):
        source_label = chunk["source"].replace("_", " ")
        parts.append(
            f"### Quelle {i}: {source_label}, Seite {chunk['page']} "
            f"({chunk['section']})\n\n{chunk['text']}"
        )
    return "\n\n---\n\n".join(parts)


def expand_step(
    game: str,
    mode: str,
    phase_id: str,
    step_id: str,
    lang: str = "de",
) -> dict:
    """
    Expandiert einen Walkthrough-Step zu natürlichem Sprechtext.

    Args:
        game: Spielname (z.B. "stalker")
        mode: Spielmodus ("campaign" oder "zone_survival")
        phase_id: Phase-ID (z.B. "overview")
        step_id: Step-ID (z.B. "welcome")
        lang: Sprache ("de" oder "en")

    Returns:
        Dict mit:
        - text (str): Generierter Sprechtext
        - sources (list[str]): Verwendete Quellen
    """
    walkthrough = load_walkthrough(game)
    step = _find_step(walkthrough, mode, phase_id, step_id)
    if not step:
        return {"text": "Schritt nicht gefunden.", "sources": []}

    # RAG-Kontext holen
    all_chunks = []
    for query in step.get("rag_queries", []):
        chunks = retrieve(query, game, k=3)
        all_chunks.extend(chunks)

    # Duplikate entfernen (nach ID)
    seen_ids = set()
    unique_chunks = []
    for c in all_chunks:
        if c["id"] not in seen_ids:
            seen_ids.add(c["id"])
            unique_chunks.append(c)

    # Prompt-Template laden und füllen
    template = _load_prompt_template(step["prompt_template"])
    display_name = GAME_DISPLAY_NAMES.get(game, game)
    mode_title = walkthrough["modes"][mode]["title"]

    rag_context = _format_rag_context(unique_chunks) if unique_chunks else "Kein zusätzlicher Kontext verfügbar."

    # Template-Variablen ersetzen
    prompt_text = template
    prompt_text = prompt_text.replace("{{spielname}}", display_name)
    prompt_text = prompt_text.replace("{{modus}}", mode_title)
    prompt_text = prompt_text.replace("{{kontext}}", rag_context)
    prompt_text = prompt_text.replace("{{sprache}}", "Deutsch" if lang == "de" else "English")

    # Zusätzliche step-spezifische Variablen
    for key, value in step.get("variables", {}).items():
        prompt_text = prompt_text.replace(f"{{{{{key}}}}}", str(value))

    # System-Prompt vom User-Prompt trennen (am ersten ## Kontext oder ## Aufgabe)
    system_part = re.split(r"\n##\s+(Kontext|Aufgabe)", prompt_text)[0].strip()
    # Bereinige Markdown-Header aus System-Teil
    system_part = re.sub(r"^#.*?\n+", "", system_part).strip()

    user_part = f"## Regelwerk-Kontext\n\n{rag_context}\n\nGeneriere jetzt den Sprechtext für diesen Schritt."

    # Claude API aufrufen
    client = _get_client()
    response = client.messages.create(
        model=MODEL,
        max_tokens=1024,
        system=system_part,
        messages=[{"role": "user", "content": user_part}],
    )

    text = response.content[0].text

    # Quellen extrahieren
    sources = []
    seen_sources = set()
    for c in unique_chunks:
        label = f"{c['source'].replace('_', ' ')} S.{c['page']}"
        if label not in seen_sources:
            seen_sources.add(label)
            sources.append(label)

    return {"text": text, "sources": sources}


def get_prerendered_step(game: str, mode: str, phase_id: str, step_id: str) -> dict | None:
    """
    Lädt einen vorgerenderten Walkthrough-Step.

    Returns:
        Dict mit text, sources, audio_url oder None wenn nicht vorhanden.
    """
    base = os.path.join(WALKTHROUGH_DIR, "prerendered", game, mode)
    filename = f"{phase_id}__{step_id}"
    json_path = os.path.join(base, f"{filename}.json")
    audio_path = os.path.join(base, f"{filename}.mp3")

    if not os.path.exists(json_path):
        return None

    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    result = {"text": data["text"], "sources": data.get("sources", [])}
    if os.path.exists(audio_path):
        result["audio_url"] = f"/api/walkthrough/audio/{game}/{mode}/{phase_id}/{step_id}"
    return result