import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles import logging import dashscope from pathlib import Path from lover.routers import voice_call as voice_call_router from lover.response import ApiResponse from lover.config import settings # 初始化 DashScope API Key if settings.DASHSCOPE_API_KEY: dashscope.api_key = settings.DASHSCOPE_API_KEY # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) app = FastAPI(title="LOVER API - Simple") # 创建 TTS 文件目录 tts_dir = Path("public/tts") tts_dir.mkdir(parents=True, exist_ok=True) # 挂载静态文件服务(用于提供 TTS 音频文件) app.mount("/tts", StaticFiles(directory=str(tts_dir)), name="tts") app.add_middleware( CORSMiddleware, allow_origins=["*"], # 简化 CORS 配置 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 只包含语音通话路由 app.include_router(voice_call_router.router) @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): detail = exc.detail msg = detail if isinstance(detail, str) else str(detail) return JSONResponse( status_code=exc.status_code, content={"code": exc.status_code, "msg": msg, "data": None}, ) @app.exception_handler(Exception) async def generic_exception_handler(request: Request, exc: Exception): logging.exception("Unhandled error", exc_info=exc) return JSONResponse( status_code=500, content={"code": 500, "msg": "服务器内部错误", "data": None}, ) @app.get("/health", response_model=ApiResponse[dict]) async def health(): return ApiResponse(code=1, msg="ok", data={"status": "ok"}) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=30102)