deno34 commited on
Commit
3f66278
Β·
verified Β·
1 Parent(s): 54a65b1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ from kokoro import KModel, KPipeline
3
+ import gradio as gr
4
+ import os
5
+ import random
6
+ import torch
7
+
8
+ IS_DUPLICATE = not os.getenv('SPACE_ID', '').startswith('hexgrad/')
9
+ CHAR_LIMIT = None if IS_DUPLICATE else 5000
10
+
11
+ CUDA_AVAILABLE = torch.cuda.is_available()
12
+ models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
13
+ pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'ab'}
14
+ pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkΙ™ΙΉO'
15
+ pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkΙ™ΙΉQ'
16
+
17
+ @spaces.GPU(duration=30)
18
+ def forward_gpu(ps, ref_s, speed):
19
+ return models[True](ps, ref_s, speed)
20
+
21
+ def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
22
+ text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
23
+ pipeline = pipelines[voice[0]]
24
+ pack = pipeline.load_voice(voice)
25
+ use_gpu = use_gpu and CUDA_AVAILABLE
26
+ for _, ps, _ in pipeline(text, voice, speed):
27
+ ref_s = pack[len(ps)-1]
28
+ try:
29
+ if use_gpu:
30
+ audio = forward_gpu(ps, ref_s, speed)
31
+ else:
32
+ audio = models[False](ps, ref_s, speed)
33
+ except gr.exceptions.Error as e:
34
+ if use_gpu:
35
+ gr.Warning(str(e))
36
+ gr.Info('Retrying with CPU. To avoid this error, change Hardware to CPU.')
37
+ audio = models[False](ps, ref_s, speed)
38
+ else:
39
+ raise gr.Error(e)
40
+ return (24000, audio.numpy()), ps
41
+ return None, ''
42
+
43
+ # Arena API
44
+ def predict(text, voice='af_heart', speed=1):
45
+ return generate_first(text, voice, speed, use_gpu=False)[0]
46
+
47
+ def tokenize_first(text, voice='af_heart'):
48
+ pipeline = pipelines[voice[0]]
49
+ for _, ps, _ in pipeline(text, voice):
50
+ return ps
51
+ return ''
52
+
53
+ def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
54
+ text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
55
+ pipeline = pipelines[voice[0]]
56
+ pack = pipeline.load_voice(voice)
57
+ use_gpu = use_gpu and CUDA_AVAILABLE
58
+ first = True
59
+ for _, ps, _ in pipeline(text, voice, speed):
60
+ ref_s = pack[len(ps)-1]
61
+ try:
62
+ if use_gpu:
63
+ audio = forward_gpu(ps, ref_s, speed)
64
+ else:
65
+ audio = models[False](ps, ref_s, speed)
66
+ except gr.exceptions.Error as e:
67
+ if use_gpu:
68
+ gr.Warning(str(e))
69
+ gr.Info('Switching to CPU')
70
+ audio = models[False](ps, ref_s, speed)
71
+ else:
72
+ raise gr.Error(e)
73
+ yield 24000, audio.numpy()
74
+ if first:
75
+ first = False
76
+ yield 24000, torch.zeros(1).numpy()
77
+
78
+ with open('en.txt', 'r') as r:
79
+ random_quotes = [line.strip() for line in r]
80
+
81
+ def get_random_quote():
82
+ return random.choice(random_quotes)
83
+
84
+ def get_gatsby():
85
+ with open('gatsby5k.md', 'r') as r:
86
+ return r.read().strip()
87
+
88
+ def get_frankenstein():
89
+ with open('frankenstein5k.md', 'r') as r:
90
+ return r.read().strip()
91
+
92
+ CHOICES = {
93
+ 'πŸ‡ΊπŸ‡Έ 🚺 Heart ❀️': 'af_heart',
94
+ 'πŸ‡ΊπŸ‡Έ 🚺 Bella πŸ”₯': 'af_bella',
95
+ 'πŸ‡ΊπŸ‡Έ 🚺 Nicole 🎧': 'af_nicole',
96
+ 'πŸ‡ΊπŸ‡Έ 🚺 Aoede': 'af_aoede',
97
+ 'πŸ‡ΊπŸ‡Έ 🚺 Kore': 'af_kore',
98
+ 'πŸ‡ΊπŸ‡Έ 🚺 Sarah': 'af_sarah',
99
+ 'πŸ‡ΊπŸ‡Έ 🚺 Nova': 'af_nova',
100
+ 'πŸ‡ΊπŸ‡Έ 🚺 Sky': 'af_sky',
101
+ 'πŸ‡ΊπŸ‡Έ 🚺 Alloy': 'af_alloy',
102
+ 'πŸ‡ΊπŸ‡Έ 🚺 Jessica': 'af_jessica',
103
+ 'πŸ‡ΊπŸ‡Έ 🚺 River': 'af_river',
104
+ 'πŸ‡ΊπŸ‡Έ 🚹 Michael': 'am_michael',
105
+ 'πŸ‡ΊπŸ‡Έ 🚹 Fenrir': 'am_fenrir',
106
+ 'πŸ‡ΊπŸ‡Έ 🚹 Puck': 'am_puck',
107
+ 'πŸ‡ΊπŸ‡Έ 🚹 Echo': 'am_echo',
108
+ 'πŸ‡ΊπŸ‡Έ 🚹 Eric': 'am_eric',
109
+ 'πŸ‡ΊπŸ‡Έ 🚹 Liam': 'am_liam',
110
+ 'πŸ‡ΊπŸ‡Έ 🚹 Onyx': 'am_onyx',
111
+ 'πŸ‡ΊπŸ‡Έ 🚹 Santa': 'am_santa',
112
+ 'πŸ‡ΊπŸ‡Έ 🚹 Adam': 'am_adam',
113
+ 'πŸ‡¬πŸ‡§ 🚺 Emma': 'bf_emma',
114
+ 'πŸ‡¬πŸ‡§ 🚺 Isabella': 'bf_isabella',
115
+ 'πŸ‡¬πŸ‡§ 🚺 Alice': 'bf_alice',
116
+ 'πŸ‡¬πŸ‡§ 🚺 Lily': 'bf_lily',
117
+ 'πŸ‡¬πŸ‡§ 🚹 George': 'bm_george',
118
+ 'πŸ‡¬πŸ‡§ 🚹 Fable': 'bm_fable',
119
+ 'πŸ‡¬πŸ‡§ 🚹 Lewis': 'bm_lewis',
120
+ 'πŸ‡¬πŸ‡§ 🚹 Daniel': 'bm_daniel',
121
+ }
122
+ for v in CHOICES.values():
123
+ pipelines[v[0]].load_voice(v)
124
+
125
+ TOKEN_NOTE = '''
126
+ πŸ’‘ Customize pronunciation with Markdown link syntax and /slashes/ like `[Kokoro](/kˈOkΙ™ΙΉO/)`
127
+ πŸ’¬ To adjust intonation, try punctuation `;:,.!?—…"()β€œβ€` or stress `ˈ` and `ˌ`
128
+ ⬇️ Lower stress `[1 level](-1)` or `[2 levels](-2)`
129
+ ⬆️ Raise stress 1 level `[or](+2)` 2 levels (only works on less stressed, usually short words)
130
+ '''
131
+
132
+ with gr.Blocks() as generate_tab:
133
+ out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
134
+ generate_btn = gr.Button('Generate', variant='primary')
135
+ with gr.Accordion('Output Tokens', open=True):
136
+ out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
137
+ tokenize_btn = gr.Button('Tokenize', variant='secondary')
138
+ gr.Markdown(TOKEN_NOTE)
139
+ predict_btn = gr.Button('Predict', variant='secondary', visible=False)
140
+
141
+ STREAM_NOTE = ['⚠️ There is an unknown Gradio bug that might yield no audio the first time you click `Stream`.']
142
+ if CHAR_LIMIT is not None:
143
+ STREAM_NOTE.append(f'βœ‚οΈ Each stream is capped at {CHAR_LIMIT} characters.')
144
+ STREAM_NOTE.append('πŸš€ Want more characters? You can [use Kokoro directly](https://huggingface.co/hexgrad/Kokoro-82M#usage) or duplicate this space:')
145
+ STREAM_NOTE = '\n\n'.join(STREAM_NOTE)
146
+
147
+ with gr.Blocks() as stream_tab:
148
+ out_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
149
+ with gr.Row():
150
+ stream_btn = gr.Button('Stream', variant='primary')
151
+ stop_btn = gr.Button('Stop', variant='stop')
152
+ with gr.Accordion('Note', open=True):
153
+ gr.Markdown(STREAM_NOTE)
154
+ gr.DuplicateButton()
155
+
156
+ BANNER_TEXT = '''
157
+ [***Kokoro*** **is an open-weight TTS model with 82 million parameters.**](https://huggingface.co/hexgrad/Kokoro-82M)
158
+ As of January 31st, 2025, Kokoro was the most-liked [**TTS model**](https://huggingface.co/models?pipeline_tag=text-to-speech&sort=likes) and the most-liked [**TTS space**](https://huggingface.co/spaces?sort=likes&search=tts) on Hugging Face.
159
+ This demo only showcases English, but you can directly use the model to access other languages.
160
+ '''
161
+ API_OPEN = os.getenv('SPACE_ID') != 'hexgrad/Kokoro-TTS'
162
+ API_NAME = None if API_OPEN else False
163
+ with gr.Blocks() as app:
164
+ with gr.Row():
165
+ gr.Markdown(BANNER_TEXT, container=True)
166
+ with gr.Row():
167
+ with gr.Column():
168
+ 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")
169
+ with gr.Row():
170
+ voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
171
+ use_gpu = gr.Dropdown(
172
+ [('ZeroGPU πŸš€', True), ('CPU 🐌', False)],
173
+ value=CUDA_AVAILABLE,
174
+ label='Hardware',
175
+ info='GPU is usually faster, but has a usage quota',
176
+ interactive=CUDA_AVAILABLE
177
+ )
178
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
179
+ random_btn = gr.Button('🎲 Random Quote πŸ’¬', variant='secondary')
180
+ with gr.Row():
181
+ gatsby_btn = gr.Button('πŸ₯‚ Gatsby πŸ“•', variant='secondary')
182
+ frankenstein_btn = gr.Button('πŸ’€ Frankenstein πŸ“—', variant='secondary')
183
+ with gr.Column():
184
+ gr.TabbedInterface([generate_tab, stream_tab], ['Generate', 'Stream'])
185
+ random_btn.click(fn=get_random_quote, inputs=[], outputs=[text], api_name=API_NAME)
186
+ gatsby_btn.click(fn=get_gatsby, inputs=[], outputs=[text], api_name=API_NAME)
187
+ frankenstein_btn.click(fn=get_frankenstein, inputs=[], outputs=[text], api_name=API_NAME)
188
+ generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu], outputs=[out_audio, out_ps], api_name=API_NAME)
189
+ tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps], api_name=API_NAME)
190
+ stream_event = stream_btn.click(fn=generate_all, inputs=[text, voice, speed, use_gpu], outputs=[out_stream], api_name=API_NAME)
191
+ stop_btn.click(fn=None, cancels=stream_event)
192
+ predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio], api_name=API_NAME)
193
+
194
+ if __name__ == '__main__':
195
+ app.queue(api_open=API_OPEN).launch(show_api=API_OPEN, ssr_mode=True)