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
41 changes: 23 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,14 @@ import asyncio
from fishaudio import AsyncFishAudio
from fishaudio.utils import play, save


async def main():
client = AsyncFishAudio()
audio = await client.tts.convert(text="Hello, world!")
play(audio)
save(audio, "output.mp3")


asyncio.run(main())
```

Expand Down Expand Up @@ -115,8 +117,7 @@ drama_audio = client.tts.convert(
```python
# Use a specific voice by ID
audio = client.tts.convert(
text="Custom voice",
reference_id="802e3bc2b27e49c2995d23ef70e6ac89"
text="Custom voice", reference_id="802e3bc2b27e49c2995d23ef70e6ac89"
)
```

Expand All @@ -125,7 +126,7 @@ audio = client.tts.convert(
```python
audio = client.tts.convert(
text="Speaking faster!",
speed=1.5 # 1.5x speed
speed=1.5, # 1.5x speed
)
```

Expand All @@ -138,7 +139,7 @@ config = TTSConfig(
prosody=Prosody(speed=1.2, volume=-5),
reference_id="933563129e564b19a115bedd57b7406a",
format="wav",
latency="balanced"
latency="balanced",
)

# Reuse across generations
Expand Down Expand Up @@ -210,11 +211,13 @@ print(result.language_code) # e.g. "en"
```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
Expand All @@ -241,6 +244,7 @@ def text_chunks():
yield "this is "
yield "streaming!"


audio_stream = client.tts.stream_websocket(text_chunks(), latency="balanced")
play(audio_stream)
```
Expand All @@ -251,11 +255,13 @@ play(audio_stream)
import asyncio
from fishaudio import AsyncFishAudio


async def text_chunks():
yield "Hello, "
yield "this is "
yield "streaming!"


async def main():
client = AsyncFishAudio()
# stream_websocket is an async generator: iterate it, don't await the call
Expand All @@ -264,6 +270,7 @@ async def main():
async for chunk in audio_stream:
f.write(chunk)


asyncio.run(main())
```

Expand All @@ -280,10 +287,7 @@ from fishaudio.types import ReferenceAudio
with open("reference.wav", "rb") as f:
audio = client.tts.convert(
text="Cloned voice speaking",
references=[ReferenceAudio(
audio=f.read(),
text="Text spoken in reference"
)]
references=[ReferenceAudio(audio=f.read(), text="Text spoken in reference")],
)
```

Expand All @@ -293,16 +297,11 @@ with open("reference.wav", "rb") as f:
# Create voice model for reuse
with open("voice_sample.wav", "rb") as f:
voice = client.voices.create(
title="My Voice",
voices=[f.read()],
description="Custom voice clone"
title="My Voice", voices=[f.read()], description="Custom voice clone"
)

# Use the created model
audio = client.tts.convert(
text="Using my saved voice",
reference_id=voice.id
)
audio = client.tts.convert(text="Using my saved voice", reference_id=voice.id)
```

[Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/voice-cloning)
Expand Down Expand Up @@ -334,18 +333,24 @@ HTTPXClientInstrumentor().instrument()
from fishaudio.core import RequestOptions, WebSocketOptions

headers = {"traceparent": traceparent}
audio = client.tts.convert(text="Hello!", request_options=RequestOptions(additional_headers=headers))
stream = client.tts.stream_websocket(text_chunks(), ws_options=WebSocketOptions(additional_headers=headers))
audio = client.tts.convert(
text="Hello!", request_options=RequestOptions(additional_headers=headers)
)
stream = client.tts.stream_websocket(
text_chunks(), ws_options=WebSocketOptions(additional_headers=headers)
)
```

Or give the client an `httpx_client` with a request event hook, which runs for HTTP calls and WebSocket handshakes alike (with `AsyncFishAudio`, use an `httpx.AsyncClient` and an async hook). A client you pass in keeps its own settings, so set its `timeout`: httpx's default is 5 seconds.

```python
import httpx


def add_traceparent(request):
request.headers["traceparent"] = current_traceparent()


http_client = httpx.Client(
base_url="https://api.fish.audio",
timeout=240.0,
Expand All @@ -361,7 +366,7 @@ from fishaudio.exceptions import (
AuthenticationError,
RateLimitError,
ValidationError,
FishAudioError
FishAudioError,
)

try:
Expand Down
2 changes: 1 addition & 1 deletion examples/getting-started/01_simple_tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def main():
if __name__ == "__main__":
try:
main()
except Exception as e:
except Exception as e: # noqa: BLE001
print(f"Error: {e}")
print("\nMake sure you have set your API key:")
print(" export FISH_API_KEY='your_api_key'")
2 changes: 1 addition & 1 deletion examples/getting-started/02_play_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def demo_playback_methods():
# print("="*50 + "\n")
# demo_playback_methods()

except Exception as e:
except Exception as e: # noqa: BLE001
print(f"Error: {e}")
print("\nTroubleshooting:")
print("1. Make sure your API key is set: export FISH_API_KEY='your_key'")
Expand Down
8 changes: 4 additions & 4 deletions examples/getting-started/03_check_credits.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def main():
# Note: Credits are consumed based on usage
# Check the Fish Audio pricing page for current rates

except Exception as e:
except Exception as e: # noqa: BLE001
print(f" Error fetching credits: {e}")

# Check prepaid package information
Expand All @@ -56,7 +56,7 @@ def main():
else:
print(" No active prepaid package")

except Exception as e:
except Exception as e: # noqa: BLE001
print(f" Error fetching package: {e}")

print("\n" + "=" * 60)
Expand All @@ -79,7 +79,7 @@ def check_api_setup():
print(f" Your current balance: {float(credits.credit):,.2f} credits")
return True

except Exception as e:
except Exception as e: # noqa: BLE001
print("API setup failed!")
print(f" Error: {e}")
print("\nPlease check:")
Expand All @@ -97,7 +97,7 @@ def check_api_setup():
# print("\n\nRunning quick API setup check...")
# check_api_setup()

except Exception as e:
except Exception as e: # noqa: BLE001
print(f"\nError: {e}")
print("\nMake sure you have set your API key:")
print(" export FISH_API_KEY='your_api_key'")
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ dev = [
"pytest-cov>=5.0.0",
"pytest-rerunfailures>=16.0.1",
"python-dotenv>=1.0.1",
"ruff>=0.14.3",
"ty>=0.0.2",
"ruff>=0.17.6",
"ty>=0.0.109",
]

[[tool.pydoc-markdown.loaders]]
Expand Down
Empty file modified scripts/copy_docs.py
100644 → 100755
Empty file.
20 changes: 10 additions & 10 deletions src/fish_audio_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@
from .websocket import AsyncWebSocketSession, WebSocketSession

__all__ = [
"Session",
"HttpCodeErr",
"WebSocketErr",
"ReferenceAudio",
"TTSRequest",
"APICreditEntity",
"ASRRequest",
"WebSocketSession",
"AsyncWebSocketSession",
"Prosody",
"PaginatedResponse",
"CloseEvent",
"HttpCodeErr",
"ModelEntity",
"APICreditEntity",
"PaginatedResponse",
"Prosody",
"ReferenceAudio",
"Session",
"StartEvent",
"TTSRequest",
"TextEvent",
"CloseEvent",
"WebSocketErr",
"WebSocketSession",
]
6 changes: 3 additions & 3 deletions src/fish_audio_sdk/schemas.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

import datetime
import datetime as dt
import decimal
from typing import Annotated, Generic, Literal, TypeVar

Expand Down Expand Up @@ -84,8 +84,8 @@ class ModelEntity(BaseModel):
state: Literal["created", "training", "trained", "failed"]
tags: list[str]
samples: list[SampleEntity]
created_at: datetime.datetime
updated_at: datetime.datetime
created_at: dt.datetime
updated_at: dt.datetime
languages: list[str]
visibility: Literal["public", "unlist", "private"]
lock_visibility: bool
Expand Down
2 changes: 1 addition & 1 deletion src/fishaudio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
from .utils import play, save, stream

# Main exports
__all__ = [
__all__ = [ # noqa: RUF022 - grouped by topic
# Main clients
"FishAudio",
"AsyncFishAudio",
Expand Down
2 changes: 1 addition & 1 deletion src/fishaudio/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from .websocket_options import WebSocketOptions

__all__ = [
"OMIT",
"AsyncClientWrapper",
"ClientWrapper",
"OMIT",
"RequestOptions",
"WebSocketOptions",
]
3 changes: 1 addition & 2 deletions src/fishaudio/core/_sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ def feed(self, chunk: bytes) -> list[ServerSentEvent]:
continue # comment, used by servers as a keep-alive

name, _, value = line.decode("utf-8", errors="replace").partition(":")
if value.startswith(" "):
value = value[1:]
value = value.removeprefix(" ")
if name == "data":
self._data.append(value)
elif name == "event":
Expand Down
6 changes: 3 additions & 3 deletions src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ def _read_error_body(response: httpx.Response) -> tuple[Any, str]:
"""
try:
text = response.text
except Exception:
except Exception: # noqa: BLE001 - an unreadable body becomes an empty text
try:
text = response.content.decode("utf-8", errors="replace")
except Exception:
except Exception: # noqa: BLE001 - an unreadable body becomes an empty text
text = ""
try:
data = response.json()
except Exception:
except Exception: # noqa: BLE001 - a body that is not JSON becomes None
data = None
return data, text

Expand Down
14 changes: 6 additions & 8 deletions src/fishaudio/core/iterators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import Optional

import httpx
from typing_extensions import Self

from fishaudio.types.shared import _set_response_headers
from fishaudio.types.tts import (
Expand Down Expand Up @@ -84,7 +85,7 @@ def close(self) -> None:
if self._on_close is not None:
self._on_close()

def __enter__(self) -> "AudioStream":
def __enter__(self) -> Self:
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
Expand All @@ -107,10 +108,7 @@ def collect(self) -> bytes:
```
"""
try:
chunks = []
for chunk in self._iter:
chunks.append(chunk)
return b"".join(chunks)
return b"".join(self._iter)
finally:
self.close()

Expand Down Expand Up @@ -186,7 +184,7 @@ async def aclose(self) -> None:
if self._on_close is not None:
await self._on_close()

async def __aenter__(self) -> "AsyncAudioStream":
async def __aenter__(self) -> Self:
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
Expand Down Expand Up @@ -348,7 +346,7 @@ def close(self) -> None:
if self._on_close is not None:
self._on_close()

def __enter__(self) -> "TTSTimestampStream":
def __enter__(self) -> Self:
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
Expand Down Expand Up @@ -478,7 +476,7 @@ async def aclose(self) -> None:
if self._on_close is not None:
await self._on_close()

async def __aenter__(self) -> "AsyncTTSTimestampStream":
async def __aenter__(self) -> Self:
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
Expand Down
Loading
Loading