Download app.py from dakl45646/2: direct link, hf CLI and curl.
- Browser
- Download file 4.23 kB
-
https://huggingface.co/spaces/dakl45646/2/resolve/main/app.py
- Command line
-
hf download hf://spaces/dakl45646/2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dakl45646/2/resolve/main/app.py
4.23 kB
| import os | |
| import sys | |
| import uvicorn | |
| import logging | |
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse, RedirectResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| from pathlib import Path | |
| import time | |
| # 设置日志 | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # 设置项目根目录 | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| # 创建FastAPI应用 | |
| app = FastAPI( | |
| title="AI Studio Proxy API", | |
| description="将Google AI Studio网页界面转换为OpenAI兼容API", | |
| version="1.0.0", | |
| docs_url="/docs", | |
| redoc_url="/redoc", | |
| openapi_url="/openapi.json" | |
| ) | |
| # 添加CORS中间件 | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # 全局状态 | |
| app.state.startup_time = time.time() | |
| app.state.is_ready = False | |
| # 健康检查端点 | |
| async def health_check(): | |
| """健康检查端点""" | |
| uptime = time.time() - app.state.startup_time | |
| return { | |
| "status": "healthy" if app.state.is_ready else "starting", | |
| "uptime_seconds": round(uptime, 2), | |
| "uptime_human": f"{uptime:.0f}秒", | |
| "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), | |
| "version": "1.0.0" | |
| } | |
| # 根路径重定向到Web UI或文档 | |
| async def root(request: Request): | |
| """根路径重定向""" | |
| return { | |
| "message": "欢迎使用AI Studio Proxy API", | |
| "docs_url": "/docs", | |
| "redoc_url": "/redoc", | |
| "api_base_url": "/v1", | |
| "web_ui_url": "/ui", | |
| "health_check_url": "/health" | |
| } | |
| # 尝试导入并挂载项目路由 | |
| try: | |
| from api_utils.routes import router as api_router | |
| app.include_router(api_router, prefix="/v1") | |
| logger.info("✅ 成功导入API路由") | |
| app.state.is_ready = True | |
| except ImportError as e: | |
| logger.error(f"⚠️ API路由导入失败: {e}") | |
| async def show_error(): | |
| return JSONResponse( | |
| status_code=500, | |
| content={ | |
| "error": "API路由加载失败", | |
| "message": str(e), | |
| "details": "请检查项目代码是否正确克隆和安装" | |
| } | |
| ) | |
| async def api_fallback(path: str): | |
| return JSONResponse( | |
| status_code=503, | |
| content={ | |
| "error": "服务暂时不可用", | |
| "message": "API服务正在启动中,请稍后重试", | |
| "path": f"/v1/{path}" | |
| } | |
| ) | |
| # 404处理 | |
| async def not_found_handler(request: Request, exc: HTTPException): | |
| return JSONResponse( | |
| status_code=404, | |
| content={ | |
| "error": "Not Found", | |
| "message": f"路径 {request.url.path} 不存在", | |
| "available_endpoints": [ | |
| "/", | |
| "/docs", | |
| "/redoc", | |
| "/health", | |
| "/v1/chat/completions" | |
| ] | |
| } | |
| ) | |
| # 500错误处理 | |
| async def server_error_handler(request: Request, exc: Exception): | |
| logger.error(f"服务器错误: {exc}", exc_info=True) | |
| return JSONResponse( | |
| status_code=500, | |
| content={ | |
| "error": "Internal Server Error", | |
| "message": "服务器内部错误", | |
| "path": request.url.path | |
| } | |
| ) | |
| # 启动配置 | |
| def start_server(): | |
| """启动服务器""" | |
| port = int(os.getenv("PORT", 7860)) | |
| host = os.getenv("HOST", "0.0.0.0") | |
| logger.info(f"🚀 启动服务器 {host}:{port}") | |
| logger.info(f"📅 启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}") | |
| uvicorn.run( | |
| "app:app", | |
| host=host, | |
| port=port, | |
| reload=False, | |
| workers=1, | |
| log_level="info", | |
| access_log=True | |
| ) | |
| if __name__ == "__main__": | |
| start_server() |