From 6c08169772966af5c6ede625750c6cc7faf58d07 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:01:41 -0800 Subject: [PATCH 1/6] fix: warn when a retiring model (s1, transcribe-1) is used s1 and transcribe-1 will be retired on December 31, 2026; after that date the API serves requests that name them with s2.1-pro and transcribe-1-pro. Passing either model now emits a warning that says so. - Warn on every TTS entry point (stream, convert, stream_websocket; sync and async) and on ASR transcribe (sync and async), including a model set through a request_options "model" header. - Use FutureWarning for all deprecated models, including speech-1.5/1.6, which used DeprecationWarning. Python hides DeprecationWarning unless it is attributed to __main__, so applications calling the SDK from their own modules never saw it. - Warn once per model per process, so streaming loops do not repeat it. A filter that turns the warning into an error still raises every call. - Point the warning at the caller's code instead of an SDK frame. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- src/fishaudio/resources/asr.py | 31 +- src/fishaudio/resources/tts.py | 24 +- src/fishaudio/types/shared.py | 73 ++++- tests/integration/test_tts_integration.py | 2 +- .../test_tts_websocket_integration.py | 13 +- tests/unit/test_deprecated_models.py | 282 ++++++++++++++++++ tests/unit/test_tts.py | 1 + tests/unit/test_tts_realtime.py | 4 +- 9 files changed, 407 insertions(+), 28 deletions(-) create mode 100644 tests/unit/test_deprecated_models.py diff --git a/README.md b/README.md index fbd31e8..8e8a11e 100644 --- a/README.md +++ b/README.md @@ -157,12 +157,15 @@ for chunk in client.tts.stream(text="Long content..."): audio = client.tts.stream(text="Hello!").collect() ``` +`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`. The SDK emits a `FutureWarning` the first time a deprecated model is used in a process. 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") diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 514c5ac..4feaa4c 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -23,10 +23,25 @@ ASRTurnDetection, TurnDetectionMode, ) +from fishaudio.types.shared import 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, *, @@ -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 once per process. request_options: Request-level overrides Returns: @@ -107,6 +126,8 @@ def transcribe( print(f"{segment.start}-{segment.end}: {segment.text}") ``` """ + warn_if_deprecated_model(_requested_model(model, request_options)) + # Build request payload payload = { "audio": audio, @@ -272,7 +293,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 once per process. request_options: Request-level overrides Returns: @@ -294,6 +319,8 @@ async def transcribe( print(f"{segment.start}-{segment.end}: {segment.text}") ``` """ + warn_if_deprecated_model(_requested_model(model, request_options)) + # Build request payload payload = { "audio": audio, diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 8326c79..071e931 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -97,7 +97,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 once per process. request_options: Request-level overrides Returns: @@ -189,7 +191,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 once per process. request_options: Request-level overrides Returns: @@ -251,7 +255,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 once per process. 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. @@ -411,7 +417,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 once per process. request_options: Request-level overrides Returns: @@ -504,7 +512,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 once per process. request_options: Request-level overrides Returns: @@ -566,7 +576,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 once per process. 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. diff --git a/src/fishaudio/types/shared.py b/src/fishaudio/types/shared.py index 0628f9f..4955766 100644 --- a/src/fishaudio/types/shared.py +++ b/src/fishaudio/types/shared.py @@ -1,7 +1,10 @@ """Shared types used across the SDK.""" +import os +import sys import warnings -from typing import Generic, Literal, TypeVar +from pathlib import Path +from typing import Generic, Literal, Optional, TypeVar from pydantic import BaseModel @@ -24,18 +27,66 @@ 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"} +# 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) + +# Not resolved, so it matches code objects' filenames (module __file__ paths +# are absolute). +_PACKAGE_DIR = str(Path(__file__).parent.parent) + os.sep +_warned_models: set[str] = set() + + +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. + """ + level = 1 + frame = sys._getframe(1) # The function that calls warnings.warn. + while frame is not None and frame.f_code.co_filename.startswith(_PACKAGE_DIR): + frame = frame.f_back + level += 1 + return level + +def warn_if_deprecated_model(model: Optional[str]) -> None: + """Emit a FutureWarning the first time a deprecated model is used. -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, - ) + FutureWarning, unlike DeprecationWarning, is shown by default in any + module, so applications that call the SDK see it. Each model warns once + per process, so streaming loops do not repeat it. If a warnings filter + turns the warning into an exception, it is raised on every call. + """ + if model is None or model in _warned_models: + return + message = DEPRECATED_TTS_MODELS.get(model) or DEPRECATED_ASR_MODELS.get(model) + if message is None: + return + warnings.warn(message, FutureWarning, stacklevel=_stacklevel_outside_package()) + _warned_models.add(model) # Audio format types diff --git a/tests/integration/test_tts_integration.py b/tests/integration/test_tts_integration.py index 5d4e91e..157b1e6 100644 --- a/tests/integration/test_tts_integration.py +++ b/tests/integration/test_tts_integration.py @@ -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) diff --git a/tests/integration/test_tts_websocket_integration.py b/tests/integration/test_tts_websocket_integration.py index ee9aa15..4e3336e 100644 --- a/tests/integration/test_tts_websocket_integration.py +++ b/tests/integration/test_tts_websocket_integration.py @@ -6,10 +6,13 @@ from fishaudio import WebSocketOptions from fishaudio.types import FlushEvent, Prosody, TextEvent, TTSConfig -from fishaudio.types.shared import DEPRECATED_MODELS, Model +from fishaudio.types.shared import Model from .conftest import TEST_REFERENCE_ID +# Legacy models the WebSocket endpoint does not serve reliably. +LEGACY_WEBSOCKET_MODELS = {"speech-1.5", "speech-1.6"} + class TestTTSWebSocketIntegration: """Test TTS WebSocket streaming with real API.""" @@ -35,7 +38,7 @@ def text_stream(): # Save the audio save_audio(audio_chunks, "test_websocket_streaming.mp3") - @pytest.mark.filterwarnings("ignore::DeprecationWarning") + @pytest.mark.filterwarnings("ignore::FutureWarning") @pytest.mark.parametrize( "model", [ @@ -45,7 +48,7 @@ def text_stream(): reason="WebSocket unreliable for legacy models" ), ) - if m in DEPRECATED_MODELS + if m in LEGACY_WEBSOCKET_MODELS else m for m in get_args(Model) ], @@ -222,7 +225,7 @@ async def text_stream(): save_audio(audio_chunks, "test_async_websocket_streaming.mp3") - @pytest.mark.filterwarnings("ignore::DeprecationWarning") + @pytest.mark.filterwarnings("ignore::FutureWarning") @pytest.mark.asyncio @pytest.mark.parametrize( "model", @@ -233,7 +236,7 @@ async def text_stream(): reason="WebSocket unreliable for legacy models" ), ) - if m in DEPRECATED_MODELS + if m in LEGACY_WEBSOCKET_MODELS else m for m in get_args(Model) ], diff --git a/tests/unit/test_deprecated_models.py b/tests/unit/test_deprecated_models.py new file mode 100644 index 0000000..0be1bfb --- /dev/null +++ b/tests/unit/test_deprecated_models.py @@ -0,0 +1,282 @@ +"""Tests for the warning emitted when a deprecated model is used.""" + +import warnings +from collections.abc import Awaitable, Callable +from typing import Any, Optional +from unittest.mock import Mock, patch + +import pytest + +from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions +from fishaudio.resources.asr import ASRClient, AsyncASRClient +from fishaudio.resources.tts import AsyncTTSClient, TTSClient +from fishaudio.types import shared +from fishaudio.types.shared import warn_if_deprecated_model + +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." +) + + +class _Stop(Exception): + """Raised by the mocked transport so a call ends right after the check.""" + + +@pytest.fixture(autouse=True) +def reset_warned_models(): + """Each test starts as a fresh process that has not warned yet.""" + shared._warned_models.clear() + yield + shared._warned_models.clear() + + +def _sync_wrapper() -> Mock: + wrapper = Mock(spec=ClientWrapper) + wrapper.client = Mock() + wrapper.request.side_effect = _Stop() + return wrapper + + +def _async_wrapper() -> Mock: + wrapper = Mock(spec=AsyncClientWrapper) + wrapper.client = Mock() + wrapper.request.side_effect = _Stop() + return wrapper + + +def _tts_stream(model: str) -> None: + TTSClient(_sync_wrapper()).stream(text="hi", model=model) + + +def _tts_convert(model: str) -> None: + TTSClient(_sync_wrapper()).convert(text="hi", model=model) + + +def _tts_stream_websocket(model: str) -> None: + with patch("fishaudio.resources.tts.connect_ws", side_effect=_Stop()): + list(TTSClient(_sync_wrapper()).stream_websocket(iter(["hi"]), model=model)) + + +def _asr_transcribe(model: str) -> None: + ASRClient(_sync_wrapper()).transcribe(audio=b"audio", model=model) + + +def _asr_transcribe_header(model: str) -> None: + ASRClient(_sync_wrapper()).transcribe( + audio=b"audio", + request_options=RequestOptions(additional_headers={"Model": model}), + ) + + +async def _async_tts_stream(model: str) -> None: + await AsyncTTSClient(_async_wrapper()).stream(text="hi", model=model) + + +async def _async_tts_convert(model: str) -> None: + await AsyncTTSClient(_async_wrapper()).convert(text="hi", model=model) + + +async def _async_tts_stream_websocket(model: str) -> None: + async def text(): + yield "hi" + + with patch("fishaudio.resources.tts.aconnect_ws", side_effect=_Stop()): + async for _ in AsyncTTSClient(_async_wrapper()).stream_websocket( + text(), model=model + ): + pass + + +async def _async_asr_transcribe(model: str) -> None: + await AsyncASRClient(_async_wrapper()).transcribe(audio=b"audio", model=model) + + +async def _async_asr_transcribe_header(model: str) -> None: + await AsyncASRClient(_async_wrapper()).transcribe( + audio=b"audio", + request_options=RequestOptions(additional_headers={"model": model}), + ) + + +SYNC_TTS = [_tts_stream, _tts_convert, _tts_stream_websocket] +SYNC_ASR = [_asr_transcribe, _asr_transcribe_header] +ASYNC_TTS = [_async_tts_stream, _async_tts_convert, _async_tts_stream_websocket] +ASYNC_ASR = [_async_asr_transcribe, _async_asr_transcribe_header] + +SYNC_CASES = [(call, "s1", S1_MESSAGE) for call in SYNC_TTS] + [ + (call, "transcribe-1", TRANSCRIBE_1_MESSAGE) for call in SYNC_ASR +] +ASYNC_CASES = [(call, "s1", S1_MESSAGE) for call in ASYNC_TTS] + [ + (call, "transcribe-1", TRANSCRIBE_1_MESSAGE) for call in ASYNC_ASR +] + + +def _ids(case: Any) -> Optional[str]: + return case.__name__ if callable(case) else None + + +def _deprecation_warnings( + record: list[warnings.WarningMessage], +) -> list[warnings.WarningMessage]: + return [w for w in record if issubclass(w.category, FutureWarning)] + + +def _run_sync(call: Callable[[str], None], model: str) -> None: + with pytest.raises(_Stop): + call(model) + + +async def _run_async(call: Callable[[str], Awaitable[None]], model: str) -> None: + with pytest.raises(_Stop): + await call(model) + + +class TestRetiringModelWarning: + """s1 and transcribe-1 warn on every entry point that accepts them.""" + + @pytest.mark.parametrize("call,model,message", SYNC_CASES, ids=_ids) + def test_sync_entry_point_warns(self, call, model, message): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + _run_sync(call, model) + + emitted = _deprecation_warnings(record) + assert [str(w.message) for w in emitted] == [message] + # The warning points at the code that called the SDK, not at the SDK. + assert emitted[0].filename == __file__ + + @pytest.mark.asyncio + @pytest.mark.parametrize("call,model,message", ASYNC_CASES, ids=_ids) + async def test_async_entry_point_warns(self, call, model, message): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + await _run_async(call, model) + + emitted = _deprecation_warnings(record) + assert [str(w.message) for w in emitted] == [message] + assert emitted[0].filename == __file__ + + @pytest.mark.parametrize("call,model,message", SYNC_CASES, ids=_ids) + def test_sync_entry_point_warns_once_per_process(self, call, model, message): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + for _ in range(3): + _run_sync(call, model) + + assert [str(w.message) for w in _deprecation_warnings(record)] == [message] + + @pytest.mark.asyncio + @pytest.mark.parametrize("call,model,message", ASYNC_CASES, ids=_ids) + async def test_async_entry_point_warns_once_per_process(self, call, model, message): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + for _ in range(3): + await _run_async(call, model) + + assert [str(w.message) for w in _deprecation_warnings(record)] == [message] + + def test_once_across_entry_points_and_per_model(self): + """The once-only state is per model, shared by sync and async clients.""" + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + _run_sync(_tts_stream, "s1") + _run_sync(_tts_convert, "s1") + _run_sync(_tts_stream, "speech-1.5") + _run_sync(_asr_transcribe, "transcribe-1") + _run_sync(_asr_transcribe_header, "transcribe-1") + + assert [str(w.message) for w in _deprecation_warnings(record)] == [ + S1_MESSAGE, + "Model 'speech-1.5' is deprecated. Use 's2.1-pro' instead.", + TRANSCRIBE_1_MESSAGE, + ] + + def test_shown_under_default_filters(self): + """Python's default filters, which hide DeprecationWarning outside + __main__, do not hide this warning.""" + with warnings.catch_warnings(record=True) as record: + warnings.resetwarnings() + # The filters a plain `python app.py` run installs (Python 3.9+). + warnings.filterwarnings("ignore", category=ResourceWarning) + warnings.filterwarnings("ignore", category=ImportWarning) + warnings.filterwarnings("ignore", category=PendingDeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings( + "default", category=DeprecationWarning, module="__main__" + ) + _run_sync(_tts_stream, "s1") + + assert len(_deprecation_warnings(record)) == 1 + + def test_error_filter_raises_on_every_call(self): + """A warning turned into an error is not swallowed by the once-only state.""" + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + for _ in range(2): + with pytest.raises(FutureWarning, match="December 31, 2026"): + _tts_stream("s1") + + +class TestCurrentModelsDoNotWarn: + @pytest.mark.parametrize("call", SYNC_TTS, ids=_ids) + @pytest.mark.parametrize( + "model", ["s2.1-pro", "s2.1-pro-free", "s2-pro", "drama-3"] + ) + def test_sync_tts(self, call, model): + with warnings.catch_warnings(): + warnings.simplefilter("error") + _run_sync(call, model) + + @pytest.mark.asyncio + @pytest.mark.parametrize("call", ASYNC_TTS, ids=_ids) + @pytest.mark.parametrize("model", ["s2.1-pro", "s2-pro", "drama-3"]) + async def test_async_tts(self, call, model): + with warnings.catch_warnings(): + warnings.simplefilter("error") + await _run_async(call, model) + + @pytest.mark.parametrize("call", SYNC_ASR, ids=_ids) + def test_sync_asr(self, call): + with warnings.catch_warnings(): + warnings.simplefilter("error") + _run_sync(call, "transcribe-1-pro") + + @pytest.mark.asyncio + @pytest.mark.parametrize("call", ASYNC_ASR, ids=_ids) + async def test_async_asr(self, call): + with warnings.catch_warnings(): + warnings.simplefilter("error") + await _run_async(call, "transcribe-1-pro") + + def test_asr_without_model(self): + """No model named: no warning, although the API default is transcribe-1.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(_Stop): + ASRClient(_sync_wrapper()).transcribe(audio=b"audio") + + def test_tts_default_model(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(_Stop): + TTSClient(_sync_wrapper()).stream(text="hi") + + def test_none_is_ignored(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + warn_if_deprecated_model(None) + + def test_model_ids_match_exactly(self): + """Lookalike IDs are not treated as the retiring models.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + for model in ["S1", "s1 ", "transcribe-1-pro", "transcribe-10"]: + warn_if_deprecated_model(model) diff --git a/tests/unit/test_tts.py b/tests/unit/test_tts.py index 859d90d..ef2fd4b 100644 --- a/tests/unit/test_tts.py +++ b/tests/unit/test_tts.py @@ -215,6 +215,7 @@ def test_convert_parameter_references_overrides_config( assert len(payload["references"]) == 1 assert payload["references"][0]["text"] == "Param" + @pytest.mark.filterwarnings("ignore::FutureWarning") def test_convert_with_different_backend(self, tts_client, mock_client_wrapper): """Test TTS with different backend/model.""" mock_response = Mock() diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 0a25e62..23fe233 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -94,7 +94,7 @@ def test_stream_websocket_basic( assert mock_connect_ws.call_args[0][0] == "/v1/tts/live" assert mock_connect_ws.call_args[1]["headers"]["model"] == "s2.1-pro" - @pytest.mark.filterwarnings("ignore::DeprecationWarning") + @pytest.mark.filterwarnings("ignore::FutureWarning") @patch("fishaudio.resources.tts.connect_ws") @patch("fishaudio.resources.tts.ThreadPoolExecutor") def test_stream_websocket_with_config( @@ -428,7 +428,7 @@ async def text_stream(): assert mock_aconnect_ws.call_args[0][0] == "/v1/tts/live" assert mock_aconnect_ws.call_args[1]["headers"]["model"] == "s2.1-pro" - @pytest.mark.filterwarnings("ignore::DeprecationWarning") + @pytest.mark.filterwarnings("ignore::FutureWarning") @pytest.mark.asyncio @patch("fishaudio.resources.tts.aconnect_ws") async def test_stream_websocket_with_config( From b7da39d02f7b2662674ab11de880817cfb2aca48 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:28:17 -0800 Subject: [PATCH 2/6] fix: let Python's warning filters decide how often the warning shows Drop the SDK's own once-per-model cache. It was not thread-safe, and after a call under an "ignore" filter it skipped warnings.warn, so a later call under an "error" filter did not raise. The warning is attributed to the caller's line, so Python's default filter action already shows it once per calling line: a streaming or request loop shows it once, and "error", "always" and "ignore" filters apply exactly as Python defines them. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/fishaudio/resources/asr.py | 4 +- src/fishaudio/resources/tts.py | 12 +-- src/fishaudio/types/shared.py | 13 ++- tests/unit/test_deprecated_models.py | 145 +++++++++++++++++++-------- 5 files changed, 117 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 8e8a11e..d04d140 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ for chunk in client.tts.stream(text="Long content..."): audio = client.tts.stream(text="Hello!").collect() ``` -`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`. The SDK emits a `FutureWarning` the first time a deprecated model is used in a process. See [Model Deprecations](https://docs.fish.audio/developer-guide/models-pricing/deprecations). +`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. 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) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 4feaa4c..24786c0 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -104,7 +104,7 @@ def transcribe( 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 once per process. + Passing "transcribe-1" emits a FutureWarning. request_options: Request-level overrides Returns: @@ -297,7 +297,7 @@ async def transcribe( 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 once per process. + Passing "transcribe-1" emits a FutureWarning. request_options: Request-level overrides Returns: diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 071e931..c96cd2a 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -99,7 +99,7 @@ def stream( config: TTS configuration (audio settings, voice, model parameters) 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 once per process. + emit a FutureWarning. request_options: Request-level overrides Returns: @@ -193,7 +193,7 @@ def convert( config: TTS configuration (audio settings, voice, model parameters) 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 once per process. + emit a FutureWarning. request_options: Request-level overrides Returns: @@ -257,7 +257,7 @@ def stream_websocket( config: TTS configuration (audio settings, voice, model parameters) 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 once per process. + 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. @@ -419,7 +419,7 @@ async def stream( config: TTS configuration (audio settings, voice, model parameters) 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 once per process. + emit a FutureWarning. request_options: Request-level overrides Returns: @@ -514,7 +514,7 @@ async def convert( config: TTS configuration (audio settings, voice, model parameters) 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 once per process. + emit a FutureWarning. request_options: Request-level overrides Returns: @@ -578,7 +578,7 @@ async def stream_websocket( config: TTS configuration (audio settings, voice, model parameters) 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 once per process. + 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. diff --git a/src/fishaudio/types/shared.py b/src/fishaudio/types/shared.py index 4955766..d71fd90 100644 --- a/src/fishaudio/types/shared.py +++ b/src/fishaudio/types/shared.py @@ -55,7 +55,6 @@ class PaginatedResponse(BaseModel, Generic[T]): # Not resolved, so it matches code objects' filenames (module __file__ paths # are absolute). _PACKAGE_DIR = str(Path(__file__).parent.parent) + os.sep -_warned_models: set[str] = set() def _stacklevel_outside_package() -> int: @@ -73,20 +72,20 @@ def _stacklevel_outside_package() -> int: def warn_if_deprecated_model(model: Optional[str]) -> None: - """Emit a FutureWarning the first time a deprecated model is used. + """Emit a FutureWarning if a deprecated model is used. FutureWarning, unlike DeprecationWarning, is shown by default in any - module, so applications that call the SDK see it. Each model warns once - per process, so streaming loops do not repeat it. If a warnings filter - turns the warning into an exception, it is raised on every call. + module, so applications that call the SDK see it. The warning is + attributed to the caller's line, so Python's warning filters decide how + often it is shown: by default once per calling line, so a loop does not + repeat it. """ - if model is None or model in _warned_models: + if model is None: return message = DEPRECATED_TTS_MODELS.get(model) or DEPRECATED_ASR_MODELS.get(model) if message is None: return warnings.warn(message, FutureWarning, stacklevel=_stacklevel_outside_package()) - _warned_models.add(model) # Audio format types diff --git a/tests/unit/test_deprecated_models.py b/tests/unit/test_deprecated_models.py index 0be1bfb..1f52b3f 100644 --- a/tests/unit/test_deprecated_models.py +++ b/tests/unit/test_deprecated_models.py @@ -1,5 +1,6 @@ """Tests for the warning emitted when a deprecated model is used.""" +import threading import warnings from collections.abc import Awaitable, Callable from typing import Any, Optional @@ -10,7 +11,6 @@ from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions from fishaudio.resources.asr import ASRClient, AsyncASRClient from fishaudio.resources.tts import AsyncTTSClient, TTSClient -from fishaudio.types import shared from fishaudio.types.shared import warn_if_deprecated_model S1_MESSAGE = ( @@ -30,14 +30,6 @@ class _Stop(Exception): """Raised by the mocked transport so a call ends right after the check.""" -@pytest.fixture(autouse=True) -def reset_warned_models(): - """Each test starts as a fresh process that has not warned yet.""" - shared._warned_models.clear() - yield - shared._warned_models.clear() - - def _sync_wrapper() -> Mock: wrapper = Mock(spec=ClientWrapper) wrapper.client = Mock() @@ -164,65 +156,132 @@ async def test_async_entry_point_warns(self, call, model, message): assert [str(w.message) for w in emitted] == [message] assert emitted[0].filename == __file__ + +def _python_default_filters() -> None: + """Install the filters a plain `python app.py` run starts with.""" + warnings.resetwarnings() + warnings.filterwarnings("ignore", category=ResourceWarning) + warnings.filterwarnings("ignore", category=ImportWarning) + warnings.filterwarnings("ignore", category=PendingDeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("default", category=DeprecationWarning, module="__main__") + + +class TestWarningFilters: + """No state of its own: Python's warning filters decide what is shown.""" + + def test_shown_under_default_filters(self): + """The default filters hide DeprecationWarning outside __main__, but + not this warning.""" + with warnings.catch_warnings(record=True) as record: + _python_default_filters() + _run_sync(_tts_stream, "s1") + + assert len(_deprecation_warnings(record)) == 1 + @pytest.mark.parametrize("call,model,message", SYNC_CASES, ids=_ids) - def test_sync_entry_point_warns_once_per_process(self, call, model, message): + def test_sync_loop_on_one_line_shows_once(self, call, model, message): with warnings.catch_warnings(record=True) as record: - warnings.simplefilter("always") - for _ in range(3): + _python_default_filters() + for _ in range(5): _run_sync(call, model) assert [str(w.message) for w in _deprecation_warnings(record)] == [message] @pytest.mark.asyncio @pytest.mark.parametrize("call,model,message", ASYNC_CASES, ids=_ids) - async def test_async_entry_point_warns_once_per_process(self, call, model, message): + async def test_async_loop_on_one_line_shows_once(self, call, model, message): with warnings.catch_warnings(record=True) as record: - warnings.simplefilter("always") - for _ in range(3): + _python_default_filters() + for _ in range(5): await _run_async(call, model) assert [str(w.message) for w in _deprecation_warnings(record)] == [message] - def test_once_across_entry_points_and_per_model(self): - """The once-only state is per model, shared by sync and async clients.""" + def test_each_calling_line_shows_once(self): + client = TTSClient(_sync_wrapper()) with warnings.catch_warnings(record=True) as record: - warnings.simplefilter("always") - _run_sync(_tts_stream, "s1") - _run_sync(_tts_convert, "s1") - _run_sync(_tts_stream, "speech-1.5") - _run_sync(_asr_transcribe, "transcribe-1") - _run_sync(_asr_transcribe_header, "transcribe-1") + _python_default_filters() + for _ in range(3): + with pytest.raises(_Stop): + client.stream(text="hi", model="s1") # first line + with pytest.raises(_Stop): + client.stream(text="hi", model="s1") # second line + + emitted = _deprecation_warnings(record) + assert [str(w.message) for w in emitted] == [S1_MESSAGE, S1_MESSAGE] + assert emitted[0].lineno != emitted[1].lineno + + def test_each_model_shows_once(self): + with warnings.catch_warnings(record=True) as record: + _python_default_filters() + for model in ["s1", "speech-1.5", "s1", "speech-1.5"]: + _run_sync(_tts_stream, model) assert [str(w.message) for w in _deprecation_warnings(record)] == [ S1_MESSAGE, "Model 'speech-1.5' is deprecated. Use 's2.1-pro' instead.", - TRANSCRIBE_1_MESSAGE, ] - def test_shown_under_default_filters(self): - """Python's default filters, which hide DeprecationWarning outside - __main__, do not hide this warning.""" + def test_always_filter_shows_every_call(self): with warnings.catch_warnings(record=True) as record: - warnings.resetwarnings() - # The filters a plain `python app.py` run installs (Python 3.9+). - warnings.filterwarnings("ignore", category=ResourceWarning) - warnings.filterwarnings("ignore", category=ImportWarning) - warnings.filterwarnings("ignore", category=PendingDeprecationWarning) - warnings.filterwarnings("ignore", category=DeprecationWarning) - warnings.filterwarnings( - "default", category=DeprecationWarning, module="__main__" - ) - _run_sync(_tts_stream, "s1") + warnings.simplefilter("always") + for _ in range(3): + _run_sync(_tts_stream, "s1") - assert len(_deprecation_warnings(record)) == 1 + assert len(_deprecation_warnings(record)) == 3 + + @pytest.mark.parametrize("call,model,message", SYNC_CASES, ids=_ids) + def test_error_filter_raises_on_every_call(self, call, model, message): + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + for _ in range(3): + with pytest.raises(FutureWarning) as exc_info: + call(model) + assert str(exc_info.value) == message - def test_error_filter_raises_on_every_call(self): - """A warning turned into an error is not swallowed by the once-only state.""" + def test_error_after_ignore_raises(self): + """An earlier call under an ignore filter does not mute a later one.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + _run_sync(_tts_stream, "s1") with warnings.catch_warnings(): warnings.simplefilter("error", FutureWarning) - for _ in range(2): - with pytest.raises(FutureWarning, match="December 31, 2026"): - _tts_stream("s1") + with pytest.raises(FutureWarning, match="December 31, 2026"): + _tts_stream("s1") + + def test_shown_after_earlier_ignore(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + _run_sync(_tts_stream, "s1") + with warnings.catch_warnings(record=True) as record: + _python_default_filters() + _run_sync(_tts_stream, "s1") + + assert len(_deprecation_warnings(record)) == 1 + + def test_threads_on_one_line_show_once(self): + threads, start = 16, threading.Barrier(16) + errors: list[BaseException] = [] + + def work() -> None: + try: + start.wait() + for _ in range(20): + _run_sync(_tts_stream, "s1") + except BaseException as e: # noqa: BLE001 - re-raised below + errors.append(e) + + with warnings.catch_warnings(record=True) as record: + _python_default_filters() + workers = [threading.Thread(target=work) for _ in range(threads)] + for worker in workers: + worker.start() + for worker in workers: + worker.join() + + assert errors == [] + assert [str(w.message) for w in _deprecation_warnings(record)] == [S1_MESSAGE] class TestCurrentModelsDoNotWarn: From 5d72d1e679a2e102629b0fde9de43735831aaeff Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:29:28 -0800 Subject: [PATCH 3/6] test: cover the timestamps entry points in the deprecated-model warning tests stream_with_timestamps and convert_with_timestamps (sync and async), added in #173, already call warn_if_deprecated_model. Add them to every entry-point test and give them the same model docstring. Co-Authored-By: Claude Opus 5.5 --- src/fishaudio/resources/tts.py | 16 +++++++++---- tests/unit/test_deprecated_models.py | 36 ++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 8cf3b1c..c7c800d 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -319,7 +319,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: @@ -404,7 +406,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: @@ -790,7 +794,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: @@ -876,7 +882,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: diff --git a/tests/unit/test_deprecated_models.py b/tests/unit/test_deprecated_models.py index 1f52b3f..5d2802f 100644 --- a/tests/unit/test_deprecated_models.py +++ b/tests/unit/test_deprecated_models.py @@ -57,6 +57,14 @@ def _tts_stream_websocket(model: str) -> None: list(TTSClient(_sync_wrapper()).stream_websocket(iter(["hi"]), model=model)) +def _tts_stream_with_timestamps(model: str) -> None: + TTSClient(_sync_wrapper()).stream_with_timestamps(text="hi", model=model) + + +def _tts_convert_with_timestamps(model: str) -> None: + TTSClient(_sync_wrapper()).convert_with_timestamps(text="hi", model=model) + + def _asr_transcribe(model: str) -> None: ASRClient(_sync_wrapper()).transcribe(audio=b"audio", model=model) @@ -87,6 +95,18 @@ async def text(): pass +async def _async_tts_stream_with_timestamps(model: str) -> None: + await AsyncTTSClient(_async_wrapper()).stream_with_timestamps( + text="hi", model=model + ) + + +async def _async_tts_convert_with_timestamps(model: str) -> None: + await AsyncTTSClient(_async_wrapper()).convert_with_timestamps( + text="hi", model=model + ) + + async def _async_asr_transcribe(model: str) -> None: await AsyncASRClient(_async_wrapper()).transcribe(audio=b"audio", model=model) @@ -98,9 +118,21 @@ async def _async_asr_transcribe_header(model: str) -> None: ) -SYNC_TTS = [_tts_stream, _tts_convert, _tts_stream_websocket] +SYNC_TTS = [ + _tts_stream, + _tts_convert, + _tts_stream_websocket, + _tts_stream_with_timestamps, + _tts_convert_with_timestamps, +] SYNC_ASR = [_asr_transcribe, _asr_transcribe_header] -ASYNC_TTS = [_async_tts_stream, _async_tts_convert, _async_tts_stream_websocket] +ASYNC_TTS = [ + _async_tts_stream, + _async_tts_convert, + _async_tts_stream_websocket, + _async_tts_stream_with_timestamps, + _async_tts_convert_with_timestamps, +] ASYNC_ASR = [_async_asr_transcribe, _async_asr_transcribe_header] SYNC_CASES = [(call, "s1", S1_MESSAGE) for call in SYNC_TTS] + [ From 187951bcd189f6abb3cad64b0a56f850533554d5 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:27:23 -0800 Subject: [PATCH 4/6] test: give the mocked client wrapper real headers The WebSocket entry points build their handshake headers before they connect; a Mock in their place fails once those headers are merged. --- tests/unit/test_deprecated_models.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit/test_deprecated_models.py b/tests/unit/test_deprecated_models.py index 5d2802f..0e9595b 100644 --- a/tests/unit/test_deprecated_models.py +++ b/tests/unit/test_deprecated_models.py @@ -33,6 +33,7 @@ class _Stop(Exception): def _sync_wrapper() -> Mock: wrapper = Mock(spec=ClientWrapper) wrapper.client = Mock() + wrapper.get_headers.return_value = {} wrapper.request.side_effect = _Stop() return wrapper @@ -40,6 +41,7 @@ def _sync_wrapper() -> Mock: def _async_wrapper() -> Mock: wrapper = Mock(spec=AsyncClientWrapper) wrapper.client = Mock() + wrapper.get_headers.return_value = {} wrapper.request.side_effect = _Stop() return wrapper From 0fb947bc6ae47127b906b0af1ebe660ca059d3a9 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:30:01 -0800 Subject: [PATCH 5/6] fix: warn at the call for stream_websocket, per API, and wherever the package is imported from Review of this PR found four faults in the warning: - tts.stream_websocket (sync and async) is a generator function, so the check in its body ran only when the stream was first iterated: no warning at the call, and then one attributed to the consumer's line. A decorator now checks the model when the method is called. - One map served both APIs, so asr.transcribe(model="s1") recommended the TTS model s2.1-pro, and TTS with transcribe-1 recommended an ASR model. Each API now checks only its own deprecated models; warn_if_deprecated_model takes the map (TTS by default, as before). - Frames were matched by file path, so a package imported through a path such as "repo//src" attributed the warning to shared.py. Frames are now matched by module name; without sys._getframe the stacklevel falls back to the SDK method's caller. - 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. This cannot be avoided for an async method without changing it into a plain function; the docstring and the README now say so. --- README.md | 2 +- src/fishaudio/resources/asr.py | 10 +- src/fishaudio/resources/tts.py | 30 +++++- src/fishaudio/types/shared.py | 39 ++++--- tests/unit/test_deprecated_models.py | 153 ++++++++++++++++++++++++++- 5 files changed, 211 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 6ec1aa7..234321c 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ 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. See [Model Deprecations](https://docs.fish.audio/developer-guide/models-pricing/deprecations). +`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) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 24786c0..7315fa2 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -23,7 +23,7 @@ ASRTurnDetection, TurnDetectionMode, ) -from fishaudio.types.shared import warn_if_deprecated_model +from fishaudio.types.shared import DEPRECATED_ASR_MODELS, warn_if_deprecated_model from .asr_realtime import REALTIME_PATH, ASRRealtimeStream, AsyncASRRealtimeStream @@ -126,7 +126,9 @@ def transcribe( print(f"{segment.start}-{segment.end}: {segment.text}") ``` """ - warn_if_deprecated_model(_requested_model(model, request_options)) + warn_if_deprecated_model( + _requested_model(model, request_options), DEPRECATED_ASR_MODELS + ) # Build request payload payload = { @@ -319,7 +321,9 @@ async def transcribe( print(f"{segment.start}-{segment.end}: {segment.text}") ``` """ - warn_if_deprecated_model(_requested_model(model, request_options)) + warn_if_deprecated_model( + _requested_model(model, request_options), DEPRECATED_ASR_MODELS + ) # Build request payload payload = { diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index c7c800d..4724bfe 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -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 @@ -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.""" @@ -443,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]], @@ -540,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="") @@ -920,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]], @@ -1015,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="") diff --git a/src/fishaudio/types/shared.py b/src/fishaudio/types/shared.py index d71fd90..09e34a4 100644 --- a/src/fishaudio/types/shared.py +++ b/src/fishaudio/types/shared.py @@ -1,9 +1,9 @@ """Shared types used across the SDK.""" -import os import sys import warnings -from pathlib import Path +from collections.abc import Mapping +from types import FrameType from typing import Generic, Literal, Optional, TypeVar from pydantic import BaseModel @@ -52,9 +52,12 @@ class PaginatedResponse(BaseModel, Generic[T]): # All deprecated model IDs (TTS and ASR). DEPRECATED_MODELS = frozenset(DEPRECATED_TTS_MODELS) | frozenset(DEPRECATED_ASR_MODELS) -# Not resolved, so it matches code objects' filenames (module __file__ paths -# are absolute). -_PACKAGE_DIR = str(Path(__file__).parent.parent) + os.sep + +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__", "") + return name == "fishaudio" or name.startswith("fishaudio.") def _stacklevel_outside_package() -> int: @@ -63,26 +66,36 @@ def _stacklevel_outside_package() -> int: 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 = sys._getframe(1) # The function that calls warnings.warn. - while frame is not None and frame.f_code.co_filename.startswith(_PACKAGE_DIR): + 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]) -> None: - """Emit a FutureWarning if a deprecated model is used. +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 caller's line, so Python's warning filters decide how - often it is shown: by default once per calling line, so a loop does not - repeat it. + 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_TTS_MODELS.get(model) or DEPRECATED_ASR_MODELS.get(model) + message = deprecated.get(model) if message is None: return warnings.warn(message, FutureWarning, stacklevel=_stacklevel_outside_package()) diff --git a/tests/unit/test_deprecated_models.py b/tests/unit/test_deprecated_models.py index 0e9595b..75b2a65 100644 --- a/tests/unit/test_deprecated_models.py +++ b/tests/unit/test_deprecated_models.py @@ -1,8 +1,13 @@ """Tests for the warning emitted when a deprecated model is used.""" +import asyncio +import subprocess +import sys +import textwrap import threading import warnings from collections.abc import Awaitable, Callable +from pathlib import Path from typing import Any, Optional from unittest.mock import Mock, patch @@ -11,6 +16,7 @@ from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions from fishaudio.resources.asr import ASRClient, AsyncASRClient from fishaudio.resources.tts import AsyncTTSClient, TTSClient +from fishaudio.types import shared from fishaudio.types.shared import warn_if_deprecated_model S1_MESSAGE = ( @@ -330,7 +336,9 @@ def test_sync_tts(self, call, model): @pytest.mark.asyncio @pytest.mark.parametrize("call", ASYNC_TTS, ids=_ids) - @pytest.mark.parametrize("model", ["s2.1-pro", "s2-pro", "drama-3"]) + @pytest.mark.parametrize( + "model", ["s2.1-pro", "s2.1-pro-free", "s2-pro", "drama-3"] + ) async def test_async_tts(self, call, model): with warnings.catch_warnings(): warnings.simplefilter("error") @@ -373,3 +381,146 @@ def test_model_ids_match_exactly(self): warnings.simplefilter("error") for model in ["S1", "s1 ", "transcribe-1-pro", "transcribe-10"]: warn_if_deprecated_model(model) + + +def _line() -> int: + """The line number of the caller of this function.""" + return sys._getframe(1).f_lineno + + +class TestWarningPointsAtTheCall: + """Found by review: where and for which API the warning is raised.""" + + def test_sync_stream_websocket_warns_at_the_call_not_when_iterated(self): + client = TTSClient(_sync_wrapper()) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + line = _line() + 1 + stream = client.stream_websocket(iter(["hi"]), model="s1") + + emitted = _deprecation_warnings(record) + assert [(w.filename, w.lineno) for w in emitted] == [(__file__, line)] + stream.close() + + def test_async_stream_websocket_warns_at_the_call_not_when_iterated(self): + client = AsyncTTSClient(_async_wrapper()) + + async def text(): + yield "hi" + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + line = _line() + 1 + stream = client.stream_websocket(text(), model="s1") + + emitted = _deprecation_warnings(record) + assert [(w.filename, w.lineno) for w in emitted] == [(__file__, line)] + assert hasattr(stream, "__aiter__") + + def test_direct_call_points_at_its_line(self): + client = TTSClient(_sync_wrapper()) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + with pytest.raises(_Stop): + line = _line() + 1 + client.convert(text="hi", model="s1") + + assert [w.lineno for w in _deprecation_warnings(record)] == [line] + + @pytest.mark.parametrize("model", ["s1", "speech-1.5", "speech-1.6"]) + def test_asr_does_not_warn_about_tts_models(self, model): + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(_Stop): + ASRClient(_sync_wrapper()).transcribe(audio=b"a", model=model) + + @pytest.mark.asyncio + async def test_async_asr_does_not_warn_about_tts_models(self): + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(_Stop): + await AsyncASRClient(_async_wrapper()).transcribe( + audio=b"a", model="s1" + ) + + @pytest.mark.parametrize("call", SYNC_TTS, ids=_ids) + def test_tts_does_not_warn_about_asr_models(self, call): + with warnings.catch_warnings(): + warnings.simplefilter("error") + _run_sync(call, "transcribe-1") + + @pytest.mark.parametrize("model", ["speech-1.5", "speech-1.6"]) + def test_older_retired_tts_models_warn(self, model): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + _run_sync(_tts_stream, model) + + emitted = _deprecation_warnings(record) + assert len(emitted) == 1 and model in str(emitted[0].message) + + @pytest.mark.asyncio + @pytest.mark.parametrize("call,model,message", ASYNC_CASES, ids=_ids) + async def test_async_error_filter_raises(self, call, model, message): + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + with pytest.raises(FutureWarning, match="deprecated"): + await call(model) + + def test_model_argument_wins_over_a_model_header(self): + options = RequestOptions(additional_headers={"model": "transcribe-1"}) + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(_Stop): + ASRClient(_sync_wrapper()).transcribe( + audio=b"a", model="transcribe-1-pro", request_options=options + ) + + @pytest.mark.asyncio + async def test_scheduled_coroutine_still_warns_once(self): + """Documented limit: a task runs from asyncio's code, so the warning + points there; it is still raised.""" + client = AsyncASRClient(_async_wrapper()) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + task = asyncio.create_task( + client.transcribe(audio=b"a", model="transcribe-1") + ) + with pytest.raises(_Stop): + await task + + emitted = _deprecation_warnings(record) + assert len(emitted) == 1 + assert Path(emitted[0].filename).parent == Path(asyncio.__file__).parent + + def test_package_imported_through_a_path_with_double_slash(self, tmp_path): + """A sys.path entry such as "repo//src" must not make the warning point + inside the SDK.""" + repo = Path(shared.__file__).parent.parent.parent.parent + src = f"{repo}//src" + script = tmp_path / "app.py" + script.write_text( + textwrap.dedent( + f""" + import sys, warnings + sys.path.insert(0, {src!r}) + import fishaudio.types.shared as shared + assert "//" in shared.__file__, shared.__file__ + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + shared.warn_if_deprecated_model("s1") + print(record[0].filename) + """ + ) + ) + result = subprocess.run( + [sys.executable, str(script)], capture_output=True, text=True, check=True + ) + assert result.stdout.strip() == str(script) + + def test_warns_without_sys_getframe(self, monkeypatch): + monkeypatch.setattr(shared, "sys", object()) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + _run_sync(_tts_stream, "s1") + + assert len(_deprecation_warnings(record)) == 1 From eeba98d3f27a3ea0d97302e15cc42f58ddcc5d05 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:06:56 -0800 Subject: [PATCH 6/6] fix: do not raise from the warning check when a caller's module name is not a str A caller frame whose __name__ is not a str (code run by exec() with its own globals, or during interpreter shutdown) made the check that finds the first frame outside the package raise AttributeError. Such a frame now counts as outside the package. Python itself drops a warning attributed to a frame whose __name__ is None. --- src/fishaudio/types/shared.py | 5 ++++- tests/unit/test_deprecated_models.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/types/shared.py b/src/fishaudio/types/shared.py index 09e34a4..dde36ca 100644 --- a/src/fishaudio/types/shared.py +++ b/src/fishaudio/types/shared.py @@ -56,7 +56,10 @@ class PaginatedResponse(BaseModel, Generic[T]): 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__", "") + 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.") diff --git a/tests/unit/test_deprecated_models.py b/tests/unit/test_deprecated_models.py index 75b2a65..2b55dd5 100644 --- a/tests/unit/test_deprecated_models.py +++ b/tests/unit/test_deprecated_models.py @@ -524,3 +524,22 @@ def test_warns_without_sys_getframe(self, monkeypatch): _run_sync(_tts_stream, "s1") assert len(_deprecation_warnings(record)) == 1 + + +@pytest.mark.parametrize("module_name,shown", [(None, 0), (123, 1)]) +def test_caller_without_a_str_module_name_does_not_raise(module_name, shown): + """Code run by exec() with its own globals, or during interpreter shutdown, + can have a __name__ that is not a str; the check must not raise. Whether the + warning is shown is then Python's decision: it drops a warning attributed to + a frame whose __name__ is None, as for any warnings.warn call.""" + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + exec( + "warn_if_deprecated_model('s1')", + { + "__name__": module_name, + "warn_if_deprecated_model": warn_if_deprecated_model, + }, + ) + + assert len(_deprecation_warnings(record)) == shown