Audio: STT and TTS¶
Use to transcribe audio (STT) and generate speech (TTS), and to pick the language and voice model by licence and where it runs.
Part of the Self-hosted generative AI recipe.
Interpret and generate voice on your hardware — no external API. Needs the
[genai-audio] extra (faster-whisper) to transcribe and, for Coqui TTS
(XTTS v2), [genai-tts-coqui] — split from [genai-audio] since 0.349.0
(why); the engines import
lazily.
In v0.252.0 the extra started shipping the Coqui runtime
coqui-tts keeps torch, torchaudio and torchcodec behind its own extras
([cpu], [cuda], [codec]), so up to v0.251.0 installing
[genai-audio] gave you a TTS that would not import. Measured with
coqui-tts 0.27.5 and torch 2.13.0:
And with torchaudio in place, a fresh resolve brought transformers 5.x,
which removed the symbol TTS.api imported eagerly:
That is why, from v0.252.0 to 0.341.0, the extra pinned
transformers<5. coqui-tts 0.28.0 no longer imports that symbol, and
since 0.342.0 the Coqui extra (today [genai-tts-coqui]) requires that
version and drops the cap.
Measured on 2026-11-01 with coqui-tts 0.28.0, transformers 5.22.1 and
torch 2.14: XTTS v2 with a built-in voice and with cloning, and Bark,
synthesized a Portuguese sentence that Whisper transcribed back
word for word. [genai-tts-coqui] declares torch>=2.14,
torchaudio>=2.11, torchcodec>=0.16 and six (coqui-tts 0.28.0 imports
it without declaring it). If you pinned those by hand, you can drop them.
With coqui-tts 0.28.0, XTTS v2 comes from the Hugging Face Hub
The model is downloaded from the tts-hub/XTTS-v2 repository into the
Hub cache (~/.cache/huggingface/hub/models--tts-hub--XTTS-v2), no longer
only into ~/.local/share/tts. The first use needs network; with the
cache filled, HF_HUB_OFFLINE=1 works (measured: synthesis completed
offline). In a container, mount that directory on a volume so a deploy
does not download it again.
On load, transformers 5 logs
bos_token_id must be None or an integer within the vocabulary ... got 50256
(and the same for eos_token_id). Synthesis completes normally.
XTTS v2 asks you to accept a licence, and a server has nobody to answer
TextToSpeech's default model is licence-gated. Read in coqui-tts 0.28.0,
ModelManager.tos_agreed accepts only a tos_agreed.txt beside the
weights or COQUI_TOS_AGREED equal to the string "1"; without
it, ask_tos calls input(). Synthesis runs in asyncio.to_thread,
where there is no tty to answer — so export it before the first
synthesize:
COQUI_TOS_AGREED=true does not count: the comparison is against "1".
Interpret audio (STT)¶
SpeechToText transcribes with faster-whisper (Whisper via
CTranslate2, fast on CPU/GPU). Loads once, runs in a worker thread,
serializes calls through a semaphore.
import asyncio
from tempest_fastapi_sdk.genai.audio import SpeechToText
stt = SpeechToText("base", device="auto") # tiny…large-v3
async def main() -> None:
"""Run this example."""
result = await stt.transcribe("meeting.wav")
print(result.text, result.language, result.duration)
for seg in result.segments: # per-span timestamps
print(seg.start, seg.end, seg.text)
asyncio.run(main())
Accepts a local file path or bytes — a string that is not an existing file (a URL, an FFmpeg protocol such as concat:) raises FileNotFoundError without touching the network. device/compute_type resolve automatically
(float16 on GPU, int8 on CPU).
Transcribing faster on CPU¶
The four knobs below change how the decode is scheduled, not which weights run — same model, same precision:
from tempest_fastapi_sdk.genai.audio import SpeechToText
stt = SpeechToText(
"large-v3-turbo",
device="cpu",
compute_type="int8",
batch_size=8, # decode 8 speech spans in parallel
cpu_threads=0, # 0 = CTranslate2 decides (intra_threads)
num_workers=1, # parallel translations in one model
condition_on_previous_text=False, # turn off alongside batch_size
)
batch_sizeswaps sequentialWhisperModel.transcribe()for faster-whisper'sBatchedInferencePipeline. It requiresvad_filter=True— the VAD is what cuts the audio into the spans a batch is made of — and passing one without the other raisesValueErrorat construction, not on the first transcription. The cost is peak memory proportional to the value.cpu_threads/num_workersare CTranslate2'sintra_threads/inter_threads.num_workersonly matters when several concurrent calls share the instance.condition_on_previous_texthands each window the previous window's text as context. The default isTrue, which is faster-whisper's own — kept so an SDK upgrade 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 path by which one bad span contaminates the ones after it (the repetition loop).
A long file should not look like a hang
faster-whisper hands back a generator, so an hour-long meeting spends
minutes with no signal at all. on_progress receives
(seconds_done, total_seconds) as the decode advances:
import asyncio
import logging
from tempest_fastapi_sdk.genai.audio import SpeechToText
logger = logging.getLogger(__name__)
stt = SpeechToText("base", device="cpu")
async def main() -> None:
"""Run this example."""
def progress(done: float, total: float) -> None:
"""Log how far the decode got."""
logger.info("transcribed %.1fs of %.1fs", done, total)
await stt.transcribe("meeting.wav", on_progress=progress)
asyncio.run(main())
The callback runs on the worker thread, not the event loop: do not
touch a coroutine in there without loop.call_soon_threadsafe.
Give Whisper the vocabulary: prompt and hotwords¶
Proper nouns are where Whisper misses most: in a voice search for bus
tickets, "from Picos to Parnaíba tomorrow" can come back with the
destination unrecognisable. The service already knows which names are
likely — the cities on its own routes, the products in its catalogue — and
prompt is how you hand them to the model:
import asyncio
from tempest_fastapi_sdk.genai.audio import SpeechToText, Transcription
stt: SpeechToText = SpeechToText("base", device="cpu")
CITIES: list[str] = ["Picos", "Teresina", "Parnaíba", "Floriano", "Oeiras"]
def domain_prompt(names: list[str], limit: int = 60) -> str:
"""Build the prompt with the most frequent names first.
Args:
names (list[str]): Domain names, most frequent first.
limit (int): How many names go into the prompt.
Returns:
str: A short sentence naming them.
"""
return "Viagens entre " + ", ".join(names[:limit]) + "."
async def main() -> None:
"""Run this example."""
result: Transcription = await stt.transcribe(
"request.wav",
language="pt",
prompt=domain_prompt(CITIES),
)
print(result.text)
asyncio.run(main())
promptbecomes faster-whisper'sinitial_prompt: text the model reads as if it came before the audio. Write it as a sentence from the domain itself, in the language of the audio and with the spelling you want back (accents, capitals); Whisper does not follow instructions ("transcribe the city names") the way a chat model does.- The limit is in tokens, and the start is what gets dropped. In
faster-whisper 1.2.1 the previous context keeps the last 223 tokens
(
max_length // 2 - 1, withmax_length = 448) — measured by calling itsget_promptwith 400 tokens of context: 223 go in, from the 178th on. OpenAI's documentation states 224 tokens forwhisper-1(speech-to-text guide). That is why the recipe puts the most frequent names in a short prompt instead of dumping the whole list: whatever passes the limit is dropped silently. How many names fit depends on the model's tokenizer; with a long list, count the tokens up front instead of estimating. hotwords(SpeechToTextonly) goes into the prompt of every window, whatevercondition_on_previous_textsays; faster-whisper 1.2.1 keeps its first 223 tokens.prompt, by contrast, conditions the first window of the sequential model and only carries forward whilecondition_on_previous_text=True; withbatch_sizeit goes in front of every batch. For short audio (one voice request) both land in the same place; for a long meeting,hotwordsis the one that keeps applying.temperaturepins one temperature for the decode.Nonekeeps faster-whisper's default, the0.0, 0.2, …, 1.0ladder it climbs when a window fails its compression/log-probability checks; afloatreplaces the ladder with that single value.- The extra's floor (
faster-whisper>=1.2.1) already has all three parameters, onWhisperModeland onBatchedInferencePipeline— a test in the suite checks the installed signature.
How much the prompt helps is your measurement, not ours
The SDK guarantees the text reaches the decoder; the accuracy gain depends on the model, the audio and the list. Measure it on recordings from your domain before relying on it.
One shared instance loads the model exactly once
load() is guarded by a threading.Lock, not by the concurrency
semaphore — the semaphore admits max_concurrent callers by
definition, so two of them arriving on a cold instance used to build
two copies of the model (fixed in v0.235.0). Keep sharing one
instance across requests: that is what saves the load.
Words with timing and confidence: with_words¶
Use it for a pronunciation score or word-by-word captions.
await stt.transcribe("lesson.wav", language="pt", with_words=True) runs
faster-whisper with word_timestamps=True (one more alignment pass per
segment, so it costs time) and fills result.words: TranscriptionWord
with word, start, end and probability (0 to 1). The space
faster-whisper 1.2.1 puts in front of each word is stripped (" dia,"
becomes "dia,"), as in OpenAICompatSpeech; punctuation stays attached.
Without with_words nothing changes and words=[]. Field and wire details
in Hosted speech.
Generate voice (TTS)¶
TextToSpeech synthesizes with Coqui TTS (WAV). Same discipline
(lazy + thread + semaphore).
import asyncio
from tempest_fastapi_sdk.genai.audio import TextToSpeech
tts = TextToSpeech("tts_models/multilingual/multi-dataset/xtts_v2")
async def main() -> None:
"""Run this example."""
wav = await tts.synthesize("Hello, world.", language="en") # -> WAV bytes
# voice cloning (XTTS): pass a reference clip
wav = await tts.synthesize("Hi!", language="en", speaker_wav="ref.wav")
asyncio.run(main())
synthesize returns the WAV bytes; pass out_path= to also write it to
disk.
Less VRAM with dtype="float16"¶
On a shared GPU (an LLM in Ollama next to it, say), XTTS can run its autoregressive transformer — 1.45 GB of its 1.78 GB of weights — in half precision:
from tempest_fastapi_sdk.genai.audio import TextToSpeech
tts = TextToSpeech(
"tts_models/multilingual/multi-dataset/xtts_v2",
device="cuda",
dtype="float16",
)
The rest (conditioning encoder, perceiver and the HiFi-GAN decoder) stays in float32. Measured on a 16 GB RTX (coqui-tts 0.28, transformers 5.22):
| float32 | dtype="float16" |
|
|---|---|---|
| Weights | 1784 MiB | 1034 MiB |
| Synthesis peak | 1991 MiB | 1234 MiB |
| Latency (medium sentence) | 1.95 s | 1.89 s |
| WER, 12 pt-BR sentences with and without cloning | 0.103 | 0.073 |
The transcription misses showed up in both precisions and are XTTS's own (reading the final period aloud, "14h30min"), not half precision's.
CUDA only, XTTS only
dtype="float16" on a CPU raises ValueError at construction. A Coqui
model other than XTTS stays in float32 whatever dtype says. Halving
the whole model (.half()) and torch.autocast do not work on XTTS:
the conditioning path forces float32 and autocast trips a device-side
assert in the GPT.
Streaming speech: synthesize_stream¶
To start playing before the whole sentence is ready, synthesize_stream
hands out 16-bit mono PCM at 24 kHz (PCM_SAMPLE_RATE) as the model
generates it:
from tempest_fastapi_sdk.genai.audio import TextToSpeech, pcm_to_wav
tts = TextToSpeech("tts_models/multilingual/multi-dataset/xtts_v2", device="cuda")
async def speak(text: str) -> bytes:
"""Join the pieces (hand each one to the player) and return the WAV."""
pcm = b""
async for piece in tts.synthesize_stream(
text, language="pt", speaker="Ana Florence"
):
pcm += piece
return pcm_to_wav(pcm)
- With XTTS v2 the pieces come from Coqui's
inference_stream, one everyXTTS_STREAM_CHUNK_TOKENS(20) GPT tokens. Measured on an RTX 16 GB, a 25-word sentence: first piece in 0.28–0.30 s against 3.1–3.8 s for the whole synthesis, in float32 and withdtype="float16", with a catalog speaker and with cloning. - Text past XTTS's limit for the language (203 characters for
pt, 250 foren) is split bysplit_for_xtts— sentences, then commas, then words — and each part streamed in turn. Coqui's own splitting (enable_text_splitting) needs spaCy and is not used. speaker_wav(bytes or a path) clones the voice; the latents of the lastCLONE_LATENT_CACHE_SIZE(8) clips are cached by content hash.- Any other Coqui model is synthesized whole and handed out in 0.25 s pieces, resampled to 24 kHz.
- Closing the iterator (
break, a client that disconnects) stops the generation at the next piece. Concurrency follows the voice'smax_concurrent. - Both
TextToSpeechandOpenAICompatSpeechsatisfy theStreamingSpeechSynthesizerprotocol.PCMAligner,split_pcm,float_to_pcm16andwav_to_pcmare the PCM helpers.
More natural speech: final period, sampling and pauses¶
XTTS reads the final period aloud. Measured on "Ana Florence" through
tempest-ai and transcribed by Whisper large-v3-turbo: six pt-BR sentences,
four syntheses each, ending in a period came back with an extra "ponto"
5 times in 24; without the period, none, at the same UTMOS (3.85 against
3.83). So with XTTS, synthesize and synthesize_stream share one path:
the text is split by split_for_xtts, each part loses its final period
(drop_final_period) and is generated with the same sampling. The whole
synthesis used Coqui's sentence splitter, which ends every sentence with a
period — 7 "ponto" in 9 renders of three paragraphs.
from tempest_fastapi_sdk.genai.audio import TextToSpeech, XTTSSampling
tts = TextToSpeech(
"tts_models/multilingual/multi-dataset/xtts_v2",
device="cuda",
sampling=XTTSSampling(temperature=0.7, top_p=0.9),
pause_ms=250,
)
sampling(XTTSSampling) takestemperature,top_p,top_k,repetition_penalty,length_penaltyandspeed; aNonefield keeps Coqui's default (as_kwargs()returns only the given ones). Measured with UTMOS on ten pt-BR sentences and two seeds: temperature 0.65, repetition penalty 5.0, temperature 0.85 withtop_p0.9 all landed within the seed-to-seed spread (±0.15 around 3.6). They are per-voice fine tuning, not a fix — the default does not change.drop_final_period=Falsesends the text as written. Ellipses,?and!are never dropped: they shape the intonation and are not read.pause_msis the silence between parts.Nonekeeps each path's own:XTTS_WHOLE_PAUSE_MS(400 ms, what Coqui'stts_to_fileput after every sentence) in the whole synthesis and none when streaming, so the first sentence is not delayed.silence_pcm(ms)builds that silence.- The whole XTTS synthesis returns the WAV at the streaming level, without
the peak normalization
tts_to_fileapplied: both paths sound the same.
The text matters most
Numbers, acronyms, units and abbreviations read wrong sound more robotic
than any parameter: XTTS reads 86,67% as "oitenta e seis vírgula seis
sete", GPU as a word and p. ex. as noise. Spell them out before
synthesis.
Language (PT-BR / EN-US)¶
No need to know the Whisper code or pick a TTS model: use the LanguageEnum
enum. It resolves the code (pt/en) for STT and a good TTS model per
language:
import asyncio
from tempest_fastapi_sdk.genai.audio import LanguageEnum, SpeechToText, TextToSpeech
async def main() -> None:
"""Run this example."""
# STT: force the language without memorizing the code
await SpeechToText("base").transcribe("audio.wav", language=LanguageEnum.PT_BR)
# TTS: picks the language's default model automatically
tts = TextToSpeech.for_language(LanguageEnum.EN_US) # en-US model
wav = await tts.synthesize("Hello, world.")
asyncio.run(main())
preset_for(LanguageEnum.PT_BR) exposes the preset (whisper_language,
tts_model, tts_language) to inspect/override. language= on
transcribe/synthesize also accepts a raw code ("pt") or None
(auto-detect for STT).
Full voice loop
Chain with the LLM: STT transcribes speech → TextGenerator/RAG
answers → TTS speaks the reply. All local, nothing leaves the box.
Multilingual voice with Bark (MIT licence)¶
BarkSpeech runs Suno's Bark through transformers. It is the local TTS
option with commercially usable weights (MIT) and Portuguese voices. The
[genai] extra is enough, and it backs /tts on make_genai_router like
TextToSpeech and OllamaSpeech.
import asyncio
from tempest_fastapi_sdk.genai.audio import BarkSpeech, LanguageEnum
voice = BarkSpeech("suno/bark-small")
async def main() -> None:
"""Read a long Portuguese notice aloud and save the WAV."""
notice = (
"O sistema de transporte da cidade passa por mudanças nesta semana. "
"As linhas que atendem o centro terão novos horários a partir de "
"segunda-feira. Quem usa o ônibus das oito deve chegar ao ponto dez "
"minutos antes."
)
await voice.synthesize(notice, language=LanguageEnum.PT_BR, seed=0, out_path="notice.wav")
asyncio.run(main())
languagepicks the language's first voice (v2/pt_speaker_0);speakerpicks a specific one (v2/pt_speaker_1).voices()lists the checkpoint's 261 presets: 130 withv2/and 131 legacy names without the prefix.- Long text is split by sentence (
.,!,?,…,;or:followed by whitespace;Dr.,Sra.,Av.and the like do not end a sentence, and numbers likeR$ 3,50or1.000are never split). One Bark call stops at 13.95 s of audio: measured, 180 Portuguese characters came out whole and 240 were cut.synthesizesplits the text into pieces of up tomax_chunk_chars(160), speaks each, and joins them withpause_seconds(0.25 s) of silence. A 442-character text became 35.75 s of complete audio; without the split it stopped at 13.95 s. - It is slow. On the RTX 4070 Ti SUPER, in bf16 (the default), those
35.75 s took 88.6 s; in fp16, 12.7 s took 24 to 27 s. For real-time
replies, prefer
OllamaSpeech.suno/bark(the large checkpoint) is slower still: on the same Portuguese text, 12.68 s of audio took 35.4 s at a 2.3 GiB peak, against 11.37 s in 19 s and 0.92 GiB forbark-small. - Errors answer
422, withdetails={"field": ...}. Before the model loads: text with nothing to speak (text), a seed outside0..2**64 - 1(seed) and aspeakerthat is not a voice of the requestedlanguage(speaker). After: a preset the checkpoint does not ship (speaker, orlanguagewhen the language has no voice). - The seed is global, applied with
torch.manual_seed. In bf16, the same seed repeated the same bytes.
The weights are a pickle
suno/bark-small publishes pytorch_model.bin, not safetensors. torch
2.14 loads it with weights_only=True, which does not execute code from
the file.
Picking a voice or audio model: licence and where it runs¶
Before picking a voice model, check two things: the licence of the weights (which can differ from the code's licence) and whether it runs on what the SDK already depends on. Generic "best models" guides often get both wrong.
The table below was read from the Hugging Face models API
(https://huggingface.co/api/models/<id>, tags field) on 2026-10-31.
Weight licences change; check the model card before shipping.
| Model | Task | Weight licence | Runs on |
|---|---|---|---|
hexgrad/Kokoro-82M |
TTS | apache-2.0 |
kokoro package (requires Python <3.13); kokoro-onnx 0.6.1 requires <3.14 and a native espeak, so the SDK does not wrap it |
nari-labs/Dia-1.6B-0626 |
TTS | apache-2.0 |
transformers (DiaForConditionalGeneration, outside the pipeline) |
sesame/csm-1b |
TTS | apache-2.0 (gated) |
transformers |
Qwen/Qwen3-TTS-12Hz-1.7B-Base |
TTS | apache-2.0 |
not in transformers 4.57.6 |
ResembleAI/chatterbox |
TTS | mit |
chatterbox-tts package |
suno/bark-small |
TTS | mit |
BarkSpeech (Bark) |
openai/whisper-large-v3-turbo |
STT | mit |
SpeechToText (faster-whisper) |
coqui/XTTS-v2 |
TTS | other (CPML) |
TextToSpeech (Coqui) |
SWivid/F5-TTS |
TTS | cc-by-nc-4.0 |
f5-tts package |
facebook/musicgen-large |
music | cc-by-nc-4.0 |
transformers |
cvssp/audioldm-s-full-v2 |
sound effects | cc-by-nc-sa-4.0 |
AudioGenerator (sound effects and music) |
ucsd-reach/musicldm |
music | cc-by-nc-sa-4.0 |
AudioGenerator; measured: generates on transformers 4.57.6, refused on 5.22.1 |
cvssp/audioldm2-large |
sound effects | cc-by-nc-sa-4.0 |
diffusers (AudioLDM2Pipeline), broken on current transformers |
stabilityai/stable-audio-open-1.0 |
music/effects | other (gated) |
diffusers (StableAudioPipeline) |
MIT code does not mean MIT weights
The F5-TTS repository is MIT, but its published weights are
cc-by-nc-4.0; AudioLDM 2 is cc-by-nc-sa-4.0. Both show up as "MIT,
commercial use allowed" in recommendation lists. Commercial use of NC
weights needs a separate agreement with the author.
What the extra's environment already has, with no new dependency: in the
venv this was measured in (diffusers 0.39.0, transformers 4.57.6),
diffusers exports AudioLDM2Pipeline, StableAudioPipeline,
MusicLDMPipeline and AutoPipelineForText2Audio, and the transformers
text-to-waveform mapping covers bark, csm, musicgen,
musicgen_melody, vits, seamless_m4t, qwen2_5_omni, qwen3_omni_moe
and fastspeech2_conformer. Kokoro is not in that mapping.
Packages whose constraints the SDK does not accept
Read from requires-dist on PyPI on 2026-10-31: chatterbox-tts 0.1.7
pins torch==2.6.0, transformers==5.2.0 and diffusers==0.29.0;
stable-audio-tools 0.0.20 pins torch==2.7.1 and requires Python
<3.11; f5-tts 1.1.22 pulls in gradio; kokoro 0.9.4 requires
Python <3.13. Bringing any of them into an extra would pin the lock of
everyone who installs the SDK.
Voice through Ollama¶
Ollama started generating speech in v0.40.11 (2026-10-24), through the
OpenAI-compatible POST /v1/audio/speech endpoint, with the phonon model
(31M English checkpoint). v0.40.12 brought lfm3-audio (2B, LFM Open
License v1.0, 18 languages including Portuguese). The v0.40.11 notes mention
macOS, and the lfm3-audio page only shows a text chat.
Measured on 2026-10-31 with the ollama/ollama:0.40.13 image in Docker,
Linux (WSL2), RTX 4070 Ti SUPER 16 GB, driver 591.86:
- Both run on the GPU on Linux.
ollama psshowsphononon themlxrunner andlfm3-audioonllamacpp, both100% GPU; with both loaded, VRAM use went from 1515 MiB to 4565 MiB. /api/showdeclares the capability.phononanswerscapabilities: ["speech"]and 38 voices invoices;lfm3-audioanswers["completion", "audio", "speech", "tools"], with voices such asfemale-portugueseandmale-portuguese.- TTS. Output is
audio/wav16-bit mono 24 kHz, with the RIFF size field set to0xFFFFFFFF(the stream does not know the length up front);pcmreturnsaudio/pcm. With the model warm, a sentence of 6.3 s of audio came back in 0.14 s (phonon) and one of 7.0 s in 0.65 s (lfm3-audio). The first request after the pull took 116 s (phonon) and 55 s (lfm3-audio); after unloading withkeep_alive: 0, reloading took 1.4 s. - Errors are
400withinvalid_request_error:response_formatmp3(use wav or pcm),speedother than 1 (only speed 1 is supported), an unknown voice (the message lists the voices),inputover 4096 characters, and/api/chaton a speech-only model ("phonon" does not support chat). - STT works, through three undocumented paths:
POST /v1/audio/transcriptions(multipartfile+model, as in OpenAI; accepts WAV and MP3, andresponse_format=verbose_jsonreturnslanguage,durationandsegments),POST /v1/chat/completionswith a base64input_audiopart, andPOST /api/chatwith base64 audio in theimagesfield. With the model warm, transcribing 7 s took 0.13 s. Sending audio tophononanswers400("phonon" does not support audio input).
Transcription quality: one sample is not a rate
On a single 7 s Portuguese clip, lfm3-audio transcribed "Lá, este
áudio..." (dropping the "O" of "Olá") and
SpeechToText("large-v3-turbo") got "Olá! Este áudio...". Both wrote
"Olama". It is one sample, not an error-rate comparison.
OllamaSpeech: voice and transcription through the SDK¶
OllamaSpeech wraps both endpoints and the voice list, with the same HTTP
client (retry, circuit-breaker, X-Request-ID) and the same OllamaError
as OllamaGenerator. It only needs the [genai-ollama] extra.
import asyncio
from tempest_fastapi_sdk.genai import OllamaSpeech
speech = OllamaSpeech("lfm3-audio", timeout=180.0)
async def main() -> None:
"""Speak Portuguese and transcribe it back."""
voices = await speech.voices()
print("female-portuguese" in voices)
wav = await speech.synthesize(
"Bom dia! O SDK agora fala português pelo Ollama.",
voice="female-portuguese",
out_path="bom-dia.wav",
)
result = await speech.transcribe(wav)
print(result.text, result.duration)
await speech.aclose()
asyncio.run(main())
One run against Ollama 0.40.13 on the RTX 4070 Ti SUPER:
Synthesis is not deterministic: the same program, run four times, produced
clips from 3.68 s to 4.32 s, and the acronym "SDK" came back as "Raskiká",
"Sicoa", "STEC" and vanished on the fourth ("Bom dia, esta agora, fala
português..."). Spoken by lfm3-audio and heard back by the same model, it
did not survive the round trip once. Spell acronyms out in text that will
become speech.
What OllamaSpeech does for you:
- Fixes the WAV header. The daemon's stream leaves the RIFF and
datasizes at0xFFFFFFFF, and Python'swavereads2147483647frames. Sincesynthesizebuffers the whole response, it rewrites the sizes: a 4.32 s clip opens with103680frames at 24 kHz.response_format="pcm"returns the raw samples, with no header. - Separates a bad request from a server failure. When the daemon
refuses the request with
400(unknown voice, model without speech or without audio input, empty input or input over 4096 characters, audio that does not decode), it raisesValidationException(422) with the daemon's message anddetails={"backend": "ollama", "model": ...}. A model that is not pulled, or a daemon failure, stays anOllamaError. - Refuses what the daemon would ignore. Ollama only echoes back the
languagelabel it received (English audio sent withlanguage=ptcame back in English, tagged"portuguese"), and for speech the voice decides the language. Sotranscribeandsynthesizeacceptlanguageonly asNone: any value raisesValidationExceptionwithdetails={"field": "language"}, before any request.Transcription.languagestays empty.promptandtemperatureare likewise accepted only asNone(details={"field": "prompt"}or"temperature"): whether the daemon honours them has not been measured, so they are neither sent nor silently dropped. There is nokeep_aliveeither, which these endpoints ignore. - A path is a path.
transcribe("https://...")raisesFileNotFoundErrorwithout touching the network, likeSpeechToText.
Streamed voice: stream_speech and speech_response¶
synthesize waits for the whole clip. stream_speech yields each piece as
the daemon flushes it — 16-bit mono 24 kHz PCM by default, no header, the
format a streaming player wants — with the same errors. To serve it over HTTP,
use speech_response, which returns the StreamingResponse already:
from fastapi import FastAPI, Response
from tempest_fastapi_sdk import register_exception_handlers
from tempest_fastapi_sdk.genai import OllamaSpeech
speech = OllamaSpeech("lfm3-audio", timeout=180.0)
app = FastAPI()
register_exception_handlers(app)
@app.get("/speak")
async def speak(text: str) -> Response:
"""Return the speech as PCM while it is generated.
Args:
text (str): The text to speak.
Returns:
Response: 16-bit mono 24 kHz PCM, streamed.
"""
return await speech.speech_response(text, voice="female-portuguese")
Why not build the StreamingResponse yourself
A StreamingResponse sends its status and headers before reading the
first chunk. Measured: with StreamingResponse(speech.stream_speech(...))
and an unknown voice, the client got 200 with an empty body, and
Starlette logged Caught handled exception, but response already started.
speech_response reads the first chunk before building the response: the
refusal raises there and becomes the SDK's 422, and the rest of the audio
still streams.
Measured with a warm lfm3-audio: on a text of ~18 s of audio, the first
chunk arrived in 24 to 30 ms, against 1.76 s for the whole synthesize.
language is refused before any request.
Serving over HTTP: /tts and /transcribe¶
make_genai_router takes any object that satisfies SpeechTranscriber
(for /transcribe) and SpeechSynthesizer (for /tts), from
tempest_fastapi_sdk.genai.audio. SpeechToText, TextToSpeech and
OllamaSpeech all do; the /tts body's speaker becomes Ollama's voice.
from fastapi import FastAPI
from tempest_fastapi_sdk import register_exception_handlers
from tempest_fastapi_sdk.genai import OllamaSpeech, make_genai_router
speech = OllamaSpeech("lfm3-audio", timeout=180.0)
app = FastAPI()
register_exception_handlers(app)
app.include_router(make_genai_router(speech_to_text=speech, text_to_speech=speech))
Measured against Ollama 0.40.13, with httpx.ASGITransport in front of the
app:
| Request | Response |
|---|---|
POST /api/genai/tts {"text": "Olá pelo roteador.", "speaker": "male-portuguese"} |
200, audio/wav with 34560 frames |
POST /api/genai/transcribe with that WAV |
200, "text": "Olá pelo roteador." |
POST /api/genai/tts {"text": "x", "speaker": "nope"} |
422, VALIDATION_ERROR, the daemon's message in detail |
POST /api/genai/tts {"text": "x", "language": "pt"} |
422, details: {"field": "language"} |
POST /api/genai/transcribe with 3000 zero bytes |
422, "detail": "Failed to load image or audio file" |
The first request after the pull is slow
It loads the model: 116 s for phonon and 55 s for lfm3-audio, against
1.4 s for a later reload. With the default 120 s timeout, the first
phonon synthesize barely makes it; warm the model up at deploy time or
raise the timeout.
Sources¶
- Ollama: speech
- Ollama release notes (v0.40.11 to v0.40.13)
lfm3-audioin the Ollama library- Transformers: text-to-speech
- transformers PR #39796: text-to-audio pipeline standardization
- Diffusers: audio pipelines
- Model cards: Kokoro-82M, Dia-1.6B, CSM-1B, Qwen3-TTS, Chatterbox, Whisper large-v3-turbo, XTTS-v2, F5-TTS, MusicGen large, AudioLDM 2 large, Stable Audio Open