Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ audio = client.tts.convert(
)
```

**Language of the text:**

```python
# 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`. 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:**

```python
Expand Down
8 changes: 7 additions & 1 deletion src/fishaudio/resources/realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
100 changes: 95 additions & 5 deletions src/fishaudio/resources/tts.py

Large diffs are not rendered by default.

30 changes: 29 additions & 1 deletion src/fishaudio/types/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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),
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -165,6 +181,18 @@ 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):
# 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)
# getattr: a request pickled before language existed has no attribute.
if getattr(self, "language", None) is None:
data.pop("language", None)
return data


# WebSocket event types for streaming TTS
class StartEvent(BaseModel):
Expand Down
18 changes: 18 additions & 0 deletions tests/integration/test_tts_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
16 changes: 16 additions & 0 deletions tests/integration/test_tts_websocket_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/test_realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down
Loading