File size: 10,368 Bytes
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45dcdd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45dcdd6
 
c6abe34
45dcdd6
c6abe34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""
Basketball Analysis API - Main FastAPI Application

This module sets up the FastAPI application with all routes, middleware,
and exception handlers for the basketball performance analysis platform.
"""
import os
from contextlib import asynccontextmanager
from typing import Dict, Any

from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles

from app.config import get_settings
from app.core import BasketballAPIException
from app.api import (
    auth, 
    videos, 
    analysis, 
    teams, 
    players, 
    analytics, 
    admin, 
    player_routes, 
    advanced_analytics,
    communications,
    personal_analysis,
    stat_import
)
from app.middleware.timeout import TimeoutMiddleware

# Basic rate limiting for abuse protection
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Application lifespan handler for startup and shutdown events.
    """
    # Startup
    settings = get_settings()
    print(f"πŸ€ Starting {settings.app_name} v{settings.app_version}")

    # Basic production hardening
    if not settings.debug and settings.jwt_secret == "your-super-secret-key-change-in-production":
        raise ValueError("JWT_SECRET must be set in production (refusing to start with default secret).")
    
    # Ensure upload directory exists
    os.makedirs(settings.upload_dir, exist_ok=True)
    
    # Check for required models
    required_models = [
        settings.player_detector_path,
        settings.ball_detector_path,
        settings.court_keypoint_detector_path,
        settings.swish_ball_rim_model,
        settings.swish_pose_model
    ]
    
    missing_models = []
    for model_path in required_models:
        if not os.path.exists(model_path):
            missing_models.append(model_path)
            
    if missing_models:
        print(f"❌ CRITICAL: Missing models: {', '.join(missing_models)}")
        print("   Please run 'python download_models.py' to fetch them.")
    else:
        print("βœ… All required models are present.")
    
    # Check GPU availability
    if settings.gpu_enabled:
        try:
            import torch
            if torch.cuda.is_available():
                print(f"βœ… GPU acceleration enabled: {torch.cuda.get_device_name(settings.cuda_device)}")
            else:
                print("⚠️ GPU requested but CUDA not available, falling back to CPU")
        except ImportError:
            print("⚠️ PyTorch not installed, running without GPU check")
    
    yield
    
    # Shutdown
    print("πŸ›‘ Shutting down application")


def create_app() -> FastAPI:
    """
    Application factory for creating the FastAPI instance.
    """
    settings = get_settings()
    
    app = FastAPI(
        title=settings.app_name,
        version=settings.app_version,
        description="""
        AI-driven basketball performance analysis platform.
        
        ## Features
        - **Video Analysis**: Upload and analyze basketball footage
        - **Team Analysis**: Multi-player tracking, passes, interceptions  
        - **Personal Analysis**: Individual skill metrics and pose analysis
        - **Progress Tracking**: Monitor improvement over time
        
        ## Account Types
        - **TEAM**: Manage organizations and team analytics
        - **COACH**: Manage player training and specialized drills
        - **PLAYER**: Focus on individual training and skill development
        """,
        docs_url="/docs",
        redoc_url="/redoc",
        openapi_url="/api/openapi.json",
        lifespan=lifespan,
    )

    # Attach a rate limiter to the app. We keep limits conservative but safe by default.
    limiter = Limiter(key_func=get_remote_address, default_limits=[settings.default_rate_limit])
    app.state.limiter = limiter
    app.add_middleware(SlowAPIMiddleware)

    # Configure CORS
    cors_origins = settings.cors_origins_list
    if not cors_origins:
        # Permissive for development/unconfigured production
        allow_origins = ["*"]
        allow_credentials = False # Cannot use credentials with "*"
    else:
        allow_origins = cors_origins
        allow_credentials = True

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

    # Request timeout (avoid resource exhaustion)
    app.add_middleware(TimeoutMiddleware, timeout_seconds=settings.request_timeout_seconds)
    
    # Register exception handlers
    register_exception_handlers(app)
    
    # Register API routes
    register_routes(app)
    
    # Static files for uploads (debug/dev only). In production, use authenticated download endpoints
    # or signed object storage URLs instead of exposing a filesystem-backed directory.
    # Anchor all static dirs to the backend root (derived from __file__) so they
    # resolve correctly even when CWD is mangled (apostrophe-stripped shell).
    _app_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    if settings.serve_uploads_in_debug and os.path.exists(settings.upload_dir):
        app.mount("/uploads", StaticFiles(directory=settings.upload_dir), name="uploads")
    
    # Serve generated clips (highlights)
    clips_dir = os.path.join(_app_dir, "output_videos", "clips")
    os.makedirs(clips_dir, exist_ok=True)
    app.mount("/clips", StaticFiles(directory=clips_dir), name="clips")
    
    # Serve personal analysis output videos β€” always mounted so results are
    # accessible regardless of the DEBUG flag.
    personal_out_dir = os.path.join(_app_dir, "uploads", "personal_output")
    os.makedirs(personal_out_dir, exist_ok=True)
    app.mount("/personal-output", StaticFiles(directory=personal_out_dir), name="personal-output")

    return app


def register_exception_handlers(app: FastAPI) -> None:
    """Register custom exception handlers."""
    
    @app.exception_handler(BasketballAPIException)
    async def basketball_exception_handler(
        request: Request, exc: BasketballAPIException
    ) -> JSONResponse:
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "error": exc.message,
                "details": exc.details,
            },
        )
    
    from fastapi.exceptions import RequestValidationError
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        print(f"Validation Error: {exc.errors()}")
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content={"detail": exc.errors()},
        )
    
    @app.exception_handler(RateLimitExceeded)
    async def rate_limit_handler(
        request: Request, exc: RateLimitExceeded
    ) -> JSONResponse:
        return JSONResponse(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            content={
                "error": "Too many requests",
                "details": {"message": str(exc)},
            },
        )

    @app.exception_handler(Exception)
    async def general_exception_handler(
        request: Request, exc: Exception
    ) -> JSONResponse:
        # Log the error without leaking internals to clients
        settings = get_settings()
        # Use standard logging so deployments can aggregate logs
        import logging

        logger = logging.getLogger("basketball_api")
        logger.exception("Unhandled error", exc_info=exc)

        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={
                "error": "An unexpected error occurred",
                # Only expose minimal type information; no stack traces or messages.
                "details": {"type": type(exc).__name__} if settings.debug else {},
            },
        )


def register_routes(app: FastAPI) -> None:
    """Register all API routers."""
    
    # Health check endpoint
    @app.get("/api/health", tags=["Health"])
    async def health_check() -> Dict[str, Any]:
        """Check API health status."""
        settings = get_settings()
        return {
            "status": "healthy",
            "version": settings.app_version,
            "gpu_enabled": settings.gpu_enabled,
        }
    
    # Root endpoint
    @app.get("/", tags=["Root"])
    async def root() -> Dict[str, str]:
        """API root endpoint."""
        settings = get_settings()
        return {
            "message": f"Welcome to {settings.app_name}",
            "docs": "/docs",
            "health": "/api/health",
        }

    @app.get("/api/test-proxy")
    async def test_proxy():
        return {"status": "proxy-ok"}
    
    # Register API routers
    app.include_router(auth.router, prefix="/api/auth", tags=["Authentication"])
    app.include_router(videos.router, prefix="/api/videos", tags=["Videos"])
    app.include_router(analysis.router, prefix="/api/analysis", tags=["Analysis"])
    app.include_router(teams.router, prefix="/api/teams", tags=["Teams"])
    app.include_router(players.router, prefix="/api/players", tags=["Players"])
    app.include_router(analytics.router, prefix="/api/analytics", tags=["Analytics"])
    app.include_router(advanced_analytics.router, prefix="/api/analytics/advanced", tags=["Advanced Analytics"])
    app.include_router(admin.router, prefix="/api/admin", tags=["Admin"])
    app.include_router(player_routes.router, prefix="/api/player", tags=["Player Portal"])
    app.include_router(personal_analysis.router, prefix="/api/player", tags=["Personal Analysis"])
    app.include_router(communications.router, prefix="/api/communications", tags=["Communication"])
    app.include_router(stat_import.router, prefix="/api/stat-import", tags=["Stat Sheet Import"])


# Create the application instance
app = create_app()


if __name__ == "__main__":
    import uvicorn
    settings = get_settings()
    uvicorn.run(
        "app.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
    )