Open full-duplex voice models that hear your tone and speak with one. One GPU with vLLM-Omni, or fully offline on a Mac with MLX. Zero-shot voice cloning, OpenAI Realtime / GPT-Live compatible, free hosted API trial. Apache-2.0.
Python apple-siliconfull-duplexlivekitmacosmlxofflineopen-sourceopenai-realtimeparalinguisticspipecatrealtimespeechspeech-to-speechttsvllmvllm-omnivoice-assistantvoice-cloningzero-shot
feat: add HTTP streaming audio benchmark for Flash (#8)
GitWJWdce1e9149fa8
diff --git a/flash/README.md b/flash/README.mdindex 8116245..c0e4cd5 100644--- a/flash/README.md+++ b/flash/README.md@@ -120,3 +120,8 @@ License: code Apache-2.0; model weights Apache-2.0, see `NOTICE` for sources.See the [910C HTTP deployment notes](../community/ascend/README.md) for thecommunity-maintained BF16 TP2 recipe, tested environment, validation results,and limitations. The core maintainers do not have Ascend hardware to test it.++## HTTP audio benchmarking++See [benchmark usage and metric definitions](docs/benchmark_http.md) for single-input,+manifest-based, concurrent and staggered-arrival workloads. This is not a duplex benchmark.diff --git a/flash/benchmark_http.py b/flash/benchmark_http.pynew file mode 100644index 0000000..2d82ee5--- /dev/null+++ b/flash/benchmark_http.py@@ -0,0 +1,270 @@+"""Benchmark Flash HTTP streaming audio; not a Live/Realtime benchmark."""+import argparse+import asyncio+import base64+import hashlib+import io+import json+import math+import random+import time+from pathlib import Path++import aiohttp+import numpy as np+import soundfile as sf+++async def sse_events(stream, max_event_bytes=16 * 1024 * 1024):+ """Parse LF/CRLF SSE incrementally without StreamReader's line limit.++ Limit raw event bytes (including comments/fields) and incomplete lines.+ UTF-8 is decoded only after a complete line, so transport splits are safe.+ """+ if max_event_bytes < 1:+ raise ValueError('max_event_bytes must be positive')+ pending = bytearray()+ data = []+ event_bytes = 0+ async for chunk in stream.iter_chunked(16 * 1024):+ pending.extend(chunk)+ while True:+ boundary = pending.find(b'\n')+ if boundary < 0:+ if event_bytes + len(pending) > max_event_bytes:+ raise ValueError('SSE event exceeds max_event_bytes')+ break+ size = boundary + 1+ if event_bytes + size > max_event_bytes:+ raise ValueError('SSE event exceeds max_event_bytes')+ raw = bytes(pending[:boundary])+ del pending[:size]+ line = raw.removesuffix(b'\r').decode('utf-8')+ event_bytes += size+ if not line:+ if data:+ yield '\n'.join(data)+ data = []+ event_bytes = 0+ elif line.startswith('data:'):+ value = line[5:]+ data.append(value[1:] if value.startswith(' ') else value)+ # Unclosed events are intentionally not dispatched.+++def playback_stall(chunks, initial_buffer=0.):+ if not chunks:+ return 0.+ end = chunks[0]['arrival_s'] + initial_buffer+ stall = 0.+ for c in chunks:+ stall += max(0., c['arrival_s'] - end)+ end = max(end, c['arrival_s']) + c['audio_s']+ return stall+++def load_inputs(wav, manifest, language, prompts):+ if manifest:+ path = Path(manifest).resolve()+ items = json.loads(path.read_text(encoding='utf-8'))+ root = path.parent+ else:+ items = [{'id': 'single', 'wav': wav, 'language': language}]+ root = Path.cwd()+ if not isinstance(items, list) or not items:+ raise ValueError('manifest must be a nonempty list')+ prepared = []+ ids = set()+ for item in items:+ ident = item['id']+ if not isinstance(ident, str) or not ident or ident in ids:+ raise ValueError('input IDs must be unique nonempty strings')+ ids.add(ident)+ lang = item.get('language', language)+ if lang not in prompts:+ raise ValueError(f'missing system prompt for {lang}')+ p = root / item['wav']+ raw = p.read_bytes()+ audio, rate = sf.read(io.BytesIO(raw), dtype='float32', always_2d=True)+ if not len(audio) or not np.isfinite(audio).all():+ raise ValueError(f'invalid input: {ident}')+ # Request declares WAV; reject mislabeled input before timed requests.+ with sf.SoundFile(io.BytesIO(raw)) as f:+ if f.format not in ('WAV', 'WAVEX', 'RF64'):+ raise ValueError(f'input must be WAV: {ident}')+ prepared.append(dict(id=ident, language=lang, sha256=hashlib.sha256(raw).hexdigest(),+ duration_s=len(audio)/rate, data=base64.b64encode(raw).decode()))+ return prepared+++async def request(session, url, body, ident, initial_buffer=0., threshold=.02, max_event_bytes=16 * 1024 * 1024):+ start = time.perf_counter()+ row = dict(request_id=ident, success=False, error_type=None, error_message=None,+ first_audio_received_s=None, first_audio_decoded_s=None,+ first_audible_s=None, audio_duration_s=0., audio_chunk_count=0,+ chunk_trace=[])+ try:+ async with session.post(url + '/v1/chat/completions', json=body) as response:+ response.raise_for_status()+ if 'text/event-stream' not in response.headers.get('Content-Type', ''):+ raise ValueError('expected text/event-stream response')+ done = False+ async for data in sse_events(response.content, max_event_bytes):+ received = time.perf_counter() - start+ if data.strip() == '[DONE]':+ done = True+ break+ event = json.loads(data)+ if 'error' in event:+ raise RuntimeError(str(event['error']))+ if event.get('modality') != 'audio':+ continue+ for choice in event.get('choices', []):+ value = (choice.get('delta') or {}).get('content')+ if not value:+ continue+ pcm, rate = sf.read(io.BytesIO(base64.b64decode(value, validate=True)),+ dtype='float32', always_2d=True)+ if not len(pcm) or not np.isfinite(pcm).all():+ raise ValueError('invalid output audio')+ decoded = time.perf_counter() - start+ if row['first_audio_received_s'] is None:+ row['first_audio_received_s'] = received+ row['first_audio_decoded_s'] = decoded+ if row['first_audible_s'] is None and np.max(np.abs(pcm)) > threshold:+ row['first_audible_s'] = received+ duration = len(pcm)/rate+ row['chunk_trace'].append(dict(arrival_s=received, decoded_s=decoded, audio_s=duration))+ row['audio_duration_s'] += duration+ row['audio_chunk_count'] += 1+ if not done:+ raise RuntimeError('stream ended without [DONE]')+ if not row['audio_chunk_count']:+ raise RuntimeError('no audio')+ row['success'] = True+ except Exception as e:+ row['error_type'] = type(e).__name__+ row['error_message'] = str(e)+ row['e2e_s'] = time.perf_counter() - start+ row['stall_s'] = playback_stall(row['chunk_trace'], initial_buffer)+ return row+++def summary(rows, wall, peak, settings, model, inputs):+ good = [r for r in rows if r['success']]+ result = dict(schema_version=1, settings=settings, model=model,+ inputs=[{k:v for k,v in x.items() if k != 'data'} for x in inputs],+ success=len(good), total=len(rows), success_rate=len(good)/len(rows),+ wall_s=wall, peak_inflight=peak, requests_per_s=len(good)/wall,+ total_output_audio_s=sum(r['audio_duration_s'] for r in good))+ result['audio_seconds_per_s'] = result['total_output_audio_s']/wall+ result['errors'] = {}+ for r in rows:+ if not r['success']:+ k=r['error_type']; result['errors'][k]=result['errors'].get(k,0)+1+ for field in ('first_audio_received_s','first_audio_decoded_s','first_audible_s','stall_s','e2e_s'):+ values=[r[field] for r in good if r[field] is not None]+ result[field] = dict(zip(('p50','p90','p95'),map(float,np.percentile(values,[50,90,95])))) if values else None+ return result+++async def run(a):+ prompts=json.loads(Path(a.system_prompt).read_text(encoding='utf-8'))+ inputs=load_inputs(a.wav, a.manifest, a.language, prompts)+ out=Path(a.out)+ out.mkdir(parents=True, exist_ok=False)+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=a.timeout),+ connector=aiohttp.TCPConnector(limit=0)) as session:+ async with session.get(a.url.rstrip('/')+'/v1/models') as r:+ r.raise_for_status(); models=(await r.json())['data']+ model=a.model+ if not model:+ if len(models)!=1:+ raise ValueError('--model required when server exposes multiple models')+ model=models[0]['id']+ rng=random.Random(a.seed)+ def body(x):+ return dict(model=model, stream=True, modalities=['text','audio'], language=x['language'],+ voice=a.voice, max_tokens=a.max_tokens, temperature=.7, top_p=.9,+ messages=[dict(role='system',content=prompts[x['language']]),+ dict(role='user',content=[dict(type='text',text='<|audio|>'),+ dict(type='input_audio',input_audio=dict(format='wav',data=x['data']))])])+ bodies=[body(x) for x in inputs]+ for i in range(a.warmup):+ r=await request(+ session, a.url.rstrip('/'), bodies[i % len(inputs)], f'warmup-{i}',+ initial_buffer=a.initial_buffer, threshold=a.audible_threshold,+ max_event_bytes=getattr(a, 'max_event_bytes', 16 * 1024 * 1024),+ )+ if not r['success']:+ raise RuntimeError(f'warmup failed: {r["error_message"]}')+ indices=[rng.randrange(len(inputs)) if a.selection=='random' else i%len(inputs) for i in range(a.requests)]+ sem=asyncio.Semaphore(a.concurrency or 1)+ active=peak=0+ begin=time.perf_counter()+ rows=[]+ with (out/'requests.jsonl').open('w',encoding='utf-8') as f:+ async def execute(i):+ nonlocal active,peak+ j=indices[i]; x=inputs[j]+ target=begin+(a.arrival_window*i/max(1,a.requests-1) if a.arrival_window is not None else 0)+ active+=1;peak=max(peak,active)+ actual=time.perf_counter()+ try:+ r=await request(session,a.url.rstrip('/'),bodies[j],str(i),a.initial_buffer,a.audible_threshold,getattr(a, "max_event_bytes", 16 * 1024 * 1024))+ finally:+ active-=1+ r.update(input_id=x['id'],input_sha256=x['sha256'],input_duration_s=x['duration_s'],+ actual_start_s=actual-begin,scheduled_start_s=target-begin if a.arrival_window is not None else None,+ send_lag_s=max(0.,actual-target) if a.arrival_window is not None else None)+ rows.append(r);f.write(json.dumps(r,allow_nan=False)+'\n');f.flush()+ async def launch(i):+ if a.arrival_window is not None:+ target=begin+a.arrival_window*i/max(1,a.requests-1)+ while time.perf_counter() < target:+ await asyncio.sleep(max(0.,target-time.perf_counter()))+ await execute(i)+ else:+ async with sem:+ await execute(i)+ await asyncio.gather(*(launch(i) for i in range(a.requests)))+ result=summary(rows,time.perf_counter()-begin,peak,vars(a),model,inputs)+ (out/'summary.json').write_text(json.dumps(result,indent=2,allow_nan=False)+'\n',encoding='utf-8')+ print(json.dumps(result,indent=2,allow_nan=False))+++def parse_args(argv=None):+ p=argparse.ArgumentParser(description=__doc__)+ g=p.add_mutually_exclusive_group(required=True)+ g.add_argument('--wav');g.add_argument('--manifest')+ p.add_argument('--url',default='http://127.0.0.1:8000')+ p.add_argument('--model');p.add_argument('--language',default='zh')+ p.add_argument('--voice',default='chelsie')+ p.add_argument('--system-prompt',default=str(Path(__file__).parent/'config/system_prompt.json'))+ p.add_argument('--selection',choices=('round-robin','random'),default='round-robin')+ p.add_argument('--seed',type=int,default=0)+ load=p.add_mutually_exclusive_group()+ load.add_argument('--concurrency',type=int);load.add_argument('--arrival-window',type=float)+ p.add_argument('--requests',type=int,default=30);p.add_argument('--warmup',type=int,default=3)+ p.add_argument('--timeout',type=float,default=300)+ p.add_argument('--max-tokens',type=int,default=300)+ p.add_argument('--initial-buffer',type=float,default=0)+ p.add_argument('--audible-threshold',type=float,default=.02)+ p.add_argument('--max-event-bytes',type=int,default=16 * 1024 * 1024)+ p.add_argument('--out',required=True)+ a=p.parse_args(argv)+ for name in ('timeout', 'initial_buffer', 'audible_threshold', 'arrival_window'):+ value = getattr(a, name)+ if value is not None and not math.isfinite(value):+ p.error('--' + name.replace('_', '-') + ' must be finite')+ if a.max_event_bytes < 1:+ p.error('--max-event-bytes must be positive')+ if a.requests<1 or a.warmup<0 or (a.concurrency is not None and a.concurrency<1) or a.timeout<=0 or a.max_tokens<1 or a.initial_buffer<0 or not 0<=a.audible_threshold<=1 or (a.arrival_window is not None and a.arrival_window<0):+ p.error('invalid numeric setting')+ if a.concurrency is None and a.arrival_window is None:+ a.concurrency=1+ return a+++if __name__=='__main__':+ asyncio.run(run(parse_args()))diff --git a/flash/docs/benchmark_http.md b/flash/docs/benchmark_http.mdnew file mode 100644index 0000000..448bbbd--- /dev/null+++ b/flash/docs/benchmark_http.md@@ -0,0 +1,136 @@+# HTTP streaming audio benchmark++Run from `flash/` with `aiohttp`, `numpy`, and `soundfile` installed. This measures+`/v1/chat/completions`, not Live, VAD, duplex turn-taking or barge-in.++```bash+python benchmark_http.py --wav examples/hello_zh.wav --concurrency 1 --requests 30 --warmup 5 --out bench/single+python benchmark_http.py --wav examples/hello_zh.wav --concurrency 4 --requests 80 --out bench/c4+python benchmark_http.py --wav examples/hello_zh.wav --requests 40 --arrival-window 10 --out bench/arrival40+python benchmark_http.py --manifest inputs.json --concurrency 4 --requests 80 --out bench/multi+```++Output directories must not exist. Concurrency and arrival-window options are+mutually exclusive. The latter schedules evenly spaced arrivals without an+in-flight cap. Peak in-flight count includes server queueing.++Manifest paths are relative to the manifest file:++```json+[+ {"id": "short-zh", "wav": "audio/short-zh.wav", "language": "zh"},+ {"id": "short-en", "wav": "audio/short-en.wav", "language": "en"}+]+```++IDs must be unique. Each language needs a system prompt in `--system-prompt`,+which defaults to the repository prompt file. Selection defaults to round-robin;+`--selection random --seed 42` is reproducible. WAV validation, hashing and base64+encoding happen before timing. Do not publish private recordings or credentials.++`requests.jsonl` flushes each completed request. `summary.json` uses successful+measured requests only. Warmups are excluded and abort the run on failure.+Success requires valid audio and a normal `[DONE]` terminator. HTTP errors,+SSE errors, missing audio, invalid WAV/base64, timeout and truncation are failures.+Partial latency is retained for diagnostics, but excluded from success percentiles.++Metrics (seconds unless stated):++- `first_audio_received_s`: application-level dispatch of the first valid audio+ SSE event, timestamped before WAV decoding; not packet arrival time.+- `first_audio_decoded_s`: first audio decode completion. The old script's+ `first_audio_s` represented this kind of measurement; names deliberately differ.+- `first_audible_s`: arrival of the first chunk with peak above+ `--audible-threshold` (default .02 normalized amplitude); chunk-level proxy,+ not exact sample onset.+- `stall_s`: simulated playback underrun from chunk arrivals and durations,+ starting at first arrival plus `--initial-buffer` (default zero).+- `e2e_s`: request start to normal stream completion processing.+- `audio_duration_s`: sum of chunk durations, assuming sequential nonoverlapping+ WAV payloads as in the repository client.+- `requests_per_s`: successful requests / measured wall time.+- `audio_seconds_per_s`: successful output audio seconds / measured wall time.+- `send_lag_s`: dispatch lateness against the open-loop schedule; null otherwise.++Silence inside actual audio counts as content. The simulated player does not+model browser buffering or sound hardware. Client decoding, JSON, network and+event-loop load affect results. A bigger initial buffer trades later playback for+fewer stalls; it does not accelerate inference. The stall algorithm is not claimed+to match the upstream published benchmark. All-failed runs have null percentiles.++Record server revisions/configuration, hardware, precision, answer durations and+cache state. Reused inputs may benefit from caching. Compare audio throughput,+not just request throughput, when answer lengths differ. This tool implements+the repository's base64 WAV SSE shape, not arbitrary provider audio protocols.+Result schema version is 1; old collectors must explicitly adapt.++Local tests (run from repository root, no NPU/model required):++```bash+python -m unittest discover -s flash/tests -p test_benchmark_http.py -v+```++Tests cover fragmented/multiline SSE, completion, HTTP/SSE errors, malformed+audio, missing audio, truncation, timeout, manifests, stall arithmetic and+success-only summary aggregation. Load-generation integration tests additionally check bounded in-flight counts,+round-robin assignment, staggered schedule metadata, and all-failed aggregation.++## Recorded server smoke tests++An Ascend-backed Flash HTTP endpoint completed all 45 measured requests:++| Workload | Success | Peak in flight | First audio receipt P50 / P90 (s) | Stall P50 / P90 (s) |+| --- | --- | --- | --- | --- |+| Single input, concurrency 1 | 5/5 | 1 | 0.623 / 0.651 | 0.744 / 0.998 |+| Three inputs, concurrency 4 | 20/20 | 4 | 0.996 / 1.137 | 0.710 / 1.071 |+| Three inputs, 20 arrivals over 10 s | 20/20 | 12 | 1.041 / 1.192 | 1.033 / 1.946 |++Both multi-input runs assigned inputs 7/7/6 times. Maximum observed scheduled+arrival lag was about 1.8 ms. The compact [validation record](benchmark_http_validation.json)+was checked against per-request records for success counts and audio throughput.+These validate the client against a real endpoint, not a controlled hardware+comparison or a serving-capacity guarantee. The supplied client results do not+capture the complete server revision/configuration; reproduce with recorded server+metadata before comparing hardware. Raw recordings and full server logs are not+included in this PR.++## Final server regression++After adding the scheduled-arrival deadline recheck, the tester reported that+all eight mock and integration tests passed on the server.++A further three-input run with 20 staggered requests over 10 seconds completed+successfully (20/20). This exercises the updated scheduling code against the+real endpoint.++The earlier 45-request smoke results and this final 20-request regression are+separate runs. Their latency percentiles are not combined. The final regression+status is based on tester confirmation; raw final-run results are not included+in this validation record, and no additional latency figures are claimed.++## Parser limits and numeric validation++SSE is parsed from transport chunks with LF or CRLF line endings, without relying+on aiohttp's line-length limit. UTF-8 characters may span transport chunks.+`--max-event-bytes` limits each raw event, including fields, comments and incomplete+lines; the default is 16777216 bytes (16 MiB). Oversized events are explicit request+failures. Increase the limit deliberately for larger expected audio payloads;+this limit does not bound all decoded waveform allocations.++All floating-point CLI parameters must be finite. NaN and positive/negative+infinity are rejected before input loading or networking. Numeric range checks+still apply. Local regression coverage now includes large valid WAV events,+oversized events, unterminated oversized lines, split UTF-8, and CLI validation.+The previous eight-test server results predate these parser changes. The tester+subsequently confirmed that all twelve updated tests passed on the server,+along with real-endpoint regressions of 5/5 single-input requests and 20/20+staggered multi-input requests. These final outcomes are based on tester+confirmation; no new latency figures or pooled percentiles are claimed.++## Warmup option consistency++Warmup requests use the same event-size limit, playback-buffer setting and audible+threshold as measured requests. The local suite now has thirteen passing tests,+including a non-default event limit that rejects warmup before measurement, then+allows warmup and measurement when increased. Warmups remain excluded from totals.+The previously recorded twelve-test server result predates this change; the tester subsequently confirmed thirteen passing server tests and 5/5 measured endpoint requests with three warmups and a 32 MiB event limit.diff --git a/flash/docs/benchmark_http_validation.json b/flash/docs/benchmark_http_validation.jsonnew file mode 100644index 0000000..90c3d63--- /dev/null+++ b/flash/docs/benchmark_http_validation.json@@ -0,0 +1,112 @@+{+ "scope": "HTTP benchmark client smoke validation; not a hardware comparison",+ "server_configuration_recorded": false,+ "mock_tests_original": {+ "methods": 5,+ "passed": true+ },+ "runs": {+ "multi-arrival20": {+ "success": 20,+ "total": 20,+ "wall_s": 14.85168485995382,+ "peak_inflight": 12,+ "first_audio_received_s": {+ "p50": 1.0410785998683423,+ "p90": 1.191718657920137,+ "p95": 1.2065214652335272+ },+ "first_audio_decoded_s": {+ "p50": 1.0413183050695807,+ "p90": 1.191943194111809,+ "p95": 1.206759960274212+ },+ "stall_s": {+ "p50": 1.0332250100094824,+ "p90": 1.9456776068694892,+ "p95": 2.087868431856856+ },+ "total_output_audio_s": 101.44000000000001,+ "audio_seconds_per_s": 6.830201485995942,+ "requests_per_s": 1.3466485579644993+ },+ "multi-c4": {+ "success": 20,+ "total": 20,+ "wall_s": 26.18463040003553,+ "peak_inflight": 4,+ "first_audio_received_s": {+ "p50": 0.9963975350838155,+ "p90": 1.1370671122334899,+ "p95": 1.17254264135845+ },+ "first_audio_decoded_s": {+ "p50": 0.9966492101084441,+ "p90": 1.1373108999803663,+ "p95": 1.1728074359009042+ },+ "stall_s": {+ "p50": 0.7100594949908554,+ "p90": 1.0711486838944255,+ "p95": 1.0922435357654467+ },+ "total_output_audio_s": 108.48,+ "audio_seconds_per_s": 4.142888341087786,+ "requests_per_s": 0.7638068475456832+ },+ "single-smoke": {+ "success": 5,+ "total": 5,+ "wall_s": 21.59982532961294,+ "peak_inflight": 1,+ "first_audio_received_s": {+ "p50": 0.6227045198902488,+ "p90": 0.6514039877802134,+ "p95": 0.6578980437479913+ },+ "first_audio_decoded_s": {+ "p50": 0.6230862298980355,+ "p90": 0.6517857877537608,+ "p95": 0.6582705837674439+ },+ "stall_s": {+ "p50": 0.7442645799554882,+ "p90": 0.997857088241726,+ "p95": 1.0710863841883835+ },+ "total_output_audio_s": 28.240000000000002,+ "audio_seconds_per_s": 1.3074179799631764,+ "requests_per_s": 0.23148335339291365+ }+ },+ "local_regression": {+ "methods": 8,+ "passed": true,+ "note": "Includes load integration; scheduling deadline recheck added after server smoke runs."+ },+ "final_server_regression": {+ "evidence": "Tester confirmation; raw final-run results not included.",+ "mock_test_methods": 8,+ "mock_tests_passed": true,+ "workload": "three-input, 20 staggered requests over 10 seconds",+ "successful_requests": 20,+ "total_requests": 20,+ "scope": "Updated scheduling code exercised; latency percentiles not pooled with earlier runs."+ },+ "parser_numeric_regression": {+ "local_test_methods": 12,+ "local_tests_passed": true,+ "server_regression": "Tester confirmed all 12 updated tests passed; real-endpoint regression completed 5/5 single-input requests and 20/20 staggered multi-input requests.",+ "changes": [+ "bounded incremental SSE parser",+ "finite floating-point CLI validation"+ ],+ "server_evidence": "Tester confirmation; final parser-fix raw results are not included."+ },+ "warmup_option_regression": {+ "local_test_methods": 13,+ "local_tests_passed": true,+ "server_regression": "Tester confirmed 13 tests passed and 5/5 measured endpoint requests succeeded with 3 warmups and a 32 MiB event limit.",+ "scope": "Non-default event cap applies to warmup; measured totals exclude warmup."+ }+}diff --git a/flash/tests/test_benchmark_http.py b/flash/tests/test_benchmark_http.pynew file mode 100644index 0000000..8b72483--- /dev/null+++ b/flash/tests/test_benchmark_http.py@@ -0,0 +1,227 @@+import asyncio+import argparse+import contextlib+import base64+import importlib.util+import io+import json+from pathlib import Path+import tempfile+import unittest++import aiohttp+from aiohttp import web+import numpy as np+import soundfile as sf++spec=importlib.util.spec_from_file_location('bench',Path(__file__).parents[1]/'benchmark_http.py')+b=importlib.util.module_from_spec(spec);spec.loader.exec_module(b)+++def audio_event(samples=1600):+ out=io.BytesIO();sf.write(out,np.ones(samples,dtype=np.float32)*.1,16000,format='WAV')+ return json.dumps({'modality':'audio','choices':[{'delta':{'content':base64.b64encode(out.getvalue()).decode()}}]})+++class BenchmarkTests(unittest.IsolatedAsyncioTestCase):+ async def asyncSetUp(self):+ self.mode='normal'+ self.active=0+ self.peak=0+ async def handler(req):+ if self.mode=='http': return web.Response(status=503)+ if self.mode=='timeout':+ await asyncio.sleep(.1);return web.Response()+ resp=web.StreamResponse(headers={'Content-Type':'text/event-stream'})+ await resp.prepare(req)+ if self.mode=='error':payload='data: {"error":"test"}\n\n'+ elif self.mode=='bad':payload='data: {"modality":"audio","choices":[{"delta":{"content":"!"}}]}\n\n'+ elif self.mode=='text':payload='data: {"choices":[]}\n\ndata: [DONE]\n\n'+ else:+ event=audio_event(96000 if self.mode == "large" else 1600)+ # Valid multiline JSON data plus fragmented transport writes.+ payload=': comment\n'+'data: '+event[:1]+'\n'+'data: '+event[1:]+'\n\n'+ if self.mode!='truncated':payload+='data: [DONE]\n\n'+ raw=payload.encode()+ try:+ for i in range(0,len(raw),17):+ await resp.write(raw[i:i+17])+ await resp.write_eof()+ except ConnectionResetError:+ if self.mode not in ('large', 'normal'):+ raise+ return resp+ @web.middleware+ async def count_active(req, handler):+ if req.path != '/v1/chat/completions':+ return await handler(req)+ self.active += 1+ self.peak = max(self.peak, self.active)+ try:+ await asyncio.sleep(.02)+ return await handler(req)+ finally:+ self.active -= 1+ async def models(req):+ return web.json_response({'data': [{'id': 'mock-model'}]})+ app=web.Application(middlewares=[count_active])+ app.router.add_post('/v1/chat/completions',handler)+ app.router.add_get('/v1/models',models)+ self.runner=web.AppRunner(app);await self.runner.setup()+ site=web.TCPSite(self.runner,'127.0.0.1',0);await site.start()+ self.url='http://127.0.0.1:'+str(site._server.sockets[0].getsockname()[1])++ async def asyncTearDown(self):await self.runner.cleanup()++ async def test_stream_cases(self):+ async with aiohttp.ClientSession() as session:+ for mode in ('normal','http','error','bad','text','truncated'):+ with self.subTest(mode=mode):+ self.mode=mode+ r=await b.request(session,self.url,{},mode)+ self.assertEqual(r['success'],mode=='normal')+ if mode=='normal':+ self.assertEqual(r['audio_chunk_count'],1)+ self.assertAlmostEqual(r['audio_duration_s'],.1)+ self.assertGreaterEqual(r['first_audio_decoded_s'],r['first_audio_received_s'])+ if mode=='truncated':+ self.assertIsNotNone(r['first_audio_received_s'])++ async def test_large_audio_event(self):+ self.mode='large'+ async with aiohttp.ClientSession() as session:+ r=await b.request(session,self.url,{},'large')+ self.assertTrue(r['success'], r['error_message'])+ self.assertAlmostEqual(r['audio_duration_s'],6.)++ async def test_oversized_audio_event(self):+ self.mode='large'+ async with aiohttp.ClientSession() as session:+ r=await b.request(session,self.url,{},'oversized',max_event_bytes=65536)+ self.assertFalse(r['success'])+ self.assertIn('max_event_bytes',r['error_message'])++ async def test_sse_bounds_and_utf8(self):+ class Stream:+ def __init__(self, raw): self.raw=raw+ async def iter_chunked(self, size):+ for i in range(0,len(self.raw),1):+ yield self.raw[i:i+1]+ raw='data: 浣犲ソ\r\n\r\n'.encode()+ self.assertEqual([x async for x in b.sse_events(Stream(raw))],['浣犲ソ'])+ for raw in (b'data: '+b'x'*100, b':'+b'x'*100+b'\n\n'):+ with self.assertRaisesRegex(ValueError,'max_event_bytes'):+ [x async for x in b.sse_events(Stream(raw),32)]++ def test_nonfinite_cli(self):+ for option in ('--timeout','--initial-buffer','--audible-threshold','--arrival-window'):+ for value in ('nan','inf','-inf'):+ with self.subTest(option=option,value=value):+ with contextlib.redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit) as cm:+ b.parse_args(['--wav','unused.wav','--out','unused',f'{option}={value}'])+ self.assertEqual(cm.exception.code,2)+ for value in ('0','-1'):+ with contextlib.redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit):+ b.parse_args(['--wav','unused.wav','--out','unused','--max-event-bytes',value])++ async def test_timeout(self):+ self.mode='timeout'+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=.01)) as session:+ r=await b.request(session,self.url,{},'timeout')+ self.assertFalse(r['success'])+ self.assertIn('Timeout',r['error_type'])++ async def exercise_load(self, arrival=None):+ with tempfile.TemporaryDirectory() as d:+ root=Path(d)+ sf.write(root/'x.wav',np.ones(1600)*.1,16000)+ items=[dict(id=str(i),wav='x.wav',language='zh') for i in range(3)]+ (root/'inputs.json').write_text(json.dumps(items))+ (root/'prompt.json').write_text(json.dumps({'zh':'test'}))+ a=argparse.Namespace(system_prompt=str(root/'prompt.json'),wav=None,+ manifest=str(root/'inputs.json'),language='zh',out=str(root/'out'),+ timeout=3,url=self.url,model=None,seed=0,voice='chelsie',+ max_tokens=10,warmup=0,requests=6,selection='round-robin',+ concurrency=2 if arrival is None else None,arrival_window=arrival,+ initial_buffer=0,audible_threshold=.02)+ with contextlib.redirect_stdout(io.StringIO()):+ await b.run(a)+ result=json.loads((root/'out/summary.json').read_text())+ rows=[json.loads(x) for x in (root/'out/requests.jsonl').read_text().splitlines()]+ self.assertEqual(result['success'],6)+ self.assertEqual(sorted(r['input_id'] for r in rows),['0','0','1','1','2','2'])+ self.assertEqual(result['total'],len(rows))+ if arrival is None:+ self.assertLessEqual(self.peak,2)+ self.assertLessEqual(result['peak_inflight'],2)+ self.assertTrue(all(r['send_lag_s'] is None for r in rows))+ else:+ for r in rows:+ expected=arrival*int(r['request_id'])/5+ self.assertAlmostEqual(r['scheduled_start_s'],expected,places=5)+ self.assertGreaterEqual(r['actual_start_s']+1e-6,r['scheduled_start_s'])+ self.assertGreaterEqual(r['send_lag_s'],0)++ async def test_warmup_respects_event_limit(self):+ with tempfile.TemporaryDirectory() as d:+ root=Path(d)+ sf.write(root/'x.wav',np.ones(1600)*.1,16000)+ (root/'prompt.json').write_text(json.dumps({'zh':'test'}))+ a=argparse.Namespace(system_prompt=str(root/'prompt.json'),+ wav=str(root/'x.wav'),manifest=None,language='zh',+ out=str(root/'small'),timeout=3,url=self.url,model=None,+ seed=0,voice='chelsie',max_tokens=10,warmup=1,requests=1,+ selection='round-robin',concurrency=1,arrival_window=None,+ initial_buffer=0,audible_threshold=.02,max_event_bytes=64)+ with self.assertRaisesRegex(RuntimeError,'warmup failed.*max_event_bytes'):+ await b.run(a)+ self.assertFalse((root/'small/summary.json').exists())+ a.out=str(root/'large')+ a.max_event_bytes=65536+ with contextlib.redirect_stdout(io.StringIO()):+ await b.run(a)+ result=json.loads((root/'large/summary.json').read_text())+ self.assertEqual(result['success'],1)+ self.assertEqual(result['total'],1) # warmup excluded++ async def test_bounded_load_and_input_selection(self):+ await self.exercise_load()++ async def test_staggered_schedule(self):+ await self.exercise_load(.1)++ def test_all_failed_summary(self):+ r=dict(success=False,error_type='Test',audio_duration_s=0)+ s=b.summary([r],1,1,{},'model',[])+ self.assertEqual(s['success_rate'],0)+ self.assertIsNone(s['first_audio_received_s'])+ self.assertEqual(s['audio_seconds_per_s'],0)++ def test_stall(self):+ chunks=[dict(arrival_s=.5,audio_s=.2),dict(arrival_s=1.,audio_s=.4)]+ self.assertAlmostEqual(b.playback_stall(chunks),.3)+ self.assertAlmostEqual(b.playback_stall(chunks,.3),0.)++ def test_manifest(self):+ with tempfile.TemporaryDirectory() as d:+ root=Path(d)+ sf.write(root/'x.wav',np.zeros(1600),16000)+ items=[dict(id='a',wav='x.wav',language='zh'),dict(id='b',wav='x.wav',language='en')]+ p=root/'inputs.json';p.write_text(json.dumps(items))+ rows=b.load_inputs(None,str(p),'zh',{'zh':'a','en':'b'})+ self.assertEqual([r['id'] for r in rows],['a','b'])+ self.assertAlmostEqual(rows[0]['duration_s'],.1)+ with self.assertRaises(ValueError):b.load_inputs(None,str(p),'zh',{'zh':'a'})++ def test_summary_excludes_failure(self):+ good=dict(success=True,audio_duration_s=2.,first_audio_received_s=.5,first_audio_decoded_s=.6,first_audible_s=.5,stall_s=0.,e2e_s=1.)+ bad=dict(good,success=False,error_type='Test',audio_duration_s=99.,first_audio_received_s=100.)+ s=b.summary([good,bad],2.,1,{},'model',[])+ self.assertEqual(s['success_rate'],.5)+ self.assertEqual(s['audio_seconds_per_s'],1.)+ self.assertEqual(s['first_audio_received_s']['p50'],.5)+++if __name__=='__main__':unittest.main()