diff --git a/README.md b/README.md index f446770..234321c 100644 --- a/README.md +++ b/README.md @@ -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") diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 514c5ac..7315fa2 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -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, *, @@ -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: @@ -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, @@ -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: @@ -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, diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 73d83f2..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.""" @@ -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: @@ -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: @@ -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: @@ -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: @@ -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]], @@ -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. @@ -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="") @@ -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: @@ -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: @@ -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: @@ -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: @@ -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]], @@ -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. @@ -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="") diff --git a/src/fishaudio/types/shared.py b/src/fishaudio/types/shared.py index 0628f9f..dde36ca 100644 --- a/src/fishaudio/types/shared.py +++ b/src/fishaudio/types/shared.py @@ -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 @@ -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 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..2b55dd5 --- /dev/null +++ b/tests/unit/test_deprecated_models.py @@ -0,0 +1,545 @@ +"""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 + +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.""" + + +def _sync_wrapper() -> Mock: + wrapper = Mock(spec=ClientWrapper) + wrapper.client = Mock() + wrapper.get_headers.return_value = {} + wrapper.request.side_effect = _Stop() + return wrapper + + +def _async_wrapper() -> Mock: + wrapper = Mock(spec=AsyncClientWrapper) + wrapper.client = Mock() + wrapper.get_headers.return_value = {} + 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 _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) + + +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_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) + + +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, + _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_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] + [ + (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__ + + +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_loop_on_one_line_shows_once(self, call, model, message): + with warnings.catch_warnings(record=True) as record: + _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_loop_on_one_line_shows_once(self, call, model, message): + with warnings.catch_warnings(record=True) as record: + _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_each_calling_line_shows_once(self): + client = TTSClient(_sync_wrapper()) + with warnings.catch_warnings(record=True) as record: + _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.", + ] + + def test_always_filter_shows_every_call(self): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + for _ in range(3): + _run_sync(_tts_stream, "s1") + + 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_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) + 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: + @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.1-pro-free", "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) + + +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 + + +@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 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 9e2a425..99e2f13 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(