"""FastAPI application entry point.""" import structlog from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from app import __version__ from app.api.v1.router import api_router from app.core.config import settings from app.core.logging import configure_logging from app.core.metrics import setup_metrics from app.db.database import init_db from pathlib import Path logger = structlog.get_logger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan manager.""" # Startup configure_logging() # Create storage directories storage_path = Path(settings.AUDIO_STORAGE_PATH) for subdir in ["music", "vocals", "mixed", "mastered"]: (storage_path / subdir).mkdir(parents=True, exist_ok=True) logger.info("storage_directories_created", path=str(storage_path)) # Try to initialize database, but don't fail if it's not available try: await init_db() logger.info("database_initialized") except Exception as e: logger.warning("database_initialization_failed", error=str(e)) logger.info("continuing_without_database") setup_metrics() logger.info("application_started", version=__version__) yield # Shutdown logger.info("application_shutting_down") app = FastAPI( title="AudioForge API", description="Open-source Suno-style music generation platform", version="0.1.0", lifespan=lifespan, docs_url="/api/docs", redoc_url="/api/redoc", ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=settings.CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API router app.include_router(api_router, prefix="/api/v1") # Metrics endpoint from app.core.metrics import metrics_endpoint app.get("/metrics", include_in_schema=False)(metrics_endpoint) @app.get("/health") async def health_check() -> dict[str, str]: """Health check endpoint.""" return {"status": "healthy", "version": "0.1.0"} @app.exception_handler(Exception) async def global_exception_handler(request, exc: Exception): """Global exception handler.""" logger.error("unhandled_exception", exc_info=exc, path=request.url.path) return JSONResponse( status_code=500, content={"detail": "Internal server error"}, ) if __name__ == "__main__": import uvicorn uvicorn.run( "app.main:app", host="0.0.0.0", port=8000, reload=True, )