en-stt-tts / app.py
StrangerInAStrangeLand's picture
Upload app.py with huggingface_hub
c3b2fc7 verified
Raw History Blame Contribute Delete
26.1 kB
"""
English-only speech tools for Hugging Face Spaces (Gradio SDK + ZeroGPU).
Two tools in one Space:
* Tab "Speech to text" -> distil-whisper/distil-large-v3.5 (English transcription only)
* Tab "Text to speech" -> hexgrad/Kokoro-82M (English voices: US + GB)
ZeroGPU rules this file follows (see https://huggingface.co/docs/hub/spaces-zerogpu):
1. Models are placed on CUDA at *module* level, NOT inside the @spaces.GPU function.
Outside @spaces.GPU a CUDA emulation layer is active; inside it real CUDA is used.
2. Only the model forward passes run inside @spaces.GPU. Audio decoding, resampling,
silence checks, G2P/phonemisation, WAV writing and temp-file housekeeping all run on
the CPU, outside the GPU allocation.
3. Durations are explicit and dynamic (a callable keyed off the input size), so short
requests keep queue priority and long ones are not cut off mid-inference.
4. No torch.compile (unsupported on ZeroGPU), no background GPU server, no assumption
that a GPU is permanently allocated.
5. Completed audio is returned as a finished WAV file -- never a generator -- so GPU
allocation lifetime can never be outlived by a lazily-consumed stream.
Nothing here is a paid API call and no LLM is involved. No secrets are read or logged.
"""
from __future__ import annotations
import logging
import os
import tempfile
import time
import uuid
from pathlib import Path
import gradio as gr
import numpy as np
import spaces
import soundfile as sf
import torch
from kokoro import KModel, KPipeline
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
# --------------------------------------------------------------------------------------
# Configuration. Every knob is overridable with a Space variable (env var) so it can be
# retuned after benchmarking without touching this file.
# --------------------------------------------------------------------------------------
ASR_MODEL_ID = os.environ.get("ASR_MODEL_ID", "distil-whisper/distil-large-v3.5")
TTS_REPO_ID = os.environ.get("TTS_REPO_ID", "hexgrad/Kokoro-82M")
TARGET_SR = 16_000 # Whisper feature extractor sample rate
TTS_SR = 24_000 # Kokoro output sample rate
# --- speech to text -------------------------------------------------------------------
ASR_CHUNK_S = 25.0 # model card: optimal chunk length for distil-large-v3.5
ASR_STRIDE_S = ASR_CHUNK_S / 6
ASR_BATCH_SIZE = int(os.environ.get("ASR_BATCH_SIZE", "8")) # chunks per GPU batch
ASR_MAX_NEW_TOKENS = 128 # enough for a 25 s chunk (~70-90 text tokens)
ASR_MAX_AUDIO_S = float(os.environ.get("ASR_MAX_AUDIO_S", "300")) # hard cap, 5 min
ASR_DEFAULT_LIMIT_S = float(os.environ.get("ASR_DEFAULT_LIMIT_S", "60")) # UI default
# --- text to speech -------------------------------------------------------------------
TTS_MAX_CHARS_CAP = int(os.environ.get("TTS_MAX_CHARS_CAP", "5000")) # hard cap
TTS_DEFAULT_MAX_CHARS = int(os.environ.get("TTS_DEFAULT_MAX_CHARS", "1500"))
SPEED_MIN, SPEED_MAX, SPEED_STEP, SPEED_DEFAULT = 0.5, 2.0, 0.1, 1.0
# --- GPU durations (seconds) ----------------------------------------------------------
# Requested duration is a CAP; ZeroGPU bills the effective allocation and a too-small
# request is killed mid-inference, so these are deliberately generous. Measured values
# for this app are in README.md; retune by setting the Space variables and restarting.
ASR_GPU_BASE_S = float(os.environ.get("ASR_GPU_BASE_S", "10")) # fixed overhead / call
ASR_GPU_PER_AUDIO_S = float(os.environ.get("ASR_GPU_PER_AUDIO_S", "0.5")) # 2x realtime budget
ASR_GPU_MAX_S = int(os.environ.get("ASR_GPU_MAX_S", "120"))
TTS_GPU_BASE_S = float(os.environ.get("TTS_GPU_BASE_S", "10"))
TTS_GPU_PER_CHAR_S = float(os.environ.get("TTS_GPU_PER_CHAR_S", "0.05")) # ~20 chars/GPU-s
TTS_GPU_MAX_S = int(os.environ.get("TTS_GPU_MAX_S", "120"))
# --- housekeeping ---------------------------------------------------------------------
SILENCE_PEAK = 1e-4 # max |sample| below this = silence
TMP_TTL_S = int(os.environ.get("TMP_TTL_S", "21600")) # delete generated WAVs after 6 h
# Gradio keeps its own cache dir for uploaded recordings. [frequency, max_age] seconds:
# sweep it every hour and drop anything older than a day. The cache is also fully wiped
# whenever the container restarts.
GRADIO_CACHE_SWEEP_S = int(os.environ.get("GRADIO_CACHE_SWEEP_S", "3600"))
GRADIO_CACHE_MAX_AGE_S = int(os.environ.get("GRADIO_CACHE_MAX_AGE_S", "86400"))
TMP_DIR = Path(tempfile.gettempdir()) / "en-speech-tools"
TMP_DIR.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(name)s | %(message)s",
)
log = logging.getLogger("en-speech-tools")
# --------------------------------------------------------------------------------------
# Kokoro English voices (v1.0). Source of truth: hexgrad/Kokoro-82M VOICES.md.
# "a" = American English, "b" = British English. The first letter of a voice id also
# selects the KPipeline (G2P language), so voice ids must stay in their own family.
# --------------------------------------------------------------------------------------
VOICE_GRADES = {
"af_heart": "A", "af_bella": "A-", "af_nicole": "B-", "af_aoede": "C+",
"af_kore": "C+", "af_sarah": "C+", "af_alloy": "C", "af_nova": "C",
"af_sky": "C-", "af_jessica": "D", "af_river": "D",
"am_michael": "C+", "am_fenrir": "C+", "am_puck": "C+", "am_echo": "D",
"am_eric": "D", "am_liam": "D", "am_onyx": "D", "am_santa": "D-", "am_adam": "F+",
"bf_emma": "B-", "bf_isabella": "C", "bf_alice": "D", "bf_lily": "D",
"bm_fable": "C", "bm_george": "C", "bm_lewis": "D+", "bm_daniel": "D",
}
VOICE_LABELS = {
"af_heart": "πŸ‡ΊπŸ‡Έ 🚺 Heart ❀️ (best)", "af_bella": "πŸ‡ΊπŸ‡Έ 🚺 Bella πŸ”₯",
"af_nicole": "πŸ‡ΊπŸ‡Έ 🚺 Nicole 🎧", "af_aoede": "πŸ‡ΊπŸ‡Έ 🚺 Aoede",
"af_kore": "πŸ‡ΊπŸ‡Έ 🚺 Kore", "af_sarah": "πŸ‡ΊπŸ‡Έ 🚺 Sarah", "af_nova": "πŸ‡ΊπŸ‡Έ 🚺 Nova",
"af_sky": "πŸ‡ΊπŸ‡Έ 🚺 Sky", "af_alloy": "πŸ‡ΊπŸ‡Έ 🚺 Alloy", "af_jessica": "πŸ‡ΊπŸ‡Έ 🚺 Jessica",
"af_river": "πŸ‡ΊπŸ‡Έ 🚺 River", "am_michael": "πŸ‡ΊπŸ‡Έ 🚹 Michael", "am_fenrir": "πŸ‡ΊπŸ‡Έ 🚹 Fenrir",
"am_puck": "πŸ‡ΊπŸ‡Έ 🚹 Puck", "am_echo": "πŸ‡ΊπŸ‡Έ 🚹 Echo", "am_eric": "πŸ‡ΊπŸ‡Έ 🚹 Eric",
"am_liam": "πŸ‡ΊπŸ‡Έ 🚹 Liam", "am_onyx": "πŸ‡ΊπŸ‡Έ 🚹 Onyx", "am_santa": "πŸ‡ΊπŸ‡Έ 🚹 Santa",
"am_adam": "πŸ‡ΊπŸ‡Έ 🚹 Adam", "bf_emma": "πŸ‡¬πŸ‡§ 🚺 Emma", "bf_isabella": "πŸ‡¬πŸ‡§ 🚺 Isabella",
"bf_alice": "πŸ‡¬πŸ‡§ 🚺 Alice", "bf_lily": "πŸ‡¬πŸ‡§ 🚺 Lily", "bm_george": "πŸ‡¬πŸ‡§ 🚹 George",
"bm_fable": "πŸ‡¬πŸ‡§ 🚹 Fable", "bm_lewis": "πŸ‡¬πŸ‡§ 🚹 Lewis", "bm_daniel": "πŸ‡¬πŸ‡§ 🚹 Daniel",
}
# Hardcode order: American English first, each group ordered by published grade.
VOICE_IDS = [
"af_heart", "af_bella", "af_nicole", "af_aoede", "af_kore", "af_sarah", "af_alloy",
"af_nova", "af_sky", "af_jessica", "af_river",
"am_michael", "am_fenrir", "am_puck", "am_echo", "am_eric", "am_liam", "am_onyx",
"am_santa", "am_adam",
"bf_emma", "bf_isabella", "bf_alice", "bf_lily",
"bm_fable", "bm_george", "bm_lewis", "bm_daniel",
]
VOICE_CHOICES = [(f"{VOICE_LABELS[v]} β€” grade {VOICE_GRADES[v]}", v) for v in VOICE_IDS]
DEFAULT_VOICE = "af_heart"
# --------------------------------------------------------------------------------------
# Module-level model placement.
#
# ZeroGPU only exposes a real GPU inside @spaces.GPU, yet the documented (and much more
# efficient) pattern is to place the models on `cuda` here, at import time: the runtime
# provides a CUDA emulation layer for the pre-GPU phase. Moving a model to CUDA inside
# the decorated function is explicitly discouraged.
# --------------------------------------------------------------------------------------
CUDA_AVAILABLE = torch.cuda.is_available()
DEVICE = os.environ.get("FORCE_DEVICE") or ("cuda" if CUDA_AVAILABLE else "cpu")
ASR_DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
log.info(
"startup: device=%s cuda_available=%s torch=%s asr=%s tts=%s",
DEVICE, CUDA_AVAILABLE, torch.__version__, ASR_MODEL_ID, TTS_REPO_ID,
)
# --- speech to text -------------------------------------------------------------------
# fp16 on GPU (standard Whisper practice), fp32 on CPU. low_cpu_mem_usage streams the
# safetensors shards instead of materialising two full copies.
_asr_model = AutoModelForSpeechSeq2Seq.from_pretrained(
ASR_MODEL_ID,
torch_dtype=ASR_DTYPE,
low_cpu_mem_usage=True,
use_safetensors=True,
)
_asr_model.to(DEVICE)
_asr_processor = AutoProcessor.from_pretrained(ASR_MODEL_ID)
# English in, English text out -- pinned explicitly rather than left to defaults.
# distil-large-v3.5 is an English-only distillation but carries a multilingual tokenizer
# (generation_config.is_multilingual = true) whose implicit forced_decoder_ids
# [[1, <|en|>], [2, <|transcribe|>]] are deprecated in transformers >= 5, where the
# supported spelling is the language/task pair used below. Translation is not reachable.
ASR_GENERATE_KWARGS = {"language": "en", "task": "transcribe"}
ASR_PIPE = pipeline(
"automatic-speech-recognition",
model=_asr_model,
tokenizer=_asr_processor.tokenizer,
feature_extractor=_asr_processor.feature_extractor,
max_new_tokens=ASR_MAX_NEW_TOKENS,
chunk_length_s=ASR_CHUNK_S, # documented chunked long-form strategy
stride_length_s=ASR_STRIDE_S,
batch_size=ASR_BATCH_SIZE,
torch_dtype=ASR_DTYPE,
device=DEVICE,
)
# --- text to speech -------------------------------------------------------------------
# One KModel on the GPU; G2P lives in "quiet" KPipelines (model=False) that only
# phonemise + chunk text and never touch the acoustic model. The model call itself is
# what gets wrapped in @spaces.GPU below.
TTS_MODEL = KModel(repo_id=TTS_REPO_ID).to(DEVICE).eval()
TTS_PIPELINES = {
lang: KPipeline(lang_code=lang, repo_id=TTS_REPO_ID, model=False)
for lang in ("a", "b") # English only: American + British
}
# --------------------------------------------------------------------------------------
# CPU-only helpers
# --------------------------------------------------------------------------------------
# ffmpeg_read is the helper the transformers ASR pipeline itself uses for file input:
# it shells out to `ffmpeg -ac 1 -ar 16000 -f f32le`, i.e. it does the stereo->mono
# downmix and the resampling in one step. Module moved between transformers versions,
# so probe both known locations.
try: # transformers <= 4.x / 5.x
from transformers.pipelines.audio_utils import ffmpeg_read as _ffmpeg_read
except Exception: # pragma: no cover - newer layout
try:
from transformers.audio_utils import ffmpeg_read as _ffmpeg_read
except Exception:
_ffmpeg_read = None
def _resample_linear(x: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray:
"""Fallback resampler (linear interpolation) used only if ffmpeg is unavailable.
Adequate for speech at 16 kHz but not alias-free; ffmpeg's resampler is preferred.
"""
if sr_in == sr_out or x.size == 0:
return x.astype(np.float32, copy=False)
n_out = int(round(x.shape[0] * sr_out / sr_in))
if n_out <= 0:
return np.zeros(0, dtype=np.float32)
t_in = np.arange(x.shape[0], dtype=np.float64) / float(sr_in)
t_out = np.arange(n_out, dtype=np.float64) / float(sr_out)
return np.interp(t_out, t_in, x).astype(np.float32)
def _decode_with_libsndfile(path: Path) -> np.ndarray:
"""Fallback decoder: libsndfile (WAV/FLAC/OGG/MP3), then mono-downmix + resample."""
data, sr = sf.read(str(path), dtype="float32", always_2d=True)
mono = data.mean(axis=1) if data.shape[1] > 1 else data[:, 0]
return _resample_linear(mono, int(sr), TARGET_SR)
def decode_audio(path: str) -> np.ndarray:
"""Decode any user-supplied audio file to mono float32 @ 16 kHz. CPU only."""
p = Path(path)
if not p.is_file():
raise ValueError("uploaded file is missing")
if p.stat().st_size == 0:
raise ValueError("uploaded file is empty")
if _ffmpeg_read is not None:
try:
samples = _ffmpeg_read(p.read_bytes(), TARGET_SR)
return np.asarray(samples, dtype=np.float32)
except Exception as exc: # corrupt file, unsupported codec, ffmpeg absent
log.info("ffmpeg decode failed (%s), trying libsndfile", type(exc).__name__)
return _decode_with_libsndfile(p)
def plan_tts_segments(text: str, voice: str) -> list[tuple[str, torch.Tensor]]:
"""Phonemise + segment text on the CPU. No model, no GPU.
Returns [(phonemes, style_vector), ...] where each phoneme string is <= 510 chars,
the context length Kokoro was trained on. Segmentation is the library's own
strategy: split on blank lines, then waterfall back to the last sentence/clause
boundary that still fits.
"""
pipe = TTS_PIPELINES[voice[0]]
pack = pipe.load_voice(voice) # cached in the KPipeline after first use
jobs: list[tuple[str, torch.Tensor]] = []
for _graphemes, phonemes, _audio in pipe(text, voice):
if not phonemes:
continue
jobs.append((phonemes, pack[len(phonemes) - 1]))
return jobs
def cleanup_tmp(ttl_s: int = TMP_TTL_S) -> int:
"""Delete generated WAVs older than ttl_s. Safe to call on every request.
Generated files are NOT deleted right after a response: the UI keeps a download
link / player pointing at the file, and the browser may fetch it seconds or minutes
later. Age-based deletion (6 h by default) plus the container being wiped on every
rebuild and restart bounds retention. Uploaded recordings are never copied out of
Gradio's own cache and are never written to disk by this app.
"""
cutoff, removed = time.time() - ttl_s, 0
try:
for f in TMP_DIR.glob("*.wav"):
if f.stat().st_mtime < cutoff:
f.unlink()
removed += 1
except OSError as exc: # pragma: no cover - best effort housekeeping
log.info("tmp cleanup skipped: %s", type(exc).__name__)
return removed
def _quota_hint(exc: Exception) -> str:
"""Turn a platform-level ZeroGPU refusal into something a visitor can act on."""
msg = str(exc)
if "quota" in msg.lower() or "ZeroGPU" in msg:
return ("The shared ZeroGPU pool refused the request (daily quota or queue limit). "
"This is enforced by Hugging Face, not by this app; sign in / retry later.")
return ""
# --------------------------------------------------------------------------------------
# GPU functions. Exactly two, one per tool; each is entered only for the model forward.
# --------------------------------------------------------------------------------------
def _asr_duration(samples: np.ndarray) -> int:
"""Dynamic duration: 10 s base + 2x the audio length, capped."""
seconds = float(np.shape(samples)[0]) / TARGET_SR
return int(min(ASR_GPU_MAX_S, ASR_GPU_BASE_S + ASR_GPU_PER_AUDIO_S * seconds))
@spaces.GPU(duration=_asr_duration)
def asr_forward(samples: np.ndarray) -> str:
# Chunking, stride blending and batching are handled by the pipeline; the model's
# own generation settings keep this English-only and transcription-only.
result = ASR_PIPE(
samples, batch_size=ASR_BATCH_SIZE, generate_kwargs=dict(ASR_GENERATE_KWARGS)
)
return (result.get("text") or "").strip()
def _tts_duration(jobs: list, speed: float) -> int:
"""Dynamic duration: 10 s base + 0.05 s per phoneme character, capped."""
chars = sum(len(ps) for ps, _ in jobs)
return int(min(TTS_GPU_MAX_S, TTS_GPU_BASE_S + TTS_GPU_PER_CHAR_S * chars))
@spaces.GPU(duration=_tts_duration)
def tts_forward(jobs: list, speed: float) -> np.ndarray | None:
# torch.inference_mode: no autograd bookkeeping for an 82M model doing pure inference.
chunks: list[np.ndarray] = []
with torch.inference_mode():
for phonemes, style in jobs:
audio = TTS_MODEL(phonemes, style, speed) # -> 24 kHz float tensor on CPU
chunks.append(audio.detach().cpu().numpy())
if not chunks:
return None
return np.concatenate(chunks)
# --------------------------------------------------------------------------------------
# Gradio handlers (all validation, decoding, file I/O on the CPU side of the GPU call)
# --------------------------------------------------------------------------------------
def transcribe(audio_path: str | None, max_seconds: float) -> tuple[str, str]:
"""STT: recording/upload -> English transcript. Gradio API name: /transcribe."""
if not audio_path:
raise gr.Error("No audio provided. Record with the microphone or upload a file.")
try:
samples = decode_audio(audio_path)
except Exception as exc:
log.warning("decode failed: %s", type(exc).__name__)
raise gr.Error(
"Could not read this audio file. Supported inputs are anything ffmpeg or "
"libsndfile can open (wav, flac, ogg, mp3, m4a). The file may be corrupt, "
"empty, or in an unsupported format."
) from exc
seconds = float(samples.shape[0]) / TARGET_SR
limit = float(max_seconds)
if seconds < 0.05:
raise gr.Error(f"Audio is only {seconds:.2f}s long -- nothing to transcribe.")
if seconds > limit + 0.05:
raise gr.Error(
f"Audio is {seconds:.1f}s but the configured maximum recording length is "
f"{limit:.0f}s. Raise the slider (cap: {ASR_MAX_AUDIO_S:.0f}s) or trim the file."
)
if float(np.max(np.abs(samples))) < SILENCE_PEAK:
return "", f"⚠️ No speech detected: {seconds:.1f}s of digital silence."
started = time.perf_counter()
try:
text = asr_forward(samples)
except Exception as exc:
log.warning("asr_forward failed: %s", type(exc).__name__)
hint = _quota_hint(exc)
raise gr.Error(
f"Transcription failed on the GPU ({type(exc).__name__}). {hint}".strip()
) from exc
elapsed = time.perf_counter() - started
log.info("asr ok: audio_s=%.2f wall_s=%.2f chars=%d", seconds, elapsed, len(text))
if not text:
return "", f"⚠️ No speech recognised in {seconds:.1f}s of audio."
return text, f"βœ… Transcribed {seconds:.1f}s of English audio in {elapsed:.1f}s."
def speak(
text: str | None,
voice: str,
speed: float,
max_chars: int,
) -> tuple[str | None, str]:
"""TTS: English text + voice + speed -> finished 24 kHz WAV. API name: /speak."""
text = (text or "").strip()
if not text:
raise gr.Error("Enter some text to speak (the input is empty).")
limit = int(max_chars)
if len(text) > limit:
raise gr.Error(
f"Text is {len(text)} characters but the configured maximum text length is "
f"{limit}. Shorten it or raise the limit (cap: {TTS_MAX_CHARS_CAP})."
)
if voice not in VOICE_GRADES:
raise gr.Error(f"Unknown voice '{voice}'. Pick one from the dropdown.")
speed = float(speed)
if not SPEED_MIN <= speed <= SPEED_MAX:
raise gr.Error(f"Speed must be between {SPEED_MIN} and {SPEED_MAX}.")
cleanup_tmp()
# CPU: G2P + segmentation (the slow, non-GPU half of Kokoro).
try:
jobs = plan_tts_segments(text, voice)
except Exception as exc:
log.warning("g2p/segmentation failed: %s", type(exc).__name__)
raise gr.Error(
"Could not convert that text to phonemes. Check for exotic characters, or "
"try shorter text."
) from exc
if not jobs:
raise gr.Error("Nothing to synthesise after text normalisation -- try other text.")
started = time.perf_counter()
try:
audio = tts_forward(jobs, speed)
except Exception as exc:
log.warning("tts_forward failed: %s", type(exc).__name__)
hint = _quota_hint(exc)
raise gr.Error(
f"Speech synthesis failed on the GPU ({type(exc).__name__}). {hint}".strip()
) from exc
elapsed = time.perf_counter() - started
if audio is None or audio.size == 0:
raise gr.Error("The model returned no audio for this input.")
# Unique name per request: concurrent users must never share a temp path.
out_path = TMP_DIR / f"tts-{uuid.uuid4().hex}.wav"
sf.write(str(out_path), audio, TTS_SR, subtype="PCM_16")
audio_s = audio.shape[0] / TTS_SR
log.info(
"tts ok: chars=%d segments=%d audio_s=%.2f wall_s=%.2f speed=%.2f voice_family=%s",
len(text), len(jobs), audio_s, elapsed, speed, voice[0],
)
return str(out_path), (
f"βœ… {len(jobs)} segment(s), {audio_s:.1f}s of audio in {elapsed:.1f}s "
f"({len(text)} characters, {voice}, speed {speed})."
)
# --------------------------------------------------------------------------------------
# UI
# --------------------------------------------------------------------------------------
VOICE_BY_FAMILY = ", ".join(v for v in VOICE_IDS if v.startswith("a"))
# NB: gradio 6 moved `theme` out of Blocks.__init__ (it is a launch() argument now).
with gr.Blocks(
title="English STT + TTS (ZeroGPU)",
delete_cache=(GRADIO_CACHE_SWEEP_S, GRADIO_CACHE_MAX_AGE_S),
) as demo:
gr.Markdown(
"# πŸ‡¬πŸ‡§πŸ‡ΊπŸ‡Έ English speech tools\n"
"Speech-to-text and text-to-speech, English only, running on the shared ZeroGPU "
"pool. No paid APIs, no LLM.\n\n"
"**STT:** [`distil-whisper/distil-large-v3.5`](https://huggingface.co/distil-whisper/distil-large-v3.5) Β· "
"**TTS:** [`hexgrad/Kokoro-82M`](https://huggingface.co/hexgrad/Kokoro-82M)\n\n"
"Named API endpoints: `/transcribe` and `/speak` (see README for parameters)."
)
with gr.Tab("Speech to text"):
with gr.Row():
with gr.Column():
stt_audio = gr.Audio(
sources=["microphone", "upload"],
type="filepath",
label="Recording or audio file",
)
stt_limit = gr.Slider(
minimum=5,
maximum=ASR_MAX_AUDIO_S,
value=min(ASR_DEFAULT_LIMIT_S, ASR_MAX_AUDIO_S),
step=5,
label="Maximum recording length (seconds)",
info="Requests longer than this are rejected before any GPU work.",
)
stt_btn = gr.Button("Transcribe", variant="primary")
with gr.Column():
stt_text = gr.Textbox(
label="Transcript (editable)",
lines=12,
buttons=["copy"], # gradio 6: was show_copy_button=True in gradio 5
placeholder="The transcript appears here and can be edited freely.",
)
stt_status = gr.Markdown("")
stt_btn.click(
fn=transcribe,
inputs=[stt_audio, stt_limit],
outputs=[stt_text, stt_status],
api_name="transcribe",
concurrency_limit=1, # never overlap two ASR GPU allocations
)
with gr.Tab("Text to speech"):
with gr.Row():
with gr.Column():
tts_text = gr.Textbox(
label="English text",
lines=8,
value="Kokoro is an open-weight text to speech model with 82 million parameters.",
info=f"Up to {TTS_DEFAULT_MAX_CHARS} characters by default (hard cap "
f"{TTS_MAX_CHARS_CAP}).",
)
with gr.Row():
tts_voice = gr.Dropdown(
choices=VOICE_CHOICES,
value=DEFAULT_VOICE,
label="Voice",
info="Grade is Kokoro's own estimate of training-data quality.",
)
tts_speed = gr.Slider(
minimum=SPEED_MIN,
maximum=SPEED_MAX,
value=SPEED_DEFAULT,
step=SPEED_STEP,
label="Speaking speed",
info="1.0 = the model's natural pace (library range 0.5-2.0).",
)
tts_limit = gr.Slider(
minimum=100,
maximum=TTS_MAX_CHARS_CAP,
value=TTS_DEFAULT_MAX_CHARS,
step=100,
label="Maximum text length (characters)",
)
tts_btn = gr.Button("Generate speech", variant="primary")
with gr.Column():
tts_audio = gr.Audio(
label="Generated audio (playable + downloadable WAV, 24 kHz)",
type="filepath",
interactive=False,
buttons=["download"], # gradio 6: was show_download_button=True
)
tts_status = gr.Markdown("")
tts_btn.click(
fn=speak,
inputs=[tts_text, tts_voice, tts_speed, tts_limit],
outputs=[tts_audio, tts_status],
api_name="speak",
concurrency_limit=1, # ditto: one TTS GPU allocation at a time
)
gr.Markdown(
"Audio uploads are read in place and never copied to disk by this app; generated "
"WAVs live in the container's temp dir and are deleted after "
f"{TMP_TTL_S // 3600} h. Transcripts, generated audio and text inputs are never "
"logged."
)
# Serial GPU work queue-wide: overlapping allocations would spike memory and burn quota
# twice for the same user. max_size caps how many requests may wait in line.
demo.queue(default_concurrency_limit=1, max_size=16)
if __name__ == "__main__":
demo.launch()