Files
rag-technical-docs-assistant/tests/unit/test_local_s2s_responsiveness.py
T
amirhosein mazaheri 628aec8def feat(voice): implement local S2S responsiveness candidate and direct TTS routing
Add local S2S responsiveness candidate pinning ASR options and sentence-at-a-time generation. Route speech synthesis directly to OpenAI API for fluent Persian phonetics with gpt-4o-mini-tts-2025-12-15. Add responsiveness, budget carry, and browser watch unit tests along with acceptance benchmarks and evaluation evidence.
2026-10-17 13:02:41 +03:30

152 lines
8.0 KiB
Python

"""Opt-in policy must reach real wire bytes and remain frozen/attested."""
import asyncio
import base64
from io import BytesIO
import importlib.util
import json
from pathlib import Path
from threading import Thread
from types import SimpleNamespace
import wave
import httpx
import pytest
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
from services.local_s2s.responsiveness import install_stt_policy,transcription_request
from services.local_s2s.extension import active_components
from services.local_s2s.components import ComponentServer
from services.local_s2s.request_policy import install_client_policy
from tests.unit.test_local_s2s_phase2 import local_config,confirmed
from tests.unit.test_local_s2s_engine import handlers
from app.infrastructure.local_s2s import LocalS2SAdapter
from app.modules.voice.settings import RuntimeSettings
def audio():
out=BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(bytes(3200))
return out.getvalue()
def request():
r=httpx.Request('POST','https://openrouter.ai/api/v1/audio/transcriptions',data=dict(model='openai/whisper-large-v3',language='fa',response_format='json',temperature='0',prompt=RESPONSIVE_ASR_PROMPT),files={'file':('audio.wav',audio(),'audio/wav')})
r.read();return r
def test_profile_changes_identity_and_requires_applied_settings():
baseline=local_config();responsive=local_config(local_s2s_responsive=True)
assert baseline.profile()!=responsive.profile()
assert not LocalS2SAdapter(None,config=baseline,settings=RuntimeSettings(_env_file=None)).acknowledged(confirmed(LocalS2SAdapter(None,config=responsive,settings=RuntimeSettings(_env_file=None))))
unit=handlers(responsive);unit.handlers[1].gen_kwargs=dict(temperature=0,prompt=RESPONSIVE_ASR_PROMPT);unit.handlers[2].stream_batch_sentences=1
assert active_components(unit,responsive.components())==responsive.components()
unit.handlers[2].stream_batch_sentences=3
with pytest.raises(ValueError):active_components(unit,responsive.components())
def test_transcription_policy_preserves_audio_and_uses_supported_options():
r=transcription_request(request());d=json.loads(r.content)
assert base64.b64decode(d['input_audio']['data'])==audio()
assert d['temperature']==0 and d['language']=='fa'
assert d['provider']=={'options':{'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}}
assert 'prompt' not in d
spec=importlib.util.spec_from_file_location('admission',Path(__file__).parents[2]/'docs/evaluation/local-s2s/native-budget-transport.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
assert m.validate_request(r)[0]=='transcriptions'
d['temperature']=1
with pytest.raises(ValueError):m.validate_request(httpx.Request(r.method,r.url,json=d))
def test_stt_settings_apply_before_native_setup_and_warmup():
calls=[]
class Handler:
def setup(self,**kwargs):calls.append(kwargs)
module=SimpleNamespace(OpenAICompatibleSTTHandler=Handler)
install_stt_policy(module);Handler().setup(gen_kwargs={'response_style':'plain'})
assert calls==[{'gen_kwargs':{'response_style':'plain','temperature':0,'prompt':RESPONSIVE_ASR_PROMPT}}]
def test_sentence_policy_applies_before_llm_warmup():
calls=[]
class Base:
def setup(self,**kwargs):calls.append(kwargs)
module=SimpleNamespace(OpenAI=lambda **kwargs:None,BaseOpenAICompatibleHandler=Base)
install_client_policy(module,local_config(local_s2s_responsive=True));Base().setup()
assert calls[0]['stream_batch_sentences']==1
def test_actual_gateway_transforms_request_without_rewriting_transcript(capsys):
observed=[]
def upstream(r):
observed.append(json.loads(r.content))
return httpx.Response(200,headers={'content-type':'application/json'},json={'text':'unchanged transcript'})
server=ComponentServer('fixture-key',port=0,transport=httpx.MockTransport(upstream),responsive=True)
thread=Thread(target=server.serve_forever,daemon=True);thread.start();assert server.ready.wait(3)
try:
r=request()
with httpx.Client(trust_env=False,timeout=5) as client:
result=client.post('http://127.0.0.1:'+str(server.server_port)+'/v1/audio/transcriptions',content=r.content,headers={'content-type':r.headers['content-type'],'authorization':'Bearer local-components'})
assert result.status_code==200 and result.json()['text']=='unchanged transcript'
assert observed[0]['provider']['options']['groq']['prompt']==RESPONSIVE_ASR_PROMPT
finally:
server.shutdown();server.server_close();thread.join(3)
output=capsys.readouterr().out
assert 'component_first_byte' in output
assert RESPONSIVE_ASR_PROMPT not in output and 'unchanged transcript' not in output
@pytest.mark.parametrize('component', ['transcriptions', 'speech'])
@pytest.mark.parametrize('has_key', [True, False])
def test_direct_openai_audio_routes_and_never_uses_router_key(monkeypatch, component, has_key):
if has_key:
monkeypatch.setenv('OPENAI_API_KEY', 'openai-fixture')
else:
monkeypatch.delenv('OPENAI_API_KEY', raising=False)
observed = []
def upstream(r):
observed.append(r)
return httpx.Response(200, headers={'content-type': 'application/json' if component == 'transcriptions' else 'audio/pcm'},
content=b'{"text":"unchanged"}' if component == 'transcriptions' else bytes(100))
if component == 'transcriptions':
r = httpx.Request('POST', 'http://fixture', data=dict(model='gpt-4o-transcribe', language='fa', response_format='json', temperature='0', prompt=RESPONSIVE_ASR_PROMPT), files={'file': ('audio.wav', audio(), 'audio/wav')})
r.read()
else:
r = httpx.Request('POST', 'http://fixture', json=dict(model='openai/gpt-4o-mini-tts', input='fixture', voice='alloy', response_format='pcm'))
server = ComponentServer('router-fixture', port=0, transport=httpx.MockTransport(upstream), responsive=True)
thread = Thread(target=server.serve_forever, daemon=True); thread.start(); assert server.ready.wait(3)
try:
with httpx.Client(trust_env=False, timeout=5) as client:
try:
result = client.post(f'http://127.0.0.1:{server.server_port}/v1/audio/{component}', content=r.content,
headers={'content-type': r.headers['content-type'], 'authorization': 'Bearer local-components'})
except httpx.RemoteProtocolError:
assert not has_key
else:
assert has_key and result.status_code == 200
if has_key:
sent = observed[0]
assert str(sent.url) == f'https://api.openai.com/v1/audio/{component}'
assert sent.headers['authorization'] == 'Bearer openai-fixture'
if component == 'transcriptions':
assert sent.content == r.content
assert sent.headers['content-type'].startswith('multipart/form-data;')
else:
assert json.loads(sent.content)['model'] == 'gpt-4o-mini-tts'
else:
assert observed == []
finally:
server.shutdown(); server.server_close(); thread.join(3)
def test_faster_tts_applies_before_warmup_and_is_attested():
from services.local_s2s.request_policy import install_tts_speed
from app.modules.voice.local_s2s import setup_session
calls = []
class Handler:
def setup(self, **kwargs):
self.speed = kwargs['speed']; calls.append(kwargs)
module = SimpleNamespace(OpenAICompatibleTTSHandler=Handler)
install_tts_speed(module, 1.3); handler = Handler(); handler.setup()
assert calls == [{'speed': 1.3}]
config = local_config(local_s2s_tts_speed=1.3)
assert setup_session(config)['audio']['output']['speed'] == 1.3
assert config.profile() != local_config().profile()
unit = handlers(config); unit.handlers[-1].speed = handler.speed
assert active_components(unit, config.components())['tts']['speed'] == 1.3
unit.handlers[-1].speed = 1.0
with pytest.raises(ValueError): active_components(unit, config.components())