Skip to content
Draft
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
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ print(result.language_code) # e.g. "en"

[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:
**Realtime:** stream live audio and get the transcript turn by turn, with `transcribe-stream-1` (Preview, the default) or `transcribe-stream-2`. Send 16-bit mono PCM in 20–40 ms chunks as you capture it:

```python
import wave
Expand All @@ -228,6 +228,18 @@ for event in client.asr.stream_websocket(
print(event.text)
```

To use `transcribe-stream-2`, pass `model="transcribe-stream-2"`. It also takes `text_format`, the style for numbers, amounts and times: `"written"` (the default, "$25 at 3:30 PM") or `"spoken"` ("twenty-five dollars at three thirty PM"). `transcribe-stream-1` refuses `text_format`.

```python
for event in client.asr.stream_websocket(
audio_chunks(), model="transcribe-stream-2", text_format="spoken"
):
if event.type == "session_started":
print(event.config["model"]) # the model serving this session
elif event.type == "committed":
print(event.text)
```

With `AsyncFishAudio`, pass an async iterator and use `async for`. The returned stream also sends control messages during the session, such as `stream.finalize()` for push-to-talk and `stream.agent_speaking(True)` for voice agents.

[Learn more](https://docs.fish.audio/features/speech-to-text/realtime)
Expand Down
36 changes: 33 additions & 3 deletions src/fishaudio/resources/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import ormsgpack
from httpx_ws import aconnect_ws, connect_ws
from pydantic import TypeAdapter

from fishaudio.core import (
OMIT,
Expand All @@ -21,6 +22,7 @@
ASRResponse,
ASRResults,
ASRSampleRate,
ASRTextFormat,
ASRTurnDetection,
TurnDetectionMode,
)
Expand All @@ -47,6 +49,11 @@ def _requested_model(
return None


# Checks the direct text_format argument as ASRResults(text_format=...) would,
# so a typo fails before the connection opens.
_TEXT_FORMAT = TypeAdapter(ASRTextFormat)


def _realtime_config(
config: ASRRealtimeConfig,
*,
Expand All @@ -56,6 +63,7 @@ def _realtime_config(
drafts: Optional[bool],
diarize: Optional[bool],
terms: Optional[list[str]],
text_format: Optional[ASRTextFormat] = None,
) -> ASRRealtimeConfig:
"""Apply direct parameters on top of config (they win when provided)."""
config = config.model_copy(deep=True)
Expand All @@ -67,12 +75,14 @@ def _realtime_config(
config.turn_detection.mode = turn_detection
if eager is not None:
config.turn_detection.eager = eager
if drafts is not None or diarize is not None:
if drafts is not None or diarize is not None or text_format is not None:
config.results = config.results or ASRResults()
if drafts is not None:
config.results.drafts = drafts
if diarize is not None:
config.results.diarize = diarize
if text_format is not None:
config.results.text_format = _TEXT_FORMAT.validate_python(text_format)
if terms is not None:
config.context = config.context or ASRContext()
config.context.terms = terms
Expand Down Expand Up @@ -169,6 +179,7 @@ def stream_websocket(
drafts: Optional[bool] = None,
diarize: Optional[bool] = None,
terms: Optional[list[str]] = None,
text_format: Optional[ASRTextFormat] = None,
config: ASRRealtimeConfig = ASRRealtimeConfig(), # noqa: B008 - copied before use
model: str = "transcribe-stream-1",
ws_options: Optional[WebSocketOptions] = None,
Expand Down Expand Up @@ -204,8 +215,16 @@ def stream_websocket(
(overrides config.results.diarize if provided)
terms: Names, products and jargon to recognize
(overrides config.context.terms if provided)
text_format: ``transcribe-stream-2`` only. The style for numbers, amounts
and times: "written" (digits and symbols, the server default) or
"spoken" (words, the way they were said). ``transcribe-stream-1``
refuses it with invalid_config. Not sent when None
(overrides config.results.text_format if provided)
config: Session configuration (audio, turn detection, results, context)
model: Realtime speech-to-text model
model: Realtime speech-to-text model: "transcribe-stream-1" (Preview,
the default) or "transcribe-stream-2". Any other value gets a
transcribe-stream-1 session; the started event's
``config["model"]`` names the model that serves the session
ws_options: WebSocket connection options for configuring timeouts, message size limits, etc.
See WebSocketOptions class for available parameters.

Expand Down Expand Up @@ -271,6 +290,7 @@ def audio_chunks():
drafts=drafts,
diarize=diarize,
terms=terms,
text_format=text_format,
),
audio_stream,
)
Expand Down Expand Up @@ -366,6 +386,7 @@ def stream_websocket(
drafts: Optional[bool] = None,
diarize: Optional[bool] = None,
terms: Optional[list[str]] = None,
text_format: Optional[ASRTextFormat] = None,
config: ASRRealtimeConfig = ASRRealtimeConfig(), # noqa: B008 - copied before use
model: str = "transcribe-stream-1",
ws_options: Optional[WebSocketOptions] = None,
Expand Down Expand Up @@ -401,8 +422,16 @@ def stream_websocket(
(overrides config.results.diarize if provided)
terms: Names, products and jargon to recognize
(overrides config.context.terms if provided)
text_format: ``transcribe-stream-2`` only. The style for numbers, amounts
and times: "written" (digits and symbols, the server default) or
"spoken" (words, the way they were said). ``transcribe-stream-1``
refuses it with invalid_config. Not sent when None
(overrides config.results.text_format if provided)
config: Session configuration (audio, turn detection, results, context)
model: Realtime speech-to-text model
model: Realtime speech-to-text model: "transcribe-stream-1" (Preview,
the default) or "transcribe-stream-2". Any other value gets a
transcribe-stream-1 session; the started event's
``config["model"]`` names the model that serves the session
ws_options: WebSocket connection options for configuring timeouts, message size limits, etc.
See WebSocketOptions class for available parameters.

Expand Down Expand Up @@ -468,6 +497,7 @@ async def audio_chunks():
drafts=drafts,
diarize=diarize,
terms=terms,
text_format=text_format,
),
audio_stream,
)
2 changes: 2 additions & 0 deletions src/fishaudio/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
ASRSessionStartedEvent,
ASRSessionStats,
ASRSpeechStartEvent,
ASRTextFormat,
ASRTurnDetection,
ASRTurnResumedEvent,
ASRUserBackchannelEvent,
Expand Down Expand Up @@ -97,6 +98,7 @@
"ASRUserTurnTakenEvent",
"ASRVadEvent",
"ASRWord",
"ASRTextFormat",
"TurnDetectionMode",
# Shared types
"AudioFormat",
Expand Down
10 changes: 10 additions & 0 deletions src/fishaudio/types/asr_realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

ASRSampleRate = Literal[8000, 12000, 16000, 22050, 24000, 32000, 44100, 48000]
TurnDetectionMode = Literal["auto", "vad", "manual"]
ASRTextFormat = Literal["spoken", "written"]


# Session configuration
Expand Down Expand Up @@ -43,6 +44,14 @@ class ASRResults(BaseModel):
ignore_timestamps: False adds word timings to committed events. Server default: True
diarize: Speaker tags such as ``<|speaker:0|>`` in the text. Server default: True
tag_audio_events: Sound tags such as ``[laughter]`` in the text. Server default: True
text_format: ``transcribe-stream-2`` only. The style for numbers, amounts
and times: "written" (digits and symbols, "$25 at 3:30 pm") or "spoken"
(words, "twenty five dollars at three thirty pm"). Server default:
"written". ``transcribe-stream-1`` refuses the field: in the session's
config, with an invalid_config error that ends the session
(ASRRealtimeError); in a mid-session ``configure``, with a configured
event whose ok is False, and the session goes on without any of that
update applied
vad_events: Send vad events (voice activity, up to 10 per second). Server default: False
eot_events: Send eot_prob events (end-of-turn likelihood). Server default: False
"""
Expand All @@ -51,6 +60,7 @@ class ASRResults(BaseModel):
ignore_timestamps: Optional[bool] = None
diarize: Optional[bool] = None
tag_audio_events: Optional[bool] = None
text_format: Optional[ASRTextFormat] = None
vad_events: Optional[bool] = None
eot_events: Optional[bool] = None

Expand Down
35 changes: 35 additions & 0 deletions tests/unit/test_asr_realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,41 @@ def test_diarize_keeps_other_result_settings(self):
assert merged.results == ASRResults(drafts=True, diarize=False)
assert base.results.diarize is True

def test_text_format_is_sent_only_when_set(self):
def results_sent(**kw):
merged = _realtime_config(
ASRRealtimeConfig(results=ASRResults(drafts=True)),
sample_rate=None,
turn_detection=None,
eager=None,
drafts=None,
diarize=None,
terms=None,
**kw,
)
return ormsgpack.unpackb(encode_config(merged))["results"]

# transcribe-stream-1 refuses the field, even null, so None must omit it.
assert results_sent() == {"drafts": True}
assert results_sent(text_format=None) == {"drafts": True}
assert results_sent(text_format="spoken") == {
"drafts": True,
"text_format": "spoken",
}

def test_text_format_argument_is_validated_like_the_model_field(self):
with pytest.raises(ValueError):
_realtime_config(
ASRRealtimeConfig(),
sample_rate=None,
turn_detection=None,
eager=None,
drafts=None,
diarize=None,
terms=None,
text_format="Written", # type: ignore[arg-type]
)

def test_audio_is_packed_as_msgpack_bin(self):
packed = encode_message(b"\x01\x02\x03")
assert ormsgpack.unpackb(packed) == {"type": "audio", "data": b"\x01\x02\x03"}
Expand Down