From c1e6c201d5bb89a868e784c638075c04caeb2113 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:04:27 -0800 Subject: [PATCH 1/2] feat(asr): send the Pro model options from transcribe() The SDK points callers to transcribe-2-pro, which by default puts speaker markers (<|speaker:0|>) and event cues ([laughter]) in text, but transcribe() could not send the fields that control them, so a caller who wanted the plain transcript had to call POST /v1/asr directly. transcribe() (sync and async) now takes tag_audio_events, diarize (True, False or "auto"), num_speakers, min_speakers, max_speakers, text_format ("written" or "spoken"), verbatim and keyterms. They go in the MessagePack body typed as the API requires: booleans, integers, a boolean or "auto" for diarize, and an array of strings for keyterms. An option left as None is not sent, so a request without options is byte for byte as before. The API checks values and combinations itself and ignores fields a model does not use; the SDK only refuses keyterms given as a string, which would otherwise be sent as one term per character. --- README.md | 12 +++ src/fishaudio/resources/asr.py | 131 +++++++++++++++++++++++- src/fishaudio/types/__init__.py | 4 +- src/fishaudio/types/asr.py | 8 +- tests/unit/test_asr.py | 172 ++++++++++++++++++++++++++++++++ 5 files changed, 323 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6126dda..bf84c0a 100644 --- a/README.md +++ b/README.md @@ -217,8 +217,20 @@ for turn in result.speaker_turns or []: # Language of the transcript, when the API returns it print(result.language_code) # e.g. "en" + +# Plain transcript on transcribe-2-pro: no speaker markers, no cues such as [laughter] +with open("meeting.wav", "rb") as f: + plain = client.asr.transcribe( + audio=f.read(), + model="transcribe-2-pro", + diarize=False, + tag_audio_events=False, + ) +print(plain.text) ``` +The Pro models also take `num_speakers`, `min_speakers` and `max_speakers` (speaker-count hints), and `transcribe-2-pro` takes `text_format="spoken"` (numbers in words), `verbatim=False` (no filler words) and `keyterms=["Fish Audio", ...]` (terms to spell as listed). Options left as `None` are not sent; the API ignores those a model does not use. + [Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/speech-to-text) **Realtime (Preview):** stream live audio to `transcribe-stream-1` and get the transcript turn by turn. Send 16-bit mono PCM in 20–40 ms chunks as you capture it: diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 076b510..001b97a 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -1,7 +1,7 @@ """ASR (Automatic Speech Recognition) namespace client.""" -from collections.abc import AsyncIterable, Iterable -from typing import Optional, Union +from collections.abc import AsyncIterable, Iterable, Sequence +from typing import Any, Optional, Union import httpx import ormsgpack @@ -17,11 +17,13 @@ from fishaudio.core.client_wrapper import _handshake_headers from fishaudio.types import ( ASRContext, + ASRDiarize, ASRRealtimeConfig, ASRRealtimeControl, ASRResponse, ASRResults, ASRSampleRate, + ASRTextFormat, ASRTurnDetection, TurnDetectionMode, ) @@ -66,6 +68,43 @@ def _sent_model( return client_headers.get("model") +def _transcribe_options( + *, + tag_audio_events: Optional[bool], + diarize: Optional[ASRDiarize], + num_speakers: Optional[int], + min_speakers: Optional[int], + max_speakers: Optional[int], + text_format: Optional[ASRTextFormat], + verbatim: Optional[bool], + keyterms: Optional[Sequence[str]], +) -> dict[str, Any]: + """The Pro model fields of POST /v1/asr that the caller set. + + A field left as None is not sent, so the API applies its default. The API + checks the values and the combinations (it ignores a field the model does + not use), so they are sent as given. + """ + if isinstance(keyterms, str): + # A string is a sequence of characters: each would become a term. + raise TypeError( + "keyterms takes a list of terms, for example ['Fish Audio'], " + f"not a string: {keyterms!r}" + ) + options: dict[str, Any] = { + "tag_audio_events": tag_audio_events, + "diarize": diarize, + "num_speakers": num_speakers, + "min_speakers": min_speakers, + "max_speakers": max_speakers, + "text_format": text_format, + "verbatim": verbatim, + # MessagePack sends a list as an array, which the API requires. + "keyterms": list(keyterms) if keyterms is not None else None, + } + return {name: value for name, value in options.items() if value is not None} + + def _realtime_config( config: ASRRealtimeConfig, *, @@ -110,6 +149,14 @@ def transcribe( audio: bytes, language: Optional[str] = OMIT, include_timestamps: bool = True, + tag_audio_events: Optional[bool] = None, + diarize: Optional[ASRDiarize] = None, + num_speakers: Optional[int] = None, + min_speakers: Optional[int] = None, + max_speakers: Optional[int] = None, + text_format: Optional[ASRTextFormat] = None, + verbatim: Optional[bool] = None, + keyterms: Optional[Sequence[str]] = None, model: Optional[str] = None, request_options: Optional[RequestOptions] = None, ) -> ASRResponse: @@ -121,6 +168,23 @@ def transcribe( language: Language code (e.g., "en", "zh"). Auto-detected if not provided. include_timestamps: Whether to include timestamp information for segments (and speaker turns, on models that return them) + tag_audio_events: Pro models. False removes emotion and vocal-event + cues such as ``[laughter]`` from the text and speaker turns. + Server default: True + diarize: Pro models. False removes the ``<|speaker:N|>`` markers + from the text and omits speaker turns. Server default: "auto" + num_speakers: Pro models. Expected number of speakers, a + best-effort hint. Not with min_speakers, max_speakers or + diarize=False + min_speakers: Pro models. Lower bound on the number of speakers + max_speakers: Pro models. Upper bound on the number of speakers + text_format: transcribe-2-pro. "written" (default) or "spoken" + numbers, dates, times and amounts + verbatim: transcribe-2-pro. False leaves out filler sounds, + stutters and false starts. Server default: True + keyterms: transcribe-2-pro. Up to 128 words or short phrases, such + as names and products, to spell as listed. With keyterms, the + API may not follow text_format="spoken" or verbatim=False model: ASR model, e.g. "transcribe-2-pro" (recommended). Sent as the ``model`` header and takes precedence over one in request_options. When the outgoing request carries no ``model`` header (from @@ -156,6 +220,15 @@ def transcribe( print(result.text) for segment in result.segments: print(f"{segment.start}-{segment.end}: {segment.text}") + + # Plain transcript on transcribe-2-pro: no speaker markers, no cues + plain = client.asr.transcribe( + audio=audio_bytes, + model="transcribe-2-pro", + diarize=False, + tag_audio_events=False, + ) + print(plain.text) ``` """ requested = _requested_model(model, request_options) @@ -169,6 +242,16 @@ def transcribe( "audio": audio, "ignore_timestamps": not include_timestamps, **({"language": language} if language is not OMIT else {}), + **_transcribe_options( + tag_audio_events=tag_audio_events, + diarize=diarize, + num_speakers=num_speakers, + min_speakers=min_speakers, + max_speakers=max_speakers, + text_format=text_format, + verbatim=verbatim, + keyterms=keyterms, + ), } # Make request @@ -317,6 +400,14 @@ async def transcribe( audio: bytes, language: Optional[str] = OMIT, include_timestamps: bool = True, + tag_audio_events: Optional[bool] = None, + diarize: Optional[ASRDiarize] = None, + num_speakers: Optional[int] = None, + min_speakers: Optional[int] = None, + max_speakers: Optional[int] = None, + text_format: Optional[ASRTextFormat] = None, + verbatim: Optional[bool] = None, + keyterms: Optional[Sequence[str]] = None, model: Optional[str] = None, request_options: Optional[RequestOptions] = None, ) -> ASRResponse: @@ -328,6 +419,23 @@ async def transcribe( language: Language code (e.g., "en", "zh"). Auto-detected if not provided. include_timestamps: Whether to include timestamp information for segments (and speaker turns, on models that return them) + tag_audio_events: Pro models. False removes emotion and vocal-event + cues such as ``[laughter]`` from the text and speaker turns. + Server default: True + diarize: Pro models. False removes the ``<|speaker:N|>`` markers + from the text and omits speaker turns. Server default: "auto" + num_speakers: Pro models. Expected number of speakers, a + best-effort hint. Not with min_speakers, max_speakers or + diarize=False + min_speakers: Pro models. Lower bound on the number of speakers + max_speakers: Pro models. Upper bound on the number of speakers + text_format: transcribe-2-pro. "written" (default) or "spoken" + numbers, dates, times and amounts + verbatim: transcribe-2-pro. False leaves out filler sounds, + stutters and false starts. Server default: True + keyterms: transcribe-2-pro. Up to 128 words or short phrases, such + as names and products, to spell as listed. With keyterms, the + API may not follow text_format="spoken" or verbatim=False model: ASR model, e.g. "transcribe-2-pro" (recommended). Sent as the ``model`` header and takes precedence over one in request_options. When the outgoing request carries no ``model`` header (from @@ -363,6 +471,15 @@ async def transcribe( print(result.text) for segment in result.segments: print(f"{segment.start}-{segment.end}: {segment.text}") + + # Plain transcript on transcribe-2-pro: no speaker markers, no cues + plain = await client.asr.transcribe( + audio=audio_bytes, + model="transcribe-2-pro", + diarize=False, + tag_audio_events=False, + ) + print(plain.text) ``` """ requested = _requested_model(model, request_options) @@ -376,6 +493,16 @@ async def transcribe( "audio": audio, "ignore_timestamps": not include_timestamps, **({"language": language} if language is not OMIT else {}), + **_transcribe_options( + tag_audio_events=tag_audio_events, + diarize=diarize, + num_speakers=num_speakers, + min_speakers=min_speakers, + max_speakers=max_speakers, + text_format=text_format, + verbatim=verbatim, + keyterms=keyterms, + ), } # Make request diff --git a/src/fishaudio/types/__init__.py b/src/fishaudio/types/__init__.py index 34cfaaf..ab92b3b 100644 --- a/src/fishaudio/types/__init__.py +++ b/src/fishaudio/types/__init__.py @@ -1,7 +1,7 @@ """Type definitions for the Fish Audio SDK.""" from .account import Credits, Package -from .asr import ASRResponse, ASRSegment, SpeakerTurn +from .asr import ASRDiarize, ASRResponse, ASRSegment, ASRTextFormat, SpeakerTurn from .asr_realtime import ( ASRAgentSpeakingEvent, ASRCommittedEvent, @@ -64,7 +64,9 @@ "Credits", "Package", # ASR types + "ASRDiarize", "ASRResponse", + "ASRTextFormat", "ASRSegment", "SpeakerTurn", # Realtime ASR types diff --git a/src/fishaudio/types/asr.py b/src/fishaudio/types/asr.py index 4f2ca6e..5f1faef 100644 --- a/src/fishaudio/types/asr.py +++ b/src/fishaudio/types/asr.py @@ -1,12 +1,18 @@ """ASR (Automatic Speech Recognition) related types.""" -from typing import Optional +from typing import Literal, Optional, Union import httpx from pydantic import BaseModel from .shared import _get_response_headers +# Speaker identification on HTTP transcription: True, False, or the server's +# default "auto". False removes speaker markers and speaker turns. +ASRDiarize = Union[bool, Literal["auto"]] +# How transcribe-2-pro writes numbers, dates, times and amounts. +ASRTextFormat = Literal["written", "spoken"] + class ASRSegment(BaseModel): """A timestamped segment of transcribed text. diff --git a/tests/unit/test_asr.py b/tests/unit/test_asr.py index c425bb0..d8ef069 100644 --- a/tests/unit/test_asr.py +++ b/tests/unit/test_asr.py @@ -371,3 +371,175 @@ async def test_model_is_sent_as_header_async(self, sample_asr_response): assert seen[0].headers["model"] == "transcribe-1-pro" assert "model" not in seen[1].headers + + +class TestTranscribeProOptions: + """The Pro model fields, checked on the body of the HTTP request that + leaves the client: MessagePack, typed as the API requires.""" + + @staticmethod + def _sync(seen, response): + def handler(request): + seen.append(request) + return httpx.Response(200, json=response) + + return FishAudio( + api_key="test-key", + httpx_client=httpx.Client( + base_url="https://api.test.fish.audio", + transport=httpx.MockTransport(handler), + ), + ) + + @staticmethod + def _async(seen, response): + def handler(request): + seen.append(request) + return httpx.Response(200, json=response) + + return AsyncFishAudio( + api_key="test-key", + httpx_client=httpx.AsyncClient( + base_url="https://api.test.fish.audio", + transport=httpx.MockTransport(handler), + ), + ) + + # No model, as before: the no-model notice is not what is tested here. + @pytest.mark.filterwarnings("ignore::FutureWarning") + def test_without_options_the_body_is_unchanged(self, sample_asr_response): + # The exact bytes the SDK sent before these options existed. + seen = [] + self._sync(seen, sample_asr_response).asr.transcribe( + audio=b"fake_audio", language="en" + ) + assert seen[0].content == ormsgpack.packb( + {"audio": b"fake_audio", "ignore_timestamps": False, "language": "en"} + ) + + @pytest.mark.parametrize( + ("options", "sent"), + [ + ({"tag_audio_events": False}, {"tag_audio_events": False}), + ({"diarize": False}, {"diarize": False}), + ({"diarize": True}, {"diarize": True}), + ({"diarize": "auto"}, {"diarize": "auto"}), + ({"num_speakers": 2}, {"num_speakers": 2}), + ( + {"min_speakers": 1, "max_speakers": 3}, + {"min_speakers": 1, "max_speakers": 3}, + ), + ({"text_format": "spoken"}, {"text_format": "spoken"}), + ({"verbatim": False}, {"verbatim": False}), + ( + {"keyterms": ["Kubernetes", "Fish Audio"]}, + {"keyterms": ["Kubernetes", "Fish Audio"]}, + ), + ({"keyterms": ("Fish Audio",)}, {"keyterms": ["Fish Audio"]}), + ({"keyterms": []}, {"keyterms": []}), + ], + ) + def test_each_option_reaches_the_body_typed( + self, sample_asr_response, options, sent + ): + seen = [] + self._sync(seen, sample_asr_response).asr.transcribe( + audio=b"fake_audio", model="transcribe-2-pro", **options + ) + body = ormsgpack.unpackb(seen[0].content) + assert body == {"audio": b"fake_audio", "ignore_timestamps": False, **sent} + for name, value in sent.items(): + assert type(body[name]) is type(value) # bool stays bool, list an array + + def test_all_options_together(self, sample_asr_response): + seen = [] + options = { + "tag_audio_events": False, + "diarize": True, + "num_speakers": 2, + "text_format": "written", + "verbatim": True, + "keyterms": ["Fish Audio"], + } + self._sync(seen, sample_asr_response).asr.transcribe( + audio=b"a", model="transcribe-2-pro", include_timestamps=False, **options + ) + assert ormsgpack.unpackb(seen[0].content) == { + "audio": b"a", + "ignore_timestamps": True, + **options, + } + + def test_keyterms_as_a_string_is_refused_before_sending(self, sample_asr_response): + seen = [] + client = self._sync(seen, sample_asr_response) + with pytest.raises(TypeError, match="list of terms"): + client.asr.transcribe( + audio=b"a", model="transcribe-2-pro", keyterms="Fish Audio" + ) + assert seen == [] + + @pytest.mark.asyncio + async def test_async_sends_the_same_body(self, sample_asr_response): + seen_sync, seen_async = [], [] + options = { + "diarize": False, + "tag_audio_events": False, + "text_format": "spoken", + "verbatim": False, + "keyterms": ("Kubernetes",), + } + self._sync(seen_sync, sample_asr_response).asr.transcribe( + audio=b"a", model="transcribe-2-pro", **options + ) + client = self._async(seen_async, sample_asr_response) + await client.asr.transcribe(audio=b"a", model="transcribe-2-pro", **options) + assert seen_async[0].content == seen_sync[0].content + assert ormsgpack.unpackb(seen_async[0].content)["keyterms"] == ["Kubernetes"] + + # No model, as before: the no-model notice is not what is tested here. + @pytest.mark.filterwarnings("ignore::FutureWarning") + @pytest.mark.asyncio + async def test_async_without_options_the_body_is_unchanged( + self, sample_asr_response + ): + seen = [] + await self._async(seen, sample_asr_response).asr.transcribe(audio=b"a") + assert seen[0].content == ormsgpack.packb( + {"audio": b"a", "ignore_timestamps": False} + ) + + @pytest.mark.asyncio + async def test_async_keyterms_as_a_string_is_refused(self, sample_asr_response): + seen = [] + client = self._async(seen, sample_asr_response) + with pytest.raises(TypeError, match="list of terms"): + await client.asr.transcribe( + audio=b"a", model="transcribe-2-pro", keyterms="Fish Audio" + ) + assert seen == [] + + def test_speaker_turns_parse(self): + seen = [] + response = { + "text": "<|speaker:0|> Hi. <|speaker:1|> [excited] Yes!", + "duration": 4.2, + "segments": [{"text": "Hi", "start": 0.08, "end": 0.4}], + "speaker_turns": [ + {"speaker": "speaker:0", "text": "Hi.", "start": 0.08, "end": 0.4}, + { + "speaker": "speaker:1", + "text": "[excited] Yes!", + "start": 1.0, + "end": 1.6, + }, + ], + "request_id": "r", + } + result = self._sync(seen, response).asr.transcribe( + audio=b"a", model="transcribe-2-pro" + ) + assert [(t.speaker, t.text) for t in result.speaker_turns] == [ + ("speaker:0", "Hi."), + ("speaker:1", "[excited] Yes!"), + ] From 2fdf084302d7934a85bbb05c84e7488b4c58a7d5 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:15:48 -0800 Subject: [PATCH 2/2] fix(asr): refuse keyterms that are not a sequence of terms, without echoing them list() turned a dict into its keys and a string into its characters, and the API accepts either. keyterms must now be a sequence that is not a str, bytes or mapping (a list, a tuple or another Sequence); anything else raises TypeError before sending. The message names the type and shows the right form, but not the value: a glossary can hold customer or product names, and exceptions get logged. The terms themselves stay the API's to check. The README and docstrings say that verbatim=False asks the model to leave out fillers and false starts. --- README.md | 2 +- src/fishaudio/resources/asr.py | 21 ++++++++++++------- tests/unit/test_asr.py | 38 +++++++++++++++++++++++++++++----- 3 files changed, 47 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index bf84c0a..f52f541 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,7 @@ with open("meeting.wav", "rb") as f: print(plain.text) ``` -The Pro models also take `num_speakers`, `min_speakers` and `max_speakers` (speaker-count hints), and `transcribe-2-pro` takes `text_format="spoken"` (numbers in words), `verbatim=False` (no filler words) and `keyterms=["Fish Audio", ...]` (terms to spell as listed). Options left as `None` are not sent; the API ignores those a model does not use. +The Pro models also take `num_speakers`, `min_speakers` and `max_speakers` (speaker-count hints), and `transcribe-2-pro` takes `text_format="spoken"` (numbers in words), `verbatim=False` (asks the model to leave out fillers and false starts) and `keyterms=["Fish Audio", ...]` (terms to spell as listed). Options left as `None` are not sent; the API ignores those a model does not use. [Learn more](https://docs.fish.audio/developer-guide/sdk-guide/python/speech-to-text) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 001b97a..db28cb5 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -1,6 +1,6 @@ """ASR (Automatic Speech Recognition) namespace client.""" -from collections.abc import AsyncIterable, Iterable, Sequence +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence from typing import Any, Optional, Union import httpx @@ -85,11 +85,16 @@ def _transcribe_options( checks the values and the combinations (it ignores a field the model does not use), so they are sent as given. """ - if isinstance(keyterms, str): - # A string is a sequence of characters: each would become a term. + if keyterms is not None and ( + isinstance(keyterms, (str, bytes, Mapping)) + or not isinstance(keyterms, Sequence) + ): + # list() would turn a string into one term per character and a dict + # into its keys, and the API would accept either. The message leaves + # the value out: a glossary can hold customer or product names. raise TypeError( "keyterms takes a list of terms, for example ['Fish Audio'], " - f"not a string: {keyterms!r}" + f"not {type(keyterms).__name__}" ) options: dict[str, Any] = { "tag_audio_events": tag_audio_events, @@ -180,8 +185,8 @@ def transcribe( max_speakers: Pro models. Upper bound on the number of speakers text_format: transcribe-2-pro. "written" (default) or "spoken" numbers, dates, times and amounts - verbatim: transcribe-2-pro. False leaves out filler sounds, - stutters and false starts. Server default: True + verbatim: transcribe-2-pro. False asks the model to leave out + filler sounds, stutters and false starts. Server default: True keyterms: transcribe-2-pro. Up to 128 words or short phrases, such as names and products, to spell as listed. With keyterms, the API may not follow text_format="spoken" or verbatim=False @@ -431,8 +436,8 @@ async def transcribe( max_speakers: Pro models. Upper bound on the number of speakers text_format: transcribe-2-pro. "written" (default) or "spoken" numbers, dates, times and amounts - verbatim: transcribe-2-pro. False leaves out filler sounds, - stutters and false starts. Server default: True + verbatim: transcribe-2-pro. False asks the model to leave out + filler sounds, stutters and false starts. Server default: True keyterms: transcribe-2-pro. Up to 128 words or short phrases, such as names and products, to spell as listed. With keyterms, the API may not follow text_format="spoken" or verbatim=False diff --git a/tests/unit/test_asr.py b/tests/unit/test_asr.py index d8ef069..b606f3d 100644 --- a/tests/unit/test_asr.py +++ b/tests/unit/test_asr.py @@ -470,14 +470,42 @@ def test_all_options_together(self, sample_asr_response): **options, } - def test_keyterms_as_a_string_is_refused_before_sending(self, sample_asr_response): + @pytest.mark.parametrize( + "keyterms", + [ + "Acme Secret Product", + b"Acme Secret Product", + {"terms": ["Acme Secret Product"]}, + {"Acme Secret Product"}, + (term for term in ["Acme Secret Product"]), + ], + ids=["str", "bytes", "dict", "set", "generator"], + ) + def test_keyterms_not_a_sequence_of_terms_is_refused( + self, sample_asr_response, keyterms + ): seen = [] client = self._sync(seen, sample_asr_response) - with pytest.raises(TypeError, match="list of terms"): + with pytest.raises(TypeError, match="list of terms") as exc_info: client.asr.transcribe( - audio=b"a", model="transcribe-2-pro", keyterms="Fish Audio" + audio=b"a", model="transcribe-2-pro", keyterms=keyterms ) assert seen == [] + # A glossary can hold names that must not end up in logs. + assert "Acme" not in str(exc_info.value) + + def test_keyterms_other_sequences_are_sent_as_an_array(self, sample_asr_response): + import collections + + seen = [] + client = self._sync(seen, sample_asr_response) + client.asr.transcribe( + audio=b"a", + model="transcribe-2-pro", + keyterms=collections.UserList(["Fish Audio", ""]), + ) + # The terms themselves are the API's to check. + assert ormsgpack.unpackb(seen[0].content)["keyterms"] == ["Fish Audio", ""] @pytest.mark.asyncio async def test_async_sends_the_same_body(self, sample_asr_response): @@ -510,12 +538,12 @@ async def test_async_without_options_the_body_is_unchanged( ) @pytest.mark.asyncio - async def test_async_keyterms_as_a_string_is_refused(self, sample_asr_response): + async def test_async_keyterms_as_a_dict_is_refused(self, sample_asr_response): seen = [] client = self._async(seen, sample_asr_response) with pytest.raises(TypeError, match="list of terms"): await client.asr.transcribe( - audio=b"a", model="transcribe-2-pro", keyterms="Fish Audio" + audio=b"a", model="transcribe-2-pro", keyterms={"terms": ["Fish Audio"]} ) assert seen == []