Skip to content
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,15 @@ with client.tts.stream_with_timestamps(text="Long content...", format="opus") as

Text without words (only punctuation, or a sound tag such as `[sigh]`) still produces audio, but the API has no timings for it: `segments` is then empty and `result.duration` is `None`.

`s1` and `transcribe-1` are deprecated and will be retired on December 31, 2026. After that date, requests that specify them are served by `s2.1-pro` and `transcribe-1-pro`. Using a deprecated model emits a `FutureWarning`; with Python's default warning filters it is shown once per calling line. A coroutine scheduled with `asyncio.create_task` or `gather` runs from asyncio's code, so its warning points there and is shown once in all. See [Model Deprecations](https://docs.fish.audio/developer-guide/models-pricing/deprecations).

[Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/text-to-speech)

### Speech-to-Text

```python
# transcribe-1-pro is the recommended model; without model, the request runs on transcribe-1.
# transcribe-1-pro is the recommended model; without model, the request runs on transcribe-1,
# which is deprecated and will be retired on December 31, 2026.
with open("meeting.wav", "rb") as f:
result = client.asr.transcribe(audio=f.read(), model="transcribe-1-pro")

Expand Down
35 changes: 33 additions & 2 deletions src/fishaudio/resources/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,25 @@
ASRTurnDetection,
TurnDetectionMode,
)
from fishaudio.types.shared import DEPRECATED_ASR_MODELS, warn_if_deprecated_model

from .asr_realtime import REALTIME_PATH, ASRRealtimeStream, AsyncASRRealtimeStream


def _requested_model(
model: Optional[str], request_options: Optional[RequestOptions]
) -> Optional[str]:
"""Return the model the request names: the argument, else a model header."""
if model is not None:
return model
if request_options is None:
return None
for name, value in request_options.additional_headers.items():
if name.lower() == "model":
return value
return None


def _realtime_config(
config: ASRRealtimeConfig,
*,
Expand Down Expand Up @@ -85,7 +100,11 @@ def transcribe(
model: ASR model, e.g. "transcribe-1-pro" (recommended). Sent as the
``model`` header and takes precedence over one in request_options.
If not provided and request_options sets no ``model`` header, the
request runs on the API's default model, transcribe-1
request runs on the API's default model, transcribe-1.
transcribe-1 is deprecated and will be retired on December 31,
2026; after that date, the requests it serves, including those
with no ``model`` header, are served by transcribe-1-pro.
Passing "transcribe-1" emits a FutureWarning.
request_options: Request-level overrides

Returns:
Expand All @@ -107,6 +126,10 @@ def transcribe(
print(f"{segment.start}-{segment.end}: {segment.text}")
```
"""
warn_if_deprecated_model(
_requested_model(model, request_options), DEPRECATED_ASR_MODELS
)

# Build request payload
payload = {
"audio": audio,
Expand Down Expand Up @@ -272,7 +295,11 @@ async def transcribe(
model: ASR model, e.g. "transcribe-1-pro" (recommended). Sent as the
``model`` header and takes precedence over one in request_options.
If not provided and request_options sets no ``model`` header, the
request runs on the API's default model, transcribe-1
request runs on the API's default model, transcribe-1.
transcribe-1 is deprecated and will be retired on December 31,
2026; after that date, the requests it serves, including those
with no ``model`` header, are served by transcribe-1-pro.
Passing "transcribe-1" emits a FutureWarning.
request_options: Request-level overrides

Returns:
Expand All @@ -294,6 +321,10 @@ async def transcribe(
print(f"{segment.start}-{segment.end}: {segment.text}")
```
"""
warn_if_deprecated_model(
_requested_model(model, request_options), DEPRECATED_ASR_MODELS
)

# Build request payload
payload = {
"audio": audio,
Expand Down
70 changes: 55 additions & 15 deletions src/fishaudio/resources/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import asyncio
import base64
import binascii
import functools
import inspect
import json
from collections.abc import AsyncIterable, Iterable, Iterator
from concurrent.futures import ThreadPoolExecutor
from typing import Optional, Union
from typing import Any, Callable, Optional, TypeVar, Union, cast

import ormsgpack
from httpx_ws import AsyncWebSocketSession, WebSocketSession, aconnect_ws, connect_ws
Expand Down Expand Up @@ -45,6 +47,26 @@

from .realtime import aiter_websocket_audio, iter_websocket_audio

_F = TypeVar("_F", bound=Callable[..., Any])


def _warns_when_called(stream_function: _F) -> _F:
"""Check the model when the method is called, not when its stream is used.

The body of a generator function runs only when its stream is first
iterated, so a check inside it would warn at the consumer's line, or never.
"""
signature = inspect.signature(stream_function)

@functools.wraps(stream_function)
def call(*args: Any, **kwargs: Any) -> Any:
bound = signature.bind(*args, **kwargs)
bound.apply_defaults()
warn_if_deprecated_model(bound.arguments["model"])
return stream_function(*args, **kwargs)

return cast("_F", call)


def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest:
"""Convert TTSConfig to TTSRequest with text."""
Expand Down Expand Up @@ -159,7 +181,9 @@ def stream(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -251,7 +275,9 @@ def convert(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -315,7 +341,9 @@ def stream_with_timestamps(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -400,7 +428,9 @@ def convert_with_timestamps(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -435,6 +465,7 @@ def convert_with_timestamps(
request_options=request_options,
).collect()

@_warns_when_called
def stream_websocket(
self,
text_stream: Iterable[Union[str, TextEvent, FlushEvent]],
Expand Down Expand Up @@ -462,7 +493,9 @@ def stream_websocket(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
max_workers: ThreadPoolExecutor workers for concurrent sender
ws_options: WebSocket connection options for configuring timeouts, message size limits, etc.
Useful for long-running generations that may exceed default timeout values.
Expand Down Expand Up @@ -530,8 +563,6 @@ def text_generator():
f.write(audio_chunk)
```
"""
warn_if_deprecated_model(model)

# Build TTSRequest from config
tts_request = _config_to_tts_request(config, text="")

Expand Down Expand Up @@ -622,7 +653,9 @@ async def stream(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -715,7 +748,9 @@ async def convert(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -780,7 +815,9 @@ async def stream_with_timestamps(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -866,7 +903,9 @@ async def convert_with_timestamps(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -902,6 +941,7 @@ async def convert_with_timestamps(
)
return await stream.collect()

@_warns_when_called
async def stream_websocket(
self,
text_stream: AsyncIterable[Union[str, TextEvent, FlushEvent]],
Expand All @@ -928,7 +968,9 @@ async def stream_websocket(
latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided)
speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided)
config: TTS configuration (audio settings, voice, model parameters)
model: TTS model to use
model: TTS model to use. Deprecated models ("s1", which will be
retired on December 31, 2026, and "speech-1.5"/"speech-1.6")
emit a FutureWarning.
ws_options: WebSocket connection options for configuring timeouts, message size limits, etc.
Useful for long-running generations that may exceed default timeout values.
See WebSocketOptions class for available parameters.
Expand Down Expand Up @@ -995,8 +1037,6 @@ async def text_generator():
await f.write(audio_chunk)
```
"""
warn_if_deprecated_model(model)

# Build TTSRequest from config
tts_request = _config_to_tts_request(config, text="")

Expand Down
92 changes: 79 additions & 13 deletions src/fishaudio/types/shared.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""Shared types used across the SDK."""

import sys
import warnings
from typing import Generic, Literal, TypeVar
from collections.abc import Mapping
from types import FrameType
from typing import Generic, Literal, Optional, TypeVar

from pydantic import BaseModel

Expand All @@ -24,18 +27,81 @@ class PaginatedResponse(BaseModel, Generic[T]):
# Model types
Model = Literal["s1", "s2-pro", "s2.1-pro", "s2.1-pro-free", "drama-3"]

# Deprecated models
DEPRECATED_MODELS = {"speech-1.5", "speech-1.6"}


def warn_if_deprecated_model(model: str) -> None:
"""Emit a deprecation warning if a legacy model is used."""
if model in DEPRECATED_MODELS:
warnings.warn(
f"Model '{model}' is deprecated. Use 's2.1-pro' instead.",
DeprecationWarning,
stacklevel=3,
)
# Deprecated models, mapped to the warning shown when one is used.
_SPEECH_1_MESSAGE = "Model '{model}' is deprecated. Use 's2.1-pro' instead."
_S1_MESSAGE = (
"Model 's1' is deprecated and will be retired on December 31, 2026. "
"After that date, requests that specify 's1' are served by 's2.1-pro' "
"and billed as 's2.1-pro'. Use 's2.1-pro' instead."
)
_TRANSCRIBE_1_MESSAGE = (
"Model 'transcribe-1' is deprecated and will be retired on December 31, "
"2026. After that date, requests that specify 'transcribe-1' are served "
"by 'transcribe-1-pro' and billed as 'transcribe-1-pro'. "
"Use 'transcribe-1-pro' instead."
)

DEPRECATED_TTS_MODELS: dict[str, str] = {
"speech-1.5": _SPEECH_1_MESSAGE.format(model="speech-1.5"),
"speech-1.6": _SPEECH_1_MESSAGE.format(model="speech-1.6"),
"s1": _S1_MESSAGE,
}
DEPRECATED_ASR_MODELS: dict[str, str] = {
"transcribe-1": _TRANSCRIBE_1_MESSAGE,
}
# All deprecated model IDs (TTS and ASR).
DEPRECATED_MODELS = frozenset(DEPRECATED_TTS_MODELS) | frozenset(DEPRECATED_ASR_MODELS)


def _in_package(frame: FrameType) -> bool:
# By module name, not file path: a path such as "src//fishaudio" or a
# symlink would not match a file path prefix.
name = frame.f_globals.get("__name__")
# exec() with other globals, or interpreter shutdown, can leave no str name.
if not isinstance(name, str):
return False
return name == "fishaudio" or name.startswith("fishaudio.")


def _stacklevel_outside_package() -> int:
"""Return the stacklevel of the first frame outside the fishaudio package.

Counted for a ``warnings.warn`` call made by the caller of this function,
so the warning points at the user's code whichever SDK method was called.
"""
getframe = getattr(sys, "_getframe", None)
if getframe is None: # Not CPython: the caller of the SDK method, usually.
return 3
level = 1
frame: Optional[FrameType] = getframe(1) # The function that calls warnings.warn.
while frame is not None and _in_package(frame):
frame = frame.f_back
level += 1
return level


def warn_if_deprecated_model(
model: Optional[str], deprecated: Mapping[str, str] = DEPRECATED_TTS_MODELS
) -> None:
"""Emit a FutureWarning if ``model`` is a key of ``deprecated``.

``deprecated`` maps the deprecated models of one API to their messages:
DEPRECATED_TTS_MODELS (the default) or DEPRECATED_ASR_MODELS.

FutureWarning, unlike DeprecationWarning, is shown by default in any
module, so applications that call the SDK see it. The warning is
attributed to the line that called the SDK method (for an async method,
the line that awaited it), so Python's warning filters decide how often it
is shown: by default once per such line, so a loop does not repeat it. A
coroutine scheduled with asyncio.create_task or gather runs from asyncio's
own code, so its warning is attributed there and shown once in all.
"""
if model is None:
return
message = deprecated.get(model)
if message is None:
return
warnings.warn(message, FutureWarning, stacklevel=_stacklevel_outside_package())


# Audio format types
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_tts_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_tts_with_prosody(self, client, save_audio):
# Write to output directory
save_audio(audio, "test_prosody.mp3")

@pytest.mark.filterwarnings("ignore::DeprecationWarning")
@pytest.mark.filterwarnings("ignore::FutureWarning")
def test_tts_with_different_models(self, client, save_audio):
"""Test TTS with different models."""
models = get_args(Model)
Expand Down
Loading