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.1Configure a client
Each workflow has its own client; import stt, tts, and agent from humain_voice. Every client takes
these keyword arguments:
| Name | Type | Default | Meaning |
|---|---|---|---|
api_url | str | Required | Service base URL. |
api_key | str | Required | API key. |
api_path | str | /socket.io | Socket.IO path. Every client except batch. |
api_version | str | v1 | REST version. BatchTranscribeClient only. |
Examples read these from API_URL, API_KEY, API_PATH, and API_VERSION; see
Connection settings.
| Workflow | Client | Clean up with |
|---|---|---|
| Batch transcription | stt.BatchTranscribeClient | close() |
| Fast transcription | stt.FastTranscriptionClient | close() |
| Realtime transcription | stt.RealtimeClient | disconnect() |
| Live diarization | stt.RealtimeDiarizationClient | disconnect() |
| Text to speech | tts.TTSClient | close() |
| Voice Agent sessions | agent.AgentClient | close() |
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:
| Client | Sync methods |
|---|---|
BatchTranscribeClient | submit_sync(), get_result_sync(), transcribe_sync(), close_sync() |
FastTranscriptionClient | transcribe_sync(), close_sync() |
RealtimeClient | start_stream_sync(); stream send_sync(), close_sync(), stop_sync() |
RealtimeDiarizationClient | start_stream_sync(); stream send_sync(), close_sync() |
TTSClient | list_voices_sync(), synthesize_sync(), close_sync() |
AgentClient | create_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.
| Name | Type | Default | Meaning |
|---|---|---|---|
audio | bytes, path (str or Path), or binary file | Required | Audio to upload. |
lang | stt.Language or str | Required | Spoken language. |
asr | stt.BatchTranscriptionModel or str | None | ASR model. |
diarization | BatchDiarization | None | On, D1, or D2 labels speakers. Enum only. |
itn | bool | None | Inverse text normalization. |
redact | BatchRedact | None | BatchRedact.On turns on redaction. Enum only. |
save_result | bool | False | Keep the result readable after it's fetched; see Read the result again. Not on submit(). |
poll_interval | float | 2.0 | Seconds between result reads. transcribe() only. |
timeout_seconds | float | 300.0 | Polling limit in seconds. transcribe() only. |
on_progress | Callable[[TranscriptionResponse], None] | None | Called with each result read. transcribe() only. |
Import BatchDiarization, BatchRedact, and TranscriptionResponse from
humain_voice.stt.batchtranscription.
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:
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.
| Name | Type | Default | Meaning |
|---|---|---|---|
audio_source | bytes or binary file | Required | Clip to transcribe. |
language | stt.Language | Required | Spoken language. |
asr_model | stt.FastTranscriptionModel or str | Required | ASR model. |
on_response | callable | None | Receives partial results, then the final one. |
on_file_upload | callable | None | Receives the upload receipt. |
on_error | callable | None | Receives an ErrorResponse. |
timeout_seconds | float | 60.0 | Wait for the final result. |
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.
| Call | Argument | Type | Default | Meaning |
|---|---|---|---|---|
start_stream() | language | stt.Language | Required | Spoken language. |
start_stream() | on_response | callable | None | Receives provisional and final results. |
start_stream() | on_error | callable | None | Receives an ErrorResponse. |
stream.send() | audio_bytes | bytes | Required | One audio chunk. |
stream.close() | timeout_seconds | float | 1.0 | Wait 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.
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.
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.52Text 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:
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,enIn 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.
| Name | Type | Default | Meaning |
|---|---|---|---|
text | str | Required | Text to speak. |
voice_id | str | None | Voice ID from list_voices(). |
voice_references | list of {"text": str, "audio": str} | None | Reference clips to clone; audio is base64 WAV. |
model | tts.TtsModel or str | None (Nebula) | TTS model. |
timeout_seconds | float or None | None | Wait for each next chunk; None waits forever, so always set it. |
on_audio | callable | None | Receives each chunk. synthesize() only. |
on_error | callable | None | Receives an ErrorResponse. |
request_id | uuid.UUID | None | Request ID; generated when omitted. |
This example adds a WAV header with wave and writes speech.wav:
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 -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 24000See 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.0b2It takes api_url and api_key. create_session() sends one
session request:
| Name | Type | Default | Meaning |
|---|---|---|---|
participant | dict with identity, optional name and gender | Required | The user who joins the call. |
agent | dict | None | prompt, intro, voice_id, client_tools, and tool_acknowledgments, as in the request. |
variables | dict[str, str | int | float | bool] | None | Values for {{name}} placeholders. |
idempotency_key | str | None | Sent as Idempotency-Key, so a retry returns the first session. |
timeout_seconds | float | 10.0 | Request 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.
| Name | Type | Default | Meaning |
|---|---|---|---|
max_duration_seconds | float | 6.0 | Longest cue. |
max_gap_seconds | float | 0.7 | Silence that starts a new cue. |
min_duration_seconds | float | 0.5 | Shortest cue. |
max_chars_per_line | int | 42 | Line width. |
max_lines | int | 2 | Lines per cue. |
split_on_speaker_change | bool | True | Start a new cue when the speaker changes. |
strict | bool | False | Raise 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:
| Class | When | Attributes |
|---|---|---|
BatchTranscribeError | Any non-2xx response, or empty api_url / api_key | status_code, code, retryable, job_id, capacity, raw_body |
BatchTranscribeAuthError | 401 | Same as above |
BatchTranscribeRateLimitError | 429 | retry_after (seconds; None unless Retry-After is an integer) |
BatchTranscribeJobFailedError | The job reached failed | error, error_code |
BatchTranscribeTimeoutError | transcribe() ran past timeout_seconds | job_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:
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.
| Client | Option | Default | Bounds |
|---|---|---|---|
BatchTranscribeClient | poll_interval | 2 | Wait between result reads in transcribe(). |
BatchTranscribeClient | timeout_seconds | 300 | Polling in transcribe() after the upload. Raises BatchTranscribeTimeoutError. |
FastTranscriptionClient | timeout_seconds on transcribe() | 60 | Wait for the final result. |
RealtimeClient | timeout_seconds on stream.close() | 1 | Wait for is_final; returns without an error on timeout. Pass close(timeout_seconds=5.0). |
RealtimeDiarizationClient | timeout_seconds on stream.close() | 5 | Wait for the final update; returns the best-known timeline. |
TTSClient | timeout_seconds on list_voices() | None | Wait for the voice list. |
TTSClient | timeout_seconds on synthesize() / synthesize_stream() | None | Wait for each next chunk. Always set it. |
The server applies its own TTS deadlines; see Timeouts.
Next steps
JavaScript and TypeScript
Transcribe audio, build speaker timelines, and synthesize speech from Node.js or Bun with @humain-voice/sdk 0.18.1.
Voice Agent browser SDK
Join a Voice Agent call from the browser with @humain-voice/agent, handle client tools, and react to status, transcripts, warnings, and end reasons.