tempest_fastapi_sdk.genai.audio¶
Áudio self-hosted: fala para texto e texto para fala.
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
¶
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
¶
The checkpoint measured for this module.
DEFAULT_CLUSTERING_THRESHOLD
module-attribute
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
Most channels accepted in a WAV file (7.1 surround).
MAX_SOURCE_RATE
module-attribute
¶
Highest declared sample rate accepted, in Hz.
192 kHz is the top rate professional audio interfaces record at.
MIN_ENROLLMENT_SECONDS
module-attribute
¶
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
¶
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_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
¶
Sample rate of streamed speech, in Hz (XTTS v2 and Bark output).
PCM_SAMPLE_WIDTH
module-attribute
¶
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
¶
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
¶
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 |
pause_seconds |
float
|
Silence inserted between pieces. |
idle_unload_seconds |
float | None
|
Idle threshold used by
:meth: |
Configure the synthesizer (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
|
DEFAULT_BARK_MODEL
|
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where weights are downloaded and read. |
None
|
hf_token
|
str | None
|
Hub 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
|
max_chunk_chars
|
int
|
Largest piece per |
DEFAULT_MAX_CHUNK_CHARS
|
pause_seconds
|
float
|
Silence between pieces. |
0.25
|
max_concurrent
|
int
|
Simultaneous syntheses. Defaults to |
1
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device resolution (tests). |
None
|
metrics
|
GenAIMetrics | None
|
Optional Prometheus metrics,
recorded under op |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_loaded
property
¶
Return True once the model is in memory.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether :meth: |
load
¶
Download (if needed) and load the processor and model.
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
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
|
|
None
|
speaker
|
str | None
|
A preset from :meth: |
None
|
seed
|
int | None
|
Seed applied with |
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
|
|
ImportError
|
When the |
unload_if_idle
¶
Free the model when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
voices
¶
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 |
ConsentRequired
¶
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
|
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
|
identify_with
|
VoiceProfileService | None
|
Match each
speaker against enrolled voice profiles. Requires
|
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 |
DiarizationModel
dataclass
¶
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
|
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
¶
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
¶
Render the conversation as labelled lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unknown
|
str
|
Template for an unidentified speaker, with a
|
'Falante {speaker}'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
One |
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. |
LanguageEnum
¶
LanguagePreset
¶
Bases: BaseSchema
Per-language identifiers for the audio engines.
Attributes:
| Name | Type | Description |
|---|---|---|
whisper_language |
str
|
The faster-whisper language code
( |
tts_model |
str
|
A good default Coqui TTS model for the language. |
tts_language |
str | None
|
The Coqui |
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.
feed
¶
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.
|
threshold |
float
|
Clustering threshold, used when
|
max_audio_seconds |
float | None
|
Longest decoded recording
accepted; |
Initialize the diarizer without loading anything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation_model
|
str | Path | None
|
Path to the ONNX
segmentation model. |
None
|
embedding_model
|
str | Path | None
|
Path to the ONNX speaker
embedding model. |
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'
|
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'
|
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: |
None
|
max_audio_seconds
|
float | None
|
Longest decoded recording
accepted, checked while decoding and before the engine
runs. |
DEFAULT_MAX_AUDIO_SECONDS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
is_loaded
property
¶
Whether the models are resident.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
seconds_idle
property
¶
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
|
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 |
ValueError
|
When |
ValidationException
|
When the audio declares a sample rate
outside the accepted range or decodes past
|
load
¶
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 |
unload
¶
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
¶
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 |
speaker_id |
str | None
|
Enrolled profile this turn matched, when
identification ran and cleared the threshold. |
speaker_name |
str | None
|
Display name of the matched profile. |
confidence |
float
|
Cosine similarity against the matched
profile, |
text |
str
|
What was said, empty until transcription is joined in. |
duration
property
¶
Length of the turn in seconds.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
|
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
|
speaker
|
str | None
|
A speaker or voice name, or |
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 ( |
device |
str
|
Resolved device ( |
compute_type |
str
|
Resolved faster-whisper compute type. |
max_audio_seconds |
float | None
|
Longest decoded recording
accepted; |
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'
|
compute_type
|
str
|
faster-whisper compute type or |
'auto'
|
max_concurrent
|
int
|
Max simultaneous transcriptions. |
2
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
None
|
hf_token
|
str | None
|
Hub token for gated or private
repositories. |
None
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
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
|
None
|
cpu_threads
|
int
|
OpenMP threads per matrix op inside
CTranslate2 (its |
0
|
num_workers
|
int
|
Parallel translations inside one model
(CTranslate2's |
1
|
condition_on_previous_text
|
bool
|
Feed each window the previous
window's text as context. |
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. |
DEFAULT_MAX_AUDIO_SECONDS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
seconds_idle
property
¶
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
¶
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 |
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: |
None
|
with_segments
|
bool
|
Include per-span timestamps. |
True
|
with_words
|
bool
|
Include per-word timestamps and confidence:
faster-whisper runs with |
False
|
beam_size
|
int | None
|
Override the instance beam width for
this call; |
None
|
vad_filter
|
bool | None
|
Override the instance VAD setting for
this call; |
None
|
on_progress
|
Callable[[float, float], None] | None
|
Called as
the decode advances, with |
None
|
prompt
|
str | None
|
Passed to faster-whisper as
|
None
|
temperature
|
float | None
|
One sampling temperature for the
decode. |
None
|
hotwords
|
str | None
|
Passed to faster-whisper as
|
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
|
ValueError
|
When the audio cannot be decoded. |
unload
¶
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
¶
Free the model when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already free, still in use, or no |
|
bool
|
|
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
|
prompt
|
str | None
|
Text the decoder reads as preceding the
audio, used to bias vocabulary and spelling (domain names,
proper nouns), or |
None
|
temperature
|
float | None
|
One sampling temperature for the
decode, or |
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
|
speaker
|
str | None
|
A speaker or voice name, or |
None
|
speaker_wav
|
str | Path | bytes | None
|
A clip to clone the
voice from (bytes or a local file path), or |
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 ( |
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'
|
max_concurrent
|
int
|
Max simultaneous syntheses. |
2
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
dtype
|
TTSDtype
|
|
'auto'
|
sampling
|
XTTSSampling | None
|
GPT sampling settings for XTTS
(temperature, |
None
|
drop_final_period
|
bool
|
Remove the final period of each XTTS
part before generating it (see :func: |
True
|
pause_ms
|
int | None
|
Silence between the parts a long XTTS
text is split into. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
seconds_idle
property
¶
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
|
|
required |
device
|
str
|
|
'auto'
|
max_concurrent
|
int
|
Max simultaneous syntheses. |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
TextToSpeech |
TextToSpeech
|
A voice configured for the language. |
load
¶
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 |
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: |
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: |
None
|
speaker
|
str | None
|
A built-in speaker name, or |
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: |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
bytes |
AsyncIterator[bytes]
|
PCM pieces, in order, each holding whole samples. |
unload
¶
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
¶
Free the voice when it has been idle past the threshold.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already free, still in use, or no |
|
bool
|
|
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
( |
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
( |
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, |
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: |
max_audio_seconds |
float | None
|
Longest decoded recording
accepted; |
Initialize the embedder without loading anything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | Path | None
|
Path to the ONNX embedding model.
|
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: |
None
|
max_audio_seconds
|
float | None
|
Longest decoded recording
accepted, checked while decoding. |
DEFAULT_MAX_AUDIO_SECONDS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
dimensions
property
¶
Length of the vectors this model produces.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The dimension, loading the model if needed. |
is_loaded
property
¶
Whether the model is resident.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
seconds_idle
property
¶
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
|
end
|
float | None
|
Span end in seconds. |
None
|
Returns:
| Type | Description |
|---|---|
list[float]
|
list[float]: The voiceprint. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When the span is empty. |
ValidationException
|
When the audio declares a sample rate
outside the accepted range or decodes past
|
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
|
ImportError
|
When the |
ValidationException
|
When the audio declares a sample rate
outside the accepted range or decodes past
|
load
¶
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 |
unload
¶
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
¶
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
|
|
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, |
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
|
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 |
delete_profile
async
¶
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 |
ValueError
|
When the recording is too short to enrol from. |
forget_user
async
¶
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; |
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
|
|
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 |
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 |
top_k |
int | None
|
Candidates kept per step (default 50). |
repetition_penalty |
float | None
|
Penalty on repeated audio tokens
(10.0 in |
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
¶
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 |
dict[str, float | int]
|
ready for |
affinity_report
¶
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]: |
dict[str, Any]
|
|
dict[str, Any]
|
beat the 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
¶
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 |
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
¶
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
¶
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
|
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
|
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 |
ImportError
|
When NumPy is missing — install the
|
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
¶
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 Halfin the firstLayerNorm); 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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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
|
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
|
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
pack_embedding
¶
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 |
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 "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
|
|
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 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 |
split_for_xtts
¶
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
¶
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 |
wav_to_pcm
¶
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. |