Skip to content
Open
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
15 changes: 15 additions & 0 deletions examples/rt/async/speaker_id/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Live Real-Time Speaker ID Example

This example demonstrates how to use the Speechmatics Python SDK to perform speaker ID in real-time.

The SDK requires an API key to be set as an environment variable before it can be used. You can obtain an API key by signing up for a Speechmatics account at https://portal.speechmatics.com/dashboard

## Prerequisites

- Install Speechmatics RT SDK: `pip install speechmatics-rt`
- Export Speechmatics API key: `export SPEECHMATICS_API_KEY=YOUR-API-KEY`

## Usage

- Generate speaker IDs: `python generate.py` - this will generate a `speakers.json` file
- Transcribe audio: `python transcribe.py` - this will use the `speakers.json` file to perform speaker ID on a conversation
56 changes: 56 additions & 0 deletions examples/rt/async/speaker_id/generate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import asyncio
import logging
import os
import json

from speechmatics.rt import (
AsyncClient,
OperatingPoint,
TranscriptionConfig,
ServerMessageType,
)


logging.basicConfig(level=logging.INFO)


speakers: list[dict] = []


async def generate_ids(voice_file: str) -> None:
"""Run async transcription example."""

transcription_config = TranscriptionConfig(
operating_point=OperatingPoint.ENHANCED,
diarization="speaker",
)

# Initialize client with API key from environment
async with AsyncClient() as client:
try:
@client.on(ServerMessageType.SPEAKERS_RESULT)
def handle_speakers_result(msg):
new_speakers = msg.get('speakers', [])
new_speakers[0]["label"] = voice_file
speakers.append(new_speakers[0])

# Transcribe audio file
with open(os.path.join(voices_folder, voice_file), "rb") as audio_file:
await client.transcribe(
audio_file,
transcription_config=transcription_config,
get_speakers=True,
)
except Exception as e:
print(f"Transcription error: {e}")


if __name__ == "__main__":
voices_folder = "./examples/rt/async/speaker_id/voices"
voice_files = [f for f in os.listdir(voices_folder) if os.path.isfile(os.path.join(voices_folder, f))]

for voice_file in voice_files:
asyncio.run(generate_ids(voice_file))

with open('./speakers.json', 'w') as f:
json.dump(speakers, f)
51 changes: 51 additions & 0 deletions examples/rt/async/speaker_id/transcribe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import asyncio
import logging
import json

from speechmatics.rt import SpeakerIdentifier
from speechmatics.rt import SpeakerDiarizationConfig
from speechmatics.rt import (
AsyncClient,
OperatingPoint,
TranscriptionConfig,
ServerMessageType
)


logging.basicConfig(level=logging.INFO)


async def main() -> None:
"""Run async transcription example."""

with open('./speakers.json') as f:
speaker_identifiers = [SpeakerIdentifier(**s) for s in json.load(f)]

transcription_config = TranscriptionConfig(
operating_point=OperatingPoint.ENHANCED,
diarization="speaker",
max_delay=4,
speaker_diarization_config=SpeakerDiarizationConfig(
speakers=speaker_identifiers,
)
)

# Initialize client with API key from environment
async with AsyncClient() as client:
try:
@client.on(ServerMessageType.ADD_TRANSCRIPT)
def handle_finals(msg):
print(f"Final: {msg['metadata']['speaker']} {msg['metadata']['transcript']}")

# Transcribe audio file
with open("./examples/conversation.wav", "rb") as audio_file:
await client.transcribe(
audio_file,
transcription_config=transcription_config,
)
except Exception as e:
print(f"Transcription error: {e}")


if __name__ == "__main__":
asyncio.run(main())
2 changes: 2 additions & 0 deletions sdk/batch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pip install speechmatics-batch

### Quick Start

To run transcription, you'll need an audio file. You can find an example file [here](https://github.com/speechmatics/speechmatics-python-sdk/blob/main/examples/example.wav).

```python
import asyncio
from speechmatics.batch import AsyncClient
Expand Down
2 changes: 2 additions & 0 deletions sdk/rt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pip install speechmatics-rt
```
## Quick Start

To run transcription, you'll need an audio file. You can find an example file [here](https://github.com/speechmatics/speechmatics-python-sdk/blob/main/examples/example.wav).

```python
import asyncio
from speechmatics.rt import AsyncClient, ServerMessageType
Expand Down
5 changes: 5 additions & 0 deletions sdk/rt/speechmatics/rt/_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ async def transcribe(
audio_events_config: Optional[AudioEventsConfig] = None,
ws_headers: Optional[dict] = None,
timeout: Optional[float] = None,
get_speakers: Optional[bool] = False,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think get speakers should be enabled by default when speaker diarization is requested rather than having an additional parameter to enable it. The user who does't need it can easily ignore it and the user who needs it can capture it just like any other message using an event handler.

This makes get_speakers function redundant as you don't have to teach the user how to enable it and how to capture it, only how to capture it. And how to capture it is already demonstrated in the example.

Copy link
Contributor

@dln22 dln22 Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it depends what type of diarization is requested as it must be set as "speaker" or "channel_and_speaker" only for the speaker id to work. I am in the process of adding the get_speakers flag to our rt and batch transcribers, It will be part of the speaker_diarization_config. Note that enabling speaker id by default, whenever diarization is enabled has its pros and cons - e.g. customers who don't want them would still receive the speaker id messages, just saying. I have tried to turn all the speaker id related errors into warnings as not to disrupt normal transcription job, so I think it will be still safe to auto-enable it. However, the moment we miss something, there will be no way for customers to disable speaker id if diarization is enabled . Hmm, I’m leaning slightly against auto-enabling it, explicit configuration feels safer and more transparent (just my thoughts atm)? So there are indeed pros and cons to that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's possible that I'm missing some context here but when requested SpeakersResult message is only sent once at the end of the session? So it shouldn't cause any issues..

But since you're updating the transcriber to be enabled via speaker_diarization_config we should hold off on merging this change

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say we don't want to auto-enable, as speaker IDs are a form of biometics and storing and handling them has legal consequences beyond our usual transcripts. There's a risk if it's auto-enabled, that customers would receive and even store biometrics without being aware of it, and that could possibly place us in an awkward position? My instinct would be in general that we should err on the side of forcing people to request biometrics rather than assume they want them.

Separately, @dln22 when will the get_speakers flag be added to speaker_diarization_config? Just wondering if we want to merge this in the meantime or whether it's better to hold off on the additional flag until it's in the transcriber?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TudorCRL My changes have been merged already, but not yet officially released. Will let you know once that happens.

) -> None:
"""
Transcribe a single audio stream in real-time.
Expand All @@ -193,6 +194,7 @@ async def transcribe(
ws_headers: Additional headers to include in the WebSocket handshake.
timeout: Maximum time in seconds to wait for transcription completion.
Default None.
get_speakers: Send a speaker identifier event at the end of the session.

Raises:
AudioError: If source is invalid or cannot be read.
Expand Down Expand Up @@ -233,6 +235,9 @@ async def transcribe(
ws_headers=ws_headers,
)

if get_speakers:
await self.send_message({"message": "GetSpeakers", "final": True})

try:
await asyncio.wait_for(
self._audio_producer(source, audio_format.chunk_size),
Expand Down
32 changes: 32 additions & 0 deletions sdk/rt/speechmatics/rt/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
from ._models import AudioEventsConfig
from ._models import AudioFormat
from ._models import ConnectionConfig
from ._models import ServerMessageType
from ._models import SessionInfo
from ._models import SpeakerIdentifier
from ._models import TranscriptionConfig
from ._models import TranslationConfig
from ._transport import Transport
Expand Down Expand Up @@ -149,6 +151,36 @@ async def send_message(self, message: dict[str, Any]) -> None:
self._closed_evt.set()
raise

async def get_speakers(self, final=False) -> list[SpeakerIdentifier]:
"""
Get the list of speakers in the current session.
This method returns as soon as a SPEAKERS_RESULT message is received.
Multiple requests to the method may therefore cause a race condition in which the same
SPEAKERS_RESULT message is received by multiple requests. This should not cause any issues,
but will result in redundant SPEAKERS_RESULT events.

Args:
final: Whether to wait to the end of the session to return speaker IDs (default: False)

Returns:
List of SpeakerIdentifier objects
"""
try:
await self.send_message({"message": "GetSpeakers", "final": final})
speaker_evt = asyncio.Event()
speaker_identifiers: list[SpeakerIdentifier] = []
self.once(
ServerMessageType.SPEAKERS_RESULT,
lambda msg: (speaker_identifiers.extend(msg.get("speakers", [])), speaker_evt.set()),
)
await speaker_evt.wait()
return speaker_identifiers
except asyncio.TimeoutError:
raise TransportError("Timeout waiting for SPEAKERS_RESULT")
except Exception:
self._closed_evt.set()
raise

async def _recv_loop(self) -> None:
"""
Background task that continuously receives and dispatches server messages.
Expand Down