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:
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user