Files
rag-technical-docs-assistant/app/local_s2s_smoke.py
T
amirhosein mazaheri 8d348f0ba1 feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add
an opt-in isolated Local S2S adapter, pinned engine extension, bounded
component gateway and frozen effective configuration profiles.

Enforce request token limits, zero retries, local asset validation,
connection deadlines, disconnect ownership, bounded cleanup and signals.
Include regression coverage, pinned source fixtures, operator guidance,
asset fingerprints and guarded disposable PostgreSQL acceptance tooling.
Preserve immutable fixture bytes across Git line-ending conversion.

Validation recorded in the reports:
- 74 repair, 107 combined and 242 preservation checks passed.
- Fresh PostgreSQL local checks: 2 passed.
- Expanded PostgreSQL: 57 passed, 6 documented baseline failures.
- Compose configurations, staged whitespace and fixture hashes passed.

Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component
audio and Persian browser acceptance remain pending. No operational switch,
paid call, model download or Phase 3 implementation is included.
2026-10-15 12:28:17 +03:30

150 lines
7.2 KiB
Python

"""Explicit offline stage demonstration or bounded opt-in OpenRouter smoke.
Default stub output is a labelled test tone, never evidence of Persian speech.
"""
import argparse
import asyncio
import base64
from io import BytesIO
import json
import math
import os
from pathlib import Path
import struct
import wave
import httpx
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.provider import strict_json
MAX_PCM = 480000 # 10 seconds at 24 kHz, also bounds saved evaluation audio.
def wav_bytes(pcm):
output = BytesIO()
with wave.open(output, 'wb') as audio:
audio.setnchannels(1)
audio.setsampwidth(2)
audio.setframerate(24000)
audio.writeframes(pcm)
return output.getvalue()
def tone():
return b''.join(struct.pack('<h', round(1800 * math.sin(2 * math.pi * 440 * i / 24000)))
for i in range(9600))
async def bounded_response(client, endpoint, *, max_bytes, **kwargs):
async with asyncio.timeout(30):
async with client.stream('POST', 'https://openrouter.ai/api/v1/' + endpoint, **kwargs) as response:
if response.status_code != 200:
raise ValueError('LOCAL_STAGE_HTTP_FAILURE')
body = bytearray()
async for part in response.aiter_bytes(8192):
if len(body) + len(part) > max_bytes:
raise ValueError('LOCAL_STAGE_RESPONSE_CAPACITY')
body.extend(part)
return bytes(body), response.headers.get('content-type', '').split(';')[0]
async def stages(config, pcm, client, key, *, stt_format='multipart'):
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM:
raise ValueError('LOCAL_STAGE_INPUT_CAPACITY')
headers = {'Authorization': 'Bearer ' + key}
audio = wav_bytes(pcm)
if stt_format == 'multipart':
payload = dict(files={'file': ('fixture.wav', audio, 'audio/wav')},
data={'model': config.local_s2s_stt_model, 'language': 'fa', 'response_format': 'json'})
elif stt_format == 'json':
payload = dict(json=dict(model=config.local_s2s_stt_model, language='fa', response_format='json',
input_audio=dict(data=base64.b64encode(audio).decode('ascii'), format='wav')))
else:
raise ValueError('LOCAL_STAGE_STT_FORMAT')
raw, media = await bounded_response(client, 'audio/transcriptions', headers=headers, max_bytes=65536, **payload)
if media != 'application/json':
raise ValueError('LOCAL_STAGE_STT_FORMAT')
text = strict_json(raw).get('text')
if not isinstance(text, str) or not text.strip() or len(text) > 1024:
raise ValueError('LOCAL_STAGE_STT_RESULT')
raw, media = await bounded_response(client, 'chat/completions', headers=headers, max_bytes=65536,
json=dict(model=config.local_s2s_llm_model, stream=False, max_tokens=128,
messages=[dict(role='system', content='Reply briefly in Persian. A greeting only; no document claims.'),
dict(role='user', content=text)]))
if media != 'application/json':
raise ValueError('LOCAL_STAGE_LLM_FORMAT')
result = strict_json(raw)
choices = result.get('choices')
if not isinstance(choices, list) or len(choices) != 1 or choices[0].get('finish_reason') != 'stop':
raise ValueError('LOCAL_STAGE_LLM_TERMINAL')
answer = choices[0].get('message', {}).get('content')
if not isinstance(answer, str) or not answer.strip() or len(answer) > 300:
raise ValueError('LOCAL_STAGE_LLM_RESULT')
raw, media = await bounded_response(client, 'audio/speech', headers=headers, max_bytes=MAX_PCM,
json=dict(model=config.local_s2s_tts_model, voice=config.local_s2s_tts_voice,
input=answer, response_format='pcm'))
if media != 'audio/pcm' or not raw or len(raw) % 2:
raise ValueError('LOCAL_STAGE_TTS_FORMAT')
return raw
def stub_response(request):
if request.url.path.endswith('/audio/transcriptions'):
return httpx.Response(200, json={'text': '\u0633\u0644\u0627\u0645'})
if request.url.path.endswith('/chat/completions'):
return httpx.Response(200, json={'choices': [{'finish_reason': 'stop', 'message': {'content': '\u0633\u0644\u0627\u0645'}}]})
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=tone())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--live', action='store_true', help='Makes exactly 3 paid requests; no retries or startup probes.')
parser.add_argument('--input', type=Path, help='Consented PCM16 mono 24k WAV, at most 10 seconds.')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--save-evaluation-audio', action='store_true', help='Consent to saving actual provider speech.')
parser.add_argument('--stt-format', choices=['multipart', 'json'], default='multipart')
args = parser.parse_args()
if args.output.exists():
parser.error('Output already exists; choose a new filename.')
if args.live and (not args.input or not args.save_evaluation_audio):
parser.error('--live requires consented --input and --save-evaluation-audio')
if args.live:
config = VoiceSettings(provider='local_s2s')
if not all((config.local_s2s_stt_model, config.local_s2s_llm_model, config.local_s2s_tts_model, config.local_s2s_tts_voice)):
parser.error('Explicit local model/voice settings are required.')
key = os.environ.get('OPENROUTER_API_KEY', '')
if not key:
parser.error('OPENROUTER_API_KEY is required.')
# Check size before reading/decompressing input.
if args.input.stat().st_size > MAX_PCM + 4096:
parser.error('Input is too large.')
with wave.open(str(args.input), 'rb') as audio:
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getcomptype()) != (1, 2, 24000, 'NONE'):
parser.error('Expected mono PCM16 24kHz WAV.')
pcm = audio.readframes(240001)
transport = httpx.AsyncHTTPTransport(retries=0)
else:
config = VoiceSettings(_env_file=None, provider='local_s2s',
local_s2s_stt_model='stub/stt', local_s2s_llm_model='stub/llm',
local_s2s_tts_model='stub/tts', local_s2s_tts_voice='stub')
key, pcm, transport = 'stub-only', tone(), httpx.MockTransport(stub_response)
async def run():
async with httpx.AsyncClient(transport=transport, timeout=30, follow_redirects=False) as client:
async with asyncio.timeout(90):
return await stages(config, pcm, client, key, stt_format=args.stt_format)
try:
output = asyncio.run(run())
with args.output.open('xb') as target:
target.write(wav_bytes(output))
except (ValueError, KeyError, TypeError, OSError, httpx.HTTPError, TimeoutError):
print(json.dumps(dict(status='failed', mode='live' if args.live else 'stub')))
return 1
print(json.dumps(dict(status='ok', mode='live' if args.live else 'stub-test-tone',
requests=3, paid_requests=3 if args.live else 0,
sample_rate=24000, samples=len(output)//2)))
return 0
if __name__ == '__main__':
raise SystemExit(main())