from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from pathlib import Path from app.routers import speakers, dialog # Import the routers from app import config from app.services.tts_service import get_global_tts_service app = FastAPI( title="Chatterbox TTS API", description="API for generating TTS dialogs using Chatterbox TTS.", version="0.1.0", ) # CORS Middleware configuration # For development, we'll allow all origins # In production, you should restrict this to specific origins app.add_middleware( CORSMiddleware, allow_origins=config.CORS_ORIGINS, allow_credentials=False, allow_methods=["*"], allow_headers=["*"], expose_headers=["*"] ) # Include routers app.include_router(speakers.router, prefix="/api/speakers", tags=["Speakers"]) app.include_router(dialog.router, prefix="/api/dialog", tags=["Dialog Generation"]) @app.get("/") async def read_root(): return {"message": "Welcome to the Chatterbox TTS API!"} # Ensure the directory for serving generated audio exists config.DIALOG_GENERATED_DIR.mkdir(parents=True, exist_ok=True) # Mount StaticFiles to serve generated dialogs app.mount("/generated_audio", StaticFiles(directory=config.DIALOG_GENERATED_DIR), name="generated_audio") # Application lifecycle events for TTS model management @app.on_event("startup") async def startup_event(): """Load TTS model on application startup.""" print("🚀 Starting Chatterbox TTS API...") tts_service = get_global_tts_service() tts_service.load_model() print("✅ TTS model loaded and ready!") @app.on_event("shutdown") async def shutdown_event(): """Unload TTS model on application shutdown.""" print("🔄 Shutting down Chatterbox TTS API...") tts_service = get_global_tts_service() tts_service.unload_model() print("✅ TTS model unloaded. Goodbye!") # Further endpoints for speakers, dialog generation, etc., will be added here.