Ir para o conteúdo

tempest_fastapi_sdk.genai.audio

Áudio self-hosted: fala para texto e texto para fala.

« IA e visão computacional


audio

Self-hosted audio — speech-to-text and text-to-speech on your hardware.

SpeechToText (faster-whisper) interprets audio into text; TextToSpeech (Coqui TTS) generates audio from text. Both load lazily and run inference in worker threads. The engines live behind the [genai-audio] extra and import lazily, so this package imports without it.

DEFAULT_AFFINITY_PERCENTILE module-attribute

DEFAULT_AFFINITY_PERCENTILE: float = 0.9

Fraction of each row's weakest affinities that get suppressed.

Row-wise pruning before the eigendecomposition is standard in spectral diarization, and it matters: every turn has a small nonzero similarity to every other turn, and summed over a long recording that noise floor blurs exactly the gap being looked for. Keeping the strongest tenth of each row sharpens the block structure without hand-tuning a distance.

DEFAULT_BARK_MODEL module-attribute

DEFAULT_BARK_MODEL: str = 'suno/bark-small'

The checkpoint measured for this module.

DEFAULT_CLUSTERING_THRESHOLD module-attribute

DEFAULT_CLUSTERING_THRESHOLD: float = 0.9

Distance below which two turns are called the same voice.

Used only when num_speakers is unknown. Pass the speaker count whenever you know it — threshold-only clustering is the weakest part of this pipeline, and this default is a compromise, not a safe value.

Swept over three reference recordings (correct count in brackets):

threshold 4-speaker zh 2-speaker en #1 2-speaker en #2
0.5 7 2 4
0.7 5 2 4
0.9 4 1 2
1.1 1 1 2

No value is right on all three. 0.9 is right on two, and its failure mode is merging two speakers rather than splitting one into seven — a transcript that under-attributes is easier to notice and repair than one claiming eight participants. sherpa-onnx's own default of 0.5 produced seven clusters for four speakers here.

DEFAULT_MATCH_THRESHOLD module-attribute

DEFAULT_MATCH_THRESHOLD: float = 0.5

Cosine similarity above which a voice is called a match.

Measured on the reference recording: same speaker 0.687, different speakers 0.146 and 0.074. The gap is wide, so the exact value between roughly 0.35 and 0.6 changes little — but this is the knob that trades letting the wrong person through against failing to recognise the right one, and which error costs more depends entirely on what the match is used for. Attributing a line in a meeting transcript can be generous; anything that grants access should not be.

DEFAULT_MAX_AUDIO_SECONDS module-attribute

DEFAULT_MAX_AUDIO_SECONDS: float = 3600.0

Longest decoded recording accepted by default, in seconds.

One hour, which holds a long meeting. At 16 kHz that is 57.6 million float32 samples, about 230 MB — the most memory one call is allowed to ask for by default. Pass max_audio_seconds=None to the engine to lift the bound for trusted, operator-supplied files.

DEFAULT_MAX_SPEAKERS module-attribute

DEFAULT_MAX_SPEAKERS: int = 10

Largest speaker count the estimator will return.

The gap search needs an upper bound: with none, a recording of N turns can nominate up to N speakers, and the largest gap in a long tail of near-identical eigenvalues is noise. Ten covers a meeting; past that the recording needs a real diarization system and a human.

DEFAULT_MAX_UPLOAD_BYTES module-attribute

DEFAULT_MAX_UPLOAD_BYTES: int = 25 * 1024 * 1024

Largest upload accepted, in bytes.

Audio arrives whole and is held in memory while it is decoded, so an unbounded upload is a way to exhaust the worker. 25 MiB is about 13.6 minutes of 16 kHz mono 16-bit WAV — beyond that the request belongs in a background job, not a synchronous endpoint.

This bounds the encoded bytes only. The decoded duration, which is what a compressed or forged upload inflates, is bounded by the engines' max_audio_seconds (see :mod:tempest_fastapi_sdk.genai.audio.decoding).

DEFAULT_MODEL_NAME module-attribute

DEFAULT_MODEL_NAME: str = '3dspeaker-eres2net-base'

Name recorded on every profile this service writes.

Stored per row so that swapping the embedding model does not silently invalidate comparisons: profiles from the old model stop matching and :meth:VoiceProfileService.stale_profiles can find them.

DIARIZATION_SAMPLE_RATE module-attribute

DIARIZATION_SAMPLE_RATE: int = 16000

Sample rate the segmentation and embedding models are trained on.

Audio at any other rate is resampled before inference. Feeding a model the wrong rate does not fail — it silently degrades, which is worse.

EMBEDDING_DIMENSIONS module-attribute

EMBEDDING_DIMENSIONS: int = 512

Length of the vector the bundled model produces.

Pinned so a stored profile can be validated on read: a row whose vector is a different length was written by a different model and comparing it would produce a number that means nothing.

EMBEDDING_MODEL module-attribute

EMBEDDING_MODEL: DiarizationModel = DiarizationModel(
    name="3dspeaker-eres2net-base",
    url="https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k.onnx",
    member="3dspeaker_speech_eres2net_base_sv_zh-cn_3dspeaker_16k.onnx",
    sha256="1a331345f04805badbb495c775a6ddffcdd1a732567d5ec8b3d5749e3c7a5e4b",
)

Speaker embedding model — turns a voice into a 512-dimension vector.

Trained on Mandarin but speaker embeddings are largely language-independent: the model encodes vocal tract characteristics, not words. Verified on the reference recording, where it separated four speakers cleanly.

The digest is of the release asset as served (39 593 761 bytes), measured with curl -L + sha256sum on 2026-09-26; GitHub publishes no digest for it.

MAX_CHANNELS module-attribute

MAX_CHANNELS: int = 8

Most channels accepted in a WAV file (7.1 surround).

MAX_SOURCE_RATE module-attribute

MAX_SOURCE_RATE: int = 192000

Highest declared sample rate accepted, in Hz.

192 kHz is the top rate professional audio interfaces record at.

MIN_ENROLLMENT_SECONDS module-attribute

MIN_ENROLLMENT_SECONDS: float = 3.0

Shortest audio accepted for enrolment.

A profile built from one word matches almost anyone. Three seconds is where the reference measurements were taken and is a common floor for this class of model; below it the vector describes the phrase more than the person.

MIN_SOURCE_RATE module-attribute

MIN_SOURCE_RATE: int = 8000

Lowest declared sample rate accepted, in Hz.

8 kHz is narrowband telephony, the lowest rate speech is recorded at in practice. Anything lower is not a recording a speech model can use, and resampling it to 16 kHz multiplies the sample count by the rate ratio, so a forged low rate is how a small upload turns into a large allocation.

PCM_CHANNELS module-attribute

PCM_CHANNELS: Final[int] = 1

Streamed speech is mono.

PCM_CHUNK_BYTES module-attribute

PCM_CHUNK_BYTES: Final[int] = PCM_SAMPLE_RATE * PCM_SAMPLE_WIDTH // 4

Size of the pieces a finished clip is cut into: a quarter of a second.

PCM_SAMPLE_RATE module-attribute

PCM_SAMPLE_RATE: Final[int] = 24000

Sample rate of streamed speech, in Hz (XTTS v2 and Bark output).

PCM_SAMPLE_WIDTH module-attribute

PCM_SAMPLE_WIDTH: Final[int] = 2

Bytes per sample: 16-bit signed integers.

SEGMENTATION_MODEL module-attribute

SEGMENTATION_MODEL: DiarizationModel = DiarizationModel(
    name="sherpa-onnx-pyannote-segmentation-3-0",
    url="https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/sherpa-onnx-pyannote-segmentation-3-0.tar.bz2",
    member="sherpa-onnx-pyannote-segmentation-3-0/model.onnx",
    sha256="220ad67ca923bef2fa91f2390c786097bf305bceb5e261d4af67b38e938e1079",
)

Segmentation model — finds where speech is and where turns change.

An ONNX export of pyannote/segmentation-3.0 published by k2-fsa, which is what lets this run without the gated HuggingFace pipeline.

The digest is of model.onnx (5 992 913 bytes) extracted from the release asset (6 958 444 bytes; the archive itself hashes to 24615ee884c897d9d2ba09bb4d30da6bb1b15e685065962db5b02e76e4996488), measured with curl -L + sha256sum on 2026-09-26. GitHub publishes no digest for these assets, so the pin records what was served that day.

TTSDtype module-attribute

TTSDtype = Literal['auto', 'float32', 'float16']

Precision of a Coqui voice's weights; see :class:TextToSpeech.

TTS_DTYPES module-attribute

TTS_DTYPES: Final[tuple[str, ...]] = get_args(TTSDtype)

Every accepted dtype value.

XTTS_WHOLE_PAUSE_MS module-attribute

XTTS_WHOLE_PAUSE_MS: Final[int] = 400

Silence between the parts of a whole-text XTTS synthesis, in ms.

Coqui's tts_to_file appended 10 000 zero samples (417 ms at 24 kHz) after every sentence; the whole-text path keeps about that gap between parts. Streaming adds none by default, so the first sentence is not delayed.

BarkSpeech

BarkSpeech(
    model_id: str = DEFAULT_BARK_MODEL,
    *,
    device: str = "auto",
    dtype: str | ModelDtypeEnum = "auto",
    cache_dir: str | None = None,
    hf_token: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    max_chunk_chars: int = DEFAULT_MAX_CHUNK_CHARS,
    pause_seconds: float = 0.25,
    max_concurrent: int = 1,
    idle_unload_seconds: float | None = None,
    hardware: HardwareInfo | None = None,
    metrics: GenAIMetrics | None = None,
)

A lazily-loaded local Bark model that speaks long text in pieces.

Example:

>>> speech = BarkSpeech()
>>> wav = await speech.synthesize(
...     "Bom dia! O ônibus das oito está atrasado.",
...     language=LanguageEnum.PT_BR,
... )

Attributes:

Name Type Description
model_id str

The HuggingFace model id.

device str

The resolved device.

dtype ModelDtypeEnum

The resolved compute precision.

source ModelRef

The resolved weight identity.

max_chunk_chars int

Largest piece sent to one generate call.

pause_seconds float

Silence inserted between pieces.

idle_unload_seconds float | None

Idle threshold used by :meth:unload_if_idle.

Configure the synthesizer (does not load weights yet).

Parameters:

Name Type Description Default
model_id str

"suno/bark-small" (measured) or "suno/bark".

DEFAULT_BARK_MODEL
device str

"auto" / "cuda" / "mps" / "cpu".

'auto'
dtype str | ModelDtypeEnum

Compute precision, or "auto".

'auto'
cache_dir str | None

Where weights are downloaded and read.

None
hf_token str | None

Hub token; None falls back to HF_TOKEN.

None
revision str | None

Branch, tag or commit sha to load.

None
local_files_only bool | None

Load from the cache without the network; None takes GENAI_OFFLINE.

None
max_chunk_chars int

Largest piece per generate call; see :data:DEFAULT_MAX_CHUNK_CHARS.

DEFAULT_MAX_CHUNK_CHARS
pause_seconds float

Silence between pieces.

0.25
max_concurrent int

Simultaneous syntheses. Defaults to 1, which also keeps seeds from interleaving on the process-wide RNG.

1
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the model after this many idle seconds.

None
hardware HardwareInfo | None

Injected snapshot for device resolution (tests).

None
metrics GenAIMetrics | None

Optional Prometheus metrics, recorded under op "tts".

None

Raises:

Type Description
ValueError

When max_concurrent or max_chunk_chars is not positive, or pause_seconds is negative.

is_loaded property

is_loaded: bool

Return True once the model is in memory.

Returns:

Name Type Description
bool bool

Whether :meth:load has run without a later :meth:unload.

load

load() -> None

Download (if needed) and load the processor and model.

Raises:

Type Description
ImportError

When the [genai] extra is missing.

OSError

When the checkpoint cannot be downloaded or read.

synthesize async

synthesize(
    text: str,
    /,
    *,
    language: LanguageEnum | str | None = None,
    speaker: str | None = None,
    seed: int | None = None,
    out_path: str | Path | None = None,
) -> bytes

Speak text and return a mono 24 kHz WAV.

Text longer than max_chunk_chars is spoken in sentence-sized pieces joined by pause_seconds of silence, so it is not cut at Bark's 13.95 s per-call ceiling.

Parameters:

Name Type Description Default
text str

The text to speak.

required
language LanguageEnum | str | None

LanguageEnum.PT_BR, "pt", "pt-BR"...; picks v2/<code>_speaker_0 when no speaker is given.

None
speaker str | None

A preset from :meth:voices, such as "v2/pt_speaker_1".

None
seed int | None

Seed applied with torch.manual_seed before the first piece, 0 to 2**64 - 1; the same seed repeated the same bytes (measured in bf16).

None
out_path str | Path | None

When given, also write the WAV.

None

Returns:

Name Type Description
bytes bytes

The WAV payload.

Raises:

Type Description
ValidationException

422, with details={"field": ...}: text with nothing speakable (text), a seed outside 0..2**64 - 1 (seed) and a speaker that is not a language voice (speaker) are refused before the model loads; a preset the checkpoint does not ship (speaker, or language when that language has no voice) after.

ImportError

When the [genai] extra is missing.

unload

unload() -> None

Free the model and its memory; waits for syntheses in flight.

unload_if_idle

unload_if_idle() -> bool

Free the model when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the model.

voices

voices() -> list[str]

List the voice presets the checkpoint ships.

Loads the model on first call, which blocks; from a coroutine, run it through asyncio.to_thread.

Returns:

Type Description
list[str]

list[str]: Preset names such as "v2/pt_speaker_1", sorted.

ConsentRequired

ConsentRequired(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: ValidationException

Raised when enrolment was attempted without evidence of consent.

ConversationTranscriber

ConversationTranscriber(*, stt: SpeechToText, diarizer: SpeakerDiarizer | None = None)

Produces a transcript split by speaker.

Holds a diarizer and a speech-to-text engine and runs them over the same recording. Both are injected so a service that already has a configured :class:~tempest_fastapi_sdk.genai.audio.stt.SpeechToText reuses it instead of loading Whisper twice.

Attributes:

Name Type Description
diarizer SpeakerDiarizer

Decides who spoke when.

stt SpeechToText

Decides what was said.

Initialize the transcriber.

Parameters:

Name Type Description Default
stt SpeechToText

Configured speech-to-text engine.

required
diarizer SpeakerDiarizer | None

Configured diarizer. None builds a default one, which downloads its models on first use.

None

transcribe async

transcribe(
    audio: str | Path | bytes,
    *,
    language: LanguageEnum | str | None = None,
    num_speakers: int | Literal["auto"] | None = None,
    identify_with: VoiceProfileService | None = None,
    session: AsyncSession | None = None,
    user_ids: list[UUID] | None = None,
) -> DiarizedTranscription

Transcribe audio and attribute each line to a speaker.

Diarization and transcription are independent, so they are dispatched together rather than in sequence. Both are CPU-bound native work in worker threads, so how much wall clock that saves depends on the cores available — on a single core it saves nothing, and the point is that neither has to wait on the other.

Parameters:

Name Type Description Default
audio str | Path | bytes

The recording.

required
language LanguageEnum | str | None

Force a language instead of detecting it.

None
num_speakers int | Literal['auto'] | None

Override the diarizer's setting for this call. None (default) leaves it alone, which means the automatic estimate unless the diarizer was built otherwise. An int is exact and skips the second pass.

None
identify_with VoiceProfileService | None

Match each speaker against enrolled voice profiles. Requires session. None leaves the turns anonymous.

None
session AsyncSession | None

Database session for the identification lookup.

None
user_ids list[UUID] | None

Restrict identification to these people — the meeting's participants, say. Far cheaper than searching everyone, and far less likely to put a stranger's name on a line.

None

Returns:

Name Type Description
DiarizedTranscription DiarizedTranscription

The conversation in order, with the

DiarizedTranscription

full transcript alongside.

Raises:

Type Description
ImportError

When the [genai-diarization] or [genai-audio] extra is missing.

DiarizationModel dataclass

DiarizationModel(name: str, url: str, member: str, sha256: str)

A downloadable model the diarizer needs.

Attributes:

Name Type Description
name str

Directory name under the cache root.

url str

Where to fetch it.

member str

File inside the archive, or the file name itself when the download is not an archive.

sha256 str

SHA-256 of the resolved model file — the archive member after extraction, not the archive. Checked by :func:ensure_models every time it resolves the file, fresh download or cache hit, so a model swapped upstream (or a corrupted cache) raises instead of changing the service's behavior with nothing in the diff. An empty string skips the check; the two shipped models are pinned.

DiarizedTranscription

Bases: BaseSchema

A conversation transcribed and split by who was speaking.

Attributes:

Name Type Description
text str

The full transcript, speakers not marked.

language str

Detected or forced language code.

duration float

Audio duration in seconds.

num_speakers int

Distinct speakers the diarizer found.

turns list[SpeakerTurn]

The conversation in order.

by_speaker

by_speaker() -> dict[int, str]

Group the transcript by speaker cluster.

Useful for "what did each person say", which is a different question from "how did the conversation go".

Returns:

Type Description
dict[int, str]

dict[int, str]: Cluster index to everything it said, joined

dict[int, str]

in chronological order.

transcript

transcript(*, unknown: str = 'Falante {speaker}') -> str

Render the conversation as labelled lines.

Parameters:

Name Type Description Default
unknown str

Template for an unidentified speaker, with a {speaker} placeholder for the cluster index.

'Falante {speaker}'

Returns:

Name Type Description
str str

One Nome: texto line per turn.

EnrollmentResponseSchema

Bases: BaseSchema

Result of enrolling a voice.

Attributes:

Name Type Description
profile VoiceProfileSchema

The stored profile.

ErasureResponseSchema

Bases: BaseSchema

Result of erasing someone's voice profiles.

Attributes:

Name Type Description
deleted int

How many profiles were removed. 0 is a successful outcome — erasing data that is not there is not an error.

LanguageEnum

Bases: BaseStrEnum

A supported audio language.

  • PT_BR — Brazilian Portuguese.
  • EN_US — US English.

LanguagePreset

Bases: BaseSchema

Per-language identifiers for the audio engines.

Attributes:

Name Type Description
whisper_language str

The faster-whisper language code ("pt" / "en").

tts_model str

A good default Coqui TTS model for the language.

tts_language str | None

The Coqui language argument, or None for single-language models that don't take one.

PCMAligner

PCMAligner()

Re-cut a byte stream so every piece holds whole 16-bit samples.

A network stream may split a sample between two reads; the odd byte is held back and prepended to the next piece.

Example:

>>> aligner = PCMAligner()
>>> aligner.feed(b"\x01\x02\x03")
b'\x01\x02'
>>> aligner.feed(b"\x04")
b'\x03\x04'

Start with nothing held back.

pending property

pending: bytes

Return the byte held back, if any (a truncated final sample).

feed

feed(chunk: bytes) -> bytes

Return the whole samples available after chunk.

Parameters:

Name Type Description Default
chunk bytes

The next bytes read.

required

Returns:

Name Type Description
bytes bytes

An even-length piece, possibly empty.

SpeakerDiarizer

SpeakerDiarizer(
    *,
    segmentation_model: str | Path | None = None,
    embedding_model: str | Path | None = None,
    cache_dir: str | Path | None = None,
    num_speakers: int | Literal["auto"] | None = "auto",
    threshold: float = DEFAULT_CLUSTERING_THRESHOLD,
    min_duration_on: float = DEFAULT_MIN_DURATION_ON,
    min_duration_off: float = DEFAULT_MIN_DURATION_OFF,
    num_threads: int = 1,
    provider: str = "cpu",
    max_speakers: int = 10,
    max_concurrent: int = 1,
    idle_unload_seconds: float | None = None,
    max_audio_seconds: float | None = DEFAULT_MAX_AUDIO_SECONDS,
)

Splits a recording into turns and clusters them by voice.

The models load on first use and stay resident; call :meth:unload or :meth:unload_if_idle to give the memory back, matching how :class:~tempest_fastapi_sdk.genai.audio.stt.SpeechToText behaves.

Attributes:

Name Type Description
num_speakers int | None

Fixed speaker count when known. None lets the clustering decide from threshold, which is the right default for a call whose participant count you do not control.

threshold float

Clustering threshold, used when num_speakers is None.

max_audio_seconds float | None

Longest decoded recording accepted; None when unbounded.

Initialize the diarizer without loading anything.

Parameters:

Name Type Description Default
segmentation_model str | Path | None

Path to the ONNX segmentation model. None resolves it from the cache, downloading on first load.

None
embedding_model str | Path | None

Path to the ONNX speaker embedding model. None resolves from the cache.

None
cache_dir str | Path | None

Where models are cached.

None
num_speakers int | Literal['auto'] | None

How many people to expect. An int is exact and cheapest — pass it whenever you know, on a two-party call you do. "auto" (default) estimates the count from the recording's own structure, which beat every fixed threshold on the benchmark (9/10 exact against 8/10) at the cost of a second pass. None clusters by threshold alone, which is the weakest option and exists for callers who want the old behaviour.

'auto'
threshold float

Clustering threshold when the count is unknown. Lower merges more aggressively.

DEFAULT_CLUSTERING_THRESHOLD
min_duration_on float

Shortest speech stretch kept.

DEFAULT_MIN_DURATION_ON
min_duration_off float

Shortest silence that splits turns.

DEFAULT_MIN_DURATION_OFF
num_threads int

ONNX Runtime intra-op threads.

1
provider str

Execution provider (cpu, cuda).

'cpu'
max_speakers int

Ceiling for the automatic estimate.

10
max_concurrent int

Diarizations allowed at once. One by default: the work is CPU-bound and a second concurrent call mostly adds latency to both.

1
idle_unload_seconds float | None

Idle time after which :meth:unload_if_idle releases the models.

None
max_audio_seconds float | None

Longest decoded recording accepted, checked while decoding and before the engine runs. None lifts the bound, for trusted files only.

DEFAULT_MAX_AUDIO_SECONDS

Raises:

Type Description
ValueError

If max_concurrent is below 1, or num_speakers is set below 1.

is_loaded property

is_loaded: bool

Whether the models are resident.

Returns:

Name Type Description
bool bool

True once :meth:load has run.

seconds_idle property

seconds_idle: float

Seconds since the models were last in use.

Reads 0.0 while a diarization is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

diarize async

diarize(
    audio: str | Path | bytes, *, num_speakers: int | Literal["auto"] | None = None
) -> list[SpeakerTurn]

Split audio into speaker turns.

With the automatic mode this runs twice: once to get the turns, then again with the count estimated from their embeddings. The second pass is what makes the estimate binding — estimating a count and then not clustering to it would report a number the output does not honour.

Parameters:

Name Type Description Default
audio str | Path | bytes

A path to a readable audio file, or its bytes.

required
num_speakers int | Literal['auto'] | None

Override the instance's setting for this call only. None (default) uses the instance's. Passed per call rather than assigned to the object: two concurrent calls wanting different counts would otherwise both see whichever was written last, and the earlier caller would silently get the other one's clustering.

None

Returns:

Type Description
list[SpeakerTurn]

list[SpeakerTurn]: Turns in chronological order, each with a

list[SpeakerTurn]

cluster index and no text. Empty when the recording holds no

list[SpeakerTurn]

speech the segmentation model recognizes.

Raises:

Type Description
ImportError

When the [genai-diarization] extra is absent.

ValueError

When num_speakers is neither a positive int, "auto", nor None, or the audio cannot be decoded.

ValidationException

When the audio declares a sample rate outside the accepted range or decodes past max_audio_seconds.

load

load() -> None

Resolve the models and build the engine.

Downloads the models when they are not cached, so the first call can be slow. Idempotent, and safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai-diarization] extra is absent.

unload

unload() -> None

Release the models.

While a diarization is in flight the release waits for it: the last call to finish drops the engine.

unload_if_idle

unload_if_idle() -> bool

Release the models when idle past the configured threshold.

Returns:

Name Type Description
bool bool

Whether anything was unloaded — never while a

bool

diarization is in flight.

SpeakerTurn

Bases: BaseSchema

One stretch of speech attributed to a single speaker.

Attributes:

Name Type Description
start float

Turn start in seconds.

end float

Turn end in seconds.

speaker int

Cluster index the diarizer assigned. Stable within one recording and meaningless across recordings — speaker 0 here is not speaker 0 in the next file.

speaker_id str | None

Enrolled profile this turn matched, when identification ran and cleared the threshold. None means not identified, which is not the same as not a person.

speaker_name str | None

Display name of the matched profile.

confidence float

Cosine similarity against the matched profile, 0.0 when no identification ran.

text str

What was said, empty until transcription is joined in.

duration property

duration: float

Length of the turn in seconds.

Returns:

Name Type Description
float float

end - start.

SpeechSynthesizer

Bases: Protocol

Anything that turns text into WAV bytes.

synthesize

synthesize(
    text: str, /, *, language: str | None = None, speaker: str | None = None
) -> Awaitable[bytes]

Synthesize text into WAV audio.

Parameters:

Name Type Description Default
text str

The text to speak.

required
language str | None

A language the caller asked for, or None.

None
speaker str | None

A speaker or voice name, or None for the backend default.

None

Returns:

Type Description
Awaitable[bytes]

Awaitable[bytes]: The WAV payload.

SpeechToText

SpeechToText(
    model_size: str = "base",
    *,
    device: str = "auto",
    compute_type: str = "auto",
    max_concurrent: int = 2,
    cache_dir: str | None = None,
    revision: str | None = None,
    local_files_only: bool | None = None,
    hf_token: str | None = None,
    idle_unload_seconds: float | None = None,
    beam_size: int = 5,
    vad_filter: bool = True,
    batch_size: int | None = None,
    cpu_threads: int = 0,
    num_workers: int = 1,
    condition_on_previous_text: bool = True,
    max_audio_seconds: float | None = DEFAULT_MAX_AUDIO_SECONDS,
)

A lazily-loaded faster-whisper transcriber.

Example:

>>> stt = SpeechToText("base", device="auto")
>>> result = await stt.transcribe("meeting.wav")
>>> print(result.text, result.language)

Attributes:

Name Type Description
model_size str

Whisper size/name (tiny…large-v3 or a path).

device str

Resolved device (cuda / cpu).

compute_type str

Resolved faster-whisper compute type.

max_audio_seconds float | None

Longest decoded recording accepted; None when unbounded.

Configure the transcriber (does not load weights yet).

faster-whisper names the same three Hub knobs differently (download_root / use_auth_token), so they are mapped here rather than splatted from a :class:~tempest_fastapi_sdk.genai.ModelRef. trust_remote_code has no counterpart: CTranslate2 loads weights, never repository Python.

Parameters:

Name Type Description Default
model_size str

Whisper size/name or a local path.

'base'
device str

"auto" / "cuda" / "cpu".

'auto'
compute_type str

faster-whisper compute type or "auto".

'auto'
max_concurrent int

Max simultaneous transcriptions.

2
cache_dir str | None

Where the downloaded weights are written and read back from. None uses the huggingface_hub default — $HF_HOME/hub, or ~/.cache/huggingface/hub when HF_HOME is unset — which is why the second run of a script starts instantly instead of downloading again. Point it at a mounted volume when the process is a container, so the layer does not re-download the model on every restart.

None
revision str | None

Branch, tag or commit sha to load; None follows the moving Hub default.

None
local_files_only bool | None

Load from the cache without touching the network — what an air-gapped or deploy-frozen host wants. None (the default) takes GENAI_OFFLINE from the environment; passing the argument overrides it.

None
hf_token str | None

Hub token for gated or private repositories. None falls back to HF_TOKEN in the environment; without either, anonymous downloads work but are rate-limited (the Hub says so on stderr).

None
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the model after this many idle seconds.

None
beam_size int

Beam width for decoding — higher is more accurate but slower. Overridable per call.

5
vad_filter bool

Drop non-speech with faster-whisper's voice activity detection before decoding. Overridable per call.

True
batch_size int | None

Decode this many VAD-detected speech spans in parallel through faster-whisper's BatchedInferencePipeline instead of one after another. None (the default) keeps the sequential path. Same model and same weights either way — only the scheduling of the decode changes — at the cost of peak memory proportional to the value. Requires vad_filter: it is the VAD that cuts the audio into the spans a batch is made of.

None
cpu_threads int

OpenMP threads per matrix op inside CTranslate2 (its intra_threads). 0 lets CTranslate2 decide, which is faster-whisper's own default.

0
num_workers int

Parallel translations inside one model (CTranslate2's inter_threads). Only matters when several transcribe calls share the instance; 1 is right when a worker handles one audio at a time.

1
condition_on_previous_text bool

Feed each window the previous window's text as context. True is faster-whisper's default and is kept here so upgrading does not silently change anybody's transcripts. Turn it off when batching: it serializes spans that would otherwise decode in parallel, and it is the documented path by which one bad span contaminates the ones after it (the repetition loop).

True
max_audio_seconds float | None

Longest decoded recording accepted. The SDK decodes the audio itself, counting samples as they come out, and refuses past this bound before the model sees anything; faster-whisper then gets the samples, not the file. None lifts the bound, for trusted, operator-supplied files only.

DEFAULT_MAX_AUDIO_SECONDS

Raises:

Type Description
ValueError

When max_concurrent is not positive, when batch_size is not positive, or when batch_size is set with vad_filter off.

is_loaded property

is_loaded: bool

Return True once the model is in memory.

seconds_idle property

seconds_idle: float

Return seconds since the model was last in use.

Reads 0.0 while a transcription is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

load

load() -> None

Download (if needed) and load the Whisper model. Idempotent.

Safe to call from several threads at once: the second caller blocks on the load lock and then sees the model the first one built, rather than building a second copy.

The is_loaded test is inside the lock, not repeated outside it as a fast path. Every call therefore pays the lifecycle's bookkeeping — the load lock plus the in-flight counter — measured at ~1.6 µs per call on a loaded model (CPython 3.11, 1M iterations, development machine), against a transcription measured in seconds. Double-checked locking would buy nothing at that price and is the shape this bug hid in once already.

Raises:

Type Description
ImportError

When the [genai-audio] extra is missing.

transcribe async

transcribe(
    audio: str | Path | bytes,
    *,
    language: LanguageEnum | str | None = None,
    with_segments: bool = True,
    with_words: bool = False,
    beam_size: int | None = None,
    vad_filter: bool | None = None,
    on_progress: Callable[[float, float], None] | None = None,
    prompt: str | None = None,
    temperature: float | None = None,
    hotwords: str | None = None,
) -> Transcription

Transcribe audio into text.

Runs the blocking model in a worker thread, capped by the concurrency semaphore.

Parameters:

Name Type Description Default
audio str | Path | bytes

Path of a local audio file, or raw bytes. URLs are not fetched.

required
language LanguageEnum | str | None

Force the language — a :class:~tempest_fastapi_sdk.genai.audio.LanguageEnum member (LanguageEnum.PT_BR), a raw Whisper code ("pt"), or None to auto-detect.

None
with_segments bool

Include per-span timestamps.

True
with_words bool

Include per-word timestamps and confidence: faster-whisper runs with word_timestamps=True (an extra alignment pass over each segment) and words is filled from each segment's words, word stripped of the leading space faster-whisper attaches, probability as faster-whisper reports it. False (the default) does not send word_timestamps and returns words=[].

False
beam_size int | None

Override the instance beam width for this call; None uses the configured default.

None
vad_filter bool | None

Override the instance VAD setting for this call; None uses the configured default.

None
on_progress Callable[[float, float], None] | None

Called as the decode advances, with (seconds_done, total_seconds). faster-whisper hands back a generator, so a long file otherwise spends minutes indistinguishable from a hang; this is what a caller turns into a log line or a progress bar. It runs on the worker thread, so it must not touch the event loop — use loop.call_soon_threadsafe if it has to.

None
prompt str | None

Passed to faster-whisper as initial_prompt: text the decoder reads as preceding the audio, the way to hand it the vocabulary of the domain (city names, product names). faster-whisper 1.2.1 keeps only the last 223 tokens of the prompt context (max_length // 2 - 1, max_length = 448). On the sequential model it conditions the first window, and later windows only while condition_on_previous_text holds; the batched pipeline (batch_size) puts it in front of every batch. None sends no prompt.

None
temperature float | None

One sampling temperature for the decode. None keeps faster-whisper's default, the fallback ladder 0.0, 0.2, ..., 1.0 the sequential model climbs when a window fails its compression or log-probability checks; a float replaces that ladder with the single value. The batched pipeline only ever uses one temperature.

None
hotwords str | None

Passed to faster-whisper as hotwords: hint phrases put in the prompt of every window, whatever condition_on_previous_text says. faster-whisper 1.2.1 keeps the first 223 tokens of it. None sends none.

None

Returns:

Name Type Description
Transcription Transcription

The transcript, language (+ probability),

Transcription

duration and segments.

Raises:

Type Description
ValidationException

When the audio declares a sample rate outside the accepted range or decodes past max_audio_seconds.

ValueError

When the audio cannot be decoded.

unload

unload() -> None

Free the model. Safe when not loaded.

While a transcription is in flight the release waits for it: the last call to finish drops the model.

unload_if_idle

unload_if_idle() -> bool

Free the model when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the model, False

bool

when it was already free, still in use, or no

bool

idle_unload_seconds was configured.

SpeechTranscriber

Bases: Protocol

Anything that turns audio into a :class:Transcription.

audio is raw bytes (what the /transcribe endpoint uploads) or a file path (what :func:~tempest_fastapi_sdk.agents.transcribe_audio_tool hands over when its path_root is set). Every SDK backend accepts both.

transcribe

transcribe(
    audio: bytes | str | Path,
    /,
    *,
    language: str | None = None,
    prompt: str | None = None,
    temperature: float | None = None,
) -> Awaitable[Transcription]

Transcribe audio.

Parameters:

Name Type Description Default
audio bytes | str | Path

The audio bytes, or a path to an audio file.

required
language str | None

A language the caller asked for, or None to let the backend decide.

None
prompt str | None

Text the decoder reads as preceding the audio, used to bias vocabulary and spelling (domain names, proper nouns), or None for no prompt.

None
temperature float | None

One sampling temperature for the decode, or None for the backend default.

None

Returns:

Type Description
Awaitable[Transcription]

Awaitable[Transcription]: The transcript.

StreamingSpeechSynthesizer

Bases: Protocol

Anything that streams speech as raw PCM while it is synthesized.

The pieces are PCM linear 16-bit little-endian, mono, at :data:~tempest_fastapi_sdk.genai.audio.PCM_SAMPLE_RATE (24 kHz), in order, each holding whole samples (an even number of bytes). A player starts on the first piece instead of waiting for the whole clip; the consumer that wants a file joins them and wraps them with :func:~tempest_fastapi_sdk.genai.audio.pcm_to_wav. Closing the iterator early stops the synthesis.

synthesize_stream

synthesize_stream(
    text: str,
    /,
    *,
    language: str | None = None,
    speaker: str | None = None,
    speaker_wav: str | Path | bytes | None = None,
) -> AsyncIterator[bytes]

Stream text as PCM pieces.

Parameters:

Name Type Description Default
text str

The text to speak.

required
language str | None

A language the caller asked for, or None.

None
speaker str | None

A speaker or voice name, or None for the backend default.

None
speaker_wav str | Path | bytes | None

A clip to clone the voice from (bytes or a local file path), or None.

None

Returns:

Type Description
AsyncIterator[bytes]

AsyncIterator[bytes]: The PCM pieces, in order.

TextToSpeech

TextToSpeech(
    model_name: str = "tts_models/multilingual/multi-dataset/xtts_v2",
    *,
    device: str = "auto",
    max_concurrent: int = 2,
    idle_unload_seconds: float | None = None,
    dtype: TTSDtype = "auto",
    sampling: XTTSSampling | None = None,
    drop_final_period: bool = True,
    pause_ms: int | None = None,
)

A lazily-loaded Coqui TTS voice.

Example:

>>> tts = TextToSpeech("tts_models/multilingual/multi-dataset/xtts_v2")
>>> wav = await tts.synthesize("Olá, mundo.", language="pt")
>>> Path("hello.wav").write_bytes(wav)

Attributes:

Name Type Description
model_name str

The Coqui model id.

device str

Resolved device (cuda / cpu).

On a server, set COQUI_TOS_AGREED=1 before the first synthesis. The default model (XTTS v2) is licence-gated, and read in coqui-tts 0.27.5, ModelManager.tos_agreed accepts only a tos_agreed.txt beside the weights or that variable set to the string "1"; otherwise ask_tos calls :func:input. Synthesis runs in asyncio.to_thread, where there is no tty to answer it, so a fresh install has nothing to type into. COQUI_TOS_AGREED=true does not count — the comparison is against "1".

dtype="float16" halves the XTTS autoregressive transformer — 1.45 GB of its 1.78 GB of weights — and keeps everything else in float32: the conditioning encoder, the perceiver and the HiFi-GAN decoder. Measured on an RTX 16 GB (coqui-tts 0.28, transformers 5.22): weights 1784 → 1034 MiB, synthesis peak 1991 → 1234 MiB, same latency, and the same word-error rate on 12 pt-BR sentences with and without cloning (0.073 against 0.103 for float32, every miss an XTTS habit both shared, such as reading the final period aloud). Halving the whole model, or wrapping it in torch.autocast, fails: the conditioning path casts to float32 on its own, and autocast trips a device-side assert in the GPT. Models other than XTTS keep float32 whatever dtype says.

With XTTS, :meth:synthesize and :meth:synthesize_stream share one path: the text is split by :func:split_for_xtts, each part loses its final period (drop_final_period) and is generated with the same sampling. Coqui's tts_to_file used to split by sentence itself, ending every one with the period XTTS reads aloud as "ponto" (7 times in 9 three-paragraph renders, against none once the period went).

Configure the voice (does not load weights yet).

Parameters:

Name Type Description Default
model_name str

Coqui TTS model id.

'tts_models/multilingual/multi-dataset/xtts_v2'
device str

"auto" / "cuda" / "cpu".

'auto'
max_concurrent int

Max simultaneous syntheses.

2
idle_unload_seconds float | None

When set, :meth:unload_if_idle frees the voice after this many idle seconds.

None
dtype TTSDtype

"auto" and "float32" keep the weights as Coqui loads them; "float16" halves the XTTS transformer (about 750 MiB less VRAM, see the class notes). CUDA only.

'auto'
sampling XTTSSampling | None

GPT sampling settings for XTTS (temperature, top_p, top_k, penalties, speed); the fields left None keep Coqui's defaults. Ignored by other models.

None
drop_final_period bool

Remove the final period of each XTTS part before generating it (see :func:drop_final_period).

True
pause_ms int | None

Silence between the parts a long XTTS text is split into. None keeps each path's behaviour: :data:XTTS_WHOLE_PAUSE_MS in :meth:synthesize, none in :meth:synthesize_stream.

None

Raises:

Type Description
ValueError

When max_concurrent is not positive, dtype is unknown, or dtype="float16" resolves to a CPU — PyTorch's CPU kernels mix badly with half precision and save nothing worth the risk there.

is_loaded property

is_loaded: bool

Return True once the model is in memory.

seconds_idle property

seconds_idle: float

Return seconds since the voice was last in use.

Reads 0.0 while a synthesis is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

for_language classmethod

for_language(
    language: LanguageEnum, *, device: str = "auto", max_concurrent: int = 2
) -> TextToSpeech

Build a voice with the default TTS model for language.

Picks a good Coqui model per language (see :func:~tempest_fastapi_sdk.genai.audio.preset_for) so you don't hand-pick a model id.

Parameters:

Name Type Description Default
language LanguageEnum

LanguageEnum.PT_BR or LanguageEnum.EN_US.

required
device str

"auto" / "cuda" / "cpu".

'auto'
max_concurrent int

Max simultaneous syntheses.

2

Returns:

Name Type Description
TextToSpeech TextToSpeech

A voice configured for the language.

load

load() -> None

Download (if needed) and load the TTS model. Idempotent.

Safe to call from several threads at once: concurrent callers on a cold instance wait for one build instead of each constructing a voice.

Raises:

Type Description
ImportError

When the [genai-tts-coqui] extra is missing.

synthesize async

synthesize(
    text: str,
    *,
    out_path: str | Path | None = None,
    speaker: str | None = None,
    language: LanguageEnum | str | None = None,
    speaker_wav: str | Path | None = None,
) -> bytes

Generate speech audio (WAV) from text.

Runs the blocking model in a worker thread, capped by the concurrency semaphore.

Parameters:

Name Type Description Default
text str

The text to speak.

required
out_path str | Path | None

When given, also write the WAV there; the bytes are returned either way.

None
speaker str | None

Speaker name for multi-speaker models.

None
language LanguageEnum | str | None

LanguageEnum for multilingual models — a :class:~tempest_fastapi_sdk.genai.audio.LanguageEnum member, a raw code ("pt"), or None.

None
speaker_wav str | Path | None

Reference clip for voice cloning (XTTS-style models).

None

Returns:

Name Type Description
bytes bytes

The synthesized WAV audio.

synthesize_stream async

synthesize_stream(
    text: str,
    /,
    *,
    language: LanguageEnum | str | None = None,
    speaker: str | None = None,
    speaker_wav: str | Path | bytes | None = None,
) -> AsyncIterator[bytes]

Stream text as 24 kHz 16-bit mono PCM while it is synthesized.

With XTTS v2 the pieces come from Coqui's inference_stream: the first one is ready after about :data:XTTS_STREAM_CHUNK_TOKENS GPT tokens instead of after the whole sentence. Text longer than the model's per-language limit is split here, by :func:split_for_xtts, and each part streamed in turn: Coqui's own splitting (enable_text_splitting) needs spaCy and raises without it. Any other model is synthesized whole and its PCM handed out in quarter-second pieces, so the call works with every voice. The generation runs in a worker thread under the same concurrency semaphore as :meth:synthesize; closing the iterator early stops it at the next piece.

Parameters:

Name Type Description Default
text str

The text to speak.

required
language LanguageEnum | str | None

As in :meth:synthesize.

None
speaker str | None

A built-in speaker name, or None.

None
speaker_wav str | Path | bytes | None

A clip to clone the voice from — bytes or a local path. Its conditioning latents are kept for the last :data:CLONE_LATENT_CACHE_SIZE clips.

None

Yields:

Name Type Description
bytes AsyncIterator[bytes]

PCM pieces, in order, each holding whole samples.

unload

unload() -> None

Free the model. Safe when not loaded.

While a synthesis is in flight the release waits for it: the last call to finish drops the voice.

unload_if_idle

unload_if_idle() -> bool

Free the voice when it has been idle past the threshold.

Returns:

Name Type Description
bool bool

True when this call unloaded the voice, False

bool

when it was already free, still in use, or no

bool

idle_unload_seconds was configured.

Transcription

Bases: BaseSchema

The result of transcribing an audio file.

Attributes:

Name Type Description
text str

The full transcript (all segments joined).

language str

Detected (or forced) language code.

language_probability float

Confidence of the detected language (0..1); 0.0 when the language was forced or unknown.

duration float

Audio duration in seconds.

segments list[TranscriptionSegment]

Per-span breakdown with timestamps (empty when segment output is disabled).

words list[TranscriptionWord]

Per-word breakdown with timestamps and confidence. Empty unless the caller asked for words (with_words=True).

TranscriptionSegment

Bases: BaseSchema

One time-stamped span of transcribed speech.

Attributes:

Name Type Description
start float

Segment start in seconds.

end float

Segment end in seconds.

text str

The transcribed text for the span.

TranscriptionWord

Bases: BaseSchema

One recognized word, with its timing and, when known, its confidence.

faster-whisper 1.2.1 hands each word back with a leading space and the punctuation glued on (" dia,", " bem?"); the SDK strips the surrounding whitespace, so the word is the same whichever backend produced it. The spacing of the full transcript stays in :attr:Transcription.text.

Attributes:

Name Type Description
word str

The word as recognized, punctuation included, surrounding whitespace stripped.

start float

Word start in seconds.

end float

Word end in seconds.

probability float | None

The recognizer's confidence in the word, 0..1. None when the source does not report it — the OpenAI wire defines no such field, so a server that sends none yields None, never a made-up 0.0.

VoiceEmbedder

VoiceEmbedder(
    *,
    model: str | Path | None = None,
    cache_dir: str | Path | None = None,
    num_threads: int = 1,
    provider: str = "cpu",
    max_concurrent: int = 2,
    idle_unload_seconds: float | None = None,
    max_audio_seconds: float | None = DEFAULT_MAX_AUDIO_SECONDS,
)

Extracts voiceprints from audio.

Loads lazily and runs inference in a worker thread, matching the rest of the audio module. Shares the embedding model with :class:~tempest_fastapi_sdk.genai.audio.diarization.SpeakerDiarizer by default, so a service doing both keeps one copy in memory.

Concurrent first calls build the extractor once, and a call in flight keeps it resident: unload_if_idle refuses while one runs, and an explicit unload waits for the last one to finish.

Attributes:

Name Type Description
idle_unload_seconds float | None

Idle time after which :meth:unload_if_idle releases the model.

max_audio_seconds float | None

Longest decoded recording accepted; None when unbounded.

Initialize the embedder without loading anything.

Parameters:

Name Type Description Default
model str | Path | None

Path to the ONNX embedding model. None resolves it from the cache, downloading on first use.

None
cache_dir str | Path | None

Where models are cached.

None
num_threads int

ONNX Runtime intra-op threads.

1
provider str

Execution provider.

'cpu'
max_concurrent int

Extractions allowed at once.

2
idle_unload_seconds float | None

Idle time after which :meth:unload_if_idle releases the model. None disables idle unloading.

None
max_audio_seconds float | None

Longest decoded recording accepted, checked while decoding. None lifts the bound, for trusted files only.

DEFAULT_MAX_AUDIO_SECONDS

Raises:

Type Description
ValueError

If max_concurrent is below 1.

dimensions property

dimensions: int

Length of the vectors this model produces.

Returns:

Name Type Description
int int

The dimension, loading the model if needed.

is_loaded property

is_loaded: bool

Whether the model is resident.

Returns:

Name Type Description
bool bool

True once loaded.

seconds_idle property

seconds_idle: float

Seconds since the model was last in use.

Reads 0.0 while an extraction is in flight.

Returns:

Name Type Description
float float

Idle time in seconds.

embed async

embed(
    audio: str | Path | bytes, *, start: float | None = None, end: float | None = None
) -> list[float]

Extract a voiceprint from a recording, or a span of one.

Parameters:

Name Type Description Default
audio str | Path | bytes

The recording.

required
start float | None

Span start in seconds. None starts at the beginning.

None
end float | None

Span end in seconds. None runs to the end.

None

Returns:

Type Description
list[float]

list[float]: The voiceprint.

Raises:

Type Description
ImportError

When the [genai-diarization] extra is absent.

ValueError

When the span is empty.

ValidationException

When the audio declares a sample rate outside the accepted range or decodes past max_audio_seconds.

embed_for_enrollment async

embed_for_enrollment(
    audio: str | Path | bytes, *, min_seconds: float = MIN_ENROLLMENT_SECONDS
) -> list[float]

Extract a voiceprint, refusing audio too short to be one.

Enrolment is the one place where a bad vector is not a bad answer but a permanently bad profile — it will keep matching the wrong people until somebody deletes it. So the length check lives here rather than in :meth:embed, which legitimately runs on two-second turns.

The recording is decoded once: the measurement and the extraction read the same pass, in the same worker thread, under the same concurrency bound as :meth:embed.

Parameters:

Name Type Description Default
audio str | Path | bytes

The enrolment recording.

required
min_seconds float

Shortest audio accepted. Measured on the decoded waveform, so a container claiming a longer duration than it carries is still refused.

MIN_ENROLLMENT_SECONDS

Returns:

Type Description
list[float]

list[float]: The voiceprint.

Raises:

Type Description
ValueError

When the recording is shorter than min_seconds.

ImportError

When the [genai-diarization] extra is absent.

ValidationException

When the audio declares a sample rate outside the accepted range or decodes past max_audio_seconds.

load

load() -> None

Resolve and load the embedding model. Idempotent.

Safe to call from several threads at once: concurrent callers on a cold instance wait for one build.

Raises:

Type Description
ImportError

When the [genai-diarization] extra is absent.

unload

unload() -> None

Release the model.

While an extraction is in flight the release waits for it: the last call to finish drops the extractor.

unload_if_idle

unload_if_idle() -> bool

Release the model when idle past idle_unload_seconds.

Returns:

Name Type Description
bool bool

Whether anything was unloaded — never while an

bool

extraction is in flight, and never when no

bool

idle_unload_seconds was configured.

VoiceMatch

Bases: BaseSchema

A voice matched against an enrolled profile.

Attributes:

Name Type Description
profile_id UUID

The profile that matched.

user_id UUID

Who it belongs to.

similarity float

Cosine similarity, 0..1 in practice.

label str | None

The profile's label.

VoiceProfileSchema

Bases: BaseSchema

One enrolled voice profile, as the owner sees it.

The embedding itself is deliberately absent: the person needs to know that a profile exists and when it was made, not to receive a copy of their own biometric template over HTTP.

Attributes:

Name Type Description
id UUID

Profile identifier, for deletion.

label str | None

What the enrolment recording was.

model_name str

Embedding model that produced it.

consent_at str

When consent was recorded, ISO-8601.

consent_reference str

What they consented to.

created_at str

When the profile was enrolled, ISO-8601.

last_matched_at str | None

Last time it matched, ISO-8601.

VoiceProfileService

VoiceProfileService(
    *,
    profile_model: type[BaseVoiceProfileModel],
    embedder: VoiceEmbedder | None = None,
    threshold: float = DEFAULT_MATCH_THRESHOLD,
    model_name: str = DEFAULT_MODEL_NAME,
)

Enrolment, recognition and deletion of voice profiles.

Attributes:

Name Type Description
profile_model type[BaseVoiceProfileModel]

The project's model.

embedder VoiceEmbedder

Produces the voiceprints.

threshold float

Similarity above which a voice is a match.

model_name str

Recorded on every profile written.

Initialize the service.

Parameters:

Name Type Description Default
profile_model type[BaseVoiceProfileModel]

Concrete model.

required
embedder VoiceEmbedder | None

Voiceprint extractor. None builds a default one.

None
threshold float

Similarity above which a voice matches. Raise it for anything that grants access; the default suits attributing lines in a transcript.

DEFAULT_MATCH_THRESHOLD
model_name str

Recorded on every profile written.

DEFAULT_MODEL_NAME

Raises:

Type Description
ValueError

When threshold is outside 0..1.

delete_profile async

delete_profile(session: AsyncSession, *, user_id: UUID, profile_id: UUID) -> None

Delete one profile.

Scoped to its owner, so a profile belonging to somebody else answers 404 exactly like one that does not exist.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required
user_id UUID

The owner.

required
profile_id UUID

The profile to delete.

required

Raises:

Type Description
NotFoundException

When that person holds no such profile.

enroll async

enroll(
    session: AsyncSession,
    *,
    user_id: UUID,
    audio: str | Path | bytes,
    consent_reference: str,
    consent_at: datetime | None = None,
    label: str | None = None,
    min_seconds: float = MIN_ENROLLMENT_SECONDS,
) -> BaseVoiceProfileModel

Record a voiceprint for user_id.

The audio is used and discarded — only the vector is stored, and nothing here writes the recording to disk.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required
user_id UUID

Who is enrolling.

required
audio str | Path | bytes

The enrolment recording.

required
consent_reference str

Evidence of the person's specific consent to voice biometrics — a policy version, a signed document id, a ticket. Required.

required
consent_at datetime | None

When they consented. Defaults to now, which is right when consent is collected in the same request and wrong when it was collected earlier — pass the real timestamp in that case.

None
label str | None

What this recording was.

None
min_seconds float

Shortest audio accepted.

MIN_ENROLLMENT_SECONDS

Returns:

Name Type Description
BaseVoiceProfileModel BaseVoiceProfileModel

The persisted profile.

Raises:

Type Description
ConsentRequired

When consent_reference is blank.

ValueError

When the recording is too short to enrol from.

forget_user async

forget_user(session: AsyncSession, *, user_id: UUID) -> int

Delete every voiceprint a person has enrolled.

This is the request the LGPD gives them an unconditional right to make (Art. 18, VI). It is a method rather than an example in the docs because "delete my biometric data" must not depend on each project writing the query correctly.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required
user_id UUID

Whose data to erase.

required

Returns:

Name Type Description
int int

How many profiles were deleted; 0 when there were

int

none, which is a successful outcome, not an error.

identify async

identify(
    session: AsyncSession, *, embedding: list[float], user_ids: list[UUID] | None = None
) -> VoiceMatch | None

Find the enrolled profile a voiceprint belongs to.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required
embedding list[float]

The voiceprint to identify.

required
user_ids list[UUID] | None

Restrict the search to these people. Pass the meeting's participants and the search stops being "who in the database is this" — smaller, faster, and far less likely to match a stranger.

None

Returns:

Type Description
VoiceMatch | None

VoiceMatch | None: The best match above the threshold, or

VoiceMatch | None

None. None means not recognised, which is not the

VoiceMatch | None

same as nobody spoke.

identify_audio async

identify_audio(
    session: AsyncSession,
    *,
    audio: str | Path | bytes,
    start: float | None = None,
    end: float | None = None,
    user_ids: list[UUID] | None = None,
) -> VoiceMatch | None

Identify the speaker in a recording, or a span of one.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required
audio str | Path | bytes

The recording.

required
start float | None

Span start in seconds.

None
end float | None

Span end in seconds.

None
user_ids list[UUID] | None

Restrict the search.

None

Returns:

Type Description
VoiceMatch | None

VoiceMatch | None: The best match, or None.

list_profiles async

list_profiles(session: AsyncSession, *, user_id: UUID) -> list[BaseVoiceProfileModel]

Return every profile enrolled by one person.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required
user_id UUID

Whose profiles to list.

required

Returns:

Type Description
list[BaseVoiceProfileModel]

list[BaseVoiceProfileModel]: The profiles, empty when there

list[BaseVoiceProfileModel]

are none.

stale_profiles async

stale_profiles(session: AsyncSession) -> list[BaseVoiceProfileModel]

Return profiles written by a different embedding model.

Swapping the model invalidates every existing profile: their vectors are no longer comparable, so those people silently stop being recognised. This is how you find them to re-enrol.

Parameters:

Name Type Description Default
session AsyncSession

Active SQLAlchemy session.

required

Returns:

Type Description
list[BaseVoiceProfileModel]

list[BaseVoiceProfileModel]: Profiles from another model.

XTTSSampling dataclass

XTTSSampling(
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    repetition_penalty: float | None = None,
    length_penalty: float | None = None,
    speed: float | None = None,
)

Sampling settings for the XTTS GPT; None keeps the model's own.

Example:

>>> XTTSSampling(temperature=0.7, top_p=0.9).as_kwargs()
{'temperature': 0.7, 'top_p': 0.9}

Attributes:

Name Type Description
temperature float | None

Softmax temperature; lower is steadier and flatter, higher more varied. Coqui's default is 0.75.

top_p float | None

Nucleus sampling mass, in (0, 1] (default 0.85).

top_k int | None

Candidates kept per step (default 50).

repetition_penalty float | None

Penalty on repeated audio tokens (10.0 in inference_stream, 5.0 in the model config).

length_penalty float | None

Length penalty of the GPT's search (default 1.0).

speed float | None

Speaking-rate factor applied by the model (default 1.0).

Measured with UTMOS on ten pt-BR sentences, two seeds each, on the built-in "Ana Florence": temperature 0.65, repetition_penalty 5.0, temperature 0.85 with top_p 0.9, speed 1.05 and a 40-token stream chunk all landed within the seed-to-seed spread (about ±0.15 MOS around 3.6), so the defaults stay Coqui's. These are knobs for a voice or language where they do matter, not a fix.

as_kwargs

as_kwargs() -> dict[str, float | int]

Return the settings that were given, as XTTS keyword arguments.

Returns:

Type Description
dict[str, float | int]

dict[str, float | int]: Only the fields that are not None,

dict[str, float | int]

ready for inference / inference_stream.

affinity_report

affinity_report(embeddings: Sequence[Sequence[float]]) -> dict[str, Any]

Return the intermediate numbers behind an estimate.

Exists because "the estimator said four" is not something a person can act on. The eigenvalues and their gaps show how close the call was: a wide margin means the recording really does split four ways, while two near-equal gaps mean the answer could as easily have been three, which is the moment to pass num_speakers explicitly.

Parameters:

Name Type Description Default
embeddings Sequence[Sequence[float]]

One voiceprint per turn.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: estimated, the sorted eigenvalues, the

dict[str, Any]

gaps between them, and margin — how much the winning gap

dict[str, Any]

beat the runner-up, 0.0 when there is no runner-up.

align_turns

align_turns(
    turns: list[SpeakerTurn], segments: list[TranscriptionSegment]
) -> list[SpeakerTurn]

Attach transcribed text to the speaker turns it overlaps.

Each transcription segment goes to the turn sharing the most time with it. A segment overlapping nothing — speech the diarizer dropped as too short, or audio outside every turn — is kept as its own turn with speaker -1 rather than discarded: losing words silently is worse than admitting the speaker is unknown.

Parameters:

Name Type Description Default
turns list[SpeakerTurn]

Diarized turns, chronological.

required
segments list[TranscriptionSegment]

Transcribed spans.

required

Returns:

Type Description
list[SpeakerTurn]

list[SpeakerTurn]: Turns carrying text, chronological, with

list[SpeakerTurn]

empty turns dropped.

cosine_similarity

cosine_similarity(first: Sequence[float], second: Sequence[float]) -> float

Compare two voiceprints.

Parameters:

Name Type Description Default
first Sequence[float]

A voice embedding.

required
second Sequence[float]

Another voice embedding.

required

Returns:

Name Type Description
float float

Cosine similarity in [-1, 1]; 0.0 when either

float

vector is all zeros, which is what an empty recording produces.

Raises:

Type Description
ValueError

When the vectors have different lengths — that means two different models, and the comparison would be a number with no meaning rather than a low score.

default_cache_dir

default_cache_dir() -> Path

Return where models are cached when the caller names no directory.

Honors TEMPEST_VOICE_MODEL_DIR first so a deployment can point at a baked image layer or a mounted volume, then falls back to the XDG cache location.

Returns:

Name Type Description
Path Path

The cache root. Not created here.

drop_final_period

drop_final_period(text: str) -> str

Remove a single trailing period, which XTTS may read aloud.

An ellipsis (... or …), a question mark and an exclamation mark are kept: they change the intonation and are never spoken as words.

Parameters:

Name Type Description Default
text str

One part of the text, as sent to the model.

required

Returns:

Name Type Description
str str

The text without its final period, right-stripped.

Measured on the built-in "Ana Florence" through tempest-ai and Whisper large-v3-turbo: six pt-BR sentences, four syntheses each, ended with a period came back with an extra "ponto" 5 times in 24; without it, 0 in 24, at the same UTMOS (3.85 against 3.83).

ensure_models

ensure_models(
    cache_dir: str | Path | None = None,
    *,
    models: Sequence[DiarizationModel] = (SEGMENTATION_MODEL, EMBEDDING_MODEL),
) -> dict[str, Path]

Download the diarization models if they are not cached yet.

Call it at build or startup time. Leaving it to the first request means one caller pays a 46 MB download inside their timeout.

Parameters:

Name Type Description Default
cache_dir str | Path | None

Where to keep them. None uses :func:default_cache_dir.

None
models Sequence[DiarizationModel]

Which models to ensure.

(SEGMENTATION_MODEL, EMBEDDING_MODEL)

Returns:

Type Description
dict[str, Path]

dict[str, Path]: Model name to the resolved file on disk.

Raises:

Type Description
OSError

When a download fails or an archive lacks its member.

estimate_speaker_count

estimate_speaker_count(
    embeddings: Sequence[Sequence[float]],
    *,
    max_speakers: int = DEFAULT_MAX_SPEAKERS,
    percentile: float = DEFAULT_AFFINITY_PERCENTILE,
) -> int

Infer how many distinct voices a set of turn embeddings holds.

Builds a cosine affinity matrix over the turns, prunes each row to its strongest links, and reads the number of speakers off the largest gap between consecutive eigenvalues of the normalized Laplacian.

Parameters:

Name Type Description Default
embeddings Sequence[Sequence[float]]

One voiceprint per turn.

required
max_speakers int

Largest count to consider.

DEFAULT_MAX_SPEAKERS
percentile float

Fraction of each row suppressed, in 0..1. Higher prunes more.

DEFAULT_AFFINITY_PERCENTILE

Returns:

Name Type Description
int int

The estimated speaker count, at least 1. A single turn is

int

one speaker by definition — there is nothing to compare it to.

Raises:

Type Description
ValueError

If max_speakers is below 1 or percentile is outside 0..1.

ImportError

When NumPy is missing — install the [genai-diarization] extra.

float_to_pcm16

float_to_pcm16(
    samples: object, sample_rate: int, target_rate: int = PCM_SAMPLE_RATE
) -> bytes

Convert float samples in [-1, 1] to 16-bit PCM at target_rate.

Accepts a NumPy array, a PyTorch tensor (moved to the CPU) or a list. Values outside the range are clipped, not wrapped, and rounded to the nearest step instead of truncated. A rate other than target_rate is resampled by linear interpolation, which is enough for speech going to a speaker.

Parameters:

Name Type Description Default
samples object

The waveform.

required
sample_rate int

Its rate in Hz.

required
target_rate int

The rate to emit.

PCM_SAMPLE_RATE

Returns:

Name Type Description
bytes bytes

16-bit little-endian mono PCM.

half_xtts_transformer

half_xtts_transformer(voice: object) -> bool

Run an XTTS voice's autoregressive transformer in float16.

Halves the GPT (and its embeddings and heads), then puts the conditioning encoder and perceiver back in float32: their GroupNorm32 casts its input to float32 itself, so they cannot run in half. Two seams keep the dtypes apart:

  • Coqui replaces GPT-2's position embedding with a function returning float32 zeros, which would promote every hidden state back to float32 (expected scalar type Float but found Half in the first LayerNorm); it is replaced by zeros in the transformer's dtype.
  • The float32 conditioning latents are cast to float16 on the way into the GPT (forward and generate) and its float16 output back to float32 on the way out, so the HiFi-GAN decoder keeps float32.

Parameters:

Name Type Description Default
voice object

A loaded TTS.api.TTS instance.

required

Returns:

Name Type Description
bool bool

True when the voice is XTTS and was converted, False

bool

when it is another model, left as loaded.

make_voice_router

make_voice_router(
    *,
    session_factory: Callable[..., AsyncIterator[AsyncSession]],
    transcriber: ConversationTranscriber | None = None,
    profiles: VoiceProfileService | None = None,
    current_user_id: Callable[..., Any] | None = None,
    prefix: str = "/voice",
    tags: list[str] | None = None,
    dependencies: Sequence[Any] | None = None,
    max_upload_bytes: int = DEFAULT_MAX_UPLOAD_BYTES,
    docs_locale: str | None = None,
) -> APIRouter

Build the voice router, mounting only what was injected.

Parameters:

Name Type Description Default
session_factory Callable

FastAPI dependency yielding an async session.

required
transcriber ConversationTranscriber | None

Mounts POST /voice/transcribe when given.

None
profiles VoiceProfileService | None

Mounts the enrolment, listing and erasure routes when given.

None
current_user_id Callable[..., Any] | None

Dependency resolving the caller's user id. Required alongside profiles: enrolling or erasing on behalf of a user id taken from the request body would let anyone write biometric data against somebody else's account.

None
prefix str

URL prefix.

'/voice'
tags list[str] | None

OpenAPI tags.

None
dependencies Sequence[Any] | None

Applied to every route — where authentication and rate limiting go.

None
max_upload_bytes int

Largest accepted upload.

DEFAULT_MAX_UPLOAD_BYTES
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount.

Raises:

Type Description
ValueError

When profiles is given without current_user_id, or when neither surface was injected — an empty router is a wiring mistake, not a configuration.

pack_embedding

pack_embedding(embedding: list[float]) -> bytes

Serialize a voiceprint for storage.

Little-endian float32, fixed by this function rather than by the platform: a profile written on one architecture has to be readable on another, and struct without an explicit byte order is not.

Parameters:

Name Type Description Default
embedding list[float]

The vector.

required

Returns:

Name Type Description
bytes bytes

The packed vector.

pcm_to_wav

pcm_to_wav(pcm: bytes, sample_rate: int = PCM_SAMPLE_RATE) -> bytes

Wrap raw 16-bit mono PCM in a WAV header.

Parameters:

Name Type Description Default
pcm bytes

The samples, 16-bit little-endian mono.

required
sample_rate int

Their rate in Hz.

PCM_SAMPLE_RATE

Returns:

Name Type Description
bytes bytes

A complete WAV file.

Raises:

Type Description
ValueError

When pcm has an odd number of bytes (a sample cut in half) or sample_rate is not positive.

preset_for

preset_for(language: LanguageEnum) -> LanguagePreset

Return the audio preset for language.

Parameters:

Name Type Description Default
language LanguageEnum

The target language.

required

Returns:

Name Type Description
LanguagePreset LanguagePreset

Whisper code + default TTS model for it.

resolve_audio_device

resolve_audio_device(device: str) -> str

Resolve "auto" to "cuda" when a GPU is present, else "cpu".

faster-whisper targets CUDA or CPU (no MPS), so anything non-CUDA resolves to "cpu".

Parameters:

Name Type Description Default
device str

"auto", "cuda" or "cpu".

required

Returns:

Name Type Description
str str

The concrete device.

Detection needs torch, and a missing torch is logged at warning level rather than folded into "no GPU". They are not the same answer: a machine with a GPU whose environment has no torch used to transcribe on the CPU with no sign at all, and the slowdown looked like faster-whisper being slow.

silence_pcm

silence_pcm(milliseconds: int, sample_rate: int = PCM_SAMPLE_RATE) -> bytes

Return milliseconds of 16-bit mono silence.

Parameters:

Name Type Description Default
milliseconds int

Length of the silence; zero or less is empty.

required
sample_rate int

Rate of the PCM it is joined to.

PCM_SAMPLE_RATE

Returns:

Name Type Description
bytes bytes

Zero samples, little-endian 16-bit.

split_for_bark

split_for_bark(text: str, max_chars: int = DEFAULT_MAX_CHUNK_CHARS) -> list[str]

Split text into pieces Bark speaks without cutting.

Sentences (see :func:_sentences) are grouped greedily up to max_chars; a longer sentence is split at commas, then at spaces. No word is dropped or reordered, and a single word longer than max_chars is kept whole. Pieces with no letter or digit ("...") are dropped, since Bark has nothing to say for them.

Parameters:

Name Type Description Default
text str

The text to speak.

required
max_chars int

The largest piece allowed.

DEFAULT_MAX_CHUNK_CHARS

Returns:

Type Description
list[str]

list[str]: The pieces, in order; empty when nothing is speakable.

Raises:

Type Description
ValueError

When max_chars is not positive.

split_for_xtts

split_for_xtts(text: str, limit: int = XTTS_DEFAULT_CHAR_LIMIT) -> list[str]

Split text into parts XTTS can speak without truncating.

Sentences are kept whole when they fit, packed together up to limit characters; a longer sentence is cut at commas, and a clause still too long at word boundaries. No part is empty, and only a single word longer than limit can exceed it. Coqui's own splitter does the same with spaCy, which is not a dependency.

Parameters:

Name Type Description Default
text str

The text to speak.

required
limit int

Maximum characters per part.

XTTS_DEFAULT_CHAR_LIMIT

Returns:

Type Description
list[str]

list[str]: The parts, in order.

split_pcm

split_pcm(pcm: bytes, chunk_bytes: int = PCM_CHUNK_BYTES) -> Iterator[bytes]

Cut PCM into pieces of whole samples, in order.

Parameters:

Name Type Description Default
pcm bytes

The samples.

required
chunk_bytes int

Target piece size; rounded down to an even number.

PCM_CHUNK_BYTES

Yields:

Name Type Description
bytes bytes

The pieces, each holding whole samples.

unpack_embedding

unpack_embedding(payload: bytes, dimensions: int) -> list[float]

Read a stored voiceprint back.

Parameters:

Name Type Description Default
payload bytes

The packed vector.

required
dimensions int

How many values it should hold.

required

Returns:

Type Description
list[float]

list[float]: The vector.

Raises:

Type Description
ValueError

When the byte length does not match dimensions — a truncated or foreign row, which must not be compared.

wav_to_pcm

wav_to_pcm(wav: bytes) -> tuple[bytes, int]

Read a 16-bit mono WAV back into raw PCM and its rate.

Parameters:

Name Type Description Default
wav bytes

A WAV file, 16-bit, mono.

required

Returns:

Type Description
tuple[bytes, int]

tuple[bytes, int]: The samples and their rate in Hz.

Raises:

Type Description
ValueError

When the file is not 16-bit mono.