Spaces:
Sleeping

File size: 8,029 Bytes
f73c3e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf010
f73c3e2
60a07be
f73c3e2
 
 
 
 
 
 
 
a1bfaa6
60a07be
f73c3e2
 
 
00cf010
 
 
 
 
 
 
 
 
f73c3e2
 
 
8a2dc22
f73c3e2
 
 
 
 
 
8a2dc22
 
 
 
 
 
 
f73c3e2
8a2dc22
f73c3e2
 
 
 
 
 
f2bbb42
 
f73c3e2
 
f2bbb42
 
 
 
 
f73c3e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4216c7a
f73c3e2
 
 
00cf010
f73c3e2
 
 
 
 
 
00cf010
f73c3e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60a07be
 
3e2ead7
 
 
 
 
 
 
 
 
 
 
60a07be
 
 
 
 
 
 
 
 
 
 
 
 
 
a1bfaa6
60a07be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1bfaa6
 
 
 
 
 
 
 
 
 
 
60a07be
 
 
 
 
 
 
 
 
 
a1bfaa6
 
 
 
 
 
 
 
 
 
 
 
 
 
60a07be
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""
Arkanum FastAPI Backend
========================
REST API für den Regelexperten (Text + Vision).

Starten (lokal):
    PYTHONPATH=. uvicorn src.api:app --reload --host 0.0.0.0 --port 8000

Starten (Azure):
    gunicorn --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 -w 2 --timeout 120 src.api:app
"""
import logging
import os
import sys

from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

# Projekt-Root für Imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.expert.query import answer_question
from src.expert.vision import answer_from_image
from src.expert.walkthrough import expand_step, get_prerendered_step, load_walkthrough
from src.voice.tts import synthesize

logger = logging.getLogger("arkanum")

# Einfache Passwort-Auth (aus Env-Variable oder Default)
APP_PASSWORD = os.environ.get("APP_PASSWORD", "stalker")


async def verify_password(x_password: str = Header(None)):
    """Prüft das Passwort aus dem X-Password Header."""
    if x_password != APP_PASSWORD:
        raise HTTPException(status_code=401, detail="Falsches Passwort")


def _ensure_index(game: str = "stalker") -> None:
    """Baut den Vektorindex falls er noch nicht existiert."""
    from src.rag.vectorstore import _get_collection, load_cached_index

    collection = _get_collection(game)
    if collection.count() > 0:
        logger.info(f"Index für '{game}' existiert bereits ({collection.count()} Chunks).")
        return

    # Versuch 1: Cache laden (schnell, ~3s)
    if load_cached_index(game):
        logger.info("Index aus Cache geladen.")
        return

    # Versuch 2: Voller Rebuild (Fallback, erzeugt auch neuen Cache)
    logger.info(f"Kein Cache für '{game}' gefunden – voller Rebuild...")
    from scripts.build_index import build_game_index
    build_game_index(game, export=True)
    logger.info("Index-Aufbau abgeschlossen.")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Startup: Index prüfen/bauen. Shutdown: aufräumen."""
    from datetime import datetime, timezone

    logging.basicConfig(level=logging.INFO)
    _ensure_index("stalker")

    from src.rag.vectorstore import _get_collection
    count = _get_collection("stalker").count()
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    logger.info(f"===== Arkanum online | {count} Chunks im Index | {now} =====")
    yield


app = FastAPI(
    title="Arkanum",
    description="KI-gestützter Regelexperte für Brettspiele",
    version="0.1.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Static files für Frontend
FRONTEND_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "frontend")
if os.path.isdir(FRONTEND_DIR):
    app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")


class AskRequest(BaseModel):
    question: str
    game: str = "stalker"


class AskResponse(BaseModel):
    answer: str
    sources: list[str]


class VisionResponse(BaseModel):
    situation: str
    answer: str
    sources: list[str]


@app.get("/")
async def root():
    """Serve Frontend oder API-Info."""
    index_path = os.path.join(FRONTEND_DIR, "index.html")
    if os.path.exists(index_path):
        return FileResponse(index_path, headers={"Cache-Control": "no-cache, must-revalidate"})
    return {"name": "Arkanum", "version": "0.1.0", "docs": "/docs"}


@app.post("/api/ask", response_model=AskResponse, dependencies=[Depends(verify_password)])
async def ask(req: AskRequest):
    """Textbasierte Regelfrage beantworten."""
    result = answer_question(req.question, req.game)
    return AskResponse(answer=result["answer"], sources=result["sources"])


@app.post("/api/ask/vision", response_model=VisionResponse, dependencies=[Depends(verify_password)])
async def ask_vision(
    question: str = Form(...),
    game: str = Form("stalker"),
    image: UploadFile = File(...),
):
    """Regelfrage mit Bild (Spielzustand/Karte) beantworten."""
    image_data = await image.read()

    # Media type bestimmen
    media_type = image.content_type or "image/jpeg"
    if media_type not in ("image/jpeg", "image/png", "image/gif", "image/webp"):
        media_type = "image/jpeg"

    result = answer_from_image(
        image_data=image_data,
        question=question,
        game=game,
        media_type=media_type,
    )
    return VisionResponse(
        situation=result["situation"],
        answer=result["answer"],
        sources=result["sources"],
    )


@app.get("/api/health")
async def health():
    return {"status": "ok"}


@app.get("/api/version")
async def version():
    """Git-Commit-Hash als Version (aus VERSION-Datei, beim Docker-Build erzeugt)."""
    version_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "VERSION")
    try:
        with open(version_file) as f:
            return {"version": f.read().strip()}
    except FileNotFoundError:
        return {"version": "dev"}


# --- Walkthrough & Voice Guide ---


class WalkthroughStepRequest(BaseModel):
    game: str = "stalker"
    mode: str  # "campaign" oder "zone_survival"
    phase_id: str
    step_id: str
    lang: str = "de"


class WalkthroughStepResponse(BaseModel):
    text: str
    sources: list[str]
    audio_url: str | None = None


class TTSRequest(BaseModel):
    text: str
    voice: str = "onyx"


@app.get("/api/walkthrough/{game}", dependencies=[Depends(verify_password)])
async def get_walkthrough(game: str):
    """Walkthrough-Definition für ein Spiel laden."""
    try:
        return load_walkthrough(game)
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail=f"Kein Walkthrough für '{game}' gefunden")


@app.post("/api/walkthrough/step", response_model=WalkthroughStepResponse, dependencies=[Depends(verify_password)])
async def walkthrough_step(req: WalkthroughStepRequest):
    """Einzelnen Walkthrough-Step laden (vorgerendert oder live via RAG + Claude)."""
    # Zuerst vorgerenderten Step prüfen
    prerendered = get_prerendered_step(req.game, req.mode, req.phase_id, req.step_id)
    if prerendered:
        return WalkthroughStepResponse(
            text=prerendered["text"],
            sources=prerendered["sources"],
            audio_url=prerendered.get("audio_url"),
        )

    # Fallback: Live-Generierung
    result = expand_step(
        game=req.game,
        mode=req.mode,
        phase_id=req.phase_id,
        step_id=req.step_id,
        lang=req.lang,
    )
    return WalkthroughStepResponse(text=result["text"], sources=result["sources"])


@app.get("/api/walkthrough/audio/{game}/{mode}/{phase_id}/{step_id}", dependencies=[Depends(verify_password)])
async def walkthrough_audio(game: str, mode: str, phase_id: str, step_id: str):
    """Vorgerenderte MP3-Audiodatei für einen Walkthrough-Step ausliefern."""
    audio_dir = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        "data", "walkthrough", "prerendered", game, mode,
    )
    filename = f"{phase_id}__{step_id}.mp3"
    audio_path = os.path.join(audio_dir, filename)
    if not os.path.exists(audio_path):
        raise HTTPException(status_code=404, detail="Audio nicht gefunden")
    return FileResponse(audio_path, media_type="audio/mpeg")


@app.post("/api/tts", dependencies=[Depends(verify_password)])
async def text_to_speech(req: TTSRequest):
    """Text in MP3-Audio umwandeln (OpenAI TTS)."""
    if not req.text.strip():
        raise HTTPException(status_code=400, detail="Text darf nicht leer sein")
    audio_bytes = synthesize(req.text, voice=req.voice)
    return Response(content=audio_bytes, media_type="audio/mpeg")