"""Minimal voice-session protocol mounted on the unified API (HEL-877). POST /api/voice/session open a room, dispatch the dedicated worker, return a short-lived join token (keys stay server-side); honest refusal when voice is not configured, no companion exists yet or TTS is down. HEL-899: the effective voice is captured here (selection if still valid, else the worker file's value, else default) and pinned for THIS call — changes applied mid-call take effect at the NEXT call at the latest, never mid-sentence. DELETE /api/voice/session/{id} end: delete the LiveKit room, which disconnects browser and worker, ends the agent job and releases the microphone. A delete that cannot land keeps the room in a bounded, persisted cleanup ledger (503, retried); it never collapses into a 404 while the room is still owned. GET /api/voice/status honest switch state for the frontend (configured / tts reachable / agent name). Custom voice protocol (HEL-899) — the browser never talks to the .12 voice panel or CosyVoice directly; everything goes through this API: GET /api/voice/voices list builtin + her custom voices (labels, selection/preview state, backup manifest fields for custom entries). POST /api/voice/voices register a reference audio: raw WAV bytes as the request body (no multipart — the project takes no new dependency for one endpoint), label/prompt_text/allow_asr as query parameters; allow_asr explicitly lets the existing FunASR transcribe when no reference text is given. POST /api/voice/preview synthesize a FRESH sample with a voice and return audio/wav (no caching, no chat/ memory/receipt writes). GET /api/voice/selection read her persisted voice selection. POST /api/voice/selection apply a voice to her subsequent calls (custom voices require a successful preview first; builtin D1 candidates do not). capabilities.voice in /api/health stays false: R5 is not real-accepted yet and this endpoint never claims end-to-end voice availability. """ from __future__ import annotations from fastapi import APIRouter, HTTPException, Request from fastapi.responses import Response from .custom import ( CustomVoiceService, RegistrationFailed, RegistryUnavailable, StateWriteFailed, pcm_to_wav, ) from .session import CleanupAbandoned, VoiceSessionService REFUSAL_NOT_CONFIGURED = "语音还没有在这台服务上配置,不能假装能通话。" REFUSAL_NO_COMPANION = "还没有创建真实伴侣,语音也不会开始。" REFUSAL_TTS_DOWN = "她的声音服务这会儿不在,稍后再试试。" REFUSAL_LIVEKIT_DOWN = "通话服务暂时连不上,稍后再试试。" REFUSAL_PANEL_DOWN = "音色登记服务这会儿不在,稍后再试试。" REFUSAL_VOICE_STATE_WRITE = "她的音色状态这会儿写不进,这次没有换成功。" REFUSAL_CLEANUP_ABANDONED = ( "这次通话的房间还没有删净,清理重试已达上限;已登记待人工收尾,请保留挂断状态。" ) def _capture_voice(service: VoiceSessionService, custom: CustomVoiceService | None) -> str: """通话开启时的有效音色(HEL-899):选择有效→选择;否则 worker 文件现值; 再无效→ default。用户从未经 API 选择时不改写 worker 文件(D1 域不代定)。""" voices = service.last_health_voices() def valid(candidate: str) -> bool: return bool(candidate) and (voices is None or candidate in voices) if custom is not None: selection = custom.selection() if selection.voice: captured = selection.voice if valid(selection.voice) else "default" try: custom.write_worker_voice(captured) # 本通话用捕获值;worker 入口读一次 except OSError: raise HTTPException(503, REFUSAL_VOICE_STATE_WRITE) from None return captured current = custom.read_worker_voice() return current if valid(current) else "default" return "" def build_voice_router(service: VoiceSessionService | None, custom: CustomVoiceService | None = None) -> APIRouter: router = APIRouter(prefix="/api/voice", tags=["voice"]) @router.get("/status") async def status() -> dict: if service is None: return {"configured": False, "tts_ok": False, "agent_name": None, "voice": False} tts_ok = await service.tts_available() return { "configured": True, "tts_ok": tts_ok, "agent_name": service.config.agent_name, "voice": False, # honest until real-device R5 acceptance **service.config.sanitized(), } @router.post("/session", status_code=201) async def open_session(request: Request) -> dict: if service is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) state = request.app.state if not state.store.query_one("SELECT id FROM companion"): raise HTTPException(409, REFUSAL_NO_COMPANION) if not await service.tts_available(): raise HTTPException(503, REFUSAL_TTS_DOWN) captured = _capture_voice(service, custom) try: session = await service.open_session(epoch=state.epoch, voice=captured) except Exception: raise HTTPException(503, REFUSAL_LIVEKIT_DOWN) from None return { "url": service.config.livekit_url, "token": service.token_for(session), "room": session.room, "session_id": session.session_id, "agent_name": service.config.agent_name, "epoch": session.epoch, "expires_at": int(session.expires_at * 1000), "voice": session.voice, } @router.delete("/session/{session_id}") async def end_session(session_id: str) -> dict: if service is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) try: session = await service.end_session(session_id) except CleanupAbandoned as exc: # Bounded cleanup crossed its persisted cap (this process or an # earlier one): the room is STILL owned and unsettled — never a # done-404, and no further delete is issued from any path. The # state stays persisted for the operator. raise HTTPException( 503, {"message": REFUSAL_CLEANUP_ABANDONED, "cleanup": {"room": exc.debt.session.room, "abandoned": exc.debt.abandoned, "attempts": exc.debt.attempts, "last_error": exc.debt.last_error}}, ) from None except Exception: # The remote delete did not land: the room stays owned in the # bounded cleanup ledger and will be retried; the caller must NOT # treat this as done (a 404 would erase the browser's owed DELETE). raise HTTPException(503, "这次通话还没有完全挂断,会自动重试清理;请稍后再试。") from None if session is None: raise HTTPException(404, "这次通话已经不在了。") return {"ended": True, "room": session.room} # -- custom voices (HEL-899) -------------------------------------------- @router.get("/voices") async def voices() -> dict: if custom is None: return {"configured": False, "voices": [], "selection": None} try: listed = await custom.registry_list() except RegistryUnavailable: raise HTTPException(503, REFUSAL_PANEL_DOWN) from None previewed = custom.previewed_voices() selection = custom.selection() records = custom.custom_voices() items = [] for voice_id in listed: record = records.get(voice_id) items.append({ "id": voice_id, "label": record["label"] if record else voice_id, "source": "custom" if voice_id.startswith("cg-") else "builtin", "selected": selection.voice == voice_id, "previewed": voice_id in previewed, "registered_at": record["registered_at"] if record else None, # 备份清单字段(CG-009 承接):自定义条目带参考文本与音频位置 "prompt_text": record["prompt_text"] if record else None, "prompt_wav": record["prompt_wav"] if record else None, }) return { "configured": True, "voices": items, "selection": {"voice": selection.voice, "label": selection.label, "updated_at": selection.updated_at or None}, } @router.post("/voices", status_code=201) async def register_voice(request: Request, label: str = "", prompt_text: str = "", allow_asr: bool = False) -> dict: if custom is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) if not request.app.state.store.query_one("SELECT id FROM companion"): raise HTTPException(409, REFUSAL_NO_COMPANION) # 请求体就是参考音频原始字节(audio/wav/octet-stream);登记参数走查询串, # 不引入 multipart 依赖。录音/文件内容照旧服务端复验,不信任任何声明。 data = await request.body() try: record = await custom.register(data=data, label=label, prompt_text=prompt_text, allow_asr=allow_asr) except RegistrationFailed as exc: raise HTTPException(422, str(exc)) from None except RegistryUnavailable: raise HTTPException(503, REFUSAL_PANEL_DOWN) from None return record @router.post("/preview") async def preview(body: dict) -> Response: if custom is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) voice = str(body.get("voice") or "") if isinstance(body, dict) else "" text = body.get("text") if isinstance(body, dict) else None if not voice: raise HTTPException(422, "请指定要试听的声音。") if text is not None and not isinstance(text, str): raise HTTPException(422, "试听文字格式无效。") try: pcm = await custom.preview_pcm(voice=voice, text=text) except KeyError: raise HTTPException(404, "这个声音现在不在列表里。") from None except RegistrationFailed as exc: raise HTTPException(422, str(exc)) from None except RegistryUnavailable: raise HTTPException(503, REFUSAL_TTS_DOWN) from None return Response(content=pcm_to_wav(pcm), media_type="audio/wav") @router.get("/selection") async def get_selection() -> dict: if custom is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) selection = custom.selection() return {"voice": selection.voice, "label": selection.label, "updated_at": selection.updated_at or None} @router.post("/selection") async def apply_selection(body: dict) -> dict: if custom is None: raise HTTPException(503, REFUSAL_NOT_CONFIGURED) voice = str(body.get("voice") or "") if isinstance(body, dict) else "" if not voice: raise HTTPException(422, "请指定要应用的声音。") try: selection = await custom.apply_selection(voice=voice) except KeyError: raise HTTPException(404, "这个声音现在不在列表里。") from None except PermissionError: raise HTTPException(409, "这个声音还没有试听过,先试听再给她用。") from None except RegistryUnavailable: raise HTTPException(503, REFUSAL_PANEL_DOWN) from None except StateWriteFailed: raise HTTPException(503, REFUSAL_VOICE_STATE_WRITE) from None return {"voice": selection.voice, "label": selection.label, "updated_at": selection.updated_at} return router