supertonic.server¶
supertonic.server ¶
Local HTTP server for Supertonic TTS.
This subpackage is optional. It depends on fastapi, uvicorn, and python-multipart which install via the [serve] extra:
pip install supertonic[serve]
It exposes a thin FastAPI wrapper around :class:supertonic.pipeline.TTS designed for local-only integration with n8n, browser extensions, Electron, Unity, Home Assistant, robotics devices, and any client that already speaks the OpenAI Audio Speech API.
Public surface:
- :func:
create_app— build a FastAPI ASGI app (model loads in lifespan). - :class:
ServerState— shared runtime state if you need to inject a pre-loadedTTS(e.g. tests). - :data:
__all__listed below.
Modules:
| Name | Description |
|---|---|
app | FastAPI application factory for |
audio | Audio encoding helpers for the local TTS server. |
routes | HTTP route handlers for |
schemas | Pydantic request/response schemas for the local TTS server. |
styles_store | On-disk store for user-imported voice styles. |
Classes:
| Name | Description |
|---|---|
ServerState | Mutable shared state used by every request handler. |
Functions:
| Name | Description |
|---|---|
create_app | Build a configured FastAPI app. |
ServerState ¶
ServerState(
model: str = DEFAULT_MODEL,
*,
tts: Optional["TTS"] = None,
custom_styles_dir: Optional[Path] = None,
custom_styles: Optional[Dict[str, Path]] = None
)
Mutable shared state used by every request handler.
Attributes:
| Name | Type | Description |
|---|---|---|
model | Model name to load (e.g. | |
tts | Loaded :class: | |
custom_styles |
| |
custom_styles_dir | Directory on disk that backs | |
synth_lock | Serializes ONNX Runtime inference across threads (FastAPI executes sync handlers in a threadpool). | |
is_ready |
|
Source code in supertonic/server/app.py
custom_styles_dir instance-attribute ¶
custom_styles_dir = (
Path(custom_styles_dir)
if custom_styles_dir
else default_custom_styles_dir(model)
)
create_app ¶
create_app(
*,
state: Optional[ServerState] = None,
model: str = DEFAULT_MODEL,
custom_styles_dir: Optional[Path] = None,
cors_origins: Optional[Iterable[str]] = None
) -> FastAPI
Build a configured FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state | Optional[ServerState] | Pre-built state to reuse. When provided, the lifespan does not instantiate :class: | None |
model | str | Model name to load if | DEFAULT_MODEL |
custom_styles_dir | Optional[Path] | Override the on-disk location of user-imported voice styles. Defaults to :func: | None |
cors_origins | Optional[Iterable[str]] | If non-empty, install | None |
Source code in supertonic/server/app.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
app ¶
FastAPI application factory for supertonic serve.
Designed so that:
cmd_servebuilds the app, uvicorn drives it.- Tests can inject a pre-built :class:
ServerState(with a fakeTTS) so no real ONNX session is created. - Anyone embedding the server inside a larger ASGI app can mount the
FastAPIreturned by :func:create_app.
Classes:
| Name | Description |
|---|---|
StyleImportSizeLimit | ASGI middleware: reject |
ServerState | Mutable shared state used by every request handler. |
Functions:
| Name | Description |
|---|---|
create_app | Build a configured FastAPI app. |
Attributes:
| Name | Type | Description |
|---|---|---|
logger | |
StyleImportSizeLimit ¶
StyleImportSizeLimit(app, max_bytes: int)
ASGI middleware: reject POST /v1/styles/import when the request Content-Length exceeds :data:MAX_STYLE_IMPORT_BYTES.
The check runs before FastAPI's dependency machinery starts buffering the multipart body, so a malicious or accidental oversized upload is rejected at the headers stage. Requests without Content-Length (chunked transfer encoding) fall through; the handler's read(MAX+1) enforces the same cap there.
Attributes:
| Name | Type | Description |
|---|---|---|
app | | |
max_bytes | |
Source code in supertonic/server/app.py
ServerState ¶
ServerState(
model: str = DEFAULT_MODEL,
*,
tts: Optional["TTS"] = None,
custom_styles_dir: Optional[Path] = None,
custom_styles: Optional[Dict[str, Path]] = None
)
Mutable shared state used by every request handler.
Attributes:
| Name | Type | Description |
|---|---|---|
model | Model name to load (e.g. | |
tts | Loaded :class: | |
custom_styles |
| |
custom_styles_dir | Directory on disk that backs | |
synth_lock | Serializes ONNX Runtime inference across threads (FastAPI executes sync handlers in a threadpool). | |
is_ready |
|
Source code in supertonic/server/app.py
custom_styles_dir instance-attribute ¶
custom_styles_dir = (
Path(custom_styles_dir)
if custom_styles_dir
else default_custom_styles_dir(model)
)
create_app ¶
create_app(
*,
state: Optional[ServerState] = None,
model: str = DEFAULT_MODEL,
custom_styles_dir: Optional[Path] = None,
cors_origins: Optional[Iterable[str]] = None
) -> FastAPI
Build a configured FastAPI app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state | Optional[ServerState] | Pre-built state to reuse. When provided, the lifespan does not instantiate :class: | None |
model | str | Model name to load if | DEFAULT_MODEL |
custom_styles_dir | Optional[Path] | Override the on-disk location of user-imported voice styles. Defaults to :func: | None |
cors_origins | Optional[Iterable[str]] | If non-empty, install | None |
Source code in supertonic/server/app.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
styles_store ¶
On-disk store for user-imported voice styles.
Imported voice styles live alongside the bundled built-ins, scoped per model so that a voice imported while serving supertonic-3 is not silently used by supertonic-2:
~/.cache/supertonic3/custom_styles/<name>.json # supertonic-3
~/.cache/supertonic2/custom_styles/<name>.json # supertonic-2
~/.cache/supertonic/custom_styles/<name>.json # supertonic v1
This matches how the bundled voices are organized (each model's voice_styles/ lives under its own cache dir) and keeps custom JSONs out of voice_styles/ so the SDK's :func:list_available_voice_style_names remains unchanged.
This module deliberately stays small: it never loads the styles itself — that work belongs to :func:supertonic.loader.load_voice_style_from_json_file, which already enforces the JSON schema via :func:supertonic.utils.validate_voice_style_format. We just decide where files live and how their names are sanitized.
Classes:
| Name | Description |
|---|---|
InvalidStyleName | Raised when an imported style name fails sanitization. |
StyleNameConflict | Raised when an imported style would overwrite an existing one. |
Functions:
| Name | Description |
|---|---|
default_custom_styles_dir | Resolve the on-disk directory for user-imported voice styles. |
sanitize_name | |
scan | Return |
save | Persist a validated style payload to |
Attributes:
| Name | Type | Description |
|---|---|---|
logger | |
default_custom_styles_dir ¶
default_custom_styles_dir(
model: str = DEFAULT_MODEL,
) -> Path
Resolve the on-disk directory for user-imported voice styles.
Priority:
$SUPERTONIC_CUSTOM_STYLES_DIR— explicit override, applies to every model (the user opted into a single shared location).<model cache dir>/custom_styles/— e.g.~/.cache/supertonic3/ custom_styles/forsupertonic-3. Respects$SUPERTONIC_CACHE_DIRthrough :func:supertonic.loader.get_cache_dir.
Source code in supertonic/server/styles_store.py
InvalidStyleName ¶
Bases: ValueError
Raised when an imported style name fails sanitization.
StyleNameConflict ¶
Bases: ValueError
Raised when an imported style would overwrite an existing one.
sanitize_name ¶
scan ¶
Return {stem: path} for every well-formed JSON in directory.
A file that fails :func:validate_voice_style_format is skipped with a warning rather than crashing startup — the server should still come up.
Source code in supertonic/server/styles_store.py
save ¶
save(
directory: Path,
name: str,
payload: dict,
*,
builtin_names: Iterable[str] = (),
overwrite: bool = False
) -> Path
Persist a validated style payload to directory / f"{name}.json".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory | Path | target directory (created if missing). | required |
name | str | requested style name; sanitized via :func: | required |
payload | dict | parsed JSON; must pass :func: | required |
builtin_names | Iterable[str] | names reserved by the bundled model; conflict → 400. | () |
overwrite | bool | if False, conflict with an existing custom name → 409. | False |
Returns:
| Type | Description |
|---|---|
Path | The path the style was written to. |
Source code in supertonic/server/styles_store.py
audio ¶
Audio encoding helpers for the local TTS server.
Only formats reachable through soundfile (libsndfile) at the model's native 44.1 kHz are supported, so the server adds no extra system dependencies beyond what the SDK already requires. MP3 / AAC / Opus are intentionally rejected with a clear error rather than silently emitting WAV — clients should detect the unsupported format and fall back.
(Opus is excluded for now because libsndfile's OGG/OPUS encoder only accepts 8/12/16/24/48 kHz, and we'd rather error clearly than ship a broken format. Re-add it once we have a resampling step.)
Classes:
| Name | Description |
|---|---|
UnsupportedAudioFormat | Raised when the caller asks for a format we cannot encode. |
Functions:
| Name | Description |
|---|---|
format_to_mime | |
encode_audio | Encode a synthesized waveform into |
duration_seconds | |
coerce_response_format | Validate and normalize a user-supplied |
Attributes:
| Name | Type | Description |
|---|---|---|
SUPPORTED_FORMATS | |
UnsupportedAudioFormat ¶
Bases: ValueError
Raised when the caller asks for a format we cannot encode.
format_to_mime ¶
encode_audio ¶
Encode a synthesized waveform into fmt bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wav | ndarray | ndarray of shape | required |
sample_rate | int | model sample rate (e.g. 44100). | required |
fmt | str | one of :data: | required |
Source code in supertonic/server/audio.py
duration_seconds ¶
coerce_response_format ¶
Validate and normalize a user-supplied response_format.
None → "wav" (sensible default for local-host integrations). An unsupported value raises :class:UnsupportedAudioFormat so handlers can return a 400 with a stable error code.
Source code in supertonic/server/audio.py
routes ¶
HTTP route handlers for supertonic serve.
The route surface is intentionally narrow and follows two conventions so that existing clients work with minimal changes:
- Native namespace under
/v1/...for first-class Supertonic features. - OpenAI Audio Speech alias at
POST /v1/audio/speechso any client that already speaks the OpenAI API (n8n OpenAI node, openai-python, many browser extensions, Electron tools) can swap the base URL.
Errors use the OpenAI-shaped envelope::
{ "error": { "message": "...", "type": "...", "code": "..." } }
so that downstream error parsers keep working.
Classes:
| Name | Description |
|---|---|
UnknownVoice | Voice name does not match any built-in or imported style. |
Functions:
| Name | Description |
|---|---|
register_routes | Attach all |
Attributes:
| Name | Type | Description |
|---|---|---|
logger | | |
MAX_STYLE_IMPORT_BYTES | |
UnknownVoice ¶
Bases: LookupError
Voice name does not match any built-in or imported style.
register_routes ¶
Attach all /v1/... routes to app.
Called from :func:supertonic.server.app.create_app after the lifespan and app.state.server_state have been set up.
Source code in supertonic/server/routes.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
schemas ¶
Pydantic request/response schemas for the local TTS server.
The wire format mirrors common TTS-server conventions so existing clients (n8n HTTP nodes, openedai-speech-compatible browser extensions, OpenAI SDKs) can talk to supertonic serve with little or no code change.
Classes:
| Name | Description |
|---|---|
TTSRequest | Native synthesis request — |
OpenAISpeechRequest | OpenAI Audio Speech-compatible request — |
BatchItem | |
BatchDefaults | |
BatchRequest | |
BatchResultItem | |
BatchResponse | |
StyleInfo | |
StylesResponse | |
StyleImportJSON | JSON-body variant of |
StyleImportResponse | |
HealthResponse | |
ErrorDetail | |
ErrorEnvelope | OpenAI-shaped error envelope so integrators can reuse existing parsers. |
TTSRequest ¶
Bases: BaseModel
Native synthesis request — POST /v1/tts.
Attributes:
| Name | Type | Description |
|---|---|---|
text | str | |
voice | str | |
lang | Optional[str] | |
speed | Optional[float] | |
steps | Optional[int] | |
max_chunk_length | Optional[int] | |
silence_duration | Optional[float] | |
response_format | Optional[str] | |
text class-attribute instance-attribute ¶
text: str = Field(
..., min_length=1, description="Text to synthesize"
)
voice class-attribute instance-attribute ¶
voice: str = Field(
"M1",
description="Voice style name (built-in or imported)",
)
lang class-attribute instance-attribute ¶
max_chunk_length class-attribute instance-attribute ¶
silence_duration class-attribute instance-attribute ¶
response_format class-attribute instance-attribute ¶
response_format: Optional[str] = Field(
None, description=f"One of: {join(SUPPORTED_FORMATS)}"
)
OpenAISpeechRequest ¶
Bases: BaseModel
OpenAI Audio Speech-compatible request — POST /v1/audio/speech.
Field names match the OpenAI API so existing clients (n8n's OpenAI node, openai-python, openedai-speech-style browser extensions) only need to swap the base URL.
Methods:
| Name | Description |
|---|---|
valid_models | |
Attributes:
| Name | Type | Description |
|---|---|---|
model | str | |
input | str | |
voice | str | |
response_format | Optional[str] | |
speed | Optional[float] | |
lang | Optional[str] | |
BatchItem ¶
BatchDefaults ¶
BatchRequest ¶
Bases: BaseModel
Attributes:
| Name | Type | Description |
|---|---|---|
items | List[BatchItem] | |
response_format | Optional[str] | |
defaults | Optional[BatchDefaults] | |
BatchResultItem ¶
Bases: BaseModel
Attributes:
| Name | Type | Description |
|---|---|---|
audio_base64 | str | |
duration_s | float | |
format | str | |
sample_rate | int | |
BatchResponse ¶
StyleInfo ¶
StylesResponse ¶
StyleImportJSON ¶
StyleImportResponse ¶
HealthResponse ¶
ErrorDetail ¶
ErrorEnvelope ¶
Bases: BaseModel
OpenAI-shaped error envelope so integrators can reuse existing parsers.
Attributes:
| Name | Type | Description |
|---|---|---|
error | ErrorDetail | |