Update app/main.py
Browse files- app/main.py +67 -8
app/main.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import sys
|
| 2 |
-
from pathlib import Path
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
# 1. 强行重定向数据路径到 Hugging Face 运行期不灭网盘 /data
|
| 6 |
import app.platform.paths
|
|
@@ -9,25 +12,24 @@ def patched_data_path(*args):
|
|
| 9 |
hf_data = Path("/data")
|
| 10 |
if hf_data.exists():
|
| 11 |
try:
|
| 12 |
-
# 自动创建子目录,确保存储卷内部组件读写不报错
|
| 13 |
hf_data.mkdir(parents=True, exist_ok=True)
|
| 14 |
return hf_data.joinpath(*args)
|
| 15 |
except Exception:
|
| 16 |
pass
|
| 17 |
-
# 本地开发环境兜底
|
| 18 |
local_path = Path(__file__).resolve().parent.parent / "data"
|
| 19 |
local_path.mkdir(parents=True, exist_ok=True)
|
| 20 |
return local_path.joinpath(*args)
|
| 21 |
|
| 22 |
app.platform.paths.data_path = patched_data_path
|
| 23 |
|
| 24 |
-
# 2. 强行在内存级接管 snapshot 配置管理器,防止数据库锁死老
|
| 25 |
import app.platform.config.snapshot
|
| 26 |
_config = app.platform.config.snapshot.config
|
| 27 |
|
| 28 |
_orig_get_str = _config.get_str
|
| 29 |
def _patched_get_str(key: str, default: str = "") -> str:
|
| 30 |
-
# 无论数据库或TOML里锁了什么,内存中强制让密码对齐你在 HF 后台配的专属隐藏密码
|
| 31 |
if key in ("app.app_key", "app.api_key", "app.webui_key"):
|
| 32 |
return os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C")
|
| 33 |
if key == "app.app_url":
|
|
@@ -55,6 +57,7 @@ Start with:
|
|
| 55 |
"""
|
| 56 |
|
| 57 |
import asyncio
|
|
|
|
| 58 |
from contextlib import asynccontextmanager
|
| 59 |
from dotenv import load_dotenv
|
| 60 |
from fastapi import FastAPI, Request
|
|
@@ -70,7 +73,6 @@ from app.platform.storage import reconcile_local_media_cache_async
|
|
| 70 |
|
| 71 |
load_dotenv()
|
| 72 |
|
| 73 |
-
# 此时导入的 data_path 将百分之百是我们上面拦截重定向后的安全路径
|
| 74 |
from app.platform.paths import data_path
|
| 75 |
|
| 76 |
# ---------------------------------------------------------------------------
|
|
@@ -295,9 +297,28 @@ async def lifespan(app: FastAPI):
|
|
| 295 |
# ---------------------------------------------------------------------------
|
| 296 |
|
| 297 |
def create_app() -> FastAPI:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
app = FastAPI(
|
| 299 |
title="Grok2API",
|
| 300 |
version=get_project_version(),
|
|
|
|
|
|
|
| 301 |
lifespan=lifespan,
|
| 302 |
)
|
| 303 |
|
|
@@ -322,11 +343,41 @@ def create_app() -> FastAPI:
|
|
| 322 |
|
| 323 |
@app.exception_handler(RequestValidationError)
|
| 324 |
async def _request_validation_handler(request: Request, exc: RequestValidationError):
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
@app.exception_handler(Exception)
|
| 328 |
async def _generic_error_handler(request: Request, exc: Exception):
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
|
| 331 |
from app.products.web import router as web_router
|
| 332 |
from app.products.openai.router import router as openai_router
|
|
@@ -340,6 +391,14 @@ def create_app() -> FastAPI:
|
|
| 340 |
if _statics_dir.is_dir():
|
| 341 |
app.mount("/static", StaticFiles(directory=_statics_dir), name="static")
|
| 342 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
@app.get("/health", include_in_schema=False)
|
| 344 |
def health():
|
| 345 |
return {"status": "ok"}
|
|
|
|
| 1 |
+
# ===========================================================================
|
| 2 |
+
# 🌟 终极云原生拦截流:必须放在文件最顶部(第1行),确保在所有原版组件加载前完成重定向
|
| 3 |
+
# ===========================================================================
|
| 4 |
import sys
|
|
|
|
| 5 |
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
|
| 8 |
# 1. 强行重定向数据路径到 Hugging Face 运行期不灭网盘 /data
|
| 9 |
import app.platform.paths
|
|
|
|
| 12 |
hf_data = Path("/data")
|
| 13 |
if hf_data.exists():
|
| 14 |
try:
|
|
|
|
| 15 |
hf_data.mkdir(parents=True, exist_ok=True)
|
| 16 |
return hf_data.joinpath(*args)
|
| 17 |
except Exception:
|
| 18 |
pass
|
| 19 |
+
# 本地开发环境降级兜底
|
| 20 |
local_path = Path(__file__).resolve().parent.parent / "data"
|
| 21 |
local_path.mkdir(parents=True, exist_ok=True)
|
| 22 |
return local_path.joinpath(*args)
|
| 23 |
|
| 24 |
app.platform.paths.data_path = patched_data_path
|
| 25 |
|
| 26 |
+
# 2. 强行在内存级接管 snapshot 配置管理器,防止数据库锁死老配置
|
| 27 |
import app.platform.config.snapshot
|
| 28 |
_config = app.platform.config.snapshot.config
|
| 29 |
|
| 30 |
_orig_get_str = _config.get_str
|
| 31 |
def _patched_get_str(key: str, default: str = "") -> str:
|
| 32 |
+
# 无论数据库或 TOML 里锁了什么,内存中强制让密码对齐你在 HF 后台配的专属隐藏密码
|
| 33 |
if key in ("app.app_key", "app.api_key", "app.webui_key"):
|
| 34 |
return os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C")
|
| 35 |
if key == "app.app_url":
|
|
|
|
| 57 |
"""
|
| 58 |
|
| 59 |
import asyncio
|
| 60 |
+
import platform # 🌟 完美修复:补齐核心平台依赖包,彻底告别 NameError
|
| 61 |
from contextlib import asynccontextmanager
|
| 62 |
from dotenv import load_dotenv
|
| 63 |
from fastapi import FastAPI, Request
|
|
|
|
| 73 |
|
| 74 |
load_dotenv()
|
| 75 |
|
|
|
|
| 76 |
from app.platform.paths import data_path
|
| 77 |
|
| 78 |
# ---------------------------------------------------------------------------
|
|
|
|
| 297 |
# ---------------------------------------------------------------------------
|
| 298 |
|
| 299 |
def create_app() -> FastAPI:
|
| 300 |
+
openapi_tags = [
|
| 301 |
+
{"name": "OpenAI - Models", "description": "Model discovery endpoints."},
|
| 302 |
+
{"name": "OpenAI - Chat", "description": "Chat Completions compatible endpoints."},
|
| 303 |
+
{"name": "OpenAI - Responses", "description": "Responses API compatible endpoints."},
|
| 304 |
+
{"name": "OpenAI - Images", "description": "Image generation and image edit endpoints."},
|
| 305 |
+
{"name": "OpenAI - Videos", "description": "Video job creation and retrieval endpoints."},
|
| 306 |
+
{"name": "OpenAI - Files", "description": "Locally cached media file endpoints."},
|
| 307 |
+
{"name": "Anthropic - Messages", "description": "Anthropic Messages API compatible endpoints."},
|
| 308 |
+
{"name": "Admin - System", "description": "Admin system status and runtime configuration endpoints."},
|
| 309 |
+
{"name": "Admin - Tokens", "description": "Admin account token management endpoints."},
|
| 310 |
+
{"name": "Admin - Batch", "description": "Admin batch operation endpoints."},
|
| 311 |
+
{"name": "Admin - Assets", "description": "Admin online asset management endpoints."},
|
| 312 |
+
{"name": "Admin - Cache", "description": "Admin local cache management endpoints."},
|
| 313 |
+
{"name": "WebUI - System", "description": "WebUI authentication and system endpoints."},
|
| 314 |
+
{"name": "WebUI - Chat", "description": "WebUI chat API endpoints."},
|
| 315 |
+
{"name": "WebUI - Voice", "description": "WebUI voice API endpoints."},
|
| 316 |
+
]
|
| 317 |
app = FastAPI(
|
| 318 |
title="Grok2API",
|
| 319 |
version=get_project_version(),
|
| 320 |
+
description="OpenAI-compatible API gateway for Grok",
|
| 321 |
+
openapi_tags=openapi_tags,
|
| 322 |
lifespan=lifespan,
|
| 323 |
)
|
| 324 |
|
|
|
|
| 343 |
|
| 344 |
@app.exception_handler(RequestValidationError)
|
| 345 |
async def _request_validation_handler(request: Request, exc: RequestValidationError):
|
| 346 |
+
errors = exc.errors()
|
| 347 |
+
first = errors[0] if errors else {}
|
| 348 |
+
loc = tuple(first.get("loc") or ())
|
| 349 |
+
param_parts = [
|
| 350 |
+
str(part)
|
| 351 |
+
for part in loc
|
| 352 |
+
if str(part) not in {"body", "query", "path", "header", "cookie"}
|
| 353 |
+
]
|
| 354 |
+
param = ".".join(param_parts)
|
| 355 |
+
message = first.get("msg") or "Request validation failed"
|
| 356 |
+
logger.warning(
|
| 357 |
+
"request validation failed: method={} path={} param={} errors={}",
|
| 358 |
+
request.method,
|
| 359 |
+
request.url.path,
|
| 360 |
+
param or "-",
|
| 361 |
+
errors,
|
| 362 |
+
)
|
| 363 |
+
payload = {
|
| 364 |
+
"error": {
|
| 365 |
+
"message": message,
|
| 366 |
+
"type": "invalid_request_error",
|
| 367 |
+
"code": "invalid_value",
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
if param:
|
| 371 |
+
payload["error"]["param"] = param
|
| 372 |
+
return JSONResponse(payload, status_code=400)
|
| 373 |
|
| 374 |
@app.exception_handler(Exception)
|
| 375 |
async def _generic_error_handler(request: Request, exc: Exception):
|
| 376 |
+
logger.exception("unhandled application exception: error={}", exc)
|
| 377 |
+
return JSONResponse(
|
| 378 |
+
{"error": {"message": "Internal server error", "type": "server_error"}},
|
| 379 |
+
status_code=500,
|
| 380 |
+
)
|
| 381 |
|
| 382 |
from app.products.web import router as web_router
|
| 383 |
from app.products.openai.router import router as openai_router
|
|
|
|
| 391 |
if _statics_dir.is_dir():
|
| 392 |
app.mount("/static", StaticFiles(directory=_statics_dir), name="static")
|
| 393 |
|
| 394 |
+
@app.get("/favicon.ico", include_in_schema=False)
|
| 395 |
+
def favicon():
|
| 396 |
+
from fastapi.responses import FileResponse as _FR
|
| 397 |
+
_ico = _statics_dir / "favicon.ico"
|
| 398 |
+
if _ico.exists():
|
| 399 |
+
return _FR(_ico)
|
| 400 |
+
return JSONResponse({"error": "not found"}, status_code=404)
|
| 401 |
+
|
| 402 |
@app.get("/health", include_in_schema=False)
|
| 403 |
def health():
|
| 404 |
return {"status": "ok"}
|