diff --git a/README.md b/README.md index fbd31e8..f1ca832 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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()` | diff --git a/src/fishaudio/__init__.py b/src/fishaudio/__init__.py index f067bb0..c771486 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, @@ -54,7 +59,11 @@ FlushEvent, ReferenceAudio, TextEvent, + TTSAlignment, TTSConfig, + TTSTimestampEvent, + TTSTimestampResult, + TTSTimestampSegment, ) from .utils import play, save, stream @@ -70,6 +79,8 @@ # Audio streams "AudioStream", "AsyncAudioStream", + "TTSTimestampStream", + "AsyncTTSTimestampStream", # Realtime speech-to-text sessions "ASRRealtimeStream", "AsyncASRRealtimeStream", @@ -86,6 +97,10 @@ "FlushEvent", "ReferenceAudio", "TextEvent", + "TTSAlignment", + "TTSTimestampEvent", + "TTSTimestampResult", + "TTSTimestampSegment", # Exceptions "APIError", "ASRRealtimeError", diff --git a/src/fishaudio/core/_sse.py b/src/fishaudio/core/_sse.py new file mode 100644 index 0000000..6fa1f70 --- /dev/null +++ b/src/fishaudio/core/_sse.py @@ -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 diff --git a/src/fishaudio/core/iterators.py b/src/fishaudio/core/iterators.py index 4761848..8142259 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,292 @@ 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]] = {} + 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, + 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) -> 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: + """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. Alternatively, call `collect()` + instead of iterating to get 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() + 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 + + @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. + + 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 + + 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 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. 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 + """ + 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( + 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. Alternatively, call `collect()` + instead of iterating to get 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() + 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 + + @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. + + 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 + + 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 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. 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 + """ + 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: + 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..73d83f2 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,56 @@ 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) + 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: + raise FishAudioError( + f"Unexpected event in text-to-speech stream: {sse.data[:200]}" + ) from exc + + class TTSClient: """Synchronous TTS operations.""" @@ -224,6 +286,155 @@ 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. + When the API has no timings for the text (for example text without + words), `segments` is empty and `duration` is None. + + 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 +751,157 @@ 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. + When the API has no timings for the text (for example text without + words), `segments` is empty and `duration` is None. + + 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 9441d90..e7d6e2f 100644 --- a/src/fishaudio/types/__init__.py +++ b/src/fishaudio/types/__init__.py @@ -50,8 +50,12 @@ ReferenceAudio, StartEvent, TextEvent, + TTSAlignment, TTSConfig, TTSRequest, + TTSTimestampEvent, + TTSTimestampResult, + TTSTimestampSegment, ) from .voices import Author, Sample, Voice @@ -109,8 +113,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..b3f1737 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,106 @@ 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 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 + """ + + 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. + + 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`. 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: Optional[float] = None diff --git a/tests/integration/test_tts_timestamps_integration.py b/tests/integration/test_tts_timestamps_integration.py new file mode 100644 index 0000000..d20ffe3 --- /dev/null +++ b/tests/integration/test_tts_timestamps_integration.py @@ -0,0 +1,46 @@ +"""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 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] + 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: + 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: + """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..ff3e028 --- /dev/null +++ b/tests/unit/test_tts_timestamps.py @@ -0,0 +1,517 @@ +"""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)] + + +# 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] + + +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"), + ] + + @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()) + 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_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") + 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) + 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', + 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): + 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_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") + 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") + 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