DevBM commited on
Commit
dda1a58
·
verified ·
1 Parent(s): c52e7ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -141
app.py CHANGED
@@ -14,113 +14,24 @@ if not IS_DUPLICATE:
14
 
15
  CHAR_LIMIT = None if IS_DUPLICATE else 5000
16
 
17
- # Initialize models
18
  models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
19
 
20
- # Supported language codes from docs
21
- LANG_CODES = {
22
- "🇺🇸 American English": "a",
23
- "🇬🇧 British English": "b",
24
- "🇯🇵 Japanese": "j",
25
- "🇨🇳 Mandarin Chinese": "z",
26
- "🇪🇸 Spanish": "e",
27
- "🇫🇷 French": "f",
28
- "🇮🇳 Hindi": "h",
29
- "🇮🇹 Italian": "i",
30
- "🇧🇷 Brazilian Portuguese": "p"
31
- }
32
-
33
- # Initialize all pipelines
34
- pipelines = {code: KPipeline(lang_code=code, model=False) for code in LANG_CODES.values()}
35
-
36
- # Voice dictionary grouped by language
37
- VOICES = {
38
- "a": { # American English
39
- '🇺🇸 🚺 Heart ❤️': 'af_heart',
40
- '🇺🇸 🚺 Bella 🔥': 'af_bella',
41
- '🇺🇸 🚺 Nicole 🎧': 'af_nicole',
42
- '🇺🇸 🚺 Aoede': 'af_aoede',
43
- '🇺🇸 🚺 Kore': 'af_kore',
44
- '🇺🇸 🚺 Sarah': 'af_sarah',
45
- '🇺🇸 🚺 Nova': 'af_nova',
46
- '🇺🇸 🚺 Sky': 'af_sky',
47
- '🇺🇸 🚺 Alloy': 'af_alloy',
48
- '🇺🇸 🚺 Jessica': 'af_jessica',
49
- '🇺🇸 🚺 River': 'af_river',
50
- '🇺🇸 🚹 Michael': 'am_michael',
51
- '🇺🇸 🚹 Fenrir': 'am_fenrir',
52
- '🇺🇸 🚹 Puck': 'am_puck',
53
- '🇺🇸 🚹 Echo': 'am_echo',
54
- '🇺🇸 🚹 Eric': 'am_eric',
55
- '🇺🇸 🚹 Liam': 'am_liam',
56
- '🇺🇸 🚹 Onyx': 'am_onyx',
57
- '🇺🇸 🚹 Santa': 'am_santa',
58
- '🇺🇸 🚹 Adam': 'am_adam',
59
- },
60
- "b": { # British English
61
- '🇬🇧 🚺 Emma': 'bf_emma',
62
- '🇬🇧 🚺 Isabella': 'bf_isabella',
63
- '🇬🇧 🚺 Alice': 'bf_alice',
64
- '🇬🇧 🚺 Lily': 'bf_lily',
65
- '🇬🇧 🚹 George': 'bm_george',
66
- '🇬🇧 🚹 Fable': 'bm_fable',
67
- '🇬🇧 🚹 Lewis': 'bm_lewis',
68
- '🇬🇧 🚹 Daniel': 'bm_daniel',
69
- },
70
- "j": { # Japanese
71
- '🇯🇵 🚺 Alpha': 'jf_alpha',
72
- '🇯🇵 🚺 Gongitsune': 'jf_gongitsune',
73
- '🇯🇵 🚺 Nezumi': 'jf_nezumi',
74
- '🇯🇵 🚺 Tebukuro': 'jf_tebukuro',
75
- '🇯🇵 🚹 Kumo': 'jm_kumo',
76
- },
77
- "z": { # Mandarin Chinese
78
- '🇨🇳 🚺 Xiaobei': 'zf_xiaobei',
79
- '🇨🇳 🚺 Xiaoni': 'zf_xiaoni',
80
- '🇨🇳 🚺 Xiaoxiao': 'zf_xiaoxiao',
81
- '🇨🇳 🚺 Xiaoyi': 'zf_xiaoyi',
82
- '🇨🇳 🚹 Yunjian': 'zm_yunjian',
83
- '🇨🇳 🚹 Yunxi': 'zm_yunxi',
84
- '🇨🇳 🚹 Yunxia': 'zm_yunxia',
85
- '🇨🇳 🚹 Yunyang': 'zm_yunyang',
86
- },
87
- "e": { # Spanish
88
- '🇪🇸 🚺 Dora': 'ef_dora',
89
- '🇪🇸 🚹 Alex': 'em_alex',
90
- '🇪🇸 🚹 Santa': 'em_santa',
91
- },
92
- "f": { # French
93
- '🇫🇷 🚺 Siwis': 'ff_siwis',
94
- },
95
- "h": { # Hindi
96
- '🇮🇳 🚺 Alpha': 'hf_alpha',
97
- '🇮🇳 🚺 Beta': 'hf_beta',
98
- '🇮🇳 🚹 Omega': 'hm_omega',
99
- '🇮🇳 🚹 Psi': 'hm_psi',
100
- },
101
- "i": { # Italian
102
- '🇮🇹 🚺 Sara': 'if_sara',
103
- '🇮🇹 🚹 Nicola': 'im_nicola',
104
- },
105
- "p": { # Brazilian Portuguese
106
- '🇧🇷 🚺 Dora': 'pf_dora',
107
- '🇧🇷 🚹 Alex': 'pm_alex',
108
- '🇧🇷 🚹 Santa': 'pm_santa',
109
- }
110
- }
111
 
112
- # Preload voices
113
- for lang_code, voices in VOICES.items():
114
- for v in voices.values():
115
- pipelines[lang_code].load_voice(v)
116
 
117
  @spaces.GPU(duration=30)
118
  def forward_gpu(ps, ref_s, speed):
119
  return models[True](ps, ref_s, speed)
120
 
121
- def generate_first(text, lang, voice, speed=1, use_gpu=CUDA_AVAILABLE):
122
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
123
- pipeline = pipelines[lang]
124
  pack = pipeline.load_voice(voice)
125
  use_gpu = use_gpu and CUDA_AVAILABLE
126
  for _, ps, _ in pipeline(text, voice, speed):
@@ -133,22 +44,26 @@ def generate_first(text, lang, voice, speed=1, use_gpu=CUDA_AVAILABLE):
133
  except gr.exceptions.Error as e:
134
  if use_gpu:
135
  gr.Warning(str(e))
136
- gr.Info('Retrying with CPU.')
137
  audio = models[False](ps, ref_s, speed)
138
  else:
139
  raise gr.Error(e)
140
  return (24000, audio.numpy()), ps
141
  return None, ''
142
 
143
- def tokenize_first(text, lang, voice):
144
- pipeline = pipelines[lang]
 
 
 
 
145
  for _, ps, _ in pipeline(text, voice):
146
  return ps
147
  return ''
148
 
149
- def generate_all(text, lang, voice, speed=1, use_gpu=CUDA_AVAILABLE):
150
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
151
- pipeline = pipelines[lang]
152
  pack = pipeline.load_voice(voice)
153
  use_gpu = use_gpu and CUDA_AVAILABLE
154
  first = True
@@ -185,7 +100,51 @@ def get_frankenstein():
185
  with open('frankenstein5k.md', 'r') as r:
186
  return r.read().strip()
187
 
188
- # UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  TOKEN_NOTE = '''
190
  💡 Customize pronunciation with Markdown link syntax and /slashes/ like `[Kokoro](/kˈOkəɹO/)`
191
 
@@ -200,22 +159,31 @@ with gr.Blocks() as generate_tab:
200
  out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
201
  generate_btn = gr.Button('Generate', variant='primary')
202
  with gr.Accordion('Output Tokens', open=True):
203
- out_ps = gr.Textbox(interactive=False, show_label=False)
204
  tokenize_btn = gr.Button('Tokenize', variant='secondary')
205
  gr.Markdown(TOKEN_NOTE)
206
  predict_btn = gr.Button('Predict', variant='secondary', visible=False)
207
 
208
- STREAM_NOTE = '⚠️ Streaming might fail the first time. Try again if no audio plays.'
 
 
 
 
 
209
  with gr.Blocks() as stream_tab:
210
  out_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
211
  with gr.Row():
212
  stream_btn = gr.Button('Stream', variant='primary')
213
  stop_btn = gr.Button('Stop', variant='stop')
 
 
 
214
 
215
  BANNER_TEXT = '''
216
- [***Kokoro*** **TTS model - multilingual**](https://huggingface.co/hexgrad/Kokoro-82M)
217
- '''
218
 
 
 
219
  API_OPEN = os.getenv('SPACE_ID') != 'hexgrad/Kokoro-TTS'
220
  API_NAME = None if API_OPEN else False
221
  with gr.Blocks() as app:
@@ -223,42 +191,31 @@ with gr.Blocks() as app:
223
  gr.Markdown(BANNER_TEXT, container=True)
224
  with gr.Row():
225
  with gr.Column():
226
- text = gr.Textbox(label='Input Text')
227
- lang = gr.Dropdown(list(LANG_CODES.keys()), value="🇺🇸 American English", label="Language")
228
- voice = gr.Dropdown([], label='Voice') # Populated dynamically
229
-
230
- def update_voices(selected_lang):
231
- code = LANG_CODES[selected_lang]
232
- return gr.update(choices=list(VOICES[code].keys()), value=list(VOICES[code].keys())[0])
233
-
234
- lang.change(fn=update_voices, inputs=[lang], outputs=[voice])
235
- # Initialize with American English voices
236
- voice.choices = list(VOICES["a"].keys())
237
- voice.value = list(VOICES["a"].keys())[0]
238
-
239
- use_gpu = gr.Dropdown(
240
- [('ZeroGPU 🚀', True), ('CPU 🐌', False)],
241
- value=CUDA_AVAILABLE,
242
- label='Hardware',
243
- interactive=CUDA_AVAILABLE
244
- )
245
- speed = gr.Slider(0.5, 2, 1, 0.1, label='Speed')
246
- random_btn = gr.Button('🎲 Random Quote')
247
- gatsby_btn = gr.Button('🥂 Gatsby')
248
- frankenstein_btn = gr.Button('💀 Frankenstein')
249
  with gr.Column():
250
  gr.TabbedInterface([generate_tab, stream_tab], ['Generate', 'Stream'])
251
-
252
- random_btn.click(get_random_quote, outputs=[text])
253
- gatsby_btn.click(get_gatsby, outputs=[text])
254
- frankenstein_btn.click(get_frankenstein, outputs=[text])
255
- generate_btn.click(lambda t, l, v, s, g: generate_first(t, LANG_CODES[l], VOICES[LANG_CODES[l]][v], s, g),
256
- inputs=[text, lang, voice, speed, use_gpu], outputs=[out_audio, out_ps])
257
- tokenize_btn.click(lambda t, l, v: tokenize_first(t, LANG_CODES[l], VOICES[LANG_CODES[l]][v]),
258
- inputs=[text, lang, voice], outputs=[out_ps])
259
- stream_event = stream_btn.click(lambda t, l, v, s, g: generate_all(t, LANG_CODES[l], VOICES[LANG_CODES[l]][v], s, g),
260
- inputs=[text, lang, voice, speed, use_gpu], outputs=[out_stream])
261
  stop_btn.click(fn=None, cancels=stream_event)
 
262
 
263
  if __name__ == '__main__':
264
  app.queue(api_open=API_OPEN).launch(show_api=API_OPEN, ssr_mode=True)
 
14
 
15
  CHAR_LIMIT = None if IS_DUPLICATE else 5000
16
 
17
+ # --- Models: CPU & GPU ---
18
  models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
19
 
20
+ # --- Pipelines: American English (a), British English (b), Hindi (h) ---
21
+ pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'abh'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Example custom phoneme golds for English voices
24
+ pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkəɹO'
25
+ pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkəɹQ'
26
+ # Hindi pipeline can have custom entries if needed
27
 
28
  @spaces.GPU(duration=30)
29
  def forward_gpu(ps, ref_s, speed):
30
  return models[True](ps, ref_s, speed)
31
 
32
+ def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
33
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
34
+ pipeline = pipelines[voice[0]]
35
  pack = pipeline.load_voice(voice)
36
  use_gpu = use_gpu and CUDA_AVAILABLE
37
  for _, ps, _ in pipeline(text, voice, speed):
 
44
  except gr.exceptions.Error as e:
45
  if use_gpu:
46
  gr.Warning(str(e))
47
+ gr.Info('Retrying with CPU. To avoid this error, change Hardware to CPU.')
48
  audio = models[False](ps, ref_s, speed)
49
  else:
50
  raise gr.Error(e)
51
  return (24000, audio.numpy()), ps
52
  return None, ''
53
 
54
+ # Arena API
55
+ def predict(text, voice='af_heart', speed=1):
56
+ return generate_first(text, voice, speed, use_gpu=False)[0]
57
+
58
+ def tokenize_first(text, voice='af_heart'):
59
+ pipeline = pipelines[voice[0]]
60
  for _, ps, _ in pipeline(text, voice):
61
  return ps
62
  return ''
63
 
64
+ def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
65
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
66
+ pipeline = pipelines[voice[0]]
67
  pack = pipeline.load_voice(voice)
68
  use_gpu = use_gpu and CUDA_AVAILABLE
69
  first = True
 
100
  with open('frankenstein5k.md', 'r') as r:
101
  return r.read().strip()
102
 
103
+ # --- Voice Choices ---
104
+ CHOICES = {
105
+ # American English
106
+ '🇺🇸 🚺 Heart ❤️': 'af_heart',
107
+ '🇺🇸 🚺 Bella 🔥': 'af_bella',
108
+ '🇺🇸 🚺 Nicole 🎧': 'af_nicole',
109
+ '🇺🇸 🚺 Aoede': 'af_aoede',
110
+ '🇺🇸 🚺 Kore': 'af_kore',
111
+ '🇺🇸 🚺 Sarah': 'af_sarah',
112
+ '🇺🇸 🚺 Nova': 'af_nova',
113
+ '🇺🇸 🚺 Sky': 'af_sky',
114
+ '🇺🇸 🚺 Alloy': 'af_alloy',
115
+ '🇺🇸 🚺 Jessica': 'af_jessica',
116
+ '🇺🇸 🚺 River': 'af_river',
117
+ '🇺🇸 🚹 Michael': 'am_michael',
118
+ '🇺🇸 🚹 Fenrir': 'am_fenrir',
119
+ '🇺🇸 🚹 Puck': 'am_puck',
120
+ '🇺🇸 🚹 Echo': 'am_echo',
121
+ '🇺🇸 🚹 Eric': 'am_eric',
122
+ '🇺🇸 🚹 Liam': 'am_liam',
123
+ '🇺🇸 🚹 Onyx': 'am_onyx',
124
+ '🇺🇸 🚹 Santa': 'am_santa',
125
+ '🇺🇸 🚹 Adam': 'am_adam',
126
+
127
+ # British English
128
+ '🇬🇧 🚺 Emma': 'bf_emma',
129
+ '🇬🇧 🚺 Isabella': 'bf_isabella',
130
+ '🇬🇧 🚺 Alice': 'bf_alice',
131
+ '🇬🇧 🚺 Lily': 'bf_lily',
132
+ '🇬🇧 🚹 George': 'bm_george',
133
+ '🇬🇧 🚹 Fable': 'bm_fable',
134
+ '🇬🇧 🚹 Lewis': 'bm_lewis',
135
+ '🇬🇧 🚹 Daniel': 'bm_daniel',
136
+
137
+ # Hindi
138
+ '🇮🇳 🚺 Alpha': 'hf_alpha',
139
+ '🇮🇳 🚺 Beta': 'hf_beta',
140
+ '🇮🇳 🚹 Omega': 'hm_omega',
141
+ '🇮🇳 🚹 Psi': 'hm_psi',
142
+ }
143
+
144
+ # Preload all voices
145
+ for v in CHOICES.values():
146
+ pipelines[v[0]].load_voice(v)
147
+
148
  TOKEN_NOTE = '''
149
  💡 Customize pronunciation with Markdown link syntax and /slashes/ like `[Kokoro](/kˈOkəɹO/)`
150
 
 
159
  out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
160
  generate_btn = gr.Button('Generate', variant='primary')
161
  with gr.Accordion('Output Tokens', open=True):
162
+ out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
163
  tokenize_btn = gr.Button('Tokenize', variant='secondary')
164
  gr.Markdown(TOKEN_NOTE)
165
  predict_btn = gr.Button('Predict', variant='secondary', visible=False)
166
 
167
+ STREAM_NOTE = ['⚠️ There is an unknown Gradio bug that might yield no audio the first time you click `Stream`.']
168
+ if CHAR_LIMIT is not None:
169
+ STREAM_NOTE.append(f'✂️ Each stream is capped at {CHAR_LIMIT} characters.')
170
+ STREAM_NOTE.append('🚀 Want more characters? You can [use Kokoro directly](https://huggingface.co/hexgrad/Kokoro-82M#usage) or duplicate this space:')
171
+ STREAM_NOTE = '\n\n'.join(STREAM_NOTE)
172
+
173
  with gr.Blocks() as stream_tab:
174
  out_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
175
  with gr.Row():
176
  stream_btn = gr.Button('Stream', variant='primary')
177
  stop_btn = gr.Button('Stop', variant='stop')
178
+ with gr.Accordion('Note', open=True):
179
+ gr.Markdown(STREAM_NOTE)
180
+ gr.DuplicateButton()
181
 
182
  BANNER_TEXT = '''
183
+ [***Kokoro*** **is an open-weight TTS model with 82 million parameters.**](https://huggingface.co/hexgrad/Kokoro-82M)
 
184
 
185
+ This demo only showcases English and Hindi, but you can directly use the model to access other languages.
186
+ '''
187
  API_OPEN = os.getenv('SPACE_ID') != 'hexgrad/Kokoro-TTS'
188
  API_NAME = None if API_OPEN else False
189
  with gr.Blocks() as app:
 
191
  gr.Markdown(BANNER_TEXT, container=True)
192
  with gr.Row():
193
  with gr.Column():
194
+ text = gr.Textbox(label='Input Text', info=f"Up to ~500 characters per Generate, or {'∞' if CHAR_LIMIT is None else CHAR_LIMIT} characters per Stream")
195
+ with gr.Row():
196
+ voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
197
+ use_gpu = gr.Dropdown(
198
+ [('ZeroGPU 🚀', True), ('CPU 🐌', False)],
199
+ value=CUDA_AVAILABLE,
200
+ label='Hardware',
201
+ info='GPU is usually faster, but has a usage quota',
202
+ interactive=CUDA_AVAILABLE
203
+ )
204
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
205
+ random_btn = gr.Button('🎲 Random Quote 💬', variant='secondary')
206
+ with gr.Row():
207
+ gatsby_btn = gr.Button('🥂 Gatsby 📕', variant='secondary')
208
+ frankenstein_btn = gr.Button('💀 Frankenstein 📗', variant='secondary')
 
 
 
 
 
 
 
 
209
  with gr.Column():
210
  gr.TabbedInterface([generate_tab, stream_tab], ['Generate', 'Stream'])
211
+ random_btn.click(fn=get_random_quote, inputs=[], outputs=[text], api_name=API_NAME)
212
+ gatsby_btn.click(fn=get_gatsby, inputs=[], outputs=[text], api_name=API_NAME)
213
+ frankenstein_btn.click(fn=get_frankenstein, inputs=[], outputs=[text], api_name=API_NAME)
214
+ generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu], outputs=[out_audio, out_ps], api_name=API_NAME)
215
+ tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps], api_name=API_NAME)
216
+ stream_event = stream_btn.click(fn=generate_all, inputs=[text, voice, speed, use_gpu], outputs=[out_stream], api_name=API_NAME)
 
 
 
 
217
  stop_btn.click(fn=None, cancels=stream_event)
218
+ predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio], api_name=API_NAME)
219
 
220
  if __name__ == '__main__':
221
  app.queue(api_open=API_OPEN).launch(show_api=API_OPEN, ssr_mode=True)