aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / test_transcribe.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Tests for POST /allen/api/transcribe (push-to-talk), each guard with a control. |
| 3 | |
| 4 | Starts throwaway gateways on loopback (never the production unit, never the |
| 5 | model: chat is not called). Fixtures are cut from whisper.cpp's samples/jfk.wav |
| 6 | with ffmpeg (a verification tool here). Under strace, the gateway and its |
| 7 | sandboxes must create no file while transcribing. |
| 8 | |
| 9 | Usage: test_transcribe.py --omc P --irwasm P --system-prompt P --whisper-cli P --whisper-model P |
| 10 | --sample jfk.wav [--gw-dir DIR] [--latency-runs N] |
| 11 | """ |
| 12 | |
| 13 | import argparse |
| 14 | import http.client |
| 15 | import json |
| 16 | import os |
| 17 | import re |
| 18 | import shutil |
| 19 | import socket |
| 20 | import statistics |
| 21 | import struct |
| 22 | import subprocess |
| 23 | import sys |
| 24 | import tempfile |
| 25 | import threading |
| 26 | import time |
| 27 | |
| 28 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 29 | results = [] |
| 30 | |
| 31 | |
| 32 | def check(name, ok, detail): |
| 33 | results.append((name, ok)) |
| 34 | print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail), flush=True) |
| 35 | |
| 36 | |
| 37 | def free_port(): |
| 38 | s = socket.socket() |
| 39 | s.bind(("127.0.0.1", 0)) |
| 40 | p = s.getsockname()[1] |
| 41 | s.close() |
| 42 | return p |
| 43 | |
| 44 | |
| 45 | def ff(*args, data=None): |
| 46 | return subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + list(args), |
| 47 | input=data, stdout=subprocess.PIPE, check=True).stdout |
| 48 | |
| 49 | |
| 50 | class Gateway: |
| 51 | def __init__(self, a, *extra, strace=None): |
| 52 | self.port = free_port() |
| 53 | self.tmp = tempfile.mkdtemp(prefix="transcribe-test-") |
| 54 | argv = [sys.executable, "-B", os.path.join(a.gw_dir, "allen_chat.py"), "--listen", "127.0.0.1:%d" % self.port, |
| 55 | "--upstream", "127.0.0.1:9", "--system-prompt", a.system_prompt, "--omc", a.omc, |
| 56 | "--irwasm", a.irwasm, "--trusted-proxy", "127.0.0.1", "--warm-every", "0"] + list(extra) |
| 57 | if strace: |
| 58 | argv = ["strace", "-f", "-qq", "-e", "trace=openat,open,creat,mknodat,linkat,renameat2,memfd_create", |
| 59 | "-o", strace] + argv |
| 60 | self.p = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.tmp) |
| 61 | self.first = self.p.stdout.readline().decode() |
| 62 | |
| 63 | def close(self): |
| 64 | # Under strace the gateway is strace's child: stop it, and strace exits after it. |
| 65 | try: |
| 66 | with open("/proc/%d/task/%d/children" % (self.p.pid, self.p.pid)) as f: |
| 67 | kids = [int(x) for x in f.read().split()] |
| 68 | except OSError: |
| 69 | kids = [] |
| 70 | for k in kids or [self.p.pid]: |
| 71 | os.kill(k, 15) |
| 72 | self.p.wait(20) |
| 73 | shutil.rmtree(self.tmp, ignore_errors=True) |
| 74 | |
| 75 | def presence(self): |
| 76 | c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) |
| 77 | c.request("GET", "/allen/api/presence", headers={"X-Real-IP": "203.0.113.1"}) |
| 78 | r = c.getresponse() |
| 79 | obj = json.loads(r.read()) |
| 80 | c.close() |
| 81 | return obj, r.getheader("Cache-Control") |
| 82 | |
| 83 | def post(self, body, ctype, ip="203.0.113.1", timeout=60, length=None): |
| 84 | c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=timeout) |
| 85 | c.putrequest("POST", "/allen/api/transcribe") |
| 86 | c.putheader("Content-Type", ctype) |
| 87 | c.putheader("X-Real-IP", ip) |
| 88 | c.putheader("Content-Length", str(len(body) if length is None else length)) |
| 89 | c.endheaders() |
| 90 | if length is None: |
| 91 | c.send(body) |
| 92 | r = c.getresponse() |
| 93 | data = r.read() |
| 94 | c.close() |
| 95 | try: |
| 96 | obj = json.loads(data) |
| 97 | except ValueError: |
| 98 | obj = {"raw": data[:200]} |
| 99 | return r.status, obj, r |
| 100 | |
| 101 | |
| 102 | def wav(pcm, rate=16000, ch=1, bits=16, tag=1): |
| 103 | blk = ch * bits // 8 |
| 104 | return (b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVEfmt " + |
| 105 | struct.pack("<IHHIIHH", 16, tag, ch, rate, rate * blk, blk, bits) + b"data" + struct.pack("<I", len(pcm)) + pcm) |
| 106 | |
| 107 | |
| 108 | def main(): |
| 109 | ap = argparse.ArgumentParser() |
| 110 | for k in ("omc", "irwasm", "system-prompt", "whisper-cli", "whisper-model", "sample"): |
| 111 | ap.add_argument("--" + k, required=True) |
| 112 | ap.add_argument("--gw-dir", default=HERE) |
| 113 | ap.add_argument("--threads", default="4") |
| 114 | ap.add_argument("--latency-runs", type=int, default=12) |
| 115 | a = ap.parse_args() |
| 116 | |
| 117 | clip5_wav = ff("-i", a.sample, "-t", "5", "-ar", "16000", "-ac", "1", "-f", "wav", "-") |
| 118 | clip5_webm = ff("-i", "-", "-c:a", "libopus", "-b:a", "32k", "-f", "webm", "-", data=clip5_wav) |
| 119 | clip5_ogg = ff("-i", "-", "-c:a", "libopus", "-b:a", "32k", "-f", "ogg", "-", data=clip5_wav) |
| 120 | clip5_44st = ff("-i", a.sample, "-t", "5", "-ar", "44100", "-ac", "2", "-f", "wav", "-") |
| 121 | long_pcm = ff("-i", a.sample, "-i", a.sample, "-filter_complex", "concat=n=2:v=0:a=1", "-t", "20", |
| 122 | "-ar", "16000", "-ac", "1", "-f", "s16le", "-") |
| 123 | long_webm = ff("-f", "s16le", "-ar", "16000", "-ac", "1", "-i", "-", "-c:a", "libopus", "-b:a", "16k", |
| 124 | "-f", "webm", "-", data=long_pcm) |
| 125 | long_wav8k = ff("-f", "s16le", "-ar", "16000", "-ac", "1", "-i", "-", "-ar", "8000", "-f", "wav", "-", |
| 126 | data=long_pcm) |
| 127 | vorbis = ff("-i", "-", "-c:a", "libvorbis", "-f", "webm", "-", data=clip5_wav) |
| 128 | clip15 = wav(long_pcm[:15 * 32000]) # exactly the limit: allowed |
| 129 | words = re.compile(r"fellow\s+americans", re.I) |
| 130 | |
| 131 | # Spoken name "Aien" (said like Ian): addressed forms map, other Ians stay (pure function). |
| 132 | sys.path.insert(0, a.gw_dir) |
| 133 | import allen_transcribe |
| 134 | for said, want in (("Ian, what is Omega?", "Aien, what is Omega?"), ("Hey Ian, how are you", "Hey Aien, how are you"), |
| 135 | ("Ian can you help me", "Aien can you help me"), ("Thanks, Ian.", "Thanks, Aien."), |
| 136 | ("Ayen, are you there?", "Aien, are you there?"), ("Een, hello", "Aien, hello"), |
| 137 | ("My friend Ian wrote this.", None), ("I asked Ian, and he said no.", None), |
| 138 | ("Brian, hey", None), ("Ianto is a name", None), ("It took an eon.", None)): |
| 139 | got = allen_transcribe.aien(said) |
| 140 | check("name_" + re.sub(r"\W+", "_", said).strip("_").lower(), got == (want or said), "%r -> %r" % (said, got)) |
| 141 | flags = ["--whisper-cli", a.whisper_cli, "--whisper-model", a.whisper_model, "--transcribe-threads", a.threads] |
| 142 | |
| 143 | # Disabled unless configured (control: the configured gateway below answers 200). |
| 144 | g = Gateway(a) |
| 145 | try: |
| 146 | st, obj, _ = g.post(clip5_wav, "audio/wav") |
| 147 | check("off_without_whisper", st == 404, "%s %s" % (st, obj)) |
| 148 | obj, cc = g.presence() |
| 149 | check("presence_transcribe_false", obj.get("transcribe") is False and cc == "no-store", "%s %s" % (obj, cc)) |
| 150 | finally: |
| 151 | g.close() |
| 152 | |
| 153 | # Pins: an unpinned model refuses startup (control: the pinned model starts below). |
| 154 | fake = tempfile.NamedTemporaryFile(suffix=".bin", delete=False) |
| 155 | fake.write(b"\0" * 4096) |
| 156 | fake.close() |
| 157 | p = subprocess.run([sys.executable, os.path.join(a.gw_dir, "allen_chat.py"), "--listen", "127.0.0.1:%d" % free_port(), |
| 158 | "--system-prompt", a.system_prompt, "--omc", a.omc, "--irwasm", a.irwasm, "--warm-every", "0", |
| 159 | "--whisper-cli", a.whisper_cli, "--whisper-model", fake.name], |
| 160 | capture_output=True, timeout=60) |
| 161 | os.unlink(fake.name) |
| 162 | check("unpinned_model_refused", p.returncode != 0 and b"not a pinned whisper model" in p.stderr, |
| 163 | "rc %s %r" % (p.returncode, p.stderr[-120:])) |
| 164 | |
| 165 | trace_dir = tempfile.mkdtemp(prefix="transcribe-strace-") |
| 166 | trace = os.path.join(trace_dir, "trace") |
| 167 | g = Gateway(a, *(flags + ["--chat-burst", "40", "--chat-refill", "1"]), strace=trace) |
| 168 | try: |
| 169 | check("started", "listening" in g.first, g.first.strip()) |
| 170 | obj, cc = g.presence() |
| 171 | check("presence_transcribe_true", obj.get("transcribe") is True and cc == "no-store", "%s %s" % (obj, cc)) |
| 172 | for name, body, ctype in (("webm_opus", clip5_webm, "audio/webm;codecs=opus"), |
| 173 | ("ogg_opus", clip5_ogg, "audio/ogg; codecs=opus"), |
| 174 | ("wav_16k_mono", clip5_wav, "audio/wav"), |
| 175 | ("wav_44k_stereo", clip5_44st, "audio/wave")): |
| 176 | st, obj, _ = g.post(body, ctype, ip="198.51.100.%d" % len(name)) |
| 177 | check("ok_" + name, st == 200 and bool(words.search(obj.get("text", ""))) and obj.get("seconds") == 5.0, |
| 178 | "%s %s" % (st, obj)) |
| 179 | # Over-length audio is refused, never truncated (control: the 5 s clips above pass). |
| 180 | st, obj, _ = g.post(long_webm, "audio/webm", ip="198.51.100.20") |
| 181 | check("too_long_webm_20s", st == 413 and obj.get("error") == "too_long", "%d bytes -> %s %s" % (len(long_webm), st, obj)) |
| 182 | st, obj, _ = g.post(long_wav8k, "audio/wav", ip="198.51.100.21") |
| 183 | check("too_long_wav_20s", st == 413 and obj.get("error") == "too_long", "%d bytes -> %s %s" % (len(long_wav8k), st, obj)) |
| 184 | # Oversize body: refused from Content-Length before any byte is read; connection closed. |
| 185 | st, obj, r = g.post(b"", "audio/webm", ip="198.51.100.22", length=(1 << 20) + 1) |
| 186 | check("oversize_body", st == 413 and r.getheader("Connection") == "close", "%s %s" % (st, obj)) |
| 187 | st, obj, _ = g.post(b"", "audio/webm", ip="198.51.100.23") |
| 188 | check("empty_body", st == 400, "%s %s" % (st, obj)) |
| 189 | # Bad formats. |
| 190 | st, obj, _ = g.post(clip5_wav, "text/plain", ip="198.51.100.24") |
| 191 | check("bad_content_type", st == 415 and obj.get("error") == "format", "%s %s" % (st, obj)) |
| 192 | st, obj, _ = g.post(clip5_wav, "audio/webm", ip="198.51.100.25") |
| 193 | check("mislabelled_wav_as_webm", st == 415, "%s %s" % (st, obj)) |
| 194 | st, obj, _ = g.post(b"\x1a\x45\xdf\xa3" + os.urandom(4000), "audio/webm", ip="198.51.100.26") |
| 195 | check("garbage_webm", st == 422 and obj.get("error") == "audio", "%s %s" % (st, obj)) |
| 196 | st, obj, _ = g.post(vorbis, "audio/webm", ip="198.51.100.27") |
| 197 | check("vorbis_not_opus", st == 422, "%s %s" % (st, obj)) |
| 198 | st, obj, _ = g.post(wav(b"\x80" * 16000, bits=8), "audio/wav", ip="198.51.100.28") |
| 199 | check("wav_8bit", st == 422 and "16-bit" in obj.get("message", ""), "%s %s" % (st, obj)) |
| 200 | st, obj, _ = g.post(wav(b"\0" * 3200)[:40], "audio/wav", ip="198.51.100.29") |
| 201 | check("wav_truncated_header", st == 422, "%s %s" % (st, obj)) |
| 202 | st, obj, _ = g.post(wav(b"\0" * 3200), "audio/wav", ip="198.51.100.30") |
| 203 | check("too_short_0_1s", st == 422 and "short" in obj.get("message", ""), "%s %s" % (st, obj)) |
| 204 | # Busy: one transcription at a time; a second concurrent clip gets 503 (control: both alone pass). |
| 205 | out = [] |
| 206 | ts = [threading.Thread(target=lambda i=i: out.append(g.post(clip15, "audio/wav", ip="192.0.2.%d" % i)[0])) |
| 207 | for i in range(3)] |
| 208 | for t in ts: |
| 209 | t.start() |
| 210 | for t in ts: |
| 211 | t.join() |
| 212 | check("cap_busy_503", sorted(out)[0] == 200 and 503 in out, "statuses %s" % sorted(out)) |
| 213 | finally: |
| 214 | g.close() |
| 215 | # No audio file: every file the gateway and its sandboxes created or opened for writing. |
| 216 | # Allowed: /dev/null, the bwrap user-namespace maps (procfs), and the bind-mount targets bwrap |
| 217 | # creates on the sandbox's own fresh tmpfs root (/newroot/..., private mount namespace, gone |
| 218 | # at exit). Control: the trace must show whisper-cli opening /model inside the sandbox. |
| 219 | lines = open(trace).read().splitlines() |
| 220 | writes = [ln for ln in lines if re.search(r"O_WRONLY|O_RDWR|O_CREAT|creat\(|mknodat|linkat|renameat2|memfd_create", ln) |
| 221 | and "= -1" not in ln] |
| 222 | writes_bad = [ln for ln in writes if not re.search(r'"/dev/(null|tty)"|"(uid_map|gid_map|setgroups)"|"/newroot/', ln)] |
| 223 | followed = sum(1 for ln in lines if '"/model"' in ln and "= -1" not in ln) |
| 224 | check("no_file_written", followed > 0 and not writes_bad, "%d sandboxed /model opens traced, %d write-opens, unexpected: %s" |
| 225 | % (followed, len(writes), [w.strip()[:160] for w in writes_bad[:5]])) |
| 226 | shutil.rmtree(trace_dir) |
| 227 | |
| 228 | # Rate limit: the chat route's bucket (burst 2 here); another address passes (control). |
| 229 | g = Gateway(a, *(flags + ["--chat-burst", "2", "--chat-refill", "600"])) |
| 230 | try: |
| 231 | sts = [g.post(clip5_webm, "audio/webm", ip="203.0.113.9")[0] for _ in range(2)] |
| 232 | st, obj, r = g.post(clip5_webm, "audio/webm", ip="203.0.113.9") |
| 233 | check("rate_limited", sts == [200, 200] and st == 429 and r.getheader("Retry-After") is not None, |
| 234 | "%s then %s %s" % (sts, st, obj)) |
| 235 | st2, _, _ = g.post(clip5_webm, "audio/webm", ip="203.0.113.10") |
| 236 | check("rate_other_address", st2 == 200, str(st2)) |
| 237 | finally: |
| 238 | g.close() |
| 239 | |
| 240 | # Latency through the gateway (HTTP on loopback, webm/opus 5 s), sequential runs. |
| 241 | g = Gateway(a, *(flags + ["--chat-burst", "1000", "--chat-refill", "0.01"])) |
| 242 | try: |
| 243 | ms, server_ms = [], [] |
| 244 | for i in range(a.latency_runs): |
| 245 | t0 = time.monotonic() |
| 246 | st, obj, _ = g.post(clip5_webm, "audio/webm", ip="203.0.113.50") |
| 247 | ms.append((time.monotonic() - t0) * 1000) |
| 248 | server_ms.append(obj.get("ms", -1)) |
| 249 | q = statistics.quantiles(ms, n=20, method="inclusive") |
| 250 | print("LATENCY model=%s threads=%s n=%d p50=%.0f p95=%.0f min=%.0f max=%.0f (gateway-measured p50=%.0f)" % ( |
| 251 | os.path.basename(a.whisper_model), a.threads, len(ms), statistics.median(ms), q[18], min(ms), max(ms), |
| 252 | statistics.median(server_ms)), flush=True) |
| 253 | finally: |
| 254 | g.close() |
| 255 | |
| 256 | bad = [n for n, ok in results if not ok] |
| 257 | print("%d/%d passed%s" % (len(results) - len(bad), len(results), (": failed " + ", ".join(bad)) if bad else "")) |
| 258 | sys.exit(1 if bad else 0) |
| 259 | |
| 260 | |
| 261 | if __name__ == "__main__": |
| 262 | main() |