"""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("= 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))}