-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathgateway.py
More file actions
1574 lines (1269 loc) · 55.2 KB
/
Copy pathgateway.py
File metadata and controls
1574 lines (1269 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""MiniCPMO45 推理 Gateway
请求分发网关,不加载模型,负责:
- 路由 Chat/Streaming/Duplex 请求到 Worker
- 会话映射和 KV Cache LRU 命中路由
- 统一 FIFO 请求排队(容量 1000,位置追踪 + ETA 估算)
- Worker 健康检查
启动方式:
cd /user/sunweiyue/lib/swy-dev/minicpmo45_service
PYTHONPATH=. .venv/base/bin/python gateway.py \\
--port 10024 --internal-port 10025
"""
import os
import re
import json
import asyncio
import argparse
import logging
import time
from typing import Optional, List, Dict, Any
from datetime import datetime
from contextlib import asynccontextmanager
from urllib.parse import urlencode
import zipfile
from io import BytesIO
import httpx
import numpy as np
import uvicorn
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Request, UploadFile, File, Body
from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse, Response, RedirectResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from gateway_modules.models import (
GatewayWorkerStatus,
ServiceStatus,
WorkersResponse,
WorkerRegistrationRequest,
QueueStatus,
EtaConfig,
EtaStatus,
)
from gateway_modules.worker_pool import WorkerPool, WorkerConnection
from gateway_modules.ref_audio_registry import (
RefAudioRegistry,
RefAudioListResponse,
UploadRefAudioRequest,
RefAudioResponse,
)
from gateway_modules.app_registry import (
AppRegistry,
AppToggleRequest,
AppsPublicResponse,
AppsAdminResponse,
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("gateway")
_SESSION_ID_RE = re.compile(r'^[a-zA-Z0-9_\-]+$')
def _sanitize_session_id(session_id: str) -> str:
"""校验 session_id 只含安全字符,防止 path traversal"""
if not _SESSION_ID_RE.match(session_id):
safe = re.sub(r'[^a-zA-Z0-9_\-]', '_', session_id)
return safe
return session_id
def _sessions_root() -> str:
from config import get_config
cfg = get_config()
return os.path.realpath(os.path.join(_BASE_DIR, cfg.data_dir, "sessions"))
def _client_ip_from_ws(ws: WebSocket) -> Optional[str]:
xff = ws.headers.get("x-forwarded-for")
if xff:
return xff.split(",")[0].strip()
return ws.headers.get("x-real-ip") or (ws.client.host if ws.client else None)
def _identity_dict(
ws: WebSocket,
*,
source_channel: str,
source_mode: Optional[str] = None,
) -> Dict[str, Any]:
"""Collect all client/page/source identity meta from the incoming WS.
单一数据源:既用于透传给 worker(urlencode),也直接作为录制 meta。
前端新增任何 identity 字段,只要在这里收集一次,即同时流入两处。
"""
client_id = (
ws.query_params.get("client_id")
or ws.headers.get("x-client-id")
or ws.cookies.get("client_id")
)
page_session_id = (
ws.query_params.get("page_session_id")
or ws.headers.get("x-page-session-id")
or ws.cookies.get("page_session_id")
)
return {
"client_id": client_id,
"page_session_id": page_session_id,
"client_ip": _client_ip_from_ws(ws),
"user_agent": ws.headers.get("user-agent"),
"origin": ws.headers.get("origin"),
"source_channel": source_channel,
"source_mode": source_mode,
"source_path": ws.url.path,
"page_route": ws.query_params.get("page_route"),
"client_surface": ws.query_params.get("client_surface"),
}
# ============ 全局变量 ============
worker_pool: Optional[WorkerPool] = None
ref_audio_registry: Optional[RefAudioRegistry] = None
app_registry: AppRegistry = AppRegistry()
# 配置(通过 main() 传入)
GATEWAY_CONFIG: Dict[str, Any] = {}
# ============ 应用初始化 ============
_cleanup_task: Optional[asyncio.Task] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期"""
global worker_pool, ref_audio_registry, _cleanup_task
workers = GATEWAY_CONFIG.get("workers", [])
max_queue = GATEWAY_CONFIG.get("max_queue_size", 1000)
timeout = GATEWAY_CONFIG.get("timeout", 300.0)
# 从 config 读取 ETA 参数
eta_config_data = GATEWAY_CONFIG.get("eta_config")
eta_config = EtaConfig(**eta_config_data) if eta_config_data else EtaConfig()
worker_pool = WorkerPool(
worker_addresses=workers,
max_queue_size=max_queue,
request_timeout=timeout,
eta_config=eta_config,
ema_alpha=GATEWAY_CONFIG.get("eta_ema_alpha", 0.3),
ema_min_samples=GATEWAY_CONFIG.get("eta_ema_min_samples", 3),
)
await worker_pool.start()
# 初始化参考音频注册表
data_dir = os.path.join(os.path.dirname(__file__), "data", "assets", "ref_audio")
ref_audio_registry = RefAudioRegistry(storage_dir=data_dir)
# 启动 session 清理后台任务(每天一次)
_cleanup_task = asyncio.create_task(_session_cleanup_loop())
logger.info(f"Gateway started, {len(worker_pool.workers)} workers, {ref_audio_registry.count} ref audios")
yield
if _cleanup_task:
_cleanup_task.cancel()
await worker_pool.stop()
logger.info("Gateway stopped")
async def _session_cleanup_loop() -> None:
"""每天执行一次 session 清理(retention_days 和 max_storage_gb 都为 -1 时不执行)"""
from session_cleanup import cleanup_sessions
from config import get_config
await asyncio.sleep(60)
while True:
try:
cfg = get_config()
days = cfg.recording.session_retention_days
gb = cfg.recording.max_storage_gb
if days < 0 and gb < 0:
logger.info("[Cleanup] Disabled (retention_days=-1, max_storage_gb=-1), sleeping")
else:
report = await asyncio.to_thread(
cleanup_sessions, cfg.data_dir, days, gb,
)
logger.info(f"[Cleanup] {report}")
except Exception as e:
logger.error(f"[Cleanup] Failed: {e}", exc_info=True)
await asyncio.sleep(86400)
app = FastAPI(
title="MiniCPMO45 Gateway",
description="MiniCPMO45 多模态推理网关",
version="1.0.0-alpha.2",
lifespan=lifespan,
docs_url=None,
redoc_url=None,
)
internal_app = FastAPI(
title="MiniCPMO45 Gateway Internal",
description="Internal worker registration API",
version="1.0.0-alpha.2",
docs_url=None,
redoc_url=None,
)
_PUBLIC_ADMIN_ENABLED = os.getenv("ENABLE_PUBLIC_ADMIN", "").lower() in {"1", "true", "yes", "on"}
_BLOCKED_ADMIN_PATHS = {"/admin", "/admin/"}
_BLOCKED_ADMIN_STATIC_PATHS = {"/static/admin.html", "/static/admin.html/"}
@app.middleware("http")
async def hide_admin_routes(request: Request, call_next):
"""Keep admin-only surfaces unavailable on public deployments by default."""
if not _PUBLIC_ADMIN_ENABLED:
path = request.url.path
if (
path in _BLOCKED_ADMIN_PATHS
or path.startswith("/api/admin/")
or path in _BLOCKED_ADMIN_STATIC_PATHS
):
return JSONResponse({"detail": "Not found"}, status_code=404)
return await call_next(request)
# ============ 健康检查 ============
@app.get("/health")
async def health():
"""健康检查"""
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
}
# ============ 前端诊断日志 (用于排查录音故障) ============
_DEBUG_LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".run-logs")
_DEBUG_LOG_PATH = os.path.join(_DEBUG_LOG_DIR, "mobile-record-trace.jsonl")
_DEBUG_LOG_MAX_BYTES = 5 * 1024 * 1024 # 5 MB rolling cap
def _append_debug_trace(payload: Dict[str, Any]) -> None:
"""Append a single JSON line to the rolling debug log."""
try:
os.makedirs(_DEBUG_LOG_DIR, exist_ok=True)
# Roll over if oversized.
try:
if os.path.exists(_DEBUG_LOG_PATH) and os.path.getsize(_DEBUG_LOG_PATH) > _DEBUG_LOG_MAX_BYTES:
rolled = _DEBUG_LOG_PATH + ".1"
if os.path.exists(rolled):
os.remove(rolled)
os.rename(_DEBUG_LOG_PATH, rolled)
except OSError:
pass
record = {
"ts": datetime.now().isoformat(timespec="milliseconds"),
**payload,
}
with open(_DEBUG_LOG_PATH, "a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
except OSError as exc:
logger.warning("failed to write mobile record trace: %s", exc)
@app.post("/api/_debug/record_trace")
async def post_record_trace(payload: Dict[str, Any]):
"""Receive a recording-session trace from the mobile frontend.
The frontend posts one record per press-to-talk attempt with the
full event timeline so we can diagnose failures (overlay shown but
no audio captured) without asking users to copy console logs.
"""
_append_debug_trace(payload)
return {"ok": True}
@app.get("/status", response_model=ServiceStatus)
async def status():
"""服务状态"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
return ServiceStatus(
gateway_healthy=True,
total_workers=len(worker_pool.workers),
idle_workers=worker_pool.idle_count,
busy_workers=worker_pool.busy_count,
duplex_workers=worker_pool.duplex_count,
loading_workers=worker_pool.loading_count,
error_workers=worker_pool.error_count,
offline_workers=worker_pool.offline_count,
queue_length=worker_pool.queue_length,
max_queue_size=worker_pool.max_queue_size,
running_tasks=worker_pool._get_running_tasks(),
)
@app.get("/workers", response_model=WorkersResponse)
async def list_workers():
"""Worker 列表"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
return WorkersResponse(
total=len(worker_pool.workers),
workers=worker_pool.get_all_workers(),
)
@internal_app.get("/health")
async def internal_health():
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
}
@internal_app.put("/internal/workers/{worker_id}")
async def register_worker(worker_id: str, payload: WorkerRegistrationRequest):
"""Register or update a worker endpoint from the internal control plane."""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
try:
worker = await worker_pool.register_worker(
worker_id=worker_id,
endpoint=payload.endpoint,
gpu_group=payload.gpu_group,
labels=payload.labels,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return {
"ok": True,
"worker": worker.to_info(),
}
# ============ Chat WebSocket 代理 ============
async def _api_worker_passthrough_ws(
ws: WebSocket,
*,
request_type: str,
worker_status: GatewayWorkerStatus,
worker_path: str,
source_channel: str,
source_mode: Optional[str],
max_duration_s: Optional[float] = None,
) -> None:
"""Queue, assign a worker, then pass API-shaped events through unchanged."""
if worker_pool is None:
await ws.close(code=1013, reason="Service not ready")
return
await ws.accept()
try:
ticket, future = worker_pool.enqueue(request_type)
except WorkerPool.QueueFullError:
await ws.send_json({
"type": "error",
"error": {"code": "queue_full", "message": "Queue full", "type": "server_error"},
})
await ws.close(code=1013, reason="Queue full")
return
worker: Optional[WorkerConnection] = None
if future.done():
worker = future.result()
else:
try:
await ws.send_json({
"type": "session.queued",
"position": ticket.position,
"estimated_wait_s": ticket.estimated_wait_s,
"ticket_id": ticket.ticket_id,
"queue_length": worker_pool.queue_length,
})
while not future.done():
try:
worker = await asyncio.wait_for(asyncio.shield(future), timeout=3.0)
break
except asyncio.TimeoutError:
updated = worker_pool.get_ticket(ticket.ticket_id)
if updated:
await ws.send_json({
"type": "session.queue_update",
"position": updated.position,
"estimated_wait_s": updated.estimated_wait_s,
"queue_length": worker_pool.queue_length,
})
except asyncio.CancelledError:
worker_pool.cancel(ticket.ticket_id)
return
except (WebSocketDisconnect, Exception) as exc:
logger.info("API WS disconnected during queue: ticket=%s (%s)", ticket.ticket_id, exc)
worker_pool.cancel(ticket.ticket_id)
return
if worker is None and future.done():
worker = future.result()
if worker is None:
await ws.send_json({
"type": "error",
"error": {"code": "worker_busy", "message": "No worker available", "type": "server_error"},
})
await ws.close(code=1013, reason="No worker available")
return
task_start = datetime.now()
worker_ws = None
recorder = None
session_closed = asyncio.Event()
try:
await ws.send_json({"type": "session.queue_done"})
worker.mark_busy(worker_status, request_type, ticket_id=ticket.ticket_id)
import websockets
identity = _identity_dict(
ws,
source_channel=source_channel,
source_mode=source_mode,
)
identity_qs = urlencode({k: v for k, v in identity.items() if v})
# ---- session 录制(旁路,fail-safe:任何异常都不影响转发主路径)----
recording_enabled = False
recorder_cls = None
recorder_mode = "turn_based" if request_type == "chat" else "full_duplex"
recorder_data_dir = None
recorder_worker = {"host": worker.host, "port": worker.port, "gpu_id": getattr(worker, "gpu_id", None)}
pending_record_frames = []
recorder = None
try:
from config import get_config
_cfg = get_config()
if _cfg.recording.enabled:
from gateway_modules.session_recording import SessionRecorder
recording_enabled = True
recorder_cls = SessionRecorder
recorder_data_dir = os.path.join(_BASE_DIR, _cfg.data_dir)
except Exception:
recording_enabled = False
recorder_cls = None
recorder_data_dir = None
recorder = None
ws_url = f"ws://{worker.host}:{worker.port}{worker_path}?{identity_qs}"
worker_ws = await websockets.connect(ws_url, open_timeout=5, max_size=128 * 1024 * 1024)
def record_or_buffer(direction: str, frame: Dict[str, Any]) -> None:
nonlocal recorder
if not recording_enabled:
return
if recorder is None:
pending_record_frames.append((direction, frame))
return
try:
recorder.record(direction, frame)
except Exception:
pass
def ensure_recorder(session_id: Optional[str]) -> None:
nonlocal recorder
if (
not recording_enabled
or recorder is not None
or recorder_cls is None
or recorder_data_dir is None
or not session_id
):
return
safe_session_id = _sanitize_session_id(session_id)
recording_identity = dict(identity)
recording_identity["session_id"] = safe_session_id
try:
recorder = recorder_cls(
safe_session_id,
recorder_mode,
data_dir=recorder_data_dir,
identity=recording_identity,
worker=recorder_worker,
)
except Exception:
recorder = None
return
buffered = list(pending_record_frames)
pending_record_frames.clear()
for direction, frame in buffered:
try:
recorder.record(direction, frame)
except Exception:
pass
async def client_to_worker() -> None:
try:
async for raw in ws.iter_text():
await worker_ws.send(raw)
try:
record_or_buffer("up", json.loads(raw))
except Exception:
pass
except WebSocketDisconnect:
pass
async def worker_to_client() -> None:
async for raw in worker_ws:
try:
msg = json.loads(raw)
msg_type = msg.get("type")
if msg_type == "session.created":
ensure_recorder(msg.get("session_id"))
raw_to_send = raw
except Exception:
msg = None
raw_to_send = raw
await ws.send_text(raw_to_send)
try:
record_or_buffer("down", msg if msg is not None else json.loads(raw_to_send))
if msg is not None and msg.get("type") == "session.closed":
session_closed.set()
return
except Exception:
pass
tasks = [
asyncio.create_task(client_to_worker()),
asyncio.create_task(worker_to_client()),
]
if max_duration_s is not None:
async def session_timeout_watchdog() -> None:
await asyncio.sleep(max_duration_s)
if session_closed.is_set():
return
logger.info("API session timeout (%ss): ticket=%s", max_duration_s, ticket.ticket_id)
await ws.send_json({"type": "session.closed", "reason": "timeout"})
session_closed.set()
tasks.append(asyncio.create_task(session_timeout_watchdog()))
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
for task in done:
task.result()
except Exception as exc:
logger.error("API worker passthrough failed: ticket=%s error=%s", ticket.ticket_id, exc, exc_info=True)
try:
await ws.send_json({
"type": "error",
"error": {"code": "session_failed", "message": str(exc), "type": "server_error"},
})
except Exception:
pass
finally:
if recorder is not None:
try:
recorder.close(reason="session_end" if session_closed.is_set() else "disconnected")
except Exception:
pass
if worker_ws:
try:
await worker_ws.close()
except Exception:
pass
duration = (datetime.now() - task_start).total_seconds()
worker_pool.release_worker(worker, request_type=request_type, duration_s=duration)
try:
await ws.close()
except Exception:
pass
# ============ 默认 Ref Audio 分发 ============
@app.get("/api/frontend_defaults")
async def get_frontend_defaults():
"""返回前端页面需要的默认配置
前端页面加载时调用此接口获取 playback_delay_ms 等可配置的默认值,
避免前端硬编码。返回值来自 config.json。
若 gateway 启动时指定了 --lang,此处也会包含 default_lang 字段。
"""
from config import get_config
defaults = get_config().frontend_defaults()
server_lang = GATEWAY_CONFIG.get("default_lang")
if server_lang:
defaults["default_lang"] = server_lang
return defaults
# ============ System Prompt 预设 ============
_presets_cache: Optional[Dict[str, List[Dict[str, Any]]]] = None
def _get_audio_meta(rel_path: str, project_root: str) -> Dict[str, Any]:
"""获取音频文件的元数据(不加载 base64),用于预设列表"""
import librosa
if not rel_path:
return {"name": "", "duration": 0}
abs_path = rel_path if os.path.isabs(rel_path) else os.path.join(project_root, rel_path)
name = os.path.basename(abs_path)
if not os.path.exists(abs_path):
return {"name": name, "duration": 0}
try:
audio, sr = librosa.load(abs_path, sr=16000, mono=True)
return {"name": name, "duration": round(len(audio) / sr, 1)}
except Exception:
return {"name": name, "duration": 0}
def _load_audio_base64(rel_path: str, project_root: str) -> Optional[Dict[str, Any]]:
"""加载音频文件为 base64(按需调用)"""
import librosa
if not rel_path:
return None
abs_path = rel_path if os.path.isabs(rel_path) else os.path.join(project_root, rel_path)
if not os.path.exists(abs_path):
return None
try:
audio, sr = librosa.load(abs_path, sr=16000, mono=True)
audio_bytes = audio.astype(np.float32).tobytes()
import base64 as b64mod
return {
"data": b64mod.b64encode(audio_bytes).decode("ascii"),
"name": os.path.basename(abs_path),
"duration": round(len(audio) / sr, 1),
}
except Exception as e:
logger.error(f"Failed to load audio {abs_path}: {e}")
return None
def _load_presets_from_dir(project_root: str) -> Dict[str, List[Dict[str, Any]]]:
"""扫描 assets/presets/<mode>/*.yaml,返回元数据(不含音频 base64)"""
import yaml
presets_root = os.path.join(project_root, "assets", "presets")
result: Dict[str, List[Dict[str, Any]]] = {}
if not os.path.isdir(presets_root):
return result
for mode_dir in sorted(os.listdir(presets_root)):
mode_path = os.path.join(presets_root, mode_dir)
if not os.path.isdir(mode_path):
continue
mode_presets = []
for fname in sorted(os.listdir(mode_path)):
if not fname.endswith((".yaml", ".yml")):
continue
fpath = os.path.join(mode_path, fname)
try:
with open(fpath, "r", encoding="utf-8") as f:
preset = yaml.safe_load(f)
if not preset or not isinstance(preset, dict):
continue
if "system_content" in preset:
resolved = []
for item in preset["system_content"]:
if item.get("type") == "audio" and item.get("path"):
meta = _get_audio_meta(item["path"], project_root)
resolved.append({
"type": "audio",
"data": None,
"path": item["path"],
"name": meta["name"],
"duration": meta["duration"],
})
else:
resolved.append(item)
preset["system_content"] = resolved
if "ref_audio_path" in preset:
meta = _get_audio_meta(preset["ref_audio_path"], project_root)
preset["ref_audio"] = {
"data": None,
"path": preset["ref_audio_path"],
"name": meta["name"],
"duration": meta["duration"],
}
del preset["ref_audio_path"]
mode_presets.append(preset)
except Exception as e:
logger.error(f"Failed to load preset {fpath}: {e}")
if mode_presets:
mode_presets.sort(key=lambda p: p.get("order", 999))
result[mode_dir] = mode_presets
total = sum(len(v) for v in result.values())
logger.info(f"Loaded {total} presets (metadata only) across {len(result)} modes")
return result
@app.get("/api/presets")
async def get_presets():
"""返回预设元数据(不含音频 base64,音频通过 /api/presets/{mode}/{id}/audio 按需加载)"""
global _presets_cache
if _presets_cache is not None:
return _presets_cache
project_root = os.path.dirname(__file__)
_presets_cache = _load_presets_from_dir(project_root)
return _presets_cache
@app.get("/api/presets/{mode}/{preset_id}/audio")
async def get_preset_audio(mode: str, preset_id: str):
"""按需加载单个 preset 的音频数据"""
global _presets_cache
if _presets_cache is None:
project_root = os.path.dirname(__file__)
_presets_cache = _load_presets_from_dir(project_root)
mode_presets = _presets_cache.get(mode, [])
preset = next((p for p in mode_presets if p.get("id") == preset_id), None)
if not preset:
raise HTTPException(status_code=404, detail=f"Preset not found: {mode}/{preset_id}")
project_root = os.path.dirname(__file__)
result: Dict[str, Any] = {}
if "system_content" in preset:
audio_items = []
for item in preset["system_content"]:
if item.get("type") == "audio" and item.get("path"):
loaded = _load_audio_base64(item["path"], project_root)
audio_items.append(loaded or {"data": None, "name": item.get("name", ""), "duration": 0})
result["system_content_audio"] = audio_items
if preset.get("ref_audio") and preset["ref_audio"].get("path"):
loaded = _load_audio_base64(preset["ref_audio"]["path"], project_root)
result["ref_audio"] = loaded or {"data": None, "name": preset["ref_audio"].get("name", ""), "duration": 0}
return result
# 缓存:启动后首次请求时加载,之后直接返回
_default_ref_audio_cache: Optional[Dict[str, Any]] = None
@app.get("/api/default_ref_audio")
async def get_default_ref_audio():
"""返回默认参考音频(PCM float32 16kHz mono base64)
前端页面加载时调用此接口获取默认 ref audio,
之后所有请求统一通过 ref_audio_base64 传递音频数据。
"""
global _default_ref_audio_cache
if _default_ref_audio_cache is not None:
return _default_ref_audio_cache
from config import get_config
cfg = get_config()
if not cfg.ref_audio_path:
raise HTTPException(status_code=404, detail="No default ref audio configured")
# 解析路径(支持相对路径,相对于 minicpmo45_service/)
ref_path = cfg.ref_audio_path
if not os.path.isabs(ref_path):
ref_path = os.path.join(os.path.dirname(__file__), ref_path)
if not os.path.exists(ref_path):
raise HTTPException(status_code=404, detail=f"Default ref audio not found: {cfg.ref_audio_path}")
try:
import base64
import librosa
import numpy as np
# 加载并重采样为 16kHz mono float32(与前端上传格式一致)
audio, sr = librosa.load(ref_path, sr=16000, mono=True)
duration = len(audio) / 16000
# 转换为 base64(PCM float32)
audio_bytes = audio.astype(np.float32).tobytes()
audio_b64 = base64.b64encode(audio_bytes).decode("ascii")
_default_ref_audio_cache = {
"name": os.path.basename(cfg.ref_audio_path),
"duration": round(duration, 1),
"sample_rate": 16000,
"samples": len(audio),
"base64": audio_b64,
}
logger.info(
f"Default ref audio loaded: {_default_ref_audio_cache['name']} "
f"({duration:.1f}s, {len(audio)} samples)"
)
return _default_ref_audio_cache
except Exception as e:
logger.error(f"Failed to load default ref audio: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to load ref audio: {e}")
# ============ 素材管理 API ============
@app.get("/api/assets/ref_audio", response_model=RefAudioListResponse)
async def list_ref_audios():
"""列出参考音频"""
if ref_audio_registry is None:
raise HTTPException(status_code=503, detail="Service not ready")
return RefAudioListResponse(
total=ref_audio_registry.count,
ref_audios=ref_audio_registry.list_all(),
)
@app.post("/api/assets/ref_audio", response_model=RefAudioResponse)
async def upload_ref_audio(request: UploadRefAudioRequest):
"""上传参考音频"""
if ref_audio_registry is None:
raise HTTPException(status_code=503, detail="Service not ready")
try:
info = ref_audio_registry.upload(
name=request.name,
audio_base64=request.audio_base64,
)
return RefAudioResponse(
success=True,
id=info.id,
name=info.name,
message=f"Uploaded successfully, duration={info.duration_ms}ms",
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Upload ref audio failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/assets/ref_audio/{ref_id}", response_model=RefAudioResponse)
async def delete_ref_audio(ref_id: str):
"""删除参考音频"""
if ref_audio_registry is None:
raise HTTPException(status_code=503, detail="Service not ready")
if not ref_audio_registry.exists(ref_id):
raise HTTPException(status_code=404, detail=f"Ref audio not found: {ref_id}")
success = ref_audio_registry.delete(ref_id)
return RefAudioResponse(
success=success,
id=ref_id,
message="Deleted" if success else "Failed to delete",
)
# ============ 队列状态 API ============
@app.get("/api/queue", response_model=QueueStatus)
async def get_queue():
"""获取当前队列状态"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
return worker_pool.get_queue_status()
@app.get("/api/queue/{ticket_id}")
async def get_queue_ticket(ticket_id: str):
"""获取指定排队项的状态(前端轮询用)"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
ticket = worker_pool.get_ticket(ticket_id)
if ticket is None:
return {"found": False, "message": "Ticket not in queue (may have been assigned or cancelled)"}
return {"found": True, "ticket": ticket.model_dump()}
@app.delete("/api/queue/{ticket_id}")
async def cancel_queue_item(ticket_id: str):
"""取消排队项(Admin 用)"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
ok = worker_pool.cancel(ticket_id)
return {"success": ok}
# ============ ETA 配置 API ============
@app.get("/api/config/eta", response_model=EtaStatus)
async def get_eta_config():
"""获取 ETA 配置和 EMA 状态"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
return worker_pool.eta_tracker.get_status()
@app.put("/api/config/eta", response_model=EtaStatus)
async def update_eta_config(new_config: EtaConfig):
"""更新 ETA 基准配置(运行时生效,无需重启)"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
worker_pool.eta_tracker.update_config(new_config)
alpha_str = f", ema_alpha={new_config.ema_alpha}" if new_config.ema_alpha is not None else ""
logger.info(
f"ETA config updated: chat={new_config.eta_chat_s}s, "
f"half_duplex={new_config.eta_half_duplex_s}s, "
f"audio_duplex={new_config.eta_audio_duplex_s}s, "
f"omni_duplex={new_config.eta_omni_duplex_s}s{alpha_str}"
)
return worker_pool.eta_tracker.get_status()
# ============ 缓存状态 API ============
@app.get("/cache")
async def list_cache():
"""查看各 Worker 的 KV cache 状态"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
return {
"workers": [
{
"worker_id": w.worker_id,
"status": w.status.value,
}
for w in worker_pool.workers.values()
],
}
# ============ Session API ============
_BASE_DIR = os.path.dirname(__file__)
def _list_active_sessions_payload() -> Dict[str, Any]:
"""Gateway 当前占用 Worker 的请求列表(Admin / 测试共用)。"""
if worker_pool is None:
raise HTTPException(status_code=503, detail="Service not ready")
sessions: List[Dict[str, Any]] = []
for w in worker_pool.workers.values():
if not w.current_ticket_id:
continue
last_active = w.last_heartbeat or w.task_started_at or datetime.now()
sessions.append(
{
"ticket_id": w.current_ticket_id,
"worker_id": w.worker_id,
"messages_hash": getattr(w, "cached_hash", "") or "",
"last_active": last_active.isoformat()
if hasattr(last_active, "isoformat")
else str(last_active),
}
)
return {"total": len(sessions), "sessions": sessions}
@app.get("/sessions")
async def list_active_sessions():
"""列出活跃会话(与 admin.html `GET /sessions` 一致)。"""
return _list_active_sessions_payload()
@app.get("/api/sessions")
async def list_active_sessions_api():