Download app/main.py from LifeVta/Grok3API: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/spaces/LifeVta/Grok3API/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/LifeVta/Grok3API/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/LifeVta/Grok3API/resolve/main/app/main.py
14.5 kB
| # =========================================================================== | |
| # 🌟 终极云原生拦截流:必须放在文件最顶部(第1行),确保在所有原版组件加载前完成重定向 | |
| # =========================================================================== | |
| import sys | |
| import os | |
| from pathlib import Path | |
| # 1. 强行重定向数据路径到 Hugging Face 运行期不灭网盘 /data | |
| import app.platform.paths | |
| def patched_data_path(*args): | |
| hf_data = Path("/data") | |
| if hf_data.exists(): | |
| try: | |
| hf_data.mkdir(parents=True, exist_ok=True) | |
| return hf_data.joinpath(*args) | |
| except Exception: | |
| pass | |
| # 本地开发环境降级兜底 | |
| local_path = Path(__file__).resolve().parent.parent / "data" | |
| local_path.mkdir(parents=True, exist_ok=True) | |
| return local_path.joinpath(*args) | |
| app.platform.paths.data_path = patched_data_path | |
| # 2. 强行在内存级接管 snapshot 配置管理器,防止数据库锁死老配置 | |
| import app.platform.config.snapshot | |
| _config = app.platform.config.snapshot.config | |
| _orig_get_str = _config.get_str | |
| def _patched_get_str(key: str, default: str = "") -> str: | |
| # 无论数据库或 TOML 里锁了什么,内存中强制让密码对齐你在 HF 后台配的专属隐藏密码 | |
| if key in ("app.app_key", "app.api_key", "app.webui_key"): | |
| return os.getenv("APP_ACCESS_PASSWORD", "93AXD*80%life=C") | |
| if key == "app.app_url": | |
| return "https://lifevta-grok2api.hf.space/" | |
| return _orig_get_str(key, default) | |
| _config.get_str = _patched_get_str | |
| _orig_get_bool = _config.get_bool | |
| def _patched_get_bool(key: str, default: bool = False) -> bool: | |
| # 内存中强行焊死前端所有功能开关状态(完美对齐图3、图4) | |
| if key == "app.webui_enabled": | |
| return True | |
| if key == "features.temporary": | |
| return False | |
| if key in ("features.memory", "features.thinking_summary", "features.dynamic_statsig", "features.enable_nsfw"): | |
| return True | |
| return _orig_get_bool(key, default) | |
| _config.get_bool = _patched_get_bool | |
| # =========================================================================== | |
| """Grok2API application entry point. | |
| Start with: | |
| uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app | |
| """ | |
| import asyncio | |
| import platform # 🌟 完美修复:补齐核心平台依赖包,彻底告别 NameError | |
| from contextlib import asynccontextmanager | |
| from dotenv import load_dotenv | |
| from fastapi import FastAPI, Request | |
| from fastapi.exceptions import RequestValidationError | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from app.platform.logging.logger import logger, setup_logging, reload_logging | |
| from app.platform.errors import AppError | |
| from app.platform.meta import get_project_version | |
| from app.platform.storage import reconcile_local_media_cache_async | |
| load_dotenv() | |
| from app.platform.paths import data_path | |
| # --------------------------------------------------------------------------- | |
| # Scheduler leader-election via advisory file lock | |
| # --------------------------------------------------------------------------- | |
| _LOCK_FILE = data_path(".scheduler.lock") | |
| _lock_fd: int | None = None | |
| def _try_acquire_scheduler_lock() -> bool: | |
| global _lock_fd | |
| try: | |
| import fcntl | |
| _LOCK_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| fd = os.open(str(_LOCK_FILE), os.O_CREAT | os.O_WRONLY) | |
| fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| _lock_fd = fd | |
| return True | |
| except BlockingIOError: | |
| return False | |
| except (ImportError, OSError, AttributeError): | |
| return True | |
| def _release_scheduler_lock() -> None: | |
| global _lock_fd | |
| if _lock_fd is None: | |
| return | |
| try: | |
| import fcntl | |
| fcntl.flock(_lock_fd, fcntl.LOCK_UN) | |
| os.close(_lock_fd) | |
| except (ImportError, OSError): | |
| pass | |
| _lock_fd = None | |
| # --------------------------------------------------------------------------- | |
| # Early logging setup | |
| # --------------------------------------------------------------------------- | |
| setup_logging( | |
| level=os.getenv("LOG_LEVEL", "INFO"), | |
| file_logging=os.getenv("LOG_FILE_ENABLED", "true").strip().lower() | |
| in {"1", "true", "yes", "on"}, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Lifespan | |
| # --------------------------------------------------------------------------- | |
| async def lifespan(app: FastAPI): | |
| # 1. Load configuration. | |
| await _config.load() | |
| reload_logging( | |
| level=os.getenv("LOG_LEVEL", "INFO"), | |
| file_level=_config.get_str("logging.file_level", "") or None, | |
| max_files=_config.get_int("logging.max_files", 7), | |
| ) | |
| logger.info( | |
| "application startup: service=grok2api python={} platform={}", | |
| sys.version.split()[0], | |
| platform.system(), | |
| ) | |
| # 2. Initialise account repository | |
| from app.control.account.backends.factory import ( | |
| create_repository, | |
| describe_repository_target, | |
| ) | |
| from app.control.account.runtime import ( | |
| reconcile_refresh_runtime, | |
| set_refresh_scheduler, | |
| set_refresh_scheduler_leader, | |
| set_refresh_service, | |
| ) | |
| from app.control.account.scheduler import get_account_refresh_scheduler | |
| from app.dataplane.account import get_account_directory | |
| storage_backend, storage_target = describe_repository_target() | |
| logger.info( | |
| "account storage configured: backend={} target={}", | |
| storage_backend, | |
| storage_target, | |
| ) | |
| repo = create_repository() | |
| await repo.initialize() | |
| # 2a. First-boot migrations | |
| from app.platform.startup import run_startup_migrations | |
| await run_startup_migrations( | |
| config_backend=_config._get_backend(), | |
| account_repo=repo, | |
| ) | |
| await _config.load() | |
| await reconcile_local_media_cache_async() | |
| directory = await get_account_directory(repo) | |
| app.state.repository = repo | |
| app.state.directory = directory | |
| # 3. Account directory sync loop | |
| _SYNC_IDLE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_INTERVAL", "30")) | |
| _SYNC_ACTIVE_INTERVAL = int(os.getenv("ACCOUNT_SYNC_ACTIVE_INTERVAL", "3")) | |
| _SYNC_IDLE_AFTER = 5 | |
| async def _sync_loop() -> None: | |
| idle_streak = 0 | |
| while True: | |
| interval = ( | |
| _SYNC_ACTIVE_INTERVAL | |
| if idle_streak < _SYNC_IDLE_AFTER | |
| else _SYNC_IDLE_INTERVAL | |
| ) | |
| await asyncio.sleep(interval) | |
| try: | |
| changed = await directory.sync_if_changed() | |
| idle_streak = 0 if changed else min(idle_streak + 1, _SYNC_IDLE_AFTER) | |
| except asyncio.CancelledError: | |
| raise | |
| except Exception as exc: | |
| logger.debug("account directory sync error: error={}", exc) | |
| idle_streak = _SYNC_IDLE_AFTER | |
| sync_task = asyncio.create_task(_sync_loop(), name="account-dir-sync") | |
| # 4. Account refresh scheduler | |
| from app.control.account.refresh import AccountRefreshService | |
| refresh_enabled = _config.get_bool("account.refresh.enabled", False) | |
| refresh_svc = AccountRefreshService(repo) | |
| set_refresh_service(refresh_svc) | |
| app.state.refresh_service = refresh_svc | |
| is_leader = _try_acquire_scheduler_lock() | |
| scheduler = get_account_refresh_scheduler(refresh_svc) | |
| set_refresh_scheduler(scheduler) | |
| set_refresh_scheduler_leader(is_leader) | |
| app.state.account_refresh_scheduler = scheduler | |
| app.state.account_refresh_is_leader = is_leader | |
| strategy_name = reconcile_refresh_runtime(refresh_enabled) | |
| # 5. Initialise proxy directory | |
| from app.control.proxy import get_proxy_directory | |
| from app.control.proxy.scheduler import ProxyClearanceScheduler | |
| proxy_dir = await get_proxy_directory() | |
| proxy_scheduler = ProxyClearanceScheduler(proxy_dir) | |
| if is_leader: | |
| proxy_scheduler.start() | |
| # 6. Console 配额窗口自动重置任务 | |
| _CONSOLE_RESET_INTERVAL = 30 | |
| async def _console_reset_loop() -> None: | |
| while True: | |
| await asyncio.sleep(_CONSOLE_RESET_INTERVAL) | |
| try: | |
| await refresh_svc.reset_expired_console_windows() | |
| except asyncio.CancelledError: | |
| raise | |
| except Exception: | |
| pass | |
| console_reset_task = asyncio.create_task( | |
| _console_reset_loop(), name="console-quota-reset" | |
| ) if is_leader else None | |
| # 7. Console 429 EXPIRED 账号自动恢复任务 | |
| _CONSOLE_RECOVERY_INTERVAL = 600 | |
| async def _console_recovery_loop() -> None: | |
| while True: | |
| await asyncio.sleep(_CONSOLE_RECOVERY_INTERVAL) | |
| try: | |
| await refresh_svc.recover_console_expired_accounts() | |
| except asyncio.CancelledError: | |
| raise | |
| except Exception: | |
| pass | |
| console_recovery_task = asyncio.create_task( | |
| _console_recovery_loop(), name="console-expired-recovery" | |
| ) if is_leader else None | |
| logger.info("application startup completed") | |
| yield | |
| # ----------- | |
| # Shutdown | |
| # ----------- | |
| if console_reset_task is not None: | |
| console_reset_task.cancel() | |
| if console_recovery_task is not None: | |
| console_recovery_task.cancel() | |
| sync_task.cancel() | |
| if is_leader: | |
| scheduler.stop() | |
| proxy_scheduler.stop() | |
| _release_scheduler_lock() | |
| set_refresh_scheduler(None) | |
| set_refresh_scheduler_leader(False) | |
| set_refresh_service(None) | |
| await repo.close() | |
| # --------------------------------------------------------------------------- | |
| # Application factory | |
| # --------------------------------------------------------------------------- | |
| def create_app() -> FastAPI: | |
| openapi_tags = [ | |
| {"name": "OpenAI - Models", "description": "Model discovery endpoints."}, | |
| {"name": "OpenAI - Chat", "description": "Chat Completions compatible endpoints."}, | |
| {"name": "OpenAI - Responses", "description": "Responses API compatible endpoints."}, | |
| {"name": "OpenAI - Images", "description": "Image generation and image edit endpoints."}, | |
| {"name": "OpenAI - Videos", "description": "Video job creation and retrieval endpoints."}, | |
| {"name": "OpenAI - Files", "description": "Locally cached media file endpoints."}, | |
| {"name": "Anthropic - Messages", "description": "Anthropic Messages API compatible endpoints."}, | |
| {"name": "Admin - System", "description": "Admin system status and runtime configuration endpoints."}, | |
| {"name": "Admin - Tokens", "description": "Admin account token management endpoints."}, | |
| {"name": "Admin - Batch", "description": "Admin batch operation endpoints."}, | |
| {"name": "Admin - Assets", "description": "Admin online asset management endpoints."}, | |
| {"name": "Admin - Cache", "description": "Admin local cache management endpoints."}, | |
| {"name": "WebUI - System", "description": "WebUI authentication and system endpoints."}, | |
| {"name": "WebUI - Chat", "description": "WebUI chat API endpoints."}, | |
| {"name": "WebUI - Voice", "description": "WebUI voice API endpoints."}, | |
| ] | |
| app = FastAPI( | |
| title="Grok2API", | |
| version=get_project_version(), | |
| description="OpenAI-compatible API gateway for Grok", | |
| openapi_tags=openapi_tags, | |
| lifespan=lifespan, | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| async def _ensure_config(request: Request, call_next): | |
| from app.control.account.runtime import reconcile_refresh_runtime | |
| await _config.load() | |
| reconcile_refresh_runtime() | |
| return await call_next(request) | |
| async def _app_error_handler(request: Request, exc: AppError): | |
| return JSONResponse(exc.to_dict(), status_code=exc.status) | |
| async def _request_validation_handler(request: Request, exc: RequestValidationError): | |
| errors = exc.errors() | |
| first = errors[0] if errors else {} | |
| loc = tuple(first.get("loc") or ()) | |
| param_parts = [ | |
| str(part) | |
| for part in loc | |
| if str(part) not in {"body", "query", "path", "header", "cookie"} | |
| ] | |
| param = ".".join(param_parts) | |
| message = first.get("msg") or "Request validation failed" | |
| logger.warning( | |
| "request validation failed: method={} path={} param={} errors={}", | |
| request.method, | |
| request.url.path, | |
| param or "-", | |
| errors, | |
| ) | |
| payload = { | |
| "error": { | |
| "message": message, | |
| "type": "invalid_request_error", | |
| "code": "invalid_value", | |
| } | |
| } | |
| if param: | |
| payload["error"]["param"] = param | |
| return JSONResponse(payload, status_code=400) | |
| async def _generic_error_handler(request: Request, exc: Exception): | |
| logger.exception("unhandled application exception: error={}", exc) | |
| return JSONResponse( | |
| {"error": {"message": "Internal server error", "type": "server_error"}}, | |
| status_code=500, | |
| ) | |
| from app.products.web import router as web_router | |
| from app.products.openai.router import router as openai_router | |
| from app.products.anthropic.router import router as anthropic_router | |
| app.include_router(web_router) | |
| app.include_router(openai_router) | |
| app.include_router(anthropic_router) | |
| _statics_dir = Path(__file__).resolve().parent / "statics" | |
| if _statics_dir.is_dir(): | |
| app.mount("/static", StaticFiles(directory=_statics_dir), name="static") | |
| def favicon(): | |
| from fastapi.responses import FileResponse as _FR | |
| _ico = _statics_dir / "favicon.ico" | |
| if _ico.exists(): | |
| return _FR(_ico) | |
| return JSONResponse({"error": "not found"}, status_code=404) | |
| def health(): | |
| return {"status": "ok"} | |
| return app | |
| app = create_app() |