"""
CosyVoice2 zero-shot TTS — Hugging Face Space (Gradio).
On first launch it fetches the CosyVoice inference code (repo + Matcha-TTS
submodule) and the CosyVoice2-0.5B weights, then serves a zero-shot voice-cloning
UI: give a reference clip + its transcript, type new text, get cloned speech.
Runs on CPU (slow) or GPU. When the Space has ZeroGPU/GPU hardware the heavy
inference is wrapped with @spaces.GPU automatically.
"""
from __future__ import annotations
import os
import subprocess
import sys
import threading
import gradio as gr
HERE = os.path.dirname(os.path.abspath(__file__))
REPO_DIR = os.path.join(HERE, "CosyVoice")
MODEL_DIR = os.path.join(HERE, "pretrained_models", "CosyVoice2-0.5B")
REPO_URL = "https://github.com/FunAudioLLM/CosyVoice.git"
MODEL_ID = "FunAudioLLM/CosyVoice2-0.5B"
# ── Optional ZeroGPU support ────────────────────────────────────────────────
try:
import spaces # type: ignore
GPU = spaces.GPU
except Exception: # not on a ZeroGPU Space
def GPU(*args, **kwargs):
def _wrap(fn):
return fn
return _wrap(args[0]) if args and callable(args[0]) else _wrap
def _bootstrap() -> None:
"""Fetch the CosyVoice code + Matcha-TTS submodule and the model weights."""
if not os.path.isdir(REPO_DIR):
subprocess.run(
["git", "clone", "--recursive", REPO_URL, REPO_DIR],
check=True,
)
for p in (REPO_DIR, os.path.join(REPO_DIR, "third_party", "Matcha-TTS")):
if os.path.isdir(p) and p not in sys.path:
sys.path.insert(0, p)
if not os.path.isdir(MODEL_DIR) or not os.listdir(MODEL_DIR):
from huggingface_hub import snapshot_download
snapshot_download(MODEL_ID, local_dir=MODEL_DIR)
_model = None
_model_lock = threading.Lock()
_boot_error: str | None = None
def _get_model():
global _model, _boot_error
if _model is None:
with _model_lock:
if _model is None:
try:
_bootstrap()
from cosyvoice.cli.cosyvoice import CosyVoice2 # noqa: WPS433
_model = CosyVoice2(MODEL_DIR, load_jit=False, load_trt=False, fp16=False)
except Exception as exc: # surfaced in the UI
_boot_error = f"{type(exc).__name__}: {exc}"
raise
return _model
LANGS = {
"pt": {
"title": "# 🗣️ CosyVoice2 — Zero-shot TTS",
"subtitle": "Clone uma voz a partir de um clipe curto de referência e sintetize um novo texto.",
"text_label": "Texto a sintetizar",
"text_ph": "Escreva aqui o que a voz deve falar…",
"audio_label": "Áudio de referência (3–10 s, limpo)",
"prompt_label": "Transcrição do áudio de referência",
"prompt_ph": "Exatamente o que é dito no clipe acima",
"btn": "🎙️ Gerar voz",
"out_label": "Resultado",
"footer": "Modelo: CosyVoice2-0.5B. No hardware CPU a geração é lenta; "
"use GPU/ZeroGPU para tempo real.",
"err_text": "Digite o texto a ser falado.",
"err_audio": "Envie ou grave um áudio de referência (voz a clonar).",
"err_prompt": "Digite a transcrição exata do áudio de referência.",
"err_empty": "Nenhum áudio gerado.",
},
"en": {
"title": "# 🗣️ CosyVoice2 — Zero-shot TTS",
"subtitle": "Clone a voice from a short reference clip and synthesize new text.",
"text_label": "Text to synthesize",
"text_ph": "Type here what the voice should say…",
"audio_label": "Reference audio (3–10 s, clean)",
"prompt_label": "Reference audio transcript",
"prompt_ph": "Exactly what is said in the clip above",
"btn": "🎙️ Generate voice",
"out_label": "Result",
"footer": "Model: CosyVoice2-0.5B. Generation is slow on CPU hardware; "
"use GPU/ZeroGPU for real time.",
"err_text": "Enter the text to be spoken.",
"err_audio": "Upload or record a reference audio (the voice to clone).",
"err_prompt": "Enter the exact transcript of the reference audio.",
"err_empty": "No audio generated.",
},
}
@GPU
def synthesize(text, prompt_audio, prompt_text, lang="pt"):
t = LANGS.get(lang, LANGS["pt"])
if not (text or "").strip():
raise gr.Error(t["err_text"])
if not prompt_audio:
raise gr.Error(t["err_audio"])
if not (prompt_text or "").strip():
raise gr.Error(t["err_prompt"])
import torchaudio
from cosyvoice.utils.file_utils import load_wav
model = _get_model()
prompt_16k = load_wav(prompt_audio, 16000)
chunks = []
for out in model.inference_zero_shot(text, prompt_text, prompt_16k, stream=False):
chunks.append(out["tts_speech"])
if not chunks:
raise gr.Error(t["err_empty"])
import torch
speech = torch.cat(chunks, dim=1)
out_path = os.path.join(HERE, "output.wav")
torchaudio.save(out_path, speech, model.sample_rate)
return out_path
CSS = """
.gradio-container { max-width: 860px !important; }
footer { display: none !important; }
"""
def set_lang(lang):
t = LANGS.get(lang, LANGS["pt"])
return [
lang,
gr.Markdown(f"{t['title']}\n{t['subtitle']}"),
gr.Textbox(label=t["text_label"], placeholder=t["text_ph"]),
gr.Audio(label=t["audio_label"]),
gr.Textbox(label=t["prompt_label"], placeholder=t["prompt_ph"]),
gr.Button(t["btn"]),
gr.Audio(label=t["out_label"]),
gr.Markdown(t["footer"]),
gr.Button(variant="primary" if lang == "pt" else "secondary"),
gr.Button(variant="primary" if lang == "en" else "secondary"),
]
with gr.Blocks(title="CosyVoice2 — TTS", css=CSS, theme=gr.themes.Soft()) as demo:
lang_state = gr.State("pt")
title_md = gr.Markdown(
f"{LANGS['pt']['title']}\n{LANGS['pt']['subtitle']}"
)
with gr.Row():
btn_pt = gr.Button("🇧🇷 Português", size="sm", variant="primary")
btn_en = gr.Button("🇺🇸 English", size="sm", variant="secondary")
with gr.Row():
with gr.Column():
text = gr.Textbox(label=LANGS["pt"]["text_label"], lines=4,
placeholder=LANGS["pt"]["text_ph"])
prompt_audio = gr.Audio(label=LANGS["pt"]["audio_label"],
type="filepath", sources=["upload", "microphone"])
prompt_text = gr.Textbox(label=LANGS["pt"]["prompt_label"], lines=2,
placeholder=LANGS["pt"]["prompt_ph"])
btn = gr.Button(LANGS["pt"]["btn"], variant="primary")
with gr.Column():
out = gr.Audio(label=LANGS["pt"]["out_label"], type="filepath", interactive=False)
footer_md = gr.Markdown(LANGS["pt"]["footer"])
lang_outputs = [lang_state, title_md, text, prompt_audio, prompt_text,
btn, out, footer_md, btn_pt, btn_en]
btn_pt.click(lambda: set_lang("pt"), outputs=lang_outputs)
btn_en.click(lambda: set_lang("en"), outputs=lang_outputs)
btn.click(synthesize, inputs=[text, prompt_audio, prompt_text, lang_state], outputs=out)
if __name__ == "__main__":
demo.queue().launch()