From fe4ab386a9d6ff0e4bb68d80420997cb85a0b2e9 Mon Sep 17 00:00:00 2001 From: fishaudio-bot <242899544+fishaudio-bot@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:39:06 +0000 Subject: [PATCH] chore: update Python SDK API reference Auto-generated from fishaudio/fish-audio-python@6a604bd799a0e0eb3b87537f7e19a8d90766fb4c --- api-reference/sdk/python/client.mdx | 2 - api-reference/sdk/python/core.mdx | 194 +++-- api-reference/sdk/python/exceptions.mdx | 21 + api-reference/sdk/python/overview.mdx | 142 ++-- api-reference/sdk/python/resources.mdx | 957 ++++++++++++++++++------ api-reference/sdk/python/types.mdx | 604 +++++++++++++-- api-reference/sdk/python/utils.mdx | 2 - 7 files changed, 1552 insertions(+), 370 deletions(-) diff --git a/api-reference/sdk/python/client.mdx b/api-reference/sdk/python/client.mdx index ea7ac07a..1819c9c7 100644 --- a/api-reference/sdk/python/client.mdx +++ b/api-reference/sdk/python/client.mdx @@ -4,8 +4,6 @@ Main Fish Audio client classes. -Install the Python SDK first: `pip install fish-audio-sdk`. - ## FishAudio Objects diff --git a/api-reference/sdk/python/core.mdx b/api-reference/sdk/python/core.mdx index d44a7aee..30c24f24 100644 --- a/api-reference/sdk/python/core.mdx +++ b/api-reference/sdk/python/core.mdx @@ -1,11 +1,63 @@ + + +# fishaudio.core.websocket\_options + +WebSocket-level options for WebSocket connections. + + + +## WebSocketOptions Objects + +```python +class WebSocketOptions() +``` + +Options for configuring WebSocket connections. + +These options are passed directly to httpx_ws's connect_ws/aconnect_ws functions. +For complete documentation, see https://frankie567.github.io/httpx-ws/reference/httpx_ws/ + +**Attributes**: + +- `keepalive_ping_timeout_seconds` - Maximum delay the client will wait for an answer + to its Ping event. If the delay is exceeded, WebSocketNetworkError will be + raised and the connection closed. Default: 20 seconds. +- `keepalive_ping_interval_seconds` - Interval at which the client will automatically + send a Ping event to keep the connection alive. Set to None to disable this + mechanism. Default: 20 seconds. +- `max_message_size_bytes` - Message size in bytes to receive from the server. +- `Default` - 65536 bytes (64 KiB). +- `queue_size` - Size of the queue where received messages will be held until they + are consumed. If the queue is full, the client will stop receiving messages + from the server until the queue has room available. Default: 512. + + +**Notes**: + + Parameter descriptions adapted from httpx_ws documentation. + + + +#### to\_httpx\_ws\_kwargs + +```python +def to_httpx_ws_kwargs() -> dict[str, Any] +``` + +Convert to kwargs dict for httpx_ws aconnect_ws/connect_ws. + + + +# fishaudio.core.omit + +OMIT sentinel for distinguishing None from not-provided parameters. + # fishaudio.core.client\_wrapper HTTP client wrapper for managing requests and authentication. -Install the Python SDK first: `pip install fish-audio-sdk`. - ## BaseClientWrapper Objects @@ -46,6 +98,7 @@ def request(method: str, path: str, *, request_options: Optional[RequestOptions] = None, + stream: bool = False, **kwargs: Any) -> httpx.Response ``` @@ -56,6 +109,9 @@ Make an HTTP request with error handling. - `method` - HTTP method (GET, POST, etc.) - `path` - API endpoint path - `request_options` - Optional request-level overrides +- `stream` - If True, return as soon as the response headers arrive and + leave the body unread. The caller must consume it with + `iter_bytes()` and then call `close()` on the response. - `**kwargs` - Additional arguments to pass to httpx.request @@ -108,6 +164,7 @@ async def request(method: str, path: str, *, request_options: Optional[RequestOptions] = None, + stream: bool = False, **kwargs: Any) -> httpx.Response ``` @@ -118,6 +175,9 @@ Make an async HTTP request with error handling. - `method` - HTTP method (GET, POST, etc.) - `path` - API endpoint path - `request_options` - Optional request-level overrides +- `stream` - If True, return as soon as the response headers arrive and + leave the body unread. The caller must consume it with + `aiter_bytes()` and then call `aclose()` on the response. - `**kwargs` - Additional arguments to pass to httpx.request @@ -216,6 +276,13 @@ This class wraps an iterator of audio bytes and provides a convenient # Or stream chunks manually for chunk in client.tts.stream(text="Hello!"): process_chunk(chunk) + + # Use a with-block (or call close()) if you may stop early, + # so the HTTP connection is released right away + with client.tts.stream(text="Hello!") as stream: + for chunk in stream: + if done(chunk): + break ``` @@ -223,7 +290,9 @@ This class wraps an iterator of audio bytes and provides a convenient #### \_\_init\_\_ ```python -def __init__(iterator: Iterator[bytes]) +def __init__(iterator: Iterator[bytes], + *, + on_close: Optional[Callable[[], None]] = None) ``` Initialize the audio iterator wrapper. @@ -231,6 +300,8 @@ Initialize the audio iterator wrapper. **Arguments**: - `iterator` - The underlying iterator of audio bytes +- `on_close` - Called by close() to release the underlying resource, + for example the open HTTP response @@ -242,6 +313,18 @@ def __iter__() -> Iterator[bytes] Allow direct iteration over audio chunks. + + +#### close + +```python +def close() -> None +``` + +Stop the stream and release the underlying connection. + +Safe to call more than once, and before iteration has started. + #### collect @@ -295,6 +378,13 @@ This class wraps an async iterator of audio bytes and provides a convenient # Or stream chunks manually async for chunk in await client.tts.stream(text="Hello!"): await process_chunk(chunk) + + # Use async with (or await aclose()) if you may stop early, + # so the HTTP connection is released right away + async with await client.tts.stream(text="Hello!") as stream: + async for chunk in stream: + if done(chunk): + break ``` @@ -302,7 +392,9 @@ This class wraps an async iterator of audio bytes and provides a convenient #### \_\_init\_\_ ```python -def __init__(async_iterator: AsyncIterator[bytes]) +def __init__(async_iterator: AsyncIterator[bytes], + *, + on_close: Optional[Callable[[], Awaitable[None]]] = None) ``` Initialize the async audio iterator wrapper. @@ -310,6 +402,8 @@ Initialize the async audio iterator wrapper. **Arguments**: - `async_iterator` - The underlying async iterator of audio bytes +- `on_close` - Awaited by aclose() to release the underlying resource, + for example the open HTTP response @@ -321,6 +415,18 @@ def __aiter__() -> AsyncIterator[bytes] Allow direct async iteration over audio chunks. + + +#### aclose + +```python +async def aclose() -> None +``` + +Stop the stream and release the underlying connection. + +Safe to call more than once, and before iteration has started. + #### collect @@ -348,57 +454,61 @@ After calling this method, the iterator cannot be used again. f.write(audio) ``` - + -# fishaudio.core.websocket\_options +# fishaudio.core.\_ws\_utils -WebSocket-level options for WebSocket connections. +Internal helpers for synchronous httpx-ws sessions. - + -## WebSocketOptions Objects +#### interrupt\_writes ```python -class WebSocketOptions() +def interrupt_writes(ws: Any) -> None ``` -Options for configuring WebSocket connections. +Make a socket write that is blocked in another thread fail now. -These options are passed directly to httpx_ws's connect_ws/aconnect_ws functions. -For complete documentation, see https://frankie567.github.io/httpx-ws/reference/httpx_ws/ +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. -**Attributes**: + -- `keepalive_ping_timeout_seconds` - Maximum delay the client will wait for an answer - to its Ping event. If the delay is exceeded, WebSocketNetworkError will be - raised and the connection closed. Default: 20 seconds. -- `keepalive_ping_interval_seconds` - Interval at which the client will automatically - send a Ping event to keep the connection alive. Set to None to disable this - mechanism. Default: 20 seconds. -- `max_message_size_bytes` - Message size in bytes to receive from the server. -- `Default` - 65536 bytes (64 KiB). -- `queue_size` - Size of the queue where received messages will be held until they - are consumed. If the queue is full, the client will stop receiving messages - from the server until the queue has room available. Default: 512. - - -**Notes**: - - Parameter descriptions adapted from httpx_ws documentation. - - - -#### to\_httpx\_ws\_kwargs +#### drain\_reader ```python -def to_httpx_ws_kwargs() -> dict[str, Any] +def drain_reader(ws: Any) -> None ``` -Convert to kwargs dict for httpx_ws aconnect_ws/connect_ws. - - - -# fishaudio.core.omit - -OMIT sentinel for distinguishing None from not-provided parameters. +Send the close frame, shut the socket down, and wait for httpx-ws's reader +thread to exit before the session's own ``close()`` frees the fd. + +Why this is needed (Linux only in practice): + +httpx-ws's sync ``WebSocketSession`` reads on a background thread and closes the +socket from the calling thread. A read that has *not started yet* is harmless: +CPython's ``SSLSocket._real_close`` sets ``_sslobj = None`` before closing the +fd, so a later read falls through to ``socket.recv`` on fd ``-1`` and fails with +``EBADF``. The problem is the read that is *already in flight*. On Linux, +``close()`` does not interrupt a thread blocked in ``recv()``. OpenSSL (with +read_ahead off) fetches a TLS record header and body with separate ``read(fd)`` +calls on the fd number cached in its BIO, so when the server's close-frame reply +arrives the second ``read()`` can land on a brand-new connection that has since +reused the same fd number, and that new session fails with +``[SSL: WRONG_VERSION_NUMBER]`` or a similar TLS error. macOS wakes the blocked +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; 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. + +Residual risk: if httpx-ws has already closed the socket on one of its own error +paths (keepalive ping timeout, or a sender ``WriteError`` triggering ``close()``), +the fd is already freed, ``shutdown()`` fails with ``EBADF``, and the in-flight +read can still race. That can only be fixed inside httpx-ws's ``close()``. diff --git a/api-reference/sdk/python/exceptions.mdx b/api-reference/sdk/python/exceptions.mdx index 1110a1bc..dbbd5df0 100644 --- a/api-reference/sdk/python/exceptions.mdx +++ b/api-reference/sdk/python/exceptions.mdx @@ -84,6 +84,27 @@ class WebSocketError(FishAudioError) Raised when WebSocket connection or streaming fails. + + +## ASRRealtimeError Objects + +```python +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 + ## ValidationError Objects diff --git a/api-reference/sdk/python/overview.mdx b/api-reference/sdk/python/overview.mdx index 2be95a17..9098cc40 100644 --- a/api-reference/sdk/python/overview.mdx +++ b/api-reference/sdk/python/overview.mdx @@ -4,7 +4,10 @@ description: "Fish Audio Python SDK for text-to-speech and voice cloning" icon: "python" --- -![python.png](https://raw.githubusercontent.com/fishaudio/fish-audio-python/refs/heads/main/.github/assets/python.png) + + + Fish Audio Python SDK + # Fish Audio Python SDK @@ -39,7 +42,7 @@ pip install fish-audio-sdk[utils] ## Authentication -Get your API key from [Get Started](https://fish.audio/app/developers/get-started/?utm_source=docs&utm_medium=python-sdk&utm_content=get-api-key): +Get your API key from [fish.audio/app/api-keys](https://fish.audio/app/api-keys/?utm_source=github&utm_medium=sdk-readme&utm_content=python): ```bash export FISH_API_KEY=your_api_key_here @@ -55,8 +58,6 @@ client = FishAudio(api_key="your_api_key") ## Quick Start -Most examples on this page pass `model="s2.1-pro-free"`, the free model, so they work before you add API credit. Without `model=`, the SDK uses a paid model. - **Synchronous:** ```python @@ -66,7 +67,7 @@ from fishaudio.utils import play, save client = FishAudio() # Generate audio -audio = client.tts.convert(text="Hello, world!", model="s2.1-pro-free") +audio = client.tts.convert(text="Hello, world!") # Play or save play(audio) @@ -82,7 +83,7 @@ from fishaudio.utils import play, save async def main(): client = AsyncFishAudio() - audio = await client.tts.convert(text="Hello, world!", model="s2.1-pro-free") + audio = await client.tts.convert(text="Hello, world!") play(audio) save(audio, "output.mp3") @@ -93,14 +94,35 @@ asyncio.run(main()) ### Text-to-Speech +**Selecting a model:** + +```python +# Recommended for production +production_audio = client.tts.convert( + text="Production speech", + model="s2.1-pro", +) + +# Free to use, including on a new account with no API credit +free_audio = client.tts.convert( + text="Free speech", + model="s2.1-pro-free", +) + +# Drama 3: our most expressive model (uses API credit) +drama_audio = client.tts.convert( + text="Expressive speech", + model="drama-3", +) +``` + **With custom voice:** ```python # Use a specific voice by ID audio = client.tts.convert( text="Custom voice", - reference_id="9a9cf47702da476aa4629e2506d4a857", - model="s2.1-pro-free", + reference_id="802e3bc2b27e49c2995d23ef70e6ac89" ) ``` @@ -109,8 +131,7 @@ audio = client.tts.convert( ```python audio = client.tts.convert( text="Speaking faster!", - speed=1.5, # 1.5x speed - model="s2.1-pro-free", + speed=1.5 # 1.5x speed ) ``` @@ -127,47 +148,70 @@ config = TTSConfig( ) # Reuse across generations -audio1 = client.tts.convert(text="First message", config=config, model="s2.1-pro-free") -audio2 = client.tts.convert(text="Second message", config=config, model="s2.1-pro-free") +audio1 = client.tts.convert(text="First message", config=config) +audio2 = client.tts.convert(text="Second message", config=config) ``` **Chunk-by-chunk processing:** ```python # Stream and process chunks as they arrive -for chunk in client.tts.stream(text="Long content...", model="s2.1-pro-free"): +for chunk in client.tts.stream(text="Long content..."): send_to_websocket(chunk) # Or collect all chunks -audio = client.tts.stream(text="Hello!", model="s2.1-pro-free").collect() +audio = client.tts.stream(text="Hello!").collect() ``` -[Learn more](https://docs.fish.audio/features/text-to-speech) +[Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/text-to-speech) ### Speech-to-Text ```python -from fishaudio.core import RequestOptions - -# Transcribe audio with transcribe-1-pro (recommended). -# Without the model header, the request runs on transcribe-1. -with open("audio.wav", "rb") as f: - result = client.asr.transcribe( - audio=f.read(), - language="en", - request_options=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(), model="transcribe-1-pro") +# On transcribe-1-pro, text keeps <|speaker:N|> markers; speaker_turns has clean text per speaker. print(result.text) -# Access timestamped segments +# Word-level timestamps for segment in result.segments: print(f"[{segment.start:.2f}s - {segment.end:.2f}s] {segment.text}") + +# Speaker turns (transcribe-1-pro, returned with timestamps) +for turn in result.speaker_turns or []: + print(f"[{turn.start:.2f}s - {turn.end:.2f}s] {turn.speaker}: {turn.text}") + +# Language of the transcript, when the API returns it +print(result.language_code) # e.g. "en" ``` -[Learn more](https://docs.fish.audio/features/speech-to-text) +[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 @@ -181,33 +225,23 @@ def text_chunks(): yield "this is " yield "streaming!" -audio_stream = client.tts.stream_websocket(text_chunks(), latency="balanced", model="s2.1-pro-free") +audio_stream = client.tts.stream_websocket(text_chunks(), latency="balanced") play(audio_stream) ``` **Asynchronous:** ```python -import asyncio -from fishaudio import AsyncFishAudio - async def text_chunks(): yield "Hello, " yield "this is " yield "streaming!" -async def main(): - async with AsyncFishAudio() as client: - # stream_websocket is an async generator: iterate it, don't await the call - audio_stream = client.tts.stream_websocket(text_chunks(), latency="balanced", model="s2.1-pro-free") - with open("out.mp3", "wb") as f: - async for chunk in audio_stream: - f.write(chunk) - -asyncio.run(main()) +audio_stream = await client.tts.stream_websocket(text_chunks(), latency="balanced") +play(audio_stream) ``` -[Learn more](https://docs.fish.audio/features/realtime-streaming) +[Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/websocket) ### Voice Cloning @@ -223,8 +257,7 @@ with open("reference.wav", "rb") as f: references=[ReferenceAudio( audio=f.read(), text="Text spoken in reference" - )], - model="s2.1-pro-free", + )] ) ``` @@ -246,14 +279,14 @@ audio = client.tts.convert( ) ``` -[Learn more](https://docs.fish.audio/features/voice-cloning) +[Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/voice-cloning) ## Resource Clients | 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()` | @@ -263,23 +296,20 @@ audio = client.tts.convert( from fishaudio.exceptions import ( AuthenticationError, RateLimitError, - NotFoundError, - APIError, - FishAudioError, + ValidationError, + FishAudioError ) try: - audio = client.tts.convert(text="Hello!", model="s2.1-pro-free") + audio = client.tts.convert(text="Hello!") except AuthenticationError: print("Invalid API key") except RateLimitError: print("Rate limit exceeded") -except NotFoundError: - print("Voice model not found") -except APIError as e: - print(f"API error {e.status}: {e.message}") # any other HTTP error, including 422 validation +except ValidationError as e: + print(f"Invalid request: {e}") except FishAudioError as e: - print(f"SDK error: {e}") + print(f"API error: {e}") ``` ## Resources diff --git a/api-reference/sdk/python/resources.mdx b/api-reference/sdk/python/resources.mdx index c616f007..a9f6d2e4 100644 --- a/api-reference/sdk/python/resources.mdx +++ b/api-reference/sdk/python/resources.mdx @@ -4,8 +4,6 @@ Voice management namespace client. -Install the Python SDK first: `pip install fish-audio-sdk`. - ## VoicesClient Objects @@ -314,164 +312,6 @@ async def delete(voice_id: str, Delete a voice (async). See sync version for details. - - -# fishaudio.resources.account - -Account namespace client for billing and credits. - - - -## AccountClient Objects - -```python -class AccountClient() -``` - -Synchronous account operations. - - - -#### get\_credits - -```python -def get_credits(*, - check_free_credit: Optional[bool] = OMIT, - request_options: Optional[RequestOptions] = None) -> Credits -``` - -Get API credit balance. - -**Arguments**: - -- `check_free_credit` - Whether to check free credit availability -- `request_options` - Request-level overrides - - -**Returns**: - - Credits information - - -**Example**: - - ```python - client = FishAudio(api_key="...") - credits = client.account.get_credits() - print(f"Available credits: {float(credits.credit)}") - - # Check free credit availability - credits = client.account.get_credits(check_free_credit=True) - if credits.has_free_credit: - print("Free credits available!") - ``` - - - -#### get\_package - -```python -def get_package(*, - request_options: Optional[RequestOptions] = None) -> Package -``` - -Get package information. - -**Arguments**: - -- `request_options` - Request-level overrides - - -**Returns**: - - Package information - - -**Example**: - - ```python - client = FishAudio(api_key="...") - package = client.account.get_package() - print(f"Balance: {package.balance}/{package.total}") - ``` - - - -## AsyncAccountClient Objects - -```python -class AsyncAccountClient() -``` - -Asynchronous account operations. - - - -#### get\_credits - -```python -async def get_credits( - *, - check_free_credit: Optional[bool] = OMIT, - request_options: Optional[RequestOptions] = None) -> Credits -``` - -Get API credit balance (async). - -**Arguments**: - -- `check_free_credit` - Whether to check free credit availability -- `request_options` - Request-level overrides - - -**Returns**: - - Credits information - - -**Example**: - - ```python - client = AsyncFishAudio(api_key="...") - credits = await client.account.get_credits() - print(f"Available credits: {float(credits.credit)}") - - # Check free credit availability - credits = await client.account.get_credits(check_free_credit=True) - if credits.has_free_credit: - print("Free credits available!") - ``` - - - -#### get\_package - -```python -async def get_package(*, - request_options: Optional[RequestOptions] = None - ) -> Package -``` - -Get package information (async). - -**Arguments**: - -- `request_options` - Request-level overrides - - -**Returns**: - - Package information - - -**Example**: - - ```python - client = AsyncFishAudio(api_key="...") - package = await client.account.get_package() - print(f"Balance: {package.balance}/{package.total}") - ``` - # fishaudio.resources.tts @@ -501,7 +341,7 @@ def stream(*, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, config: TTSConfig = TTSConfig(), - model: Model = "s2-pro", + model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None) -> AudioStream ``` @@ -553,7 +393,7 @@ def convert(*, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, config: TTSConfig = TTSConfig(), - model: Model = "s2-pro", + model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None) -> bytes ``` @@ -612,7 +452,7 @@ def stream_websocket( latency: Optional[LatencyMode] = None, speed: Optional[float] = None, config: TTSConfig = TTSConfig(), - model: Model = "s2-pro", + model: Union[Model, str] = "s2.1-pro", max_workers: int = 10, ws_options: Optional[WebSocketOptions] = None) -> Iterator[bytes] ``` @@ -726,7 +566,7 @@ async def stream( latency: Optional[LatencyMode] = None, speed: Optional[float] = None, config: TTSConfig = TTSConfig(), - model: Model = "s2-pro", + model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None) -> AsyncAudioStream ``` @@ -779,7 +619,7 @@ async def convert(*, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, config: TTSConfig = TTSConfig(), - model: Model = "s2-pro", + model: Union[Model, str] = "s2.1-pro", request_options: Optional[RequestOptions] = None) -> bytes ``` @@ -838,7 +678,7 @@ async def stream_websocket(text_stream: AsyncIterable[Union[str, TextEvent, latency: Optional[LatencyMode] = None, speed: Optional[float] = None, config: TTSConfig = TTSConfig(), - model: Model = "s2-pro", + model: Union[Model, str] = "s2.1-pro", ws_options: Optional[WebSocketOptions] = None) ``` @@ -986,113 +826,782 @@ Unknown events are ignored and iteration continues. - `WebSocketError` - On disconnect or error finish event - + -# fishaudio.resources.asr +# fishaudio.resources.account -ASR (Automatic Speech Recognition) namespace client. +Account namespace client for billing and credits. - + -## ASRClient Objects +## AccountClient Objects ```python -class ASRClient() +class AccountClient() ``` -Synchronous ASR operations. +Synchronous account operations. - + -#### transcribe +#### get\_credits ```python -def transcribe( - *, - audio: bytes, - language: Optional[str] = OMIT, - include_timestamps: bool = True, - request_options: Optional[RequestOptions] = None) -> ASRResponse +def get_credits(*, + check_free_credit: Optional[bool] = OMIT, + request_options: Optional[RequestOptions] = None) -> Credits ``` -Transcribe audio to text. +Get API credit balance. **Arguments**: -- `audio` - Audio file bytes -- `language` - Language code (e.g., "en", "zh"). Auto-detected if not provided. -- `include_timestamps` - Whether to include timestamp information for segments +- `check_free_credit` - Whether to check free credit availability - `request_options` - Request-level overrides **Returns**: - ASRResponse with transcription text, duration, and segments + Credits information **Example**: ```python client = FishAudio(api_key="...") + credits = client.account.get_credits() + print(f"Available credits: {float(credits.credit)}") - with open("audio.mp3", "rb") as f: - audio_bytes = f.read() - - result = client.asr.transcribe(audio=audio_bytes, language="en") - print(result.text) - for segment in result.segments: - print(f"{segment.start}-{segment.end}: {segment.text}") + # Check free credit availability + credits = client.account.get_credits(check_free_credit=True) + if credits.has_free_credit: + print("Free credits available!") ``` - - -## AsyncASRClient Objects - -```python -class AsyncASRClient() -``` - -Asynchronous ASR operations. - - + -#### transcribe +#### get\_package ```python -async def transcribe( - *, - audio: bytes, - language: Optional[str] = OMIT, - include_timestamps: bool = True, - request_options: Optional[RequestOptions] = None) -> ASRResponse +def get_package(*, + request_options: Optional[RequestOptions] = None) -> Package ``` -Transcribe audio to text (async). +Get package information. **Arguments**: -- `audio` - Audio file bytes -- `language` - Language code (e.g., "en", "zh"). Auto-detected if not provided. -- `include_timestamps` - Whether to include timestamp information for segments - `request_options` - Request-level overrides **Returns**: - ASRResponse with transcription text, duration, and segments + Package information **Example**: ```python - client = AsyncFishAudio(api_key="...") + client = FishAudio(api_key="...") + package = client.account.get_package() + print(f"Balance: {package.balance}/{package.total}") + ``` - async with aiofiles.open("audio.mp3", "rb") as f: - audio_bytes = await f.read() + - result = await client.asr.transcribe(audio=audio_bytes, language="en") - print(result.text) - for segment in result.segments: - print(f"{segment.start}-{segment.end}: {segment.text}") - ``` +## AsyncAccountClient Objects + +```python +class AsyncAccountClient() +``` + +Asynchronous account operations. + + + +#### get\_credits + +```python +async def get_credits( + *, + check_free_credit: Optional[bool] = OMIT, + request_options: Optional[RequestOptions] = None) -> Credits +``` + +Get API credit balance (async). + +**Arguments**: + +- `check_free_credit` - Whether to check free credit availability +- `request_options` - Request-level overrides + + +**Returns**: + + Credits information + + +**Example**: + + ```python + client = AsyncFishAudio(api_key="...") + credits = await client.account.get_credits() + print(f"Available credits: {float(credits.credit)}") + + # Check free credit availability + credits = await client.account.get_credits(check_free_credit=True) + if credits.has_free_credit: + print("Free credits available!") + ``` + + + +#### get\_package + +```python +async def get_package(*, + request_options: Optional[RequestOptions] = None + ) -> Package +``` + +Get package information (async). + +**Arguments**: + +- `request_options` - Request-level overrides + + +**Returns**: + + Package information + + +**Example**: + + ```python + client = AsyncFishAudio(api_key="...") + package = await client.account.get_package() + print(f"Balance: {package.balance}/{package.total}") + ``` + + + +# fishaudio.resources.asr + +ASR (Automatic Speech Recognition) namespace client. + + + +## ASRClient Objects + +```python +class ASRClient() +``` + +Synchronous ASR operations. + + + +#### transcribe + +```python +def transcribe( + *, + audio: bytes, + language: Optional[str] = OMIT, + include_timestamps: bool = True, + model: Optional[str] = None, + request_options: Optional[RequestOptions] = None) -> ASRResponse +``` + +Transcribe audio to text. + +**Arguments**: + +- `audio` - Audio file bytes +- `language` - Language code (e.g., "en", "zh"). Auto-detected if not provided. +- `include_timestamps` - Whether to include timestamp information for segments + (and speaker turns, on models that return them) +- `model` - ASR model, e.g. "transcribe-1-pro" (recommended). Sent as the + ``model`` header and takes precedence over one in request_options. + If not provided and request_options sets no ``model`` header, the + request runs on the API's default model, transcribe-1 +- `request_options` - Request-level overrides + + +**Returns**: + + ASRResponse with transcription text, duration (in seconds), and segments, + plus language, request ID and speaker turns when the API returns them + + +**Example**: + + ```python + client = FishAudio(api_key="...") + + with open("audio.mp3", "rb") as f: + audio_bytes = f.read() + + result = client.asr.transcribe( + audio=audio_bytes, model="transcribe-1-pro" + ) + print(result.text) + for segment in result.segments: + print(f"{segment.start}-{segment.end}: {segment.text}") + ``` + + + +#### stream\_websocket + +```python +def stream_websocket( + audio_stream: Iterable[Union[bytes, ASRRealtimeControl]], + *, + sample_rate: Optional[ASRSampleRate] = None, + turn_detection: Optional[TurnDetectionMode] = None, + eager: Optional[bool] = None, + drafts: Optional[bool] = None, + diarize: Optional[bool] = None, + terms: Optional[list[str]] = None, + config: ASRRealtimeConfig = ASRRealtimeConfig(), + model: str = "transcribe-stream-1", + ws_options: Optional[WebSocketOptions] = None) -> ASRRealtimeStream +``` + +Stream audio and receive transcripts in real-time via WebSocket. + +Audio is divided into turns. Each turn ends with one committed event that +holds its final transcript; with drafts=True you also get live draft events +while the turn is open. The session ends with a session_done event once +audio_stream is exhausted. + +By default the transcript text starts with a speaker tag, e.g. +``<|speaker:0|> Hello.``, and can contain sound tags such as ``[laughter]``. +Pass diarize=False for text without speaker tags; sound tags are turned off +with config=ASRRealtimeConfig(results=ASRResults(tag_audio_events=False)). + +**Arguments**: + +- `audio_stream` - Iterator of raw audio chunks: 16-bit little-endian mono PCM, + ideally 20-40 ms each, sent as you capture them. It can also yield + control messages (e.g. ASRFinalizeEvent()), which are sent at that + position in the audio +- `sample_rate` - Sample rate of the audio in Hz: 8000, 12000, 16000, 22050, + 24000, 32000, 44100 or 48000 (overrides config.sample_rate if provided) +- `turn_detection` - When a turn ends - "auto" (the server judges that the user + has finished), "vad" (after a fixed silence) or "manual" (when you send + finalize) (overrides config.turn_detection.mode if provided) +- `eager` - Send eager_end_of_turn events in auto mode + (overrides config.turn_detection.eager if provided) +- `drafts` - Send live draft events (overrides config.results.drafts if provided) +- `diarize` - Speaker tags such as ``<|speaker:0|>`` in the transcript text. The + server adds them by default; pass False for plain text + (overrides config.results.diarize if provided) +- `terms` - Names, products and jargon to recognize + (overrides config.context.terms if provided) +- `config` - Session configuration (audio, turn detection, results, context) +- `model` - Realtime speech-to-text model +- `ws_options` - WebSocket connection options for configuring timeouts, message size limits, etc. + See WebSocketOptions class for available parameters. + + +**Returns**: + +- `ASRRealtimeStream` - an iterator of typed events (check event.type), with + methods to send control messages during the session: finalize(), + agent_speaking(), add_context() and configure() + + +**Raises**: + +- `ASRRealtimeError` - If the server reports an error that ends the session, or + closes the connection abnormally (see error_type and close_code) +- `APIError` - If the connection is refused (e.g. AuthenticationError for 401) +- `WebSocketError` - If the connection is lost + + +**Example**: + + ```python + import wave + + from fishaudio import FishAudio + + client = FishAudio(api_key="...") + + def audio_chunks(): + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM + while chunk := wav.readframes(640): # 40 ms at 16 kHz + yield chunk + + # Final transcript of each turn (diarize=False: no <|speaker:0|> tags) + for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, diarize=False + ): + if event.type == "committed": + print(event.text) + + # Live captions: drafts while the turn is open, then the final text + for event in client.asr.stream_websocket(audio_chunks(), drafts=True): + if event.type == "draft": + print("...", event.text) + elif event.type == "committed": + print(event.text) + + # Voice agent: answer the user's turns, and tell the server while you speak + with client.asr.stream_websocket(audio_chunks(), eager=True) as stream: + for event in stream: + if event.type == "committed" and event.user_turn: + stream.agent_speaking(True) + ... # reply, then stream.agent_speaking(False) + ``` + + + +## AsyncASRClient Objects + +```python +class AsyncASRClient() +``` + +Asynchronous ASR operations. + + + +#### transcribe + +```python +async def transcribe( + *, + audio: bytes, + language: Optional[str] = OMIT, + include_timestamps: bool = True, + model: Optional[str] = None, + request_options: Optional[RequestOptions] = None) -> ASRResponse +``` + +Transcribe audio to text (async). + +**Arguments**: + +- `audio` - Audio file bytes +- `language` - Language code (e.g., "en", "zh"). Auto-detected if not provided. +- `include_timestamps` - Whether to include timestamp information for segments + (and speaker turns, on models that return them) +- `model` - ASR model, e.g. "transcribe-1-pro" (recommended). Sent as the + ``model`` header and takes precedence over one in request_options. + If not provided and request_options sets no ``model`` header, the + request runs on the API's default model, transcribe-1 +- `request_options` - Request-level overrides + + +**Returns**: + + ASRResponse with transcription text, duration (in seconds), and segments, + plus language, request ID and speaker turns when the API returns them + + +**Example**: + + ```python + client = AsyncFishAudio(api_key="...") + + async with aiofiles.open("audio.mp3", "rb") as f: + audio_bytes = await f.read() + + result = await client.asr.transcribe( + audio=audio_bytes, model="transcribe-1-pro" + ) + print(result.text) + for segment in result.segments: + print(f"{segment.start}-{segment.end}: {segment.text}") + ``` + + + +#### stream\_websocket + +```python +def stream_websocket( + audio_stream: AsyncIterable[Union[bytes, ASRRealtimeControl]], + *, + sample_rate: Optional[ASRSampleRate] = None, + turn_detection: Optional[TurnDetectionMode] = None, + eager: Optional[bool] = None, + drafts: Optional[bool] = None, + diarize: Optional[bool] = None, + terms: Optional[list[str]] = None, + config: ASRRealtimeConfig = ASRRealtimeConfig(), + model: str = "transcribe-stream-1", + ws_options: Optional[WebSocketOptions] = None +) -> AsyncASRRealtimeStream +``` + +Stream audio and receive transcripts in real-time via WebSocket (async). + +Audio is divided into turns. Each turn ends with one committed event that +holds its final transcript; with drafts=True you also get live draft events +while the turn is open. The session ends with a session_done event once +audio_stream is exhausted. + +By default the transcript text starts with a speaker tag, e.g. +``<|speaker:0|> Hello.``, and can contain sound tags such as ``[laughter]``. +Pass diarize=False for text without speaker tags; sound tags are turned off +with config=ASRRealtimeConfig(results=ASRResults(tag_audio_events=False)). + +**Arguments**: + +- `audio_stream` - Async iterator of raw audio chunks: 16-bit little-endian mono PCM, + ideally 20-40 ms each, sent as you capture them. It can also yield + control messages (e.g. ASRFinalizeEvent()), which are sent at that + position in the audio +- `sample_rate` - Sample rate of the audio in Hz: 8000, 12000, 16000, 22050, + 24000, 32000, 44100 or 48000 (overrides config.sample_rate if provided) +- `turn_detection` - When a turn ends - "auto" (the server judges that the user + has finished), "vad" (after a fixed silence) or "manual" (when you send + finalize) (overrides config.turn_detection.mode if provided) +- `eager` - Send eager_end_of_turn events in auto mode + (overrides config.turn_detection.eager if provided) +- `drafts` - Send live draft events (overrides config.results.drafts if provided) +- `diarize` - Speaker tags such as ``<|speaker:0|>`` in the transcript text. The + server adds them by default; pass False for plain text + (overrides config.results.diarize if provided) +- `terms` - Names, products and jargon to recognize + (overrides config.context.terms if provided) +- `config` - Session configuration (audio, turn detection, results, context) +- `model` - Realtime speech-to-text model +- `ws_options` - WebSocket connection options for configuring timeouts, message size limits, etc. + See WebSocketOptions class for available parameters. + + +**Returns**: + +- `AsyncASRRealtimeStream` - an async iterator of typed events (check event.type), with + methods to send control messages during the session: finalize(), + agent_speaking(), add_context() and configure() + + +**Raises**: + +- `ASRRealtimeError` - If the server reports an error that ends the session, or + closes the connection abnormally (see error_type and close_code) +- `APIError` - If the connection is refused (e.g. AuthenticationError for 401) +- `WebSocketError` - If the connection is lost + + +**Example**: + + ```python + import wave + + from fishaudio import AsyncFishAudio + + client = AsyncFishAudio(api_key="...") + + async def audio_chunks(): + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM + while chunk := wav.readframes(640): # 40 ms at 16 kHz + yield chunk + + # Final transcript of each turn (diarize=False: no <|speaker:0|> tags) + async for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, diarize=False + ): + if event.type == "committed": + print(event.text) + + # Live captions: drafts while the turn is open, then the final text + async for event in client.asr.stream_websocket(audio_chunks(), drafts=True): + if event.type == "draft": + print("...", event.text) + elif event.type == "committed": + print(event.text) + + # Voice agent: answer the user's turns, and tell the server while you speak + async with client.asr.stream_websocket(audio_chunks(), eager=True) as stream: + async for event in stream: + if event.type == "committed" and event.user_turn: + await stream.agent_speaking(True) + ... # reply, then await stream.agent_speaking(False) + ``` + + + +# fishaudio.resources.asr\_realtime + +Realtime speech-to-text sessions over WebSocket. + + + +#### encode\_config + +```python +def encode_config(config: ASRRealtimeConfig) -> bytes +``` + +Pack the ``config`` message that opens a session. + + + +#### encode\_message + +```python +def encode_message(item: Union[bytes, ASRRealtimeControl]) -> bytes +``` + +Pack an audio chunk or a control message for the wire. + + + +#### decode\_event + +```python +def decode_event(message: bytes) -> Optional[ASRRealtimeEvent] +``` + +Parse a server message. Returns None for message types this SDK does not know. + + + +## \_Link Objects + +```python +class _Link() +``` + +The open connection, shared by the audio sender thread and control methods. + + + +#### close + +```python +def close() -> None +``` + +End the link. Does not wait for a write that is blocked. + + + +## ASRRealtimeStream Objects + +```python +class ASRRealtimeStream() +``` + +A realtime speech-to-text session (sync). + +Iterate it for the server's events. The connection opens on the first +iteration and closes when the session ends, when an error is raised, or when +you leave the loop early. Use it as a context manager (or call ``close()``) +if you keep a reference to it after leaving the loop. + +The audio stream is read on a background thread. When the session ends +before the audio does, that thread stops as soon as the audio stream yields +its next chunk, and closes the stream if it is a generator. The SDK cannot +interrupt an audio stream that is blocked waiting for audio (for example a +microphone read with no timeout): make your audio source end, or yield +regularly, so the thread can exit. + +Closing does not wait for a server that has stopped reading: a write that +is still pending after half a second is interrupted by cutting the +connection, without a close frame. + +Read the events from one thread at a time. + +The control methods send a message at the current position in the audio +stream; they can be called from any thread once ``session_started`` has +been received. + + + +#### close + +```python +def close() -> None +``` + +Close the connection. Safe to call more than once. + + + +#### send + +```python +def send(message: ASRRealtimeControl) -> None +``` + +Send a control message. + +**Raises**: + +- `WebSocketError` - If the session is not open (not started yet, or closed) + + + +#### finalize + +```python +def finalize() -> None +``` + +Commit the current turn now (push-to-talk: the button was released). + + + +#### agent\_speaking + +```python +def agent_speaking(speaking: bool) -> None +``` + +Tell the server that your voice agent started or stopped speaking. + + + +#### add\_context + +```python +def add_context(items: list[ASRContextItem], + *, + reset_history: bool = False) -> None +``` + +Add conversation context, typically each line your agent speaks. + + + +#### configure + +```python +def configure(*, + turn_detection: Optional[ASRTurnDetection] = None, + results: Optional[ASRResults] = None, + terms: Optional[list[str]] = None) -> None +``` + +Change settings during the session. The server answers with a configured event. + + + +#### keepalive + +```python +def keepalive() -> None +``` + +Keep an idle session open. Rarely needed: WebSocket pings count as activity. + + + +## AsyncASRRealtimeStream Objects + +```python +class AsyncASRRealtimeStream() +``` + +A realtime speech-to-text session (async). + +Iterate it with ``async for`` for the server's events. The connection opens +on the first iteration and closes when the session ends, when an error is +raised, or when you leave the loop early. Use it as an async context manager +(or call ``aclose()``) if you keep a reference to it after leaving the loop. + +Closing cancels the task that reads the audio stream and closes the stream +if it is an async generator. Up to 256 events are buffered for a consumer +that reads slowly; beyond that the session stops reading from the server +until the consumer catches up. + +Read the events from one task at a time: a read started while another is +waiting raises ``RuntimeError``. A read that was cancelled (for example by +``asyncio.wait_for``) loses nothing; just read again. + +The control methods send a message at the current position in the audio +stream; they can be awaited once ``session_started`` has been received. + +Keep reading: when you stop, the SDK buffers a few hundred events and then +stops reading from the connection, which also stops it answering keepalive +pings. A consumer that stays stalled past the keepalive timeout (20 s by +default, see ``ws_options``) while events keep arriving loses the connection. + + + +#### aclose + +```python +async def aclose() -> None +``` + +Close the connection. Safe to call more than once. + + + +#### send + +```python +async def send(message: ASRRealtimeControl) -> None +``` + +Send a control message. + +**Raises**: + +- `WebSocketError` - If the session is not open (not started yet, or closed) + + + +#### finalize + +```python +async def finalize() -> None +``` + +Commit the current turn now (push-to-talk: the button was released). + + + +#### agent\_speaking + +```python +async def agent_speaking(speaking: bool) -> None +``` + +Tell the server that your voice agent started or stopped speaking. + + + +#### add\_context + +```python +async def add_context(items: list[ASRContextItem], + *, + reset_history: bool = False) -> None +``` + +Add conversation context, typically each line your agent speaks. + + + +#### configure + +```python +async def configure(*, + turn_detection: Optional[ASRTurnDetection] = None, + results: Optional[ASRResults] = None, + terms: Optional[list[str]] = None) -> None +``` + +Change settings during the session. The server answers with a configured event. + + + +#### keepalive + +```python +async def keepalive() -> None +``` + +Keep an idle session open. Rarely needed: WebSocket pings count as activity. diff --git a/api-reference/sdk/python/types.mdx b/api-reference/sdk/python/types.mdx index 38738651..40994430 100644 --- a/api-reference/sdk/python/types.mdx +++ b/api-reference/sdk/python/types.mdx @@ -57,7 +57,7 @@ Represents a TTS voice that can be used for synthesis. - `description` - Detailed description of the voice model - `cover_image` - URL to the voice model's cover image - `train_mode` - Training mode used. Options: "fast" -- `state` - Current model state: "created", "training", "trained", or "failed" +- `state` - Current model state (e.g., "ready", "training", "failed") - `tags` - List of tags for categorization (e.g., ["male", "english", "young"]) - `samples` - List of audio samples demonstrating the voice - `created_at` - Timestamp when the model was created @@ -73,52 +73,36 @@ Represents a TTS voice that can be used for synthesis. - `marked` - Whether the current user has bookmarked this model. Default: False - `author` - Information about the voice model's creator - + -# fishaudio.types.account +# fishaudio.types.shared -Account-related types (credits, packages, etc.). +Shared types used across the SDK. - + -## Credits Objects +## PaginatedResponse Objects ```python -class Credits(BaseModel) +class PaginatedResponse(BaseModel, Generic[T]) ``` -User's API credit balance. +Generic paginated response. **Attributes**: -- `id` - Unique credits record identifier -- `user_id` - User identifier -- `credit` - Current credit balance (decimal for precise accounting) -- `created_at` - Timestamp when the credits record was created -- `updated_at` - Timestamp when the credits were last updated -- `has_phone_sha256` - Whether the user has a verified phone number. Optional -- `has_free_credit` - Whether the user has received free credits. Optional +- `total` - Total number of items across all pages +- `items` - List of items on the current page - + -## Package Objects +#### warn\_if\_deprecated\_model ```python -class Package(BaseModel) +def warn_if_deprecated_model(model: str) -> None ``` -User's prepaid package information. - -**Attributes**: - -- `id` - Unique package identifier -- `user_id` - User identifier -- `type` - Package type identifier -- `total` - Total units in the package -- `balance` - Remaining units in the package -- `created_at` - Timestamp when the package was purchased -- `updated_at` - Timestamp when the package was last updated -- `finished_at` - Timestamp when the package was fully consumed. None if still active +Emit a deprecation warning if a legacy model is used. @@ -205,7 +189,7 @@ All parameters have sensible defaults. - `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). Default: "balanced" -- `reference_id` - Voice model ID from fish.audio (e.g., "9a9cf47702da476aa4629e2506d4a857"). +- `reference_id` - Voice model ID from fish.audio (e.g., "802e3bc2b27e49c2995d23ef70e6ac89"). Find IDs in voice URLs or via voices.list() - `references` - List of reference audio samples for instant voice cloning. Default: [] - `prosody` - Speech speed and volume settings. Default: None (uses natural prosody) @@ -312,36 +296,52 @@ WebSocket event to end the streaming session. - `event` - Event type identifier, always "stop" - + -# fishaudio.types.shared +# fishaudio.types.account -Shared types used across the SDK. +Account-related types (credits, packages, etc.). - + -## PaginatedResponse Objects +## Credits Objects ```python -class PaginatedResponse(BaseModel, Generic[T]) +class Credits(BaseModel) ``` -Generic paginated response. +User's API credit balance. **Attributes**: -- `total` - Total number of items across all pages -- `items` - List of items on the current page +- `id` - Unique credits record identifier +- `user_id` - User identifier +- `credit` - Current credit balance (decimal for precise accounting) +- `created_at` - Timestamp when the credits record was created +- `updated_at` - Timestamp when the credits were last updated +- `has_phone_sha256` - Whether the user has a verified phone number. Optional +- `has_free_credit` - Whether the user has received free credits. Optional - + -#### warn\_if\_deprecated\_model +## Package Objects ```python -def warn_if_deprecated_model(model: str) -> None +class Package(BaseModel) ``` -Emit a deprecation warning if a legacy model is used. +User's prepaid package information. + +**Attributes**: + +- `id` - Unique package identifier +- `user_id` - User identifier +- `type` - Package type identifier +- `total` - Total units in the package +- `balance` - Remaining units in the package +- `created_at` - Timestamp when the package was purchased +- `updated_at` - Timestamp when the package was last updated +- `finished_at` - Timestamp when the package was fully consumed. None if still active @@ -365,6 +365,23 @@ A timestamped segment of transcribed text. - `start` - Segment start time in seconds - `end` - Segment end time in seconds + + +## SpeakerTurn Objects + +```python +class SpeakerTurn(BaseModel) +``` + +A stretch of the transcript spoken by one speaker. + +**Attributes**: + +- `speaker` - Speaker label (e.g., "speaker:0"). Labels identify speakers within one response only +- `text` - What the speaker said in this turn, without inline speaker markers +- `start` - Turn start time in seconds +- `end` - Turn end time in seconds + ## ASRResponse Objects @@ -380,6 +397,10 @@ Response from speech-to-text transcription. - `text` - Complete transcription of the entire audio - `duration` - Total audio duration in seconds - `segments` - List of timestamped text segments. Empty if include_timestamps=False +- `language` - Display name of the transcript's language (e.g., "English"). None if not returned +- `language_code` - Language code of the transcript (e.g., "en"): the detected language, or the requested language if none was detected. None if not returned +- `request_id` - Identifier of this request; quote it when reporting a problem with the request. None if not returned +- `speaker_turns` - Speaker turns in order, with times in seconds. Returned only by models with speaker diarization, and only if include_timestamps=True; empty if no speech was found. None otherwise @@ -387,3 +408,498 @@ Response from speech-to-text transcription. Duration in seconds + + +# fishaudio.types.asr\_realtime + +Types for realtime speech-to-text (``/v1/asr/realtime``). + + + +## ASRTurnDetection Objects + +```python +class ASRTurnDetection(BaseModel) +``` + +How the server decides that a turn has ended. + +Fields left as None are not sent: the server uses its default at session +start, and keeps the current value in a mid-session ``configure``. + +**Attributes**: + +- `mode` - "auto" (default): the server judges when the user has finished and tells + user turns from noise and other voices. "vad": a turn ends after + silence_timeout_ms of silence. "manual": a turn ends when you send finalize +- `eager` - Send eager_end_of_turn events (auto mode only). Server default: False +- `silence_timeout_ms` - Silence that ends a turn. auto: default 5000, allowed + 3000-60000. vad: default 700, allowed 300-60000. manual: default 60000, + allowed 300-60000 + + + +## ASRResults Objects + +```python +class ASRResults(BaseModel) +``` + +Which results the server sends, and what the transcript text contains. + +Fields left as None are not sent: the server uses its default at session +start, and keeps the current value in a mid-session ``configure``. + +**Attributes**: + +- `drafts` - Send live draft events. Server default: False +- `ignore_timestamps` - False adds word timings to committed events. Server default: True +- `diarize` - Speaker tags such as ``<|speaker:0|>`` in the text. Server default: True +- `tag_audio_events` - Sound tags such as ``[laughter]`` in the text. Server default: True +- `vad_events` - Send vad events (voice activity, up to 10 per second). Server default: False +- `eot_events` - Send eot_prob events (end-of-turn likelihood). Server default: False + + + +## ASRContextItem Objects + +```python +class ASRContextItem(BaseModel) +``` + +One line of conversation given to the server as context. + +**Attributes**: + +- `role` - Who said it: "user" or "assistant" +- `text` - What was said (up to 2000 characters) + + + +## ASRContext Objects + +```python +class ASRContext(BaseModel) +``` + +Conversation context that helps the server recognize names and follow-ups. + +**Attributes**: + +- `history` - Earlier conversation, oldest first (up to 32 items). Only accepted + at session start; add lines later with context_add +- `terms` - Names, products and jargon to recognize (up to 100 terms of up to + 32 characters) + + + +## ASRRealtimeConfig Objects + +```python +class ASRRealtimeConfig(BaseModel) +``` + +Configuration for a realtime speech-to-text session. + +**Attributes**: + +- `sample_rate` - Sample rate of the audio you send, in Hz. The server converts + other rates to 16000, so you never need to resample. Default: 16000 +- `turn_detection` - Turn detection settings. Default: None (server defaults) +- `results` - Result settings. Default: None (server defaults) +- `context` - Conversation history and custom vocabulary. Default: None +- `client_reference_id` - Your own ID for the session (up to 256 characters). + Recorded with the session; not sent back. Default: None + + + +## ASRFinalizeEvent Objects + +```python +class ASRFinalizeEvent(BaseModel) +``` + +Commit the current turn now (push-to-talk: the button was released). + +**Attributes**: + +- `type` - Message type identifier, always "finalize" + + + +## ASRAgentSpeakingEvent Objects + +```python +class ASRAgentSpeakingEvent(BaseModel) +``` + +Tell the server whether your voice agent is speaking (auto mode). + +While the agent speaks, a short acknowledgement from the user produces +user_backchannel instead of user_turn_taken. + +**Attributes**: + +- `type` - Message type identifier, always "agent_speaking" +- `speaking` - True when you commit to playing a reply; False when its last + sample has played or you stop it + + + +## ASRContextAddEvent Objects + +```python +class ASRContextAddEvent(BaseModel) +``` + +Add conversation context, typically each line your agent speaks. + +**Attributes**: + +- `type` - Message type identifier, always "context_add" +- `items` - Conversation items, oldest first (up to 32) +- `reset_history` - First drop the items you added before. Default: False + + + +## ASRConfigureEvent Objects + +```python +class ASRConfigureEvent(BaseModel) +``` + +Change settings during the session. Answered by a configured event. + +**Attributes**: + +- `type` - Message type identifier, always "configure" +- `turn_detection` - Turn detection changes; omitted fields keep their values +- `results` - Result changes; omitted fields keep their values +- `context` - Only ``terms`` is accepted here; it replaces the list of terms + + + +## ASRKeepaliveEvent Objects + +```python +class ASRKeepaliveEvent(BaseModel) +``` + +Keep an idle session open. + +Rarely needed: the SDK's WebSocket pings already count as client activity. + +**Attributes**: + +- `type` - Message type identifier, always "keepalive" + + + +## ASRWord Objects + +```python +class ASRWord(BaseModel) +``` + +A word of a committed transcript with its position in the audio. + +**Attributes**: + +- `text` - The word +- `start_ms` - Where the word starts, in milliseconds of session audio +- `end_ms` - Where the word ends, in milliseconds of session audio + + + +## ASRSessionStartedEvent Objects + +```python +class ASRSessionStartedEvent(_ServerEvent) +``` + +The session is ready; audio is sent after this event. + +**Attributes**: + +- `type` - Event type identifier, always "session_started" +- `seq` - Sequence number, increasing by one per server message +- `session_id` - The session's ID +- `request_id` - Identifier of this request; quote it when reporting a problem +- `config` - The configuration in effect, with defaults filled in +- `limits` - Session limits (max_session_ms, max_turn_ms, max_frame_bytes) + + + +## ASRSpeechStartEvent Objects + +```python +class ASRSpeechStartEvent(_ServerEvent) +``` + +A turn opened on voice activity. + +In auto mode noise and other voices open turns too: wait for +user_turn_taken before treating it as the user's turn. + +**Attributes**: + +- `type` - Event type identifier, always "speech_start" +- `seq` - Sequence number +- `turn_index` - The turn that opened, counting from 0 +- `audio_ms` - Where the turn starts, slightly before the speech + + + +## ASRUserTurnTakenEvent Objects + +```python +class ASRUserTurnTakenEvent(_ServerEvent) +``` + +Auto mode: the server judged that the user is taking their turn. + +For a voice agent that is speaking, this is the signal to stop (barge-in). + +**Attributes**: + +- `type` - Event type identifier, always "user_turn_taken" +- `seq` - Sequence number +- `turn_index` - The turn the user took +- `audio_ms` - Where the server judged that the user took the turn + + + +## ASRDraftEvent Objects + +```python +class ASRDraftEvent(_ServerEvent) +``` + +Live draft of the open turn (with ``drafts=True``). Not final. + +**Attributes**: + +- `type` - Event type identifier, always "draft" +- `seq` - Sequence number +- `turn_index` - The open turn +- `text` - The whole turn so far. Replaces the previous draft +- `settled_text` - The beginning of text that the server is confident will not + change. Often empty +- `language` - English name of the detected language. None if not identified +- `language_code` - ISO 639-1 code of the detected language. None if not identified +- `audio_ms` - The audio position the draft covers up to +- `audio_received_ms` - Audio received so far +- `audio_processed_ms` - Audio processed so far +- `audio_committed_ms` - Audio covered by committed turns so far + + + +## ASREagerEndOfTurnEvent Objects + +```python +class ASREagerEndOfTurnEvent(_ServerEvent) +``` + +The turn has probably ended (auto mode with ``eager=True``). + +Start preparing your response; a turn_resumed event cancels it. + +**Attributes**: + +- `type` - Event type identifier, always "eager_end_of_turn" +- `seq` - Sequence number +- `turn_index` - The turn that probably ended +- `text` - Exactly what committed will say unless turn_resumed follows. Can be empty +- `language` - English name of the detected language. None if not identified +- `language_code` - ISO 639-1 code of the detected language. None if not identified +- `audio_ms` - The audio position of the signal + + + +## ASRTurnResumedEvent Objects + +```python +class ASRTurnResumedEvent(_ServerEvent) +``` + +The speaker went on after eager_end_of_turn: discard that text. + +**Attributes**: + +- `type` - Event type identifier, always "turn_resumed" +- `seq` - Sequence number +- `turn_index` - The turn that resumed + + + +## ASRUserBackchannelEvent Objects + +```python +class ASRUserBackchannelEvent(_ServerEvent) +``` + +Auto mode, while your agent speaks: the user only acknowledged ("mm-hm"). + +**Attributes**: + +- `type` - Event type identifier, always "user_backchannel" +- `seq` - Sequence number +- `turn_index` - The open turn, or the index the next turn will get +- `audio_ms` - Where the acknowledgement is in the audio + + + +## ASRCommittedEvent Objects + +```python +class ASRCommittedEvent(_ServerEvent) +``` + +The final transcript of a turn. Every turn has exactly one. + +**Attributes**: + +- `type` - Event type identifier, always "committed" +- `seq` - Sequence number +- `turn_index` - The turn that ended +- `text` - The final transcript. Can contain speaker tags such as ``<|speaker:0|>`` + and sound tags such as ``[laughter]``. Can be empty +- `words` - Word timings. Only with ``ignore_timestamps=False``; None otherwise +- `language` - English name of the detected language. None if not identified +- `language_code` - ISO 639-1 code of the detected language. None if not identified +- `audio_start_ms` - Where the turn starts in the session audio +- `audio_end_ms` - Where the turn ends in the session audio +- `reason` - Why the turn ended: "eot", "finalize", "silence_timeout", + "max_turn_duration" or "audio_done". Treat an unknown value like "eot" +- `degraded` - True when the final pass failed and the text comes from the last draft +- `user_turn` - True for the user's turn. Decide whether to answer by this field +- `turn_kind` - "user", "backchannel" or "other" +- `audio_received_ms` - Audio received so far +- `audio_processed_ms` - Audio processed so far +- `audio_committed_ms` - Audio covered by committed turns so far + + + +## ASRVadEvent Objects + +```python +class ASRVadEvent(_ServerEvent) +``` + +Voice activity (with ``vad_events=True``), up to 10 per second. + +**Attributes**: + +- `type` - Event type identifier, always "vad" +- `seq` - Sequence number +- `audio_ms` - The audio position of the score +- `score` - Voice activity, from 0 to 1 + + + +## ASREotProbEvent Objects + +```python +class ASREotProbEvent(_ServerEvent) +``` + +End-of-turn likelihood for display (with ``eot_events=True``). + +**Attributes**: + +- `type` - Event type identifier, always "eot_prob" +- `seq` - Sequence number +- `turn_index` - The open turn +- `audio_ms` - The audio position of the estimate +- `prob` - End-of-turn likelihood, from 0 to 1 + + + +## ASRConfiguredEvent Objects + +```python +class ASRConfiguredEvent(_ServerEvent) +``` + +The reply to a configure message. + +**Attributes**: + +- `type` - Event type identifier, always "configured" +- `seq` - Sequence number +- `ok` - False means nothing changed +- `config` - The configuration in effect +- `message` - Why the change was refused, in English. None when ok is True + + + +## ASRProgressEvent Objects + +```python +class ASRProgressEvent(_ServerEvent) +``` + +Audio watermarks, sent every 5 seconds while the client sends nothing. + +**Attributes**: + +- `type` - Event type identifier, always "progress" +- `seq` - Sequence number +- `audio_received_ms` - Audio received so far +- `audio_processed_ms` - Audio processed so far +- `audio_committed_ms` - Audio covered by committed turns so far + + + +## ASRErrorEvent Objects + +```python +class ASRErrorEvent(_ServerEvent) +``` + +A recoverable error: the session continues. + +Errors that end the session are raised as ASRRealtimeError instead. + +**Attributes**: + +- `type` - Event type identifier, always "error" +- `seq` - Sequence number +- `code` - HTTP-style status +- `error_type` - Machine-readable error type, e.g. "invalid_request". Match on this +- `message` - A short English description, for humans +- `request_id` - Identifier of this request; quote it when reporting a problem +- `recoverable` - True when the session continues + + + +## ASRSessionStats Objects + +```python +class ASRSessionStats(BaseModel) +``` + +Totals for a finished session. + +**Attributes**: + +- `audio_ms` - Audio received in the session +- `turns` - Every committed turn, user turn or not +- `request_id` - Identifier of this request + + + +## ASRSessionDoneEvent Objects + +```python +class ASRSessionDoneEvent(_ServerEvent) +``` + +The session ended normally. Always the last event. + +**Attributes**: + +- `type` - Event type identifier, always "session_done" +- `seq` - Sequence number +- `stats` - Totals for the session + diff --git a/api-reference/sdk/python/utils.mdx b/api-reference/sdk/python/utils.mdx index 93a81c58..30f93ea2 100644 --- a/api-reference/sdk/python/utils.mdx +++ b/api-reference/sdk/python/utils.mdx @@ -4,8 +4,6 @@ Audio playback utility. -Install the Python SDK first: `pip install fish-audio-sdk`. - #### play