import os import sys import uvicorn from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pathlib import Path # 设置项目根目录 sys.path.insert(0, str(Path(__file__).parent)) # 导入项目模块 try: from api_utils.app import create_app from api_utils.routes import router as api_router from config.settings import Settings except ImportError as e: print(f"导入错误: {e}") print("正在克隆项目代码...") # 如果没有项目代码,自动克隆 import subprocess subprocess.run([ "git", "clone", "https://github.com/CJackHwang/AIstudioProxyAPI.git", "." ], check=True) # 重新导入 from api_utils.app import create_app from api_utils.routes import router as api_router from config.settings import Settings # 创建FastAPI应用 app = create_app() # 添加CORS中间件 app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 健康检查端点 @app.get("/health") async def health_check(): return {"status": "healthy", "message": "AI Studio Proxy API is running"} # 根路径重定向到API文档 @app.get("/") async def root(): return {"message": "欢迎使用AI Studio Proxy API", "docs_url": "/docs"} # 启动服务器 if __name__ == "__main__": port = int(os.getenv("PORT", 7860)) print(f"启动服务器,端口: {port}") uvicorn.run( "app:app", host="0.0.0.0", port=port, reload=False, workers=1 )