File size: 8,356 Bytes
d98f3c7 e9b69d2 9cc0dc7 d98f3c7 e9b69d2 8d0ba45 41b5e7a 8d0ba45 d98f3c7 e9b69d2 8d0ba45 d989475 8d0ba45 41b5e7a d98f3c7 41b5e7a d989475 8d0ba45 d98f3c7 9afcf62 8d0ba45 e8c4059 d98f3c7 41b5e7a d989475 41b5e7a 8d0ba45 d98f3c7 8d0ba45 d98f3c7 e9b69d2 8d0ba45 da8e3d2 8d0ba45 da8e3d2 8d0ba45 d98f3c7 8d0ba45 d98f3c7 8d0ba45 d98f3c7 8d0ba45 9afcf62 d98f3c7 8d0ba45 9afcf62 d98f3c7 9afcf62 8d0ba45 d98f3c7 8d0ba45 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
import spaces
from kokoro import KModel, KPipeline
import gradio as gr
import os
import random
import torch
import openai
# Check if running in a duplicate space
IS_DUPLICATE = not os.getenv('SPACE_ID', '').startswith('hexgrad/')
CHAR_LIMIT = None if IS_DUPLICATE else 5000
# Check if CUDA is available
CUDA_AVAILABLE = torch.cuda.is_available()
# Load the models (GPU and CPU versions)
models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'abefhijpz'}
pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkəɹO'
pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkəɹQ'
# GPU function to generate audio
@spaces.GPU(duration=10)
def forward_gpu(ps, ref_s, speed):
return models[True](ps, ref_s, speed)
# Function to generate first output
def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
pipeline = pipelines[voice[0]]
pack = pipeline.load_voice(voice)
use_gpu = use_gpu and CUDA_AVAILABLE
for _, ps, _ in pipeline(text, voice, speed):
ref_s = pack[len(ps)-1]
try:
if use_gpu:
audio = forward_gpu(ps, ref_s, speed)
else:
audio = models[False](ps, ref_s, speed)
except gr.exceptions.Error as e:
if use_gpu:
gr.Warning(str(e))
gr.Info('Retrying with CPU. To avoid this error, change Hardware to CPU.')
audio = models[False](ps, ref_s, speed)
else:
raise gr.Error(e)
return (24000, audio.numpy()), ps
return None, ''
# Function to tokenize first
def tokenize_first(text, voice='af_heart'):
words = text.split() # This splits the text into words based on spaces
return words # Return a list of words
# Function to get random text for the "Random Text" button
random_texts = {}
for lang in ['en']:
with open(f'{lang}.txt', 'r') as r:
random_texts[lang] = [line.strip() for line in r]
def get_random_text(voice):
lang = dict(a='en', b='en')[voice[0]]
return random.choice(random_texts[lang])
# OpenAI GPT-4 translation function
def translate_to_english(text, model="gpt-4"):
try:
response = openai.Completion.create(
model=model,
prompt=f"Translate the following text to English:\n\n{text}",
temperature=0.5,
max_tokens=500,
)
return response.choices[0].text.strip()
except Exception as e:
return str(e)
# Function to handle generation for translated text
def translate_and_generate(text, voice, speed):
translated_text = translate_to_english(text)
audio, tokens = generate_first(translated_text, voice, speed, use_gpu=CUDA_AVAILABLE)
return audio, tokens, translated_text
# Predefined voices for the dropdown menu
CHOICES = {
'🇺🇸 🚺 Heart ❤️': 'af_heart',
'🇺🇸 🚺 Bella 🔥': 'af_bella',
'🇺🇸 🚺 Nicole 🎧': 'af_nicole',
'🇺🇸 🚺 Aoede': 'af_aoede',
'🇺🇸 🚺 Kore': 'af_kore',
'🇺🇸 🚺 Sarah': 'af_sarah',
'🇺🇸 🚺 Nova': 'af_nova',
'🇺🇸 🚺 Sky': 'af_sky',
'🇺🇸 🚺 Alloy': 'af_alloy',
'🇺🇸 🚺 Jessica': 'af_jessica',
'🇺🇸 🚺 River': 'af_river',
'🇺🇸 🚹 Michael': 'am_michael',
'🇺🇸 🚹 Fenrir': 'am_fenrir',
'🇺🇸 🚹 Puck': 'am_puck',
'🇺🇸 🚹 Echo': 'am_echo',
'🇺🇸 🚹 Eric': 'am_eric',
'🇺🇸 🚹 Liam': 'am_liam',
'🇺🇸 🚹 Onyx': 'am_onyx',
'🇺🇸 🚹 Santa': 'am_santa',
'🇺🇸 🚹 Adam': 'am_adam',
'🇬🇧 🚺 Emma': 'bf_emma',
'🇬🇧 🚺 Isabella': 'bf_isabella',
'🇬🇧 🚺 Alice': 'bf_alice',
'🇬🇧 🚺 Lily': 'bf_lily',
'🇬🇧 🚹 George': 'bm_george',
'🇬🇧 🚹 Fable': 'bm_fable',
'🇬🇧 🚹 Lewis': 'bm_lewis',
'🇬🇧 🚹 Daniel': 'bm_daniel',
'🇪🇸 🚺 Dora': 'ef_dora',
'🇪🇸 🚹 Alex': 'em_alex',
'🇪🇸 🚹 Santa': 'em_santa',
'🇫🇷 🚺 Siwis': 'ff_siwis',
'🇮🇳 🚹 Alpha': 'hf_alpha',
'🇮🇳 🚹 Beta': 'hf_beta',
'🇮🇳 🚹 Omega': 'hm_omega',
'🇮🇳 🚹 Psi': 'hm_psi',
'🇮🇹 🚺 Sara': 'if_sara',
'🇮🇹 🚺 Nicola': 'im_nicola',
'🇯🇵 🚹 Alpha': 'jf_alpha',
'🇯🇵 🚹 Gongitsune': 'jf_gongitsune',
'🇯🇵 🚹 Nezumi': 'jf_nezumi',
'🇯🇵 🚹 Tebukuro': 'jf_tebukuro',
'🇯🇵 🚹 Kumo': 'jm_kumo',
'🇧🇷 🚺 Dora': 'pf_dora',
'🇧🇷 🚹 Alex': 'pm_alex',
'🇧🇷 🚹 Santa': 'pm_santa',
'🇨🇳 🚺 Xiaobei': 'zf_xiaobei',
'🇨🇳 🚺 Xiaoni': 'zf_xiaoni',
'🇨🇳 🚺 Xiaoxiao': 'zf_xiaoxiao',
'🇨🇳 🚺 Xiaoyi': 'zf_xiaoyi',
'🇨🇳 🚹 Yunjian': 'zm_yunjian',
'🇨🇳 🚹 Yunxi': 'zm_yunxi',
'🇨🇳 🚹 Yunxia': 'zm_yunxia',
'🇨🇳 🚹 Yunyang': 'zm_yunyang',
}
# Load voices
for v in CHOICES.values():
pipelines[v[0]].load_voice(v)
# Build the interface
with gr.Blocks() as generate_tab:
out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
generate_btn = gr.Button('Generate', variant='primary')
with gr.Accordion('Output Tokens', open=True):
out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
tokenize_btn = gr.Button('Tokenize', variant='secondary')
predict_btn = gr.Button('Predict', variant='secondary', visible=False)
# Translator Tab
with gr.Blocks() as translator_tab:
trans_out_audio = gr.Audio(label='Translated Audio Output', interactive=False, streaming=False, autoplay=True)
trans_out_tokens = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the translated audio')
translate_btn = gr.Button('Translate & Generate Audio', variant='primary')
translate_btn.click(fn=translate_and_generate, inputs=[text, voice, speed], outputs=[trans_out_audio, trans_out_tokens, text], api_name=None)
# Main Interface
with gr.Blocks() as app:
with gr.Row():
gr.Markdown('''[***Kokoro*** **is an open-weight TTS model with 82 million parameters.**](https://huggingface.co/hexgrad/Kokoro-82M)
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.
This demo only showcases English, but you can directly use the model to access other languages.''', container=True)
with gr.Row():
with gr.Column():
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")
with gr.Row():
voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
use_gpu = gr.Dropdown(
[('ZeroGPU 🚀', True), ('CPU 🐌', False)],
value=CUDA_AVAILABLE,
label='Hardware',
info='GPU is usually faster, but has a usage quota',
interactive=CUDA_AVAILABLE
)
speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
random_btn = gr.Button('Random Text', variant='secondary')
with gr.Column():
gr.TabbedInterface([generate_tab, translator_tab], ['Generate', 'Translator'])
random_btn.click(fn=get_random_text, inputs=[voice], outputs=[text])
generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu], outputs=[out_audio, out_ps])
tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps])
predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio])
if __name__ == '__main__':
app.queue().launch(show_api=True)
|