jpedrops commited on
Commit
c081e18
·
1 Parent(s): ba9f88c

feat: CosyVoice2 zero-shot TTS Gradio Space

Browse files
Files changed (5) hide show
  1. README.md +18 -4
  2. app.py +126 -0
  3. index.html +0 -19
  4. requirements.txt +21 -0
  5. style.css +0 -28
README.md CHANGED
@@ -1,11 +1,25 @@
1
  ---
2
  title: CosyVoice
3
- emoji: 📊
4
  colorFrom: red
5
  colorTo: blue
6
- sdk: static
 
 
7
  pinned: false
8
- short_description: 'tts fancy '
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: CosyVoice
3
+ emoji: 🗣️
4
  colorFrom: red
5
  colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 5.9.1
8
+ app_file: app.py
9
  pinned: false
10
+ short_description: 'CosyVoice2 zero-shot TTS'
11
  ---
12
 
13
+ # CosyVoice2 — zero-shot TTS
14
+
15
+ Fancy Gradio demo of [CosyVoice2-0.5B](https://huggingface.co/FunAudioLLM/CosyVoice2-0.5B):
16
+ clone any voice from a short reference clip and synthesize new speech.
17
+
18
+ - Enter the **text** to speak.
19
+ - Upload/record a **reference clip** (3–10 s, clean) and type its **transcript**.
20
+ - Get cloned-voice audio back.
21
+
22
+ > On CPU hardware this is slow. For real-time use, run the Space on GPU
23
+ > (ZeroGPU/A10G) — the code auto-uses `@spaces.GPU` when available.
24
+
25
+ The CosyVoice inference code and the model weights are fetched on first launch.
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CosyVoice2 zero-shot TTS — Hugging Face Space (Gradio).
3
+
4
+ On first launch it fetches the CosyVoice inference code (repo + Matcha-TTS
5
+ submodule) and the CosyVoice2-0.5B weights, then serves a zero-shot voice-cloning
6
+ UI: give a reference clip + its transcript, type new text, get cloned speech.
7
+
8
+ Runs on CPU (slow) or GPU. When the Space has ZeroGPU/GPU hardware the heavy
9
+ inference is wrapped with @spaces.GPU automatically.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+
18
+ import gradio as gr
19
+
20
+ HERE = os.path.dirname(os.path.abspath(__file__))
21
+ REPO_DIR = os.path.join(HERE, "CosyVoice")
22
+ MODEL_DIR = os.path.join(HERE, "pretrained_models", "CosyVoice2-0.5B")
23
+ REPO_URL = "https://github.com/FunAudioLLM/CosyVoice.git"
24
+ MODEL_ID = "FunAudioLLM/CosyVoice2-0.5B"
25
+
26
+ # ── Optional ZeroGPU support ────────────────────────────────────────────────
27
+ try:
28
+ import spaces # type: ignore
29
+ GPU = spaces.GPU
30
+ except Exception: # not on a ZeroGPU Space
31
+ def GPU(*args, **kwargs):
32
+ def _wrap(fn):
33
+ return fn
34
+ return _wrap(args[0]) if args and callable(args[0]) else _wrap
35
+
36
+
37
+ def _bootstrap() -> None:
38
+ """Fetch the CosyVoice code + Matcha-TTS submodule and the model weights."""
39
+ if not os.path.isdir(REPO_DIR):
40
+ subprocess.run(
41
+ ["git", "clone", "--recursive", REPO_URL, REPO_DIR],
42
+ check=True,
43
+ )
44
+ for p in (REPO_DIR, os.path.join(REPO_DIR, "third_party", "Matcha-TTS")):
45
+ if os.path.isdir(p) and p not in sys.path:
46
+ sys.path.insert(0, p)
47
+ if not os.path.isdir(MODEL_DIR) or not os.listdir(MODEL_DIR):
48
+ from huggingface_hub import snapshot_download
49
+ snapshot_download(MODEL_ID, local_dir=MODEL_DIR)
50
+
51
+
52
+ _model = None
53
+ _model_lock = threading.Lock()
54
+ _boot_error: str | None = None
55
+
56
+
57
+ def _get_model():
58
+ global _model, _boot_error
59
+ if _model is None:
60
+ with _model_lock:
61
+ if _model is None:
62
+ try:
63
+ _bootstrap()
64
+ from cosyvoice.cli.cosyvoice import CosyVoice2 # noqa: WPS433
65
+ _model = CosyVoice2(MODEL_DIR, load_jit=False, load_trt=False, fp16=False)
66
+ except Exception as exc: # surfaced in the UI
67
+ _boot_error = f"{type(exc).__name__}: {exc}"
68
+ raise
69
+ return _model
70
+
71
+
72
+ @GPU
73
+ def synthesize(text, prompt_audio, prompt_text):
74
+ if not (text or "").strip():
75
+ raise gr.Error("Digite o texto a ser falado.")
76
+ if not prompt_audio:
77
+ raise gr.Error("Envie ou grave um áudio de referência (voz a clonar).")
78
+ if not (prompt_text or "").strip():
79
+ raise gr.Error("Digite a transcrição exata do áudio de referência.")
80
+
81
+ import torchaudio
82
+ from cosyvoice.utils.file_utils import load_wav
83
+
84
+ model = _get_model()
85
+ prompt_16k = load_wav(prompt_audio, 16000)
86
+ chunks = []
87
+ for out in model.inference_zero_shot(text, prompt_text, prompt_16k, stream=False):
88
+ chunks.append(out["tts_speech"])
89
+ if not chunks:
90
+ raise gr.Error("Nenhum áudio gerado.")
91
+ import torch
92
+ speech = torch.cat(chunks, dim=1)
93
+ out_path = os.path.join(HERE, "output.wav")
94
+ torchaudio.save(out_path, speech, model.sample_rate)
95
+ return out_path
96
+
97
+
98
+ CSS = """
99
+ .gradio-container { max-width: 860px !important; }
100
+ footer { display: none !important; }
101
+ """
102
+
103
+ with gr.Blocks(title="CosyVoice2 — TTS", css=CSS, theme=gr.themes.Soft()) as demo:
104
+ gr.Markdown(
105
+ "# 🗣️ CosyVoice2 — Zero-shot TTS\n"
106
+ "Clone uma voz a partir de um clipe curto de referência e sintetize um novo texto."
107
+ )
108
+ with gr.Row():
109
+ with gr.Column():
110
+ text = gr.Textbox(label="Texto a sintetizar", lines=4,
111
+ placeholder="Escreva aqui o que a voz deve falar…")
112
+ prompt_audio = gr.Audio(label="Áudio de referência (3–10 s, limpo)",
113
+ type="filepath", sources=["upload", "microphone"])
114
+ prompt_text = gr.Textbox(label="Transcrição do áudio de referência", lines=2,
115
+ placeholder="Exatamente o que é dito no clipe acima")
116
+ btn = gr.Button("🎙️ Gerar voz", variant="primary")
117
+ with gr.Column():
118
+ out = gr.Audio(label="Resultado", type="filepath", interactive=False)
119
+ btn.click(synthesize, inputs=[text, prompt_audio, prompt_text], outputs=out)
120
+ gr.Markdown(
121
+ "<sub>Modelo: CosyVoice2-0.5B. No hardware CPU a geração é lenta; "
122
+ "use GPU/ZeroGPU para tempo real.</sub>"
123
+ )
124
+
125
+ if __name__ == "__main__":
126
+ demo.queue().launch()
index.html DELETED
@@ -1,19 +0,0 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CosyVoice2 Gradio Space. The CosyVoice repo (code + Matcha-TTS submodule) and
2
+ # the model weights are fetched at runtime by app.py; these are the Python deps
3
+ # its inference path needs.
4
+ gradio>=5
5
+ spaces # ZeroGPU decorator (@spaces.GPU); harmless on CPU
6
+ torch
7
+ torchaudio
8
+ huggingface_hub
9
+ modelscope
10
+ soundfile
11
+ librosa
12
+ numpy
13
+ scipy
14
+ hyperpyyaml
15
+ omegaconf
16
+ conformer
17
+ diffusers
18
+ lightning
19
+ rich
20
+ inflect
21
+ onnxruntime
style.css DELETED
@@ -1,28 +0,0 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
- }
5
-
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
28
- }