File size: 4,072 Bytes
eb3e391
fcaa899
2655a7f
eadc77b
fcaa899
 
c371e15
d091da8
a61ba58
 
eb3e391
 
 
 
 
83003f5
fcaa899
 
 
 
2655a7f
 
 
c371e15
1ce02f3
eb3e391
554ad2f
2655a7f
5db3b83
fcaa899
 
 
 
2655a7f
eb3e391
 
 
37757ef
 
2655a7f
fcaa899
 
 
 
 
eb3e391
9d49be3
 
 
 
83003f5
eb3e391
9d49be3
d091da8
 
eb3e391
2655a7f
 
 
eb3e391
39c89a5
eb3e391
83003f5
eb3e391
 
 
83003f5
39c89a5
eb3e391
 
 
 
39c89a5
d091da8
 
eb3e391
 
 
d091da8
eb3e391
 
1ce02f3
2655a7f
554ad2f
60e1a98
 
 
eadc77b
60e1a98
eadc77b
b0a6020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2655a7f
fcaa899
 
eb3e391
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
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import os
from dotenv import load_dotenv

# Import local modules
from core.story_generator import StoryGenerator
from core.setup import setup_game, get_universe_generator
from core.session_manager import SessionManager
from services.flux_client import FluxClient
from api.routes.chat import get_chat_router
from api.routes.image import get_image_router
from api.routes.speech import get_speech_router
from api.routes.universe import get_universe_router

# Load environment variables
load_dotenv()

# API configuration
API_HOST = os.getenv("API_HOST", "0.0.0.0")
API_PORT = int(os.getenv("API_PORT", "8000"))
STATIC_FILES_DIR = os.getenv("STATIC_FILES_DIR", "../client/dist")
HF_API_KEY = os.getenv("HF_API_KEY")
ELEVEN_LABS_API_KEY = os.getenv("ELEVEN_LABS_API_KEY")
IS_DOCKER = os.getenv("IS_DOCKER", "false").lower() == "true"

app = FastAPI(title="Echoes of Influence")

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",
        f"http://localhost:{API_PORT}",
        "https://huggingface.co.",
        "https://*.hf.space",
        "https://mistral-ai-game-jam-dont-lookup.hf.space"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize components
mistral_api_key = os.getenv("MISTRAL_API_KEY")
if not mistral_api_key:
    raise ValueError("MISTRAL_API_KEY environment variable is not set")

print("Creating global SessionManager")
session_manager = SessionManager()
story_generator = StoryGenerator(api_key=mistral_api_key)
flux_client = FluxClient(api_key=HF_API_KEY)

# Health check endpoint
@app.get("/api/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy"}

# Register route handlers
print("Registering route handlers with SessionManager", id(session_manager))
app.include_router(get_chat_router(session_manager, story_generator), prefix="/api")
app.include_router(get_image_router(flux_client), prefix="/api")
app.include_router(get_speech_router(), prefix="/api")
app.include_router(get_universe_router(session_manager, story_generator), prefix="/api")

@app.on_event("startup")
async def startup_event():
    """Initialize components on startup"""
    pass

@app.on_event("shutdown")
async def shutdown_event():
    """Clean up on shutdown"""
    # Clean up expired sessions
    session_manager.cleanup_expired_sessions()
    
    # Close API clients
    await flux_client.close()

# Mount static files (this should be after all API routes)
if IS_DOCKER:
    # Mount static files
    app.mount("/", StaticFiles(directory="static", html=True), name="static")

    # En mode Docker (HF Space), on monte les fichiers statiques avec des types MIME spécifiques
    # app.mount("/assets", StaticFiles(directory=os.path.join(STATIC_FILES_DIR, "assets"), html=False), name="assets")
    
#     @app.get("/{full_path:path}")
#     async def serve_spa(full_path: str):
#         # Si le chemin pointe vers un fichier JavaScript
#         if full_path.endswith('.js'):
#             return FileResponse(
#                 os.path.join(STATIC_FILES_DIR, full_path),
#                 media_type='application/javascript'
#             )
#         # Si le chemin pointe vers un fichier CSS
#         elif full_path.endswith('.css'):
#             return FileResponse(
#                 os.path.join(STATIC_FILES_DIR, full_path),
#                 media_type='text/css'
#             )
#         # Pour tous les autres chemins, servir index.html
#         return FileResponse(
#             os.path.join(STATIC_FILES_DIR, "index.html"),
#             media_type='text/html'
#         )
# else:
#     # En local, on monte simplement à la racine
#     app.mount("/", StaticFiles(directory=STATIC_FILES_DIR, html=True), name="static")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("server:app", host=API_HOST, port=API_PORT, reload=True)