Skip to content
Open
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
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,25 @@ for chunk in client.tts.stream(text="Long content..."):
audio = client.tts.stream(text="Hello!").collect()
```

**Word-level timestamps:**

```python
# Audio plus the start and end time of every word, for captions, highlighting or lip-sync
result = client.tts.convert_with_timestamps(text="Hello! Welcome to Fish Audio.")
save(result.audio, "output.mp3")

for segment in result.segments:
print(f"{segment.start:.2f}s - {segment.end:.2f}s {segment.text}")

# Or use audio and timings while they arrive
with client.tts.stream_with_timestamps(text="Long content...", format="opus") as stream:
for event in stream:
send_to_player(event.audio)
update_captions(stream.segments) # timings so far, in seconds from the start
```

Text without words (only punctuation, or a sound tag such as `[sigh]`) still produces audio, but the API has no timings for it: `segments` is then empty and `result.duration` is `None`.

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

### Speech-to-Text
Expand Down Expand Up @@ -279,7 +298,7 @@ audio = client.tts.convert(

| Resource | Description | Key Methods |
|----------|-------------|-------------|
| `client.tts` | Text-to-speech | `convert()`, `stream()`, `stream_websocket()` |
| `client.tts` | Text-to-speech | `convert()`, `stream()`, `convert_with_timestamps()`, `stream_with_timestamps()`, `stream_websocket()` |
| `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
17 changes: 16 additions & 1 deletion src/fishaudio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@

from ._version import __version__
from .client import AsyncFishAudio, FishAudio
from .core.iterators import AsyncAudioStream, AudioStream
from .core.iterators import (
AsyncAudioStream,
AsyncTTSTimestampStream,
AudioStream,
TTSTimestampStream,
)
from .core.websocket_options import WebSocketOptions
from .exceptions import (
APIError,
Expand All @@ -54,7 +59,11 @@
FlushEvent,
ReferenceAudio,
TextEvent,
TTSAlignment,
TTSConfig,
TTSTimestampEvent,
TTSTimestampResult,
TTSTimestampSegment,
)
from .utils import play, save, stream

Expand All @@ -70,6 +79,8 @@
# Audio streams
"AudioStream",
"AsyncAudioStream",
"TTSTimestampStream",
"AsyncTTSTimestampStream",
# Realtime speech-to-text sessions
"ASRRealtimeStream",
"AsyncASRRealtimeStream",
Expand All @@ -86,6 +97,10 @@
"FlushEvent",
"ReferenceAudio",
"TextEvent",
"TTSAlignment",
"TTSTimestampEvent",
"TTSTimestampResult",
"TTSTimestampSegment",
# Exceptions
"APIError",
"ASRRealtimeError",
Expand Down
63 changes: 63 additions & 0 deletions src/fishaudio/core/_sse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Minimal Server-Sent Events decoder."""

from typing import NamedTuple


class ServerSentEvent(NamedTuple):
"""One dispatched SSE event."""

event: str
data: str


class SSEDecoder:
"""Incrementally decode a Server-Sent Events byte stream.

Feed raw response bytes with `feed()`; each call returns the events that
were completed by those bytes. Lines end with CRLF, LF or CR, the three
endings the SSE specification allows; other Unicode line separators stay
inside the payload. An event left unterminated when the stream ends is
dropped, as the specification requires.
"""

def __init__(self) -> None:
self._buffer = b""
self._skip_lf = False
self._event = ""
self._data: list[str] = []

def feed(self, chunk: bytes) -> list[ServerSentEvent]:
"""Add bytes from the stream and return the events they complete."""
if not chunk:
return []
# A CR ends its line at once, so a CR-only stream is never held back.
# If the previous chunk ended with CR, a leading LF here is the second
# half of a CRLF pair and not another line ending.
if self._skip_lf and chunk.startswith(b"\n"):
chunk = chunk[1:]
self._skip_lf = chunk.endswith(b"\r")

chunk = chunk.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
*lines, self._buffer = (self._buffer + chunk).split(b"\n")

events = []
for line in lines:
if not line:
if self._data:
events.append(
ServerSentEvent(self._event or "message", "\n".join(self._data))
)
self._event = ""
self._data = []
continue
if line.startswith(b":"):
continue # comment, used by servers as a keep-alive

name, _, value = line.decode("utf-8", errors="replace").partition(":")
if value.startswith(" "):
value = value[1:]
if name == "data":
self._data.append(value)
elif name == "event":
self._event = value
return events
Loading