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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -82
app.py CHANGED
@@ -13,18 +13,114 @@ if not IS_DUPLICATE:
13
  print('DEBUG', kokoro.__version__, CUDA_AVAILABLE, misaki.__version__)
14
 
15
  CHAR_LIMIT = None if IS_DUPLICATE else 5000
 
 
16
  models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
17
- pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'ab'}
18
- pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkəɹO'
19
- pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkəɹQ'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @spaces.GPU(duration=30)
22
  def forward_gpu(ps, ref_s, speed):
23
  return models[True](ps, ref_s, speed)
24
 
25
- def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
26
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
27
- pipeline = pipelines[voice[0]]
28
  pack = pipeline.load_voice(voice)
29
  use_gpu = use_gpu and CUDA_AVAILABLE
30
  for _, ps, _ in pipeline(text, voice, speed):
@@ -37,26 +133,22 @@ def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
37
  except gr.exceptions.Error as e:
38
  if use_gpu:
39
  gr.Warning(str(e))
40
- gr.Info('Retrying with CPU. To avoid this error, change Hardware to CPU.')
41
  audio = models[False](ps, ref_s, speed)
42
  else:
43
  raise gr.Error(e)
44
  return (24000, audio.numpy()), ps
45
  return None, ''
46
 
47
- # Arena API
48
- def predict(text, voice='af_heart', speed=1):
49
- return generate_first(text, voice, speed, use_gpu=False)[0]
50
-
51
- def tokenize_first(text, voice='af_heart'):
52
- pipeline = pipelines[voice[0]]
53
  for _, ps, _ in pipeline(text, voice):
54
  return ps
55
  return ''
56
 
57
- def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
58
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
59
- pipeline = pipelines[voice[0]]
60
  pack = pipeline.load_voice(voice)
61
  use_gpu = use_gpu and CUDA_AVAILABLE
62
  first = True
@@ -93,39 +185,7 @@ def get_frankenstein():
93
  with open('frankenstein5k.md', 'r') as r:
94
  return r.read().strip()
95
 
96
- CHOICES = {
97
- '🇺🇸 🚺 Heart ❤️': 'af_heart',
98
- '🇺🇸 🚺 Bella 🔥': 'af_bella',
99
- '🇺🇸 🚺 Nicole 🎧': 'af_nicole',
100
- '🇺🇸 🚺 Aoede': 'af_aoede',
101
- '🇺🇸 🚺 Kore': 'af_kore',
102
- '🇺🇸 🚺 Sarah': 'af_sarah',
103
- '🇺🇸 🚺 Nova': 'af_nova',
104
- '🇺🇸 🚺 Sky': 'af_sky',
105
- '🇺🇸 🚺 Alloy': 'af_alloy',
106
- '🇺🇸 🚺 Jessica': 'af_jessica',
107
- '🇺🇸 🚺 River': 'af_river',
108
- '🇺🇸 🚹 Michael': 'am_michael',
109
- '🇺🇸 🚹 Fenrir': 'am_fenrir',
110
- '🇺🇸 🚹 Puck': 'am_puck',
111
- '🇺🇸 🚹 Echo': 'am_echo',
112
- '🇺🇸 🚹 Eric': 'am_eric',
113
- '🇺🇸 🚹 Liam': 'am_liam',
114
- '🇺🇸 🚹 Onyx': 'am_onyx',
115
- '🇺🇸 🚹 Santa': 'am_santa',
116
- '🇺🇸 🚹 Adam': 'am_adam',
117
- '🇬🇧 🚺 Emma': 'bf_emma',
118
- '🇬🇧 🚺 Isabella': 'bf_isabella',
119
- '🇬🇧 🚺 Alice': 'bf_alice',
120
- '🇬🇧 🚺 Lily': 'bf_lily',
121
- '🇬🇧 🚹 George': 'bm_george',
122
- '🇬🇧 🚹 Fable': 'bm_fable',
123
- '🇬🇧 🚹 Lewis': 'bm_lewis',
124
- '🇬🇧 🚹 Daniel': 'bm_daniel',
125
- }
126
- for v in CHOICES.values():
127
- pipelines[v[0]].load_voice(v)
128
-
129
  TOKEN_NOTE = '''
130
  💡 Customize pronunciation with Markdown link syntax and /slashes/ like `[Kokoro](/kˈOkəɹO/)`
131
 
@@ -140,31 +200,22 @@ with gr.Blocks() as generate_tab:
140
  out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
141
  generate_btn = gr.Button('Generate', variant='primary')
142
  with gr.Accordion('Output Tokens', open=True):
143
- out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
144
  tokenize_btn = gr.Button('Tokenize', variant='secondary')
145
  gr.Markdown(TOKEN_NOTE)
146
  predict_btn = gr.Button('Predict', variant='secondary', visible=False)
147
 
148
- STREAM_NOTE = ['⚠️ There is an unknown Gradio bug that might yield no audio the first time you click `Stream`.']
149
- if CHAR_LIMIT is not None:
150
- STREAM_NOTE.append(f'✂️ Each stream is capped at {CHAR_LIMIT} characters.')
151
- STREAM_NOTE.append('🚀 Want more characters? You can [use Kokoro directly](https://huggingface.co/hexgrad/Kokoro-82M#usage) or duplicate this space:')
152
- STREAM_NOTE = '\n\n'.join(STREAM_NOTE)
153
-
154
  with gr.Blocks() as stream_tab:
155
  out_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
156
  with gr.Row():
157
  stream_btn = gr.Button('Stream', variant='primary')
158
  stop_btn = gr.Button('Stop', variant='stop')
159
- with gr.Accordion('Note', open=True):
160
- gr.Markdown(STREAM_NOTE)
161
- gr.DuplicateButton()
162
 
163
  BANNER_TEXT = '''
164
- [***Kokoro*** **is an open-weight TTS model with 82 million parameters.**](https://huggingface.co/hexgrad/Kokoro-82M)
165
-
166
- This demo only showcases English, but you can directly use the model to access other languages.
167
  '''
 
168
  API_OPEN = os.getenv('SPACE_ID') != 'hexgrad/Kokoro-TTS'
169
  API_NAME = None if API_OPEN else False
170
  with gr.Blocks() as app:
@@ -172,31 +223,42 @@ with gr.Blocks() as app:
172
  gr.Markdown(BANNER_TEXT, container=True)
173
  with gr.Row():
174
  with gr.Column():
175
- 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")
176
- with gr.Row():
177
- voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
178
- use_gpu = gr.Dropdown(
179
- [('ZeroGPU 🚀', True), ('CPU 🐌', False)],
180
- value=CUDA_AVAILABLE,
181
- label='Hardware',
182
- info='GPU is usually faster, but has a usage quota',
183
- interactive=CUDA_AVAILABLE
184
- )
185
- speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
186
- random_btn = gr.Button('🎲 Random Quote 💬', variant='secondary')
187
- with gr.Row():
188
- gatsby_btn = gr.Button('🥂 Gatsby 📕', variant='secondary')
189
- frankenstein_btn = gr.Button('💀 Frankenstein 📗', variant='secondary')
 
 
 
 
 
 
 
 
190
  with gr.Column():
191
  gr.TabbedInterface([generate_tab, stream_tab], ['Generate', 'Stream'])
192
- random_btn.click(fn=get_random_quote, inputs=[], outputs=[text], api_name=API_NAME)
193
- gatsby_btn.click(fn=get_gatsby, inputs=[], outputs=[text], api_name=API_NAME)
194
- frankenstein_btn.click(fn=get_frankenstein, inputs=[], outputs=[text], api_name=API_NAME)
195
- generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu], outputs=[out_audio, out_ps], api_name=API_NAME)
196
- tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps], api_name=API_NAME)
197
- stream_event = stream_btn.click(fn=generate_all, inputs=[text, voice, speed, use_gpu], outputs=[out_stream], api_name=API_NAME)
 
 
 
 
198
  stop_btn.click(fn=None, cancels=stream_event)
199
- predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio], api_name=API_NAME)
200
 
201
  if __name__ == '__main__':
202
  app.queue(api_open=API_OPEN).launch(show_api=API_OPEN, ssr_mode=True)
 
13
  print('DEBUG', kokoro.__version__, CUDA_AVAILABLE, misaki.__version__)
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
  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
  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
  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
  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)