ngxson HF staff commited on
Commit
a72c43d
ยท
1 Parent(s): 18592dd
Files changed (3) hide show
  1. app.py +163 -0
  2. packages.txt +2 -0
  3. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ print(os.system('node --version')) # test
9
+
10
+ CHAR_LIMIT = 5000 # test
11
+
12
+ CUDA_AVAILABLE = torch.cuda.is_available()
13
+ models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
14
+ pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'ab'}
15
+ pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kหˆOkษ™ษนO'
16
+ pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kหˆQkษ™ษนQ'
17
+
18
+ @spaces.GPU(duration=30)
19
+ def forward_gpu(ps, ref_s, speed):
20
+ return models[True](ps, ref_s, speed)
21
+
22
+ def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
23
+ text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
24
+ pipeline = pipelines[voice[0]]
25
+ pack = pipeline.load_voice(voice)
26
+ use_gpu = use_gpu and CUDA_AVAILABLE
27
+ for _, ps, _ in pipeline(text, voice, speed):
28
+ ref_s = pack[len(ps)-1]
29
+ try:
30
+ if use_gpu:
31
+ audio = forward_gpu(ps, ref_s, speed)
32
+ else:
33
+ audio = models[False](ps, ref_s, speed)
34
+ except gr.exceptions.Error as e:
35
+ if use_gpu:
36
+ gr.Warning(str(e))
37
+ gr.Info('Retrying with CPU. To avoid this error, change Hardware to CPU.')
38
+ audio = models[False](ps, ref_s, speed)
39
+ else:
40
+ raise gr.Error(e)
41
+ return (24000, audio.numpy()), ps
42
+ return None, ''
43
+
44
+ # Arena API
45
+ def predict(text, voice='af_heart', speed=1):
46
+ return generate_first(text, voice, speed, use_gpu=False)[0]
47
+
48
+ def tokenize_first(text, voice='af_heart'):
49
+ pipeline = pipelines[voice[0]]
50
+ for _, ps, _ in pipeline(text, voice):
51
+ return ps
52
+ return ''
53
+
54
+ def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
55
+ text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
56
+ pipeline = pipelines[voice[0]]
57
+ pack = pipeline.load_voice(voice)
58
+ use_gpu = use_gpu and CUDA_AVAILABLE
59
+ first = True
60
+ for _, ps, _ in pipeline(text, voice, speed):
61
+ ref_s = pack[len(ps)-1]
62
+ try:
63
+ if use_gpu:
64
+ audio = forward_gpu(ps, ref_s, speed)
65
+ else:
66
+ audio = models[False](ps, ref_s, speed)
67
+ except gr.exceptions.Error as e:
68
+ if use_gpu:
69
+ gr.Warning(str(e))
70
+ gr.Info('Switching to CPU')
71
+ audio = models[False](ps, ref_s, speed)
72
+ else:
73
+ raise gr.Error(e)
74
+ yield 24000, audio.numpy()
75
+ if first:
76
+ first = False
77
+ yield 24000, torch.zeros(1).numpy()
78
+
79
+ CHOICES = {
80
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Heart โค๏ธ': 'af_heart',
81
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Bella ๐Ÿ”ฅ': 'af_bella',
82
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Nicole ๐ŸŽง': 'af_nicole',
83
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Aoede': 'af_aoede',
84
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Kore': 'af_kore',
85
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Sarah': 'af_sarah',
86
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Nova': 'af_nova',
87
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Sky': 'af_sky',
88
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Alloy': 'af_alloy',
89
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Jessica': 'af_jessica',
90
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ River': 'af_river',
91
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Michael': 'am_michael',
92
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Fenrir': 'am_fenrir',
93
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Puck': 'am_puck',
94
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Echo': 'am_echo',
95
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Eric': 'am_eric',
96
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Liam': 'am_liam',
97
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Onyx': 'am_onyx',
98
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Santa': 'am_santa',
99
+ '๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน Adam': 'am_adam',
100
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšบ Emma': 'bf_emma',
101
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšบ Isabella': 'bf_isabella',
102
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšบ Alice': 'bf_alice',
103
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšบ Lily': 'bf_lily',
104
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšน George': 'bm_george',
105
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšน Fable': 'bm_fable',
106
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšน Lewis': 'bm_lewis',
107
+ '๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšน Daniel': 'bm_daniel',
108
+ }
109
+ for v in CHOICES.values():
110
+ pipelines[v[0]].load_voice(v)
111
+
112
+ TOKEN_NOTE = '''
113
+ ๐Ÿ’ก Customize pronunciation with Markdown link syntax and /slashes/ like `[Kokoro](/kหˆOkษ™ษนO/)`
114
+
115
+ ๐Ÿ’ฌ To adjust intonation, try punctuation `;:,.!?โ€”โ€ฆ"()โ€œโ€` or stress `หˆ` and `หŒ`
116
+
117
+ โฌ‡๏ธ Lower stress `[1 level](-1)` or `[2 levels](-2)`
118
+
119
+ โฌ†๏ธ Raise stress 1 level `[or](+2)` 2 levels (only works on less stressed, usually short words)
120
+ '''
121
+
122
+ with gr.Blocks() as generate_tab:
123
+ out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
124
+ generate_btn = gr.Button('Generate', variant='primary')
125
+ with gr.Accordion('Output Tokens', open=True):
126
+ out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
127
+ tokenize_btn = gr.Button('Tokenize', variant='secondary')
128
+ gr.Markdown(TOKEN_NOTE)
129
+ predict_btn = gr.Button('Predict', variant='secondary', visible=False)
130
+
131
+ STREAM_NOTE = ['โš ๏ธ There is an unknown Gradio bug that might yield no audio the first time you click `Stream`.']
132
+ if CHAR_LIMIT is not None:
133
+ STREAM_NOTE.append(f'โœ‚๏ธ Each stream is capped at {CHAR_LIMIT} characters.')
134
+ STREAM_NOTE.append('๐Ÿš€ Want more characters? You can [use Kokoro directly](https://huggingface.co/hexgrad/Kokoro-82M#usage) or duplicate this space:')
135
+ STREAM_NOTE = '\n\n'.join(STREAM_NOTE)
136
+
137
+ with gr.Blocks() as stream_tab:
138
+ out_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
139
+ with gr.Row():
140
+ stream_btn = gr.Button('Stream', variant='primary')
141
+ stop_btn = gr.Button('Stop', variant='stop')
142
+ with gr.Accordion('Note', open=True):
143
+ gr.Markdown(STREAM_NOTE)
144
+ gr.DuplicateButton()
145
+
146
+ API_NAME = 'tts'
147
+
148
+ with gr.Blocks() as app:
149
+ with gr.Row():
150
+ with gr.Column():
151
+ 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")
152
+ voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
153
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
154
+ with gr.Column():
155
+ gr.TabbedInterface([generate_tab, stream_tab], ['Generate', 'Stream'])
156
+ generate_btn.click(fn=generate_first, inputs=[text, voice, speed], outputs=[out_audio, out_ps], api_name=API_NAME)
157
+ tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps], api_name=API_NAME)
158
+ stream_event = stream_btn.click(fn=generate_all, inputs=[text, voice, speed], outputs=[out_stream], api_name=API_NAME)
159
+ stop_btn.click(fn=None, cancels=stream_event)
160
+ predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio], api_name=API_NAME)
161
+
162
+ if __name__ == '__main__':
163
+ app.queue(api_open=True).launch(show_api=True, ssr_mode=True)
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ espeak-ng
2
+ nodejs
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ kokoro>=0.7.16