diff --git a/api-reference/endpoint/openapi-v1/speech-to-text.mdx b/api-reference/endpoint/openapi-v1/speech-to-text.mdx index 1d687a25..348272a6 100644 --- a/api-reference/endpoint/openapi-v1/speech-to-text.mdx +++ b/api-reference/endpoint/openapi-v1/speech-to-text.mdx @@ -97,11 +97,13 @@ A field that is not returned is absent from the JSON, never `null`. Do not depen Both SDKs select `transcribe-1-pro` through the `model` header. In Python, - pass - `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})` - to `asr.transcribe()`. In JavaScript, pass - `{ headers: { model: "transcribe-1-pro" } }` as the second argument to - `speechToText.convert()`. Neither SDK can send `tag_audio_events`, + pass `model="transcribe-1-pro"` to `asr.transcribe()` (`fish-audio-sdk` 1.5.0 + or later; on earlier versions, pass + `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})`). + In JavaScript, pass `model: "transcribe-1-pro"` in the request to + `speechToText.convert()` (`fish-audio` 0.2.0 or later; on 0.1.0, pass + `{ headers: { model: "transcribe-1-pro" } }` as the second argument). Neither + SDK can send `tag_audio_events`, `diarize`, or the speaker-count hints. To use them, call the API directly, as in the examples above. The Python SDK returns the fields listed above (`fish-audio-sdk` 1.4.0 or later; earlier versions keep only `text`, diff --git a/developer-guide/models-pricing/migrate-from-transcribe-1.mdx b/developer-guide/models-pricing/migrate-from-transcribe-1.mdx index f0ac2d97..0efdb8a4 100644 --- a/developer-guide/models-pricing/migrate-from-transcribe-1.mdx +++ b/developer-guide/models-pricing/migrate-from-transcribe-1.mdx @@ -51,17 +51,12 @@ curl --request POST https://api.fish.audio/v1/asr \ ```python Python from fishaudio import FishAudio -from fishaudio.core import RequestOptions client = FishAudio() # reads FISH_API_KEY with open("speech.wav", "rb") as f: - result = client.asr.transcribe( - audio=f.read(), - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), - ) + # model sends the header; it requires fish-audio-sdk 1.5.0 or later + result = client.asr.transcribe(audio=f.read(), model="transcribe-1-pro") print(result.text) ``` diff --git a/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx b/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx index d0e4734a..3d0a98da 100644 --- a/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx +++ b/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx @@ -12,13 +12,18 @@ import Prerequisites from "/snippets/prerequisites.mdx"; ## Recipe -This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Every tab selects it with the `model` request header; without that header, the request is served and billed as `transcribe-1`. +This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Every tab selects it with the `model` request header, which the Python SDK sends for its `model` argument; without that header, the request is served and billed as `transcribe-1`. Read each file's bytes from disk and pass them to [`asr.transcribe()`](/api-reference/sdk/python/resources#transcribe) with `language` set to a lowercase ISO 639-1 code such as `en`, `zh`, or `ja`. Other forms, such as `en-US` or `English`, may be rejected with 400. Pass `language` when you know the source language. Detection still runs, and the hint does not force the transcript into that language; the hint is reported as `language_code` when the language cannot be determined. See [Language](/features/speech-to-text#language) for details. Collect one result row per file as you go. If a file cannot be read, its request fails with a network error such as a timeout, or the API returns an error for it, record the error in that file's row and move on to the next file. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade fish-audio-sdk`. + + + The `model` argument of `asr.transcribe()` requires `fish-audio-sdk` 1.5.0 or + later. + @@ -32,10 +37,7 @@ client = FishAudio() paths = ["speech.wav"] # add more file paths here language = "en" -options = RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, -) +options = RequestOptions(timeout=900) # long recordings can take several minutes results = [] for path in paths: @@ -44,6 +46,7 @@ for path in paths: audio = f.read() transcript = client.asr.transcribe( audio=audio, + model="transcribe-1-pro", language=language, include_timestamps=False, request_options=options, @@ -81,10 +84,8 @@ async def main(): async with AsyncFishAudio() as client: paths = ["speech.wav"] # add more file paths here language = "en" - options = RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, - ) + # long recordings can take several minutes + options = RequestOptions(timeout=900) results = [] for path in paths: @@ -93,6 +94,7 @@ async def main(): audio = f.read() transcript = await client.asr.transcribe( audio=audio, + model="transcribe-1-pro", language=language, include_timestamps=False, request_options=options, diff --git a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx index 8fa2cf82..c83b838d 100644 --- a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx +++ b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx @@ -13,29 +13,368 @@ import Prerequisites from "/snippets/prerequisites.mdx"; -This recipe speaks the WebSocket protocol directly, so it needs no SDK. The Python SDK (`fish-audio-sdk` 1.5.0 or later) also wraps this endpoint as `client.asr.stream_websocket()`, and the JavaScript SDK (`fish-audio` 0.2.0 or later, Node.js only) as [`client.speechToText.convertRealtime()`](/api-reference/sdk/javascript/api-reference#speech-to-text). Install a WebSocket client and a MessagePack library: +Install the Python or TypeScript SDK: ```bash Python -pip install "websockets>=14" msgpack +pip install --upgrade fish-audio-sdk ``` -```bash JavaScript -npm install ws @msgpack/msgpack +```bash TypeScript +npm install fish-audio ``` + + `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later, and + [`client.speechToText.convertRealtime()`](/api-reference/sdk/javascript/api-reference#speech-to-text) + requires `fish-audio` 0.2.0 or later (Node.js only). In browsers or other + languages, [connect to the WebSocket directly](#without-the-sdk). + + You also need a 16-bit PCM mono WAV file, at 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. To convert a recording, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav`. ## Recipe -The script connects to `wss://api.fish.audio/v1/asr/realtime`, sends a `config` message, waits for `session_started`, and then streams the file in 40 ms messages at real-time speed, as a live microphone would. It prints every message the server sends until the session ends. +`client.asr.stream_websocket()` in Python and `client.speechToText.convertRealtime()` in TypeScript take an iterator of audio chunks and return the events the server sends. The script streams the file in 40 ms chunks at real-time speed, as a live microphone would, and prints every event until the session ends. The SDK opens the session, sends each chunk as it is yielded, and ends the session when the iterator is exhausted. ```python Python +"""Stream a WAV file to Fish Audio realtime speech-to-text and print the events. + + pip install --upgrade fish-audio-sdk + export FISH_API_KEY=... + python transcribe_file.py speech.wav + +The WAV must be 16-bit PCM, mono, at 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. +""" +import sys +import time +import wave + +from fishaudio import FishAudio + +CHUNK_MS = 40 # ms of audio per chunk; 20-40 ms suits live audio + + +def microphone(wav, rate): + """Yield the audio in real time, as a live microphone would.""" + start = time.monotonic() + sent_ms = 0 + while chunk := wav.readframes(rate * CHUNK_MS // 1000): + yield chunk + sent_ms += CHUNK_MS + time.sleep(max(0.0, start + sent_ms / 1000 - time.monotonic())) + + +def show(event): + t = event.type + if t == "session_started": + print(f"session {event.session_id} (request {event.request_id})") + elif t == "draft": + print(f" draft #{event.turn_index}: {event.text}") + elif t == "eager_end_of_turn": + print(f" eager #{event.turn_index}: {event.text}") + elif t == "committed": + who = "user " if event.user_turn else "other" + print(f"committed #{event.turn_index} [{who}] {event.audio_start_ms}-{event.audio_end_ms} ms " + f"({event.reason}, {event.language_code or '?'}): {event.text}") + elif t == "error": # recoverable: the session continues + print(f"error {event.error_type} ({event.code}): {event.message} [request {event.request_id}]") + elif t == "session_done": + print(f"done: {event.stats.audio_ms} ms of audio, {event.stats.turns} turns") + else: # speech_start, user_turn_taken, turn_resumed, ... + print(f" {t} #{getattr(event, 'turn_index', '')}") + + +def main(path): + wav = wave.open(path, "rb") + if wav.getsampwidth() != 2 or wav.getnchannels() != 1: + sys.exit("need a 16-bit mono WAV") + rate = wav.getframerate() + + client = FishAudio() # reads FISH_API_KEY + for event in client.asr.stream_websocket( + microphone(wav, rate), sample_rate=rate, eager=True, drafts=True + ): + show(event) + + +if __name__ == "__main__": + main(sys.argv[1]) +``` + +```python Python (async) +"""The same script with AsyncFishAudio: pass an async iterator, read with async for.""" +import asyncio +import sys +import wave + +from fishaudio import AsyncFishAudio + +CHUNK_MS = 40 # ms of audio per chunk; 20-40 ms suits live audio + + +async def microphone(wav, rate): + """Yield the audio in real time, as a live microphone would.""" + loop = asyncio.get_running_loop() + start = loop.time() + sent_ms = 0 + while chunk := wav.readframes(rate * CHUNK_MS // 1000): + yield chunk + sent_ms += CHUNK_MS + await asyncio.sleep(max(0.0, start + sent_ms / 1000 - loop.time())) + + +async def main(path): + wav = wave.open(path, "rb") + if wav.getsampwidth() != 2 or wav.getnchannels() != 1: + sys.exit("need a 16-bit mono WAV") + rate = wav.getframerate() + + client = AsyncFishAudio() # reads FISH_API_KEY + async for event in client.asr.stream_websocket( + microphone(wav, rate), sample_rate=rate, eager=True, drafts=True + ): + if event.type == "draft": + print(f" draft #{event.turn_index}: {event.text}") + elif event.type == "committed": + print(f"committed #{event.turn_index}: {event.text}") + elif event.type == "session_done": + print(f"done: {event.stats.audio_ms} ms of audio, {event.stats.turns} turns") + await client.close() + + +if __name__ == "__main__": + asyncio.run(main(sys.argv[1])) +``` + +```typescript TypeScript +// npm install fish-audio +// FISH_API_KEY=... node transcribe_file.ts speech.wav (Node.js 22.18+ runs TypeScript directly) +import { readFileSync } from "node:fs"; +import { setTimeout as sleep } from "node:timers/promises"; +import { + FishAudioClient, + type RealtimeSTTEvent, + type RealtimeSTTSampleRate, +} from "fish-audio"; + +const CHUNK_MS = 40; // ms of audio per chunk; 20-40 ms suits live audio + +// Read a 16-bit mono PCM WAV file: its sample rate and its samples. +function readWav(path: string) { + const buf = readFileSync(path); + let rate = 0, + channels = 0, + bits = 0; + let data: Buffer | undefined; + for (let pos = 12; pos + 8 <= buf.length; ) { + const id = buf.toString("ascii", pos, pos + 4); + const size = buf.readUInt32LE(pos + 4); + if (id === "fmt ") { + channels = buf.readUInt16LE(pos + 10); + rate = buf.readUInt32LE(pos + 12); + bits = buf.readUInt16LE(pos + 22); + } else if (id === "data") { + data = buf.subarray(pos + 8, pos + 8 + size); + } + pos += 8 + size + (size % 2); + } + if (bits !== 16 || channels !== 1 || !data) + throw new Error("need a 16-bit mono WAV"); + return { rate, data }; +} + +// Yield the audio in real time, as a live microphone would. +async function* microphone(data: Buffer, rate: number) { + const bytesPerChunk = ((rate * CHUNK_MS) / 1000) * 2; + const start = Date.now(); + for (let i = 0; i < data.length; i += bytesPerChunk) { + yield data.subarray(i, i + bytesPerChunk); + const sentMs = (i / bytesPerChunk + 1) * CHUNK_MS; + await sleep(Math.max(0, start + sentMs - Date.now())); + } +} + +function show(event: RealtimeSTTEvent) { + switch (event.type) { + case "session_started": + console.log(`session ${event.session_id} (request ${event.request_id})`); + break; + case "draft": + console.log(` draft #${event.turn_index}: ${event.text}`); + break; + case "eager_end_of_turn": + console.log(` eager #${event.turn_index}: ${event.text}`); + break; + case "committed": { + const who = event.user_turn ? "user " : "other"; + console.log( + `committed #${event.turn_index} [${who}] ${event.audio_start_ms}-${event.audio_end_ms} ms ` + + `(${event.reason}, ${event.language_code ?? "?"}): ${event.text}` + ); + break; + } + case "error": // recoverable: the session continues + console.log( + `error ${event.error_type} (${event.code}): ${event.message} [request ${event.request_id}]` + ); + break; + case "session_done": + console.log( + `done: ${event.stats.audio_ms} ms of audio, ${event.stats.turns} turns` + ); + break; + default: // speech_start, user_turn_taken, turn_resumed, ... + console.log( + ` ${event.type} #${"turn_index" in event ? event.turn_index : ""}` + ); + } +} + +const { rate, data } = readWav(process.argv[2]); +const client = new FishAudioClient(); // reads FISH_API_KEY +const stream = client.speechToText.convertRealtime( + { sample_rate: rate as RealtimeSTTSampleRate, eager: true, drafts: true }, + microphone(data, rate) +); +for await (const event of stream) show(event); +``` + + + +Run it with your API key in `FISH_API_KEY`: + + + +```bash Python +python transcribe_file.py speech.wav +``` + +```bash TypeScript +node transcribe_file.ts speech.wav +``` + + + +Node.js 22.18 or later runs TypeScript files directly; on an earlier version, compile the script with `tsc` first. The script uses `import`: inside a project whose `package.json` sets `"type": "commonjs"`, name it `transcribe_file.mts`. + +For a 15-second customer-support clip, the output looks like this (`...` marks drafts left out): + +```text +session s_ab12cd34 (request 0b6f4c1e-7d2a-4e8b-9f3c-5a1d2e3f4b6c) + speech_start #0 + draft #0: <|speaker:0|>Can you... + draft #0: <|speaker:0|>Can you tell + user_turn_taken #0 + draft #0: <|speaker:0|>Can you tell me what... + ... + draft #0: <|speaker:0|>Can you tell me what time the pharmacy on Main Street closes tonight? + eager #0: <|speaker:0|>Can you tell me what time the pharmacy on Main Street closes tonight? +committed #0 [user ] 2768-8000 ms (eot, en): <|speaker:0|>Can you tell me what time the pharmacy on Main Street closes tonight? + speech_start #1 + draft #1: <|speaker:0|>Uh-huh. + user_turn_taken #1 + eager #1: <|speaker:0|>Uh-huh. +committed #1 [user ] 9840-11840 ms (eot, ?): <|speaker:0|>Uh-huh. + speech_start #2 + draft #2: <|speaker:0|>I'd like + user_turn_taken #2 + ... + draft #2: <|speaker:0|>I'd like to change my deli- +committed #2 [user ] 13168-14992 ms (audio_done, en): <|speaker:0|>I'd like to change my delivery +done: 15000 ms of audio, 3 turns +``` + +The clip ends mid-sentence, so the last turn is committed by `audio_done`. Drafts can hold partial words, such as `deli-`; the committed text is final. + +## Read the events + +Each event is an object with a `type` and the fields of the server message as attributes; a field the server left out is `None` in Python and `undefined` in TypeScript. The exceptions are on `committed`: a missing `user_turn` is `True` in both SDKs, and Python also fills a missing `reason` with `"eot"` and `degraded` with `False`. The options have the same names in both SDKs: `drafts=True` in Python is `drafts: true` in TypeScript. + +- **`speech_start`** opens a turn when voice activity begins. In the default `auto` mode, noise and other voices open turns too. +- **`draft`** is the whole turn so far, and replaces the previous draft. Drafts come only with `drafts=True` (`results.drafts: true` in the protocol); use them for live captions. +- **`user_turn_taken`** says the server judged that the user is taking their turn, rather than noise or someone else nearby. +- **`eager_end_of_turn`** comes with `eager=True` (`turn_detection.eager: true`) when the turn has probably ended. Its text equals the final transcript unless `turn_resumed` follows, so an agent can start its reply early. +- **`committed`** is the final transcript of the turn. `user_turn: false` marks a non-user turn, such as background noise or a short acknowledgement while your agent is speaking. Speaker tags such as `<|speaker:0|>` are stable within the session; strip them and trim the text, or pass `diarize=False` (`results.diarize: false`). Text can also contain [sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags) such as `[laughter]`; strip them too, or turn them off with `results.tag_audio_events: false`. `language_code` is missing when the text is too short to tell, as for "Uh-huh." above. +- **`session_done`** is the last event. The SDK sends `audio_done` when your iterator is exhausted; the server answers with `session_done` and closes the connection with code 1000. + +The SDKs skip message types they do not know; if you read the protocol yourself, ignore message types and fields you do not know, because new ones can be added. Every message is described in the [WebSocket reference](/api-reference/endpoint/websocket/asr-realtime#server-messages). + + + The script streams the file at real-time speed so that the events arrive as + they would for live audio. To transcribe a recording you already have, use + [`POST /v1/asr`](/features/speech-to-text) instead; it is simpler and returns + the whole transcript at once. + + +## Choose what you receive + +The keyword arguments of `stream_websocket()`, and the fields of the first argument of `convertRealtime()`, set the session's options: + +| Argument | Default | What it does | +| ---------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `sample_rate` | `16000` | The sample rate of your audio, in Hz. The server converts it, so do not resample. | +| `drafts` | off | Turn on to receive live `draft` events while a turn is open. | +| `eager` | off | Turn on to receive `eager_end_of_turn` as soon as a turn has probably ended. | +| `diarize` | on | Turn off to remove speaker tags from the text. | +| `turn_detection` | `"auto"` | `"vad"` ends a turn after a fixed silence; `"manual"` ends it when you call `finalize()`. | +| `terms` | none | Names, products and jargon to recognize, for example `["Main Street"]`. | +| `config` | | Python only: an `ASRRealtimeConfig` with every other option, such as word timestamps, sound tags and history. In TypeScript, pass `results` and `context` next to the fields above. | + +By default, each transcript starts with a speaker tag, as in the output above. For plain text, turn `diarize` off: + + + +```python Python +for event in client.asr.stream_websocket(audio_chunks, sample_rate=16000, diarize=False): + if event.type == "committed": + print(event.text) # Can you tell me what time the pharmacy on Main Street closes tonight? +``` + +```typescript TypeScript +const stream = client.speechToText.convertRealtime( + { sample_rate: 16000, diarize: false }, + audioChunks +); +for await (const event of stream) { + if (event.type === "committed") console.log(event.text); +} +``` + + + +The stream that both calls return also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent); in TypeScript they are `agentSpeaking()`, `addContext()` and `configure()`. To stop before the audio ends in Python, use the stream in a `with` block (`async with` with `AsyncFishAudio`), or call `close()` (`await stream.aclose()`). Leaving the loop is not enough while you still hold the stream in a variable: the session stays open and the SDK keeps sending your audio. In TypeScript, leave the loop or call `close()`. If the server has stopped reading, the Python SDK does not wait for it when closing: after half a second it cuts the connection. + +Read the events from one place at a time. In Python with `AsyncFishAudio`, a second read started while another is waiting raises `RuntimeError`; a read cancelled by a timeout, such as `asyncio.wait_for()`, loses no event, so read again. + +An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. `close_code` can be `None` when the server's error message ended the session before the connection closed. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. In TypeScript, the stream throws `RealtimeSTTError` (from `fish-audio`), with `errorType` and `closeCode`, and a refused connection throws an API error such as `UnauthorizedError`. + +## Without the SDK + +In other languages, or to control the connection yourself, speak the WebSocket protocol directly: connect to `wss://api.fish.audio/v1/asr/realtime`, send a `config` message, wait for `session_started`, then send `audio` messages and finish with `audio_done`. Every message is a MessagePack map in a binary frame. Install a WebSocket client and a MessagePack library: + + + +```bash Python +pip install "websockets>=14" msgpack +``` + +```bash JavaScript +npm install ws @msgpack/msgpack +``` + + + +These scripts do the same as the recipe above, and also print the close code when the session ends (`closed: 1000 done`): + + + +```python Python (websockets) """Stream a WAV file to Fish Audio realtime speech-to-text and print the events. pip install "websockets>=14" msgpack @@ -125,7 +464,7 @@ if __name__ == "__main__": asyncio.run(main(sys.argv[1])) ``` -```javascript JavaScript +```javascript JavaScript (ws) // npm install ws @msgpack/msgpack // FISH_API_KEY=... node transcribe_file.mjs speech.wav import { readFileSync } from "node:fs"; @@ -240,7 +579,7 @@ The audio goes in `data` as the raw PCM bytes, which must travel as MessagePack The server closes a session after 30 seconds without any client message, but a WebSocket ping counts as one, and Python's `websockets` sends a ping every 20 seconds by default, so the session stays open even if your audio stops; see [Capture audio well](/developer-guide/sdk-guide/cookbook/realtime-voice-agent#capture-audio-well) for a live source that can stall. -Run it with your API key in `FISH_API_KEY`: +Run them with your API key in `FISH_API_KEY`: ```bash python transcribe_file.py speech.wav @@ -248,54 +587,6 @@ python transcribe_file.py speech.wav node transcribe_file.mjs speech.wav ``` -For a 15-second customer-support clip, the output looks like this (`...` marks drafts left out): - -```text -session s_ab12cd34 (request 0b6f4c1e-7d2a-4e8b-9f3c-5a1d2e3f4b6c) - speech_start #0 - draft #0: <|speaker:0|> Can you... - draft #0: <|speaker:0|> Can you tell - user_turn_taken #0 - draft #0: <|speaker:0|> Can you tell me what... - ... - draft #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? - eager #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? -committed #0 [user ] 2768-8000 ms (eot, en): <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? - speech_start #1 - draft #1: <|speaker:0|> Uh-huh. - user_turn_taken #1 - eager #1: <|speaker:0|> Uh-huh. -committed #1 [user ] 9840-11840 ms (eot, ?): <|speaker:0|> Uh-huh. - speech_start #2 - draft #2: <|speaker:0|> I'd like - user_turn_taken #2 - ... - draft #2: <|speaker:0|> I'd like to change my deli- -committed #2 [user ] 13168-14992 ms (audio_done, en): <|speaker:0|> I'd like to change my delivery -done: 15000 ms of audio, 3 turns -closed: 1000 done -``` - -The clip ends mid-sentence, so the last turn is committed by `audio_done`. Drafts can hold partial words, such as `deli-`; the committed text is final. - -## Read the events - -- **`speech_start`** opens a turn when voice activity begins. In the default `auto` mode, noise and other voices open turns too. -- **`draft`** is the whole turn so far, and replaces the previous draft. Drafts come only with `results.drafts: true`; use them for live captions. -- **`user_turn_taken`** says the server judged that the user is taking their turn, rather than noise or someone else nearby. -- **`eager_end_of_turn`** comes with `turn_detection.eager: true` when the turn has probably ended. Its text equals the final transcript unless `turn_resumed` follows, so an agent can start its reply early. -- **`committed`** is the final transcript of the turn. `user_turn: false` marks a non-user turn, such as background noise or a short acknowledgement while your agent is speaking. Speaker tags such as `<|speaker:0|>` are stable within the session; strip them and trim the text, or send `results.diarize: false`. Text can also contain [sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags) such as `[laughter]`; strip them too, or send `results.tag_audio_events: false`. `language_code` is omitted when the text is too short to tell, as for "Uh-huh." above. -- **`session_done`** follows `audio_done`, and the server then closes the connection with code 1000. - -Ignore message types and fields you do not know: new ones can be added. Every message is described in the [WebSocket reference](/api-reference/endpoint/websocket/asr-realtime#server-messages). - - - The script streams the file at real-time speed so that the events arrive as - they would for live audio. To transcribe a recording you already have, use - [`POST /v1/asr`](/features/speech-to-text) instead; it is simpler and returns - the whole transcript at once. - - ## Capture from a browser microphone The API key travels in a request header, and browsers cannot set headers on a WebSocket. Never put your API key in a web page: run a small relay on your server that adds the `Authorization` header and passes MessagePack frames through unchanged. The page then speaks the same protocol as the scripts above. diff --git a/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx b/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx index 4a4d6aa0..8ecde43d 100644 --- a/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx +++ b/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx @@ -12,13 +12,18 @@ import Prerequisites from "/snippets/prerequisites.mdx"; ## Recipe -This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Both tabs select it with the `model` request header; without that header, the request is served and billed as `transcribe-1`. +This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Both tabs select it with the `model` request header, which the Python SDK sends for its `model` argument; without that header, the request is served and billed as `transcribe-1`. Call [`asr.transcribe()`](/api-reference/sdk/python/resources#transcribe) with `include_timestamps=True` (in JavaScript, `ignore_timestamps: false`) to get timed segments ([`ASRSegment`](/api-reference/sdk/python/types#asrsegment-objects)). Segments are word-level (one character, or a few, in Chinese and Japanese) and carry no punctuation, so group consecutive segments into caption-sized cues before you format 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, which are written without spaces. 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. Every cue therefore ends after it starts, as SRT and WebVTT players expect. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade fish-audio-sdk`. + + + The `model` argument of `asr.transcribe()` requires `fish-audio-sdk` 1.5.0 or + later. + @@ -87,11 +92,10 @@ def format_timestamp(ms: int, separator: str) -> str: with open("speech.wav", "rb") as f: result = client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=True, - request_options=RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, - ), + # long recordings can take several minutes + request_options=RequestOptions(timeout=900), ) cues = group_cues(result.segments) diff --git a/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx b/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx index 0f2e8974..08277b53 100644 --- a/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx +++ b/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx @@ -14,9 +14,14 @@ import Prerequisites from "/snippets/prerequisites.mdx"; A voice agent is three stages chained together: [`asr.transcribe()`](/api-reference/sdk/python/resources#transcribe) turns the caller's audio into text, your own LLM turns that text into a reply, and [`tts.stream()`](/api-reference/sdk/python/resources#stream) turns the reply back into speech. The transcript and the reply are just strings, so the only Fish Audio-specific parts are the first and last calls. Streaming the reply lets you start writing (or forwarding) audio before the whole sentence is synthesized. -The recipe transcribes with `transcribe-1-pro`. Every tab selects it with the `model` request header; without that header, the request is served and billed as `transcribe-1`. +The recipe transcribes with `transcribe-1-pro`. Every tab selects it with the `model` request header, which the Python SDK sends for its `model` argument; without that header, the request is served and billed as `transcribe-1`. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade fish-audio-sdk`. + + + The `model` argument of `asr.transcribe()` requires `fish-audio-sdk` 1.5.0 or + later. + @@ -24,7 +29,6 @@ Install the Python SDK first: `pip install fish-audio-sdk`. import re from fishaudio import FishAudio -from fishaudio.core import RequestOptions from fishaudio.utils import save client = FishAudio() @@ -39,10 +43,8 @@ def voice_agent_turn(audio_path: str, out_path: str) -> str: with open(audio_path, "rb") as f: heard = client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=False, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), ) # Drop speaker markers such as <|speaker:0|>; keep cues such as [laughter]. @@ -62,7 +64,6 @@ import asyncio import re from fishaudio import AsyncFishAudio -from fishaudio.core import RequestOptions from fishaudio.utils import save def reply_from_llm(text: str) -> str: @@ -75,10 +76,8 @@ async def main(): with open("speech.wav", "rb") as f: heard = await client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=False, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), ) # Drop speaker markers such as <|speaker:0|>; keep cues such as [laughter]. diff --git a/features/speech-to-text.mdx b/features/speech-to-text.mdx index 79b91793..92fb447f 100644 --- a/features/speech-to-text.mdx +++ b/features/speech-to-text.mdx @@ -80,7 +80,7 @@ Create an [API key](/developer-guide/getting-started/api-key) and set `FISH_API_ Every example on this page selects `transcribe-1-pro`. The examples below also request timestamps. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade "fish-audio-sdk>=1.5.0"`. @@ -93,11 +93,10 @@ client = FishAudio() # reads FISH_API_KEY with open("speech.wav", "rb") as f: result = client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=True, - request_options=RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, - ), + # long recordings can take several minutes + request_options=RequestOptions(timeout=900), ) print(result.text) @@ -162,10 +161,8 @@ Each segment is `{ "text", "start", "end" }`, with times in **seconds**. Segment ```python Python result = client.asr.transcribe( audio=audio_bytes, + model="transcribe-1-pro", include_timestamps=True, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), ) print(f"{result.duration:.1f}s total") @@ -373,14 +370,12 @@ If the language cannot be determined (for example, very short audio), `language_ ```python Python -pro = RequestOptions(additional_headers={"model": "transcribe-1-pro"}) - # Auto-detect -result = client.asr.transcribe(audio=audio_bytes, request_options=pro) +result = client.asr.transcribe(audio=audio_bytes, model="transcribe-1-pro") # Provide a language hint result = client.asr.transcribe( - audio=audio_bytes, language="zh", request_options=pro + audio=audio_bytes, language="zh", model="transcribe-1-pro" ) ``` @@ -496,12 +491,7 @@ import json from fishaudio.exceptions import APIError try: - result = client.asr.transcribe( - audio=audio_bytes, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), - ) + result = client.asr.transcribe(audio=audio_bytes, model="transcribe-1-pro") except APIError as e: try: error = json.loads(e.body or "{}") @@ -527,10 +517,8 @@ async def main(): with open("speech.wav", "rb") as f: result = await client.asr.transcribe( audio=f.read(), - request_options=RequestOptions( - timeout=900, - additional_headers={"model": "transcribe-1-pro"}, - ), + model="transcribe-1-pro", + request_options=RequestOptions(timeout=900), ) print(result.text) @@ -546,12 +534,13 @@ from fishaudio.core import RequestOptions async def transcribe_all(paths): client = AsyncFishAudio() - pro = RequestOptions( - timeout=900, additional_headers={"model": "transcribe-1-pro"} - ) + options = RequestOptions(timeout=900) clips = [open(p, "rb").read() for p in paths] return await asyncio.gather(*[ - client.asr.transcribe(audio=clip, request_options=pro) for clip in clips + client.asr.transcribe( + audio=clip, model="transcribe-1-pro", request_options=options + ) + for clip in clips ]) for result in asyncio.run(transcribe_all(["speech.wav"])): diff --git a/features/speech-to-text/realtime.mdx b/features/speech-to-text/realtime.mdx index 84796b52..9fc6010d 100644 --- a/features/speech-to-text/realtime.mdx +++ b/features/speech-to-text/realtime.mdx @@ -76,7 +76,76 @@ The realtime endpoints of the [compatible APIs](/developer-guide/compat/capabili ## Quick start -The steps below use the protocol directly: you connect with any WebSocket client and exchange MessagePack messages. The Python SDK (`fish-audio-sdk` 1.5.0 or later) wraps this endpoint as `client.asr.stream_websocket()`, and the JavaScript SDK (`fish-audio` 0.2.0 or later, Node.js only) as [`client.speechToText.convertRealtime()`](/api-reference/sdk/javascript/api-reference#speech-to-text). +With the Python or TypeScript SDK, pass an iterator of audio chunks and read the events it returns. Install it with `pip install --upgrade fish-audio-sdk` or `npm install fish-audio` and set `FISH_API_KEY` in your environment. + + + +```python Python +import wave + +from fishaudio import FishAudio + +client = FishAudio() # reads FISH_API_KEY + + +def audio_chunks(): + # From a microphone, yield each chunk as you capture it. + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM, 16 kHz + while chunk := wav.readframes(640): # 40 ms + yield chunk + + +for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, drafts=True, diarize=False +): + if event.type == "draft": # live text of the open turn, not final + print("...", event.text) + elif event.type == "committed": # final transcript of the turn + print(event.text) +``` + +```typescript TypeScript +import { createReadStream } from "node:fs"; +import { FishAudioClient } from "fish-audio"; + +const client = new FishAudioClient(); // reads FISH_API_KEY + +// Raw 16-bit mono PCM at 16 kHz, 40 ms (1280 bytes) per chunk. +// From a microphone, yield each chunk as you capture it. +async function* audioChunks() { + yield* createReadStream("speech.pcm", { highWaterMark: 1280 }); +} + +const stream = client.speechToText.convertRealtime( + { sample_rate: 16000, drafts: true, diarize: false }, + audioChunks() +); + +for await (const event of stream) { + if (event.type === "draft") { + console.log("...", event.text); // live text of the open turn, not final + } else if (event.type === "committed") { + console.log(event.text); // final transcript of the turn + } +} +``` + + + +The Python example reads a WAV file and the TypeScript example reads raw PCM; to make `speech.pcm`, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -f s16le speech.pcm`. Transcripts start with a speaker tag such as `<|speaker:0|>` by default; `diarize=False` (`diarize: false` in TypeScript) gives plain text. With `AsyncFishAudio`, pass an async iterator and read the events with `async for`. + + + `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. + [`client.speechToText.convertRealtime()`](/api-reference/sdk/javascript/api-reference#speech-to-text) + requires `fish-audio` 0.2.0 or later and runs in Node.js only. For the control + methods and errors of both SDKs, see [Choose what you + receive](/developer-guide/sdk-guide/cookbook/realtime-transcription#choose-what-you-receive) + in the recipe. + + +### Without the SDK + +In other languages and in browsers, connect with any WebSocket client and exchange MessagePack messages. The SDKs do these steps for you. @@ -110,7 +179,7 @@ The steps below use the protocol directly: you connect with any WebSocket client } ``` -[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has complete, tested clients in Python and Node.js, and a browser microphone page with a server relay. +[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has a complete recipe with the Python and TypeScript SDKs, WebSocket clients in Python and Node.js, and a browser microphone page with a server relay. ## How a session works @@ -198,7 +267,7 @@ Send 16-bit little-endian PCM, mono, at 8000, 12000, 16000, 22050, 24000, 32000, ### Speakers -Transcripts contain speaker tags such as `<|speaker:0|>`, stable within a session. Strip them, or send `results.diarize: false` for plain text. Whitespace right after a tag can vary, so trim the text after you strip the tags. Transcripts can also contain sound tags such as `[laughter]` or `[pause]`. Strip them too, or send `results.tag_audio_events: false` to remove them; see [Sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags). +Transcripts contain speaker tags such as `<|speaker:0|>`, stable within a session. Strip them, or send `results.diarize: false` (`diarize=False` in the Python SDK, `diarize: false` in the TypeScript SDK) for plain text. Whitespace right after a tag can vary, so trim the text after you strip the tags. Transcripts can also contain sound tags such as `[laughter]` or `[pause]`. Strip them too, or send `results.tag_audio_events: false` to remove them; see [Sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags). ### Keys and browsers diff --git a/tests/cookbooks/specs.py b/tests/cookbooks/specs.py index 2007c248..aca1d913 100644 --- a/tests/cookbooks/specs.py +++ b/tests/cookbooks/specs.py @@ -28,6 +28,24 @@ def print(*args, **kwargs): raise """ +# The same for a recipe that uses the SDK's client.asr.stream_websocket(). +SDK_REALTIME_RUN = """ +import builtins +import pytest +from fishaudio import APIError +_lines = [] +def print(*args, **kwargs): + _lines.append(" ".join(str(a) for a in args)) + builtins.print(*args, **kwargs) +def _run(recipe): + try: + recipe() + except APIError as e: + if e.status == 403: + pytest.skip("realtime speech to text is not enabled for this key's team") + raise +""" + SPECS = [ { "slug": "streaming-to-file", @@ -67,7 +85,7 @@ def print(*args, **kwargs): ], }, # ---- recipes authored by the cookbook workflow (one live-tested primary block each) ---- - # The speech-to-text recipes select transcribe-1-pro with the `model` header. + # The speech-to-text recipes select transcribe-1-pro with the SDK's `model` argument. { "slug": "transcribe-to-captions", "path": f"{COOKBOOK}/transcribe-to-captions.mdx", @@ -171,7 +189,19 @@ def print(*args, **kwargs): "slug": "realtime-transcription", "path": f"{COOKBOOK}/realtime-transcription.mdx", "cases": [ - {"name": "stream a wav file", "block": 0, "postamble": REALTIME_RUN + """ + {"name": "stream a wav file (sdk, sync)", "block": 0, "postamble": SDK_REALTIME_RUN + """ +_run(lambda: main("speech.wav")) +assert any(line.startswith("session ") for line in _lines), _lines +assert any(line.startswith("committed") for line in _lines), _lines +assert any(line.startswith("done: ") for line in _lines), _lines +"""}, + {"name": "stream a wav file (sdk, async)", "block": 1, "postamble": SDK_REALTIME_RUN + """ +import asyncio +_run(lambda: asyncio.run(main("speech.wav"))) +assert any(line.startswith("committed") for line in _lines), _lines +assert any(line.startswith("done: ") for line in _lines), _lines +"""}, + {"name": "stream a wav file (websocket)", "block": 3, "postamble": REALTIME_RUN + """ assert any(line.startswith("session ") for line in _lines), _lines assert any(line.startswith("committed") for line in _lines), _lines assert any(line.startswith("done: ") for line in _lines), _lines