File size: 5,281 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""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))}