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
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,9 +377,9 @@ client = FishAudio(httpx_client=http_client)

```python
from fishaudio.exceptions import (
APIError,
AuthenticationError,
RateLimitError,
ValidationError,
FishAudioError,
)

Expand All @@ -389,12 +389,15 @@ except AuthenticationError:
print("Invalid API key")
except RateLimitError:
print("Rate limit exceeded")
except ValidationError as e:
print(f"Invalid request: {e}")
except APIError as e:
# Any other error response, such as 400 for a request the API rejects
print(f"API error {e.status}: {e.message}")
except FishAudioError as e:
print(f"API error: {e}")
print(f"Error: {e}")
```

A value the SDK can check before sending, such as a `speed` outside 0.5 to 2.0, raises pydantic's `ValidationError` instead, and no request is sent. `fishaudio.exceptions.ValidationError` is not raised by the SDK.

Every `APIError` carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent.

```python
Expand Down
12 changes: 6 additions & 6 deletions src/fishaudio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ class FishAudio:
# Generate speech
audio = client.tts.convert(text="Hello world")
with open("output.mp3", "wb") as f:
for chunk in audio:
f.write(chunk)
f.write(audio)

# List voices
voices = client.voices.list(page_size=20)
Expand Down Expand Up @@ -114,16 +113,17 @@ class AsyncFishAudio:

Example:
```python
import asyncio

from fishaudio import AsyncFishAudio

async def main():
client = AsyncFishAudio(api_key="your_api_key")

# Generate speech
audio = client.tts.convert(text="Hello world")
async with aiofiles.open("output.mp3", "wb") as f:
async for chunk in audio:
await f.write(chunk)
audio = await client.tts.convert(text="Hello world")
with open("output.mp3", "wb") as f:
f.write(audio)

# List voices
voices = await client.voices.list(page_size=20)
Expand Down
6 changes: 6 additions & 0 deletions src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""HTTP client wrapper for managing requests and authentication."""

import json
import os
import platform
import re
Expand Down Expand Up @@ -74,13 +75,18 @@ def _raise_for_status(response: httpx.Response) -> None:
If the body is a JSON object with a truthy ``message`` field, that is the
message; otherwise its truthy ``detail`` field. In every other case the
message is the body text, or the status phrase when the text is empty.
A field that is not a string is turned into JSON text.
"""
status = response.status_code
data, text = _read_error_body(response)

message = None
if isinstance(data, dict):
message = data.get("message") or data.get("detail")
if message and not isinstance(message, str):
# A structured field (a 422's list of problems, say) becomes text:
# APIError.message is a str. The body keeps the content as sent.
message = json.dumps(message, ensure_ascii=False)

raise _api_error(
status,
Expand Down
32 changes: 31 additions & 1 deletion src/fishaudio/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
"""Custom exceptions for the Fish Audio SDK."""

from collections.abc import Mapping
from typing import Optional
from typing import Any, Optional

import httpx


def _builds_as(error: BaseException, cls: type) -> bool:
"""Whether error's class is constructed exactly as cls is (the SDK's own
construction), not by a subclass that changed __init__ or __new__, or
whose metaclass does the constructing."""
kind = type(error)
return (
type(kind) is type(cls)
and kind.__init__ is cls.__init__
and kind.__new__ is cls.__new__
)


class FishAudioError(Exception):
"""Base exception for all Fish Audio SDK errors."""

Expand Down Expand Up @@ -38,6 +50,17 @@ def __init__(
self.headers = httpx.Headers(headers, encoding="utf-8")
super().__init__(f"HTTP {status}: {message}")

def __reduce__(self) -> Any:
# Pickle (worker pools, multiprocessing) calls the class with args,
# which hold only the formatted text. For the SDK's own construction,
# pass the constructor's arguments instead (the headers as they are,
# raw bytes kept); __dict__ carries the rest. A subclass that changes
# construction pickles as any exception does.
if _builds_as(self, APIError):
args = (self.status, self.message, self.body, self.headers)
return (type(self), args, self.__dict__)
return super().__reduce__()


class AuthenticationError(APIError):
"""Raised when authentication fails (401)."""
Expand Down Expand Up @@ -117,3 +140,10 @@ def __init__(self, dependency: str, install_command: str):
f"Missing required dependency: {dependency}\n"
f"Install it with: {install_command}"
)

def __reduce__(self) -> Any:
# As APIError.__reduce__: the SDK's own construction only.
if _builds_as(self, DependencyError):
args = (self.dependency, self.install_command)
return (type(self), args, self.__dict__)
return super().__reduce__()
Empty file added src/fishaudio/py.typed
Empty file.
22 changes: 16 additions & 6 deletions src/fishaudio/resources/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,17 @@ def transcribe(
(and speaker turns, on models that return them)
model: ASR model, e.g. "transcribe-2-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.
When the outgoing request carries no ``model`` header (from
this argument, request_options, or headers set on a custom
httpx client), it runs on the API's default model, transcribe-1.
transcribe-1 is deprecated and will be retired on December 31,
2026; after that date, the requests it serves, including those
with no ``model`` header, are served by transcribe-2-pro.
Passing "transcribe-1" emits a FutureWarning.
Pass model="transcribe-2-pro" to move to it now; a request
without a model gets no warning. "transcribe-1" given as
``model``, or as a ``model`` header in request_options when
``model`` is not given, emits a FutureWarning; one set only
in a custom httpx client's headers is not seen.
request_options: Request-level overrides

Returns:
Expand Down Expand Up @@ -301,12 +306,17 @@ async def transcribe(
(and speaker turns, on models that return them)
model: ASR model, e.g. "transcribe-2-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.
When the outgoing request carries no ``model`` header (from
this argument, request_options, or headers set on a custom
httpx client), it runs on the API's default model, transcribe-1.
transcribe-1 is deprecated and will be retired on December 31,
2026; after that date, the requests it serves, including those
with no ``model`` header, are served by transcribe-2-pro.
Passing "transcribe-1" emits a FutureWarning.
Pass model="transcribe-2-pro" to move to it now; a request
without a model gets no warning. "transcribe-1" given as
``model``, or as a ``model`` header in request_options when
``model`` is not given, emits a FutureWarning; one set only
in a custom httpx client's headers is not seen.
request_options: Request-level overrides

Returns:
Expand Down
22 changes: 18 additions & 4 deletions src/fishaudio/utils/play.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,25 @@ def play(

Args:
audio: Audio bytes or iterable of bytes
notebook: Use Jupyter notebook playback (IPython.display.Audio)
use_ffmpeg: Use ffplay for playback (default, falls back to sounddevice)
notebook: Use Jupyter notebook playback (IPython.display.Audio).
``use_ffmpeg`` is then ignored: neither ffplay nor sounddevice
is used.
use_ffmpeg: Outside notebook mode, play with ffplay (the default). If ffplay is not
installed, DependencyError is raised; there is no fallback.
Playback falls back to sounddevice only when ffplay exits with a
non-zero status (an ffplay that reports a problem but exits with
0 counts as played). False plays with sounddevice (the
``[utils]`` extra).

Raises:
DependencyError: If required playback tool is not installed
DependencyError: If IPython is not installed (``notebook=True``, which
is checked first), if ffplay is not installed (``use_ffmpeg=True``), or
sounddevice or soundfile cannot be imported when sounddevice is
used: any ImportError from importing them (a missing package, or
a missing native binding) is raised as DependencyError, with the
original error chained to it. Other errors from importing them
(an OSError for a missing PortAudio library, say) are raised as
they are.

Examples:
```python
Expand All @@ -44,7 +58,7 @@ def play(
# In Jupyter notebook
play(audio, notebook=True)

# Force sounddevice fallback
# Play with sounddevice instead of ffplay
play(audio, use_ffmpeg=False)
```
"""
Expand Down
13 changes: 7 additions & 6 deletions src/fishaudio/utils/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import shutil
import subprocess
from collections.abc import Iterator
from collections.abc import Iterable

from fishaudio.exceptions import DependencyError

Expand All @@ -12,15 +12,15 @@ def _is_installed(command: str) -> bool:
return shutil.which(command) is not None


def stream(audio_stream: Iterator[bytes]) -> bytes:
def stream(audio_stream: Iterable[bytes]) -> bytes:
"""
Stream audio in real-time while playing it with mpv.

This function plays the audio as it's being generated and
simultaneously captures it to return the complete audio buffer.

Args:
audio_stream: Iterator of audio byte chunks
audio_stream: Audio byte chunks, such as ``client.tts.stream(...)``

Returns:
Complete audio bytes after streaming finishes
Expand All @@ -33,10 +33,11 @@ def stream(audio_stream: Iterator[bytes]) -> bytes:
from fishaudio import FishAudio, stream

client = FishAudio(api_key="...")
audio_stream = client.tts.convert(text="Hello world")

# Stream and play in real-time, get complete audio
complete_audio = stream(audio_stream)
# Stream and play in real-time, get complete audio. The with block
# closes the response even if playback fails (mpv missing, say).
with client.tts.stream(text="Hello world") as audio_stream:
complete_audio = stream(audio_stream)

# Save the captured audio
with open("output.mp3", "wb") as f:
Expand Down
Loading