shukdevdatta123 commited on
Commit
d98f3c7
·
verified ·
1 Parent(s): 09fa377

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -144
app.py CHANGED
@@ -1,39 +1,25 @@
 
 
1
  import gradio as gr
2
- import openai
3
- from kokoro import KPipeline, KModel
4
- import random
5
  import os
 
6
  import torch
7
- import time
8
 
9
- # Set up the OpenAI API key (optional)
10
- openai.api_key = None # Will be set by the user through the UI
11
 
12
- # Check if GPU is available
13
  CUDA_AVAILABLE = torch.cuda.is_available()
14
-
15
- # Initialize the models and pipelines (for TTS)
16
- # Initialize the models and pipelines (for TTS)
17
  models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
18
-
19
- # Fixed the iteration and dictionary comprehension for pipelines
20
- pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in ['a', 'b', 'e', 'f', 'h', 'i', 'j', 'p', 'z']}
21
- # Load lexicon for specific languages
22
  pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkəɹO'
23
  pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkəɹQ'
24
 
25
- # Initialize random texts for generating sample text
26
- random_texts = {}
27
- for lang in ['en']:
28
- with open(f'{lang}.txt', 'r') as r:
29
- random_texts[lang] = [line.strip() for line in r]
30
-
31
- def get_random_text(voice):
32
- lang = dict(a='en', b='en')[voice[0]]
33
- return random.choice(random_texts[lang])
34
 
35
- # Generate function to create speech from text
36
  def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
 
37
  pipeline = pipelines[voice[0]]
38
  pack = pipeline.load_voice(voice)
39
  use_gpu = use_gpu and CUDA_AVAILABLE
@@ -54,23 +40,18 @@ def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
54
  return (24000, audio.numpy()), ps
55
  return None, ''
56
 
57
- # Translator function using OpenAI API
58
- def translate_to_english(api_key, text, lang_code):
59
- openai.api_key = api_key
60
- try:
61
- prompt = f"Translate the following text from {lang_code} to English: \n\n{text}"
62
- response = openai.ChatCompletion.create(
63
- model="gpt-4",
64
- messages=[{"role": "system", "content": "You are a helpful assistant that translates text."},
65
- {"role": "user", "content": prompt}]
66
- )
67
- translated_text = response['choices'][0]['message']['content'].strip()
68
- return translated_text
69
- except Exception as e:
70
- return f"Error: {str(e)}"
71
 
72
- def generate_audio_from_text(text, lang_code, voice, speed, use_gpu=True):
73
- pipeline = pipelines[lang_code]
 
 
 
 
 
 
74
  pack = pipeline.load_voice(voice)
75
  use_gpu = use_gpu and CUDA_AVAILABLE
76
  for _, ps, _ in pipeline(text, voice, speed):
@@ -87,114 +68,131 @@ def generate_audio_from_text(text, lang_code, voice, speed, use_gpu=True):
87
  audio = models[False](ps, ref_s, speed)
88
  else:
89
  raise gr.Error(e)
90
- return (24000, audio.numpy())
 
 
 
 
 
 
 
 
 
91
 
92
- # Define your available voices here in the CHOICES dictionary
93
  CHOICES = {
94
- 'af_heart': '🇺🇸 🚺 Heart ❤️',
95
- 'af_bella': '🇺🇸 🚺 Bella 🔥',
96
- 'af_nicole': '🇺🇸 🚺 Nicole 🎧',
97
- 'af_aoede': '🇺🇸 🚺 Aoede',
98
- 'af_kore': '🇺🇸 🚺 Kore',
99
- 'af_sarah': '🇺🇸 🚺 Sarah',
100
- 'af_nova': '🇺🇸 🚺 Nova',
101
- 'af_sky': '🇺🇸 🚺 Sky',
102
- 'af_alloy': '🇺🇸 🚺 Alloy',
103
- 'af_jessica': '🇺🇸 🚺 Jessica',
104
- 'af_river': '🇺🇸 🚺 River',
105
-
106
- 'am_michael': '🇺🇸 🚹 Michael',
107
- 'am_fenrir': '🇺🇸 🚹 Fenrir',
108
- 'am_puck': '🇺🇸 🚹 Puck',
109
- 'am_echo': '🇺🇸 🚹 Echo',
110
- 'am_eric': '🇺🇸 🚹 Eric',
111
- 'am_liam': '🇺🇸 🚹 Liam',
112
- 'am_onyx': '🇺🇸 🚹 Onyx',
113
- 'am_santa': '🇺🇸 🚹 Santa',
114
- 'am_adam': '🇺🇸 🚹 Adam',
115
-
116
- 'bf_emma': '🇬🇧 🚺 Emma',
117
- 'bf_isabella': '🇬🇧 🚺 Isabella',
118
- 'bf_alice': '🇬🇧 🚺 Alice',
119
- 'bf_lily': '🇬🇧 🚺 Lily',
120
-
121
- 'bm_george': '🇬🇧 🚹 George',
122
- 'bm_fable': '🇬🇧 🚹 Fable',
123
- 'bm_lewis': '🇬🇧 🚹 Lewis',
124
- 'bm_daniel': '🇬🇧 🚹 Daniel',
125
-
126
- 'ef_dora': '🇪🇸 🚺 Dora',
127
-
128
- 'em_alex': '🇪🇸 🚹 Alex',
129
- 'em_santa': '🇪🇸 🚹 Santa',
130
-
131
- 'ff_siwis': '🇫🇷 🚺 Siwis',
132
-
133
- 'hf_alpha': '🇮🇳 🚹 Alpha',
134
- 'hf_beta': '🇮🇳 🚹 Beta',
135
-
136
- 'hm_omega': '🇮🇳 🚹 Omega',
137
- 'hm_psi': '🇮🇳 🚹 Psi',
138
-
139
- 'if_sara': '🇮🇹 🚺 Sara',
140
-
141
- 'im_nicola': '🇮🇹 🚺 Nicola',
142
-
143
- 'jf_alpha': '🇯🇵 🚹 Alpha',
144
- 'jf_gongitsune': '🇯🇵 🚹 Gongitsune',
145
- 'jf_nezumi': '🇯🇵 🚹 Nezumi',
146
- 'jf_tebukuro': '🇯🇵 🚹 Tebukuro',
147
-
148
- 'jm_kumo': '🇯🇵 🚹 Kumo',
149
-
150
- 'pf_dora': '🇧🇷 🚺 Dora',
151
-
152
- 'pm_alex': '🇧🇷 🚹 Alex',
153
- 'pm_santa': '🇧🇷 🚹 Santa',
154
-
155
- 'zf_xiaobei': '🇨🇳 🚺 Xiaobei',
156
- 'zf_xiaoni': '🇨🇳 🚺 Xiaoni',
157
- 'zf_xiaoxiao': '🇨🇳 🚺 Xiaoxiao',
158
- 'zf_xiaoyi': '🇨🇳 🚺 Xiaoyi',
159
-
160
- 'zm_yunjian': '🇨🇳 🚹 Yunjian',
161
- 'zm_yunxi': '🇨🇳 🚹 Yunxi',
162
- 'zm_yunxia': '🇨🇳 🚹 Yunxia',
163
- 'zm_yunyang': '🇨🇳 🚹 Yunyang'
164
  }
165
-
166
- # Gradio interface setup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  with gr.Blocks() as app:
168
- gr.Markdown("### Kokoro Text-to-Speech with Translation")
 
169
  with gr.Row():
170
  with gr.Column():
171
- # Input for text and language settings
172
- input_text = gr.Textbox(label="Enter Text", placeholder="Type your text here...")
173
- voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice')
174
- use_gpu = gr.Checkbox(label="Use GPU", value=CUDA_AVAILABLE)
175
- speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label="Speed")
176
- openai_api_key = gr.Textbox(label="Enter OpenAI API Key (for translation)", type="password")
177
- random_btn = gr.Button("Random Text")
178
-
 
 
 
 
179
  with gr.Column():
180
- out_audio = gr.Audio(label="Generated Audio", interactive=False, autoplay=True)
181
- out_text = gr.Textbox(label="Generated Audio Tokens", interactive=False)
182
- generate_btn = gr.Button("Generate Audio")
183
- translate_btn = gr.Button("Translate and Generate Audio")
184
-
185
- random_btn.click(fn=get_random_text, inputs=[voice], outputs=[input_text])
186
-
187
- def handle_translation(text, api_key, lang_code, voice, speed, use_gpu):
188
- translated_text = translate_to_english(api_key, text, lang_code)
189
- translated_audio = generate_audio_from_text(translated_text, 'a', voice, speed, use_gpu)
190
- return translated_audio, translated_text
191
-
192
- translate_btn.click(fn=handle_translation, inputs=[input_text, openai_api_key, voice, speed, use_gpu], outputs=[out_audio, out_text])
193
-
194
- def generate_and_play(text, voice, speed, use_gpu):
195
- audio, tokens = generate_first(text, voice, speed, use_gpu)
196
- return audio, tokens
197
-
198
- generate_btn.click(fn=generate_and_play, inputs=[input_text, voice, speed, use_gpu], outputs=[out_audio, out_text])
199
-
200
- app.launch()
 
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 'abefhijpz'}
 
 
 
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=10)
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
 
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
+ # Split the input text into words and return as a list of words (fix applied here)
49
+ words = text.split() # This splits the text into words based on spaces
50
+ return words # Return a list of words
51
+
52
+ def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
53
+ text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
54
+ pipeline = pipelines[voice[0]]
55
  pack = pipeline.load_voice(voice)
56
  use_gpu = use_gpu and CUDA_AVAILABLE
57
  for _, ps, _ in pipeline(text, voice, speed):
 
68
  audio = models[False](ps, ref_s, speed)
69
  else:
70
  raise gr.Error(e)
71
+ yield 24000, audio.numpy()
72
+
73
+ random_texts = {}
74
+ for lang in ['en']:
75
+ with open(f'{lang}.txt', 'r') as r:
76
+ random_texts[lang] = [line.strip() for line in r]
77
+
78
+ def get_random_text(voice):
79
+ lang = dict(a='en', b='en')[voice[0]]
80
+ return random.choice(random_texts[lang])
81
 
 
82
  CHOICES = {
83
+ '🇺🇸 🚺 Heart ❤️': 'af_heart',
84
+ '🇺🇸 🚺 Bella 🔥': 'af_bella',
85
+ '🇺🇸 🚺 Nicole 🎧': 'af_nicole',
86
+ '🇺🇸 🚺 Aoede': 'af_aoede',
87
+ '🇺🇸 🚺 Kore': 'af_kore',
88
+ '🇺🇸 🚺 Sarah': 'af_sarah',
89
+ '🇺🇸 🚺 Nova': 'af_nova',
90
+ '🇺🇸 🚺 Sky': 'af_sky',
91
+ '🇺🇸 🚺 Alloy': 'af_alloy',
92
+ '🇺🇸 🚺 Jessica': 'af_jessica',
93
+ '🇺🇸 🚺 River': 'af_river',
94
+
95
+ '🇺🇸 🚹 Michael': 'am_michael',
96
+ '🇺🇸 🚹 Fenrir': 'am_fenrir',
97
+ '🇺🇸 🚹 Puck': 'am_puck',
98
+ '🇺🇸 🚹 Echo': 'am_echo',
99
+ '🇺🇸 🚹 Eric': 'am_eric',
100
+ '🇺🇸 🚹 Liam': 'am_liam',
101
+ '🇺🇸 🚹 Onyx': 'am_onyx',
102
+ '🇺🇸 🚹 Santa': 'am_santa',
103
+ '🇺🇸 🚹 Adam': 'am_adam',
104
+
105
+ '🇬🇧 🚺 Emma': 'bf_emma',
106
+ '🇬🇧 🚺 Isabella': 'bf_isabella',
107
+ '🇬🇧 🚺 Alice': 'bf_alice',
108
+ '🇬🇧 🚺 Lily': 'bf_lily',
109
+
110
+ '🇬🇧 🚹 George': 'bm_george',
111
+ '🇬🇧 🚹 Fable': 'bm_fable',
112
+ '🇬🇧 🚹 Lewis': 'bm_lewis',
113
+ '🇬🇧 🚹 Daniel': 'bm_daniel',
114
+
115
+ '🇪🇸 🚺 Dora': 'ef_dora',
116
+
117
+ '🇪🇸 🚹 Alex': 'em_alex',
118
+ '🇪🇸 🚹 Santa': 'em_santa',
119
+
120
+ '🇫🇷 🚺 Siwis': 'ff_siwis',
121
+
122
+ '🇮🇳 🚹 Alpha': 'hf_alpha',
123
+ '🇮🇳 🚹 Beta': 'hf_beta',
124
+
125
+ '🇮🇳 🚹 Omega': 'hm_omega',
126
+ '🇮🇳 🚹 Psi': 'hm_psi',
127
+
128
+ '🇮🇹 🚺 Sara': 'if_sara',
129
+
130
+ '🇮🇹 🚺 Nicola': 'im_nicola',
131
+
132
+ '🇯🇵 🚹 Alpha': 'jf_alpha',
133
+ '🇯🇵 🚹 Gongitsune': 'jf_gongitsune',
134
+ '🇯🇵 🚹 Nezumi': 'jf_nezumi',
135
+ '🇯🇵 🚹 Tebukuro': 'jf_tebukuro',
136
+
137
+ '🇯🇵 🚹 Kumo': 'jm_kumo',
138
+
139
+ '🇧🇷 🚺 Dora': 'pf_dora',
140
+
141
+ '🇧🇷 🚹 Alex': 'pm_alex',
142
+ '🇧🇷 🚹 Santa': 'pm_santa',
143
+
144
+ '🇨🇳 🚺 Xiaobei': 'zf_xiaobei',
145
+ '🇨🇳 🚺 Xiaoni': 'zf_xiaoni',
146
+ '🇨🇳 🚺 Xiaoxiao': 'zf_xiaoxiao',
147
+ '🇨🇳 🚺 Xiaoyi': 'zf_xiaoyi',
148
+
149
+ '🇨🇳 🚹 Yunjian': 'zm_yunjian',
150
+ '🇨🇳 🚹 Yunxi': 'zm_yunxi',
151
+ '🇨🇳 🚹 Yunxia': 'zm_yunxia',
152
+ '🇨🇳 🚹 Yunyang': 'zm_yunyang',
153
  }
154
+ for v in CHOICES.values():
155
+ pipelines[v[0]].load_voice(v)
156
+
157
+ with gr.Blocks() as generate_tab:
158
+ out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
159
+ generate_btn = gr.Button('Generate', variant='primary')
160
+ with gr.Accordion('Output Tokens', open=True):
161
+ out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
162
+ tokenize_btn = gr.Button('Tokenize', variant='secondary')
163
+ predict_btn = gr.Button('Predict', variant='secondary', visible=False)
164
+
165
+ BANNER_TEXT = '''
166
+ [***Kokoro*** **is an open-weight TTS model with 82 million parameters.**](https://huggingface.co/hexgrad/Kokoro-82M)
167
+ 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.
168
+ This demo only showcases English, but you can directly use the model to access other languages.
169
+ '''
170
+
171
+ API_OPEN = os.getenv('SPACE_ID') != 'hexgrad/Kokoro-TTS'
172
+ API_NAME = None if API_OPEN else False
173
  with gr.Blocks() as app:
174
+ with gr.Row():
175
+ gr.Markdown(BANNER_TEXT, container=True)
176
  with gr.Row():
177
  with gr.Column():
178
+ 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")
179
+ with gr.Row():
180
+ voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
181
+ use_gpu = gr.Dropdown(
182
+ [('ZeroGPU 🚀', True), ('CPU 🐌', False)],
183
+ value=CUDA_AVAILABLE,
184
+ label='Hardware',
185
+ info='GPU is usually faster, but has a usage quota',
186
+ interactive=CUDA_AVAILABLE
187
+ )
188
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
189
+ random_btn = gr.Button('Random Text', variant='secondary')
190
  with gr.Column():
191
+ gr.TabbedInterface([generate_tab], ['Generate'])
192
+ random_btn.click(fn=get_random_text, inputs=[voice], outputs=[text], api_name=API_NAME)
193
+ generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu], outputs=[out_audio, out_ps], api_name=API_NAME)
194
+ tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps], api_name=API_NAME)
195
+ predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio], api_name=API_NAME)
196
+
197
+ if __name__ == '__main__':
198
+ app.queue(api_open=API_OPEN).launch(show_api=API_OPEN, ssr_mode=True)