IFMedTechdemo commited on
Commit
a818502
·
verified ·
1 Parent(s): 4654d74

Add NeuTTS-Air model alongside Kokoro TTS with model selection

Browse files
Files changed (1) hide show
  1. app.py +151 -52
app.py CHANGED
@@ -1,18 +1,27 @@
1
- """
2
- 🎙️ Kokoro-TTS-only demo – Zero-GPU edition
3
- Routes every synthesis to an idle A100.
4
- """
5
-
6
- import os, tempfile, subprocess, numpy as np
7
  import gradio as gr
8
- import spaces # Zero-GPU decorator
9
  import soundfile as sf
10
 
11
- # ------------------------------------------------------------------
12
- # 1. Lazy Kokoro loader (runs once per GPU worker)
13
- # ------------------------------------------------------------------
 
14
  kokoro_pipe = None
 
15
 
 
 
 
 
 
 
 
 
 
16
  def load_kokoro():
17
  global kokoro_pipe
18
  if kokoro_pipe is None:
@@ -20,60 +29,150 @@ def load_kokoro():
20
  kokoro_pipe = KPipeline(lang_code='a')
21
  return kokoro_pipe
22
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # ------------------------------------------------------------------
24
- # 2. Generation helper
25
  # ------------------------------------------------------------------
26
- @spaces.GPU
27
- def tts_kokoro(text, voice, speed):
 
 
 
28
  pipe = load_kokoro()
29
  generator = pipe(text, voice=voice, speed=speed)
30
  for gs, ps, audio in generator:
31
- return audio
 
 
 
 
32
  raise RuntimeError("Kokoro generation failed")
33
 
34
  # ------------------------------------------------------------------
35
- # 3. Zero-GPU entry point
36
  # ------------------------------------------------------------------
37
- @spaces.GPU
38
- def synthesise(text, voice, speed):
39
- if not text.strip():
40
- raise gr.Error("Please enter some text.")
41
- wav = tts_kokoro(text, voice=voice, speed=speed)
42
- fd, tmp = tempfile.mkstemp(suffix='.wav')
43
- os.close(fd)
44
- sf.write(tmp, wav, 24000)
45
- return tmp
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  # ------------------------------------------------------------------
48
- # 4. Gradio UI
49
  # ------------------------------------------------------------------
50
  css = """footer {visibility: hidden}"""
51
 
52
- with gr.Blocks(css=css, title="Kokoro TTS – Zero-GPU") as demo:
53
- gr.Markdown("## 🎙️ Kokoro TTS – Zero-GPU Demo")
54
-
55
- with gr.Row():
56
- with gr.Column():
57
- voice = gr.Dropdown(
58
- label="Voice",
59
- choices=['af_heart', 'af_sky', 'af_mist', 'af_dusk'],
60
- value='af_heart'
61
- )
62
- speed = gr.Slider(0.5, 2.0, 1.0, step=0.1, label="Speed")
63
-
64
- with gr.Column(scale=3):
65
- text = gr.Textbox(
66
- label="Text to speak",
67
- placeholder="Type or paste text here …",
68
- lines=6, max_lines=12
69
- )
70
- btn = gr.Button("🎧 Synthesise", variant="primary")
71
- audio_out = gr.Audio(label="Generated speech", type="filepath")
72
-
73
- btn.click(synthesise, inputs=[text, voice, speed], outputs=audio_out)
74
-
75
- gr.Markdown("### Tips \n"
76
- "- **Kokoro** – fast, high-quality English TTS \n"
77
- "Audio is returned as 24 kHz WAV.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- demo.launch()
 
 
1
+ import spaces
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ import numpy as np
 
6
  import gradio as gr
 
7
  import soundfile as sf
8
 
9
+ # Add NeuTTS-Air to path
10
+ sys.path.append("neutts-air")
11
+
12
+ # Global variables for lazy loading
13
  kokoro_pipe = None
14
+ neutts_model = None
15
 
16
+ # NeuTTS-Air configuration
17
+ SAMPLES_PATH = os.path.join(os.getcwd(), "neutts-air", "samples")
18
+ DEFAULT_REF_TEXT = "So I'm live on radio. And I say, well, my dear friend James here clearly, and the whole room just froze. Turns out I'd completely misspoken and mentioned our other friend."
19
+ DEFAULT_REF_PATH = os.path.join(SAMPLES_PATH, "dave.wav")
20
+ DEFAULT_GEN_TEXT = "My name is Dave, and um, I'm from London."
21
+
22
+ # ------------------------------------------------------------------
23
+ # 1. Lazy loaders
24
+ # ------------------------------------------------------------------
25
  def load_kokoro():
26
  global kokoro_pipe
27
  if kokoro_pipe is None:
 
29
  kokoro_pipe = KPipeline(lang_code='a')
30
  return kokoro_pipe
31
 
32
+ def load_neutts():
33
+ global neutts_model
34
+ if neutts_model is None:
35
+ from neuttsair.neutts import NeuTTSAir
36
+ neutts_model = NeuTTSAir(
37
+ backbone_repo="neuphonic/neutts-air",
38
+ backbone_device="cuda",
39
+ codec_repo="neuphonic/neucodec",
40
+ codec_device="cuda"
41
+ )
42
+ return neutts_model
43
+
44
  # ------------------------------------------------------------------
45
+ # 2. Kokoro TTS inference
46
  # ------------------------------------------------------------------
47
+ @spaces.GPU()
48
+ def kokoro_infer(text, voice, speed):
49
+ if not text.strip():
50
+ raise gr.Error("Please enter some text.")
51
+
52
  pipe = load_kokoro()
53
  generator = pipe(text, voice=voice, speed=speed)
54
  for gs, ps, audio in generator:
55
+ # Save to temporary file
56
+ fd, tmp = tempfile.mkstemp(suffix='.wav')
57
+ os.close(fd)
58
+ sf.write(tmp, audio, 24000)
59
+ return tmp
60
  raise RuntimeError("Kokoro generation failed")
61
 
62
  # ------------------------------------------------------------------
63
+ # 3. NeuTTS-Air inference
64
  # ------------------------------------------------------------------
65
+ @spaces.GPU()
66
+ def neutts_infer(ref_text: str, ref_audio_path: str, gen_text: str) -> tuple:
67
+ """
68
+ Generates speech using NeuTTS-Air given a reference audio and text, and new text to synthesize.
69
+ """
70
+ if not gen_text.strip():
71
+ raise gr.Error("Please enter text to generate.")
72
+ if not ref_audio_path:
73
+ raise gr.Error("Please provide reference audio.")
74
+ if not ref_text.strip():
75
+ raise gr.Error("Please provide reference text.")
76
+
77
+ gr.Info("Starting inference request!")
78
+ gr.Info("Encoding reference...")
79
+
80
+ tts = load_neutts()
81
+ ref_codes = tts.encode_reference(ref_audio_path)
82
+
83
+ gr.Info(f"Generating audio for input text: {gen_text}")
84
+ wav = tts.infer(gen_text, ref_codes, ref_text)
85
+
86
+ return (24_000, wav)
87
 
88
  # ------------------------------------------------------------------
89
+ # 4. Gradio UI with model selection
90
  # ------------------------------------------------------------------
91
  css = """footer {visibility: hidden}"""
92
 
93
+ with gr.Blocks(css=css, title="Text2Audio - Kokoro & NeuTTS-Air") as demo:
94
+ gr.Markdown("# 🎙️ Text-to-Audio Generation")
95
+ gr.Markdown("Choose between **Kokoro TTS** (fast English TTS) or **NeuTTS-Air** (voice cloning with reference audio)")
96
+
97
+ # Model selection
98
+ model_choice = gr.Radio(
99
+ choices=["Kokoro TTS", "NeuTTS-Air"],
100
+ value="Kokoro TTS",
101
+ label="Select TTS Engine",
102
+ interactive=True
103
+ )
104
+
105
+ # Kokoro TTS Interface
106
+ with gr.Group(visible=True) as kokoro_group:
107
+ gr.Markdown("### 🎧 Kokoro TTS Settings")
108
+ with gr.Row():
109
+ with gr.Column():
110
+ kokoro_voice = gr.Dropdown(
111
+ label="Voice",
112
+ choices=['af_heart', 'af_sky', 'af_mist', 'af_dusk'],
113
+ value='af_heart'
114
+ )
115
+ kokoro_speed = gr.Slider(0.5, 2.0, 1.0, step=0.1, label="Speed")
116
+
117
+ with gr.Column(scale=3):
118
+ kokoro_text = gr.Textbox(
119
+ label="Text to speak",
120
+ placeholder="Type or paste text here…",
121
+ lines=6,
122
+ max_lines=12
123
+ )
124
+ kokoro_btn = gr.Button("🎧 Synthesise with Kokoro", variant="primary")
125
+ kokoro_audio_out = gr.Audio(label="Generated speech", type="filepath")
126
+
127
+ gr.Markdown("**Kokoro** – fast, high-quality English TTS. Audio is returned as 24 kHz WAV.")
128
+
129
+ # NeuTTS-Air Interface
130
+ with gr.Group(visible=False) as neutts_group:
131
+ gr.Markdown("### ☁️ NeuTTS-Air Settings")
132
+ neutts_ref_text = gr.Textbox(
133
+ label="Reference Text",
134
+ value=DEFAULT_REF_TEXT,
135
+ lines=3
136
+ )
137
+ neutts_ref_audio = gr.Audio(
138
+ type="filepath",
139
+ label="Reference Audio",
140
+ value=DEFAULT_REF_PATH if os.path.exists(DEFAULT_REF_PATH) else None
141
+ )
142
+ neutts_gen_text = gr.Textbox(
143
+ label="Text to Generate",
144
+ value=DEFAULT_GEN_TEXT,
145
+ lines=3
146
+ )
147
+ neutts_btn = gr.Button("☁️ Generate with NeuTTS-Air", variant="primary")
148
+ neutts_audio_out = gr.Audio(label="Generated Speech", type="numpy")
149
+
150
+ gr.Markdown("**NeuTTS-Air** – Upload a reference audio sample, provide the reference text, and enter new text to synthesize.")
151
+
152
+ # Event handlers
153
+ def toggle_interface(choice):
154
+ if choice == "Kokoro TTS":
155
+ return gr.update(visible=True), gr.update(visible=False)
156
+ else:
157
+ return gr.update(visible=False), gr.update(visible=True)
158
+
159
+ model_choice.change(
160
+ fn=toggle_interface,
161
+ inputs=[model_choice],
162
+ outputs=[kokoro_group, neutts_group]
163
+ )
164
+
165
+ kokoro_btn.click(
166
+ kokoro_infer,
167
+ inputs=[kokoro_text, kokoro_voice, kokoro_speed],
168
+ outputs=kokoro_audio_out
169
+ )
170
+
171
+ neutts_btn.click(
172
+ neutts_infer,
173
+ inputs=[neutts_ref_text, neutts_ref_audio, neutts_gen_text],
174
+ outputs=neutts_audio_out
175
+ )
176
 
177
+ if __name__ == "__main__":
178
+ demo.launch(allowed_paths=[SAMPLES_PATH] if os.path.exists(SAMPLES_PATH) else None, mcp_server=True, inbrowser=True)