from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.documents import router as documents_router from app.api.onboarding import router as onboarding_router from app.api.voice_onboarding import router as voice_router from app.database import models from app.database.database import Base, engine @asynccontextmanager async def lifespan(app: FastAPI): Base.metadata.create_all(bind=engine) yield app = FastAPI( title="AI Patient Onboarding API", description="Multi-Model Voice-First Hospital Patient Onboarding Engine (Sarvam + OpenAI + Claude + Gemini)", version="1.0.0", lifespan=lifespan, ) from uuid import uuid4 from fastapi import Request from fastapi.responses import JSONResponse from app.config import CORS_ORIGINS # Global Exception Handler (Hides Stack Traces in Production) @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): import traceback print(f"[Unhandled Server Error] Path: {request.url.path} Error: {exc}") traceback.print_exc() return JSONResponse( status_code=500, content={ "success": False, "error": { "code": "INTERNAL_SERVER_ERROR", "message": "An unexpected internal server error occurred. Please contact system administration.", } } ) # Security Headers & Request Correlation Middleware @app.middleware("http") async def security_and_request_id_middleware(request: Request, call_next): request_id = request.headers.get("X-Request-ID") or f"req_{uuid4().hex[:12]}" response = await call_next(request) response.headers["X-Request-ID"] = request_id response.headers["X-Content-Type-Options"] = "nosniff" response.headers["X-Frame-Options"] = "DENY" response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" return response # Enable Production-Safe CORS for React Web & Mobile clients (Outermost Layer) app.add_middleware( CORSMiddleware, allow_origins=CORS_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], expose_headers=["X-Request-ID"], ) app.include_router(onboarding_router) app.include_router(voice_router) app.include_router(documents_router) from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse import os docs_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "docs") if os.path.exists(docs_dir): app.mount("/static", StaticFiles(directory=docs_dir), name="static") @app.get("/") @app.get("/dashboard") async def serve_dashboard(): dashboard_path = os.path.join(docs_dir, "index.html") if os.path.exists(dashboard_path): return FileResponse(dashboard_path) return {"message": "CureSelect AI Voice Backend Ready"} @app.get("/health") async def health(): return { "success": True, "service": "AI Patient Onboarding", "status": "healthy", "models": { "speech": "Sarvam AI (Indian Languages) / OpenAI Whisper", "conversation": "OpenAI GPT-4o-mini", "validation": "Claude 3.5 Sonnet", "vision_documents": "Gemini 1.5 Flash", }, }