This repository was archived by the owner on May 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
106 lines (90 loc) · 3 KB
/
Copy pathapp.py
File metadata and controls
106 lines (90 loc) · 3 KB
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
# Copyright iX.
# SPDX-License-Identifier: MIT-0
import uvicorn
import gradio as gr
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from core.config import app_config
from llm.model_manager import model_manager
from common.login import router as login_router, get_auth_user
from common.main_ui import create_main_interface
from core.logger import logger
# Get configurations from app_config
server_config = app_config.server_config
security_config = app_config.security_config
cors_config = app_config.cors_config
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan context manager for FastAPI app"""
try:
# Startup
logger.info("Initializing application...")
# Initialize default LLM models if none exist
model_manager.init_default_models()
# Module configs are initialized on-demand when accessed
logger.info("Application initialization complete")
yield
except Exception as e:
logger.error(f"Failed to initialize application: {str(e)}")
raise
finally:
# Shutdown
logger.info("Shutting down application...")
# Create FastAPI app
app = FastAPI(lifespan=lifespan)
# Add session middleware
app.add_middleware(
SessionMiddleware,
secret_key=security_config['secret_key'],
session_cookie="session",
max_age=None, # Let Cognito handle token expiration
same_site="lax", # Prevents CSRF while allowing normal navigation
https_only=security_config['ssl_enabled'], # Enable for production with HTTPS
path="/", # Make cookie available for all paths
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=cors_config['allow_origins'],
allow_credentials=True,
allow_methods=cors_config['allow_methods'],
allow_headers=cors_config['allow_headers'],
expose_headers=["*"],
max_age=3600
)
# Include login routes
app.include_router(login_router)
@app.get('/')
def root_path(request: Request):
"""Root route handler"""
try:
get_auth_user(request)
logger.debug("User found, redirecting to main")
return RedirectResponse(url='/main')
except HTTPException:
logger.debug("No user found, redirecting to login")
return RedirectResponse(url='/login')
@app.get("/health")
async def health_check():
"""Health check endpoint for both application and App Runner"""
return {"status": "OK!"}
# Create main interface
main_ui = create_main_interface()
# Mount Gradio app with auth_dependency
app = gr.mount_gradio_app(
app,
main_ui,
path="/main",
auth_dependency=get_auth_user
)
if __name__ == "__main__":
# Start server with configuration from app_config
uvicorn.run(
app,
host=server_config['host'],
port=server_config['port'],
log_level=server_config['log_level']
)