"""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(' 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())