fix(tts): OpenRouter-TTS bei transient leerer/5xx-Antwort wiederholen
Preview-Modelle liefern gelegentlich HTTP 200 mit leerem Body (oder 5xx) -> bisher
brach das die ganze Sprech-Runde ab ('empty audio content', 502). Jetzt bis zu 3
Versuche mit linearem Backoff; 4xx (z. B. ungueltige Stimme) wird sofort gemeldet
(kein Retry). Damit klappt das Durchprobieren von Stimmen zuverlaessig (Live-Test:
alle 20 getesteten Gemini-Stimmen inkl. Leda liefern Audio).
Tests: tests/test_openrouter_tts.py (leer->ok, 4xx sofort, alles-leer, 5xx->ok).
Doku-Hinweis in BEDIENUNGSANLEITUNG.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
parent
295f066b6a
commit
03892463a5
3 changed files with 115 additions and 25 deletions
|
|
@ -309,8 +309,11 @@ Verfügbare Stimmen je Modell (laut Anbieter-Doku — Preview, im Zweifel auspro
|
||||||
`echo`, `fable`, `nova`, `onyx`, `sage`, `shimmer`, `verse`.
|
`echo`, `fable`, `nova`, `onyx`, `sage`, `shimmer`, `verse`.
|
||||||
|
|
||||||
> Es gibt keinen Endpoint, der TTS-Stimmen auflistet, und die Modelle sind Preview.
|
> Es gibt keinen Endpoint, der TTS-Stimmen auflistet, und die Modelle sind Preview.
|
||||||
> **Authentischster Test:** Stimme setzen und probieren — ein ungültiger Name liefert
|
> **Authentischster Test:** Stimme setzen und probieren — ein **wirklich** ungültiger Name
|
||||||
> einen OpenRouter-Fehler (HTTP 502 mit Klartext, der oft die gültigen Stimmen nennt).
|
> liefert einen OpenRouter-Fehler (HTTP 502 mit Klartext, der oft die gültigen Stimmen nennt).
|
||||||
|
> Preview-Modelle antworten gelegentlich transient **leer** (HTTP 200, kein Audio) — das
|
||||||
|
> wiederholt der TTS-Provider automatisch (bis zu 3 Versuche), bevor ein Fehler kommt. Eine
|
||||||
|
> einzelne „empty audio content"-Meldung war also meist nur ein Aussetzer; einfach erneut versuchen.
|
||||||
|
|
||||||
Umstellen:
|
Umstellen:
|
||||||
```bash
|
```bash
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,14 @@
|
||||||
|
import asyncio
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from app.providers.tts.base import TTSProvider
|
from app.providers.tts.base import TTSProvider
|
||||||
|
|
||||||
|
# Preview-TTS-Modelle liefern gelegentlich HTTP 200 mit LEEREM Body oder ein
|
||||||
|
# transientes 5xx. Solche Aussetzer kurz wiederholen, statt die Runde abzubrechen.
|
||||||
|
_MAX_ATTEMPTS = 3
|
||||||
|
_RETRY_BACKOFF = 0.6 # Sekunden, linear ansteigend
|
||||||
|
|
||||||
|
|
||||||
class OpenRouterTTSProvider(TTSProvider):
|
class OpenRouterTTSProvider(TTSProvider):
|
||||||
def __init__(self, api_key: str, model: str, voice: str):
|
def __init__(self, api_key: str, model: str, voice: str):
|
||||||
|
|
@ -36,27 +43,37 @@ class OpenRouterTTSProvider(TTSProvider):
|
||||||
timeout = httpx.Timeout(connect=10.0, read=120.0, write=30.0, pool=10.0)
|
timeout = httpx.Timeout(connect=10.0, read=120.0, write=30.0, pool=10.0)
|
||||||
|
|
||||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||||
try:
|
last_error = "OpenRouter TTS returned empty audio content"
|
||||||
response = await client.post(
|
for attempt in range(_MAX_ATTEMPTS):
|
||||||
"https://openrouter.ai/api/v1/audio/speech",
|
try:
|
||||||
headers={
|
response = await client.post(
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"https://openrouter.ai/api/v1/audio/speech",
|
||||||
"Content-Type": "application/json",
|
headers={
|
||||||
},
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
json=payload,
|
"Content-Type": "application/json",
|
||||||
)
|
},
|
||||||
response.raise_for_status()
|
json=payload,
|
||||||
except httpx.HTTPStatusError as exc:
|
)
|
||||||
raise RuntimeError(
|
response.raise_for_status()
|
||||||
f"OpenRouter TTS error {exc.response.status_code}: {exc.response.text}"
|
except httpx.HTTPStatusError as exc:
|
||||||
) from exc
|
status = exc.response.status_code
|
||||||
except httpx.TimeoutException as exc:
|
# 4xx (z. B. ungueltige Stimme) ist nicht transient -> sofort melden.
|
||||||
raise RuntimeError("OpenRouter TTS timeout") from exc
|
if status < 500:
|
||||||
except httpx.HTTPError as exc:
|
raise RuntimeError(
|
||||||
raise RuntimeError(f"OpenRouter TTS transport error: {exc}") from exc
|
f"OpenRouter TTS error {status}: {exc.response.text}"
|
||||||
|
) from exc
|
||||||
|
last_error = f"OpenRouter TTS error {status}: {exc.response.text}"
|
||||||
|
except httpx.TimeoutException:
|
||||||
|
last_error = "OpenRouter TTS timeout"
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise RuntimeError(f"OpenRouter TTS transport error: {exc}") from exc
|
||||||
|
else:
|
||||||
|
if response.content:
|
||||||
|
return response.content
|
||||||
|
# HTTP 200 mit leerem Body -> transienter Aussetzer, erneut versuchen.
|
||||||
|
|
||||||
if not response.content:
|
if attempt < _MAX_ATTEMPTS - 1:
|
||||||
raise RuntimeError("OpenRouter TTS returned empty audio content")
|
await asyncio.sleep(_RETRY_BACKOFF * (attempt + 1))
|
||||||
|
|
||||||
return response.content
|
raise RuntimeError(last_error)
|
||||||
|
|
||||||
|
|
|
||||||
70
tests/test_openrouter_tts.py
Normal file
70
tests/test_openrouter_tts.py
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
"""Tests fuer das Retry-Verhalten des OpenRouter-TTS (transiente leere/5xx-Antworten)."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import app.providers.tts.openrouter as orm
|
||||||
|
from app.providers.tts.openrouter import OpenRouterTTSProvider
|
||||||
|
|
||||||
|
REQ = httpx.Request("POST", "https://openrouter.ai/api/v1/audio/speech")
|
||||||
|
|
||||||
|
|
||||||
|
def _run(coro):
|
||||||
|
return asyncio.run(coro)
|
||||||
|
|
||||||
|
|
||||||
|
def _patch(monkeypatch, responses):
|
||||||
|
"""httpx-POST liefert nacheinander die vorgegebenen Antworten; kein echtes Sleep."""
|
||||||
|
it = iter(responses)
|
||||||
|
calls = {"n": 0}
|
||||||
|
|
||||||
|
async def fake_post(self, url, **kw):
|
||||||
|
calls["n"] += 1
|
||||||
|
return next(it)
|
||||||
|
|
||||||
|
async def no_sleep(*a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
monkeypatch.setattr(httpx.AsyncClient, "post", fake_post)
|
||||||
|
monkeypatch.setattr(orm.asyncio, "sleep", no_sleep)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
def _provider():
|
||||||
|
return OpenRouterTTSProvider("key", "some/model", "Zephyr")
|
||||||
|
|
||||||
|
|
||||||
|
def test_retries_on_empty_then_succeeds(monkeypatch):
|
||||||
|
calls = _patch(monkeypatch, [
|
||||||
|
httpx.Response(200, content=b"", request=REQ), # transienter Aussetzer
|
||||||
|
httpx.Response(200, content=b"AUDIO", request=REQ), # dann echtes Audio
|
||||||
|
])
|
||||||
|
assert _run(_provider().synthesize("Hallo")) == b"AUDIO"
|
||||||
|
assert calls["n"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_4xx_raises_immediately_without_retry(monkeypatch):
|
||||||
|
calls = _patch(monkeypatch, [
|
||||||
|
httpx.Response(400, text="invalid voice", request=REQ),
|
||||||
|
])
|
||||||
|
with pytest.raises(RuntimeError, match="400"):
|
||||||
|
_run(_provider().synthesize("Hallo"))
|
||||||
|
assert calls["n"] == 1 # kein Retry bei 4xx
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_empty_raises_after_attempts(monkeypatch):
|
||||||
|
calls = _patch(monkeypatch, [httpx.Response(200, content=b"", request=REQ)] * orm._MAX_ATTEMPTS)
|
||||||
|
with pytest.raises(RuntimeError, match="empty audio content"):
|
||||||
|
_run(_provider().synthesize("Hallo"))
|
||||||
|
assert calls["n"] == orm._MAX_ATTEMPTS
|
||||||
|
|
||||||
|
|
||||||
|
def test_5xx_then_success(monkeypatch):
|
||||||
|
calls = _patch(monkeypatch, [
|
||||||
|
httpx.Response(503, text="upstream", request=REQ),
|
||||||
|
httpx.Response(200, content=b"OK", request=REQ),
|
||||||
|
])
|
||||||
|
assert _run(_provider().synthesize("Hallo")) == b"OK"
|
||||||
|
assert calls["n"] == 2
|
||||||
Loading…
Add table
Add a link
Reference in a new issue