Files
CyberGril/docs/rework/hel910/tools/hel910_client.py
T

476 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""HEL-910 real-window voice test client (runs on .12, agent venv).
继承 HEL-907 hel907_client 的真链框架(预录音频回放经真实 WebRTC ->
LiveKit -> FunASR -> 统一 /api/chat(LLM) -> CosyVoice -> WebRTC 回流),
为本卡改造:dry(建房即删的挂断核验)、call2(稍长问题的首文/首声时延 +
回放打断停声同钟量测 + 思考泄漏取证)。所有时间戳同一客户端时钟(毫秒)。
文字打断的「真实网页原发送入口」场景在本机浏览器驱动脚本里,不在本文件。
Usage: hel910_client.py <phase> <outdir>
phases: dry | call2 | status
"""
from __future__ import annotations
import asyncio
import json
import sys
import time
import wave
from pathlib import Path
import httpx
from livekit import api, rtc
API = "http://127.0.0.1:8360"
LK_INTERNAL = "http://127.0.0.1:7880"
KEY = "devkey"
SECRET = "voiceagent-local-secret-2026"
SAMPLES = Path("/opt/voice-agent/cosyvoice/voice_samples")
TRIM = Path("/opt/cybergril-hel910/etc/trim")
DB = "/opt/cybergril-hel910/data/companion.db"
OUT = Path(sys.argv[2] if len(sys.argv) > 2 else "/opt/cybergril-hel910/evidence")
OUT.mkdir(parents=True, exist_ok=True)
T0 = time.time()
def log(msg: str) -> None:
print(f"[{time.time()-T0:8.2f}] {msg}", flush=True)
def now_ms() -> int:
return int(time.time() * 1000)
def load_wav_16k_mono(p: Path) -> bytes:
with wave.open(str(p), "rb") as w:
raw = w.readframes(w.getnframes())
rate, ch, width = w.getframerate(), w.getnchannels(), w.getsampwidth()
assert width == 2 and ch == 1 and rate == 16000, f"{p}: {rate}Hz ch{ch} w{width}"
return raw
async def list_rooms() -> list[str]:
lk = api.LiveKitAPI(url=LK_INTERNAL, api_key=KEY, api_secret=SECRET)
try:
res = await lk.room.list_rooms(api.ListRoomsRequest())
return [r.name for r in res.rooms]
finally:
await lk.aclose()
def safe_json(r: httpx.Response):
try:
return r.json()
except Exception:
return r.text[:200]
class Call:
"""One voice call through the real product API; full frame timeline kept."""
def __init__(self, tag: str):
self.tag = tag
self.http = httpx.AsyncClient(timeout=15)
self.room: rtc.Room | None = None
self.session: dict = {}
self.source: rtc.AudioSource | None = None
self.track: rtc.LocalAudioTrack | None = None
self.subtitles: list[dict] = []
self.frames: list[tuple[int, int]] = [] # (arrival_ms, bytes)
self.agent_audio = bytearray()
self.audio_rate = 48000
self.agent_joined_ms: int | None = None
self._speaking = False
self._keeper: asyncio.Task | None = None
self._first_pub_ms: int | None = None
async def open(self) -> dict:
r = await self.http.post(f"{API}/api/voice/session")
r.raise_for_status()
self.session = r.json()
log(f"[{self.tag}] session room={self.session['room']} voice={self.session.get('voice')} epoch={self.session['epoch']}")
return self.session
async def connect(self) -> None:
url = self.session["url"]
self.room = rtc.Room()
self.room.on("data_received", self._on_data)
self.room.on("track_subscribed", self._on_track)
self.room.on("participant_connected", self._on_participant)
await self.room.connect(url, self.session["token"])
self.source = rtc.AudioSource(16000, 1)
self.track = rtc.LocalAudioTrack.create_audio_track("mic", self.source)
opt = rtc.TrackPublishOptions()
opt.source = rtc.TrackSource.SOURCE_MICROPHONE
await self.room.local_participant.publish_track(self.track, opt)
log(f"[{self.tag}] connected via {url} mic published")
self._keeper = asyncio.create_task(self._keep_silent())
async def _keep_silent(self) -> None:
silence = b"\x00" * 3200
while self.source is not None:
if not self._speaking:
try:
await self.source.capture_frame(
rtc.AudioFrame(silence, 16000, 1, 1600))
except Exception:
return
await asyncio.sleep(0.1)
def _on_data(self, msg: rtc.DataPacket) -> None:
try:
payload = json.loads(msg.data.decode("utf-8"))
except Exception:
return
payload["_at_ms"] = now_ms()
self.subtitles.append(payload)
text = str(payload.get("text", ""))[:40]
log(f"[{self.tag}][sub] seq={payload.get('seq')} kind={payload.get('kind')} "
f"role={payload.get('role')} {text}")
def _on_participant(self, p: rtc.RemoteParticipant) -> None:
log(f"[{self.tag}] joined: {p.identity}")
if "agent" in p.identity:
self.agent_joined_ms = now_ms()
def _on_track(self, track: rtc.Track, pub, participant) -> None:
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
log(f"[{self.tag}] agent audio track: {track.sid}")
async def read():
stream = rtc.AudioStream(track)
async for ev in stream:
frame = ev.frame
self.audio_rate = frame.sample_rate
self.frames.append((now_ms(), len(bytes(frame.data))))
self.agent_audio.extend(bytes(frame.data))
asyncio.create_task(read())
async def _publish_pcm(self, pcm: bytes, label: str) -> dict:
self._speaking = True
started = now_ms()
self._first_pub_ms = self._first_pub_ms or started
step = 3200
try:
for i in range(0, len(pcm), step):
chunk = pcm[i:i + step]
if len(chunk) < step:
chunk = chunk + b"\x00" * (step - len(chunk))
await self.source.capture_frame(rtc.AudioFrame(chunk, 16000, 1, 1600))
await asyncio.sleep(0.1)
finally:
self._speaking = False
ended = now_ms()
log(f"[{self.tag}] played {label} {len(pcm)/32000:.1f}s ({started}->{ended})")
return {"label": label, "start_ms": started, "end_ms": ended}
async def speak(self, pcm: bytes, label: str) -> dict:
return await self._publish_pcm(pcm, label)
async def wait_kind(self, kinds: tuple[str, ...], timeout: float, after_idx: int = 0) -> tuple[int, dict] | None:
deadline = time.time() + timeout
while time.time() < deadline:
await asyncio.sleep(0.05)
for i, s in enumerate(self.subtitles[after_idx:], start=after_idx):
if s.get("kind") in kinds:
return i, s
return None
async def wait_reply(self, timeout: float = 60.0) -> dict:
start_len = len(self.subtitles)
deadline = time.time() + timeout
seen_speech: str | None = None
while time.time() < deadline:
await asyncio.sleep(0.2)
for s in self.subtitles[start_len:]:
if s.get("kind") == "turn_start":
seen_speech = s.get("speech_id")
if s.get("kind") in ("turn_end", "turn_cancel") and (
seen_speech is None or s.get("speech_id") == seen_speech):
return {"kind": s["kind"], "speech_id": s.get("speech_id"),
"reason": s.get("reason")}
return {"kind": "timeout", "speech_id": seen_speech}
async def speak_and_wait(self, pcm: bytes, label: str, timeout: float = 60.0) -> dict:
play = asyncio.create_task(self._publish_pcm(pcm, label))
reply = await self.wait_reply(timeout)
await play
return {"play_label": label, "reply": reply}
async def wait_frames(self, min_seconds: float = 2.0, timeout: float = 40.0) -> int | None:
"""Wait until agent audio frames have been arriving for min_seconds."""
deadline = time.time() + timeout
while time.time() < deadline:
await asyncio.sleep(0.1)
if len(self.frames) >= 2:
cutoff = self.frames[-1][0] - int(min_seconds * 1000)
earliest_in_window = next((t for t, _ in reversed(self.frames) if t < cutoff), None)
if earliest_in_window is not None:
return now_ms()
# fewer than min_seconds of frames recorded at all
if self.frames[-1][0] - self.frames[0][0] >= int(min_seconds * 1000) - 300:
return now_ms()
return None
async def barge_interrupt(self, pcm: bytes) -> dict:
"""她长回复实际有声时,用预录响亮短句回放打断(真实 WebRTC 发布)。
T0 = 打断音频首帧发布;T1 = 旧语音最后一帧到达(≥1s 帧间隙分界)。
声源为预录 WAV 回放(工程输入),非真实用户麦克风。
"""
base_subs = len(self.subtitles)
ready = await self.wait_frames(min_seconds=3.0, timeout=45.0)
if ready is None:
return {"outcome": "no-audible-old-voice"}
barge = asyncio.create_task(self.speak(pcm, "barge-xiaoyun"))
# 打断首帧真正发布时刻由 speak 返回;此处先记发起
cancel_ms = None
deadline = time.time() + 25
while time.time() < deadline:
await asyncio.sleep(0.05)
for s in self.subtitles[base_subs:]:
if s.get("kind") == "turn_cancel":
cancel_ms = s["_at_ms"]
break
if cancel_ms:
break
await asyncio.sleep(14.0) # 观察旧声停止 + 新回复起播
await barge
timeline = [t for (t, _) in self.frames]
last_old = None
for i, t in enumerate(timeline):
if i + 1 < len(timeline) and timeline[i + 1] - t >= 1000:
last_old = t
break
if last_old is None and timeline:
last_old = timeline[-1]
return {
"outcome": "interrupted" if cancel_ms else "no-cancel",
"old_audio_last_frame_ms": last_old,
"cancel_ms": cancel_ms,
"frames_total": len(self.frames),
"source": "pre-recorded wav playback over real WebRTC (not a human microphone)",
}
async def hangup(self) -> dict:
sid = self.session.get("session_id")
self.source = None
frames_at_hangup = len(self.frames)
t_delete = now_ms()
r = await self.http.delete(f"{API}/api/voice/session/{sid}")
body = {"delete_status": r.status_code, "delete_body": safe_json(r),
"delete_ms": t_delete}
await asyncio.sleep(0.5)
if self.room is not None:
await self.room.disconnect()
await asyncio.sleep(2.0)
body["agent_frames_after_delete"] = len(self.frames) - frames_at_hangup
lk = api.LiveKitAPI(url=LK_INTERNAL, api_key=KEY, api_secret=SECRET)
try:
res = await lk.room.list_rooms(api.ListRoomsRequest(names=[self.session["room"]]))
body["room_removed"] = len(res.rooms) == 0
finally:
await lk.aclose()
log(f"[{self.tag}] hangup: {body}")
return body
def save(self, name: str) -> dict:
sub_path = OUT / f"{name}.subtitles.jsonl"
with sub_path.open("w", encoding="utf-8") as f:
for s in self.subtitles:
f.write(json.dumps(s, ensure_ascii=False) + "\n")
tl_path = OUT / f"{name}.frames.json"
tl_path.write_text(json.dumps(
{"first_pub_ms": self._first_pub_ms,
"frames": self.frames}, ensure_ascii=False))
audio_path = None
if self.agent_audio:
audio_path = OUT / f"{name}.agent.wav"
with wave.open(str(audio_path), "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(self.audio_rate)
w.writeframes(bytes(self.agent_audio))
seqs = [s.get("seq") for s in self.subtitles if isinstance(s.get("seq"), int)]
return {
"tag": self.tag,
"session": self.session,
"session_voice": self.session.get("voice"),
"subtitle_count": len(self.subtitles),
"seq_monotonic": all(b > a for a, b in zip(seqs, seqs[1:])),
"agent_frames": len(self.frames),
"agent_audio_seconds": round(len(self.agent_audio) / 2 / self.audio_rate, 1),
"agent_audio_rate": self.audio_rate,
"agent_joined_ms": self.agent_joined_ms,
"subtitles_file": str(sub_path),
"frames_file": str(tl_path),
"agent_audio_file": str(audio_path) if audio_path else None,
}
def _db_query(sql: str, params: tuple = ()) -> list[dict]:
import sqlite3
conn = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
conn.row_factory = sqlite3.Row
try:
return [dict(r) for r in conn.execute(sql, params)]
finally:
conn.close()
def db_dump() -> dict:
out: dict = {}
try:
out["chat_message"] = _db_query(
"SELECT id, ts, role, turn_id, status, substr(text,1,120) AS text FROM chat_message ORDER BY id")
out["budget_total"] = _db_query("SELECT key, value FROM budget_total")
out["token_usage"] = _db_query("SELECT day, scene, used FROM token_usage")
out["request_usage"] = _db_query("SELECT * FROM request_usage")
except Exception as e:
out["error"] = str(e)
return out
def budget_snapshot() -> dict:
out: dict = {"at_ms": now_ms()}
try:
out["token_usage"] = _db_query("SELECT day, scene, used FROM token_usage")
out["request_usage"] = _db_query("SELECT * FROM request_usage")
out["budget_total"] = _db_query("SELECT key, value FROM budget_total")
except Exception as e:
out["error"] = str(e)
return out
def asr_ledger_summary() -> dict:
p = Path("/opt/cybergril-hel910/asr-usage.jsonl")
if not p.exists():
return {"exists": False}
events = [json.loads(l) for l in p.read_text().splitlines() if l.strip()]
return {"exists": True, "events": len(events), "raw": events[-8:]}
def worker_state() -> dict:
p = Path("/opt/cybergril-hel910/worker/voice_state_cybergril.json")
if not p.exists():
return {"exists": False}
try:
return {"exists": True, "content": json.loads(p.read_text())}
except Exception as e:
return {"exists": True, "error": str(e)}
def save_json(name: str, payload: dict) -> None:
path = OUT / f"{name}.json"
path.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
log(f"saved {path}")
async def phase_dry() -> None:
"""建房即删:核验建房/派发/删除链路与房间清空;不发音频、无 LLM/TTS。"""
rooms_before = await list_rooms()
call = Call("dry")
await call.open()
await asyncio.sleep(10) # 给 worker 派发入房
rooms_mid = await list_rooms()
hangup = await call.hangup()
await asyncio.sleep(2)
rooms_after = await list_rooms()
save_json("dry", {"rooms_before": rooms_before, "rooms_mid": rooms_mid,
"hangup": hangup, "rooms_after": rooms_after,
"budget_after": budget_snapshot(),
"asr_ledger_after": asr_ledger_summary()})
async def phase_call2() -> None:
"""第二通:稍长问题(bajie)首文/首声时延 + 回放打断(xiaoyun)停声同钟量测。"""
call = Call("call2")
await call.open()
sess_voice = call.session.get("voice")
await call.connect()
marks: dict[str, int | None] = {}
base = len(call.subtitles)
await call.speak(load_wav_16k_mono(TRIM / "u_bajie.trim.wav"), "q-bajie")
# 输入结束 = 回放发完
marks["playback_end_ms"] = now_ms()
# user_final
got = await call.wait_kind(("user_final",), timeout=25)
marks["user_final_ms"] = got[1]["_at_ms"] if got else None
# 她的回复:turn_start(buffer_turn 下 interim 不先于全文)
got = await call.wait_kind(("turn_start",), timeout=60, after_idx=base)
marks["turn_start_ms"] = got[1]["_at_ms"] if got else None
got = await call.wait_kind(("assistant_final", "turn_cancel", "error"), timeout=90, after_idx=base)
marks["assistant_final_ms"] = got[1]["_at_ms"] if got else None
marks["assistant_final_kind"] = got[1].get("kind") if got else None
reply_text = (got[1].get("text") if got else "") or ""
# 首帧音频(回放发完之后到达的第一帧她的音频)
after = [t for (t, _) in call.frames if t > marks["playback_end_ms"]]
marks["first_agent_frame_ms"] = after[0] if after else None
# 等她实际有声再打断(不等 turn_end:那时音频已播完)
barge = await call.barge_interrupt(load_wav_16k_mono(TRIM / "u_xiaoyun.trim.wav"))
# 打断后的新回复
new = await call.wait_kind(("user_final",), timeout=20)
barge["new_user_final_ms"] = new[1]["_at_ms"] if new else None
new_reply = await call.wait_kind(("turn_end", "turn_cancel"), timeout=90)
barge["new_reply_end"] = {"kind": new_reply[1].get("kind"), "at_ms": new_reply[1]["_at_ms"]} if new_reply else None
# 时机A:她仍在生成时发文字(turn_start=生成开始;文字 POST 取消服务端活动轮)。
# 口径如实:本步文字走 API 直发(python 客户端),不是网页输入框;网页入口的
# 两种时机已在第一通完成(T1 在播时、T2 在 final→待播间隙)。
base2 = len(call.subtitles)
await call.speak(load_wav_16k_mono(TRIM / "u_bajie.trim.wav"), "q2-bajie")
got = await call.wait_kind(("turn_start",), timeout=40, after_idx=base2)
marks["q2_turn_start_ms"] = got[1]["_at_ms"] if got else None
a_out: dict = {"fired": False}
if got:
h = (await call.http.get(f"{API}/api/health")).json()
a_text = "先别把这句长回答生成完,我打字打断你:只用一句话告诉我你现在待在哪个角落。"
t_post = now_ms()
r = await call.http.post(f"{API}/api/chat", json={
"text": a_text, "turn_id": str(__import__("uuid").uuid4()), "epoch": h["epoch"]},
timeout=90)
a_out = {"fired": True, "post_ms": t_post, "status": r.status_code,
"body_head": r.text[:200]}
marks["A_post_ms"] = t_post
# 预期:语音轮 turn_cancel(生成被取消,零泄漏零复活),文字轮获完整回复
got2 = await call.wait_kind(("turn_cancel",), timeout=30, after_idx=base2)
a_out["voice_turn_cancel_ms"] = got2[1]["_at_ms"] if got2 else None
a_out["voice_turn_cancel_reason"] = got2[1].get("reason") if got2 else None
# 她此后不得再为 Q2 发声(观察窗口)
quiet_from = now_ms()
await asyncio.sleep(8.0)
a_out["q2_frames_after_cancel"] = sum(1 for (t, _) in call.frames if t >= quiet_from)
timing_a = a_out
await asyncio.sleep(3.0)
hangup = await call.hangup()
save_json("call2", {"session_voice": sess_voice, "marks": marks,
"reply_text_head": reply_text[:200],
"barge": barge, "timing_a": timing_a,
"hangup": hangup, "call": call.save("call2"),
"budget_after": budget_snapshot(),
"worker_state_after": worker_state(),
"db_dump": db_dump(),
"asr_ledger_after": asr_ledger_summary()})
async def phase_status() -> None:
rooms = await list_rooms()
save_json("status", {"rooms": rooms, "budget": budget_snapshot(),
"worker_state": worker_state(),
"asr_ledger": asr_ledger_summary(), "db": db_dump()})
async def main() -> None:
phase = sys.argv[1]
fn = {"dry": phase_dry, "call2": phase_call2, "status": phase_status}[phase]
await fn()
if __name__ == "__main__":
asyncio.run(main())