192 lines
8.7 KiB
Python
192 lines
8.7 KiB
Python
"""HEL-899 offline one-shot chain check: custom voice registration -> preview
|
|
-> apply -> call-time capture -> restart persistence, against the real app
|
|
with a fake .12 voice stack (panel + CosyVoice) and fake LiveKit.
|
|
|
|
Zero network, zero real LLM/embedding/ASR/TTS calls. Mirrors
|
|
scripts/verify_hel877_voice_chain.py in spirit: real router + real services,
|
|
fake transports only.
|
|
|
|
Usage: PYTHONPATH=src .venv311/bin/python scripts/verify_hel899_custom_voice.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import json
|
|
import sys
|
|
import tempfile
|
|
import wave
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
from test_r2 import R2LLM # noqa: E402
|
|
|
|
from cybergril.api.app import create_app # noqa: E402
|
|
from cybergril.life.runtime import LifeConfig # noqa: E402
|
|
from cybergril.think.router import build_router # noqa: E402
|
|
from cybergril.think.scenes import Tier # noqa: E402
|
|
from cybergril.voice.custom import CustomVoiceConfig, CustomVoiceService # noqa: E402
|
|
from cybergril.voice.session import VoiceConfig, VoiceSessionService # noqa: E402
|
|
|
|
BUILTIN = ["default", "rain", "xiaoyun"]
|
|
CREATE = {"name": "链路测试", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"}
|
|
RESULTS: list[tuple[str, bool, str]] = []
|
|
|
|
|
|
def check(name: str, ok: bool, note: str = "") -> None:
|
|
RESULTS.append((name, ok, note))
|
|
print(f"{'PASS' if ok else 'FAIL'} {name} {note}")
|
|
|
|
|
|
def make_wav(seconds: float = 3.0) -> bytes:
|
|
buffer = io.BytesIO()
|
|
with wave.open(buffer, "wb") as wav:
|
|
wav.setnchannels(1)
|
|
wav.setsampwidth(2)
|
|
wav.setframerate(16000)
|
|
wav.writeframes(b"\x00\x01" * int(16000 * seconds))
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _multipart_field(body: bytes, field: bytes) -> str:
|
|
for part in body.split(b"--"):
|
|
header, _, value = part.partition(b"\r\n\r\n")
|
|
if field + b'"' in header:
|
|
return value.strip(b"\r\n-").decode()
|
|
return ""
|
|
|
|
|
|
def fake_transport(state: dict) -> httpx.MockTransport:
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
host, path = request.url.host, request.url.path
|
|
if host == "panel.test":
|
|
if path == "/api/voices" and request.method == "GET":
|
|
return httpx.Response(200, json={"voices": sorted(state["ids"])})
|
|
if path == "/api/voices/upload":
|
|
name = _multipart_field(request.content, b"name")
|
|
prompt_text = _multipart_field(request.content, b"prompt_text")
|
|
if not prompt_text: # 参考文本为空 → 面板 FunASR 转写(桩:固定文本)
|
|
prompt_text = state["asr_text"]
|
|
state["ids"].append(name)
|
|
state["registry"][name] = {"prompt_text": prompt_text,
|
|
"prompt_wav": f"/samples/{name}.wav"}
|
|
if state.get("registry_file"):
|
|
Path(state["registry_file"]).write_text(
|
|
json.dumps(state["registry"], ensure_ascii=False), encoding="utf-8")
|
|
state["uploads"] += 1
|
|
return httpx.Response(200, json={"ok": True, "voice": name})
|
|
return httpx.Response(404)
|
|
if host == "tts.test":
|
|
if path == "/health":
|
|
return httpx.Response(200, json={"ok": True, "voices": sorted(state["ids"])})
|
|
if path == "/tts":
|
|
body = json.loads(request.content)
|
|
state["tts_calls"] += 1
|
|
return httpx.Response(200, content=f"{body['voice']}:".encode() + b"\x01\x00" * 240)
|
|
if host == "livekit.test":
|
|
return httpx.Response(200, json={"id": "AD_1", "room": "r"})
|
|
return httpx.Response(404)
|
|
|
|
return httpx.MockTransport(handler)
|
|
|
|
|
|
def build(tmp: Path, state: dict):
|
|
combined = httpx.MockTransport(lambda request: fake_transport(state).handler(request))
|
|
voice = VoiceSessionService(
|
|
config=VoiceConfig(livekit_url="ws://voice.test:7880",
|
|
livekit_internal="http://livekit.test",
|
|
api_key="devkey", api_secret="test-secret-not-real",
|
|
tts_health_url="http://tts.test/health"),
|
|
http=httpx.AsyncClient(transport=combined))
|
|
custom = CustomVoiceService(
|
|
config=CustomVoiceConfig(panel_url="https://panel.test", tts_url="http://tts.test",
|
|
registry_file=str(tmp / "voices.json"),
|
|
worker_state_file=str(tmp / "worker.json")),
|
|
http=httpx.AsyncClient(transport=fake_transport(state), verify=False),
|
|
selection_path=tmp / "sel.json", registry_path=tmp / "custom.json",
|
|
journal_path=tmp / "usage.jsonl")
|
|
provider = R2LLM()
|
|
router = build_router(providers={t: provider
|
|
for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
|
return create_app(db_path=":memory:", router=router,
|
|
life_config=LifeConfig(enabled=True, poll_seconds=3600),
|
|
semantic_mode="stub", voice_service=voice,
|
|
custom_voice_service=custom), custom
|
|
|
|
|
|
def main() -> int:
|
|
state = {"ids": list(BUILTIN), "registry": {}, "tts_calls": 0, "uploads": 0,
|
|
"asr_text": "自动转写参考文本。"}
|
|
with tempfile.TemporaryDirectory() as raw:
|
|
tmp = Path(raw)
|
|
registry_file = tmp / "voices.json"
|
|
registry_file.write_text(json.dumps(state["registry"]), encoding="utf-8")
|
|
state["registry_file"] = str(registry_file)
|
|
app, _custom = build(tmp, state)
|
|
with TestClient(app) as client:
|
|
client.post("/api/companion", json=CREATE)
|
|
|
|
listing = client.get("/api/voice/voices").json()
|
|
check("list builtin", {v["id"] for v in listing["voices"]} == set(BUILTIN))
|
|
|
|
refusal = client.post("/api/voice/voices", content=make_wav())
|
|
check("no-asr-consent refused", refusal.status_code == 422
|
|
and state["uploads"] == 0, refusal.json().get("detail", ""))
|
|
|
|
registered = client.post("/api/voice/voices",
|
|
params={"allow_asr": "true", "label": "她的声音"},
|
|
content=make_wav())
|
|
record = registered.json()
|
|
check("register with explicit ASR", registered.status_code == 201
|
|
and record["id"].startswith("cg-")
|
|
and record["prompt_text_source"] == "asr", str(record))
|
|
|
|
unapplied = client.post("/api/voice/selection", json={"voice": record["id"]})
|
|
check("apply requires preview", unapplied.status_code == 409)
|
|
|
|
preview = client.post("/api/voice/preview", json={"voice": record["id"]})
|
|
check("preview fresh wav", preview.status_code == 200
|
|
and preview.headers["content-type"] == "audio/wav"
|
|
and state["tts_calls"] == 1)
|
|
|
|
applied = client.post("/api/voice/selection", json={"voice": record["id"]})
|
|
check("apply after preview", applied.status_code == 200
|
|
and json.loads((tmp / "worker.json").read_text())["voice"] == record["id"])
|
|
|
|
opened = client.post("/api/voice/session").json()
|
|
check("session captures selection", opened["voice"] == record["id"])
|
|
|
|
client.post("/api/voice/selection", json={"voice": "rain"})
|
|
pinned = client.app.state.voice_service.get(opened["session_id"])
|
|
check("call keeps its voice", pinned.voice == record["id"])
|
|
second = client.post("/api/voice/session").json()
|
|
check("next call uses new voice", second["voice"] == "rain")
|
|
|
|
health = client.get("/api/health").json()
|
|
check("capabilities.voice stays false",
|
|
health["capabilities"]["voice"] is False)
|
|
|
|
# “重启”:同批文件重建服务,选择/元数据/试听凭据都读回
|
|
app2, _custom2 = build(tmp, state)
|
|
with TestClient(app2) as client2:
|
|
client2.post("/api/companion", json=CREATE)
|
|
selection = client2.get("/api/voice/selection").json()
|
|
listing = client2.get("/api/voice/voices").json()
|
|
entry = next(v for v in listing["voices"] if v["id"] == record["id"])
|
|
check("selection survives restart", selection["voice"] == "rain")
|
|
check("custom entry survives restart", entry["label"] == "她的声音"
|
|
and entry["previewed"] is True)
|
|
|
|
failed = [name for name, ok, _ in RESULTS if not ok]
|
|
print(f"\n{len(RESULTS) - len(failed)}/{len(RESULTS)} passed")
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|