From 957659fbfab8908e4fd0bfe3c69facc03a21b5ab Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:13:46 -0800 Subject: [PATCH 1/3] feat(tts): add text-to-speech with word-level timestamps Add client.tts.convert_with_timestamps() and stream_with_timestamps() (sync and async) on top of POST /v1/tts/stream/with-timestamp. Events are typed (audio bytes plus the timing snapshot), and the stream keeps the per-chunk snapshots merged into one timeline measured from the start of the complete audio. Refs #17 Co-Authored-By: Claude Fable 5.2 --- README.md | 19 +- src/fishaudio/__init__.py | 24 +- src/fishaudio/core/_sse.py | 54 +++ src/fishaudio/core/iterators.py | 246 +++++++++++ src/fishaudio/resources/tts.py | 358 +++++++++++++++- src/fishaudio/types/__init__.py | 8 + src/fishaudio/types/tts.py | 95 ++++- .../test_tts_timestamps_integration.py | 44 ++ tests/unit/test_tts_timestamps.py | 396 ++++++++++++++++++ 9 files changed, 1239 insertions(+), 5 deletions(-) create mode 100644 src/fishaudio/core/_sse.py create mode 100644 tests/integration/test_tts_timestamps_integration.py create mode 100644 tests/unit/test_tts_timestamps.py diff --git a/README.md b/README.md index 1ea4a99..5aba62f 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,23 @@ 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 +``` + [Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/text-to-speech) ### Speech-to-Text @@ -260,7 +277,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()` | | `client.voices` | Voice management | `list()`, `get()`, `create()`, `update()`, `delete()` | | `client.account` | Account info | `get_credits()`, `get_package()` | diff --git a/src/fishaudio/__init__.py b/src/fishaudio/__init__.py index ce383a2..d27642c 100644 --- a/src/fishaudio/__init__.py +++ b/src/fishaudio/__init__.py @@ -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, @@ -42,7 +47,16 @@ ValidationError, WebSocketError, ) -from .types import FlushEvent, ReferenceAudio, TextEvent, TTSConfig +from .types import ( + FlushEvent, + ReferenceAudio, + TextEvent, + TTSAlignment, + TTSConfig, + TTSTimestampEvent, + TTSTimestampResult, + TTSTimestampSegment, +) from .utils import play, save, stream # Main exports @@ -57,6 +71,8 @@ # Audio streams "AudioStream", "AsyncAudioStream", + "TTSTimestampStream", + "AsyncTTSTimestampStream", # Configuration "TTSConfig", "WebSocketOptions", @@ -64,6 +80,10 @@ "FlushEvent", "ReferenceAudio", "TextEvent", + "TTSAlignment", + "TTSTimestampEvent", + "TTSTimestampResult", + "TTSTimestampSegment", # Exceptions "APIError", "AuthenticationError", diff --git a/src/fishaudio/core/_sse.py b/src/fishaudio/core/_sse.py new file mode 100644 index 0000000..4b9b725 --- /dev/null +++ b/src/fishaudio/core/_sse.py @@ -0,0 +1,54 @@ +"""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 are split on LF or CRLF only, so + payloads that contain other Unicode line separators stay intact. An event + left unterminated when the stream ends is dropped, as the SSE + specification requires. + """ + + def __init__(self) -> None: + self._buffer = b"" + self._event = "" + self._data: list[str] = [] + + def feed(self, chunk: bytes) -> list[ServerSentEvent]: + """Add bytes from the stream and return the events they complete.""" + self._buffer += chunk + *lines, self._buffer = self._buffer.split(b"\n") + + events = [] + for raw in lines: + line = raw[:-1] if raw.endswith(b"\r") else raw + 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 diff --git a/src/fishaudio/core/iterators.py b/src/fishaudio/core/iterators.py index 4761848..da501c6 100644 --- a/src/fishaudio/core/iterators.py +++ b/src/fishaudio/core/iterators.py @@ -3,6 +3,13 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from typing import Optional +from fishaudio.types.tts import ( + TTSAlignment, + TTSTimestampEvent, + TTSTimestampResult, + TTSTimestampSegment, +) + class AudioStream: """Wrapper for sync audio byte streams with collection utilities. @@ -196,3 +203,242 @@ async def collect(self) -> bytes: return b"".join(chunks) finally: await self.aclose() + + +class _Timeline: + """Keeps the newest timing snapshot of every text chunk.""" + + def __init__(self) -> None: + self._chunks: dict[int, tuple[float, TTSAlignment]] = {} + + def add(self, event: TTSTimestampEvent) -> None: + if event.alignment is not None: + self._chunks[event.chunk_seq] = ( + event.chunk_audio_offset_sec, + event.alignment, + ) + + @property + def segments(self) -> list[TTSTimestampSegment]: + return [ + TTSTimestampSegment( + text=segment.text, + start=segment.start + offset, + end=segment.end + offset, + ) + for offset, alignment in (self._chunks[k] for k in sorted(self._chunks)) + for segment in alignment.segments + ] + + @property + def duration(self) -> float: + return max( + ( + offset + alignment.audio_duration + for offset, alignment in self._chunks.values() + ), + default=0.0, + ) + + +class TTSTimestampStream: + """Sync stream of text-to-speech audio with timestamps. + + Iterating yields `TTSTimestampEvent` objects as the server produces them. + While you iterate, `segments` holds the timings received so far, measured + from the start of the complete audio. `collect()` reads the rest of the + stream and returns the complete audio with its final timings. + + Examples: + ```python + from fishaudio import FishAudio + + client = FishAudio(api_key="...") + + # Play audio as it arrives and keep the timings up to date + with client.tts.stream_with_timestamps(text="Hello world") as stream: + for event in stream: + player.write(event.audio) + show_captions(stream.segments) + + # Or collect everything at once + result = client.tts.stream_with_timestamps(text="Hello world").collect() + ``` + """ + + def __init__( + self, + iterator: Iterator[TTSTimestampEvent], + *, + on_close: Optional[Callable[[], None]] = None, + ): + """Initialize the stream. + + Args: + iterator: The underlying iterator of events + on_close: Called by close() to release the underlying resource, + for example the open HTTP response + """ + self._iter = iterator + self._on_close = on_close + self._closed = False + self._timeline = _Timeline() + + def __iter__(self) -> "TTSTimestampStream": + return self + + def __next__(self) -> TTSTimestampEvent: + event = next(self._iter) + self._timeline.add(event) + return event + + @property + def segments(self) -> list[TTSTimestampSegment]: + """Timings received so far, in speaking order. + + Times are in seconds from the start of the complete audio. Entries near + the end can still be corrected by later events, so read this again + after each event instead of appending to an earlier copy. + """ + return self._timeline.segments + + def close(self) -> None: + """Stop the stream and release the underlying connection. + + Safe to call more than once, and before iteration has started. + """ + if self._closed: + return + self._closed = True + try: + close_iter = getattr(self._iter, "close", None) + if close_iter is not None: + close_iter() + finally: + if self._on_close is not None: + self._on_close() + + def __enter__(self) -> "TTSTimestampStream": + return self + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + self.close() + + def collect(self) -> TTSTimestampResult: + """Read the rest of the stream and return the audio with its timings. + + Returns: + TTSTimestampResult with the complete audio and final timings + """ + try: + audio = b"".join(event.audio for event in self) + return TTSTimestampResult( + audio=audio, + segments=self._timeline.segments, + duration=self._timeline.duration, + ) + finally: + self.close() + + +class AsyncTTSTimestampStream: + """Async stream of text-to-speech audio with timestamps. + + Iterating yields `TTSTimestampEvent` objects as the server produces them. + While you iterate, `segments` holds the timings received so far, measured + from the start of the complete audio. `collect()` reads the rest of the + stream and returns the complete audio with its final timings. + + Examples: + ```python + from fishaudio import AsyncFishAudio + + client = AsyncFishAudio(api_key="...") + + # Play audio as it arrives and keep the timings up to date + async with await client.tts.stream_with_timestamps(text="Hello world") as stream: + async for event in stream: + await player.write(event.audio) + show_captions(stream.segments) + + # Or collect everything at once + stream = await client.tts.stream_with_timestamps(text="Hello world") + result = await stream.collect() + ``` + """ + + def __init__( + self, + async_iterator: AsyncIterator[TTSTimestampEvent], + *, + on_close: Optional[Callable[[], Awaitable[None]]] = None, + ): + """Initialize the stream. + + Args: + async_iterator: The underlying async iterator of events + on_close: Awaited by aclose() to release the underlying resource, + for example the open HTTP response + """ + self._iter = async_iterator + self._on_close = on_close + self._closed = False + self._timeline = _Timeline() + + def __aiter__(self) -> "AsyncTTSTimestampStream": + return self + + async def __anext__(self) -> TTSTimestampEvent: + event = await self._iter.__anext__() + self._timeline.add(event) + return event + + @property + def segments(self) -> list[TTSTimestampSegment]: + """Timings received so far, in speaking order. + + Times are in seconds from the start of the complete audio. Entries near + the end can still be corrected by later events, so read this again + after each event instead of appending to an earlier copy. + """ + return self._timeline.segments + + async def aclose(self) -> None: + """Stop the stream and release the underlying connection. + + Safe to call more than once, and before iteration has started. + """ + if self._closed: + return + self._closed = True + try: + close_iter = getattr(self._iter, "aclose", None) + if close_iter is not None: + await close_iter() + finally: + if self._on_close is not None: + await self._on_close() + + async def __aenter__(self) -> "AsyncTTSTimestampStream": + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: + await self.aclose() + + async def collect(self) -> TTSTimestampResult: + """Read the rest of the stream and return the audio with its timings. + + Returns: + TTSTimestampResult with the complete audio and final timings + """ + try: + chunks = [] + async for event in self: + chunks.append(event.audio) + return TTSTimestampResult( + audio=b"".join(chunks), + segments=self._timeline.segments, + duration=self._timeline.duration, + ) + finally: + await self.aclose() diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 8326c79..965b7e6 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -1,6 +1,9 @@ """TTS (Text-to-Speech) namespace client.""" import asyncio +import base64 +import binascii +import json from collections.abc import AsyncIterable, Iterable, Iterator from concurrent.futures import ThreadPoolExecutor from typing import Optional, Union @@ -14,8 +17,15 @@ RequestOptions, WebSocketOptions, ) +from fishaudio.core._sse import ServerSentEvent, SSEDecoder from fishaudio.core._ws_utils import drain_reader -from fishaudio.core.iterators import AsyncAudioStream, AudioStream +from fishaudio.core.iterators import ( + AsyncAudioStream, + AsyncTTSTimestampStream, + AudioStream, + TTSTimestampStream, +) +from fishaudio.exceptions import FishAudioError from fishaudio.types import ( AudioFormat, CloseEvent, @@ -28,6 +38,8 @@ TextEvent, TTSConfig, TTSRequest, + TTSTimestampEvent, + TTSTimestampResult, ) from fishaudio.types.shared import warn_if_deprecated_model @@ -67,6 +79,54 @@ def _normalize_to_event( return TextEvent(text=item) +_TIMESTAMP_PATH = "/v1/tts/stream/with-timestamp" +_TIMESTAMP_HEADERS = { + "Content-Type": "application/msgpack", + "Accept": "text/event-stream", +} + + +def _build_tts_payload( + text: str, + config: TTSConfig, + *, + reference_id: Optional[str], + references: Optional[list[ReferenceAudio]], + format: Optional[AudioFormat], + latency: Optional[LatencyMode], + speed: Optional[float], +) -> bytes: + """Build the MessagePack request body; direct parameters override config.""" + request = _config_to_tts_request(config, text) + if reference_id is not None: + request.reference_id = reference_id + if references is not None: + request.references = references + if format is not None: + request.format = format + if latency is not None: + request.latency = latency + if speed is not None: + request.prosody = Prosody.from_speed_override(speed, base=config.prosody) + return ormsgpack.packb(request.model_dump(exclude_none=True)) + + +def _parse_timestamp_event(sse: ServerSentEvent) -> Optional[TTSTimestampEvent]: + """Turn one SSE event into a TTSTimestampEvent; None for events to skip.""" + if sse.event == "error": + raise FishAudioError(f"Text-to-speech stream failed: {sse.data}") + if sse.event != "message": + return None + try: + payload = json.loads(sse.data) + payload["audio"] = base64.b64decode(payload.pop("audio_base64"), validate=True) + return TTSTimestampEvent.model_validate(payload) + except (ValueError, KeyError, TypeError, binascii.Error) as exc: + raise FishAudioError( + f"Unexpected event in text-to-speech stream: {sse.data[:200]}" + ) from exc + + class TTSClient: """Synchronous TTS operations.""" @@ -224,6 +284,153 @@ def convert( request_options=request_options, ).collect() + def stream_with_timestamps( + self, + *, + text: str, + reference_id: Optional[str] = None, + references: Optional[list[ReferenceAudio]] = None, + format: Optional[AudioFormat] = None, + latency: Optional[LatencyMode] = None, + speed: Optional[float] = None, + config: TTSConfig = TTSConfig(), + model: Union[Model, str] = "s2.1-pro", + request_options: Optional[RequestOptions] = None, + ) -> TTSTimestampStream: + """ + Stream text-to-speech audio together with word-level timestamps. + + Each event carries the next audio bytes and the newest timing snapshot. + The returned stream keeps the timings up to date in `stream.segments`. + + Args: + text: Text to synthesize + reference_id: Voice reference ID (overrides config.reference_id if provided) + references: Reference audio samples (overrides config.references if provided) + format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided). + "opus" is the best fit for playing audio while it streams; "wav" and "pcm" + are uncompressed, which keeps sample positions exact. + latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) + speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + config: TTS configuration (audio settings, voice, model parameters) + model: TTS model to use + request_options: Request-level overrides + + Returns: + TTSTimestampStream that yields TTSTimestampEvent objects + + Example: + ```python + from fishaudio import FishAudio + + client = FishAudio(api_key="...") + + with client.tts.stream_with_timestamps(text="Hello world") as stream: + for event in stream: + player.write(event.audio) + show_captions(stream.segments) # timings received so far + + # Or collect the audio and final timings at once + result = client.tts.stream_with_timestamps(text="Hello world").collect() + ``` + """ + warn_if_deprecated_model(model) + + content = _build_tts_payload( + text, + config, + reference_id=reference_id, + references=references, + format=format, + latency=latency, + speed=speed, + ) + + # Return once headers arrive; events are read lazily as they are produced. + response = self._client.request( + "POST", + _TIMESTAMP_PATH, + headers={**_TIMESTAMP_HEADERS, "model": model}, + content=content, + request_options=request_options, + stream=True, + ) + + def _events(): + decoder = SSEDecoder() + try: + for chunk in response.iter_bytes(): + for sse in decoder.feed(chunk): + event = _parse_timestamp_event(sse) + if event is not None: + yield event + finally: + response.close() + + return TTSTimestampStream(_events(), on_close=response.close) + + def convert_with_timestamps( + self, + *, + text: str, + reference_id: Optional[str] = None, + references: Optional[list[ReferenceAudio]] = None, + format: Optional[AudioFormat] = None, + latency: Optional[LatencyMode] = None, + speed: Optional[float] = None, + config: TTSConfig = TTSConfig(), + model: Union[Model, str] = "s2.1-pro", + request_options: Optional[RequestOptions] = None, + ) -> TTSTimestampResult: + """ + Convert text to speech and return the audio with word-level timestamps. + + This is a convenience method that reads the whole stream. To use audio + and timings while they arrive, use stream_with_timestamps() instead. + + Args: + text: Text to synthesize + reference_id: Voice reference ID (overrides config.reference_id if provided) + references: Reference audio samples (overrides config.references if provided) + format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided). + "opus" is the best fit for playing audio while it streams; "wav" and "pcm" + are uncompressed, which keeps sample positions exact. + latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) + speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + config: TTS configuration (audio settings, voice, model parameters) + model: TTS model to use + request_options: Request-level overrides + + Returns: + TTSTimestampResult with the complete audio, the timing of each word + in seconds from the start of the audio, and the audio duration + + Example: + ```python + from fishaudio import FishAudio + from fishaudio.utils import save + + client = FishAudio(api_key="...") + + result = client.tts.convert_with_timestamps(text="Hello world") + save(result.audio, "output.mp3") + + for segment in result.segments: + print(f"{segment.start:.2f}-{segment.end:.2f} {segment.text}") + ``` + """ + return self.stream_with_timestamps( + text=text, + reference_id=reference_id, + references=references, + format=format, + latency=latency, + speed=speed, + config=config, + model=model, + request_options=request_options, + ).collect() + def stream_websocket( self, text_stream: Iterable[Union[str, TextEvent, FlushEvent]], @@ -540,6 +747,155 @@ async def convert( ) return await stream.collect() + async def stream_with_timestamps( + self, + *, + text: str, + reference_id: Optional[str] = None, + references: Optional[list[ReferenceAudio]] = None, + format: Optional[AudioFormat] = None, + latency: Optional[LatencyMode] = None, + speed: Optional[float] = None, + config: TTSConfig = TTSConfig(), + model: Union[Model, str] = "s2.1-pro", + request_options: Optional[RequestOptions] = None, + ) -> AsyncTTSTimestampStream: + """ + Stream text-to-speech audio together with word-level timestamps (async). + + Each event carries the next audio bytes and the newest timing snapshot. + The returned stream keeps the timings up to date in `stream.segments`. + + Args: + text: Text to synthesize + reference_id: Voice reference ID (overrides config.reference_id if provided) + references: Reference audio samples (overrides config.references if provided) + format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided). + "opus" is the best fit for playing audio while it streams; "wav" and "pcm" + are uncompressed, which keeps sample positions exact. + latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) + speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + config: TTS configuration (audio settings, voice, model parameters) + model: TTS model to use + request_options: Request-level overrides + + Returns: + AsyncTTSTimestampStream that yields TTSTimestampEvent objects + + Example: + ```python + from fishaudio import AsyncFishAudio + + client = AsyncFishAudio(api_key="...") + + async with await client.tts.stream_with_timestamps(text="Hello world") as stream: + async for event in stream: + await player.write(event.audio) + show_captions(stream.segments) # timings received so far + + # Or collect the audio and final timings at once + stream = await client.tts.stream_with_timestamps(text="Hello world") + result = await stream.collect() + ``` + """ + warn_if_deprecated_model(model) + + content = _build_tts_payload( + text, + config, + reference_id=reference_id, + references=references, + format=format, + latency=latency, + speed=speed, + ) + + # Return once headers arrive; events are read lazily as they are produced. + response = await self._client.request( + "POST", + _TIMESTAMP_PATH, + headers={**_TIMESTAMP_HEADERS, "model": model}, + content=content, + request_options=request_options, + stream=True, + ) + + async def _events(): + decoder = SSEDecoder() + try: + async for chunk in response.aiter_bytes(): + for sse in decoder.feed(chunk): + event = _parse_timestamp_event(sse) + if event is not None: + yield event + finally: + await response.aclose() + + return AsyncTTSTimestampStream(_events(), on_close=response.aclose) + + async def convert_with_timestamps( + self, + *, + text: str, + reference_id: Optional[str] = None, + references: Optional[list[ReferenceAudio]] = None, + format: Optional[AudioFormat] = None, + latency: Optional[LatencyMode] = None, + speed: Optional[float] = None, + config: TTSConfig = TTSConfig(), + model: Union[Model, str] = "s2.1-pro", + request_options: Optional[RequestOptions] = None, + ) -> TTSTimestampResult: + """ + Convert text to speech and return the audio with word-level timestamps (async). + + This is a convenience method that reads the whole stream. To use audio + and timings while they arrive, use stream_with_timestamps() instead. + + Args: + text: Text to synthesize + reference_id: Voice reference ID (overrides config.reference_id if provided) + references: Reference audio samples (overrides config.references if provided) + format: Audio format - "mp3", "wav", "pcm", or "opus" (overrides config.format if provided). + "opus" is the best fit for playing audio while it streams; "wav" and "pcm" + are uncompressed, which keeps sample positions exact. + latency: Latency mode - "normal" or "balanced" (overrides config.latency if provided) + speed: Speech speed multiplier, e.g. 1.5 for 1.5x speed (overrides config.prosody.speed if provided) + config: TTS configuration (audio settings, voice, model parameters) + model: TTS model to use + request_options: Request-level overrides + + Returns: + TTSTimestampResult with the complete audio, the timing of each word + in seconds from the start of the audio, and the audio duration + + Example: + ```python + from fishaudio import AsyncFishAudio + from fishaudio.utils import save + + client = AsyncFishAudio(api_key="...") + + result = await client.tts.convert_with_timestamps(text="Hello world") + save(result.audio, "output.mp3") + + for segment in result.segments: + print(f"{segment.start:.2f}-{segment.end:.2f} {segment.text}") + ``` + """ + stream = await self.stream_with_timestamps( + text=text, + reference_id=reference_id, + references=references, + format=format, + latency=latency, + speed=speed, + config=config, + model=model, + request_options=request_options, + ) + return await stream.collect() + async def stream_websocket( self, text_stream: AsyncIterable[Union[str, TextEvent, FlushEvent]], diff --git a/src/fishaudio/types/__init__.py b/src/fishaudio/types/__init__.py index 584bc38..6731d32 100644 --- a/src/fishaudio/types/__init__.py +++ b/src/fishaudio/types/__init__.py @@ -18,8 +18,12 @@ ReferenceAudio, StartEvent, TextEvent, + TTSAlignment, TTSConfig, TTSRequest, + TTSTimestampEvent, + TTSTimestampResult, + TTSTimestampSegment, ) from .voices import Author, Sample, Voice @@ -46,8 +50,12 @@ "ReferenceAudio", "StartEvent", "TextEvent", + "TTSAlignment", "TTSConfig", "TTSRequest", + "TTSTimestampEvent", + "TTSTimestampResult", + "TTSTimestampSegment", # Voice types "Author", "Sample", diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index 8799cbd..8ceb331 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -2,7 +2,7 @@ from typing import Annotated, Literal, Optional -from pydantic import BaseModel, Field, field_serializer +from pydantic import BaseModel, ConfigDict, Field, field_serializer from .shared import AudioFormat, LatencyMode @@ -208,3 +208,96 @@ class CloseEvent(BaseModel): """ event: Literal["stop"] = "stop" + + +# Text-to-speech with timestamps +class TTSTimestampSegment(BaseModel): + """Timing of one piece of text (usually a word) in generated speech. + + Attributes: + text: The text covered by this entry. Punctuation is not included, and + languages written without spaces are split per character. + start: Start time in seconds + end: End time in seconds + """ + + model_config = ConfigDict(extra="allow") + + text: str + start: float + end: float + + +class TTSAlignment(BaseModel): + """Timing snapshot for one text chunk. + + Attributes: + segments: Timing entries produced so far, with times measured from the + start of the chunk's audio + audio_duration: Seconds of the chunk's audio rendered so far + """ + + model_config = ConfigDict(extra="allow") + + segments: list[TTSTimestampSegment] + audio_duration: float + + +class TTSTimestampEvent(BaseModel): + """One event from a text-to-speech stream with timestamps. + + Audio and timing travel together but are not aligned to each other: `audio` + is the next piece of the audio file, while `alignment` is the newest timing + snapshot for the text chunk `chunk_seq`. Each snapshot replaces the earlier + one for the same chunk. The stream objects do this bookkeeping for you and + expose the result as `segments`. + + Attributes: + audio: Next audio bytes. Join them in arrival order to get the complete + audio. May be empty on a closing event that only corrects timings. + content: Text of the chunk that `alignment` describes. Long input is + split into several chunks. + alignment: Newest timing snapshot for chunk `chunk_seq`, or None when + there is nothing new yet + chunk_seq: Index of the text chunk that `content` and `alignment` describe + chunk_audio_offset_sec: Where that chunk starts in the complete audio, + in seconds + """ + + model_config = ConfigDict(extra="allow") + + audio: bytes + content: str = "" + alignment: Optional[TTSAlignment] = None + chunk_seq: int = 0 + chunk_audio_offset_sec: float = 0.0 + + @property + def segments(self) -> list[TTSTimestampSegment]: + """This event's snapshot with times measured from the start of the complete audio.""" + if self.alignment is None: + return [] + offset = self.chunk_audio_offset_sec + return [ + TTSTimestampSegment( + text=segment.text, + start=segment.start + offset, + end=segment.end + offset, + ) + for segment in self.alignment.segments + ] + + +class TTSTimestampResult(BaseModel): + """Complete audio together with the timing of its text. + + Attributes: + audio: Complete audio as bytes + segments: Timing entries (usually words) in speaking order, with times + in seconds from the start of `audio` + duration: Audio length in seconds as reported by the API + """ + + audio: bytes + segments: list[TTSTimestampSegment] + duration: float diff --git a/tests/integration/test_tts_timestamps_integration.py b/tests/integration/test_tts_timestamps_integration.py new file mode 100644 index 0000000..e4de78c --- /dev/null +++ b/tests/integration/test_tts_timestamps_integration.py @@ -0,0 +1,44 @@ +"""Integration tests for TTS with timestamps.""" + +import io + +import soundfile as sf + +TEXT = "Hello! Welcome to Fish Audio." +WORDS = ["Hello", "Welcome", "to", "Fish", "Audio"] + + +def _check(result): + """Timings cover the spoken words, in order, inside the decoded audio.""" + info = sf.info(io.BytesIO(result.audio)) + assert abs(info.duration - result.duration) < 0.1 + assert [s.text for s in result.segments] == WORDS + starts = [s.start for s in result.segments] + assert starts == sorted(starts) + assert all(0 <= s.start <= s.end <= info.duration + 0.1 for s in result.segments) + + +class TestTTSTimestampsIntegration: + """Test TTS with timestamps against the real API.""" + + def test_convert_with_timestamps(self, client, save_audio): + result = client.tts.convert_with_timestamps(text=TEXT, format="wav") + save_audio(result.audio, "test_timestamps.wav") + _check(result) + + def test_stream_with_timestamps(self, client): + with client.tts.stream_with_timestamps(text=TEXT, format="wav") as stream: + counts = [] + for _ in stream: + counts.append(len(stream.segments)) + assert counts == sorted(counts) # timings only grow as audio arrives + assert [s.text for s in stream.segments] == WORDS + + +class TestAsyncTTSTimestampsIntegration: + """Test async TTS with timestamps against the real API.""" + + async def test_convert_with_timestamps(self, async_client, save_audio): + result = await async_client.tts.convert_with_timestamps(text=TEXT, format="wav") + save_audio(result.audio, "test_timestamps_async.wav") + _check(result) diff --git a/tests/unit/test_tts_timestamps.py b/tests/unit/test_tts_timestamps.py new file mode 100644 index 0000000..6135bd4 --- /dev/null +++ b/tests/unit/test_tts_timestamps.py @@ -0,0 +1,396 @@ +"""Tests for TTS with timestamps over real httpx transports. + +The responses replay the Server-Sent Events framing recorded from the live +`POST /v1/tts/stream/with-timestamp` endpoint: `event: message` lines, one JSON +payload per event, snapshots that grow per chunk, and a closing event with +empty audio that only corrects timings. +""" + +import base64 +import json + +import httpx +import ormsgpack +import pytest + +from fishaudio import ( + AsyncTTSTimestampStream, + TTSConfig, + TTSTimestampEvent, + TTSTimestampResult, + TTSTimestampStream, +) +from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions +from fishaudio.core._sse import ServerSentEvent, SSEDecoder +from fishaudio.exceptions import APIError, FishAudioError +from fishaudio.resources.tts import AsyncTTSClient, TTSClient + +BASE_URL = "https://api.test.fish.audio" + + +def _seg(text, start, end): + return {"text": text, "start": start, "end": end} + + +def _payload(audio, *, seq=0, offset=0.0, content="Hello world.", alignment=None): + return { + "audio_base64": base64.b64encode(audio).decode(), + "content": content, + "alignment": alignment, + "chunk_seq": seq, + "chunk_audio_offset_sec": offset, + } + + +def _sse(payload): + return f"event: message\r\ndata: {json.dumps(payload)}\r\n\r\n".encode() + + +# Two text chunks. Chunk 0 starts without timings, grows, and its last word is +# corrected by a later snapshot; chunk 1 ends with an audio-less correction. +PAYLOADS = [ + _payload(b"aa"), + _payload( + b"bb", + alignment={"segments": [_seg("Hello", 0.0, 0.5)], "audio_duration": 0.6}, + ), + _payload( + b"cc", + alignment={ + "segments": [_seg("Hello", 0.0, 0.4), _seg("world", 0.5, 1.0)], + "audio_duration": 1.25, + }, + ), + _payload( + b"dd", + seq=1, + offset=1.25, + content="你好", + alignment={"segments": [_seg("你", 0.0, 0.25)], "audio_duration": 0.5}, + ), + _payload( + b"", + seq=1, + offset=1.25, + content="你好", + alignment={ + "segments": [_seg("你", 0.0, 0.25), _seg("好", 0.25, 0.5)], + "audio_duration": 0.75, + }, + ), +] +BODY = [_sse(p) for p in PAYLOADS] +FINAL = [("Hello", 0.0, 0.4), ("world", 0.5, 1.0), ("你", 1.25, 1.5), ("好", 1.5, 1.75)] + + +def _timings(segments): + return [(s.text, s.start, s.end) for s in segments] + + +class _SyncBody(httpx.SyncByteStream): + def __init__(self, chunks): + self.chunks = chunks + self.produced = 0 + self.closed = False + + def __iter__(self): + for chunk in self.chunks: + self.produced += 1 + yield chunk + + def close(self): + self.closed = True + + +class _AsyncBody(httpx.AsyncByteStream): + def __init__(self, chunks): + self.chunks = chunks + self.produced = 0 + self.closed = False + + async def __aiter__(self): + for chunk in self.chunks: + self.produced += 1 + yield chunk + + async def aclose(self): + self.closed = True + + +def _sync_tts(handler): + http = httpx.Client(base_url=BASE_URL, transport=httpx.MockTransport(handler)) + return TTSClient(ClientWrapper(api_key="test", httpx_client=http)) + + +def _async_tts(handler): + http = httpx.AsyncClient(base_url=BASE_URL, transport=httpx.MockTransport(handler)) + return AsyncTTSClient(AsyncClientWrapper(api_key="test", httpx_client=http)) + + +def _ok(body): + return lambda request: httpx.Response( + 200, headers={"content-type": "text/event-stream"}, stream=body + ) + + +class TestSSEDecoder: + def test_event_split_across_arbitrary_byte_boundaries(self): + raw = b"".join(BODY) + for size in (1, 7, 64): + decoder = SSEDecoder() + events = [] + for i in range(0, len(raw), size): + events += decoder.feed(raw[i : i + size]) + assert [json.loads(e.data) for e in events] == PAYLOADS + assert {e.event for e in events} == {"message"} + + def test_framing_rules(self): + decoder = SSEDecoder() + events = decoder.feed( + b": keep-alive\n\n" # comment only: no event + b"data: plain\n\n" # LF endings, default event name + b"event: error\ndata:no-space\nid: 7\n\n" # named, no space, unknown field + b"data: line1\ndata: line2\n\n" # multi-line data + b"data: unterminated\n" # dropped: stream ends before the blank line + ) + assert events == [ + ServerSentEvent("message", "plain"), + ServerSentEvent("error", "no-space"), + ServerSentEvent("message", "line1\nline2"), + ] + + def test_unicode_line_separators_stay_inside_data(self): + text = "a
b\u0085c" + events = SSEDecoder().feed(f"data: {text}\n\n".encode()) + assert events == [ServerSentEvent("message", text)] + + +class TestSyncTimestamps: + def test_request_matches_plain_tts_request(self): + seen = {} + + def handler(request): + seen["request"] = request + return httpx.Response(200, stream=_SyncBody(BODY)) + + _sync_tts(handler).stream_with_timestamps( + text="Hello world.", + reference_id="voice-1", + format="opus", + latency="normal", + speed=1.5, + config=TTSConfig(opus_bitrate=24), + model="s2-pro", + ).close() + + request = seen["request"] + assert request.method == "POST" + assert request.url.path == "/v1/tts/stream/with-timestamp" + assert request.headers["content-type"] == "application/msgpack" + assert request.headers["accept"] == "text/event-stream" + assert request.headers["model"] == "s2-pro" + assert request.headers["authorization"] == "Bearer test" + body = ormsgpack.unpackb(request.content) + assert body["text"] == "Hello world." + assert body["reference_id"] == "voice-1" + assert body["format"] == "opus" + assert body["latency"] == "normal" + assert body["prosody"]["speed"] == 1.5 + assert body["opus_bitrate"] == 24000 + + def test_events_are_typed_and_arrive_incrementally(self): + body = _SyncBody(BODY) + stream = _sync_tts(_ok(body)).stream_with_timestamps(text="Hello world.") + assert isinstance(stream, TTSTimestampStream) + assert body.produced == 0 # nothing read until the caller iterates + + first = next(stream) + assert isinstance(first, TTSTimestampEvent) + assert body.produced == 1 + assert (first.audio, first.alignment, first.segments) == (b"aa", None, []) + assert stream.segments == [] + + second = next(stream) + assert second.content == "Hello world." + assert second.alignment.audio_duration == 0.6 + assert _timings(stream.segments) == [("Hello", 0.0, 0.5)] + + rest = list(stream) + assert [e.audio for e in rest] == [b"cc", b"dd", b""] + assert rest[1].chunk_seq == 1 + assert rest[1].chunk_audio_offset_sec == 1.25 + # event.segments is that event's own snapshot on the full-audio timeline + assert _timings(rest[1].segments) == [("你", 1.25, 1.5)] + # stream.segments replaces snapshots per chunk and joins chunks in order + assert _timings(stream.segments) == FINAL + assert body.closed + + def test_collect_returns_audio_final_timings_and_duration(self): + body = _SyncBody(BODY) + result = _sync_tts(_ok(body)).stream_with_timestamps(text="Hi").collect() + assert isinstance(result, TTSTimestampResult) + assert result.audio == b"aabbccdd" + assert _timings(result.segments) == FINAL + assert result.duration == 2.0 + assert body.closed + + def test_convert_with_timestamps(self): + tts = _sync_tts(_ok(_SyncBody(BODY))) + result = tts.convert_with_timestamps(text="Hello world.") + assert result.audio == b"aabbccdd" + assert _timings(result.segments) == FINAL + + def test_collect_after_partial_iteration_keeps_earlier_timings(self): + stream = _sync_tts(_ok(_SyncBody(BODY))).stream_with_timestamps(text="Hi") + consumed = [next(stream).audio for _ in range(3)] + result = stream.collect() + assert b"".join(consumed) + result.audio == b"aabbccdd" + assert _timings(result.segments) == FINAL + + def test_with_block_closes_after_early_break(self): + body = _SyncBody(BODY) + with _sync_tts(_ok(body)).stream_with_timestamps(text="Hi") as stream: + for _ in stream: + break + assert not body.closed + assert body.produced == 1 + assert body.closed + stream.close() # idempotent + assert list(stream) == [] + + def test_close_before_iteration_releases_response(self): + body = _SyncBody(BODY) + stream = _sync_tts(_ok(body)).stream_with_timestamps(text="Hi") + stream.close() + assert body.produced == 0 + assert body.closed + + def test_unknown_fields_and_event_names_are_tolerated(self): + payload = _payload(b"aa", alignment={"segments": [], "audio_duration": 0.0}) + payload["new_field"] = 1 + body = [b"event: ping\ndata: {}\n\n", b": keep-alive\n\n", _sse(payload)] + events = list(_sync_tts(_ok(_SyncBody(body))).stream_with_timestamps(text="x")) + assert [e.audio for e in events] == [b"aa"] + assert events[0].model_extra == {"new_field": 1} + + def test_http_error_raised_at_call_time(self): + tts = _sync_tts( + lambda request: httpx.Response( + 400, json={"message": "Reference not found", "status": 400} + ) + ) + with pytest.raises(APIError) as exc: + tts.stream_with_timestamps(text="Hello", reference_id="missing") + assert exc.value.status == 400 + assert "Reference not found" in str(exc.value) + + @pytest.mark.parametrize( + "frame", + [ + b"event: error\ndata: backend unavailable\n\n", + b'data: {"message": "backend unavailable"}\n\n', + b"data: not json\n\n", + b'data: {"audio_base64": "!", "chunk_seq": 0}\n\n', + ], + ) + def test_unusable_event_raises_and_closes(self, frame): + body = _SyncBody([BODY[0], frame, BODY[1]]) + stream = _sync_tts(_ok(body)).stream_with_timestamps(text="Hello") + assert next(stream).audio == b"aa" + with pytest.raises(FishAudioError): + next(stream) + assert body.closed + + def test_request_options_timeout_applies(self): + seen = {} + + def handler(request): + seen["timeout"] = request.extensions["timeout"] + return httpx.Response(200, stream=_SyncBody(BODY)) + + _sync_tts(handler).convert_with_timestamps( + text="Hello", request_options=RequestOptions(timeout=12.5) + ) + assert seen["timeout"]["read"] == 12.5 + + +class TestAsyncTimestamps: + async def test_request_path_and_headers(self): + seen = {} + + def handler(request): + seen["request"] = request + return httpx.Response(200, stream=_AsyncBody(BODY)) + + stream = await _async_tts(handler).stream_with_timestamps( + text="Hello world.", format="wav", model="s2-pro" + ) + await stream.aclose() + + request = seen["request"] + assert request.url.path == "/v1/tts/stream/with-timestamp" + assert request.headers["content-type"] == "application/msgpack" + assert request.headers["model"] == "s2-pro" + assert ormsgpack.unpackb(request.content)["format"] == "wav" + + async def test_events_are_typed_and_arrive_incrementally(self): + body = _AsyncBody(BODY) + stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi") + assert isinstance(stream, AsyncTTSTimestampStream) + assert body.produced == 0 + + first = await stream.__anext__() + assert body.produced == 1 + assert (first.audio, first.alignment) == (b"aa", None) + + audio = [event.audio async for event in stream] + assert audio == [b"bb", b"cc", b"dd", b""] + assert _timings(stream.segments) == FINAL + assert body.closed + + async def test_collect_and_convert(self): + body = _AsyncBody(BODY) + stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi") + result = await stream.collect() + assert result.audio == b"aabbccdd" + assert _timings(result.segments) == FINAL + assert result.duration == 2.0 + assert body.closed + + tts = _async_tts(_ok(_AsyncBody(BODY))) + converted = await tts.convert_with_timestamps(text="Hi") + assert converted == result + + async def test_async_with_closes_after_early_break(self): + body = _AsyncBody(BODY) + stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi") + async with stream: + async for _ in stream: + break + assert not body.closed + assert body.produced == 1 + assert body.closed + await stream.aclose() # idempotent + + async def test_close_before_iteration_releases_response(self): + body = _AsyncBody(BODY) + stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi") + await stream.aclose() + assert body.produced == 0 + assert body.closed + + async def test_http_error_raised_at_call_time(self): + tts = _async_tts( + lambda request: httpx.Response(402, json={"message": "No credit"}) + ) + with pytest.raises(APIError) as exc: + await tts.stream_with_timestamps(text="Hello") + assert exc.value.status == 402 + + async def test_unusable_event_raises_and_closes(self): + body = _AsyncBody([BODY[0], b"data: not json\n\n"]) + stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hello") + assert (await stream.__anext__()).audio == b"aa" + with pytest.raises(FishAudioError): + await stream.__anext__() + assert body.closed From ca45ec2c5aa1e01b79bf350b92fd5543dbfd5bf9 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:44:42 -0800 Subject: [PATCH 2/3] fix(tts): address review of timestamp streaming - SSE decoder accepts CR, LF and CRLF line endings, including a CRLF pair split across chunks; a CR ends its line without waiting for more bytes. - collect() on a timestamp stream raises RuntimeError once iteration has started instead of returning partial audio with full timings. - A JSON payload that is not an object raises FishAudioError. - The live streaming test checks the decoded audio and no longer requires segment counts to grow between snapshots. Co-Authored-By: Claude Fable 5.2 --- src/fishaudio/core/_sse.py | 25 ++++++--- src/fishaudio/core/iterators.py | 44 +++++++++++++--- src/fishaudio/resources/tts.py | 2 + .../test_tts_timestamps_integration.py | 11 ++-- tests/unit/test_tts_timestamps.py | 52 ++++++++++++++++--- 5 files changed, 109 insertions(+), 25 deletions(-) diff --git a/src/fishaudio/core/_sse.py b/src/fishaudio/core/_sse.py index 4b9b725..6fa1f70 100644 --- a/src/fishaudio/core/_sse.py +++ b/src/fishaudio/core/_sse.py @@ -14,25 +14,34 @@ 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 are split on LF or CRLF only, so - payloads that contain other Unicode line separators stay intact. An event - left unterminated when the stream ends is dropped, as the SSE - specification requires. + 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.""" - self._buffer += chunk - *lines, self._buffer = self._buffer.split(b"\n") + 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 raw in lines: - line = raw[:-1] if raw.endswith(b"\r") else raw + for line in lines: if not line: if self._data: events.append( diff --git a/src/fishaudio/core/iterators.py b/src/fishaudio/core/iterators.py index da501c6..550f24e 100644 --- a/src/fishaudio/core/iterators.py +++ b/src/fishaudio/core/iterators.py @@ -246,8 +246,8 @@ class TTSTimestampStream: Iterating yields `TTSTimestampEvent` objects as the server produces them. While you iterate, `segments` holds the timings received so far, measured - from the start of the complete audio. `collect()` reads the rest of the - stream and returns the complete audio with its final timings. + from the start of the complete audio. Alternatively, call `collect()` + instead of iterating to get the complete audio with its final timings. Examples: ```python @@ -283,11 +283,13 @@ def __init__( self._on_close = on_close self._closed = False self._timeline = _Timeline() + self._started = False def __iter__(self) -> "TTSTimestampStream": return self def __next__(self) -> TTSTimestampEvent: + self._started = True event = next(self._iter) self._timeline.add(event) return event @@ -325,11 +327,25 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> None: self.close() def collect(self) -> TTSTimestampResult: - """Read the rest of the stream and return the audio with its timings. + """Read the whole stream and return the complete audio with its timings. + + Call this instead of iterating, not after it. Events that were already + yielded are not kept, so the complete audio can no longer be returned + once iteration has started; in that case use the audio you received + and read `segments` when the stream ends. Returns: TTSTimestampResult with the complete audio and final timings + + Raises: + RuntimeError: If iteration has already started """ + if self._started: + raise RuntimeError( + "collect() must be called before iterating: events already " + "yielded are not kept, so the complete audio is no longer " + "available. Join event.audio yourself and read stream.segments." + ) try: audio = b"".join(event.audio for event in self) return TTSTimestampResult( @@ -346,8 +362,8 @@ class AsyncTTSTimestampStream: Iterating yields `TTSTimestampEvent` objects as the server produces them. While you iterate, `segments` holds the timings received so far, measured - from the start of the complete audio. `collect()` reads the rest of the - stream and returns the complete audio with its final timings. + from the start of the complete audio. Alternatively, call `collect()` + instead of iterating to get the complete audio with its final timings. Examples: ```python @@ -384,11 +400,13 @@ def __init__( self._on_close = on_close self._closed = False self._timeline = _Timeline() + self._started = False def __aiter__(self) -> "AsyncTTSTimestampStream": return self async def __anext__(self) -> TTSTimestampEvent: + self._started = True event = await self._iter.__anext__() self._timeline.add(event) return event @@ -426,11 +444,25 @@ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: await self.aclose() async def collect(self) -> TTSTimestampResult: - """Read the rest of the stream and return the audio with its timings. + """Read the whole stream and return the complete audio with its timings. + + Call this instead of iterating, not after it. Events that were already + yielded are not kept, so the complete audio can no longer be returned + once iteration has started; in that case use the audio you received + and read `segments` when the stream ends. Returns: TTSTimestampResult with the complete audio and final timings + + Raises: + RuntimeError: If iteration has already started """ + if self._started: + raise RuntimeError( + "collect() must be called before iterating: events already " + "yielded are not kept, so the complete audio is no longer " + "available. Join event.audio yourself and read stream.segments." + ) try: chunks = [] async for event in self: diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 965b7e6..293d617 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -119,6 +119,8 @@ def _parse_timestamp_event(sse: ServerSentEvent) -> Optional[TTSTimestampEvent]: return None try: payload = json.loads(sse.data) + if not isinstance(payload, dict): + raise TypeError("event payload is not a JSON object") payload["audio"] = base64.b64decode(payload.pop("audio_base64"), validate=True) return TTSTimestampEvent.model_validate(payload) except (ValueError, KeyError, TypeError, binascii.Error) as exc: diff --git a/tests/integration/test_tts_timestamps_integration.py b/tests/integration/test_tts_timestamps_integration.py index e4de78c..e4756a9 100644 --- a/tests/integration/test_tts_timestamps_integration.py +++ b/tests/integration/test_tts_timestamps_integration.py @@ -28,11 +28,12 @@ def test_convert_with_timestamps(self, client, save_audio): def test_stream_with_timestamps(self, client): with client.tts.stream_with_timestamps(text=TEXT, format="wav") as stream: - counts = [] - for _ in stream: - counts.append(len(stream.segments)) - assert counts == sorted(counts) # timings only grow as audio arrives - assert [s.text for s in stream.segments] == WORDS + audio = b"".join(event.audio for event in stream) + segments = stream.segments + + info = sf.info(io.BytesIO(audio)) + assert [s.text for s in segments] == WORDS + assert all(0 <= s.start <= s.end <= info.duration + 0.1 for s in segments) class TestAsyncTTSTimestampsIntegration: diff --git a/tests/unit/test_tts_timestamps.py b/tests/unit/test_tts_timestamps.py index 6135bd4..e23b540 100644 --- a/tests/unit/test_tts_timestamps.py +++ b/tests/unit/test_tts_timestamps.py @@ -159,6 +159,26 @@ def test_framing_rules(self): ServerSentEvent("message", "line1\nline2"), ] + @pytest.mark.parametrize("newline", [b"\r", b"\n", b"\r\n"]) + def test_every_line_ending_at_every_chunk_boundary(self, newline): + raw = b"".join(BODY).replace(b"\r\n", newline) + raw += b"event: ping" + newline + b"data: last" + newline + newline + for size in (1, 2, 3, 7, len(raw)): + decoder = SSEDecoder() + events = [] + for i in range(0, len(raw), size): + events += decoder.feed(raw[i : i + size]) + assert [json.loads(e.data) for e in events[:-1]] == PAYLOADS + assert events[-1] == ServerSentEvent("ping", "last") + + def test_cr_terminated_event_is_dispatched_without_waiting_for_more_bytes(self): + decoder = SSEDecoder() + assert decoder.feed(b"data: one\r\r") == [ServerSentEvent("message", "one")] + # A CRLF pair split across chunks must not count as two line endings. + assert decoder.feed(b"data: two\r") == [] + assert decoder.feed(b"\ndata: three\r") == [] + assert decoder.feed(b"\n\r\n") == [ServerSentEvent("message", "two\nthree")] + def test_unicode_line_separators_stay_inside_data(self): text = "a
b\u0085c" events = SSEDecoder().feed(f"data: {text}\n\n".encode()) @@ -240,12 +260,17 @@ def test_convert_with_timestamps(self): assert result.audio == b"aabbccdd" assert _timings(result.segments) == FINAL - def test_collect_after_partial_iteration_keeps_earlier_timings(self): - stream = _sync_tts(_ok(_SyncBody(BODY))).stream_with_timestamps(text="Hi") - consumed = [next(stream).audio for _ in range(3)] - result = stream.collect() - assert b"".join(consumed) + result.audio == b"aabbccdd" - assert _timings(result.segments) == FINAL + def test_collect_after_iteration_started_is_refused(self): + body = _SyncBody(BODY) + stream = _sync_tts(_ok(body)).stream_with_timestamps(text="Hi") + assert next(stream).audio == b"aa" + with pytest.raises(RuntimeError, match="collect"): + stream.collect() + # The stream is left usable: nothing was read or closed by the refusal. + assert body.produced == 1 + assert not body.closed + assert [e.audio for e in stream] == [b"bb", b"cc", b"dd", b""] + assert _timings(stream.segments) == FINAL def test_with_block_closes_after_early_break(self): body = _SyncBody(BODY) @@ -291,6 +316,10 @@ def test_http_error_raised_at_call_time(self): b'data: {"message": "backend unavailable"}\n\n', b"data: not json\n\n", b'data: {"audio_base64": "!", "chunk_seq": 0}\n\n', + b"data: null\n\n", + b'data: "text"\n\n', + b"data: 5\n\n", + b'data: ["audio_base64"]\n\n', ], ) def test_unusable_event_raises_and_closes(self, frame): @@ -361,6 +390,17 @@ async def test_collect_and_convert(self): converted = await tts.convert_with_timestamps(text="Hi") assert converted == result + async def test_collect_after_iteration_started_is_refused(self): + body = _AsyncBody(BODY) + stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi") + assert (await stream.__anext__()).audio == b"aa" + with pytest.raises(RuntimeError, match="collect"): + await stream.collect() + assert body.produced == 1 + assert not body.closed + assert [e.audio async for e in stream] == [b"bb", b"cc", b"dd", b""] + assert _timings(stream.segments) == FINAL + async def test_async_with_closes_after_early_break(self): body = _AsyncBody(BODY) stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi") From 0b555511db8da227826b7294f6b1bd7f6b22e68e Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:38:12 -0800 Subject: [PATCH 3/3] fix(tts): report an unknown duration as None instead of 0.0 The timestamp endpoint sends audio with `alignment: null` on every event when the text has nothing to align, for example "[sigh]" or punctuation only. The API reports audio length only inside alignment snapshots, so `TTSTimestampResult.duration` was 0.0 for non-empty audio. `duration` is now `Optional[float]`. It is None when the last text chunk has no snapshot, which also covers a stream whose earlier chunks have timings but whose last chunk does not; that case returned a length that was too short. `segments` stays an empty list when there are no timings. Chunk offsets come from the server, so a chunk without timings does not shift the chunks after it; a test now pins that. Co-Authored-By: Claude Fable 5.2 --- README.md | 2 + src/fishaudio/core/iterators.py | 38 ++++++--- src/fishaudio/resources/tts.py | 8 +- src/fishaudio/types/tts.py | 18 ++++- .../test_tts_timestamps_integration.py | 1 + tests/unit/test_tts_timestamps.py | 81 +++++++++++++++++++ 6 files changed, 132 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 5aba62f..de2f280 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,8 @@ with client.tts.stream_with_timestamps(text="Long content...", format="opus") as 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 diff --git a/src/fishaudio/core/iterators.py b/src/fishaudio/core/iterators.py index 550f24e..8142259 100644 --- a/src/fishaudio/core/iterators.py +++ b/src/fishaudio/core/iterators.py @@ -210,8 +210,10 @@ class _Timeline: def __init__(self) -> None: self._chunks: dict[int, tuple[float, TTSAlignment]] = {} + self._last_seq = -1 def add(self, event: TTSTimestampEvent) -> None: + self._last_seq = max(self._last_seq, event.chunk_seq) if event.alignment is not None: self._chunks[event.chunk_seq] = ( event.chunk_audio_offset_sec, @@ -231,14 +233,18 @@ def segments(self) -> list[TTSTimestampSegment]: ] @property - def duration(self) -> float: - return max( - ( - offset + alignment.audio_duration - for offset, alignment in self._chunks.values() - ), - default=0.0, - ) + def duration(self) -> Optional[float]: + """End of the last text chunk, or None when the API did not report it. + + The API reports audio length only inside timing snapshots. Without a + snapshot for the last chunk, the end of the audio is unknown: earlier + chunks would give a length that is too short, and no chunk gives none. + """ + last = self._chunks.get(self._last_seq) + if last is None: + return None + offset, alignment = last + return offset + alignment.audio_duration class TTSTimestampStream: @@ -301,6 +307,10 @@ def segments(self) -> list[TTSTimestampSegment]: Times are in seconds from the start of the complete audio. Entries near the end can still be corrected by later events, so read this again after each event instead of appending to an earlier copy. + + Empty until the first timings arrive, and it stays empty when the API + has no timings for the text (for example text without words). The + audio still arrives in full. """ return self._timeline.segments @@ -335,7 +345,9 @@ def collect(self) -> TTSTimestampResult: and read `segments` when the stream ends. Returns: - TTSTimestampResult with the complete audio and final timings + TTSTimestampResult with the complete audio and final timings. When + the API has no timings for the text, `segments` is empty and + `duration` is None; the audio is still complete. Raises: RuntimeError: If iteration has already started @@ -418,6 +430,10 @@ def segments(self) -> list[TTSTimestampSegment]: Times are in seconds from the start of the complete audio. Entries near the end can still be corrected by later events, so read this again after each event instead of appending to an earlier copy. + + Empty until the first timings arrive, and it stays empty when the API + has no timings for the text (for example text without words). The + audio still arrives in full. """ return self._timeline.segments @@ -452,7 +468,9 @@ async def collect(self) -> TTSTimestampResult: and read `segments` when the stream ends. Returns: - TTSTimestampResult with the complete audio and final timings + TTSTimestampResult with the complete audio and final timings. When + the API has no timings for the text, `segments` is empty and + `duration` is None; the audio is still complete. Raises: RuntimeError: If iteration has already started diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 293d617..73d83f2 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -405,7 +405,9 @@ def convert_with_timestamps( Returns: TTSTimestampResult with the complete audio, the timing of each word - in seconds from the start of the audio, and the audio duration + in seconds from the start of the audio, and the audio duration. + When the API has no timings for the text (for example text without + words), `segments` is empty and `duration` is None. Example: ```python @@ -869,7 +871,9 @@ async def convert_with_timestamps( Returns: TTSTimestampResult with the complete audio, the timing of each word - in seconds from the start of the audio, and the audio duration + in seconds from the start of the audio, and the audio duration. + When the API has no timings for the text (for example text without + words), `segments` is empty and `duration` is None. Example: ```python diff --git a/src/fishaudio/types/tts.py b/src/fishaudio/types/tts.py index 8ceb331..b3f1737 100644 --- a/src/fishaudio/types/tts.py +++ b/src/fishaudio/types/tts.py @@ -258,7 +258,7 @@ class TTSTimestampEvent(BaseModel): content: Text of the chunk that `alignment` describes. Long input is split into several chunks. alignment: Newest timing snapshot for chunk `chunk_seq`, or None when - there is nothing new yet + there is none yet or the API cannot time this text chunk_seq: Index of the text chunk that `content` and `alignment` describe chunk_audio_offset_sec: Where that chunk starts in the complete audio, in seconds @@ -291,13 +291,23 @@ def segments(self) -> list[TTSTimestampSegment]: class TTSTimestampResult(BaseModel): """Complete audio together with the timing of its text. + The API cannot always time the text, for example when it contains no words + (only punctuation or a sound tag such as "[sigh]"). The audio is complete + in that case too, but `segments` is empty and `duration` is None. Parts of + a long text can also be missing from `segments` for the same reason. + Attributes: audio: Complete audio as bytes segments: Timing entries (usually words) in speaking order, with times - in seconds from the start of `audio` - duration: Audio length in seconds as reported by the API + in seconds from the start of `audio`. Empty when the API returned + no timings. + duration: Length of `audio` in seconds as reported by the API, or None + when the API did not report it. The API reports it together with + the timings, so it is None when the end of the audio has no + timings. It is never measured from `audio`; decode the audio if you + need its length in that case. """ audio: bytes segments: list[TTSTimestampSegment] - duration: float + duration: Optional[float] = None diff --git a/tests/integration/test_tts_timestamps_integration.py b/tests/integration/test_tts_timestamps_integration.py index e4756a9..d20ffe3 100644 --- a/tests/integration/test_tts_timestamps_integration.py +++ b/tests/integration/test_tts_timestamps_integration.py @@ -11,6 +11,7 @@ def _check(result): """Timings cover the spoken words, in order, inside the decoded audio.""" info = sf.info(io.BytesIO(result.audio)) + assert result.duration is not None assert abs(info.duration - result.duration) < 0.1 assert [s.text for s in result.segments] == WORDS starts = [s.start for s in result.segments] diff --git a/tests/unit/test_tts_timestamps.py b/tests/unit/test_tts_timestamps.py index e23b540..ff3e028 100644 --- a/tests/unit/test_tts_timestamps.py +++ b/tests/unit/test_tts_timestamps.py @@ -83,6 +83,24 @@ def _sse(payload): FINAL = [("Hello", 0.0, 0.4), ("world", 0.5, 1.0), ("你", 1.25, 1.5), ("好", 1.5, 1.75)] +# What the live API sends when the text has nothing to align (for example +# "[sigh]" or punctuation only): audio, and `alignment: null` on every event. +NO_ALIGNMENT_BODY = [ + _sse(_payload(audio, content="[sigh]")) for audio in (b"aa", b"bb", b"cc") +] +_WORLD = {"segments": [_seg("world", 0.0, 0.5)], "audio_duration": 0.75} +# Chunk 0 never gets timings, chunk 1 does. +FIRST_CHUNK_UNALIGNED_BODY = [ + _sse(_payload(b"aa", content="...")), + _sse(_payload(b"bb", seq=1, offset=1.5, content="world", alignment=_WORLD)), +] +# Chunk 0 gets timings, the last chunk never does. +LAST_CHUNK_UNALIGNED_BODY = [ + _sse(_payload(b"aa", content="world", alignment=_WORLD)), + _sse(_payload(b"bb", seq=1, offset=0.75, content="[sigh]")), +] + + def _timings(segments): return [(s.text, s.start, s.end) for s in segments] @@ -260,6 +278,38 @@ def test_convert_with_timestamps(self): assert result.audio == b"aabbccdd" assert _timings(result.segments) == FINAL + def test_audio_without_alignment_has_no_duration(self): + tts = _sync_tts(_ok(_SyncBody(NO_ALIGNMENT_BODY))) + result = tts.stream_with_timestamps(text="[sigh]").collect() + assert result.audio == b"aabbcc" + assert result.segments == [] + assert result.duration is None + + tts = _sync_tts(_ok(_SyncBody(NO_ALIGNMENT_BODY))) + assert tts.convert_with_timestamps(text="[sigh]") == result + + def test_streaming_audio_without_alignment(self): + tts = _sync_tts(_ok(_SyncBody(NO_ALIGNMENT_BODY))) + with tts.stream_with_timestamps(text="[sigh]") as stream: + events = list(stream) + assert stream.segments == [] + assert [e.audio for e in events] == [b"aa", b"bb", b"cc"] + assert all(e.alignment is None and e.segments == [] for e in events) + + def test_chunk_without_alignment_does_not_shift_later_chunks(self): + tts = _sync_tts(_ok(_SyncBody(FIRST_CHUNK_UNALIGNED_BODY))) + result = tts.convert_with_timestamps(text="... world") + assert result.audio == b"aabb" + assert _timings(result.segments) == [("world", 1.5, 2.0)] + assert result.duration == 2.25 + + def test_last_chunk_without_alignment_has_no_duration(self): + tts = _sync_tts(_ok(_SyncBody(LAST_CHUNK_UNALIGNED_BODY))) + result = tts.convert_with_timestamps(text="world [sigh]") + assert result.audio == b"aabb" + assert _timings(result.segments) == [("world", 0.0, 0.5)] + assert result.duration is None + def test_collect_after_iteration_started_is_refused(self): body = _SyncBody(BODY) stream = _sync_tts(_ok(body)).stream_with_timestamps(text="Hi") @@ -390,6 +440,37 @@ async def test_collect_and_convert(self): converted = await tts.convert_with_timestamps(text="Hi") assert converted == result + async def test_audio_without_alignment_has_no_duration(self): + tts = _async_tts(_ok(_AsyncBody(NO_ALIGNMENT_BODY))) + stream = await tts.stream_with_timestamps(text="[sigh]") + result = await stream.collect() + assert result.audio == b"aabbcc" + assert result.segments == [] + assert result.duration is None + + tts = _async_tts(_ok(_AsyncBody(NO_ALIGNMENT_BODY))) + assert await tts.convert_with_timestamps(text="[sigh]") == result + + async def test_streaming_audio_without_alignment(self): + tts = _async_tts(_ok(_AsyncBody(NO_ALIGNMENT_BODY))) + async with await tts.stream_with_timestamps(text="[sigh]") as stream: + events = [event async for event in stream] + assert stream.segments == [] + assert [e.audio for e in events] == [b"aa", b"bb", b"cc"] + assert all(e.alignment is None and e.segments == [] for e in events) + + async def test_chunk_without_alignment_does_not_shift_later_chunks(self): + tts = _async_tts(_ok(_AsyncBody(FIRST_CHUNK_UNALIGNED_BODY))) + result = await tts.convert_with_timestamps(text="... world") + assert _timings(result.segments) == [("world", 1.5, 2.0)] + assert result.duration == 2.25 + + async def test_last_chunk_without_alignment_has_no_duration(self): + tts = _async_tts(_ok(_AsyncBody(LAST_CHUNK_UNALIGNED_BODY))) + result = await tts.convert_with_timestamps(text="world [sigh]") + assert _timings(result.segments) == [("world", 0.0, 0.5)] + assert result.duration is None + async def test_collect_after_iteration_started_is_refused(self): body = _AsyncBody(BODY) stream = await _async_tts(_ok(body)).stream_with_timestamps(text="Hi")