45 lines
2.2 KiB
Plaintext
45 lines
2.2 KiB
Plaintext
|
|
|
|
@router.post('/speech/pcm-stream')
|
|
async def athena_pcm_speech(request: Request, user=Depends(get_verified_user)):
|
|
"""Relay Athena PCM immediately; never cache or transcode the live stream."""
|
|
from starlette.responses import StreamingResponse
|
|
if user.role != 'admin' and not await has_permission(user.id, 'chat.tts', await Config.get('user.permissions')):
|
|
raise HTTPException(403, 'Speech permission required.')
|
|
if await Config.get('audio.tts.engine') != 'openai':
|
|
raise HTTPException(400, 'Athena streaming requires the OpenAI-compatible TTS engine.')
|
|
payload = await request.json()
|
|
if not isinstance(payload, dict):
|
|
raise HTTPException(400, 'JSON object required.')
|
|
payload = {**payload, **(await Config.get('audio.tts.openai.params') or {})}
|
|
payload['model'] = await Config.get('audio.tts.model')
|
|
payload['voice'] = payload.get('voice') or await Config.get('audio.tts.voice')
|
|
payload['response_format'] = 'pcm'
|
|
payload['speed'] = 1
|
|
key = await Config.get('audio.tts.openai.api_key')
|
|
base = (await Config.get('audio.tts.openai.api_base_url')).rstrip('/')
|
|
session = await get_session()
|
|
response = await session.post(base + '/audio/speech', json=payload,
|
|
headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'},
|
|
ssl=AIOHTTP_CLIENT_SESSION_SSL)
|
|
if response.status >= 400:
|
|
try:
|
|
await response.read()
|
|
response.raise_for_status()
|
|
except Exception as exc:
|
|
await _raise_tts_error(exc, response)
|
|
finally:
|
|
response.release()
|
|
if response.headers.get('X-Audio-Format') != 's16le' or response.headers.get('X-Audio-Sample-Rate') != '24000':
|
|
response.release()
|
|
raise HTTPException(502, 'Provider did not return the required PCM stream.')
|
|
async def chunks():
|
|
try:
|
|
async for chunk in response.content.iter_chunked(8192):
|
|
yield chunk
|
|
finally:
|
|
response.close()
|
|
return StreamingResponse(chunks(), media_type='audio/pcm', headers={
|
|
'X-Audio-Sample-Rate': '24000', 'X-Audio-Channels': '1',
|
|
'X-Audio-Format': 's16le', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no'})
|