Spaces:
Sleeping
Sleeping
Download src/api.py from FC-Bit/arkanum: direct link, hf CLI and curl.
- Browser
- Download file 8.03 kB
-
https://huggingface.co/spaces/FC-Bit/arkanum/resolve/main/src/api.py
- Command line
-
hf download hf://spaces/FC-Bit/arkanum/src/api.py
-
curl -L -o api.py https://huggingface.co/spaces/FC-Bit/arkanum/resolve/main/src/api.py
8.03 kB
| """ | |
| 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.") | |
| 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] | |
| 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"} | |
| async def ask(req: AskRequest): | |
| """Textbasierte Regelfrage beantworten.""" | |
| result = answer_question(req.question, req.game) | |
| return AskResponse(answer=result["answer"], sources=result["sources"]) | |
| 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"], | |
| ) | |
| async def health(): | |
| return {"status": "ok"} | |
| 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" | |
| 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") | |
| 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"]) | |
| 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") | |
| 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") | |