HEL-899: custom voice via reference audio on the unified API — reuse .12 panel zero-shot registry (server-side proxy, cg- namespaced IDs never collide with the 11 builtin voices, panel stays the only voices.json writer) + CosyVoice fresh-synthesis preview (unknown voice pre-checked: no silent default fallback) + persisted selection/manifest/usage journal in instance data space with atomic writes and full rollback; session-open captures the effective voice (selection if valid else worker-file value else default, D1 domain untouched when user never chose) pinned per call, mid-call changes land at next call at the earliest; explicit allow_asr gates FunASR transcription, preview/ASR journaled, preview writes no chat/memory/receipt rows; zero new deps (raw-bytes upload endpoint), zero real calls in tests: 18 new cases (formats/size/duration refusals, collision+concurrency, panel down/reject/lying, tts down, rollback, restart persistence, call pinning, identity/shared-state untouched) + offline chain script 12/12, suite 370; req governance v1.12: CG-010 boundary updated to custom-voice-first per user comment 01a17de1 (verbatim evidence + changes + manifest), checks pass vs origin/main and base 8dc84f8 with handoff-HEL-899

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
施工员2号
2026-10-27 23:34:00 +08:00
co-authored by multica-agent
parent 8dc84f88e9
commit ce7279e68f
19 changed files with 1692 additions and 27 deletions
+35 -13
View File
@@ -15,6 +15,7 @@ from typing import Literal
from uuid import UUID
from zoneinfo import ZoneInfo
import httpx
import yaml
from anyio import CancelScope
from fastapi import FastAPI, HTTPException, Query, Request
@@ -25,6 +26,7 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, field_validator
from ..config import CharacterConfig, ModelsConfig
from ..contracts import LLMMessage
from ..contracts.text import safe_text
from ..core.bazi import (
GAN_ELEM,
Derived,
@@ -48,7 +50,13 @@ from ..memory.semantic import build_semantic
from ..memory.store import Store
from ..think.scenes import Scene
from ..think.wiring import build_router_from_config
from ..voice import VoiceSessionService, build_voice_router, load_voice_config
from ..voice import (
CustomVoiceConfig,
CustomVoiceService,
VoiceSessionService,
build_voice_router,
load_voice_config,
)
HOURS = [
"子时",
@@ -67,17 +75,6 @@ HOURS = [
ERROR = "她这会儿没接上话,稍后再试试。你写的话还在。"
def safe_text(value: str, maximum: int, label: str, required: bool = False) -> str:
value = value.strip()
if (
(required and not value)
or len(value) > maximum
or any(ord(c) < 32 or ord(c) == 127 or c in "<>" for c in value)
):
raise ValueError(f"{label}请填写{1 if required else 0}–{maximum}字,不含控制字符或尖括号。")
return value
class StrictBody(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
@@ -182,6 +179,7 @@ def create_app(
semantic_mode: str | None = None,
semantic_config: dict | None = None,
voice_service=None,
custom_voice_service=None,
) -> FastAPI:
"""Dependencies can be injected for isolated fault/cancellation tests, never via browser flags."""
db_path = db_path or os.environ.get(
@@ -291,6 +289,8 @@ def create_app(
await provider.aclose()
if getattr(app.state, "voice_service", None):
await app.state.voice_service.aclose()
if getattr(app.state, "custom_voice_service", None):
await app.state.custom_voice_service.aclose()
store.close()
finally:
app.state.lifespan_active = False
@@ -315,8 +315,30 @@ def create_app(
Path(db_path).stem + "-voice-sessions.json"),
) if voice_config is not None else None
)
# Custom voice service (HEL-899) rides the same config: same instance
# data space (selection/registry/journal beside the DB), dedicated
# HTTP client because the .12 voice panel is https with a self-signed
# cert the API must not fail to trust server-to-server.
if voice_config is not None:
in_memory = str(db_path) == ":memory:"
custom_voice_service = CustomVoiceService(
config=CustomVoiceConfig(
panel_url=voice_config.panel_url,
tts_url=voice_config.tts_url,
registry_file=voice_config.registry_file,
worker_state_file=voice_config.worker_state_file,
),
http=httpx.AsyncClient(verify=False, timeout=httpx.Timeout(30, read=120)),
selection_path=None if in_memory else Path(db_path).with_name(
Path(db_path).stem + "-voice-selection.json"),
registry_path=None if in_memory else Path(db_path).with_name(
Path(db_path).stem + "-voice-custom.json"),
journal_path=None if in_memory else Path(db_path).with_name(
Path(db_path).stem + "-voice-usage.jsonl"),
)
app.state.voice_service = voice_service
app.include_router(build_voice_router(voice_service))
app.state.custom_voice_service = custom_voice_service
app.include_router(build_voice_router(voice_service, custom_voice_service))
@app.exception_handler(RequestValidationError)
async def invalid(_request, exc):
+14
View File
@@ -0,0 +1,14 @@
"""跨层共享的纯文本校验(唯一实现,API 与语音模块共用)."""
from __future__ import annotations
def safe_text(value: str, maximum: int, label: str, required: bool = False) -> str:
value = value.strip()
if (
(required and not value)
or len(value) > maximum
or any(ord(c) < 32 or ord(c) == 127 or c in "<>" for c in value)
):
raise ValueError(f"{label}请填写{1 if required else 0}–{maximum}字,不含控制字符或尖括号。")
return value
+4
View File
@@ -19,6 +19,10 @@ def __getattr__(name: str): # lazy: API side must import without livekit instal
from . import session
return getattr(session, name)
if name in {"CustomVoiceConfig", "CustomVoiceService"}:
from . import custom
return getattr(custom, name)
if name == "build_voice_router":
from . import router
+423
View File
@@ -0,0 +1,423 @@
"""参考音频自定义声音与专属音色选择(HEL-899,CyberGril 统一 API 侧).
复用既有能力,不自建克隆引擎(GOV-006):
* 音色登记 = .12 语音面板 ``POST /api/voices/upload``(写共享 ``voices.json``
+ CosyVoice mtime 热加载;参考文本留空时面板用 FunASR 自动转写)。
本模块是它的**服务端代理**:浏览器永远不直连 8090,凭据/共享状态不进浏览器,
共享 ``voices.json`` 也只有 8090 这一个写者(跨进程读-改-写不再加竞态)。
* 试听 = CosyVoice ``POST /tts``(返回 24k mono int16 PCM),本模块包成 WAV
给浏览器;每次试听都是新合成,不缓存旧音频冒充本次结果。
* 应用 = 写 CyberGril 自己的音色状态(worker 的
``voice_state_cybergril.json``),通话开启时由 router 捕获并落同一文件,
worker 在会话入口读一次——通话中改选最迟下一通话生效,绝不半句换人。
命名空间:新增音色一律 ``cg-`` + 8 位十六进制(服务端生成,不收用户起名),
不可能撞上/覆盖共享注册表里的既有 11 支音色,也不会互相覆盖。显示名
(label,可中文)只存在 CyberGril 自己的资料空间,不进共享注册表。
共享注册表涉及的操作(全部经 8090,本服务不直接改共享文件):
1. ``GET /api/voices`` 读列表(只读);2. ``POST /api/voices/upload`` 以
``cg-`` 专属 ID 登记新参考音频(唯一写入);3. 登记成功后**只读**回看
``voices.json``(部署配置的路径)补全 ASR 自动转写的参考文本,供备份清单。
通用助手自己的 ``voice_state.json`` / ``persona_state.json`` 与既有音色
条目从不触碰,也不通过改全局默认偷换她的声音。
持久化(CyberGril 资料空间,实例数据库旁,与语音清理账同模式):
``<db>-voice-selection.json``(当前选择,重启读回)、
``<db>-voice-custom.json``(自定义音色元数据 + 备份清单)、
``<db>-voice-usage.jsonl``(ASR/TTS 资源使用流水,可核算;有界保留)。
"""
from __future__ import annotations
import asyncio
import contextlib
import io
import json
import secrets
import struct
import time
import wave
from dataclasses import dataclass, field
from pathlib import Path
import httpx
from ..contracts.text import safe_text
CUSTOM_PREFIX = "cg-"
ID_HEX_CHARS = 8
MAX_UPLOAD_BYTES = 15 * 1024 * 1024 # 与 8090 面板一致
MIN_UPLOAD_BYTES = 16000 * 2 # 与 8090 面板一致(<2s @16k mono int16 的字节代理)
MIN_SECONDS = 2.0 # 参考音频有效时长下限(比面板的字节检查更诚实)
PREVIEW_TEXT_MAX = 200
LABEL_MAX = 20
PROMPT_TEXT_MAX = 500
JOURNAL_KEEP_LINES = 2000
JOURNAL_PRUNE_ABOVE = 5000
DEFAULT_PREVIEW_TEXT = "你好,这是我的声音,以后就用它陪你说话。"
STATE_VERSION = 1
class RegistryUnavailable(Exception):
"""8090 面板或 CosyVoice 暂不可用——如实上抛,不假装登记/试听成功。"""
class StateWriteFailed(Exception):
"""音色状态文件写不进——选择未成立,已整体回滚,不留下半状态。"""
class RegistrationFailed(Exception):
"""面板拒绝或返回异常——登记未成立,不留下半条可选项。"""
@dataclass
class CustomVoiceConfig:
panel_url: str = "https://127.0.0.1:8090"
tts_url: str = "http://127.0.0.1:9880"
# 只读回看(ASR 参考文本补全);不配置则清单里该字段如实留空
registry_file: str | None = None
# CyberGril 专属 worker 的音色状态文件(worker 在会话入口读一次)
worker_state_file: str = "/opt/voice-agent-cybergril/voice_state_cybergril.json"
def _atomic_write_json(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(path)
def parse_wav_header(data: bytes) -> dict:
"""最小 WAV 头解析(RIFF/WAVE + fmt/data 定位),用于服务端复验.
只做诚实的格式事实读取:magic、声道数、采样率、位深、data 长度、时长。
不信任任何客户端声明,也不接受用户文件路径(输入只有上传字节)。
"""
if len(data) < 44 or data[:4] != b"RIFF" or data[8:12] != b"WAVE":
raise ValueError("只支持 WAV 格式的参考音频。")
pos, channels, rate, bits, data_bytes = 12, None, None, None, 0
while pos + 8 <= len(data):
chunk_id = data[pos:pos + 4]
(size,) = struct.unpack_from("<I", data, pos + 4)
body = pos + 8
if chunk_id == b"fmt ":
if size < 16 or body + 16 > len(data):
raise ValueError("WAV 头不完整。")
fmt_code, channels, rate, _, _, bits = struct.unpack_from("<HHIIHH", data, body)
if fmt_code not in (1, 3, 0xFFFE):
raise ValueError("只支持 PCM/IEEE float WAV。")
elif chunk_id == b"data":
data_bytes = min(size, len(data) - body)
pos = body + size + (size & 1)
if not channels or not rate or not bits:
raise ValueError("WAV 头缺少格式信息。")
byte_rate = max(rate * channels * bits // 8, 1)
return {"channels": channels, "sample_rate": rate, "bits": bits,
"data_bytes": data_bytes, "seconds": data_bytes / byte_rate}
def pcm_to_wav(pcm: bytes, sample_rate: int = 24000, channels: int = 1, width: int = 2) -> bytes:
"""CosyVoice 的 audio/L16 裸 PCM 包成浏览器可播的 WAV(无缓存,每次现包)。"""
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
wav.setnchannels(channels)
wav.setsampwidth(width)
wav.setframerate(sample_rate)
wav.writeframes(pcm)
return buffer.getvalue()
@dataclass
class VoiceSelection:
voice: str | None = None
label: str = ""
updated_at: int = 0
@dataclass
class CustomVoiceService:
"""统一 API 的自定义音色门面(一个实例一份文件,进程内锁串行化写)."""
config: CustomVoiceConfig = field(default_factory=CustomVoiceConfig)
http: httpx.AsyncClient = field(default_factory=httpx.AsyncClient)
clock: object = time.time
selection_path: Path | str | None = None
registry_path: Path | str | None = None # 自定义音色元数据(备份清单同源)
journal_path: Path | str | None = None
def __post_init__(self) -> None:
self._lock = asyncio.Lock()
self._selection = self._load_selection()
self._custom: dict[str, dict] = self._load_custom()
self._prune_journal()
# -- 持久化(CyberGril 资料空间;重启读回) ------------------------------
def _load_selection(self) -> VoiceSelection:
if not self.selection_path:
return VoiceSelection()
try:
data = json.loads(Path(self.selection_path).read_text(encoding="utf-8"))
return VoiceSelection(voice=data.get("voice") or None,
label=str(data.get("label", "")),
updated_at=int(data.get("updated_at", 0)))
except (OSError, ValueError):
return VoiceSelection()
def _load_custom(self) -> dict[str, dict]:
if not self.registry_path:
return {}
try:
data = json.loads(Path(self.registry_path).read_text(encoding="utf-8"))
return dict(data.get("voices", {})) if data.get("version") == STATE_VERSION else {}
except (OSError, ValueError):
return {}
def _persist_selection(self) -> None:
if self.selection_path:
_atomic_write_json(Path(self.selection_path), {
"version": STATE_VERSION,
"voice": self._selection.voice,
"label": self._selection.label,
"updated_at": self._selection.updated_at,
})
def _persist_custom(self) -> None:
if self.registry_path:
_atomic_write_json(Path(self.registry_path), {
"version": STATE_VERSION, "voices": self._custom,
})
# -- 资源使用流水(可核算;ASR/TTS 才记,选择/列出不耗资源不记) ----------
def _journal(self, kind: str, voice: str) -> None:
if not self.journal_path:
return
try:
with Path(self.journal_path).open("a", encoding="utf-8") as fh:
fh.write(json.dumps({"ts": int(self.clock() * 1000),
"kind": kind, "voice": voice}, ensure_ascii=False) + "\n")
except OSError:
pass # 流水尽力而为;核算缺失不影响功能诚实性(文档已注明)
def _prune_journal(self) -> None:
if not self.journal_path:
return
try:
lines = Path(self.journal_path).read_text(encoding="utf-8").splitlines()
except OSError:
return
if len(lines) > JOURNAL_PRUNE_ABOVE:
kept = [ln for ln in lines[-JOURNAL_KEEP_LINES:] if ln.strip()]
tmp = Path(self.journal_path).with_suffix(".jsonl.tmp")
tmp.write_text("\n".join(kept) + "\n", encoding="utf-8")
tmp.replace(self.journal_path)
def previewed_voices(self) -> set[str]:
"""已成功试听过的音色(持久流水读回;重启不丢「应用前有可听试听」凭据)."""
if not self.journal_path:
return set()
try:
lines = Path(self.journal_path).read_text(encoding="utf-8").splitlines()
except OSError:
return set()
seen: set[str] = set()
for line in lines:
try:
entry = json.loads(line)
except ValueError:
continue
if entry.get("kind") == "preview_tts":
seen.add(str(entry.get("voice", "")))
return seen
# -- 共享注册表(8090 面板,唯一写者) ------------------------------------
async def registry_list(self) -> list[str]:
try:
response = await self.http.get(
f"{self.config.panel_url.rstrip('/')}/api/voices", timeout=5.0)
response.raise_for_status()
return sorted(response.json().get("voices", []))
except Exception as exc:
raise RegistryUnavailable(f"voices list: {type(exc).__name__}") from exc
def _read_registry_entry(self, voice_id: str) -> dict | None:
"""只读回看共享 voices.json(部署配置路径)补全 ASR 参考文本;失败留空."""
path = self.config.registry_file
if not path:
return None
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
entry = data.get(voice_id)
return dict(entry) if isinstance(entry, dict) else None
except (OSError, ValueError):
return None
async def register(self, *, data: bytes, label: str, prompt_text: str,
allow_asr: bool) -> dict:
"""登记参考音频:服务端复验 → cg- 专属 ID → 面板 zero-shot 注册.
失败不留下半条可选项:面板拒绝/异常时不写任何 CyberGril 元数据,
面板自己对失败的 wav 有清理(ASR 失败即删,见其源码)。
"""
if not data:
raise RegistrationFailed("请选择一段参考音频。")
if len(data) > MAX_UPLOAD_BYTES:
raise RegistrationFailed("文件过大(>15MB),请录 5–20 秒的一段。")
try:
header = parse_wav_header(data) # 非法格式在这里被拒
label = safe_text(label or "", LABEL_MAX, "声音名字") or ""
prompt_text = (safe_text(prompt_text or "", PROMPT_TEXT_MAX, "参考文字") or "").strip()
except ValueError as exc:
raise RegistrationFailed(str(exc)) from exc
if len(data) < MIN_UPLOAD_BYTES or header["seconds"] < MIN_SECONDS:
raise RegistrationFailed("参考音频太短(至少 2 秒),请录 5–20 秒。")
if not prompt_text and not allow_asr:
raise RegistrationFailed(
"请填写这段音频的参考文字,或明确选择让系统转写(会用到语音识别)。")
async with self._lock:
known = set(await self.registry_list())
for _ in range(6):
voice_id = CUSTOM_PREFIX + secrets.token_hex(ID_HEX_CHARS // 2)
if voice_id not in known and voice_id not in self._custom:
break
else: # pragma: no cover - 2^32 空间连撞 6 次属天文事件
raise RegistrationFailed("生成声音编号失败,请重试。")
files = {"file": (f"{voice_id}.wav", data, "audio/wav")}
form = {"name": voice_id, "prompt_text": prompt_text}
try:
response = await self.http.post(
f"{self.config.panel_url.rstrip('/')}/api/voices/upload",
data=form, files=files, timeout=60.0)
except Exception as exc:
raise RegistryUnavailable(f"voices upload: {type(exc).__name__}") from exc
if response.status_code >= 500:
raise RegistryUnavailable(f"voices upload: HTTP {response.status_code}")
if response.status_code >= 400:
# 面板拒绝(格式/大小/转写失败):登记未成立,如实透传原因
detail = ""
try:
detail = str(response.json().get("detail", ""))
except Exception:
detail = response.text[:120]
raise RegistrationFailed(detail or f"音色登记被拒绝(HTTP {response.status_code})。")
if voice_id not in set(await self.registry_list()):
raise RegistrationFailed("登记结果没有出现在音色列表里,请重试。")
entry = self._read_registry_entry(voice_id) or {}
record = {
"id": voice_id,
"label": label or voice_id,
"prompt_text": entry.get("prompt_text") or (prompt_text or None),
"prompt_text_source": "asr" if (not prompt_text and entry.get("prompt_text"))
else ("user" if prompt_text else None),
"prompt_wav": entry.get("prompt_wav"),
"registered_at": int(self.clock() * 1000),
}
self._custom[voice_id] = record
self._persist_custom()
if record["prompt_text_source"] == "asr":
self._journal("register_asr", voice_id) # 显式获准的 FunASR 转写,可核算
return dict(record)
async def preview_pcm(self, *, voice: str, text: str | None) -> bytes:
"""试听:先验存在(CosyVoice 对未知音色会静默回落 default,必须拦住),
再现场合成一段新 PCM。绝不缓存、绝不拿旧音频冒充本次结果。"""
if not voice or not await self._voice_exists(voice):
raise KeyError(voice)
try:
words = safe_text(text or DEFAULT_PREVIEW_TEXT, PREVIEW_TEXT_MAX, "试听文字") \
or DEFAULT_PREVIEW_TEXT
except ValueError as exc:
raise RegistrationFailed(str(exc)) from exc
try:
response = await self.http.post(
f"{self.config.tts_url.rstrip('/')}/tts",
json={"text": words, "voice": voice}, timeout=120.0)
except Exception as exc:
raise RegistryUnavailable(f"tts: {type(exc).__name__}") from exc
if response.status_code >= 400:
raise RegistryUnavailable(f"tts: HTTP {response.status_code}")
pcm = response.content or b""
if not pcm:
raise RegistryUnavailable("tts: empty audio")
self._journal("preview_tts", voice)
return pcm
async def _voice_exists(self, voice: str) -> bool:
return voice in set(await self.registry_list())
# -- 专属音色选择(换声音只换发声;人格/记忆/关系一概不动) ----------------
def selection(self) -> VoiceSelection:
return VoiceSelection(self._selection.voice, self._selection.label,
self._selection.updated_at)
def custom_voices(self) -> dict[str, dict]:
return {vid: dict(rec) for vid, rec in self._custom.items()}
def read_worker_voice(self) -> str:
"""worker 当前状态文件里的音色(部署/D1 域;无人经 API 选择时不代写)."""
path = Path(self.config.worker_state_file)
try:
return str(json.loads(path.read_text(encoding="utf-8")).get("voice", "")) or ""
except (OSError, ValueError):
return ""
def write_worker_voice(self, voice: str) -> None:
"""原子写 worker 音色状态(保留文件里其他键);失败抛 OSError,不半写."""
path = Path(self.config.worker_state_file)
try:
state = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(state, dict):
state = {}
except (OSError, ValueError):
state = {}
state["voice"] = voice
_atomic_write_json(path, state)
async def apply_selection(self, *, voice: str) -> VoiceSelection:
"""把她后续通话的发声换成指定音色(最迟下一通话生效).
自定义(cg-)音色必须先成功试听过(「应用前有可听试听」);内置
音色是既有 D1 候选,不强制。写 worker 状态文件与本地选择状态都
原子落盘;任一失败整体回滚,绝不留下两边不一致的半状态。
"""
if not voice or not await self._voice_exists(voice):
raise KeyError(voice)
if voice.startswith(CUSTOM_PREFIX) and voice not in self.previewed_voices():
raise PermissionError(voice)
async with self._lock:
previous = VoiceSelection(self._selection.voice, self._selection.label,
self._selection.updated_at)
record = self._custom.get(voice)
try:
self._selection = VoiceSelection(
voice=voice,
label=(record["label"] if record else voice),
updated_at=int(self.clock() * 1000))
self._persist_selection()
self.write_worker_voice(voice)
except OSError as exc:
self._selection = previous
with contextlib.suppress(OSError):
self._persist_selection() # 回滚本地状态
if previous.voice:
self.write_worker_voice(previous.voice)
raise StateWriteFailed(f"voice state write: {type(exc).__name__}") from exc
return VoiceSelection(self._selection.voice, self._selection.label,
self._selection.updated_at)
def manifest(self) -> dict:
"""备份清单(CG-009 承接用):参考音频路径/参考文本/映射 + 当前选择."""
return {
"version": STATE_VERSION,
"selection": {"voice": self._selection.voice, "label": self._selection.label},
"custom_voices": [dict(rec) for rec in
sorted(self._custom.values(), key=lambda r: r["registered_at"])],
"shared_registry_note": (
"自定义音色登记在 .12 共享 voices.json(8090 面板写入)与 "
"voice_samples/<id>.wav;恢复时按 prompt_text + prompt_wav 重新登记即可。"
),
}
async def aclose(self) -> None:
await self.http.aclose()
+164 -3
View File
@@ -4,7 +4,12 @@ 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.
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.
@@ -15,6 +20,27 @@ DELETE /api/voice/session/{id} end: delete the LiveKit room, which
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.
"""
@@ -22,19 +48,52 @@ 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 build_voice_router(service: VoiceSessionService | None) -> APIRouter:
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")
@@ -59,8 +118,9 @@ def build_voice_router(service: VoiceSessionService | None) -> APIRouter:
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)
session = await service.open_session(epoch=state.epoch, voice=captured)
except Exception:
raise HTTPException(503, REFUSAL_LIVEKIT_DOWN) from None
return {
@@ -71,6 +131,7 @@ def build_voice_router(service: VoiceSessionService | None) -> APIRouter:
"agent_name": service.config.agent_name,
"epoch": session.epoch,
"expires_at": int(session.expires_at * 1000),
"voice": session.voice,
}
@router.delete("/session/{session_id}")
@@ -101,4 +162,104 @@ def build_voice_router(service: VoiceSessionService | None) -> APIRouter:
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
+35 -3
View File
@@ -65,6 +65,11 @@ class VoiceConfig:
token_ttl_seconds: float = DEFAULT_TOKEN_TTL
session_ttl_seconds: float = DEFAULT_SESSION_TTL
dispatch_timeout_seconds: float = 5.0
# HEL-899 自定义音色(复用 .12 语音面板与 CosyVoice;缺省即本机默认值)
panel_url: str = "https://127.0.0.1:8090"
tts_url: str = "http://127.0.0.1:9880"
registry_file: str | None = None # 共享 voices.json 只读回看(ASR 参考文本补全)
worker_state_file: str = "/opt/voice-agent-cybergril/voice_state_cybergril.json"
def sanitized(self) -> dict:
return {
@@ -116,6 +121,10 @@ def load_voice_config(
"api_key": os.environ.get("CYBERGRIL_VOICE_API_KEY"),
"api_secret": os.environ.get("CYBERGRIL_VOICE_API_SECRET"),
"tts_health_url": os.environ.get("CYBERGRIL_VOICE_TTS_HEALTH_URL"),
"panel_url": os.environ.get("CYBERGRIL_VOICE_PANEL_URL"),
"tts_url": os.environ.get("CYBERGRIL_VOICE_TTS_URL"),
"registry_file": os.environ.get("CYBERGRIL_VOICE_REGISTRY_FILE"),
"worker_state_file": os.environ.get("CYBERGRIL_VOICE_WORKER_STATE"),
}
values = {**data, **{k: v for k, v in overrides.items() if v}}
required = ("livekit_url", "livekit_internal", "api_key", "api_secret")
@@ -131,6 +140,11 @@ def load_voice_config(
tts_health_url=str(values.get("tts_health_url") or "http://127.0.0.1:9880/health"),
token_ttl_seconds=float(values.get("token_ttl_seconds") or DEFAULT_TOKEN_TTL),
session_ttl_seconds=float(values.get("session_ttl_seconds") or DEFAULT_SESSION_TTL),
panel_url=str(values.get("panel_url") or "https://127.0.0.1:8090"),
tts_url=str(values.get("tts_url") or "http://127.0.0.1:9880"),
registry_file=(str(values["registry_file"]) if values.get("registry_file") else None),
worker_state_file=str(values.get("worker_state_file")
or "/opt/voice-agent-cybergril/voice_state_cybergril.json"),
)
@@ -143,12 +157,13 @@ class VoiceSession:
expires_at: float
epoch: int
dispatch_id: str = ""
voice: str = "" # HEL-899: 本次通话捕获的有效音色(开启时定住,通话中改选不影响本通话)
def as_state(self) -> dict:
return {
"session_id": self.session_id, "room": self.room, "identity": self.identity,
"created_at": self.created_at, "expires_at": self.expires_at,
"epoch": self.epoch, "dispatch_id": self.dispatch_id,
"epoch": self.epoch, "dispatch_id": self.dispatch_id, "voice": self.voice,
}
@classmethod
@@ -158,6 +173,7 @@ class VoiceSession:
identity=str(data.get("identity", "")), created_at=float(data.get("created_at", 0)),
expires_at=float(data.get("expires_at", 0)), epoch=int(data.get("epoch", 0)),
dispatch_id=str(data.get("dispatch_id", "")),
voice=str(data.get("voice", "")),
)
@@ -193,6 +209,7 @@ class _CleanupDebt:
class _Health:
checked: float = 0.0
ok: bool = False
voices: list[str] | None = None # HEL-899: /health 顺带的热加载音色表(无则 None)
@dataclass
@@ -282,11 +299,25 @@ class VoiceSessionService:
try:
response = await self.http.get(self.config.tts_health_url, timeout=3.0)
ok = response.status_code // 100 == 2
voices: list[str] | None = None
if ok:
# CosyVoice /health = {"ok", "voices": [...]}(同请求内已热加载);
# 空体/异常体只当"探到了但没带名单",不推翻 ok 判定。
try:
listed = response.json().get("voices")
voices = sorted(str(v) for v in listed) if isinstance(listed, list) else None
except Exception:
voices = None
except Exception:
ok = False
self._tts_health = _Health(checked=self.clock(), ok=ok)
voices = None
self._tts_health = _Health(checked=self.clock(), ok=ok, voices=voices)
return ok
def last_health_voices(self) -> list[str] | None:
"""最近一次健康探测拿到的音色表(None=本次探测没带回名单)."""
return self._tts_health.voices
# -- lifecycle ----------------------------------------------------------
def _prune(self) -> None:
"""Expired registrations move into the cleanup ledger — never silently
@@ -387,7 +418,7 @@ class VoiceSessionService:
this instance (bounded by the persisted ledger)."""
self._kick_cleanup()
async def open_session(self, *, epoch: int) -> VoiceSession:
async def open_session(self, *, epoch: int, voice: str = "") -> VoiceSession:
self._prune()
self._kick_cleanup()
alphabet = string.ascii_lowercase + string.digits
@@ -411,6 +442,7 @@ class VoiceSessionService:
expires_at=now + self.config.session_ttl_seconds,
epoch=epoch,
dispatch_id=dispatch.dispatch_id,
voice=voice,
)
self._sessions[session.session_id] = session
self._persist_state()