Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
588e6b0
fix(tts): raise on a WebSocket error event instead of waiting forever
lumpinif Nov 25, 2026
62343d3
feat(tts): add language option for text normalization (FISH-1400)
lumpinif Nov 25, 2026
0b1fb05
fix(tts): stop the WebSocket sender when the stream ends early
lumpinif Nov 25, 2026
3c3ba7b
test(tts): reject only after the first text in the sender-shutdown tests
lumpinif Nov 25, 2026
0034e2c
Merge remote-tracking branch 'origin/main' into feat/tts-language
lumpinif Nov 30, 2026
d15c864
fix(tts): keep TTSRequest's serialization schema
lumpinif Nov 30, 2026
60d8d2a
fix(tts): do not read text_stream again once the stream is over
lumpinif Dec 1, 2026
61a9bb2
Merge remote-tracking branch 'origin/main' into feat/tts-language
lumpinif Dec 1, 2026
41e74a4
fix(tts): send no stop once the stream is over
lumpinif Dec 1, 2026
97e913e
fix(tts): end the WebSocket stream when the server finishes first
lumpinif Dec 1, 2026
3e999be
fix(tts): send nothing more once the async stream has ended
lumpinif Dec 1, 2026
57268de
docs(tts): say what happens to text_stream when the stream ends first
lumpinif Dec 1, 2026
c1644cc
fix(tts): raise a text_stream error at once and close text_stream on …
lumpinif Dec 1, 2026
c941f9d
fix(tts): keep text_stream cleanup off the caller's path and uncut
lumpinif Dec 1, 2026
4e02e77
fix(tts): do not lose a send error while text_stream is being closed
lumpinif Dec 1, 2026
d545c72
fix(tts): close sync text_stream off the executor; keep every sender …
lumpinif Dec 1, 2026
4849fbb
docs(tts): say the sync text_stream is closed on a background thread
lumpinif Dec 1, 2026
95e6dc8
fix(tts): close a sync text_stream on the thread that ran it
lumpinif Dec 1, 2026
d15ef9e
fix(tts): close text_stream only once the SDK has read from it
lumpinif Dec 1, 2026
6702c41
fix(tts): report every async text_stream cancellation as WebSocketError
lumpinif Dec 1, 2026
5cdf1fe
test(tts): let the early-finish server script tolerate a client that …
lumpinif Dec 1, 2026
c84b6ff
fix(tts): let the server's finish decide over a failed send; never ha…
lumpinif Dec 1, 2026
1d28e11
fix(tts): a send that fails while receiving still names the cause; cl…
lumpinif Dec 1, 2026
8c0218f
fix(tts): log sync cleanup errors of every kind; order the receive-ra…
lumpinif Dec 1, 2026
d00c11b
fix(tts): one outcome rule for the receive loop
lumpinif Dec 1, 2026
ab5ed6b
refactor(tts): run the async stream's connection in a task of its own
lumpinif Dec 1, 2026
177295a
Test the outcome rules against a real broken write and paired faults
lumpinif Dec 1, 2026
926e514
Merge remote-tracking branch 'origin/main' into feat/tts-language
lumpinif Dec 2, 2026
09fc32b
style(tts): mark the deliberate broad catches for main's ruff rules
lumpinif Dec 2, 2026
5d9f592
fix(tts): async stream no longer waits forever when the session ends …
lumpinif Dec 2, 2026
4517507
refactor(tts): narrow stream_websocket to language, the error event a…
lumpinif Dec 2, 2026
4e0d96d
fix(tts): a finish does not hide a text_stream failure already recorded
lumpinif Dec 2, 2026
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,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
Expand Down
75 changes: 69 additions & 6 deletions src/fishaudio/resources/realtime.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
"""Real-time WebSocket streaming helpers."""

import queue
from collections.abc import AsyncIterator, Iterator
from typing import Any, Optional
from typing import Any, Callable, Optional

import ormsgpack
from httpx_ws import WebSocketDisconnect

from fishaudio.exceptions import WebSocketError

ErrorCheck = Callable[[], Optional[BaseException]]


def _should_stop(data: dict[str, Any]) -> bool:
"""
Expand All @@ -33,16 +36,26 @@ 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')}")
Comment thread
lumpinif marked this conversation as resolved.
Resolved
if data.get("event") == "finish" and data.get("reason") == "error":
raise WebSocketError("WebSocket stream ended with error")
return None # Ignore unknown events


def iter_websocket_audio(ws) -> Iterator[bytes]:
def iter_websocket_audio(
ws,
sender_failed: Optional[ErrorCheck] = None,
poll_seconds: float = 0.25,
) -> Iterator[bytes]:
"""
Process WebSocket audio messages (sync).

Expand All @@ -51,6 +64,10 @@ def iter_websocket_audio(ws) -> Iterator[bytes]:

Args:
ws: WebSocket connection from httpx_ws.connect_ws
sender_failed: Returns the error of the text sender, or None. When
given, a receive waits at most ``poll_seconds``; if nothing has
arrived by then and the sender has failed, its error is raised.
poll_seconds: How long a receive waits before checking ``sender_failed``.

Yields:
Audio bytes
Expand All @@ -60,10 +77,29 @@ def iter_websocket_audio(ws) -> Iterator[bytes]:
"""
while True:
try:
message = ws.receive_bytes()
if sender_failed is None:
message = ws.receive_bytes()
else:
try:
message = ws.receive_bytes(timeout=poll_seconds)
except (queue.Empty, TimeoutError): # nothing within poll_seconds
message = None
if message is None:
# Raised outside the except block, so the exception is
# raised as it is.
error = sender_failed()
if error is not None:
raise error
continue
data = ormsgpack.unpackb(message)

if _should_stop(data):
# A finish does not hide a sender failure already recorded:
# the server may have finished on the text sent before it.
if sender_failed is not None:
error = sender_failed()
if error is not None:
raise error
break

audio = _process_audio_event(data)
Expand All @@ -74,7 +110,11 @@ def iter_websocket_audio(ws) -> Iterator[bytes]:
raise WebSocketError("WebSocket disconnected unexpectedly")


async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]:
async def aiter_websocket_audio(
ws,
sender_failed: Optional[ErrorCheck] = None,
poll_seconds: float = 0.25,
) -> AsyncIterator[bytes]:
"""
Process WebSocket audio messages (async).

Expand All @@ -83,6 +123,10 @@ async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]:

Args:
ws: WebSocket connection from httpx_ws.aconnect_ws
sender_failed: Returns the error of the text sender, or None. When
given, a receive waits at most ``poll_seconds``; if nothing has
arrived by then and the sender has failed, its error is raised.
poll_seconds: How long a receive waits before checking ``sender_failed``.

Yields:
Audio bytes
Expand All @@ -92,10 +136,29 @@ async def aiter_websocket_audio(ws) -> AsyncIterator[bytes]:
"""
while True:
try:
message = await ws.receive_bytes()
if sender_failed is None:
message = await ws.receive_bytes()
else:
try:
message = await ws.receive_bytes(timeout=poll_seconds)
except (queue.Empty, TimeoutError): # nothing within poll_seconds
message = None
if message is None:
# Raised outside the except block, so the exception is
# raised as it is.
error = sender_failed()
if error is not None:
raise error
continue
data = ormsgpack.unpackb(message)

if _should_stop(data):
# A finish does not hide a sender failure already recorded:
# the server may have finished on the text sent before it.
if sender_failed is not None:
error = sender_failed()
if error is not None:
raise error
break

audio = _process_audio_event(data)
Expand Down
Loading