diff --git a/.mintlify/skills/fish-audio-sdk/SKILL.md b/.mintlify/skills/fish-audio-sdk/SKILL.md index b8cc56b5..f18a374e 100644 --- a/.mintlify/skills/fish-audio-sdk/SKILL.md +++ b/.mintlify/skills/fish-audio-sdk/SKILL.md @@ -100,6 +100,7 @@ The two SDKs do **not** use the same names. Use this map when porting code betwe | Text-to-Speech | `client.tts.convert(text=...)` → `bytes` | `client.textToSpeech.convert({ text })` | | TTS HTTP stream | `client.tts.stream(...)` → `AudioStream` | (use `convert`; realtime streaming is `convertRealtime`) | | Realtime WebSocket | `client.tts.stream_websocket(text_stream)` | `client.textToSpeech.convertRealtime(request, textStream)` | +| TTS + word timestamps | `client.tts.convert_with_timestamps(text=...)` | not in the SDK; call the HTTP endpoint | | Speech-to-Text | `client.asr.transcribe(audio=...)` | `client.speechToText.convert({ audio })` | | List voice models | `client.voices.list()` | `client.voices.search()` | | Get voice model | `client.voices.get(id)` | `client.voices.get(id)` | @@ -113,6 +114,7 @@ The two SDKs do **not** use the same names. Use this map when porting code betwe ## Decision shortcuts - **Audio from text** → `tts.convert` (Python) / `textToSpeech.convert` (JS). +- **Audio plus the time of each word (captions, highlighting)** → `tts.convert_with_timestamps` / `tts.stream_with_timestamps` (Python, `fish-audio-sdk` 1.6.0+). See "Word timestamps" in `references/text-to-speech.md`. - **Reuse a saved voice** → pass `reference_id` (the voice model `id`). - **Clone a voice instantly from a clip** → pass `references=[ReferenceAudio(audio=..., text=...)]` (Python) / `references: [{ audio, text }]` (JS). See [voice-cloning](references/voice-cloning.md). - **Persistent custom voice to reuse** → create a voice model, then use its `id` as `reference_id`. diff --git a/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md b/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md index 88fea888..72829ddf 100644 --- a/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md +++ b/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md @@ -76,6 +76,30 @@ audio = client.tts.stream(text="Hello!").collect() Async: every method mirrors onto `AsyncFishAudio`; `await client.tts.convert(...)`, and `client.tts.stream(...)` must be awaited before iterating with `async for`. +### Word timestamps (`fish-audio-sdk` 1.6.0+) + +`convert_with_timestamps()` / `stream_with_timestamps()` take the same keyword arguments as `convert()` / `stream()` and call `POST /v1/tts/stream/with-timestamp`. + +```python +result = client.tts.convert_with_timestamps(text="Hello! Welcome to Fish Audio.") +result.audio # bytes, complete audio +result.segments # list[TTSTimestampSegment(text, start, end)], seconds from the start of result.audio +result.duration # float | None, length reported by the API + +with client.tts.stream_with_timestamps(text="Long passage...", format="opus") as stream: + for event in stream: # TTSTimestampEvent + sink.write(event.audio) # may be b"" on a closing event that only corrects timings + show(stream.segments) # timings so far on the full-audio timeline; re-read after every event +``` + +- Segments are words without punctuation; Chinese/Japanese come back one character per segment; numbers follow the spoken reading (`$42.50` → `42`, `50`). Never match segments against the input text. +- Text the API can't time (only punctuation, or only a tag like `[sigh]`): audio is complete, `segments == []`, `duration is None`. Guard before formatting `duration`. +- `stream.collect()` returns the same `TTSTimestampResult`; call it instead of iterating. After iteration has started it raises `RuntimeError`. +- Leaving the `with` block (e.g. `break`) closes the connection; without `with`, call `stream.close()` (`await stream.aclose()` async). +- Async: `await client.tts.convert_with_timestamps(...)`; `async with await client.tts.stream_with_timestamps(...) as stream: async for event in stream: ...`. +- Do not add `event.chunk_audio_offset_sec` to `stream.segments` or `result.segments`: they are already global. (`event.alignment` is the raw per-chunk snapshot, chunk-local times, `None` when absent.) +- No timestamps from `stream_websocket()`, and the JS SDK has no timestamp method; use the HTTP/WebSocket endpoints from the `fish-audio-api` skill. + ## JavaScript: `client.textToSpeech` `convert(request, backend?, requestOptions?)` resolves to a `ReadableStream` you can `play()` or pipe to a file. `backend` is the **second positional** argument, **not** a named option. Always pass it: the npm release (`fish-audio` 0.1.0) defaults it to the deprecated `"s1"` at runtime, although its README says `"s2-pro"`. diff --git a/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps.mdx b/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps.mdx index 96b5b967..b6777453 100644 --- a/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps.mdx +++ b/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps.mdx @@ -18,6 +18,14 @@ iconType: "solid" timeline editing. + + The Python SDK (`fish-audio-sdk` 1.6.0 or later) parses this stream for you: + `client.tts.convert_with_timestamps()` and + `client.tts.stream_with_timestamps()` return the audio with every segment + already on the complete audio timeline. See [Word + timestamps](/features/text-to-speech#word-timestamps). + + ## How the Stream Works The response is a Server-Sent Events stream. Every event includes: diff --git a/developer-guide/getting-started/changelog.mdx b/developer-guide/getting-started/changelog.mdx index 8d743d6f..fb87fc84 100644 --- a/developer-guide/getting-started/changelog.mdx +++ b/developer-guide/getting-started/changelog.mdx @@ -4,6 +4,14 @@ description: "Complete release history and version updates for all Fish Audio pr icon: "clock-rotate-left" rss: true --- + + ## Python SDK 1.6.0: word timestamps + + `fish-audio-sdk` 1.6.0 adds text to speech with word-level timestamps. `client.tts.convert_with_timestamps()` returns the audio with the start and end time of each word, and `client.tts.stream_with_timestamps()` yields audio and timings as they arrive, in both the sync and async clients. Timings are already on the timeline of the complete audio, also for long text generated in several chunks. + + [Word timestamps](/features/text-to-speech#word-timestamps) | [Generate speech with captions](/developer-guide/sdk-guide/cookbook/speech-with-captions) | [Release notes](https://github.com/fishaudio/fish-audio-python/releases/tag/fish-audio-sdk-v1.6.0) + + ## Voice Agents React Native SDK and widget diff --git a/developer-guide/sdk-guide/cookbook/speech-with-captions.mdx b/developer-guide/sdk-guide/cookbook/speech-with-captions.mdx new file mode 100644 index 00000000..754491a9 --- /dev/null +++ b/developer-guide/sdk-guide/cookbook/speech-with-captions.mdx @@ -0,0 +1,139 @@ +--- +title: "Generate speech with SRT/VTT captions" +description: "Generate narration with word-level timestamps from the Python SDK, group the words into caption cues, and write the audio with matching SRT and WebVTT files" +icon: "closed-captioning" +--- + +import Prerequisites from "/snippets/prerequisites.mdx"; + +## Prerequisites + + + +This recipe needs `fish-audio-sdk` 1.6.0 or later: `pip install -U fish-audio-sdk`. + +## Recipe + +[`tts.convert_with_timestamps()`](/features/text-to-speech#word-timestamps) returns the audio together with timed segments, so the captions match the generated speech exactly. Segments are word-level (one character in Chinese and Japanese) and carry no punctuation, so the recipe groups consecutive segments into caption-sized cues before it writes them. Segment `start` / `end` are in **seconds**; SRT wants `HH:MM:SS,mmm` (comma), WebVTT wants `HH:MM:SS.mmm` (dot). + +The recipe starts a new cue after a pause longer than 0.6 seconds, or when the cue would grow past 42 characters or 6 seconds. It joins words with a space, except between Chinese or Japanese characters. A segment can have `start` equal to `end`, so a cue with no duration gets a short one that ends no later than the next cue starts. If the next cue starts at the same millisecond, that cue is moved 1 ms later, so every cue ends after it starts and cues never overlap. + +```python Python +import re + +from fishaudio import FishAudio +from fishaudio.utils import save + +client = FishAudio() + +MAX_CHARS = 42 # longest cue text, in characters +MAX_MS = 6000 # longest cue, in milliseconds +MAX_GAP_MS = 600 # a longer pause between words starts a new cue +MIN_MS = 500 # display time for a cue whose words have no duration + +# Chinese and Japanese are written without spaces between words. +NO_SPACE = re.compile(r"[぀-ヿ㐀-䶿一-鿿]") + +TEXT = ( + "Welcome to the museum. The east wing opens at nine and closes at six. " + "Guided tours leave every hour from the main hall, and the café on the " + "second floor serves lunch until three." +) + + +def join_words(left: str, right: str) -> str: + if NO_SPACE.match(left[-1]) and NO_SPACE.match(right[0]): + return left + right + return f"{left} {right}" + + +def group_cues(segments) -> list[dict]: + """Group word-level segments into cues, with start and end in milliseconds.""" + cues = [] + for segment in segments: + word = segment.text.strip() + if not word: + continue + start, end = round(segment.start * 1000), round(segment.end * 1000) + if cues: + cue = cues[-1] + text = join_words(cue["text"], word) + if ( + start - cue["end"] <= MAX_GAP_MS + and len(text) <= MAX_CHARS + and end - cue["start"] <= MAX_MS + ): + cue["text"], cue["end"] = text, max(cue["end"], end) + continue + cues.append({"start": start, "end": end, "text": word}) + + # A segment can have start == end. Give a cue with no duration a short one, + # ending no later than the next cue starts, so every cue ends after it starts. + for i, cue in enumerate(cues): + if cue["end"] <= cue["start"]: + end = cue["start"] + MIN_MS + if i + 1 < len(cues): + end = min(end, cues[i + 1]["start"]) + cue["end"] = max(end, cue["start"] + 1) + # If the next cue starts at the same millisecond, move it 1 ms later + # so the two cues don't overlap. + if i + 1 < len(cues) and cues[i + 1]["start"] < cue["end"]: + cues[i + 1]["start"] = cue["end"] + return cues + + +def format_timestamp(ms: int, separator: str) -> str: + """HH:MM:SS,mmm for SRT (separator ","), HH:MM:SS.mmm for WebVTT (".").""" + hours, ms = divmod(ms, 3_600_000) + minutes, ms = divmod(ms, 60_000) + seconds, ms = divmod(ms, 1000) + return f"{hours:02d}:{minutes:02d}:{seconds:02d}{separator}{ms:03d}" + + +result = client.tts.convert_with_timestamps(text=TEXT, format="mp3") +save(result.audio, "narration.mp3") + +# Text without words (only punctuation or a sound tag such as "[sigh]") still +# produces audio, but no timings. Parts of a long text can also lack timings. +if not result.segments: + raise SystemExit("No word timings for this text; captions not written.") + +cues = group_cues(result.segments) + +# SRT: 1-based index, comma decimal separator, blank line between cues. +with open("narration.srt", "w", encoding="utf-8") as srt: + for i, cue in enumerate(cues, start=1): + start = format_timestamp(cue["start"], ",") + end = format_timestamp(cue["end"], ",") + srt.write(f"{i}\n{start} --> {end}\n{cue['text']}\n\n") + +# WebVTT: same cues, "WEBVTT" header, dot decimal separator. +with open("narration.vtt", "w", encoding="utf-8") as vtt: + vtt.write("WEBVTT\n\n") + for cue in cues: + start = format_timestamp(cue["start"], ".") + end = format_timestamp(cue["end"], ".") + vtt.write(f"{start} --> {end}\n{cue['text']}\n\n") + +# duration is None when the end of the audio has no timings. +length = f"{result.duration:.2f}s" if result.duration is not None else "length not reported" +print(f"Wrote narration.mp3 ({length}) with {len(cues)} cues") +``` + +Play `narration.mp3` with `narration.vtt` as its text track, or load `narration.srt` next to it in a video editor. Tune `MAX_CHARS`, `MAX_MS`, and `MAX_GAP_MS` for your player and audience. + +Captions show the words as they were spoken after [text normalization](/features/text-to-speech#language), without punctuation: `$42.50` becomes the two words `42` and `50`, not the text you sent. To show your original wording, keep your own sentences and use the segment times only to decide when each sentence starts and ends. + + + Long text is generated in several chunks. The SDK already places every segment + on the timeline of the complete audio, so you don't need to add + `chunk_audio_offset_sec` yourself as the [API + reference](/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps) + describes for raw requests. + + +## Related + +- [Text to Speech: word timestamps](/features/text-to-speech#word-timestamps) +- [Transcribe audio to SRT/VTT captions](/developer-guide/sdk-guide/cookbook/transcribe-to-captions), the same cues from a recording instead of generated speech +- [Text to Speech Stream with Timestamps API](/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps) diff --git a/docs.json b/docs.json index 63889ff9..120c878b 100644 --- a/docs.json +++ b/docs.json @@ -196,7 +196,8 @@ "group": "Text to Speech", "pages": [ "developer-guide/sdk-guide/cookbook/streaming-to-file", - "developer-guide/sdk-guide/cookbook/telephony-8khz-audio" + "developer-guide/sdk-guide/cookbook/telephony-8khz-audio", + "developer-guide/sdk-guide/cookbook/speech-with-captions" ] }, { diff --git a/features/text-to-speech.mdx b/features/text-to-speech.mdx index ccf99b5a..f8583738 100644 --- a/features/text-to-speech.mdx +++ b/features/text-to-speech.mdx @@ -163,13 +163,14 @@ curl --request POST https://api.fish.audio/v1/tts \ ### Generation methods (Python) -The Python SDK exposes three ways to generate, depending on whether you have the full text upfront and how you want to consume the audio: +The Python SDK exposes these ways to generate, depending on whether you have the full text upfront, how you want to consume the audio, and whether you need word timings: | Method | Returns | Use it for | |---|---|---| | `tts.convert()` | complete audio `bytes` | most cases: you have the text, you want the file | | `tts.stream()` | `AudioStream` (iterate chunks, or `.collect()`) | memory-efficient transfer of large audio; write chunks to disk as they arrive | | `tts.stream_websocket()` | iterator of audio `bytes` | text arriving in real time (LLM tokens, live captions) | +| `tts.convert_with_timestamps()` / `tts.stream_with_timestamps()` | audio with word timings | captions and word highlighting; see [Word timestamps](#word-timestamps) | ```python # Memory-efficient: write each chunk as it arrives instead of buffering @@ -181,6 +182,56 @@ with open("out.mp3", "wb") as f: For real-time text streaming with `stream_websocket()`, see [Realtime Streaming](/features/realtime-streaming). +### Word timestamps + +`tts.convert_with_timestamps()` returns the audio together with the time each word is spoken, for captions, highlighting words during playback, or editing on a timeline. It needs `fish-audio-sdk` 1.6.0 or later (`pip install -U fish-audio-sdk`), takes the same arguments as `convert()`, and calls [`POST /v1/tts/stream/with-timestamp`](/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps). + +```python +from fishaudio import FishAudio +from fishaudio.utils import save + +client = FishAudio() +result = client.tts.convert_with_timestamps(text="Hello! Welcome to Fish Audio.") +save(result.audio, "hello.mp3") + +for segment in result.segments: + print(f"{segment.start:.2f}-{segment.end:.2f} {segment.text}") +if result.duration is not None: + print(f"{result.duration:.2f} seconds") +``` + +```text +0.00-0.56 Hello +0.96-1.44 Welcome +1.44-1.60 to +1.60-1.92 Fish +1.92-2.56 Audio +2.69 seconds +``` + +- `start` and `end` are seconds from the start of `result.audio`, also for long text that is generated in several chunks. +- A segment is usually one word without punctuation. Text written without spaces, such as Chinese, comes back one character per segment, and numbers follow the spoken reading after [normalization](#language): `$42.50` gives the segments `42` and `50`. Don't expect segments to match your input text. +- When the API can't time the text, for example text that is only punctuation or a sound tag such as `[sigh]`, the audio is still complete, but `segments` is `[]` and `duration` is `None`. In a long text, only some parts can lack timings: `segments` then has the timed words, and `duration` is `None` if the end of the audio has no timings. `duration` is the length the API reports, not one measured from the audio. + +To use audio and timings while they arrive, call `tts.stream_with_timestamps()`. Each event carries the next piece of audio in `event.audio`, which can be empty, and `stream.segments` holds the timings received so far on the timeline of the complete audio: + +```python +with client.tts.stream_with_timestamps(text="A long passage...", format="opus") as stream: + with open("out.opus", "wb") as f: + for event in stream: + f.write(event.audio) + if stream.segments: + latest = stream.segments[-1] + print(f"timed up to {latest.end:.2f}s: {latest.text}") +``` + +- Read `stream.segments` again after each event instead of keeping an earlier copy: later events can still correct the last entries. +- Leaving the `with` block closes the connection, so you can stop early with `break`. Without `with`, call `stream.close()`. +- `stream.collect()` returns the same result as `convert_with_timestamps()`. Call it instead of iterating, not after: once iteration has started it raises `RuntimeError`. +- With `AsyncFishAudio`, await both methods and iterate with `async with await client.tts.stream_with_timestamps(...) as stream:` and `async for event in stream:`. + +`stream_websocket()` doesn't return timestamps; for timestamps over a WebSocket, use the [WebSocket endpoint](/api-reference/endpoint/openapi-v1/text-to-speech-live-with-timestamps) directly. To write captions from the segments, see [Generate speech with SRT/VTT captions](/developer-guide/sdk-guide/cookbook/speech-with-captions). + ### Instant voice cloning (reference audio) Instead of a saved `reference_id`, pass raw audio plus its transcript to clone a voice on the fly, with no training step. Best with a clean 10–30s sample. diff --git a/llms.txt b/llms.txt index 64820aad..b24f9d6c 100644 --- a/llms.txt +++ b/llms.txt @@ -27,6 +27,7 @@ - [Update Model](https://docs.fish.audio/api-reference/endpoint/model/update-model.md): Update an existing model. - [Delete Model](https://docs.fish.audio/api-reference/endpoint/model/delete-model.md): Delete an existing model. - [Revoke Exposed API Keys](https://docs.fish.audio/api-reference/endpoint/apikey/revoke-api-keys.md): Revoke exposed Fish Audio API keys without signing in; for secret scanners, partners, and key owners. +- [Text to Speech Stream with Timestamps](https://docs.fish.audio/api-reference/endpoint/openapi-v1/text-to-speech-stream-with-timestamps.md): Stream generated speech over SSE with word-level alignment snapshots (POST /v1/tts/stream/with-timestamp); in Python use tts.convert_with_timestamps() or tts.stream_with_timestamps() (fish-audio-sdk 1.6.0+). - [WebSocket TTS Streaming](https://docs.fish.audio/api-reference/endpoint/websocket/tts-live.md): Real-time text-to-speech streaming via WebSocket. - [WebSocket Realtime Speech to Text](https://docs.fish.audio/api-reference/endpoint/websocket/asr-realtime.md): Stream audio to wss://api.fish.audio/v1/asr/realtime (transcribe-stream-1, Preview) and receive transcripts per turn; every client and server message, turn detection modes, errors, close codes and limits. @@ -42,12 +43,13 @@ - [One-shot vs Persistent Voice Cloning](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/oneshot-vs-persistent-cloning.md): Choose between instant per-request cloning and a saved, reusable voice model, with Python SDK and JavaScript SDK examples. - [Stream TTS to a File](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/streaming-to-file.md): Generate long text-to-speech audio and write it to disk chunk by chunk without buffering it all in memory, with Python SDK and JavaScript SDK examples. - [Telephony-grade Audio (8 kHz)](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/telephony-8khz-audio.md): Generate 8 kHz mono WAV or PCM text-to-speech audio for IVR and phone playback, with Python SDK, JavaScript SDK, and curl examples. +- [Generate Speech with SRT/VTT Captions](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/speech-with-captions.md): Generate narration with word-level timestamps using tts.convert_with_timestamps() in the Python SDK (fish-audio-sdk 1.6.0+), group the words into cues, and write matching SRT and WebVTT files. - [Realtime LLM Tokens to Speech](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/realtime-llm-to-speech.md): Pipe a streaming LLM response into speech over a WebSocket as tokens arrive, with stream_websocket() in the Python SDK. - [Build a Voice Agent Loop](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/voice-agent-loop.md): Transcribe an utterance, generate a reply with your own LLM, and stream the reply back as speech, with Python SDK and JavaScript SDK examples. ## Product Guides -- [Text to Speech Guide](https://docs.fish.audio/features/text-to-speech.md): Generate natural speech from text, with Python SDK, JavaScript SDK, and curl examples, plus voice selection, output formats, speed, and latency settings. +- [Text to Speech Guide](https://docs.fish.audio/features/text-to-speech.md): Generate natural speech from text, with Python SDK, JavaScript SDK, and curl examples, plus voice selection, output formats, speed, latency settings, and word timestamps in the Python SDK. - [Drama 3](https://docs.fish.audio/features/text-to-speech/drama-3.md): Text-to-speech model (drama-3) directed with plain-language directions in square brackets, sounds and pauses, paired tags for specific words, and multi-speaker dialogue. - [Audio Infill](https://docs.fish.audio/features/text-to-speech/audio-infill.md): Apply a script change to an existing recording with drama-3: send the take, the full revised transcript and the span to replace, and get the whole take back. - [Speech to Text Guide](https://docs.fish.audio/features/speech-to-text.md): Transcribe audio with transcribe-1-pro, including multi-speaker conversations with speaker turns, long recordings and inline emotion cues. diff --git a/tests/cookbooks/requirements.txt b/tests/cookbooks/requirements.txt index 8c9c7f96..30accb47 100644 --- a/tests/cookbooks/requirements.txt +++ b/tests/cookbooks/requirements.txt @@ -1,4 +1,4 @@ -fish-audio-sdk>=1.3.0 +fish-audio-sdk>=1.6.0 httpx>=0.28 python-dotenv>=1.0 pytest>=8.0 diff --git a/tests/cookbooks/specs.py b/tests/cookbooks/specs.py index 1c15d741..2007c248 100644 --- a/tests/cookbooks/specs.py +++ b/tests/cookbooks/specs.py @@ -104,6 +104,27 @@ def print(*args, **kwargs): {"name": "8 kHz raw pcm", "block": 2, "var_nonempty": "audio"}, ], }, + { + "slug": "speech-with-captions", + "path": f"{COOKBOOK}/speech-with-captions.mdx", + "cases": [ + { + "name": "TTS with SRT/VTT captions", + "block": 0, + "file": ("narration.mp3", "mp3"), + # Cues are grouped words in order, each ending after it starts, none overlapping the + # next, the last no later than MIN_MS past the reported duration; both caption files are written. + "postamble": ( + "assert cues and all(c['end'] > c['start'] for c in cues), cues\n" + "assert all(a['start'] <= b['start'] for a, b in zip(cues, cues[1:])), cues\n" + "assert all(a['end'] <= b['start'] for a, b in zip(cues, cues[1:])), cues\n" + "assert result.duration is None or cues[-1]['end'] <= round(result.duration * 1000) + MIN_MS, (cues[-1], result.duration)\n" + "assert open('narration.srt', encoding='utf-8').read().startswith('1\\n')\n" + "assert open('narration.vtt', encoding='utf-8').read().startswith('WEBVTT\\n')" + ), + } + ], + }, { "slug": "clone-and-wait-until-ready", "path": f"{COOKBOOK}/clone-and-wait-until-ready.mdx",