|
1 | | -from fastapi import APIRouter, Depends, HTTPException, Request, Query, Body |
| 1 | +from fastapi import APIRouter, Depends, HTTPException, Request, Query, Body, WebSocket |
2 | 2 | from fastapi.responses import HTMLResponse, RedirectResponse |
3 | 3 | from pydantic import BaseModel |
4 | | -from typing import Any |
| 4 | +from typing import Any, Optional |
5 | 5 |
|
6 | 6 | from app.core.auth import verify_api_key |
7 | 7 | from app.core.config import config, get_config |
|
11 | 11 | import aiofiles |
12 | 12 | import asyncio |
13 | 13 | import json |
| 14 | +import time |
| 15 | +import uuid |
| 16 | +import orjson |
| 17 | +from starlette.websockets import WebSocketDisconnect, WebSocketState |
14 | 18 | from app.core.logger import logger |
15 | 19 | from app.services.register import get_auto_register_manager |
16 | 20 | from app.services.api_keys import api_key_manager |
| 21 | +from app.services.grok.model import ModelService |
| 22 | +from app.services.grok.imagine_generation import ( |
| 23 | + collect_experimental_generation_images, |
| 24 | + is_valid_image_value as is_valid_imagine_image_value, |
| 25 | + resolve_aspect_ratio as resolve_imagine_aspect_ratio, |
| 26 | +) |
| 27 | +from app.services.token import get_token_manager |
| 28 | +from app.core.auth import _load_legacy_api_keys |
17 | 29 |
|
18 | 30 |
|
19 | 31 | router = APIRouter() |
@@ -82,6 +94,224 @@ async def admin_chat_page(): |
82 | 94 | """在线聊天页(后台入口)""" |
83 | 95 | return await render_template("chat/chat_admin.html") |
84 | 96 |
|
| 97 | + |
| 98 | +async def _verify_ws_api_key(websocket: WebSocket) -> bool: |
| 99 | + api_key = str(get_config("app.api_key", "") or "").strip() |
| 100 | + legacy_keys = await _load_legacy_api_keys() |
| 101 | + if not api_key and not legacy_keys: |
| 102 | + return True |
| 103 | + token = str(websocket.query_params.get("api_key") or "").strip() |
| 104 | + if not token: |
| 105 | + return False |
| 106 | + if (api_key and token == api_key) or token in legacy_keys: |
| 107 | + return True |
| 108 | + try: |
| 109 | + await api_key_manager.init() |
| 110 | + if api_key_manager.validate_key(token): |
| 111 | + return True |
| 112 | + except Exception as e: |
| 113 | + logger.warning(f"Imagine ws api_key validation fallback failed: {e}") |
| 114 | + return False |
| 115 | + |
| 116 | + |
| 117 | +async def _collect_imagine_batch(token: str, prompt: str, aspect_ratio: str) -> list[str]: |
| 118 | + return await collect_experimental_generation_images( |
| 119 | + token=token, |
| 120 | + prompt=prompt, |
| 121 | + n=6, |
| 122 | + response_format="b64_json", |
| 123 | + aspect_ratio=aspect_ratio, |
| 124 | + concurrency=1, |
| 125 | + ) |
| 126 | + |
| 127 | + |
| 128 | +@router.websocket("/api/v1/admin/imagine/ws") |
| 129 | +async def admin_imagine_ws(websocket: WebSocket): |
| 130 | + if not await _verify_ws_api_key(websocket): |
| 131 | + await websocket.close(code=1008) |
| 132 | + return |
| 133 | + |
| 134 | + await websocket.accept() |
| 135 | + stop_event = asyncio.Event() |
| 136 | + run_task: Optional[asyncio.Task] = None |
| 137 | + |
| 138 | + async def _send(payload: dict) -> bool: |
| 139 | + try: |
| 140 | + await websocket.send_text(orjson.dumps(payload).decode()) |
| 141 | + return True |
| 142 | + except Exception: |
| 143 | + return False |
| 144 | + |
| 145 | + async def _stop_run(): |
| 146 | + nonlocal run_task |
| 147 | + stop_event.set() |
| 148 | + if run_task and not run_task.done(): |
| 149 | + run_task.cancel() |
| 150 | + try: |
| 151 | + await run_task |
| 152 | + except Exception: |
| 153 | + pass |
| 154 | + run_task = None |
| 155 | + stop_event.clear() |
| 156 | + |
| 157 | + async def _run(prompt: str, aspect_ratio: str): |
| 158 | + model_id = "grok-imagine-1.0" |
| 159 | + model_info = ModelService.get(model_id) |
| 160 | + if not model_info or not model_info.is_image: |
| 161 | + await _send( |
| 162 | + { |
| 163 | + "type": "error", |
| 164 | + "message": "Image model is not available.", |
| 165 | + "code": "model_not_supported", |
| 166 | + } |
| 167 | + ) |
| 168 | + return |
| 169 | + |
| 170 | + token_mgr = await get_token_manager() |
| 171 | + sequence = 0 |
| 172 | + run_id = uuid.uuid4().hex |
| 173 | + await _send( |
| 174 | + { |
| 175 | + "type": "status", |
| 176 | + "status": "running", |
| 177 | + "prompt": prompt, |
| 178 | + "aspect_ratio": aspect_ratio, |
| 179 | + "run_id": run_id, |
| 180 | + } |
| 181 | + ) |
| 182 | + |
| 183 | + while not stop_event.is_set(): |
| 184 | + try: |
| 185 | + await token_mgr.reload_if_stale() |
| 186 | + token = token_mgr.get_token_for_model(model_info.model_id) |
| 187 | + if not token: |
| 188 | + await _send( |
| 189 | + { |
| 190 | + "type": "error", |
| 191 | + "message": "No available tokens. Please try again later.", |
| 192 | + "code": "rate_limit_exceeded", |
| 193 | + } |
| 194 | + ) |
| 195 | + await asyncio.sleep(2) |
| 196 | + continue |
| 197 | + |
| 198 | + start_at = time.time() |
| 199 | + images = await _collect_imagine_batch(token, prompt, aspect_ratio) |
| 200 | + elapsed_ms = int((time.time() - start_at) * 1000) |
| 201 | + |
| 202 | + sent_any = False |
| 203 | + for image_b64 in images: |
| 204 | + if not is_valid_imagine_image_value(image_b64): |
| 205 | + continue |
| 206 | + sent_any = True |
| 207 | + sequence += 1 |
| 208 | + ok = await _send( |
| 209 | + { |
| 210 | + "type": "image", |
| 211 | + "b64_json": image_b64, |
| 212 | + "sequence": sequence, |
| 213 | + "created_at": int(time.time() * 1000), |
| 214 | + "elapsed_ms": elapsed_ms, |
| 215 | + "aspect_ratio": aspect_ratio, |
| 216 | + "run_id": run_id, |
| 217 | + } |
| 218 | + ) |
| 219 | + if not ok: |
| 220 | + stop_event.set() |
| 221 | + break |
| 222 | + |
| 223 | + if sent_any: |
| 224 | + try: |
| 225 | + await token_mgr.sync_usage( |
| 226 | + token, |
| 227 | + model_info.model_id, |
| 228 | + consume_on_fail=True, |
| 229 | + is_usage=True, |
| 230 | + ) |
| 231 | + except Exception as e: |
| 232 | + logger.warning(f"Imagine ws token sync failed: {e}") |
| 233 | + else: |
| 234 | + await _send( |
| 235 | + { |
| 236 | + "type": "error", |
| 237 | + "message": "Image generation returned empty data.", |
| 238 | + "code": "empty_image", |
| 239 | + } |
| 240 | + ) |
| 241 | + except asyncio.CancelledError: |
| 242 | + break |
| 243 | + except Exception as e: |
| 244 | + logger.warning(f"Imagine stream error: {e}") |
| 245 | + await _send( |
| 246 | + { |
| 247 | + "type": "error", |
| 248 | + "message": str(e), |
| 249 | + "code": "internal_error", |
| 250 | + } |
| 251 | + ) |
| 252 | + await asyncio.sleep(1.5) |
| 253 | + |
| 254 | + await _send({"type": "status", "status": "stopped", "run_id": run_id}) |
| 255 | + |
| 256 | + try: |
| 257 | + while True: |
| 258 | + try: |
| 259 | + raw = await websocket.receive_text() |
| 260 | + except (RuntimeError, WebSocketDisconnect): |
| 261 | + break |
| 262 | + |
| 263 | + try: |
| 264 | + payload = orjson.loads(raw) |
| 265 | + except Exception: |
| 266 | + await _send( |
| 267 | + { |
| 268 | + "type": "error", |
| 269 | + "message": "Invalid message format.", |
| 270 | + "code": "invalid_payload", |
| 271 | + } |
| 272 | + ) |
| 273 | + continue |
| 274 | + |
| 275 | + msg_type = payload.get("type") |
| 276 | + if msg_type == "start": |
| 277 | + prompt = str(payload.get("prompt") or "").strip() |
| 278 | + if not prompt: |
| 279 | + await _send( |
| 280 | + { |
| 281 | + "type": "error", |
| 282 | + "message": "Prompt cannot be empty.", |
| 283 | + "code": "empty_prompt", |
| 284 | + } |
| 285 | + ) |
| 286 | + continue |
| 287 | + ratio = resolve_imagine_aspect_ratio(str(payload.get("aspect_ratio") or "2:3").strip()) |
| 288 | + await _stop_run() |
| 289 | + run_task = asyncio.create_task(_run(prompt, ratio)) |
| 290 | + elif msg_type == "stop": |
| 291 | + await _stop_run() |
| 292 | + elif msg_type == "ping": |
| 293 | + await _send({"type": "pong"}) |
| 294 | + else: |
| 295 | + await _send( |
| 296 | + { |
| 297 | + "type": "error", |
| 298 | + "message": "Unknown command.", |
| 299 | + "code": "unknown_command", |
| 300 | + } |
| 301 | + ) |
| 302 | + except WebSocketDisconnect: |
| 303 | + logger.debug("WebSocket disconnected by client") |
| 304 | + except Exception as e: |
| 305 | + logger.warning(f"WebSocket error: {e}") |
| 306 | + finally: |
| 307 | + await _stop_run() |
| 308 | + try: |
| 309 | + if websocket.client_state == WebSocketState.CONNECTED: |
| 310 | + await websocket.close(code=1000, reason="Server closing connection") |
| 311 | + except Exception as e: |
| 312 | + logger.debug(f"WebSocket close ignored: {e}") |
| 313 | + |
| 314 | + |
85 | 315 | @router.post("/api/v1/admin/login") |
86 | 316 | async def admin_login_api(request: Request, body: AdminLoginBody | None = Body(default=None)): |
87 | 317 | """管理后台登录验证(用户名+密码) |
|
0 commit comments