Download eval/ws_client.py from RightNowAI/duplex-v0: direct link, hf CLI and curl.
- Browser
- Download file 5.28 kB
-
https://huggingface.co/RightNowAI/duplex-v0/resolve/main/eval/ws_client.py
- Command line
-
hf download hf://RightNowAI/duplex-v0/eval/ws_client.py
-
curl -L -o ws_client.py https://huggingface.co/RightNowAI/duplex-v0/resolve/main/eval/ws_client.py
5.28 kB
| """A caller for the duplex endpoint, shared by the load test and the evaluations. | |
| Audio is sent the way a live microphone would send it: the frame holding samples | |
| [i*80 ms, (i+1)*80 ms) leaves at (i+1)*80 ms. "The caller finished" is therefore | |
| t_start + len(audio)/16000, and every latency below is measured from that instant | |
| on the client's own clock. | |
| """ | |
| import asyncio | |
| import json | |
| import time | |
| import aiohttp | |
| import numpy as np | |
| from duplex.spec import FRAME, SR, read_wav | |
| FRAME_S = FRAME / SR | |
| def load_16k(path): | |
| x, sr = read_wav(path) | |
| x = x.mean(axis=1) | |
| if sr != SR: | |
| from scipy.signal import resample_poly | |
| x = resample_poly(x, SR, sr) | |
| return (np.clip(x, -1, 1) * 32767).astype(np.int16) | |
| async def open_session(http, url, system_prompt, endpointing): | |
| ws = await http.ws_connect(url, max_msg_size=1 << 20) | |
| await ws.send_str(json.dumps({"type": "session.start", "system_prompt": system_prompt, "endpointing": endpointing})) | |
| msg = json.loads((await ws.receive()).data) | |
| if msg.get("type") != "session.started": | |
| raise RuntimeError(f"session did not start: {msg}") | |
| return ws | |
| async def run_turn(ws, pcm, commit=False, until="first_done", max_wait_s=60.0): | |
| """Speak `pcm` (int16, 16 kHz) to the server in real time, then stay silent until the reply is over. | |
| commit=True sends input.commit right after the last frame (manual endpointing). | |
| until="first_done": return at the first reply.done. | |
| until="done_after_audio": return at the first reply that ran to its end after the caller | |
| finished (earlier replies that were cut off are kept in res["replies"]). | |
| """ | |
| n = -(-len(pcm) // FRAME) | |
| frames = np.concatenate([pcm, np.zeros(n * FRAME - len(pcm), np.int16)]).astype("<i2").reshape(n, FRAME) | |
| silence = np.zeros(FRAME, "<i2").tobytes() | |
| res = {"audio": bytearray(), "text": "", "events": [], "replies": [], "t_first_audio": None, "t_reply_start": None, | |
| "max_gap_ms": 0.0, "error": None, "audio_ms_before_caller_end": 0} | |
| t_start = time.perf_counter() | |
| t_end = t_start + len(pcm) / SR | |
| res["t_caller_end"] = t_end | |
| finished = asyncio.Event() | |
| async def receive(): | |
| last = None | |
| async for msg in ws: | |
| now = time.perf_counter() | |
| if msg.type == aiohttp.WSMsgType.BINARY: | |
| if last is not None: | |
| res["max_gap_ms"] = max(res["max_gap_ms"], (now - last) * 1000) | |
| last = now | |
| res["t_first_audio"] = res["t_first_audio"] or now | |
| if now < t_end: | |
| res["audio_ms_before_caller_end"] += 80 # the caller hears the model while still speaking | |
| res["audio"] += msg.data | |
| elif msg.type == aiohttp.WSMsgType.TEXT: | |
| ev = json.loads(msg.data) | |
| ev["t_client"] = now - t_start | |
| res["events"].append(ev) | |
| if ev["type"] == "reply.start": # a new reply: timings, text and audio are per reply | |
| res["t_reply_start"] = res["t_reply_start"] or now | |
| res["text"], res["audio"], res["t_first_audio"], last = "", bytearray(), None, None | |
| elif ev["type"] == "transcript.delta": | |
| res["text"] += ev["text"] | |
| elif ev["type"] == "error": | |
| res["error"] = ev.get("message") | |
| elif ev["type"] == "reply.done": | |
| res["replies"].append(ev) | |
| if until == "first_done" or (ev["reason"] == "done" and now >= t_end): | |
| break | |
| else: | |
| res["error"] = res["error"] or f"socket closed: {msg.type}" | |
| break | |
| finished.set() | |
| task = asyncio.create_task(receive()) | |
| i = 0 | |
| while not finished.is_set(): | |
| due = t_start + (i + 1) * FRAME_S | |
| if due > t_end + max_wait_s: | |
| res["error"] = res["error"] or "timeout: no finished reply" | |
| break | |
| await asyncio.sleep(max(0.0, due - time.perf_counter())) | |
| try: | |
| await ws.send_bytes(frames[i].tobytes() if i < n else silence) | |
| if i == n - 1 and commit: | |
| res["t_commit"] = time.perf_counter() | |
| await ws.send_str(json.dumps({"type": "input.commit"})) | |
| except (ConnectionError, RuntimeError) as e: | |
| res["error"] = res["error"] or f"send failed: {e!r}" | |
| break | |
| i += 1 | |
| task.cancel() | |
| done = res["replies"][-1] if res["replies"] else None | |
| res["done"] = done | |
| # caller finished -> first audio of the last reply (negative when that reply began before the caller finished) | |
| res["latency_ms"] = (res["t_first_audio"] - t_end) * 1000 if res["t_first_audio"] else None | |
| res["started_early"] = bool(res["t_reply_start"] and res["t_reply_start"] < t_end) # any reply began while the caller spoke | |
| res["audio"] = bytes(res["audio"]) | |
| return res | |
| def percentiles(values): | |
| v = [x for x in values if x is not None] | |
| if not v: | |
| return {"n": 0} | |
| return {"n": len(v), "min": float(np.min(v)), "p50": float(np.percentile(v, 50)), "p90": float(np.percentile(v, 90)), | |
| "p95": float(np.percentile(v, 95)), "max": float(np.max(v))} | |