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.
This commit is contained in:
amirhosein mazaheri
2026-10-17 13:02:41 +03:30
parent a94b8cd3ea
commit 628aec8def
40 changed files with 1568 additions and 70 deletions
+4
View File
@@ -0,0 +1,4 @@
# COPY-only candidate; dependencies and upstream remain from the verified local base.
FROM rag-local-s2s-candidate:windows-rebuild-20261017
COPY app /app/app
COPY services/local_s2s /app/services/local_s2s
@@ -0,0 +1,9 @@
**
!app/
!app/**
!services/
!services/local_s2s/
!services/local_s2s/**
**/__pycache__
**/*.pyc
**/.env
+5
View File
@@ -407,3 +407,8 @@ restored its stopped state. No runtime assertion was relaxed. Phase 2 remains
NOT ACCEPTED until complete engine/SDK/POSIX, component audio and Persian browser
evidence exists along with Phase 1 acceptance. There were no paid calls, downloads,
image builds or operational changes in this preparation checkpoint.
## Isolated responsiveness candidate (2026-10-17)
`LOCAL_S2S_RESPONSIVE=true` pins sentence-at-a-time output and ASR decode options. Default false retains baseline identities. See [implementation, checks and live comparison gate](../../docs/evaluation/local-s2s/responsive-candidate-20261017.md). No measured Persian latency/accuracy improvement is claimed before human comparison.
+48 -6
View File
@@ -1,5 +1,7 @@
"""Owned local HTTP gateway: total connection deadlines and bounded async I/O."""
import asyncio
import json
import os
from collections import Counter
import socket
from threading import Event, Thread
@@ -19,9 +21,10 @@ class EvaluationBudgetExhausted(ValueError):
class ComponentServer:
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None):
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None, responsive=False):
if not key or not key.isascii() or any(c.isspace() for c in key):
raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED')
self.responsive = responsive
self.key, self.transport, self.timeout = key, transport, timeout
self.inactivity = min(timeout, 5) if inactivity is None else min(timeout, inactivity)
if self.timeout <= 0 or self.inactivity <= 0:
@@ -99,15 +102,51 @@ class ComponentServer:
pass
async def _forward(self, client, writer, path, fields, body, response):
request = client.build_request('POST', 'https://openrouter.ai/api' + path,
headers={'Authorization': 'Bearer ' + self.key,
url = 'https://openrouter.ai/api' + path
auth_key = self.key
forward_body = bytes(body)
direct_asr = False
if path.endswith('/transcriptions'):
from email.parser import BytesParser
from email.policy import default
message = BytesParser(policy=default).parsebytes(
('Content-Type: ' + fields.get('content-type', '') + '\r\n\r\n').encode() + forward_body)
models = [part.get_payload(decode=True).decode() for part in message.iter_parts()
if part.get_param('name', header='content-disposition') == 'model']
if len(models) != 1:
raise ValueError('LOCAL_ASR_MODEL_REQUIRED')
direct_asr = models[0] in ('gpt-4o-transcribe', 'gpt-4o-mini-transcribe',
'gpt-4o-mini-transcribe-2025-12-15', 'whisper-1')
if path.endswith('/speech'):
payload = json.loads(forward_body)
model_name = payload.get('model', '')
direct_tts = model_name.startswith(('openai/', 'gpt-', 'tts-'))
if direct_tts and model_name.startswith('openai/'):
payload['model'] = model_name.removeprefix('openai/')
forward_body = json.dumps(payload).encode()
else:
direct_tts = False
if direct_asr or direct_tts:
url = 'https://api.openai.com' + path
auth_key = os.environ.get('OPENAI_API_KEY', '')
if not auth_key:
raise ValueError('LOCAL_OPENAI_CREDENTIAL_REQUIRED')
request = client.build_request('POST', url,
headers={'Authorization': 'Bearer ' + auth_key,
'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
content=bytes(body))
content=forward_body)
# The owner closes the response independently, even if cancellation or a
# stalled stream prevents this operation from reaching normal completion.
if self.responsive and path.endswith('/transcriptions') and not direct_asr:
from services.local_s2s.responsiveness import transcription_request
request = transcription_request(request)
began = self.loop.time()
result = await client.send(request, stream=True)
header_ms = round((self.loop.time() - began) * 1000)
response.append(result)
if result.status_code != 200:
print(json.dumps(dict(stage="component_error", component=path.rsplit("/", 1)[-1], status=result.status_code)), flush=True)
await self._error(writer, 502)
return
media = result.headers.get('content-type', '').split(';')[0]
@@ -120,6 +159,9 @@ class ComponentServer:
total = 0
# No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
async for raw in result.aiter_bytes():
if self.responsive and raw and total == 0:
print(json.dumps(dict(stage='component_first_byte', component=path.rsplit('/',1)[-1],
headers_ms=header_ms, first_body_ms=round((self.loop.time()-began)*1000))),flush=True)
total += len(raw)
if total > LIMITS[path][1]:
raise ValueError('Response capacity')
@@ -224,8 +266,8 @@ class ComponentServer:
self.socket.close()
def start_components(key, timeout=30):
server = ComponentServer(key, timeout=timeout)
def start_components(key, timeout=30, **options):
server = ComponentServer(key, timeout=timeout, **options)
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
if not server.ready.wait(5):
+10 -2
View File
@@ -1,4 +1,4 @@
"""Development engine launcher; local asset preflight precedes every paid probe."""
"""Development engine launcher; local asset preflight precedes every paid probe."""
import argparse
import json
import logging
@@ -33,6 +33,13 @@ def build_runtime(config, stop):
pipeline.Queue = PipelineQueue
# Base setup invokes warmup from inside construction; install before it runs.
install_client_policy(base_llm, config)
import speech_to_speech.TTS.openai_compatible_handler as native_tts
from services.local_s2s.request_policy import install_tts_speed
install_tts_speed(native_tts, config.local_s2s_tts_speed)
if config.local_s2s_responsive:
import speech_to_speech.STT.openai_compatible_handler as native_stt
from services.local_s2s.responsiveness import install_stt_policy
install_stt_policy(native_stt)
# The pinned output processor also detects language for fixed session configs.
# Its first lazy Lingua preload can hold the GIL beyond the media send deadline.
# Prime the same cache before exposing the listener, within the startup budget.
@@ -87,7 +94,8 @@ def main():
key = os.environ.get('OPENROUTER_API_KEY', '')
if not key:
parser.error('OPENROUTER_API_KEY is required in the engine only.')
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds)
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds,
component_options={'responsive': True} if config.local_s2s_responsive else None)
if __name__ == '__main__':
+5
View File
@@ -31,6 +31,11 @@ def active_components(unit, expected):
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
response_format=tts.response_format, sample_rate=tts.sample_rate),
request_timeout_seconds=stt.timeout)
if 'speed' in expected['tts']:
actual['tts']['speed'] = tts.speed
if 'temperature' in expected['stt']:
actual['stt'].update(temperature=stt.gen_kwargs.get('temperature'), prompt=stt.gen_kwargs.get('prompt'))
actual['llm']['stream_batch_sentences'] = llm.stream_batch_sentences
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
or str(llm.client.base_url).rstrip('/') != stt.base_url
+2 -2
View File
@@ -50,12 +50,12 @@ def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print):
return any(counters.values())
def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print):
def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print, component_options=None):
stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock()
runtime = None
result = {}
with termination_signals(stop):
guard, thread = start_components(key, request_timeout)
guard, thread = start_components(key, request_timeout, **(component_options or {}))
def drive():
nonlocal runtime
if stop.is_set():
+10
View File
@@ -36,6 +36,16 @@ def install_client_policy(base_module, config):
native_setup = base.setup
def setup(self, *args, **kwargs):
kwargs['request_timeout_s'] = config.local_s2s_request_timeout_seconds
if getattr(config, 'local_s2s_responsive', False):
kwargs['stream_batch_sentences'] = 1
return native_setup(self, *args, **kwargs)
base.setup = setup
return native
def install_tts_speed(module, speed):
native = module.OpenAICompatibleTTSHandler.setup
def setup(self, *args, **kwargs):
kwargs['speed'] = speed
return native(self, *args, **kwargs)
module.OpenAICompatibleTTSHandler.setup = setup
+36
View File
@@ -0,0 +1,36 @@
"""Opt-in applied ASR policy; provider routing remains in the engine gateway."""
import base64
from email.parser import BytesParser
from email.policy import default
import json
import httpx
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
def install_stt_policy(module):
native=module.OpenAICompatibleSTTHandler.setup
def setup(self,*args,**kwargs):
kwargs['gen_kwargs']={**kwargs.get('gen_kwargs',{}),'temperature':0,'prompt':RESPONSIVE_ASR_PROMPT}
return native(self,*args,**kwargs)
module.OpenAICompatibleSTTHandler.setup=setup
def transcription_request(request):
"""Map pinned multipart to documented JSON provider.options; never change audio."""
if not request.headers.get('content-type','').startswith('multipart/form-data;'):
raise ValueError('LOCAL_ASR_MULTIPART_REQUIRED')
message=BytesParser(policy=default).parsebytes(('Content-Type: '+request.headers['content-type']+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+request.content)
fields={}
for part in message.iter_parts():
name=part.get_param('name',header='content-disposition')
if name in fields:raise ValueError('LOCAL_ASR_DUPLICATE_FIELD')
fields[name]=part.get_payload(decode=True)
if (set(fields)!={'file','model','language','response_format','temperature','prompt'} or
fields['language']!=b'fa' or fields['response_format']!=b'json' or
fields['temperature'] not in (b'0',b'0.0') or fields['prompt'].decode()!=RESPONSIVE_ASR_PROMPT):
raise ValueError('LOCAL_ASR_PROFILE_MISMATCH')
data=dict(model=fields['model'].decode(),language='fa',response_format='json',temperature=0,
input_audio=dict(data=base64.b64encode(fields['file']).decode('ascii'),format='wav'),
provider=dict(options={'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}))
return httpx.Request(request.method,request.url,
headers={k:v for k,v in request.headers.items() if k not in ('content-type','content-length')},json=data)