Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` (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)

**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:
Expand Down
136 changes: 134 additions & 2 deletions src/fishaudio/resources/asr.py
Original file line number Diff line number Diff line change
@@ -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, Mapping, Sequence
from typing import Any, Optional, Union

import httpx
import ormsgpack
Expand All @@ -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,
)
Expand Down Expand Up @@ -66,6 +68,48 @@ 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 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 {type(keyterms).__name__}"
)
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,
*,
Expand Down Expand Up @@ -110,6 +154,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:
Expand All @@ -121,6 +173,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 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
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
Expand Down Expand Up @@ -156,6 +225,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)
Expand All @@ -169,6 +247,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
Expand Down Expand Up @@ -317,6 +405,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:
Expand All @@ -328,6 +424,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 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
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
Expand Down Expand Up @@ -363,6 +476,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)
Expand All @@ -376,6 +498,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
Expand Down
4 changes: 3 additions & 1 deletion src/fishaudio/types/__init__.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -64,7 +64,9 @@
"Credits",
"Package",
# ASR types
"ASRDiarize",
"ASRResponse",
"ASRTextFormat",
"ASRSegment",
"SpeakerTurn",
# Realtime ASR types
Expand Down
8 changes: 7 additions & 1 deletion src/fishaudio/types/asr.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
Loading