Add MP3 speech output and Hermes Accept negotiation; stage without activation
This commit is contained in:
1 parent
f3630f63ba
commit
92b8214c87
6 files changed
+143
-7
No files matched your search
+9
-3
@@ -215,7 +215,7 @@ Profilfreigaben: mehrere Chatprofile, höchstens ein Bildprofil. Die Auswahl ein
|
||||
|
||||
`POST /v1/audio/speech` verwendet ein freigegebenes TTS-Profil als `model`,
|
||||
`input` (1–1000 Zeichen), optional `voice` (Standard Ryan), `language` (Standard
|
||||
German), `speed` (0,25–4; sonst Profilwert) und `response_format=wav|pcm`.
|
||||
German), `speed` (0,25–4; sonst Profilwert) und `response_format=wav|pcm|mp3`.
|
||||
Qwen-TTS nutzt das gepinnte Base-Modell mit versionierten Preset-Embeddings;
|
||||
Serena ist die in OpenWebUI gewählte Stimme, kein globaler API-Default.
|
||||
|
||||
@@ -224,11 +224,17 @@ HTTP-Chunked-Transfer geliefert: mono S16LE, 24 kHz, Header `X-Audio-Format`,
|
||||
`X-Audio-Channels`, `X-Audio-Sample-Rate`. Alternativ
|
||||
`POST /v1/audio/speech/pcm-stream`; Streaming benötigt `speed=1`.
|
||||
Vor Streambeginn sind Fehler JSON; danach wird ein fehlerhafter Stream abgebrochen.
|
||||
MP3 ist am Deck-Endpunkt nicht implementiert. Ein Client muss PCM tatsächlich
|
||||
MP3 wird nach der Synthese mit FFmpeg/libmp3lame als vollständige Datei mit
|
||||
`Content-Type: audio/mpeg` geliefert (128 kbit/s, Kodierung auf CPU). Ohne
|
||||
`response_format` bleibt WAV der Standard; bei `Accept: audio/mpeg` wird MP3
|
||||
gewählt, wie es Hermes Live Talk anfordert. Ein explizites `response_format`
|
||||
hat Vorrang. Native Installation und Restore benötigen dafür das Paket
|
||||
`ffmpeg` mit libmp3lame; das vorhandene Deck-Image enthält es bereits.
|
||||
Ein Client muss PCM tatsächlich
|
||||
fortlaufend abspielen; die unveränderte OpenWebUI-Wiedergabe nutzt WAV.
|
||||
|
||||
Ein freigegebenes VoxCPM2-/OmniVoice-Profil kann über denselben Speech-Endpunkt
|
||||
WAV erzeugen: `voice=default`, bei VoxCPM2 `speed=1`. Referenzstimmen werden im
|
||||
WAV oder MP3 erzeugen: `voice=default`, bei VoxCPM2 `speed=1`. Referenzstimmen werden im
|
||||
Deck-Testbereich verwendet; diese JSON-Route nimmt keine Referenzdatei an.
|
||||
PCM-Streaming ist für diese Stimmwerkzeuge nicht implementiert.
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# App-only update. Build with the active Deck image and endpoint.py as context.
|
||||
ARG DECK_RUNTIME_IMAGE
|
||||
FROM ${DECK_RUNTIME_IMAGE}
|
||||
USER root
|
||||
COPY endpoint.py /app/endpoint.py
|
||||
RUN chmod 0644 /app/endpoint.py && command -v ffmpeg >/dev/null
|
||||
USER 65534:65534
|
||||
@@ -0,0 +1,66 @@
|
||||
# Athena speech MP3 — prepared, not activated
|
||||
|
||||
The user requested MP3 output for Hermes Live Talk, then explicitly asked not to
|
||||
restart the Athena endpoint yet. No production restart or activation was made.
|
||||
|
||||
## Implementation
|
||||
|
||||
`POST /v1/audio/speech` accepts `response_format=mp3` and returns a complete
|
||||
MP3 file with `Content-Type: audio/mpeg`. The generated WAV is encoded locally
|
||||
using the existing FFmpeg/libmp3lame, 128 kbit/s and one encoder thread. Both
|
||||
ordinary TTS and the voice-tool output path use the same final encoding step.
|
||||
|
||||
Hermes WebUI's installed read-aloud request omits `response_format` and sends
|
||||
`Accept: audio/mpeg`. Athena now selects MP3 for that header. An explicit
|
||||
`response_format` overrides Accept. Otherwise the existing WAV default remains;
|
||||
PCM streaming and its response headers are unchanged. Encoder errors have
|
||||
dedicated API codes, without exposing FFmpeg stderr.
|
||||
|
||||
## Prepared artifact and activation boundary
|
||||
|
||||
- Stage: `/opt/athena-deck-dev/tts-mp3-20261017`.
|
||||
- Prepared image: `athena-deck-standalone:tts-mp3-20261017`.
|
||||
- Image ID: `sha256:4c0bf988aa766615893fe32610dea2e9156a0de5cd24eb5a4f9b74d458aa785e`.
|
||||
- Base remains the currently active
|
||||
`athena-deck-standalone:ssd-bars-fixed-20261015`.
|
||||
- Recipe: `deploy/Dockerfile.tts-mp3`, app-only replacement of `endpoint.py`.
|
||||
- Active container remains `athena-deck-dev`, healthy on the old image.
|
||||
- Its start timestamp and restart count were compared before/after and match.
|
||||
|
||||
Activation is deferred until the user gives a new go. Before activation, check
|
||||
for active requests and intervening image/code updates. Preserve the installation
|
||||
manifest, mounts, settings and runtime selection through the regular deployment
|
||||
helper. Do not overwrite newer application changes with this prepared delta.
|
||||
|
||||
## Validation
|
||||
|
||||
Seven focused tests passed in a disposable container using the prepared image,
|
||||
with no network, no GPUs and no production state mounts (1 CPU, 512 MiB RAM):
|
||||
|
||||
- MP3 through explicit format and Hermes-style Accept, correct MIME/length.
|
||||
- Explicit WAV overrides MPEG Accept; MPEG with q=0 keeps WAV default.
|
||||
- Real HTTP MP3 conversion of one second of synthetic WAV followed by successful
|
||||
FFmpeg decoding to PCM. Encoding took approximately 0.14 seconds in this test;
|
||||
this is not a model synthesis or end-to-end voice latency measurement.
|
||||
- Existing WAV publication/voice/language behavior and PCM streaming/error cases.
|
||||
- Missing encoder, conversion timeout and safe error handling.
|
||||
|
||||
The broader local endpoint suite was also attempted and is not fully green:
|
||||
chat/vision/queue tests failed independently of the audio path. The unchanged
|
||||
HEAD version of `test_chat_accepts_json_larger_than_one_mib` was run separately
|
||||
and reproduces the same 503. No claim that the entire suite passes is made.
|
||||
The initially incomplete new test mock was corrected; all seven focused tests
|
||||
then passed in the prepared image.
|
||||
|
||||
No real voice generation was requested from production during this preparation,
|
||||
and Hermes browser Live Talk has not been verified against an activated build.
|
||||
HTTPS on the WebUI page and the separate TTS provider URL are distinct; this
|
||||
change does not modify either URL or bypass Hermes URL validation.
|
||||
|
||||
## Native installation and restore
|
||||
|
||||
The implementation is ordinary Deck Python code. A fresh native Debian runtime
|
||||
needs `apt-get install ffmpeg` with the distribution's libmp3lame encoder;
|
||||
the current Deck image already contains it. Restore the code from Git plus the
|
||||
normal encrypted state/provider data. No new model weights, credentials or
|
||||
private files are required. Full native install/restore was not tested here.
|
||||
+20
-3
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
import secrets
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit,parse_qs
|
||||
@@ -25,6 +26,18 @@ class APIError(ValueError):
|
||||
def __init__(self,message,status=400,code='invalid_request_error'):
|
||||
super().__init__(message);self.status=status;self.code=code
|
||||
|
||||
def speech_mp3(wav):
|
||||
"""Encode the generated WAV locally; never expose encoder output in errors."""
|
||||
try:
|
||||
result=subprocess.run(['ffmpeg','-nostdin','-hide_banner','-loglevel','error',
|
||||
'-protocol_whitelist','pipe','-f','wav','-i','pipe:0','-map_metadata','-1',
|
||||
'-vn','-threads','1','-codec:a','libmp3lame','-b:a','128k','-f','mp3','pipe:1'],
|
||||
input=wav,capture_output=True,timeout=60)
|
||||
except FileNotFoundError:raise APIError('MP3-Ausgabe benötigt FFmpeg mit libmp3lame.',503,'audio_encoder_unavailable') from None
|
||||
except subprocess.TimeoutExpired:raise APIError('Zeitlimit der MP3-Konvertierung überschritten.',504,'audio_encoding_timeout') from None
|
||||
if result.returncode or not result.stdout:raise APIError('Sprachausgabe konnte nicht als MP3 kodiert werden.',503,'audio_encoding_failed')
|
||||
return result.stdout
|
||||
|
||||
def chat_upstream_error(status, raw, runtime=None):
|
||||
"""Translate verified error formats; never echo arbitrary upstream text."""
|
||||
backend = {'strata': 'Strata', 'llama': 'llama.cpp'}.get(runtime, 'Modell-Backend')
|
||||
@@ -414,8 +427,11 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
started=time.monotonic()
|
||||
if not ep.tts:raise APIError('TTS-Laufzeit nicht eingerichtet.',501)
|
||||
if set(data)-{'model','input','voice','response_format','speed','language'}:raise APIError('Nicht unterstützte TTS-Felder.')
|
||||
audio_format=data.get('response_format','wav')
|
||||
if audio_format not in ('wav','pcm'):raise APIError('response_format=wav oder pcm verwenden.')
|
||||
# Keep the existing WAV default, but honor clients such as Hermes that
|
||||
# explicitly accept MPEG audio without sending response_format.
|
||||
accepts_mp3=any(part.split(';',1)[0].strip().lower()=='audio/mpeg' and not re.search(r';\s*q=0(?:\.0*)?\s*(?:;|$)',part,re.I) for part in self.headers.get('Accept','').split(','))
|
||||
audio_format=data.get('response_format','mp3' if accepts_mp3 else 'wav')
|
||||
if audio_format not in ('wav','pcm','mp3'):raise APIError('response_format=wav, pcm oder mp3 verwenden.')
|
||||
streaming=audio_format=='pcm'
|
||||
from profiles import voice_recipe
|
||||
voice=next((p for p in ep.rows() if p.get('model') and voice_recipe(p['model']) and data.get('model') in [p.get('api_id',p['name']),p['name'],*p.get('api_aliases',[])] and p['enabled']),None)
|
||||
@@ -448,8 +464,9 @@ class APIHandler(BaseHTTPRequestHandler):
|
||||
raise APIError(current['phase'],503,'tts_generation_failed')
|
||||
try:body=backend.audio(job['id'])
|
||||
except (ValueError,OSError):time.sleep(.25);continue
|
||||
if audio_format=='mp3':body=speech_mp3(body)
|
||||
logging.getLogger('athena.tts').warning('TTS request completed job=%s elapsed_seconds=%.3f',job['id'],time.monotonic()-started)
|
||||
self.sent=True;self.send_response(200);self.send_header('Content-Type','audio/wav');self.send_header('Content-Length',str(len(body)));self.send_header('Cache-Control','no-store');self.send_header('Connection','close');self.end_headers();self.wfile.write(body);return
|
||||
self.sent=True;self.send_response(200);self.send_header('Content-Type','audio/mpeg' if audio_format=='mp3' else 'audio/wav');self.send_header('Content-Length',str(len(body)));self.send_header('Cache-Control','no-store');self.send_header('Connection','close');self.end_headers();self.wfile.write(body);return
|
||||
raise APIError('Zeitlimit der Sprachausgabe überschritten. Auftrag in Deck prüfen.',504,'tts_timeout')
|
||||
def speech_stream(self,backend,job,started):
|
||||
chunks=backend.stream_audio(job['id'])
|
||||
|
||||
+25
-1
@@ -302,7 +302,7 @@ class EndpointTests(unittest.TestCase):
|
||||
self.ep.tts=Mock();self.ep.tts.start.return_value={'id':'a'*32};self.ep.tts.status.return_value={'job':{'id':'a'*32,'state':'complete'}};self.ep.tts.audio.return_value=b'RIFF-test-WAVE'
|
||||
self.assertEqual(self.request('/v1/audio/speech',{'model':'audio','input':'hello'})[0],404)
|
||||
self.enable('audio')
|
||||
self.assertEqual(self.request('/v1/audio/speech',{'model':'audio','input':'hello','response_format':'mp3'})[0],400)
|
||||
self.assertEqual(self.request('/v1/audio/speech',{'model':'audio','input':'hello','response_format':'flac'})[0],400)
|
||||
c=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5);c.request('POST','/v1/audio/speech',json.dumps({'model':'audio','input':'hello','voice':'Ryan','response_format':'wav'}),{'Content-Type':'application/json','Authorization':'Bearer '+'A'*32});r=c.getresponse()
|
||||
self.assertEqual(r.status,200);self.assertEqual(r.getheader('Content-Type'),'audio/wav');self.assertEqual(r.read(),b'RIFF-test-WAVE');c.close()
|
||||
self.assertEqual(self.ep.tts.start.call_args.kwargs['speaker'],'Ryan')
|
||||
@@ -310,6 +310,30 @@ class EndpointTests(unittest.TestCase):
|
||||
c=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5);c.request('POST','/v1/audio/speech',json.dumps({'model':'audio','input':'hello','language':'English'}),{'Content-Type':'application/json','Authorization':'Bearer '+'A'*32});r=c.getresponse()
|
||||
self.assertEqual(r.status,200);self.assertEqual(r.read(),b'RIFF-test-WAVE');c.close()
|
||||
self.assertEqual(self.ep.tts.start.call_args.kwargs['language'],'English')
|
||||
def test_tts_mp3_explicit_and_hermes_accept_header(self):
|
||||
from unittest.mock import patch
|
||||
self.rows[-1].update(runnable=True,blockers=[]);self.enable('audio')
|
||||
self.ep.tts=Mock();self.ep.tts.start.return_value={'id':'a'*32};self.ep.tts.status.return_value={'job':{'id':'a'*32,'state':'complete'}};self.ep.tts.audio.return_value=b'RIFF-test-WAVE'
|
||||
for fmt,accept,mime,body in [('mp3','*/*','audio/mpeg',b'ID3-test'),(None,'audio/mpeg','audio/mpeg',b'ID3-test'),('wav','audio/mpeg','audio/wav',b'RIFF-test-WAVE'),(None,'audio/mpeg;q=0','audio/wav',b'RIFF-test-WAVE')]:
|
||||
with self.subTest(fmt=fmt,accept=accept),patch('endpoint.speech_mp3',return_value=b'ID3-test') as encode:
|
||||
payload=dict(model='audio',input='synthetic')
|
||||
if fmt:payload['response_format']=fmt
|
||||
c=http.client.HTTPConnection('127.0.0.1',self.port,timeout=5)
|
||||
c.request('POST','/v1/audio/speech',json.dumps(payload),{'Content-Type':'application/json','Accept':accept,'Authorization':'Bearer '+'A'*32})
|
||||
r=c.getresponse();self.assertEqual(r.status,200);self.assertEqual(r.getheader('Content-Type'),mime);self.assertEqual(int(r.getheader('Content-Length')),len(body));self.assertEqual(r.read(),body);c.close()
|
||||
self.assertEqual(encode.called,mime=='audio/mpeg')
|
||||
def test_tts_real_mp3_roundtrip(self):
|
||||
import io,shutil,subprocess,wave
|
||||
if not shutil.which('ffmpeg'):self.skipTest('FFmpeg required for real MP3 roundtrip')
|
||||
wav=io.BytesIO()
|
||||
with wave.open(wav,'wb') as out:out.setnchannels(1);out.setsampwidth(2);out.setframerate(24000);out.writeframes(b'\0\0'*24000)
|
||||
self.rows[-1].update(runnable=True,blockers=[]);self.enable('audio')
|
||||
self.ep.tts=Mock();self.ep.tts.start.return_value={'id':'a'*32};self.ep.tts.status.return_value={'job':{'id':'a'*32,'state':'complete'}};self.ep.tts.audio.return_value=wav.getvalue()
|
||||
c=http.client.HTTPConnection('127.0.0.1',self.port,timeout=10)
|
||||
c.request('POST','/v1/audio/speech',json.dumps(dict(model='audio',input='synthetic')),{'Content-Type':'application/json','Accept':'audio/mpeg','Authorization':'Bearer '+'A'*32})
|
||||
r=c.getresponse();body=r.read();self.assertEqual(r.status,200);self.assertEqual(r.getheader('Content-Type'),'audio/mpeg');c.close()
|
||||
decoded=subprocess.run(['ffmpeg','-nostdin','-v','error','-i','pipe:0','-f','s16le','-ac','1','-ar','24000','pipe:1'],input=body,capture_output=True,timeout=15)
|
||||
self.assertEqual(decoded.returncode,0);self.assertGreaterEqual(len(decoded.stdout),24000*2)
|
||||
def test_tts_resource_errors_are_service_errors_not_invalid_input(self):
|
||||
self.rows[-1].update(runnable=True,blockers=[]);self.enable('audio')
|
||||
self.ep.tts=Mock();self.ep.tts.start.side_effect=InferenceError('Sprachausgabe wartet auf belegte Ressourcen.')
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import subprocess
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
from endpoint import APIError,speech_mp3
|
||||
|
||||
class SpeechMP3Tests(unittest.TestCase):
|
||||
def test_encoder_failure_does_not_expose_stderr(self):
|
||||
with patch('endpoint.subprocess.run',return_value=SimpleNamespace(returncode=1,stdout=b'',stderr=b'PRIVATE')):
|
||||
with self.assertRaises(APIError) as e:speech_mp3(b'bad')
|
||||
self.assertEqual(e.exception.code,'audio_encoding_failed');self.assertNotIn('PRIVATE',str(e.exception))
|
||||
def test_missing_encoder_and_timeout_are_actionable(self):
|
||||
for error,code in [(FileNotFoundError(),'audio_encoder_unavailable'),(subprocess.TimeoutExpired('ffmpeg',60),'audio_encoding_timeout')]:
|
||||
with self.subTest(code=code),patch('endpoint.subprocess.run',side_effect=error):
|
||||
with self.assertRaises(APIError) as e:speech_mp3(b'wav')
|
||||
self.assertEqual(e.exception.code,code)
|
||||
Reference in new issue
Block a user