From db444cd06e5715fe780bedf88e23f7fa3c2f1610 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:45:11 -0800 Subject: [PATCH 01/10] feat(tts): add language option for text normalization (FISH-1400) TTSConfig.language and a language parameter on convert, stream, convert_with_timestamps, stream_with_timestamps and stream_websocket (sync and async) set the BCP-47 tag the API uses to spell out numbers, dates, units and symbols. The parameter overrides the config value. The tag is sent as given; the API checks it. When language is unset nothing is sent: TTSRequest drops the field from every dump, including the WebSocket start event, which is serialized without exclude_none. Other unset start-event fields keep their current behaviour. --- README.md | 12 + src/fishaudio/resources/tts.py | 42 ++++ src/fishaudio/types/tts.py | 27 +- tests/integration/test_tts_integration.py | 18 ++ .../test_tts_websocket_integration.py | 16 ++ tests/unit/test_tts_language.py | 231 ++++++++++++++++++ 6 files changed, 345 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_tts_language.py diff --git a/README.md b/README.md index 6126dda..bcb53ef 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,18 @@ audio = client.tts.convert( ) ``` +**Language of the text:** + +```python +# "$300" is read as "trescientos pesos" with es-MX, "trescientos dólares" with es +audio = client.tts.convert( + text="La entrada cuesta $300.", + language="es-MX", +) +``` + +`language` is a BCP-47 tag such as `en`, `es-MX` or `zh-CN`. It only changes how numbers, dates, units and symbols are spelled out before synthesis (and word-timestamp alignment); it does not change the voice or accent. Without it, the API detects the language of each chunk, which is also the right choice for text that mixes languages. It is accepted by every text-to-speech method and by `TTSConfig`; on `stream_websocket` it applies to the whole session. See [supported normalization languages](https://docs.fish.audio/features/text-to-speech#supported-normalization-languages). + **Reusable configuration:** ```python diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 2926b7a..c5d9cfa 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -81,6 +81,7 @@ def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest: references=config.references, reference_id=config.reference_id, normalize=config.normalize, + language=config.language, latency=config.latency, prosody=config.prosody, top_p=config.top_p, @@ -118,6 +119,7 @@ def _build_tts_payload( format: Optional[AudioFormat], latency: Optional[LatencyMode], speed: Optional[float], + language: Optional[str], ) -> bytes: """Build the MessagePack request body; direct parameters override config.""" request = _config_to_tts_request(config, text) @@ -131,6 +133,8 @@ def _build_tts_payload( request.latency = latency if speed is not None: request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + if language is not None: + request.language = language return ormsgpack.packb(request.model_dump(exclude_none=True)) @@ -167,6 +171,7 @@ def stream( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -181,6 +186,7 @@ def stream( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -225,6 +231,9 @@ def stream( if speed is not None: request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + if language is not None: + request.language = language + payload = request.model_dump(exclude_none=True) # Send the request and return once headers arrive; the body is read @@ -258,6 +267,7 @@ def convert( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -275,6 +285,7 @@ def convert( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -308,6 +319,7 @@ def convert( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -322,6 +334,7 @@ def stream_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -341,6 +354,7 @@ def stream_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -375,6 +389,7 @@ def stream_with_timestamps( format=format, latency=latency, speed=speed, + language=language, ) # Return once headers arrive; events are read lazily as they are produced. @@ -411,6 +426,7 @@ def convert_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -430,6 +446,7 @@ def convert_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -463,6 +480,7 @@ def convert_with_timestamps( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -478,6 +496,7 @@ def stream_websocket( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", max_workers: int = 10, @@ -495,6 +514,7 @@ def stream_websocket( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -587,6 +607,9 @@ def text_generator(): speed, base=config.prosody ) + if language is not None: + tts_request.language = language + # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} headers = _handshake_headers(self._client, model, ws_options) @@ -642,6 +665,7 @@ async def stream( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -656,6 +680,7 @@ async def stream( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -701,6 +726,9 @@ async def stream( if speed is not None: request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + if language is not None: + request.language = language + payload = request.model_dump(exclude_none=True) # Send the request and return once headers arrive; the body is read @@ -736,6 +764,7 @@ async def convert( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -753,6 +782,7 @@ async def convert( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -786,6 +816,7 @@ async def convert( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -801,6 +832,7 @@ async def stream_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -820,6 +852,7 @@ async def stream_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -855,6 +888,7 @@ async def stream_with_timestamps( format=format, latency=latency, speed=speed, + language=language, ) # Return once headers arrive; events are read lazily as they are produced. @@ -891,6 +925,7 @@ async def convert_with_timestamps( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", request_options: Optional[RequestOptions] = None, @@ -910,6 +945,7 @@ async def convert_with_timestamps( are uncompressed, which keeps sample positions exact. latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -943,6 +979,7 @@ async def convert_with_timestamps( format=format, latency=latency, speed=speed, + language=language, config=config, model=model, request_options=request_options, @@ -959,6 +996,7 @@ async def stream_websocket( format: Optional[AudioFormat] = None, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, + language: Optional[str] = None, config: TTSConfig = TTSConfig(), # noqa: B008 - never mutated model: Union[Model, str] = "s3-pro", ws_options: Optional[WebSocketOptions] = None, @@ -975,6 +1013,7 @@ async def stream_websocket( format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided) latency: Latency mode - "normal", "balanced" or "low" (overrides config.latency if provided) speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + language: BCP-47 tag of the text, e.g. "es-MX", for text normalization (overrides config.language if provided) 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") @@ -1066,6 +1105,9 @@ async def text_generator(): speed, base=config.prosody ) + if language is not None: + tts_request.language = language + # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} headers = _handshake_headers(self._client, model, ws_options) diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index fff6110..0b6f73e 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -3,7 +3,14 @@ from typing import Annotated, Literal, Optional import httpx -from pydantic import BaseModel, ConfigDict, Field, field_serializer +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SerializerFunctionWrapHandler, + field_serializer, + model_serializer, +) from .shared import AudioFormat, LatencyMode, _get_response_headers @@ -66,6 +73,11 @@ class TTSConfig(BaseModel): mp3_bitrate: MP3 bitrate in kbps. Options: 64, 128, 192. Default: 128 opus_bitrate: Opus bitrate in kbps. Options: -1000, 24, 32, 48, 64. Default: 32 normalize: Whether to normalize/clean the input text. Default: True + language: BCP-47 tag of the text's language, such as "en", "es-MX" or "zh-CN". + Only changes how text normalization spells out numbers, dates, units + and symbols (and word-timestamp alignment); it does not change the + voice or accent. Sent as given; the API checks it. Default: None + (not sent, the API detects the language of each chunk) chunk_length: Characters per generation chunk. Range: 100-300. Default: 200. Lower values = faster initial response, higher values = better quality latency: Generation mode. Options: "normal" (higher quality), "balanced" (faster), @@ -90,6 +102,7 @@ class TTSConfig(BaseModel): mp3_bitrate: Literal[64, 128, 192] = 128 opus_bitrate: Literal[-1000, 24, 32, 48, 64] = 32 normalize: bool = True + language: Optional[str] = None # Generation settings chunk_length: Annotated[int, Field(ge=100, le=300, strict=True)] = 200 @@ -129,6 +142,8 @@ class TTSRequest(BaseModel): references: List of reference audio samples for voice cloning. Default: [] reference_id: Voice model ID for using a specific voice. Default: None normalize: Whether to normalize/clean the input text. Default: True + language: BCP-47 tag of the text's language for text normalization. + Default: None, which leaves the field out of the request latency: Generation mode. Options: "normal", "balanced". Default: "balanced" "low" is also accepted; it gives earlier first audio on s3-pro. prosody: Speech speed and volume settings. Default: None @@ -150,6 +165,7 @@ class TTSRequest(BaseModel): references: list[ReferenceAudio] = [] reference_id: Optional[str] = None normalize: bool = True + language: Optional[str] = None latency: LatencyMode = "balanced" prosody: Optional[Prosody] = None top_p: Annotated[float, Field(ge=0.0, le=1.0)] = 0.7 @@ -165,6 +181,15 @@ def _opus_bitrate_bps(self, value: int) -> int: # The API takes opus_bitrate in bps (24000, 32000, ...); -1000 means auto. return value * 1000 if value > 0 else value + @model_serializer(mode="wrap") + def _omit_unset_language(self, handler: SerializerFunctionWrapHandler) -> dict: + # An unset language must not reach the API as null, including in the + # WebSocket start event, which is serialized without exclude_none. + data = handler(self) + if self.language is None: + data.pop("language", None) + return data + # WebSocket event types for streaming TTS class StartEvent(BaseModel): diff --git a/tests/integration/test_tts_integration.py b/tests/integration/test_tts_integration.py index 437049b..40684b1 100644 --- a/tests/integration/test_tts_integration.py +++ b/tests/integration/test_tts_integration.py @@ -46,6 +46,24 @@ def test_tts_with_prosody(self, client, save_audio): # Write to output directory save_audio(audio, "test_prosody.mp3") + def test_tts_with_language(self, client, save_audio): + """Test TTS with a language tag for text normalization.""" + audio = client.tts.convert(text="La entrada cuesta $300.", language="es-MX") + assert len(audio) > 1000 + save_audio(audio, "test_language_es_mx.mp3") + + config = TTSConfig(language="es") + result = client.tts.convert_with_timestamps( + text="La entrada cuesta $300.", config=config + ) + assert len(result.audio) > 1000 + + def test_tts_with_invalid_language_is_rejected_by_api(self, client): + """The SDK sends the tag as given; the API rejects an invalid one.""" + with pytest.raises(APIError) as exc_info: + client.tts.convert(text="Hello", language="en US") + assert exc_info.value.status == 400 + @pytest.mark.filterwarnings("ignore::FutureWarning") def test_tts_with_different_models(self, client, save_audio): """Test TTS with different models.""" diff --git a/tests/integration/test_tts_websocket_integration.py b/tests/integration/test_tts_websocket_integration.py index a0a8a33..6dfede4 100644 --- a/tests/integration/test_tts_websocket_integration.py +++ b/tests/integration/test_tts_websocket_integration.py @@ -5,6 +5,7 @@ import pytest from fishaudio import WebSocketOptions +from fishaudio.exceptions import WebSocketError from fishaudio.types import FlushEvent, Prosody, TextEvent, TTSConfig from fishaudio.types.shared import Model @@ -38,6 +39,21 @@ def text_stream(): # Save the audio save_audio(audio_chunks, "test_websocket_streaming.mp3") + def test_websocket_streaming_with_language(self, client, save_audio): + """Test WebSocket streaming with a language tag for the session.""" + audio_chunks = list( + client.tts.stream_websocket( + iter(["La entrada cuesta $300."]), language="es-MX" + ) + ) + assert len(b"".join(audio_chunks)) > 1000 + save_audio(audio_chunks, "test_websocket_language_es_mx.mp3") + + def test_websocket_invalid_language_raises(self, client): + """The API answers an invalid tag with an error event; the SDK raises it.""" + with pytest.raises(WebSocketError, match="Invalid language"): + list(client.tts.stream_websocket(iter(["Hello"]), language="en US")) + @pytest.mark.filterwarnings("ignore::FutureWarning") @pytest.mark.parametrize( "model", diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py new file mode 100644 index 0000000..c88fb55 --- /dev/null +++ b/tests/unit/test_tts_language.py @@ -0,0 +1,231 @@ +"""Tests for the text-to-speech `language` option on every entry point. + +HTTP requests go through real httpx transports and WebSocket sessions through a +local server (see realtime_server.py), so the assertions read the bytes the SDK +actually sends. An unset language must not appear on the wire at all, not even +as nil. +""" + +import contextlib + +import httpx +import ormsgpack +import pytest + +from fishaudio import AsyncFishAudio, FishAudio, TTSConfig +from fishaudio.core import AsyncClientWrapper, ClientWrapper +from fishaudio.exceptions import WebSocketError +from fishaudio.resources.tts import AsyncTTSClient, TTSClient +from fishaudio.types import StartEvent, TTSRequest + +from .realtime_server import RealtimeServer + +BASE_URL = "https://api.test.fish.audio" + +SSE_BODY = ( + b'event: message\ndata: {"audio_base64": "", "content": "", "alignment": null}\n\n' +) + +# (call kwargs, expected "language" in the body; None means absent) +CASES = [ + pytest.param({}, None, id="unset"), + pytest.param({"config": TTSConfig()}, None, id="default-config"), + pytest.param({"language": "es-MX"}, "es-MX", id="parameter"), + pytest.param({"config": TTSConfig(language="zh-CN")}, "zh-CN", id="config"), + pytest.param( + {"language": "es-MX", "config": TTSConfig(language="en")}, + "es-MX", + id="parameter-overrides-config", + ), + pytest.param({"language": "ES_mx"}, "ES_mx", id="sent-as-given"), + pytest.param({"language": ""}, "", id="empty-string-sent-as-given"), +] + + +def _check(body, expected): + if expected is None: + assert "language" not in body + else: + assert body["language"] == expected + + +def _capture(seen, response_body): + def handler(request): + seen.append(request) + return httpx.Response(200, content=response_body) + + return handler + + +def _sync_tts(seen, response_body=b"audio"): + transport = httpx.MockTransport(_capture(seen, response_body)) + http = httpx.Client(base_url=BASE_URL, transport=transport) + return TTSClient(ClientWrapper(api_key="test", httpx_client=http)) + + +def _async_tts(seen, response_body=b"audio"): + transport = httpx.MockTransport(_capture(seen, response_body)) + http = httpx.AsyncClient(base_url=BASE_URL, transport=transport) + return AsyncTTSClient(AsyncClientWrapper(api_key="test", httpx_client=http)) + + +class TestTypes: + def test_config_defaults_to_unset(self): + assert TTSConfig().language is None + + def test_request_omits_unset_language_in_every_dump(self): + request = TTSRequest(text="hi") + assert "language" not in request.model_dump() + assert "language" not in request.model_dump(exclude_none=True) + assert "language" not in StartEvent(request=request).model_dump()["request"] + + def test_request_keeps_a_set_language(self): + request = TTSRequest(text="hi", language="es-MX") + assert request.model_dump()["language"] == "es-MX" + assert StartEvent(request=request).model_dump()["request"]["language"] == ( + "es-MX" + ) + + def test_other_none_fields_are_unchanged(self): + # Only language is dropped when unset; the start event keeps sending the + # other optional fields as nil, as it did before. + dumped = StartEvent(request=TTSRequest(text="")).model_dump()["request"] + assert dumped["reference_id"] is None + assert dumped["sample_rate"] is None + assert dumped["prosody"] is None + + +class TestHTTP: + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_convert(self, kwargs, expected): + seen = [] + _sync_tts(seen).convert(text="La entrada cuesta $300.", **kwargs) + assert seen[0].url.path == "/v1/tts" + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_stream(self, kwargs, expected): + seen = [] + _sync_tts(seen).stream(text="Hi", **kwargs).collect() + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_convert_with_timestamps(self, kwargs, expected): + seen = [] + _sync_tts(seen, SSE_BODY).convert_with_timestamps(text="Hi", **kwargs) + assert seen[0].url.path == "/v1/tts/stream/with-timestamp" + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_stream_with_timestamps(self, kwargs, expected): + seen = [] + _sync_tts(seen, SSE_BODY).stream_with_timestamps(text="Hi", **kwargs).close() + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_convert(self, kwargs, expected): + seen = [] + await _async_tts(seen).convert(text="Hi", **kwargs) + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_stream(self, kwargs, expected): + seen = [] + stream = await _async_tts(seen).stream(text="Hi", **kwargs) + await stream.collect() + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_convert_with_timestamps(self, kwargs, expected): + seen = [] + await _async_tts(seen, SSE_BODY).convert_with_timestamps(text="Hi", **kwargs) + _check(ormsgpack.unpackb(seen[0].content), expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_stream_with_timestamps(self, kwargs, expected): + seen = [] + stream = await _async_tts(seen, SSE_BODY).stream_with_timestamps( + text="Hi", **kwargs + ) + await stream.aclose() + _check(ormsgpack.unpackb(seen[0].content), expected) + + +def tts_script(conn): + """Read the start event and the text, then answer with audio and finish.""" + while conn.recv().get("event") != "stop": + pass + conn.send({"event": "audio", "audio": b"audio"}) + conn.send({"event": "finish", "reason": "stop"}) + + +def rejecting_script(conn): + """What the API does with an invalid start event: an error event, then silence.""" + conn.recv() + conn.send({"event": "error", "error": 'Invalid language "en us".'}) + + +@contextlib.contextmanager +def serving(script): + server = RealtimeServer(script) + client = FishAudio(api_key="test-key", base_url=server.url) + try: + yield server, client + finally: + client.close() + server.close() + + +@contextlib.asynccontextmanager +async def aserving(script): + server = RealtimeServer(script) + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + try: + yield server, client + finally: + await client.close() + server.close() + + +async def _aiter(*items): + for item in items: + yield item + + +class TestWebSocket: + @pytest.mark.parametrize("kwargs, expected", CASES) + def test_start_event(self, kwargs, expected): + with serving(tts_script) as (server, client): + audio = b"".join(client.tts.stream_websocket(iter(["Hola"]), **kwargs)) + conn = server.stop() + assert audio == b"audio" + assert conn.path == "/v1/tts/live" + start = conn.received[0] + assert start["event"] == "start" + _check(start["request"], expected) + + @pytest.mark.parametrize("kwargs, expected", CASES) + async def test_async_start_event(self, kwargs, expected): + async with aserving(tts_script) as (server, client): + chunks = [ + chunk + async for chunk in client.tts.stream_websocket(_aiter("Hola"), **kwargs) + ] + conn = server.stop() + assert b"".join(chunks) == b"audio" + _check(conn.received[0]["request"], expected) + + def test_rejected_start_event_raises_instead_of_hanging(self): + with serving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + list(client.tts.stream_websocket(iter(["Hola"]), language="en us")) + server.stop() + + async def test_async_rejected_start_event_raises_instead_of_hanging(self): + async with aserving(rejecting_script) as (server, client): + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + async for _ in client.tts.stream_websocket( + _aiter("Hola"), language="en us" + ): + pass + server.stop() From ac59808a5a811eb4de1a3cb32491876d41183bd6 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:28:23 -0800 Subject: [PATCH 02/10] fix(tts): keep TTSRequest's serialization schema The model serializer that drops an unset language was annotated '-> dict', which Pydantic publishes as the serialization schema, so TTSRequest.model_json_schema(mode="serialization") listed no fields. Without the annotation the schema is main's plus language. --- src/fishaudio/types/tts.py | 4 +++- tests/unit/test_tts_language.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index 0b6f73e..43d6898 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -182,9 +182,11 @@ def _opus_bitrate_bps(self, value: int) -> int: return value * 1000 if value > 0 else value @model_serializer(mode="wrap") - def _omit_unset_language(self, handler: SerializerFunctionWrapHandler) -> dict: + def _omit_unset_language(self, handler: SerializerFunctionWrapHandler): # An unset language must not reach the API as null, including in the # WebSocket start event, which is serialized without exclude_none. + # No return annotation: Pydantic would publish it as the + # serialization schema in place of the model's fields. data = handler(self) if self.language is None: data.pop("language", None) diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index c88fb55..1bb4b22 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -86,6 +86,19 @@ def test_request_keeps_a_set_language(self): "es-MX" ) + def test_serialization_schema_keeps_every_field(self): + # Dropping an unset language must not change the published schema: + # every field stays described and text stays required. + schema = TTSRequest.model_json_schema(mode="serialization") + assert set(schema["properties"]) == set(TTSRequest.model_fields) + assert schema["required"] == ["text"] + assert schema["properties"]["language"]["anyOf"] == [ + {"type": "string"}, + {"type": "null"}, + ] + nested = StartEvent.model_json_schema(mode="serialization")["$defs"] + assert set(nested["TTSRequest"]["properties"]) == set(TTSRequest.model_fields) + def test_other_none_fields_are_unchanged(self): # Only language is dropped when unset; the start event keeps sending the # other optional fields as nil, as it did before. From bccb3d7b1c816010f32921381df9b69a5c679a69 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:45:11 -0800 Subject: [PATCH 03/10] fix(tts): raise on a WebSocket error event instead of waiting forever When the API rejects the start event of /v1/tts/live (for example an invalid language tag), it sends {"event": "error", "error": "..."} and then nothing more. stream_websocket ignored that event as unknown and kept waiting for audio or a finish event, so the call never returned. It now raises WebSocketError with the server's message. --- src/fishaudio/resources/realtime.py | 8 +++++++- tests/unit/test_realtime.py | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/resources/realtime.py b/src/fishaudio/resources/realtime.py index 1049859..2bec49f 100644 --- a/src/fishaudio/resources/realtime.py +++ b/src/fishaudio/resources/realtime.py @@ -33,10 +33,16 @@ def _process_audio_event(data: dict[str, Any]) -> Optional[bytes]: Audio bytes if audio event, None for unknown events Raises: - WebSocketError: If finish event has error reason + WebSocketError: If the server reports an error, either as an error + event or as a finish event with reason "error" """ if data.get("event") == "audio": return data.get("audio") + if data.get("event") == "error": + # The server sends this when it rejects the start event (for example an + # invalid language tag) and then sends nothing more, so waiting for a + # finish event would block forever. + raise WebSocketError(f"WebSocket stream failed: {data.get('error')}") if data.get("event") == "finish" and data.get("reason") == "error": raise WebSocketError("WebSocket stream ended with error") return None # Ignore unknown events diff --git a/tests/unit/test_realtime.py b/tests/unit/test_realtime.py index 446ae3c..54e662c 100644 --- a/tests/unit/test_realtime.py +++ b/tests/unit/test_realtime.py @@ -60,6 +60,12 @@ def test_finish_event_with_error_raises_exception(self): with pytest.raises(WebSocketError, match="WebSocket stream ended with error"): _process_audio_event(data) + def test_error_event_raises_with_server_message(self): + """An error event (sent when the server rejects the start event) raises.""" + data = {"event": "error", "error": 'Invalid language "en us".'} + with pytest.raises(WebSocketError, match='Invalid language "en us"'): + _process_audio_event(data) + def test_finish_event_with_stop_returns_none(self): """Test that finish event with stop reason returns None.""" data = {"event": "finish", "reason": "stop"} From 3b02fd4b37d75b505d1c3cc635d609493a7ee295 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:47:54 -0800 Subject: [PATCH 04/10] fix(tts): a refused stream_websocket handshake raises the SDK's error class A bad key, no credit or a rate limit on the /v1/tts/live handshake raised the bare httpx_ws.WebSocketUpgradeError, so except AuthenticationError or except FishAudioError did not catch it, unlike realtime speech to text and every REST call. It now raises the APIError subclass for the status (AuthenticationError for 401, RateLimitError for 429, ...), with the response headers; the upgrade error is kept as its __cause__. Only entering the connection is mapped: an error raised inside it, for example by text_stream, passes through unchanged. How the stream runs and ends is not touched. --- README.md | 2 +- src/fishaudio/resources/tts.py | 64 +++++++++++++++++++++++++------ tests/unit/test_error_headers.py | 66 +++++++++++++++++++++++++++++--- tests/unit/test_user_agent.py | 5 +-- 4 files changed, 117 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index bcb53ef..a04969c 100644 --- a/README.md +++ b/README.md @@ -422,7 +422,7 @@ except APIError as e: print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code")) ``` -A `tts.stream_websocket` handshake that the server refuses raises `httpx_ws.WebSocketUpgradeError`; read the same headers from `e.response.headers`. +A `tts.stream_websocket` handshake that the server refuses raises the same classes (`AuthenticationError` for an invalid key), with the same `headers`. Earlier releases raised the bare `httpx_ws.WebSocketUpgradeError`; it is now the error's `__cause__`. ### Trace IDs diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index c5d9cfa..968664e 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -11,7 +11,13 @@ from typing import Any, Callable, Optional, TypeVar, Union, cast import ormsgpack -from httpx_ws import AsyncWebSocketSession, WebSocketSession, aconnect_ws, connect_ws +from httpx_ws import ( + AsyncWebSocketSession, + WebSocketSession, + WebSocketUpgradeError, + aconnect_ws, + connect_ws, +) from fishaudio.core import ( AsyncClientWrapper, @@ -46,11 +52,43 @@ ) from fishaudio.types.shared import warn_if_deprecated_model +from .asr_realtime import _upgrade_error from .realtime import aiter_websocket_audio, iter_websocket_audio _F = TypeVar("_F", bound=Callable[..., Any]) +class _MappedHandshake: + """Wrap connect_ws / aconnect_ws: a refused handshake raises the SDK error. + + Only entering the connection is mapped (the HTTP status to the APIError + subclass, as realtime speech to text and REST calls do, with the + upgrade error as its __cause__). An error raised inside the ``with`` + block, such as one from text_stream, passes through unchanged. + """ + + def __init__(self, connection: Any) -> None: + self._connection = connection + + def __enter__(self) -> WebSocketSession: + try: + return self._connection.__enter__() + except WebSocketUpgradeError as e: + raise _upgrade_error(e.response) from e + + def __exit__(self, *exc_info: object) -> Any: + return self._connection.__exit__(*exc_info) + + async def __aenter__(self) -> AsyncWebSocketSession: + try: + return await self._connection.__aenter__() + except WebSocketUpgradeError as e: + raise _upgrade_error(e.response) from e + + async def __aexit__(self, *exc_info: object) -> Any: + return await self._connection.__aexit__(*exc_info) + + def _warns_when_called(stream_function: _F) -> _F: """Check the model when the method is called, not when its stream is used. @@ -618,11 +656,13 @@ def text_generator(): try: ws: WebSocketSession - with connect_ws( - "/v1/tts/live", - client=self._client.client, - headers=headers, - **ws_kwargs, + with _MappedHandshake( + connect_ws( + "/v1/tts/live", + client=self._client.client, + headers=headers, + **ws_kwargs, + ) ) as ws: def sender(): @@ -1113,11 +1153,13 @@ async def text_generator(): headers = _handshake_headers(self._client, model, ws_options) ws: AsyncWebSocketSession - async with aconnect_ws( - "/v1/tts/live", - client=self._client.client, - headers=headers, - **ws_kwargs, + async with _MappedHandshake( + aconnect_ws( + "/v1/tts/live", + client=self._client.client, + headers=headers, + **ws_kwargs, + ) ) as ws: async def sender(): diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index c394eb0..e60af66 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -129,19 +129,75 @@ def test_error_built_without_headers_has_empty_headers(): assert len(error.headers) == 0 -def test_refused_tts_websocket_exposes_the_headers_on_the_upgrade_error(): - """The README's second path: tts.stream_websocket is not wrapped.""" +def test_refused_tts_websocket_keeps_the_upgrade_error_as_its_cause(): + """Earlier releases raised the bare upgrade error; it is now the cause.""" server = RealtimeServer(lambda conn: None, reject_status=401) try: with ( FishAudio(api_key="k", base_url=server.url) as client, - pytest.raises(WebSocketUpgradeError) as exc_info, + pytest.raises(AuthenticationError) as exc_info, ): list(client.tts.stream_websocket(iter(["hi"]))) finally: server.close() - assert exc_info.value.response.status_code == 401 - assert exc_info.value.response.headers["x-fish-trace-id"] == "trace-123" + cause = exc_info.value.__cause__ + assert isinstance(cause, WebSocketUpgradeError) + assert cause.response.status_code == 401 + assert cause.response.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.parametrize( + ("status", "error_class"), + [(401, AuthenticationError), (429, RateLimitError), (503, ServerError)], +) +def test_refused_tts_websocket_raises_the_sdk_class_with_headers(status, error_class): + server = RealtimeServer(lambda conn: None, reject_status=status) + try: + with ( + FishAudio(api_key="k", base_url=server.url) as client, + pytest.raises(APIError) as exc_info, + ): + list(client.tts.stream_websocket(iter(["hi"]))) + finally: + server.close() + assert type(exc_info.value) is error_class + assert exc_info.value.status == status + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.asyncio +async def test_refused_async_tts_websocket_raises_the_sdk_class_with_headers(): + server = RealtimeServer(lambda conn: None, reject_status=429) + + async def text(): + yield "hi" + + try: + async with AsyncFishAudio(api_key="k", base_url=server.url) as client: + with pytest.raises(RateLimitError) as exc_info: + async for _ in client.tts.stream_websocket(text()): + pass + finally: + server.close() + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + assert isinstance(exc_info.value.__cause__, WebSocketUpgradeError) + + +def test_only_the_handshake_is_mapped(): + """An upgrade error raised inside the connection (for example by + text_stream) is not the server refusing this one: it passes unchanged.""" + from fishaudio.resources.tts import _MappedHandshake + + response = httpx.Response( + 429, request=httpx.Request("GET", "https://api.fish.audio/v1/tts/live") + ) + own = WebSocketUpgradeError(response) + with ( + pytest.raises(WebSocketUpgradeError) as exc_info, + _MappedHandshake(contextlib.nullcontext()), + ): + raise own + assert exc_info.value is own @pytest.mark.parametrize( diff --git a/tests/unit/test_user_agent.py b/tests/unit/test_user_agent.py index 2d167c0..fc50aa8 100644 --- a/tests/unit/test_user_agent.py +++ b/tests/unit/test_user_agent.py @@ -15,7 +15,6 @@ import httpx import pytest -from httpx_ws import WebSocketUpgradeError from fishaudio import AsyncFishAudio, FishAudio, __version__ from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions @@ -320,7 +319,7 @@ class TestWebSockets: def test_tts_websocket_handshake(self): with refusing_ws_server() as server: client = FishAudio(api_key="test-key", base_url=server.url) - with pytest.raises(WebSocketUpgradeError): + with pytest.raises(APIError): for _ in client.tts.stream_websocket(iter(["hi"])): pass client.close() @@ -335,7 +334,7 @@ async def test_async_tts_websocket_handshake(self): async def text(): yield "hi" - with pytest.raises(WebSocketUpgradeError): + with pytest.raises(APIError): async for _ in client.tts.stream_websocket(text()): pass await client.close() From 15d0510492c5687ea60f1d5eaff81888b42db726 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:55:29 -0800 Subject: [PATCH 05/10] fix(tts): raise an async stream_websocket error as itself, not in a group httpx-ws 0.9 and later run the connection in an anyio task group, so an error raised inside the async stream (a finish with reason "error", the server's error event, a text_stream failure) reached the caller wrapped in an ExceptionGroup, and except WebSocketError did not catch it. That is what pip installs on Python 3.10 and later. When the group holds one error, that error is raised as it is, as on httpx-ws 0.7/0.8 and in the sync stream; a group of several errors is left as it is. --- src/fishaudio/resources/tts.py | 16 ++++++++++++- tests/unit/test_tts_realtime.py | 41 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 968664e..fbf207f 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -6,6 +6,7 @@ import functools import inspect import json +import sys from collections.abc import AsyncIterable, Iterable, Iterator from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, TypeVar, Union, cast @@ -53,6 +54,10 @@ from fishaudio.types.shared import warn_if_deprecated_model from .asr_realtime import _upgrade_error + +if sys.version_info < (3, 11): + # Installed with anyio (an httpx dependency) on these versions. + from exceptiongroup import ExceptionGroup from .realtime import aiter_websocket_audio, iter_websocket_audio _F = TypeVar("_F", bound=Callable[..., Any]) @@ -86,7 +91,16 @@ async def __aenter__(self) -> AsyncWebSocketSession: raise _upgrade_error(e.response) from e async def __aexit__(self, *exc_info: object) -> Any: - return await self._connection.__aexit__(*exc_info) + try: + return await self._connection.__aexit__(*exc_info) + except ExceptionGroup as group: + # httpx-ws 0.9+ runs the connection in an anyio task group, which + # wraps an error raised inside it (a server error event, a + # text_stream failure) in an ExceptionGroup. With one error in it, + # raise that error, as httpx-ws 0.7/0.8 and the sync stream do. + if len(group.exceptions) == 1: + raise group.exceptions[0] + raise def _warns_when_called(stream_function: _F) -> _F: diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 8100579..6980c63 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -1,14 +1,19 @@ """Tests for TTS realtime streaming.""" +import sys from unittest.mock import AsyncMock, MagicMock, Mock, patch import ormsgpack import pytest from fishaudio.core import AsyncClientWrapper, ClientWrapper, WebSocketOptions +from fishaudio.exceptions import WebSocketError from fishaudio.resources.tts import AsyncTTSClient, TTSClient from fishaudio.types import FlushEvent, Prosody, ReferenceAudio, TextEvent, TTSConfig +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + @pytest.fixture def mock_client_wrapper(mock_api_key): @@ -722,3 +727,39 @@ async def text_stream(): assert ( mock_aconnect_ws.call_args[1]["keepalive_ping_timeout_seconds"] == 60.0 ) + + +class TestAsyncErrorIsNotWrapped: + """httpx-ws 0.9+ runs the connection in an anyio task group, which wraps an + error raised inside it in an ExceptionGroup; the stream raises the error.""" + + @staticmethod + def _connection(error: BaseException): + class Connection: + async def __aenter__(self): + return None + + async def __aexit__(self, *exc_info): + raise error + + return Connection() + + @pytest.mark.asyncio + async def test_one_error_is_raised_as_itself(self): + from fishaudio.resources.tts import _MappedHandshake + + inner = WebSocketError("WebSocket stream failed: Invalid language") + with pytest.raises(WebSocketError) as exc_info: + async with _MappedHandshake(self._connection(ExceptionGroup("", [inner]))): + pass + assert exc_info.value is inner + + @pytest.mark.asyncio + async def test_several_errors_stay_grouped(self): + from fishaudio.resources.tts import _MappedHandshake + + group = ExceptionGroup("", [ValueError("a"), KeyError("b")]) + with pytest.raises(ExceptionGroup) as exc_info: + async with _MappedHandshake(self._connection(group)): + pass + assert exc_info.value is group From 667913153bc334d7c2d1b861d8f50b2d9ca66d6d Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:11:19 -0800 Subject: [PATCH 06/10] revert(tts): leave the refused-handshake mapping to its own change A refused stream_websocket handshake raises httpx_ws.WebSocketUpgradeError again, as on main. Raising the SDK's error class instead changes what an existing `except WebSocketUpgradeError` handler catches (a 429 retry written against main stops matching), so it is a compatibility decision of its own and goes with the stream lifecycle change, with an upgrade note. Its README sentence and tests go with it. The async exit wrapper keeps only the group unwrapping. --- README.md | 2 +- src/fishaudio/resources/tts.py | 48 +++++------------------ tests/unit/test_error_headers.py | 66 +++----------------------------- tests/unit/test_tts_realtime.py | 8 ++-- tests/unit/test_user_agent.py | 5 ++- 5 files changed, 23 insertions(+), 106 deletions(-) diff --git a/README.md b/README.md index a04969c..bcb53ef 100644 --- a/README.md +++ b/README.md @@ -422,7 +422,7 @@ except APIError as e: print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code")) ``` -A `tts.stream_websocket` handshake that the server refuses raises the same classes (`AuthenticationError` for an invalid key), with the same `headers`. Earlier releases raised the bare `httpx_ws.WebSocketUpgradeError`; it is now the error's `__cause__`. +A `tts.stream_websocket` handshake that the server refuses raises `httpx_ws.WebSocketUpgradeError`; read the same headers from `e.response.headers`. ### Trace IDs diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index fbf207f..0bffbbf 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -12,13 +12,7 @@ from typing import Any, Callable, Optional, TypeVar, Union, cast import ormsgpack -from httpx_ws import ( - AsyncWebSocketSession, - WebSocketSession, - WebSocketUpgradeError, - aconnect_ws, - connect_ws, -) +from httpx_ws import AsyncWebSocketSession, WebSocketSession, aconnect_ws, connect_ws from fishaudio.core import ( AsyncClientWrapper, @@ -53,8 +47,6 @@ ) from fishaudio.types.shared import warn_if_deprecated_model -from .asr_realtime import _upgrade_error - if sys.version_info < (3, 11): # Installed with anyio (an httpx dependency) on these versions. from exceptiongroup import ExceptionGroup @@ -63,32 +55,14 @@ _F = TypeVar("_F", bound=Callable[..., Any]) -class _MappedHandshake: - """Wrap connect_ws / aconnect_ws: a refused handshake raises the SDK error. - - Only entering the connection is mapped (the HTTP status to the APIError - subclass, as realtime speech to text and REST calls do, with the - upgrade error as its __cause__). An error raised inside the ``with`` - block, such as one from text_stream, passes through unchanged. - """ +class _GroupUnwrapped: + """Wrap aconnect_ws so an error raised inside it is not left in a group.""" def __init__(self, connection: Any) -> None: self._connection = connection - def __enter__(self) -> WebSocketSession: - try: - return self._connection.__enter__() - except WebSocketUpgradeError as e: - raise _upgrade_error(e.response) from e - - def __exit__(self, *exc_info: object) -> Any: - return self._connection.__exit__(*exc_info) - async def __aenter__(self) -> AsyncWebSocketSession: - try: - return await self._connection.__aenter__() - except WebSocketUpgradeError as e: - raise _upgrade_error(e.response) from e + return await self._connection.__aenter__() async def __aexit__(self, *exc_info: object) -> Any: try: @@ -670,13 +644,11 @@ def text_generator(): try: ws: WebSocketSession - with _MappedHandshake( - connect_ws( - "/v1/tts/live", - client=self._client.client, - headers=headers, - **ws_kwargs, - ) + with connect_ws( + "/v1/tts/live", + client=self._client.client, + headers=headers, + **ws_kwargs, ) as ws: def sender(): @@ -1167,7 +1139,7 @@ async def text_generator(): headers = _handshake_headers(self._client, model, ws_options) ws: AsyncWebSocketSession - async with _MappedHandshake( + async with _GroupUnwrapped( aconnect_ws( "/v1/tts/live", client=self._client.client, diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index e60af66..c394eb0 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -129,75 +129,19 @@ def test_error_built_without_headers_has_empty_headers(): assert len(error.headers) == 0 -def test_refused_tts_websocket_keeps_the_upgrade_error_as_its_cause(): - """Earlier releases raised the bare upgrade error; it is now the cause.""" +def test_refused_tts_websocket_exposes_the_headers_on_the_upgrade_error(): + """The README's second path: tts.stream_websocket is not wrapped.""" server = RealtimeServer(lambda conn: None, reject_status=401) try: with ( FishAudio(api_key="k", base_url=server.url) as client, - pytest.raises(AuthenticationError) as exc_info, + pytest.raises(WebSocketUpgradeError) as exc_info, ): list(client.tts.stream_websocket(iter(["hi"]))) finally: server.close() - cause = exc_info.value.__cause__ - assert isinstance(cause, WebSocketUpgradeError) - assert cause.response.status_code == 401 - assert cause.response.headers["x-fish-trace-id"] == "trace-123" - - -@pytest.mark.parametrize( - ("status", "error_class"), - [(401, AuthenticationError), (429, RateLimitError), (503, ServerError)], -) -def test_refused_tts_websocket_raises_the_sdk_class_with_headers(status, error_class): - server = RealtimeServer(lambda conn: None, reject_status=status) - try: - with ( - FishAudio(api_key="k", base_url=server.url) as client, - pytest.raises(APIError) as exc_info, - ): - list(client.tts.stream_websocket(iter(["hi"]))) - finally: - server.close() - assert type(exc_info.value) is error_class - assert exc_info.value.status == status - assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" - - -@pytest.mark.asyncio -async def test_refused_async_tts_websocket_raises_the_sdk_class_with_headers(): - server = RealtimeServer(lambda conn: None, reject_status=429) - - async def text(): - yield "hi" - - try: - async with AsyncFishAudio(api_key="k", base_url=server.url) as client: - with pytest.raises(RateLimitError) as exc_info: - async for _ in client.tts.stream_websocket(text()): - pass - finally: - server.close() - assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" - assert isinstance(exc_info.value.__cause__, WebSocketUpgradeError) - - -def test_only_the_handshake_is_mapped(): - """An upgrade error raised inside the connection (for example by - text_stream) is not the server refusing this one: it passes unchanged.""" - from fishaudio.resources.tts import _MappedHandshake - - response = httpx.Response( - 429, request=httpx.Request("GET", "https://api.fish.audio/v1/tts/live") - ) - own = WebSocketUpgradeError(response) - with ( - pytest.raises(WebSocketUpgradeError) as exc_info, - _MappedHandshake(contextlib.nullcontext()), - ): - raise own - assert exc_info.value is own + assert exc_info.value.response.status_code == 401 + assert exc_info.value.response.headers["x-fish-trace-id"] == "trace-123" @pytest.mark.parametrize( diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 6980c63..300d62d 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -746,20 +746,20 @@ async def __aexit__(self, *exc_info): @pytest.mark.asyncio async def test_one_error_is_raised_as_itself(self): - from fishaudio.resources.tts import _MappedHandshake + from fishaudio.resources.tts import _GroupUnwrapped inner = WebSocketError("WebSocket stream failed: Invalid language") with pytest.raises(WebSocketError) as exc_info: - async with _MappedHandshake(self._connection(ExceptionGroup("", [inner]))): + async with _GroupUnwrapped(self._connection(ExceptionGroup("", [inner]))): pass assert exc_info.value is inner @pytest.mark.asyncio async def test_several_errors_stay_grouped(self): - from fishaudio.resources.tts import _MappedHandshake + from fishaudio.resources.tts import _GroupUnwrapped group = ExceptionGroup("", [ValueError("a"), KeyError("b")]) with pytest.raises(ExceptionGroup) as exc_info: - async with _MappedHandshake(self._connection(group)): + async with _GroupUnwrapped(self._connection(group)): pass assert exc_info.value is group diff --git a/tests/unit/test_user_agent.py b/tests/unit/test_user_agent.py index fc50aa8..2d167c0 100644 --- a/tests/unit/test_user_agent.py +++ b/tests/unit/test_user_agent.py @@ -15,6 +15,7 @@ import httpx import pytest +from httpx_ws import WebSocketUpgradeError from fishaudio import AsyncFishAudio, FishAudio, __version__ from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions @@ -319,7 +320,7 @@ class TestWebSockets: def test_tts_websocket_handshake(self): with refusing_ws_server() as server: client = FishAudio(api_key="test-key", base_url=server.url) - with pytest.raises(APIError): + with pytest.raises(WebSocketUpgradeError): for _ in client.tts.stream_websocket(iter(["hi"])): pass client.close() @@ -334,7 +335,7 @@ async def test_async_tts_websocket_handshake(self): async def text(): yield "hi" - with pytest.raises(APIError): + with pytest.raises(WebSocketUpgradeError): async for _ in client.tts.stream_websocket(text()): pass await client.close() From 35014374bdafcc108a4ad99b24c96e74b313937a Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:13:35 -0800 Subject: [PATCH 07/10] fix(tts): unwrap only the async stream's own error from the task group The wrapper raised the single member of any one-item group, so a failure while the connection closes (for example the response stream raising in cleanup) lost its group, unlike main. It now unwraps only when the group holds exactly the exception raised inside the connection block, the same object. Any other group, including the GeneratorExit group of an early aclose() on httpx-ws 0.9+, passes through unchanged, as on main. --- src/fishaudio/resources/tts.py | 30 +++++++++++++------ tests/unit/test_tts_language.py | 52 +++++++++++++++++++++++++++++++++ tests/unit/test_tts_realtime.py | 51 +++++++++++++++++++++++++++----- 3 files changed, 117 insertions(+), 16 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 0bffbbf..754728f 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -9,6 +9,7 @@ import sys from collections.abc import AsyncIterable, Iterable, Iterator from concurrent.futures import ThreadPoolExecutor +from types import TracebackType from typing import Any, Callable, Optional, TypeVar, Union, cast import ormsgpack @@ -56,7 +57,16 @@ class _GroupUnwrapped: - """Wrap aconnect_ws so an error raised inside it is not left in a group.""" + """Wrap aconnect_ws so the stream's own error is not left in a group. + + httpx-ws 0.9+ runs the connection in an anyio task group, which wraps an + error raised inside the ``async with`` block (a server error event, a + text_stream failure) in an ExceptionGroup. When the group that leaves the + block holds exactly that one exception, the same object, it is raised as + itself, as on httpx-ws 0.7/0.8 and in the sync stream. Any other group, + such as a failure while the connection is closed or the GeneratorExit of + an early close, passes through unchanged. + """ def __init__(self, connection: Any) -> None: self._connection = connection @@ -64,16 +74,18 @@ def __init__(self, connection: Any) -> None: async def __aenter__(self) -> AsyncWebSocketSession: return await self._connection.__aenter__() - async def __aexit__(self, *exc_info: object) -> Any: + async def __aexit__( + self, + exc_type: Optional[type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> Any: try: - return await self._connection.__aexit__(*exc_info) + return await self._connection.__aexit__(exc_type, exc, tb) except ExceptionGroup as group: - # httpx-ws 0.9+ runs the connection in an anyio task group, which - # wraps an error raised inside it (a server error event, a - # text_stream failure) in an ExceptionGroup. With one error in it, - # raise that error, as httpx-ws 0.7/0.8 and the sync stream do. - if len(group.exceptions) == 1: - raise group.exceptions[0] + # Identity, not type: only the exception raised in the block. + if len(group.exceptions) == 1 and group.exceptions[0] is exc: + raise exc raise diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 1bb4b22..78cff89 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -6,7 +6,9 @@ as nil. """ +import asyncio import contextlib +from importlib.metadata import version import httpx import ormsgpack @@ -20,6 +22,12 @@ from .realtime_server import RealtimeServer +# httpx-ws 0.9 and later run the connection in an anyio task group. +_HTTPX_WS_TASK_GROUP = tuple(int(p) for p in version("httpx-ws").split(".")[:2]) >= ( + 0, + 9, +) + BASE_URL = "https://api.test.fish.audio" SSE_BODY = ( @@ -242,3 +250,47 @@ async def test_async_rejected_start_event_raises_instead_of_hanging(self): ): pass server.stop() + + async def test_async_rejected_start_event_is_not_in_a_group(self): + """On httpx-ws 0.9+ the error event used to reach the caller inside an + ExceptionGroup, which `except WebSocketError` does not catch.""" + async with aserving(rejecting_script) as (server, client): + caught = None + try: + async for _ in client.tts.stream_websocket( + _aiter("Hola"), language="en us" + ): + pass + except WebSocketError as e: + caught = e + server.stop() + assert type(caught) is WebSocketError + + async def test_async_early_close_is_as_on_main(self): + """Closing the stream after the first chunk is not changed here: on + httpx-ws 0.9+ aclose() raises BaseExceptionGroup([GeneratorExit]), as + on main; the stream lifecycle change addresses it.""" + + def script(conn): + conn.recv() + for _ in range(3): + conn.send({"event": "audio", "audio": b"x"}) + conn.recv() # until the client leaves + + async def text(): + yield "Hola" + await asyncio.sleep(5) + + async with aserving(script) as (server, client): + stream = client.tts.stream_websocket(text()) + assert await stream.__anext__() == b"x" + raised = None + try: + await stream.aclose() + except BaseException as e: # noqa: BLE001 - recorded and checked below + raised = e + server.stop() + if _HTTPX_WS_TASK_GROUP: + assert [type(x) for x in raised.exceptions] == [GeneratorExit] + else: + assert raised is None diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 300d62d..18dceaf 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -12,7 +12,7 @@ from fishaudio.types import FlushEvent, Prosody, ReferenceAudio, TextEvent, TTSConfig if sys.version_info < (3, 11): - from exceptiongroup import ExceptionGroup + from exceptiongroup import BaseExceptionGroup, ExceptionGroup @pytest.fixture @@ -731,7 +731,8 @@ async def text_stream(): class TestAsyncErrorIsNotWrapped: """httpx-ws 0.9+ runs the connection in an anyio task group, which wraps an - error raised inside it in an ExceptionGroup; the stream raises the error.""" + error raised inside it in an ExceptionGroup. Only a group holding exactly + the exception raised in the stream is unwrapped; any other passes.""" @staticmethod def _connection(error: BaseException): @@ -745,21 +746,57 @@ async def __aexit__(self, *exc_info): return Connection() @pytest.mark.asyncio - async def test_one_error_is_raised_as_itself(self): + async def test_the_stream_s_own_error_is_raised_as_itself(self): from fishaudio.resources.tts import _GroupUnwrapped inner = WebSocketError("WebSocket stream failed: Invalid language") + group = ExceptionGroup("", [inner]) with pytest.raises(WebSocketError) as exc_info: - async with _GroupUnwrapped(self._connection(ExceptionGroup("", [inner]))): - pass + async with _GroupUnwrapped(self._connection(group)): + raise inner assert exc_info.value is inner @pytest.mark.asyncio - async def test_several_errors_stay_grouped(self): + async def test_a_group_from_closing_the_connection_stays_a_group(self): + """Nothing raised in the block: a one-item group from cleanup (for + example the response stream failing as it closes) is left as it is.""" from fishaudio.resources.tts import _GroupUnwrapped - group = ExceptionGroup("", [ValueError("a"), KeyError("b")]) + group = ExceptionGroup("", [ValueError("response stream failed")]) with pytest.raises(ExceptionGroup) as exc_info: async with _GroupUnwrapped(self._connection(group)): pass assert exc_info.value is group + + @pytest.mark.asyncio + async def test_another_error_in_the_group_stays_a_group(self): + from fishaudio.resources.tts import _GroupUnwrapped + + group = ExceptionGroup("", [ValueError("from cleanup")]) + with pytest.raises(ExceptionGroup) as exc_info: + async with _GroupUnwrapped(self._connection(group)): + raise WebSocketError("raised in the block") + assert exc_info.value is group + + @pytest.mark.asyncio + async def test_several_errors_stay_grouped(self): + from fishaudio.resources.tts import _GroupUnwrapped + + inner = WebSocketError("raised in the block") + group = ExceptionGroup("", [inner, ValueError("from cleanup")]) + with pytest.raises(ExceptionGroup) as exc_info: + async with _GroupUnwrapped(self._connection(group)): + raise inner + assert exc_info.value is group + + @pytest.mark.asyncio + async def test_early_close_group_passes_through(self): + """The GeneratorExit of an early aclose() is not unwrapped.""" + from fishaudio.resources.tts import _GroupUnwrapped + + exit_ = GeneratorExit() + group = BaseExceptionGroup("", [exit_]) + with pytest.raises(BaseExceptionGroup) as exc_info: + async with _GroupUnwrapped(self._connection(group)): + raise exit_ + assert exc_info.value is group From 48d9716b54b5d62d8374d06aa5b095815e2b9fee Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:22:46 -0800 Subject: [PATCH 08/10] fix(tts): read a pickled pre-language config as unset; propagate the stream's own error A TTSConfig or TTSRequest pickled by an earlier release has no language attribute (Pydantic restores the saved attributes as they are), so converting the config or serializing the request raised AttributeError before anything was sent. Both reads now treat a missing attribute as unset. The async group handler now returns False for the stream's own error, so Python propagates it as it was raised, instead of re-raising it inside the handler, which chained the ExceptionGroup to it and put the group in every logged traceback. The early-close test no longer requires aclose() to fail on httpx-ws 0.9+; the wrapper's unit tests still check that any other group, including GeneratorExit from an early close, passes through unchanged. --- src/fishaudio/resources/tts.py | 7 ++-- src/fishaudio/types/tts.py | 3 +- tests/unit/test_tts_language.py | 59 ++++++++++++--------------------- tests/unit/test_tts_realtime.py | 9 +++++ 4 files changed, 38 insertions(+), 40 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 754728f..015c988 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -84,8 +84,10 @@ async def __aexit__( return await self._connection.__aexit__(exc_type, exc, tb) except ExceptionGroup as group: # Identity, not type: only the exception raised in the block. + # Returning False lets Python propagate that exception as it was, + # so its traceback does not show the group. if len(group.exceptions) == 1 and group.exceptions[0] is exc: - raise exc + return False raise @@ -119,7 +121,8 @@ def _config_to_tts_request(config: TTSConfig, text: str) -> TTSRequest: references=config.references, reference_id=config.reference_id, normalize=config.normalize, - language=config.language, + # getattr: a config pickled before language existed has no attribute. + language=getattr(config, "language", None), latency=config.latency, prosody=config.prosody, top_p=config.top_p, diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index 43d6898..a30dce6 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -188,7 +188,8 @@ def _omit_unset_language(self, handler: SerializerFunctionWrapHandler): # No return annotation: Pydantic would publish it as the # serialization schema in place of the model's fields. data = handler(self) - if self.language is None: + # getattr: a request pickled before language existed has no attribute. + if getattr(self, "language", None) is None: data.pop("language", None) return data diff --git a/tests/unit/test_tts_language.py b/tests/unit/test_tts_language.py index 78cff89..6c7ce27 100644 --- a/tests/unit/test_tts_language.py +++ b/tests/unit/test_tts_language.py @@ -6,9 +6,7 @@ as nil. """ -import asyncio import contextlib -from importlib.metadata import version import httpx import ormsgpack @@ -22,12 +20,6 @@ from .realtime_server import RealtimeServer -# httpx-ws 0.9 and later run the connection in an anyio task group. -_HTTPX_WS_TASK_GROUP = tuple(int(p) for p in version("httpx-ws").split(".")[:2]) >= ( - 0, - 9, -) - BASE_URL = "https://api.test.fish.audio" SSE_BODY = ( @@ -78,6 +70,28 @@ def _async_tts(seen, response_body=b"audio"): class TestTypes: + @staticmethod + def _as_pickled_before_language(obj): + # Pydantic restores a pickle's saved attributes as they are, so an + # object pickled by an earlier release has no language attribute. + del obj.__dict__["language"] + return obj + + def test_config_pickled_before_language_converts(self): + from fishaudio.resources.tts import _config_to_tts_request + + config = self._as_pickled_before_language(TTSConfig(format="wav")) + request = _config_to_tts_request(config, "Hola") + assert request.language is None + assert "language" not in request.model_dump() + + def test_request_pickled_before_language_serializes(self): + request = self._as_pickled_before_language(TTSRequest(text="Hola")) + assert "language" not in request.model_dump() + start = StartEvent(request=request).model_dump() + assert "language" not in start["request"] + assert ormsgpack.unpackb(ormsgpack.packb(start))["request"]["text"] == "Hola" + def test_config_defaults_to_unset(self): assert TTSConfig().language is None @@ -265,32 +279,3 @@ async def test_async_rejected_start_event_is_not_in_a_group(self): caught = e server.stop() assert type(caught) is WebSocketError - - async def test_async_early_close_is_as_on_main(self): - """Closing the stream after the first chunk is not changed here: on - httpx-ws 0.9+ aclose() raises BaseExceptionGroup([GeneratorExit]), as - on main; the stream lifecycle change addresses it.""" - - def script(conn): - conn.recv() - for _ in range(3): - conn.send({"event": "audio", "audio": b"x"}) - conn.recv() # until the client leaves - - async def text(): - yield "Hola" - await asyncio.sleep(5) - - async with aserving(script) as (server, client): - stream = client.tts.stream_websocket(text()) - assert await stream.__anext__() == b"x" - raised = None - try: - await stream.aclose() - except BaseException as e: # noqa: BLE001 - recorded and checked below - raised = e - server.stop() - if _HTTPX_WS_TASK_GROUP: - assert [type(x) for x in raised.exceptions] == [GeneratorExit] - else: - assert raised is None diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 18dceaf..53e43b6 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -1,6 +1,7 @@ """Tests for TTS realtime streaming.""" import sys +import traceback from unittest.mock import AsyncMock, MagicMock, Mock, patch import ormsgpack @@ -755,6 +756,14 @@ async def test_the_stream_s_own_error_is_raised_as_itself(self): async with _GroupUnwrapped(self._connection(group)): raise inner assert exc_info.value is inner + # Propagated as it was: the group is not chained to it, so logs and + # tracebacks do not show it. + assert exc_info.value.__context__ is None + assert "ExceptionGroup" not in "".join( + traceback.format_exception( + type(exc_info.value), exc_info.value, exc_info.value.__traceback__ + ) + ) @pytest.mark.asyncio async def test_a_group_from_closing_the_connection_stays_a_group(self): From 2ff79853bc7270aa96573c984b06bde8803d6dcd Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:50:22 -0800 Subject: [PATCH 09/10] fix(tts): recognize the task group without importing the exceptiongroup backport The type check runs on Python 3.14, where the exceptiongroup backport is not installed, and the import guarded by sys.version_info < (3, 11) still failed to resolve because the package supports Python 3.9. The handler now recognizes a group by its `exceptions` tuple, which both the builtin ExceptionGroup and the backport have, so the SDK imports neither. Only a group whose single member is the exception raised in the block is unwrapped, as before. --- src/fishaudio/resources/tts.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 015c988..e1922b7 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -6,7 +6,6 @@ import functools import inspect import json -import sys from collections.abc import AsyncIterable, Iterable, Iterator from concurrent.futures import ThreadPoolExecutor from types import TracebackType @@ -48,9 +47,6 @@ ) from fishaudio.types.shared import warn_if_deprecated_model -if sys.version_info < (3, 11): - # Installed with anyio (an httpx dependency) on these versions. - from exceptiongroup import ExceptionGroup from .realtime import aiter_websocket_audio, iter_websocket_audio _F = TypeVar("_F", bound=Callable[..., Any]) @@ -82,11 +78,20 @@ async def __aexit__( ) -> Any: try: return await self._connection.__aexit__(exc_type, exc, tb) - except ExceptionGroup as group: - # Identity, not type: only the exception raised in the block. - # Returning False lets Python propagate that exception as it was, - # so its traceback does not show the group. - if len(group.exceptions) == 1 and group.exceptions[0] is exc: + except Exception as group: + # Recognized by its ``exceptions`` (the builtin ExceptionGroup, or + # the exceptiongroup backport anyio uses before Python 3.11), so + # the SDK imports neither. Identity, not type: only a group whose + # one member is the exception raised in the block. Returning + # False lets Python propagate that exception as it was, so its + # traceback does not show the group. + members = getattr(group, "exceptions", None) + if ( + group is not exc + and isinstance(members, tuple) + and len(members) == 1 + and members[0] is exc + ): return False raise From 3c18eedc29970b4a292f01ff8ae0229789ebf9ac Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:50:22 -0800 Subject: [PATCH 10/10] docs: run the regional language example on s2.1-pro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The example called TTS without a model, so it ran on the default s3-pro, which normalizes a regional tag with its base language: "$300" is read as pesos with es and es-MX alike. The peso/dólar difference is documented for s2.1-pro, s2-pro and s1. The example now names s2.1-pro, says why in its comment, and the text says which models apply regional conventions. --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dccf974..0c49ed1 100644 --- a/README.md +++ b/README.md @@ -147,14 +147,17 @@ audio = client.tts.convert( **Language of the text:** ```python -# "$300" is read as "trescientos pesos" with es-MX, "trescientos dólares" with es +# On s2.1-pro, "$300" is read as pesos with es-MX and as dólares with es. +# s3-pro, the default, normalizes a regional tag with its base language and +# reads this "$300" as pesos with es and es-MX alike. audio = client.tts.convert( text="La entrada cuesta $300.", + model="s2.1-pro", language="es-MX", ) ``` -`language` is a BCP-47 tag such as `en`, `es-MX` or `zh-CN`. It only changes how numbers, dates, units and symbols are spelled out before synthesis (and word-timestamp alignment); it does not change the voice or accent. Without it, the API detects the language of each chunk, which is also the right choice for text that mixes languages. It is accepted by every text-to-speech method and by `TTSConfig`; on `stream_websocket` it applies to the whole session. See [supported normalization languages](https://docs.fish.audio/features/text-to-speech#supported-normalization-languages). +`language` is a BCP-47 tag such as `en`, `es-MX` or `zh-CN`. Regional conventions (`es-MX` against `es`) apply on `s2.1-pro`, `s2-pro` and `s1`; `s3-pro` reads a regional tag as its base language. It only changes how numbers, dates, units and symbols are spelled out before synthesis (and word-timestamp alignment); it does not change the voice or accent. Without it, the API detects the language of each chunk, which is also the right choice for text that mixes languages. It is accepted by every text-to-speech method and by `TTSConfig`; on `stream_websocket` it applies to the whole session. See [supported normalization languages](https://docs.fish.audio/features/text-to-speech#supported-normalization-languages). **Reusable configuration:**