SDKs

Python

Transcribe audio, build speaker timelines, and synthesize speech from Python with humain-voice 0.18.1.

Install

python -m pip install humain-voice==0.18.1

Configure a client

Each workflow has its own client; import stt, tts, and agent from humain_voice. Every client takes these keyword arguments:

NameTypeDefaultMeaning
api_urlstrRequiredService base URL.
api_keystrRequiredAPI key.
api_pathstr/socket.ioSocket.IO path. Every client except batch.
api_versionstrv1REST version. BatchTranscribeClient only.

Examples read these from API_URL, API_KEY, API_PATH, and API_VERSION; see Connection settings.

WorkflowClientClean up with
Batch transcriptionstt.BatchTranscribeClientclose()
Fast transcriptionstt.FastTranscriptionClientclose()
Realtime transcriptionstt.RealtimeClientdisconnect()
Live diarizationstt.RealtimeDiarizationClientdisconnect()
Text to speechtts.TTSClientclose()
Voice Agent sessionsagent.AgentClientclose()

Open every client with async with; Socket.IO clients connect on entry, so a bad key fails there. Callbacks must be plain, non-blocking functions: the SDK doesn't await them. Language and model values are in Models and voices.

Sync and async variants

Client methods are coroutines. Some have a blocking _sync twin:

ClientSync methods
BatchTranscribeClientsubmit_sync(), get_result_sync(), transcribe_sync(), close_sync()
FastTranscriptionClienttranscribe_sync(), close_sync()
RealtimeClientstart_stream_sync(); stream send_sync(), close_sync(), stop_sync()
RealtimeDiarizationClientstart_stream_sync(); stream send_sync(), close_sync()
TTSClientlist_voices_sync(), synthesize_sync(), close_sync()
AgentClientcreate_session_sync(), close_sync()

Use _sync methods only from synchronous code, with a plain with, and don't mix them with coroutines on one client.

Batch transcription

transcribe(audio, lang, ...) uploads a complete file, polls until the job is done, and returns the transcript with word offsets. To poll from a worker, call submit(audio, lang, ...), then get_result(job_id, lang, save_result=False) until done, failed, or cleared (see Batch is a job). Arguments after lang are keyword-only.

NameTypeDefaultMeaning
audiobytes, path (str or Path), or binary fileRequiredAudio to upload.
langstt.Language or strRequiredSpoken language.
asrstt.BatchTranscriptionModel or strNoneASR model.
diarizationBatchDiarizationNoneOn, D1, or D2 labels speakers. Enum only.
itnboolNoneInverse text normalization.
redactBatchRedactNoneBatchRedact.On turns on redaction. Enum only.
save_resultboolFalseKeep the result readable after it's fetched; see Read the result again. Not on submit().
poll_intervalfloat2.0Seconds between result reads. transcribe() only.
timeout_secondsfloat300.0Polling limit in seconds. transcribe() only.
on_progressCallable[[TranscriptionResponse], None]NoneCalled with each result read. transcribe() only.

Import BatchDiarization, BatchRedact, and TranscriptionResponse from humain_voice.stt.batchtranscription.

batch_transcription.py
from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

from humain_voice import stt
from humain_voice.stt.batchtranscription import BatchDiarization


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


async def main() -> None:
    input_path = Path(sys.argv[1] if len(sys.argv) > 1 else "recording.wav")
    output_path = Path(sys.argv[2] if len(sys.argv) > 2 else "recording.vtt")

    async with stt.BatchTranscribeClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_version=os.environ.get("API_VERSION", "v1"),
    ) as client:
        result = await client.transcribe(
            input_path,
            lang=stt.Language.ArEn,
            asr=stt.BatchTranscriptionModel.BayanArEn,
            diarization=BatchDiarization.On,
            save_result=True,
            poll_interval=2.0,
            timeout_seconds=300.0,
            on_progress=lambda response: print("status:", response.status.value),
        )

    print(result.results.transcript if result.results else "")
    output_path.write_text(
        stt.Subtitles.from_response(result).to_vtt(),
        encoding="utf-8",
    )


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative):

status: queued
status: processing
status: done
Hello and welcome to the meeting.

With diarization on, each word offset carries a speaker label. This example groups words into speaker turns:

batch_speakers.py
from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

from humain_voice import stt
from humain_voice.stt.batchtranscription import BatchDiarization


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


async def main() -> None:
    input_path = Path(sys.argv[1] if len(sys.argv) > 1 else "recording.wav")

    async with stt.BatchTranscribeClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_version=os.environ.get("API_VERSION", "v1"),
    ) as client:
        result = await client.transcribe(
            input_path,
            lang=stt.Language.ArEn,
            asr=stt.BatchTranscriptionModel.BayanArEn,
            diarization=BatchDiarization.On,
            save_result=True,
            timeout_seconds=300.0,
            on_progress=lambda response: print("status:", response.status.value),
        )

    turns: list[tuple[str, list[str]]] = []
    for offset in result.results.offsets if result.results else []:
        speaker = offset.speaker or "UNKNOWN_SPEAKER"
        if turns and turns[-1][0] == speaker:
            turns[-1][1].append(offset.word)
        else:
            turns.append((speaker, [offset.word]))
    for speaker, words in turns:
        print(f"{speaker}: {' '.join(words)}")


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative; labels are opaque strings):

status: processing
status: done
SPEAKER_1: Hello and welcome to the meeting.
SPEAKER_2: Thanks for having me.

Fast transcription

FastTranscriptionClient.transcribe(audio_source, language, asr_model, ...) sends one short, complete clip over Socket.IO and returns the final result. Send longer recordings to batch; see Fast transcription limits.

NameTypeDefaultMeaning
audio_sourcebytes or binary fileRequiredClip to transcribe.
languagestt.LanguageRequiredSpoken language.
asr_modelstt.FastTranscriptionModel or strRequiredASR model.
on_responsecallableNoneReceives partial results, then the final one.
on_file_uploadcallableNoneReceives the upload receipt.
on_errorcallableNoneReceives an ErrorResponse.
timeout_secondsfloat60.0Wait for the final result.
fast_transcription.py
from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

from humain_voice import stt


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


def handle_response(response: stt.FtTranscribeResponse) -> None:
    kind = "final" if response.is_final else "partial"
    print(f"{kind}:", response.transcription)


def handle_upload(response: stt.FileUploadedResponse) -> None:
    print("status:", "uploaded", response.id)


def handle_error(error: stt.ErrorResponse | None) -> None:
    if error is not None:
        print("error:", error.code, error.message, file=sys.stderr)


async def main() -> None:
    input_path = Path(sys.argv[1] if len(sys.argv) > 1 else "recording.wav")
    output_path = Path(sys.argv[2] if len(sys.argv) > 2 else "recording.vtt")

    async with stt.FastTranscriptionClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_path=os.environ.get("API_PATH"),
    ) as client:
        result = await client.transcribe(
            input_path.read_bytes(),
            stt.Language.ArEn,
            stt.FastTranscriptionModel.BayanArEn,
            on_response=handle_response,
            on_file_upload=handle_upload,
            on_error=handle_error,
            timeout_seconds=60.0,
        )

    if result is None:
        raise RuntimeError("Fast transcription ended without a final result")
    output_path.write_text(
        stt.Subtitles.from_response(result).to_vtt(),
        encoding="utf-8",
    )


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative):

status: uploaded 3f1c2a9e-5b7d-4e8a-9c41-0d2e6f8b7a15
partial: Hello and
final: Hello and welcome to the meeting.

Realtime transcription

RealtimeClient.start_stream(language, ...) opens a stream. Send PCM16 little-endian, 16 kHz, mono audio with stream.send(), then call stream.close() to wait for is_final; stream.stop() ends without waiting. See Streaming results are state, not a log.

CallArgumentTypeDefaultMeaning
start_stream()languagestt.LanguageRequiredSpoken language.
start_stream()on_responsecallableNoneReceives provisional and final results.
start_stream()on_errorcallableNoneReceives an ErrorResponse.
stream.send()audio_bytesbytesRequiredOne audio chunk.
stream.close()timeout_secondsfloat1.0Wait for is_final. Pass 5.0.

The example sends 3,200-byte (100 ms) chunks and writes captions from the final words. To make recording.pcm, see Prepare audio.

realtime_transcription.py
from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

from humain_voice import stt


CHUNK_BYTES = 3_200  # 100 ms of PCM16LE, 16 kHz, mono audio.


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


async def main() -> None:
    input_path = Path(sys.argv[1] if len(sys.argv) > 1 else "recording.pcm")
    output_path = Path(sys.argv[2] if len(sys.argv) > 2 else "recording.vtt")
    finalized_words: list[stt.WordSegment] = []
    server_error: stt.ErrorResponse | None = None
    protocol_final_observed = False

    def handle_response(response: stt.RtTranscribeResponse) -> None:
        nonlocal protocol_final_observed
        if response.is_final:
            kind = "final"
        elif response.is_speech_final:
            kind = "speech-final"
        else:
            kind = "partial"
        print(f"{kind}:", response.transcription)
        if response.is_final:
            protocol_final_observed = True
        if response.is_final or response.is_speech_final:
            # seq is not guaranteed to increase, so keep words in arrival order.
            finalized_words.extend(response.words)

    def handle_error(error: stt.ErrorResponse | None) -> None:
        nonlocal server_error
        if error is not None:
            print("error:", error.code, error.message, file=sys.stderr)
            server_error = error

    async with stt.RealtimeClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_path=os.environ.get("API_PATH"),
    ) as client:
        stream = await client.start_stream(
            language=stt.Language.ArEn,
            on_response=handle_response,
            on_error=handle_error,
        )
        pcm = input_path.read_bytes()
        try:
            for offset in range(0, len(pcm), CHUNK_BYTES):
                if server_error is not None:
                    break
                await stream.send(pcm[offset : offset + CHUNK_BYTES])
                await asyncio.sleep(0.1)
            # Returns (does not raise) if is_final has not arrived within 5 s.
            if server_error is None:
                await stream.close(timeout_seconds=5.0)
        except Exception:
            # The SDK drops the stream on a server error, so send() and close() raise.
            if server_error is None:
                raise

    if server_error is not None:
        raise RuntimeError(server_error.message or server_error.code or "Realtime stream failed")
    if not protocol_final_observed:
        raise RuntimeError("Realtime stream ended before protocol is_final")
    output_path.write_text(
        stt.Subtitles.from_words(finalized_words).to_vtt(),
        encoding="utf-8",
    )


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative):

partial: Hello and
speech-final: Hello and welcome to the meeting.
partial: Let's start
final: Let's start with the agenda.

Live diarization

RealtimeDiarizationClient.start_stream(on_update=...) reports who is speaking while you send() realtime-format PCM in 15,360-byte (480 ms) chunks, DIARIZATION_RECOMMENDED_CHUNK_BYTES. Each DiarizationUpdate carries the full timeline in segments and new final segments in newly_finalized. stream.close(timeout_seconds=5.0) returns the final timeline, and stt.to_rttm() renders it as RTTM.

realtime_diarization.py
from __future__ import annotations

import asyncio
import os
import sys
from pathlib import Path

from humain_voice import stt
from humain_voice.stt.constants import DIARIZATION_RECOMMENDED_CHUNK_BYTES


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


def handle_error(error: stt.ErrorResponse | None) -> None:
    if error is not None:
        print("error:", error.code, error.message, file=sys.stderr)


async def main() -> None:
    input_path = Path(sys.argv[1] if len(sys.argv) > 1 else "recording.pcm")
    output_path = Path(sys.argv[2] if len(sys.argv) > 2 else "recording.rttm")
    async with stt.RealtimeDiarizationClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_path=os.environ.get("API_PATH"),
    ) as client:
        final_observed = False

        def on_update(update: stt.DiarizationUpdate) -> None:
            nonlocal final_observed
            final_observed = final_observed or update.is_final
            for segment in update.newly_finalized:
                print(segment.speaker, segment.start_time, segment.end_time)

        stream = await client.start_stream(
            on_update=on_update,
            on_error=handle_error,
        )
        pcm = input_path.read_bytes()
        if not pcm or len(pcm) % 2:
            raise ValueError("Input must be nonempty PCM16 with an even byte length")
        for offset in range(0, len(pcm), DIARIZATION_RECOMMENDED_CHUNK_BYTES):
            await stream.send(
                pcm[offset : offset + DIARIZATION_RECOMMENDED_CHUNK_BYTES]
            )
            await asyncio.sleep(0.48)

        # Returns the best-known timeline after 5 s even without a final update.
        timeline = await stream.close(timeout_seconds=5.0)

    destination = output_path if final_observed else Path(f"{output_path}.partial")
    destination.write_text(stt.to_rttm(timeline, uri="recording"), encoding="utf-8")
    if not final_observed:
        print("status:", f"Final result not observed; wrote incomplete output to {destination}")


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative):

SPEAKER_01 0.0 3.84
SPEAKER_02 3.84 7.2
SPEAKER_01 7.2 11.52

Text to speech

TTSClient returns raw PCM16 little-endian mono audio at tts.get_sample_rate(model) Hz (24,000 for the default TtsModel.Nebula). list_voices(timeout_seconds=None) returns dictionaries with id, label, and, when available, profile:

list_voices.py
from __future__ import annotations

import asyncio
import os

from humain_voice import tts


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


async def main() -> None:
    async with tts.TTSClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_path=os.environ.get("API_PATH"),
    ) as client:
        for voice in await client.list_voices(timeout_seconds=5.0):
            dialect = ""
            languages = ""
            if profile := voice.get("profile"):
                dialect = profile["speaker"]["dialect"]
                languages = ",".join(profile["languages"])
            print(voice["id"], voice["label"], dialect, languages)


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative; IDs vary by environment):

42e38a63-849a-481a-b5bf-3c1b7a985de3 mul_nourah ars ar,en
af52a907-1086-46f7-8f5d-72317875d7bd mul_youssef arz ar,en

In 0.18.1, or 0.19.0b3 or later, profile can also have emotions and styles (list[str]). They're absent where emotion and speaking style aren't enabled, so read them with profile.get("emotions"); see Voice list.

synthesize(text, voice_id, ...) returns the whole clip as bytes; synthesize_stream(text, voice_id, ...) yields TtsAudioResponse chunks (id, is_last, audio). Pass exactly one of voice_id or voice_references. Arguments after voice_id are keyword-only.

NameTypeDefaultMeaning
textstrRequiredText to speak.
voice_idstrNoneVoice ID from list_voices().
voice_referenceslist of {"text": str, "audio": str}NoneReference clips to clone; audio is base64 WAV.
modeltts.TtsModel or strNone (Nebula)TTS model.
timeout_secondsfloat or NoneNoneWait for each next chunk; None waits forever, so always set it.
on_audiocallableNoneReceives each chunk. synthesize() only.
on_errorcallableNoneReceives an ErrorResponse.
request_iduuid.UUIDNoneRequest ID; generated when omitted.

This example adds a WAV header with wave and writes speech.wav:

tts_to_wav.py
from __future__ import annotations

import asyncio
import os
import sys
import wave
from pathlib import Path

from humain_voice import stt, tts


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


def write_pcm16_wav(path: Path, pcm: bytes, sample_rate: int) -> None:
    with wave.open(str(path), "wb") as wav_file:
        wav_file.setnchannels(1)
        wav_file.setsampwidth(2)
        wav_file.setframerate(sample_rate)
        wav_file.writeframes(pcm)


def handle_error(error: stt.ErrorResponse | None) -> None:
    if error is not None:
        print("error:", error.code, error.message, file=sys.stderr)


async def main() -> None:
    text = sys.argv[1] if len(sys.argv) > 1 else "Hello from HUMAIN Voice"
    output_path = Path(sys.argv[2] if len(sys.argv) > 2 else "speech.wav")
    async with tts.TTSClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_path=os.environ.get("API_PATH"),
    ) as client:
        voices = await client.list_voices(timeout_seconds=5.0)
        if not voices:
            raise RuntimeError("No TTS voices are available")
        voice = next((item for item in voices if item.get("profile")), voices[0])
        if profile := voice.get("profile"):
            print(
                "status:",
                "voice",
                voice["label"],
                profile["speaker"]["dialect"],
                profile["languages"],
            )

        model = tts.TtsModel.Nebula
        pcm = await client.synthesize(
            text,
            voice_id=voice["id"],
            model=model,
            # Inactivity timeout per audio chunk, not a total deadline.
            timeout_seconds=30.0,
            on_error=handle_error,
        )

    write_pcm16_wav(output_path, pcm, tts.get_sample_rate(model))


if __name__ == "__main__":
    asyncio.run(main())

Expected output (illustrative):

status: voice mul_nourah ars ['ar', 'en']

This example streams audio to stdout:

python tts_stream.py "Hello from HUMAIN Voice" | ffplay -f s16le -ar 24000 -ch_layout mono -
tts_stream.py
from __future__ import annotations

import asyncio
import os
import sys

from humain_voice import stt, tts


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


def handle_error(error: stt.ErrorResponse | None) -> None:
    if error is not None:
        print("error:", error.code, error.message, file=sys.stderr)


async def main() -> None:
    text = sys.argv[1] if len(sys.argv) > 1 else "Hello from HUMAIN Voice"
    model = tts.TtsModel.Nebula
    async with tts.TTSClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_path=os.environ.get("API_PATH"),
    ) as client:
        voices = await client.list_voices(timeout_seconds=5.0)
        if not voices:
            raise RuntimeError("No TTS voices are available")

        # Audio goes to stdout, so logs go to stderr.
        print("status: sample rate", tts.get_sample_rate(model), file=sys.stderr)
        async for chunk in client.synthesize_stream(
            text,
            voice_id=voices[0]["id"],
            model=model,
            timeout_seconds=30.0,
            on_error=handle_error,
        ):
            sys.stdout.buffer.write(chunk.audio)
            sys.stdout.buffer.flush()


if __name__ == "__main__":
    asyncio.run(main())

Expected output on stderr (illustrative):

status: sample rate 24000

See Speech output to choose a mode and Models and voices for voices.

Voice agent sessions

agent.AgentClient starts Voice Agent sessions from your server. It needs the beta release:

python -m pip install humain-voice==0.19.0b2

It takes api_url and api_key. create_session() sends one session request:

NameTypeDefaultMeaning
participantdict with identity, optional name and genderRequiredThe user who joins the call.
agentdictNoneprompt, intro, voice_id, client_tools, and tool_acknowledgments, as in the request.
variablesdict[str, str | int | float | bool]NoneValues for {{name}} placeholders.
idempotency_keystrNoneSent as Idempotency-Key, so a retry returns the first session.
timeout_secondsfloat10.0Request timeout.

It returns AgentSessionCredentials with server_url, participant_token, session_id, expires_at (datetime), effective (the response's effective object as a dict), and limits (max_duration_s and idle_timeout_s; None means no limit). token_response() returns the server_url and participant_token to send to the browser:

import asyncio
import os

from humain_voice.agent import AgentClient, AgentError


async def main() -> None:
    async with AgentClient(api_url=os.environ["API_URL"], api_key=os.environ["API_KEY"]) as agent:
        try:
            session = await agent.create_session(
                participant={"identity": "user-123"},
                agent={"prompt": "You help {{name}} with their orders.", "intro": "Hi {{name}}!"},
                variables={"name": "Sara"},
            )
        except AgentError as err:
            print("error:", err.code, err.status_code, err.data)
            raise
        print("session:", session.session_id, session.expires_at.isoformat())


asyncio.run(main())

A failed request raises AgentError with status_code, code, retryable, retry_after (seconds), and data; validation problems are in data["errors"]. AgentAuthError (401) and AgentRateLimitError (429) are subclasses, as with batch errors. The browser side is @humain-voice/agent.

Subtitles

stt.Subtitles.from_response(result, **options) builds cues from a batch or fast result; stt.Subtitles.from_words(words, **options) takes any word list. to_vtt(**options) and to_srt(**options) render them and accept max_chars_per_line, max_lines, and strict.

NameTypeDefaultMeaning
max_duration_secondsfloat6.0Longest cue.
max_gap_secondsfloat0.7Silence that starts a new cue.
min_duration_secondsfloat0.5Shortest cue.
max_chars_per_lineint42Line width.
max_linesint2Lines per cue.
split_on_speaker_changeboolTrueStart a new cue when the speaker changes.
strictboolFalseRaise SubtitleError on malformed timing instead of fixing or skipping it.

For realtime captions, collect the words of each is_speech_final and is_final result and call Subtitles.from_words(), as the realtime example does.

Errors

Batch methods raise subclasses of stt.BatchTranscribeError:

ClassWhenAttributes
BatchTranscribeErrorAny non-2xx response, or empty api_url / api_keystatus_code, code, retryable, job_id, capacity, raw_body
BatchTranscribeAuthError401Same as above
BatchTranscribeRateLimitError429retry_after (seconds; None unless Retry-After is an integer)
BatchTranscribeJobFailedErrorThe job reached failederror, error_code
BatchTranscribeTimeoutErrortranscribe() ran past timeout_secondsjob_id, elapsed_seconds

Network failures raise aiohttp.ClientError or asyncio.TimeoutError; retry them on reads. Socket.IO clients pass an ErrorResponse to on_error: branch on code (constants in humain_voice.errors) and retryable, and read retry_after_seconds, data, and retry_scope (new_stream means open a new stream). Diarization iterators raise DiarizationStreamError, whose response is the ErrorResponse. Codes and retry rules are in Errors and limits.

This example retries a batch result read with backoff and save_result=True:

batch_error_retry.py
from __future__ import annotations

import asyncio
import os
import random
import sys

import aiohttp

from humain_voice import stt
from humain_voice.stt.batchtranscription import TranscriptionResponse


def required_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"{name} is required")
    return value


async def get_result_with_retry(
    client: stt.BatchTranscribeClient,
    job_id: str,
    attempts: int = 5,
) -> TranscriptionResponse:
    for attempt in range(1, attempts + 1):
        try:
            # save_result keeps the stored result readable for a retry.
            return await client.get_result(
                job_id, stt.Language.ArEn, save_result=True
            )
        except stt.BatchTranscribeError as error:
            retryable = (
                isinstance(error, stt.BatchTranscribeRateLimitError)
                or error.retryable is True
            )
            server_delay = 0.0
            if isinstance(error, stt.BatchTranscribeRateLimitError):
                server_delay = error.retry_after or 0
            print(
                "error:",
                error.code or "",
                error.status_code or "",
                "" if error.capacity is None else error.capacity,
                file=sys.stderr,
            )
            if not retryable or attempt == attempts:
                raise
        except (aiohttp.ClientError, asyncio.TimeoutError) as error:
            # Network failures aren't SDK errors; a result read is safe to retry.
            server_delay = 0.0
            print("error:", "network", error, file=sys.stderr)
            if attempt == attempts:
                raise

        exponential_delay = 0.5 * 2 ** (attempt - 1)
        await asyncio.sleep(max(server_delay, exponential_delay) + random.random() * 0.25)

    raise RuntimeError("Retry loop exhausted")


async def main() -> None:
    if len(sys.argv) < 2:
        raise RuntimeError("Pass a batch job ID as the first argument")

    async with stt.BatchTranscribeClient(
        api_url=required_env("API_URL"),
        api_key=required_env("API_KEY"),
        api_version=os.environ.get("API_VERSION", "v1"),
    ) as client:
        result = await get_result_with_retry(client, sys.argv[1])
        print("status:", result.status.value)
        print(result.results.transcript if result.results else "")


if __name__ == "__main__":
    asyncio.run(main())

Pass a job ID as the first argument. Expected output (illustrative):

error: SERVER_INTERNAL 500
status: done
Hello and welcome to the meeting.

Retry submit() only on 429 or 503. After a 500, a timeout, or a dropped connection, a job may exist; see Retries and duplicates.

Timeouts and defaults

Values are in seconds. Expired timeouts raise asyncio.TimeoutError unless noted.

ClientOptionDefaultBounds
BatchTranscribeClientpoll_interval2Wait between result reads in transcribe().
BatchTranscribeClienttimeout_seconds300Polling in transcribe() after the upload. Raises BatchTranscribeTimeoutError.
FastTranscriptionClienttimeout_seconds on transcribe()60Wait for the final result.
RealtimeClienttimeout_seconds on stream.close()1Wait for is_final; returns without an error on timeout. Pass close(timeout_seconds=5.0).
RealtimeDiarizationClienttimeout_seconds on stream.close()5Wait for the final update; returns the best-known timeline.
TTSClienttimeout_seconds on list_voices()NoneWait for the voice list.
TTSClienttimeout_seconds on synthesize() / synthesize_stream()NoneWait for each next chunk. Always set it.

The server applies its own TTS deadlines; see Timeouts.

Next steps

On this page