Skip to content

Commit 180cd5d

Browse files
fix(api): pcm at 24 kHz, reject unavailable formats before synthesis, declare openai test dep
- pcm is resampled to 24 kHz as OpenAI defines it (LuxTTS renders at 48 kHz). - response_format is validated against what this server can actually encode (libsndfile formats, ffmpeg presence) before any model is touched. - The openai SDK joins the dev install line in both justfile setup-python recipes; the test module importorskips it so a bare venv still collects. Co-authored-by: capy-ai-staging[bot] <305915985+capy-ai-staging[bot]@users.noreply.github.com>
1 parent 4df6405 commit 180cd5d

4 files changed

Lines changed: 37 additions & 8 deletions

File tree

‎backend/routes/openai_compat.py‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
The text to speak, in the profile's language.
2121
``response_format``
2222
``wav`` (default), ``mp3``, ``flac``, ``opus``, ``pcm`` (raw 16-bit
23-
little-endian mono at the engine's sample rate), ``aac`` (needs ffmpeg).
23+
little-endian mono at 24 kHz, as OpenAI defines it), ``aac`` (needs ffmpeg).
2424
``speed``
2525
0.25-4.0, applied as a pitch-preserving time stretch after synthesis.
2626
``instructions``
@@ -66,6 +66,7 @@
6666
"aac": (["-c:a", "aac", "-b:a", "128k", "-f", "adts"], "audio/aac"),
6767
}
6868
RESPONSE_FORMATS = (*_SOUNDFILE_FORMATS, "pcm", *_FFMPEG_FORMATS)
69+
PCM_SAMPLE_RATE = 24000
6970

7071
# Voicebox launched long after the OpenAI `created` epoch convention; a fixed
7172
# value keeps the field deterministic for clients that display it.
@@ -115,7 +116,9 @@ class SpeechRequest(BaseModel):
115116

116117

117118
def _available_formats() -> list[str]:
118-
formats = [f for f in RESPONSE_FORMATS if f not in _FFMPEG_FORMATS]
119+
"""Formats this server can actually produce, given its libsndfile build and PATH."""
120+
formats = ["pcm"]
121+
formats.extend(f for f, (fmt, _, _) in _SOUNDFILE_FORMATS.items() if fmt in sf.available_formats())
119122
if shutil.which("ffmpeg"):
120123
formats.extend(_FFMPEG_FORMATS)
121124
return formats
@@ -195,6 +198,12 @@ def encode_audio(audio: np.ndarray, sample_rate: int, response_format: str) -> t
195198
import io
196199

197200
if response_format == "pcm":
201+
# OpenAI defines pcm as headerless 16-bit mono at 24 kHz; the body
202+
# carries no rate, so engines at another rate (LuxTTS: 48 kHz) must be resampled.
203+
if sample_rate != PCM_SAMPLE_RATE:
204+
import librosa
205+
206+
audio = librosa.resample(audio.astype(np.float32), orig_sr=sample_rate, target_sr=PCM_SAMPLE_RATE)
198207
pcm = np.clip(audio, -1.0, 1.0)
199208
return (pcm * 32767).astype("<i2").tobytes(), "audio/pcm"
200209

@@ -300,10 +309,11 @@ async def _create_speech(request: Request, db: Session) -> Response:
300309
param = ".".join(str(p) for p in first.get("loc", ())) or None
301310
raise OpenAIError(400, f"Invalid value for '{param}': {first['msg']}", param=param) from exc
302311

303-
if data.response_format not in RESPONSE_FORMATS:
312+
if data.response_format not in _available_formats():
304313
raise OpenAIError(
305314
400,
306-
f"Invalid response_format '{data.response_format}'. Supported: {', '.join(RESPONSE_FORMATS)}.",
315+
f"Invalid response_format '{data.response_format}'. Supported on this server: "
316+
f"{', '.join(_available_formats())}.",
307317
param="response_format",
308318
code="unsupported_format",
309319
)

‎backend/tests/test_openai_compat.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import pytest
1616
import soundfile as sf
1717
from fastapi import FastAPI
18-
from openai import AsyncOpenAI, BadRequestError, NotFoundError
1918

2019
import backend.backends as backends
2120
import backend.mcp_server.resolve as resolve_mod
@@ -25,6 +24,9 @@
2524
from backend.database import get_db
2625
from backend.routes import openai_compat
2726

27+
openai = pytest.importorskip("openai", reason="the openai SDK is a test-only dependency (installed by `just setup`)")
28+
AsyncOpenAI, BadRequestError, NotFoundError = openai.AsyncOpenAI, openai.BadRequestError, openai.NotFoundError
29+
2830
SAMPLE_RATE = 24000
2931
DURATION_S = 1.0
3032

@@ -298,6 +300,23 @@ def preset_profile(explicit, client_id, db):
298300
# ─── encoder unit coverage ────────────────────────────────────────────────
299301

300302

303+
def test_encode_audio_pcm_resamples_to_24k():
304+
content, media_type = openai_compat.encode_audio(np.zeros(48000, dtype=np.float32), 48000, "pcm")
305+
assert media_type == "audio/pcm"
306+
assert len(content) == 24000 * 2
307+
308+
309+
async def test_aac_without_ffmpeg_is_rejected_before_synthesis(raw_client, app, monkeypatch):
310+
monkeypatch.setattr(openai_compat.shutil, "which", lambda name: None)
311+
response = await raw_client.post(
312+
"/v1/audio/speech",
313+
json={"model": "tts-1", "voice": "Morgan", "input": "Hi", "response_format": "aac"},
314+
)
315+
assert response.status_code == 400
316+
assert response.json()["error"]["code"] == "unsupported_format"
317+
assert "text" not in app.state.calls
318+
319+
301320
def test_encode_audio_wav_roundtrip():
302321
audio = np.zeros(2400, dtype=np.float32)
303322
content, media_type = openai_compat.encode_audio(audio, 24000, "wav")

‎docs/content/docs/overview/mcp-server.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ How the OpenAI fields map onto Voicebox:
267267
| `voice` | A voice profile, by name (case-insensitive) or id. Omit it and the [voice resolution](#voice-resolution) chain applies: the `X-Voicebox-Client-Id` binding, then the default playback voice. There are no built-in `alloy`/`nova` voices — create a profile (a Kokoro preset profile named "Alloy" works fine). |
268268
| `model` | A TTS engine (`qwen`, `qwen_custom_voice`, `luxtts`, `chatterbox`, `chatterbox_turbo`, `tada`, `kokoro`) or a model variant such as `qwen-tts-0.6B`. OpenAI's own ids `tts-1`, `tts-1-hd` and `gpt-4o-mini-tts` are accepted as aliases for "the engine configured on the profile", so unchanged client code works. `GET /v1/models` lists every accepted id. The model must already be downloaded (Voicebox → Models). |
269269
| `input` | The text to speak, up to 10,000 characters, in the profile's language. Long text is chunked at sentence boundaries like the rest of Voicebox. |
270-
| `response_format` | `wav` (default), `mp3`, `flac`, `opus`, `pcm` (raw 16-bit little-endian mono at the engine's sample rate, 24 kHz for most engines) and `aac` (requires `ffmpeg` on the server's PATH). |
270+
| `response_format` | `wav` (default), `mp3`, `flac`, `opus`, `pcm` (raw 16-bit little-endian mono at 24 kHz, as OpenAI defines it; engines running at another rate are resampled) and `aac` (requires `ffmpeg` on the server's PATH). |
271271
| `speed` | `0.25`–`4.0`. Applied as a pitch-preserving time stretch after synthesis. |
272272
| `instructions` | Forwarded as the engine's instruct prompt where supported (Qwen). |
273273

‎justfile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ setup-python:
134134
"{{ python }}" -m pip install --no-deps mlx-audio==0.4.1
135135
fi
136136
"{{ python }}" -m pip install git+https://github.com/QwenLM/Qwen3-TTS.git
137-
"{{ python }}" -m pip install pyinstaller ruff pytest pytest-asyncio -q
137+
"{{ python }}" -m pip install pyinstaller ruff pytest pytest-asyncio openai -q
138138
echo "Python environment ready."
139139
140140
[windows]
@@ -208,7 +208,7 @@ setup-python:
208208
Invoke-Pip install --no-deps chatterbox-tts; \
209209
Invoke-Pip install --no-deps hume-tada; \
210210
Invoke-Pip install git+https://github.com/QwenLM/Qwen3-TTS.git; \
211-
Invoke-Pip install pyinstaller ruff pytest pytest-asyncio -q; \
211+
Invoke-Pip install pyinstaller ruff pytest pytest-asyncio openai -q; \
212212
Write-Host "Python environment ready."
213213

214214
# Install JavaScript dependencies

0 commit comments

Comments
 (0)