Skip to content
35 changes: 27 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,9 @@ audio = client.tts.stream(text="Hello!").collect()
### Speech-to-Text

```python
from fishaudio.core import RequestOptions

# transcribe-1-pro is the recommended model. Select it with the model header;
# without it, the request runs on transcribe-1.
pro = RequestOptions(additional_headers={"model": "transcribe-1-pro"})

# transcribe-1-pro is the recommended model; without model, the request runs on transcribe-1.
with open("meeting.wav", "rb") as f:
result = client.asr.transcribe(audio=f.read(), request_options=pro)
result = client.asr.transcribe(audio=f.read(), model="transcribe-1-pro")

# On transcribe-1-pro, text keeps <|speaker:N|> markers; speaker_turns has clean text per speaker.
print(result.text)
Expand All @@ -185,6 +180,30 @@ print(result.language_code) # e.g. "en"

[Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/speech-to-text)

**Realtime (Preview):** stream live audio to `transcribe-stream-1` and get the transcript turn by turn. Send 16-bit mono PCM in 20–40 ms chunks as you capture it:

```python
import wave

def audio_chunks():
with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM, 16 kHz
while chunk := wav.readframes(640): # 40 ms
yield chunk

# diarize=False gives plain text; by default it starts with a speaker tag: "<|speaker:0|> Hello."
for event in client.asr.stream_websocket(
audio_chunks(), sample_rate=16000, drafts=True, diarize=False
):
if event.type == "draft": # live text of the open turn, not final
print("...", event.text)
elif event.type == "committed": # final transcript of the turn
print(event.text)
```

With `AsyncFishAudio`, pass an async iterator and use `async for`. The returned stream also sends control messages during the session, such as `stream.finalize()` for push-to-talk and `stream.agent_speaking(True)` for voice agents.

[Learn more](https://docs.fish.audio/features/speech-to-text/realtime)

### Real-time Streaming

Stream dynamically generated text for conversational AI and live applications:
Expand Down Expand Up @@ -258,7 +277,7 @@ audio = client.tts.convert(
| Resource | Description | Key Methods |
|----------|-------------|-------------|
| `client.tts` | Text-to-speech | `convert()`, `stream()`, `stream_websocket()` |
| `client.asr` | Speech recognition | `transcribe()` |
| `client.asr` | Speech recognition | `transcribe()`, `stream_websocket()` |
| `client.voices` | Voice management | `list()`, `get()`, `create()`, `update()`, `delete()` |
| `client.account` | Account info | `get_credits()`, `get_package()` |

Expand Down
25 changes: 24 additions & 1 deletion src/fishaudio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from .core.websocket_options import WebSocketOptions
from .exceptions import (
APIError,
ASRRealtimeError,
AuthenticationError,
DependencyError,
FishAudioError,
Expand All @@ -42,7 +43,19 @@
ValidationError,
WebSocketError,
)
from .types import FlushEvent, ReferenceAudio, TextEvent, TTSConfig
from .resources.asr_realtime import ASRRealtimeStream, AsyncASRRealtimeStream
from .types import (
ASRContext,
ASRContextItem,
ASRFinalizeEvent,
ASRRealtimeConfig,
ASRResults,
ASRTurnDetection,
FlushEvent,
ReferenceAudio,
TextEvent,
TTSConfig,
)
from .utils import play, save, stream

# Main exports
Expand All @@ -57,15 +70,25 @@
# Audio streams
"AudioStream",
"AsyncAudioStream",
# Realtime speech-to-text sessions
"ASRRealtimeStream",
"AsyncASRRealtimeStream",
# Configuration
"ASRContext",
"ASRRealtimeConfig",
"ASRResults",
"ASRTurnDetection",
"TTSConfig",
"WebSocketOptions",
# Types
"ASRContextItem",
"ASRFinalizeEvent",
"FlushEvent",
"ReferenceAudio",
"TextEvent",
# Exceptions
"APIError",
"ASRRealtimeError",
"AuthenticationError",
"DependencyError",
"FishAudioError",
Expand Down
86 changes: 75 additions & 11 deletions src/fishaudio/core/_ws_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,49 @@

import contextlib
import logging
import queue
import socket
import threading
import time
from typing import Any

import wsproto.events

logger = logging.getLogger(__name__)

# How long a close frame may take to be written before the socket is shut down
# without it.
_CLOSE_FRAME_SECONDS = 0.5


def _send_close_frame(ws: Any) -> None:
with contextlib.suppress(Exception):
ws.send(wsproto.events.CloseConnection(1000))


def _socket(ws: Any) -> Any:
stream = getattr(ws, "stream", None)
if stream is None:
response = getattr(ws, "response", None)
stream = response.extensions.get("network_stream") if response else None
return stream.get_extra_info("socket") if stream is not None else None


def interrupt_writes(ws: Any) -> None:
"""Make a socket write that is blocked in another thread fail now.

A write blocks for as long as the peer does not read, and httpx-ws holds its
write lock meanwhile, so nothing else can be sent either, not even the close
frame. Shutting the socket down is the only way to end that from outside.
"""
try:
sock = _socket(ws)
if sock is not None:
with contextlib.suppress(OSError):
sock.shutdown(socket.SHUT_RDWR)
except Exception:
logger.debug("interrupt_writes failed", exc_info=True)


def drain_reader(ws: Any) -> None:
"""Send the close frame, shut the socket down, and wait for httpx-ws's reader
Expand All @@ -32,7 +68,8 @@ def drain_reader(ws: Any) -> None:
reader with ``EBADF`` on ``close()``, so it is unaffected.

The fix is to end the in-flight read *before* the fd is freed: send the close
frame (so the server still sees a clean 1000 close rather than 1006), then
frame (so the server still sees a clean 1000 close rather than 1006; a peer
that has stopped reading does not get one, see below), then
``shutdown(SHUT_RDWR)`` the socket, which wakes the blocked reader with EOF, and
join the reader thread. The later ``close()`` sees ``LOCAL_CLOSING`` and skips
sending a second frame.
Expand All @@ -43,24 +80,51 @@ def drain_reader(ws: Any) -> None:
read can still race. That can only be fixed inside httpx-ws's ``close()``.
"""
try:
stream = getattr(ws, "stream", None)
if stream is None:
response = getattr(ws, "response", None)
stream = response.extensions.get("network_stream") if response else None
sock = stream.get_extra_info("socket") if stream is not None else None
sock = _socket(ws)

# Moves the wsproto state to LOCAL_CLOSING; later close() calls skip the frame.
with contextlib.suppress(Exception):
ws.send(wsproto.events.CloseConnection(1000))
# The frame is a socket write, and httpx-ws writes without a timeout: it
# does not finish while the peer is not reading and the send buffer is
# full. So it is sent from a helper thread and given a deadline. The
# shutdown below makes a write that is still blocked fail.
closer = threading.Thread(
target=_send_close_frame,
args=(ws,),
name="fishaudio-ws-close-frame",
daemon=True,
)
closer.start()
closer.join(timeout=_CLOSE_FRAME_SECONDS)

if sock is not None:
with contextlib.suppress(OSError):
sock.shutdown(socket.SHUT_RDWR)
closer.join(timeout=_CLOSE_FRAME_SECONDS)

events = getattr(ws, "_events", None)

def discard_unread_events() -> None:
if isinstance(events, queue.Queue):
with contextlib.suppress(queue.Empty):
while True:
events.get_nowait()

thread = getattr(ws, "_background_receive_task", None)
if thread is not None:
# 5 s is the worst case only when the reader is stuck; httpx-ws's own
# untimed join in __exit__ would hang afterwards anyway.
thread.join(timeout=5)
# The reader can also be blocked putting an event into httpx-ws's
# bounded queue (the consumer stopped reading). Nothing will read
# those events any more, so discard them until the thread exits;
# httpx-ws's own untimed join in __exit__ would hang otherwise.
deadline = time.monotonic() + 5
thread.join(timeout=0.02)
while thread.is_alive() is True and time.monotonic() < deadline:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
discard_unread_events()
thread.join(timeout=0.02)

# The keepalive thread writes to the same queue: after a ping timeout it
# closes the transport and puts an error. With the queue still full and
# the reader gone it would block there, and httpx-ws joins it without a
# timeout too. Make room once more now that the reader adds nothing.
discard_unread_events()
except Exception:
logger.debug("drain_reader failed; falling back to plain close", exc_info=True)
37 changes: 24 additions & 13 deletions src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@
from .request_options import RequestOptions


def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError:
"""Build the exception that matches an HTTP error status."""
if status == 401:
return AuthenticationError(status, message, body)
if status == 403:
return PermissionError(status, message, body)
if status == 404:
return NotFoundError(status, message, body)
if status == 429:
return RateLimitError(status, message, body)
if status >= 500:
return ServerError(status, message, body)
return APIError(status, message, body)


def _raise_for_status(response: httpx.Response) -> None:
"""Raise appropriate exception based on status code."""
status = response.status_code
Expand All @@ -30,18 +45,7 @@ def _raise_for_status(response: httpx.Response) -> None:
except JSONDecodeError:
message = response.text or httpx.codes.get_reason_phrase(status)

# Raise specific exception based on status code
if status == 401:
raise AuthenticationError(status, message, response.text)
if status == 403:
raise PermissionError(status, message, response.text)
if status == 404:
raise NotFoundError(status, message, response.text)
if status == 429:
raise RateLimitError(status, message, response.text)
if status >= 500:
raise ServerError(status, message, response.text)
raise APIError(status, message, response.text)
raise _api_error(status, message, response.text)


class BaseClientWrapper:
Expand Down Expand Up @@ -80,7 +84,14 @@ def _prepare_request_kwargs(
headers = self.get_headers()
if request_options and request_options.additional_headers:
headers.update(request_options.additional_headers)
kwargs["headers"] = {**headers, **kwargs.get("headers", {})}
# Headers set by the calling method win, whatever the case of the name:
# {"Model": ...} from request options must not travel next to {"model": ...}.
explicit = kwargs.get("headers", {})
explicit_names = {name.lower() for name in explicit}
kwargs["headers"] = {
**{k: v for k, v in headers.items() if k.lower() not in explicit_names},
**explicit,
}

# Apply timeout override if provided
if request_options and request_options.timeout is not None:
Expand Down
40 changes: 40 additions & 0 deletions src/fishaudio/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,46 @@ class WebSocketError(FishAudioError):
pass


class ASRRealtimeError(WebSocketError):
"""Raised when a realtime speech-to-text session ends with an error.

Attributes:
message: A short English description, for humans
error_type: Machine-readable error type from the server's error event
(e.g., "invalid_config", "idle_timeout"). None if the connection closed
without one
code: HTTP-style status from the server's error event. None if not sent
request_id: Identifier of the request; quote it when reporting a problem
close_code: WebSocket close code (e.g., 4400, 4408, 1012). None if the error
was raised before the connection closed
"""

def __init__(
self,
message: str,
*,
error_type: Optional[str] = None,
code: Optional[int] = None,
request_id: Optional[str] = None,
close_code: Optional[int] = None,
):
self.message = message
self.error_type = error_type
self.code = code
self.request_id = request_id
self.close_code = close_code
details = [
f"close code {close_code}" if close_code is not None else None,
f"request {request_id}" if request_id else None,
]
suffix = ", ".join(d for d in details if d)
super().__init__(
(f"{error_type}: " if error_type else "")
+ message
+ (f" ({suffix})" if suffix else "")
)


class ValidationError(FishAudioError):
"""Raised when request validation fails."""

Expand Down
Loading
Loading