feat(voice): implement local S2S retained history and provider selection
Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling. Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
"""Bounded three-stage component test; no engine startup or automatic retry.
|
||||
|
||||
Run from the repo root. Credential lives only in ignored local storage. A fresh
|
||||
exclusive ledger prevents accidentally re-running the paid sequence. --check
|
||||
validates the captured prices and budget without reading the credential.
|
||||
"""
|
||||
import argparse
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
|
||||
if not __debug__:
|
||||
raise RuntimeError('Budget checks require Python assertions enabled')
|
||||
ROOT = Path('.local-s2s-build')
|
||||
LEDGER = ROOT / 'live-components-one-dollar-ledger.json'
|
||||
API = 'https://openrouter.ai/api/v1/'
|
||||
RESERVES = {'tts': Decimal('.25'), 'stt': Decimal('.05'), 'llm': Decimal('.01')}
|
||||
TEXT = 'سلام، این یک آزمایش کوتاه برای بررسی صدای فارسی است.'
|
||||
|
||||
|
||||
def validate_budget():
|
||||
assert sum(RESERVES.values()) <= Decimal('1')
|
||||
tts = json.loads((ROOT / 'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
|
||||
assert 0 < len(tts) <= 2
|
||||
full = Decimal('0')
|
||||
for endpoint in tts:
|
||||
assert endpoint['max_completion_tokens'] == 16384 and endpoint['max_prompt_tokens'] == 8192
|
||||
p = endpoint['pricing']
|
||||
assert Decimal(p['prompt']) <= Decimal('.0000005')
|
||||
assert Decimal(p['completion']) <= Decimal('.000006')
|
||||
assert Decimal(str(p.get('request', 0))) == 0
|
||||
full += Decimal(p['prompt']) * 8192 + Decimal(p['completion']) * 16384
|
||||
# Reserve even a full model-size result at each currently listed TTS endpoint.
|
||||
assert full < RESERVES['tts']
|
||||
stt = json.loads((ROOT / 'endpoints-openai-whisper-large-v3.json').read_text())['data']['endpoints']
|
||||
assert 0 < len(stt) <= 3
|
||||
assert all(Decimal(e['pricing']['prompt']) <= Decimal('.000031') for e in stt)
|
||||
# Up to ten seconds of audio; reserve far above a full minute on every route.
|
||||
assert sum(Decimal(e['pricing']['prompt']) * 60 for e in stt) < RESERVES['stt']
|
||||
assert Decimal('.000001') * 8192 + Decimal('.000002') * 128 < RESERVES['llm']
|
||||
return {'budget_usd': '1', 'total_reserved_usd': str(sum(RESERVES.values())),
|
||||
'tts_full_endpoint_maxima_usd': str(full), 'requests_max': 3,
|
||||
'provider_enforced_test_cap': False,
|
||||
'basis': 'Published endpoint limits/prices, bounded input, fixed requests and no client retries; shared key retains its existing $5 cap.'}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--check', action='store_true')
|
||||
parser.add_argument('--resume-pcm', action='store_true', help='Explicit format correction after the sole WAV HTTP400; not an automatic retry.')
|
||||
args = parser.parse_args()
|
||||
budget = validate_budget()
|
||||
if args.check:
|
||||
print(json.dumps(budget))
|
||||
return
|
||||
if args.resume_pcm:
|
||||
state = json.loads(LEDGER.read_text())
|
||||
assert state['status']=='failed_stopped_no_retry' and state['paid_attempts']==1
|
||||
assert state['stages'][0]['http_status']==400 and state['reserved_usd']=='0.25'
|
||||
state['format_correction']='Explicit PCM request matching native engine after WAV HTTP400; initial error body was not retained.'
|
||||
state['budget'].update(requests_max=4, maximum_execution_reserved_usd='0.56')
|
||||
else:
|
||||
state = dict(budget=budget, stages=[], status='started', paid_attempts=0,
|
||||
reserved_usd='0', speech_text=TEXT)
|
||||
with LEDGER.open('x') as f:
|
||||
json.dump(state, f, indent=2)
|
||||
key = (ROOT / 'openrouter-test.key').read_text().strip()
|
||||
|
||||
def save():
|
||||
temporary = LEDGER.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps(state, indent=2, ensure_ascii=False)+'\n')
|
||||
temporary.replace(LEDGER)
|
||||
|
||||
def metadata(client):
|
||||
response = client.get(API+'key')
|
||||
response.raise_for_status()
|
||||
data = response.json()['data']
|
||||
return {k: data.get(k) for k in ('usage', 'limit', 'limit_remaining', 'limit_reset')}
|
||||
|
||||
def request(client, stage, endpoint, max_bytes, **kwargs):
|
||||
amount = RESERVES['tts'] if stage == 'tts_pcm' else RESERVES[stage]
|
||||
assert stage not in [s['stage'] for s in state['stages']]
|
||||
reserved = Decimal(state['reserved_usd']) + amount
|
||||
assert reserved <= Decimal('1') and state['paid_attempts'] < state['budget']['requests_max']
|
||||
row = dict(stage=stage, reserved_usd=str(amount), status='in_flight')
|
||||
state['stages'].append(row)
|
||||
state.update(reserved_usd=str(reserved), paid_attempts=state['paid_attempts']+1)
|
||||
save() # persist admission before sending, including failures/timeouts
|
||||
began = time.monotonic()
|
||||
try:
|
||||
with client.stream('POST', API+endpoint, **kwargs) as response:
|
||||
row['http_status'] = response.status_code
|
||||
row['headers'] = {k: v for k,v in response.headers.items() if
|
||||
k in ('content-type','content-length','x-request-id','x-generation-id',
|
||||
'x-openrouter-request-id','x-audio-sample-rate')}
|
||||
if response.status_code != 200:
|
||||
error_body = bytearray()
|
||||
for chunk in response.iter_bytes(1024):
|
||||
error_body.extend(chunk)
|
||||
if len(error_body) > 8192:
|
||||
break
|
||||
try:
|
||||
error = json.loads(error_body).get('error', {})
|
||||
row['provider_error'] = {k: str(error[k]).replace(key, '[redacted]')[:1000]
|
||||
for k in ('code','message') if k in error}
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
row['provider_error'] = 'unparseable'
|
||||
response.raise_for_status()
|
||||
body = bytearray()
|
||||
for part in response.iter_bytes(8192):
|
||||
assert time.monotonic()-began <= 30, 'stage wall deadline'
|
||||
assert len(body)+len(part) <= max_bytes, 'response capacity'
|
||||
body.extend(part)
|
||||
row.update(status='received', bytes=len(body), elapsed_seconds=round(time.monotonic()-began, 3))
|
||||
return bytes(body), response.headers.get('content-type','').split(';')[0]
|
||||
except BaseException as exc:
|
||||
row.update(status='failed', error_type=type(exc).__name__)
|
||||
raise
|
||||
finally:
|
||||
save()
|
||||
|
||||
transport = httpx.HTTPTransport(retries=0)
|
||||
with httpx.Client(transport=transport, timeout=30, trust_env=False,
|
||||
follow_redirects=False, headers={'Authorization': 'Bearer '+key}) as client:
|
||||
try:
|
||||
if args.resume_pcm:
|
||||
state['resume_key_preflight'] = metadata(client)
|
||||
else:
|
||||
state['key_before'] = metadata(client)
|
||||
save()
|
||||
assert state['key_before']['limit_remaining'] is not None
|
||||
assert Decimal(str(state['key_before']['limit_remaining'])) >= sum(RESERVES.values())
|
||||
raw, media = request(client, 'tts_pcm' if args.resume_pcm else 'tts', 'audio/speech', 484096,
|
||||
json=dict(model='google/gemini-3.8-flash-lite-tts', voice='Kore',
|
||||
input=TEXT, response_format='pcm' if args.resume_pcm else 'wav'))
|
||||
native_header = raw.startswith(b'RIFF')
|
||||
if args.resume_pcm and not native_header:
|
||||
assert media in ('audio/pcm','application/octet-stream','audio/l16')
|
||||
assert raw and len(raw) % 2 == 0 and len(raw) <= 480000
|
||||
output = BytesIO()
|
||||
with wave.open(output,'wb') as audio:
|
||||
audio.setnchannels(1); audio.setsampwidth(2); audio.setframerate(24000)
|
||||
audio.writeframes(raw)
|
||||
raw = output.getvalue()
|
||||
else:
|
||||
assert media in ('audio/wav','audio/x-wav','audio/wave'), 'self-describing WAV required'
|
||||
with wave.open(BytesIO(raw), 'rb') as audio:
|
||||
channels, width, rate, frames = audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getnframes()
|
||||
assert channels == 1 and width == 2 and rate == 24000 and audio.getcomptype() == 'NONE'
|
||||
assert 0 < frames <= 240000, 'audio duration exceeds 10s'
|
||||
pcm = audio.readframes(frames)
|
||||
assert len(pcm) == frames * 2 and any(pcm)
|
||||
path = ROOT / 'persian-real-tts-one-dollar.wav'
|
||||
with path.open('xb') as f:
|
||||
f.write(raw)
|
||||
state['tts_artifact'] = dict(path=str(path), header_rate=rate,
|
||||
frames=frames, seconds=frames/rate,
|
||||
rate_independently_verified=native_header,
|
||||
pcm_native_path_tested=args.resume_pcm and not native_header)
|
||||
save()
|
||||
raw, media = request(client, 'stt', 'audio/transcriptions', 65536,
|
||||
files={'file': ('generated-persian.wav', path.read_bytes(), 'audio/wav')},
|
||||
data={'model': 'openai/whisper-large-v3', 'language': 'fa', 'response_format': 'json'})
|
||||
assert media == 'application/json'
|
||||
stt = json.loads(raw)
|
||||
text = stt['text']
|
||||
assert isinstance(text,str) and 0 < len(text) <= 1024
|
||||
state['stt_result'] = stt
|
||||
save()
|
||||
raw, media = request(client, 'llm', 'chat/completions', 65536,
|
||||
json=dict(model='openai/gpt-4.1-mini', stream=False, max_tokens=128,
|
||||
provider={'allow_fallbacks': False, 'max_price': {'prompt': 1, 'completion': 2}},
|
||||
messages=[dict(role='system', content='Reply with one short Persian greeting. No factual or document claims.'),
|
||||
dict(role='user', content=text)]))
|
||||
assert media == 'application/json'
|
||||
llm = json.loads(raw)
|
||||
assert llm['choices'][0]['finish_reason'] == 'stop'
|
||||
state['llm_result'] = llm
|
||||
state['status'] = 'components_completed_listening_pending'
|
||||
state.pop('error_type', None)
|
||||
except BaseException as exc:
|
||||
state.update(status='failed_stopped_no_retry', error_type=type(exc).__name__)
|
||||
finally:
|
||||
try:
|
||||
state['key_after'] = metadata(client)
|
||||
state['observed_key_usage_delta_usd'] = str(Decimal(str(state['key_after']['usage']))-Decimal(str(state['key_before']['usage'])))
|
||||
except Exception as exc:
|
||||
state['usage_check_error_type'] = type(exc).__name__
|
||||
save()
|
||||
print(json.dumps({'status':state['status'],'paid_attempts':state['paid_attempts'],
|
||||
'reserved_usd':state['reserved_usd'],
|
||||
'observed_key_usage_delta_usd':state.get('observed_key_usage_delta_usd')}))
|
||||
if state['status'] != 'components_completed_listening_pending':
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user