8 bit commited on
Commit
c6c707b
·
1 Parent(s): 0b44591

Add application file

Browse files
Files changed (1) hide show
  1. app.py +777 -0
app.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from hashlib import sha256
3
+ from huggingface_hub import snapshot_download
4
+ from katsu import Katsu
5
+ from models import build_model
6
+ import gradio as gr
7
+ import librosa
8
+ import numpy as np
9
+ import os
10
+ import phonemizer
11
+ import pypdf
12
+ import random
13
+ import re
14
+ import spaces
15
+ import subprocess
16
+ import torch
17
+ import yaml
18
+
19
+ CUDA_AVAILABLE = torch.cuda.is_available()
20
+
21
+ snapshot = snapshot_download(repo_id='hexgrad/kokoro', allow_patterns=['*.pt', '*.pth', '*.yml'], use_auth_token=os.environ['TOKEN'])
22
+ config = yaml.safe_load(open(os.path.join(snapshot, 'config.yml')))
23
+
24
+ models = {device: build_model(config['model_params'], device) for device in ['cpu'] + (['cuda'] if CUDA_AVAILABLE else [])}
25
+ for key, state_dict in torch.load(os.path.join(snapshot, 'net.pth'), map_location='cpu', weights_only=True)['net'].items():
26
+ for device in models:
27
+ assert key in models[device], key
28
+ try:
29
+ models[device][key].load_state_dict(state_dict)
30
+ except:
31
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
32
+ models[device][key].load_state_dict(state_dict, strict=False)
33
+
34
+ PARAM_COUNT = sum(p.numel() for value in models['cpu'].values() for p in value.parameters())
35
+ assert PARAM_COUNT < 82_000_000, PARAM_COUNT
36
+ with open(os.path.join(snapshot, 'net.pth'), 'rb') as rb:
37
+ model_hash = sha256(rb.read()).hexdigest()
38
+ print('model_hash', model_hash)
39
+ # SHA256 hash matches https://huggingface.co/hexgrad/Kokoro-82M/blob/main/kokoro-v0_19.pth
40
+ assert model_hash == '3b0c392f87508da38fad3a2f9d94c359f1b657ebd2ef79f9d56d69503e470b0a'
41
+
42
+ random_texts = {}
43
+ for lang in ['en', 'fr', 'ja', 'ko', 'zh']:
44
+ with open(f'{lang}.txt', 'r') as r:
45
+ random_texts[lang] = [line.strip() for line in r]
46
+
47
+ def get_random_text(voice):
48
+ lang = dict(a='en', b='en', f='fr', j='ja', k='ko', z='zh')[voice[0]]
49
+ return random.choice(random_texts[lang])
50
+
51
+ sents = set()
52
+ for txt in {'harvard_sentences', 'llama3_command-r_sentences_1st_person', 'llama3_command-r_sentences_excla', 'llama3_command-r_questions'}:
53
+ txt += '.txt'
54
+ subprocess.run(['wget', f'https://huggingface.co/spaces/Pendrokar/TTS-Spaces-Arena/resolve/main/{txt}'])
55
+ with open(txt, 'r') as r:
56
+ sents.update(r.read().strip().splitlines())
57
+ print('len(sents)', len(sents))
58
+
59
+ def parens_to_angles(s):
60
+ return s.replace('(', '«').replace(')', '»')
61
+
62
+ def split_num(num):
63
+ num = num.group()
64
+ if '.' in num:
65
+ return num
66
+ elif ':' in num:
67
+ h, m = [int(n) for n in num.split(':')]
68
+ if m == 0:
69
+ return f"{h} o'clock"
70
+ elif m < 10:
71
+ return f'{h} oh {m}'
72
+ return f'{h} {m}'
73
+ year = int(num[:4])
74
+ if year < 1100 or year % 1000 < 10:
75
+ return num
76
+ left, right = num[:2], int(num[2:4])
77
+ s = 's' if num.endswith('s') else ''
78
+ if 100 <= year % 1000 <= 999:
79
+ if right == 0:
80
+ return f'{left} hundred{s}'
81
+ elif right < 10:
82
+ return f'{left} oh {right}{s}'
83
+ return f'{left} {right}{s}'
84
+
85
+ def flip_money(m):
86
+ m = m.group()
87
+ bill = 'dollar' if m[0] == '$' else 'pound'
88
+ if m[-1].isalpha():
89
+ return f'{m[1:]} {bill}s'
90
+ elif '.' not in m:
91
+ s = '' if m[1:] == '1' else 's'
92
+ return f'{m[1:]} {bill}{s}'
93
+ b, c = m[1:].split('.')
94
+ s = '' if b == '1' else 's'
95
+ c = int(c.ljust(2, '0'))
96
+ coins = f"cent{'' if c == 1 else 's'}" if m[0] == '$' else ('penny' if c == 1 else 'pence')
97
+ return f'{b} {bill}{s} and {c} {coins}'
98
+
99
+ def point_num(num):
100
+ a, b = num.group().split('.')
101
+ return ' point '.join([a, ' '.join(b)])
102
+
103
+ def normalize_text(text, lang):
104
+ text = text.replace(chr(8216), "'").replace(chr(8217), "'")
105
+ text = text.replace('«', chr(8220)).replace('»', chr(8221))
106
+ text = text.replace(chr(8220), '"').replace(chr(8221), '"')
107
+ text = parens_to_angles(text)
108
+ for a, b in zip('、。!,:;?', ',.!,:;?'):
109
+ text = text.replace(a, b+' ')
110
+ text = re.sub(r'[^\S \n]', ' ', text)
111
+ text = re.sub(r' +', ' ', text)
112
+ text = re.sub(r'(?<=\n) +(?=\n)', '', text)
113
+ if lang == 'j':
114
+ return text.strip()
115
+ text = re.sub(r'\bD[Rr]\.(?= [A-Z])', 'Doctor', text)
116
+ text = re.sub(r'\b(?:Mr\.|MR\.(?= [A-Z]))', 'Mister', text)
117
+ text = re.sub(r'\b(?:Ms\.|MS\.(?= [A-Z]))', 'Miss', text)
118
+ text = re.sub(r'\b(?:Mrs\.|MRS\.(?= [A-Z]))', 'Mrs', text)
119
+ text = re.sub(r'\betc\.(?! [A-Z])', 'etc', text)
120
+ text = re.sub(r'(?i)\b(y)eah?\b', r"\1e'a", text)
121
+ text = re.sub(r'\d*\.\d+|\b\d{4}s?\b|(?<!:)\b(?:[1-9]|1[0-2]):[0-5]\d\b(?!:)', split_num, text)
122
+ text = re.sub(r'(?<=\d),(?=\d)', '', text)
123
+ text = re.sub(r'(?i)[$£]\d+(?:\.\d+)?(?: hundred| thousand| (?:[bm]|tr)illion)*\b|[$£]\d+\.\d\d?\b', flip_money, text)
124
+ text = re.sub(r'\d*\.\d+', point_num, text)
125
+ text = re.sub(r'(?<=\d)-(?=\d)', ' to ', text) # TODO: could be minus
126
+ text = re.sub(r'(?<=\d)S', ' S', text)
127
+ text = re.sub(r"(?<=[BCDFGHJ-NP-TV-Z])'?s\b", "'S", text)
128
+ text = re.sub(r"(?<=X')S\b", 's', text)
129
+ text = re.sub(r'(?:[A-Za-z]\.){2,} [a-z]', lambda m: m.group().replace('.', '-'), text)
130
+ text = re.sub(r'(?i)(?<=[A-Z])\.(?=[A-Z])', '-', text)
131
+ return text.strip()
132
+
133
+ phonemizers = dict(
134
+ a=phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True),
135
+ b=phonemizer.backend.EspeakBackend(language='en-gb', preserve_punctuation=True, with_stress=True),
136
+ j=Katsu(),
137
+ )
138
+
139
+ # Starred voices are more stable
140
+ CHOICES = {
141
+ '🇺🇸 🚺 American Female ⭐': 'af',
142
+ '🇺🇸 🚺 Bella ⭐': 'af_bella',
143
+ '🇺🇸 🚺 Nicole ⭐': 'af_nicole',
144
+ '🇺🇸 🚺 Sarah ⭐': 'af_sarah',
145
+ '🇺🇸 🚺 American Female 1': 'af_1',
146
+ '🇺🇸 🚺 Alloy': 'af_alloy',
147
+ '🇺🇸 🚺 Jessica': 'af_jessica',
148
+ '🇺🇸 🚺 Nova': 'af_nova',
149
+ '🇺🇸 🚺 River': 'af_river',
150
+ '🇺🇸 🚺 Sky': 'af_sky',
151
+ '🇺🇸 🚹 Michael ⭐': 'am_michael',
152
+ '🇺🇸 🚹 Adam': 'am_adam',
153
+ '🇺🇸 🚹 Echo': 'am_echo',
154
+ '🇺🇸 🚹 Eric': 'am_eric',
155
+ '🇺🇸 🚹 Liam': 'am_liam',
156
+ '🇺🇸 🚹 Onyx': 'am_onyx',
157
+ '🇬🇧 🚺 British Female 0': 'bf_0',
158
+ '🇬🇧 🚺 British Female 1': 'bf_1',
159
+ '🇬🇧 🚺 British Female 2': 'bf_2',
160
+ '🇬🇧 🚺 British Female 3': 'bf_3',
161
+ '🇬🇧 🚺 Alice': 'bf_alice',
162
+ '🇬🇧 🚺 Lily': 'bf_lily',
163
+ '🇬🇧 🚹 British Male 0': 'bm_0',
164
+ '🇬🇧 🚹 British Male 1': 'bm_1',
165
+ '🇬🇧 🚹 Daniel': 'bm_daniel',
166
+ '🇬🇧 🚹 Fable': 'bm_fable',
167
+ '🇬🇧 🚹 George': 'bm_george',
168
+ '🇬🇧 🚹 Lewis': 'bm_lewis',
169
+ '🇯🇵 🚺 Japanese Female ⭐': 'jf_0',
170
+ '🇯🇵 🚺 Japanese Female 1': 'jf_1',
171
+ '🇯🇵 🚺 Japanese Female 2': 'jf_2',
172
+ '🇯🇵 🚺 Japanese Female 3': 'jf_3',
173
+ }
174
+ VOICES = {device: {k: torch.load(os.path.join(snapshot, 'voicepacks', f'{k}.pt'), weights_only=True).to(device) for k in CHOICES.values()} for device in models}
175
+
176
+ def resolve_voices(voice, warn=True):
177
+ if not isinstance(voice, str) or voice == list(CHOICES.keys())[0]:
178
+ return ['af']
179
+ voices = voice.lower().replace(' ', '+').replace(',', '+').split('+')
180
+ if warn:
181
+ unks = {v for v in voices if v and v not in VOICES['cpu']}
182
+ if unks:
183
+ gr.Warning(f"Unknown voice{'s' if len(unks) > 1 else ''}: {','.join(unks)}")
184
+ voices = [v for v in voices if v in VOICES['cpu']]
185
+ return voices if voices else ['af']
186
+
187
+ def get_vocab():
188
+ _pad = "$"
189
+ _punctuation = ';:,.!?¡¿—…"«»“” '
190
+ _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
191
+ _letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
192
+ symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa)
193
+ dicts = {}
194
+ for i in range(len((symbols))):
195
+ dicts[symbols[i]] = i
196
+ return dicts
197
+
198
+ VOCAB = get_vocab()
199
+
200
+ def tokenize(ps):
201
+ return [i for i in map(VOCAB.get, ps) if i is not None]
202
+
203
+ def phonemize(text, voice, norm=True):
204
+ lang = resolve_voices(voice)[0][0]
205
+ if norm:
206
+ text = normalize_text(text, lang)
207
+ ps = phonemizers[lang].phonemize([text])
208
+ ps = ps[0] if ps else ''
209
+ # TODO: Custom phonemization rules?
210
+ ps = parens_to_angles(ps)
211
+ # https://en.wiktionary.org/wiki/kokoro#English
212
+ if lang in 'ab':
213
+ ps = ps.replace('kəkˈoːɹoʊ', 'kˈoʊkəɹoʊ').replace('kəkˈɔːɹəʊ', 'kˈəʊkəɹəʊ')
214
+ ps = ps.replace('ʲ', 'j').replace('r', 'ɹ').replace('x', 'k').replace('ɬ', 'l')
215
+ ps = re.sub(r'(?<=[a-zɹː])(?=hˈʌndɹɪd)', ' ', ps)
216
+ ps = re.sub(r' z(?=[;:,.!?¡¿—…"«»“” ]|$)', 'z', ps)
217
+ if lang == 'a':
218
+ ps = re.sub(r'(?<=nˈaɪn)ti(?!ː)', 'di', ps)
219
+ ps = ''.join(filter(lambda p: p in VOCAB, ps))
220
+ if lang == 'j' and any(p in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for p in ps):
221
+ gr.Warning('Japanese tokenizer does not handle English letters')
222
+ return ps.strip()
223
+
224
+ harvard_sentences = set()
225
+ with open('harvard_sentences.txt', 'r') as r:
226
+ for line in r:
227
+ harvard_sentences.add(phonemize(line, 'af'))
228
+ harvard_sentences.add(phonemize(line, 'bf_0'))
229
+
230
+ def length_to_mask(lengths):
231
+ mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
232
+ mask = torch.gt(mask+1, lengths.unsqueeze(1))
233
+ return mask
234
+
235
+ SAMPLE_RATE = 24000
236
+
237
+ @torch.no_grad()
238
+ def forward(tokens, voices, speed, sk, device='cpu'):
239
+ assert sk in {os.environ['SK'], os.environ['ARENA'], os.environ['TEMP']}, sk
240
+ ref_s = torch.mean(torch.stack([VOICES[device][v][len(tokens)] for v in voices]), dim=0)
241
+ tokens = torch.LongTensor([[0, *tokens, 0]]).to(device)
242
+ input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
243
+ text_mask = length_to_mask(input_lengths).to(device)
244
+ bert_dur = models[device].bert(tokens, attention_mask=(~text_mask).int())
245
+ d_en = models[device].bert_encoder(bert_dur).transpose(-1, -2)
246
+ s = ref_s[:, 128:]
247
+ d = models[device].predictor.text_encoder(d_en, s, input_lengths, text_mask)
248
+ x, _ = models[device].predictor.lstm(d)
249
+ duration = models[device].predictor.duration_proj(x)
250
+ duration = torch.sigmoid(duration).sum(axis=-1) / speed
251
+ pred_dur = torch.round(duration).clamp(min=1).long()
252
+ pred_aln_trg = torch.zeros(input_lengths, pred_dur.sum().item())
253
+ c_frame = 0
254
+ for i in range(pred_aln_trg.size(0)):
255
+ pred_aln_trg[i, c_frame:c_frame + pred_dur[0,i].item()] = 1
256
+ c_frame += pred_dur[0,i].item()
257
+ en = d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)
258
+ F0_pred, N_pred = models[device].predictor.F0Ntrain(en, s)
259
+ t_en = models[device].text_encoder(tokens, input_lengths, text_mask)
260
+ asr = t_en @ pred_aln_trg.unsqueeze(0).to(device)
261
+ return models[device].decoder(asr, F0_pred, N_pred, ref_s[:, :128]).squeeze().cpu().numpy()
262
+
263
+ @spaces.GPU(duration=10)
264
+ def forward_gpu(tokens, voices, speed, sk):
265
+ return forward(tokens, voices, speed, sk, device='cuda')
266
+
267
+ def clamp_speed(speed):
268
+ if not isinstance(speed, float) and not isinstance(speed, int):
269
+ return 1
270
+ elif speed < 0.5:
271
+ return 0.5
272
+ elif speed > 2:
273
+ return 2
274
+ return speed
275
+
276
+ def clamp_trim(trim):
277
+ if not isinstance(trim, float) and not isinstance(trim, int):
278
+ return 0.5
279
+ elif trim < 0:
280
+ return 0
281
+ elif trim > 1:
282
+ return 0.5
283
+ return trim
284
+
285
+ def trim_if_needed(out, trim):
286
+ if not trim:
287
+ return out
288
+ a, b = librosa.effects.trim(out, top_db=30)[1]
289
+ a = int(a*trim)
290
+ b = int(len(out)-(len(out)-b)*trim)
291
+ return out[a:b]
292
+
293
+ # Must be backwards compatible with https://huggingface.co/spaces/Pendrokar/TTS-Spaces-Arena
294
+ def generate(text, voice='af', ps=None, speed=1, trim=0.5, use_gpu='auto', sk=None):
295
+ if not text.strip():
296
+ return (None, '')
297
+ ps = ps or phonemize(text, voice)
298
+ if sk not in {os.environ['SK'], os.environ['ARENA'], os.environ['TEMP']}:
299
+ assert text in sents or ps.strip('"') in harvard_sentences, ('❌', datetime.now(), text, voice, use_gpu, sk)
300
+ sk = os.environ['ARENA']
301
+ voices = resolve_voices(voice, warn=ps)
302
+ speed = clamp_speed(speed)
303
+ trim = clamp_trim(trim)
304
+ use_gpu = use_gpu if use_gpu in ('auto', False, True) else 'auto'
305
+ tokens = tokenize(ps)
306
+ if not tokens:
307
+ return (None, '')
308
+ elif len(tokens) > 510:
309
+ tokens = tokens[:510]
310
+ ps = ''.join(next(k for k, v in VOCAB.items() if i == v) for i in tokens)
311
+ use_gpu = len(ps) > 99 if use_gpu == 'auto' else use_gpu
312
+ debug = '🔥' if sk == os.environ['SK'] else '🏆'
313
+ try:
314
+ if use_gpu:
315
+ out = forward_gpu(tokens, voices, speed, sk)
316
+ else:
317
+ out = forward(tokens, voices, speed, sk)
318
+ except gr.exceptions.Error as e:
319
+ if use_gpu:
320
+ gr.Warning(str(e))
321
+ gr.Info('Switching to CPU')
322
+ out = forward(tokens, voices, speed, sk)
323
+ else:
324
+ raise gr.Error(e)
325
+ print(debug, datetime.now(), voices, repr(text), len(ps), use_gpu, repr(e))
326
+ return (None, '')
327
+ out = trim_if_needed(out, trim)
328
+ print(debug, datetime.now(), voices, repr(text), len(ps), use_gpu, len(out))
329
+ return ((SAMPLE_RATE, out), ps)
330
+
331
+ def toggle_autoplay(autoplay):
332
+ return gr.Audio(interactive=False, label='Output Audio', autoplay=autoplay)
333
+
334
+ ML_LANGUAGES = {
335
+ '🇺🇸 en-US': 'a',
336
+ '🇬🇧 en-GB': 'b',
337
+ '🇫🇷 fr-FR': 'f',
338
+ '🇯🇵 ja-JP': 'j',
339
+ '🇰🇷 ko-KR': 'k',
340
+ '🇨🇳 zh-CN': 'z',
341
+ }
342
+
343
+ from gradio_client import Client
344
+ client = Client('hexgrad/kokoro-src', hf_token=os.environ['SRC'])
345
+ import json
346
+ ML_CHOICES = json.loads(client.predict(api_name='/list_voices'))
347
+ DEFAULT_VOICE = list(ML_CHOICES['a'].values())[0]
348
+ def change_language(value):
349
+ choices = list(ML_CHOICES[value].items())
350
+ return gr.Dropdown(choices, value=choices[0][1], label='Voice', info='⭐ voices are stable, 🧪 are unstable')
351
+
352
+ def multilingual(text, voice, speed, trim, sk):
353
+ if not text.strip():
354
+ return None
355
+ assert sk == os.environ['SK'], ('❌', datetime.now(), text, voice, sk)
356
+ try:
357
+ audio, out_ps = client.predict(text=text, voice=voice, speed=speed, trim=trim, use_gpu=True, sk=sk, api_name='/generate')
358
+ if len(out_ps) == 510:
359
+ gr.Warning('Input may have been truncated')
360
+ except Exception as e:
361
+ print('📡', datetime.now(), text, voice, repr(e))
362
+ gr.Warning('v0.23 temporarily unavailable')
363
+ gr.Info('Switching to v0.19')
364
+ audio = generate(text, voice=voice, speed=speed, trim=trim, sk=sk)[0]
365
+ return audio
366
+
367
+ with gr.Blocks() as ml_tts:
368
+ with gr.Row():
369
+ lang = gr.Radio(choices=ML_LANGUAGES.items(), value='a', label='Language', show_label=False)
370
+ with gr.Row():
371
+ with gr.Column():
372
+ text = gr.Textbox(label='Input Text', info='Generate speech for one segment of text, up to ~500 characters')
373
+ voice = gr.Dropdown(list(ML_CHOICES['a'].items()), value=DEFAULT_VOICE, label='Voice', info='⭐ voices are stable, 🧪 are unstable')
374
+ lang.change(fn=change_language, inputs=[lang], outputs=[voice])
375
+ with gr.Row():
376
+ random_btn = gr.Button('Random Text', variant='secondary')
377
+ generate_btn = gr.Button('Generate', variant='primary')
378
+ random_btn.click(get_random_text, inputs=[lang], outputs=[text])
379
+ with gr.Column():
380
+ audio = gr.Audio(interactive=False, label='Output Audio', autoplay=True)
381
+ with gr.Accordion('Audio Settings', open=False):
382
+ autoplay = gr.Checkbox(value=True, label='Autoplay')
383
+ autoplay.change(toggle_autoplay, inputs=[autoplay], outputs=[audio])
384
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='⚡️ Speed', info='Adjust the speaking speed')
385
+ trim = gr.Slider(minimum=0, maximum=1, value=0.5, step=0.1, label='✂️ Trim', info='How much to cut from both ends')
386
+ with gr.Row():
387
+ gr.Markdown('''
388
+ ❗ **This space is experiencing heavy lag, possibly due to high traffic.**
389
+
390
+ 🎄 Kokoro v0.19, Bella, & Sarah have been open sourced at [hf.co/hexgrad/Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M)
391
+
392
+ 🎉 New! Kokoro v0.23 now supports 5 languages. 🎉
393
+
394
+ 🧪 Note that v0.23 is experimental/WIP and may produce shaky speech. v0.19 is the last stable version.
395
+
396
+ ⚠️ v0.23 does not yet support custom pronunciation, Long Form, or Voice Mixer. You can still use these features in v0.19.
397
+
398
+ 📡 Telemetry: For debugging purposes, the text you enter anywhere in this space may be printed to temporary logs, which are periodically wiped.
399
+
400
+ 🇨🇳🇯🇵🇰🇷 Tokenizers for Chinese, Japanese, and Korean do not correctly handle English letters yet. Remove or convert them to CJK first.
401
+ ''', container=True)
402
+ with gr.Row():
403
+ sk = gr.Textbox(visible=False)
404
+ text.change(lambda: os.environ['SK'], outputs=[sk])
405
+ text.submit(multilingual, inputs=[text, voice, speed, trim, sk], outputs=[audio])
406
+ generate_btn.click(multilingual, inputs=[text, voice, speed, trim, sk], outputs=[audio])
407
+
408
+ USE_GPU_CHOICES = [('Auto 🔀', 'auto'), ('CPU 💬', False), ('ZeroGPU 📄', True)]
409
+ USE_GPU_INFOS = {
410
+ 'auto': 'Use CPU or GPU, whichever is faster',
411
+ False: 'CPU is ~faster <100 tokens',
412
+ True: 'ZeroGPU is ~faster >100 tokens',
413
+ }
414
+ def change_use_gpu(value):
415
+ return gr.Dropdown(USE_GPU_CHOICES, value=value, label='Hardware', info=USE_GPU_INFOS[value], interactive=CUDA_AVAILABLE)
416
+
417
+ with gr.Blocks() as basic_tts:
418
+ with gr.Row():
419
+ with gr.Column():
420
+ text = gr.Textbox(label='Input Text', info='Generate speech for one segment of text using Kokoro, a TTS model with 82 million parameters')
421
+ with gr.Row():
422
+ voice = gr.Dropdown(list(CHOICES.items()), value='af', allow_custom_value=True, label='Voice', info='Starred voices are more stable')
423
+ use_gpu = gr.Dropdown(
424
+ USE_GPU_CHOICES,
425
+ value='auto' if CUDA_AVAILABLE else False,
426
+ label='Hardware',
427
+ info=USE_GPU_INFOS['auto' if CUDA_AVAILABLE else False],
428
+ interactive=CUDA_AVAILABLE
429
+ )
430
+ use_gpu.change(fn=change_use_gpu, inputs=[use_gpu], outputs=[use_gpu])
431
+ with gr.Row():
432
+ random_btn = gr.Button('Random Text', variant='secondary')
433
+ generate_btn = gr.Button('Generate', variant='primary')
434
+ random_btn.click(get_random_text, inputs=[voice], outputs=[text])
435
+ with gr.Accordion('Input Tokens', open=False):
436
+ in_ps = gr.Textbox(show_label=False, info='Override the input text with custom phonemes. Leave this blank to automatically tokenize the input text instead.')
437
+ with gr.Row():
438
+ clear_btn = gr.ClearButton(in_ps)
439
+ phonemize_btn = gr.Button('Tokenize Input Text', variant='primary')
440
+ phonemize_btn.click(phonemize, inputs=[text, voice], outputs=[in_ps])
441
+ with gr.Column():
442
+ audio = gr.Audio(interactive=False, label='Output Audio', autoplay=True)
443
+ with gr.Accordion('Audio Settings', open=False):
444
+ autoplay = gr.Checkbox(value=True, label='Autoplay')
445
+ autoplay.change(toggle_autoplay, inputs=[autoplay], outputs=[audio])
446
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='⚡️ Speed', info='Adjust the speaking speed')
447
+ trim = gr.Slider(minimum=0, maximum=1, value=0.5, step=0.1, label='✂️ Trim', info='How much to cut from both ends of each segment')
448
+ with gr.Accordion('Output Tokens', open=True):
449
+ out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 allowed. Same as input tokens if supplied, excluding unknowns.')
450
+ with gr.Accordion('Voice Mixer', open=False):
451
+ gr.Markdown('Create a custom voice by mixing and matching other voices. Click an orange button to add one part to your mix, or click a gray button to start over. You can also enter a voice mix as text.')
452
+ for i in range(8):
453
+ with gr.Row():
454
+ for j in range(4):
455
+ with gr.Column():
456
+ btn = gr.Button(list(CHOICES.values())[i*4+j], variant='primary' if i*4+j < 10 else 'secondary')
457
+ btn.click(lambda v, b: f'{v}+{b}' if v.startswith(b[:2]) else b, inputs=[voice, btn], outputs=[voice])
458
+ voice.change(lambda v, b: gr.Button(b, variant='primary' if v.startswith(b[:2]) else 'secondary'), inputs=[voice, btn], outputs=[btn])
459
+ with gr.Row():
460
+ sk = gr.Textbox(visible=False)
461
+ text.change(lambda: os.environ['SK'], outputs=[sk])
462
+ text.submit(generate, inputs=[text, voice, in_ps, speed, trim, use_gpu, sk], outputs=[audio, out_ps])
463
+ generate_btn.click(generate, inputs=[text, voice, in_ps, speed, trim, use_gpu, sk], outputs=[audio, out_ps])
464
+
465
+ @torch.no_grad()
466
+ def lf_forward(token_lists, voices, speed, sk, device='cpu'):
467
+ assert sk == os.environ['SK'], sk
468
+ voicepack = torch.mean(torch.stack([VOICES[device][v] for v in voices]), dim=0)
469
+ outs = []
470
+ for tokens in token_lists:
471
+ ref_s = voicepack[len(tokens)]
472
+ s = ref_s[:, 128:]
473
+ tokens = torch.LongTensor([[0, *tokens, 0]]).to(device)
474
+ input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
475
+ text_mask = length_to_mask(input_lengths).to(device)
476
+ bert_dur = models[device].bert(tokens, attention_mask=(~text_mask).int())
477
+ d_en = models[device].bert_encoder(bert_dur).transpose(-1, -2)
478
+ d = models[device].predictor.text_encoder(d_en, s, input_lengths, text_mask)
479
+ x, _ = models[device].predictor.lstm(d)
480
+ duration = models[device].predictor.duration_proj(x)
481
+ duration = torch.sigmoid(duration).sum(axis=-1) / speed
482
+ pred_dur = torch.round(duration).clamp(min=1).long()
483
+ pred_aln_trg = torch.zeros(input_lengths, pred_dur.sum().item())
484
+ c_frame = 0
485
+ for i in range(pred_aln_trg.size(0)):
486
+ pred_aln_trg[i, c_frame:c_frame + pred_dur[0,i].item()] = 1
487
+ c_frame += pred_dur[0,i].item()
488
+ en = d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)
489
+ F0_pred, N_pred = models[device].predictor.F0Ntrain(en, s)
490
+ t_en = models[device].text_encoder(tokens, input_lengths, text_mask)
491
+ asr = t_en @ pred_aln_trg.unsqueeze(0).to(device)
492
+ outs.append(models[device].decoder(asr, F0_pred, N_pred, ref_s[:, :128]).squeeze().cpu().numpy())
493
+ return outs
494
+
495
+ @spaces.GPU
496
+ def lf_forward_gpu(token_lists, voices, speed, sk):
497
+ return lf_forward(token_lists, voices, speed, sk, device='cuda')
498
+
499
+ def resplit_strings(arr):
500
+ # Handle edge cases
501
+ if not arr:
502
+ return '', ''
503
+ if len(arr) == 1:
504
+ return arr[0], ''
505
+ # Try each possible split point
506
+ min_diff = float('inf')
507
+ best_split = 0
508
+ # Calculate lengths when joined with spaces
509
+ lengths = [len(s) for s in arr]
510
+ spaces = len(arr) - 1 # Total spaces needed
511
+ # Try each split point
512
+ left_len = 0
513
+ right_len = sum(lengths) + spaces
514
+ for i in range(1, len(arr)):
515
+ # Add current word and space to left side
516
+ left_len += lengths[i-1] + (1 if i > 1 else 0)
517
+ # Remove current word and space from right side
518
+ right_len -= lengths[i-1] + 1
519
+ diff = abs(left_len - right_len)
520
+ if diff < min_diff:
521
+ min_diff = diff
522
+ best_split = i
523
+ # Join the strings with the best split point
524
+ return ' '.join(arr[:best_split]), ' '.join(arr[best_split:])
525
+
526
+ def recursive_split(text, voice):
527
+ if not text:
528
+ return []
529
+ tokens = phonemize(text, voice, norm=False)
530
+ if len(tokens) < 511:
531
+ return [(text, tokens, len(tokens))] if tokens else []
532
+ if ' ' not in text:
533
+ return []
534
+ for punctuation in ['!.?…', ':;', ',—']:
535
+ splits = re.split(f'(?:(?<=[{punctuation}])|(?<=[{punctuation}]["\'»])|(?<=[{punctuation}]["\'»]["\'»])) ', text)
536
+ if len(splits) > 1:
537
+ break
538
+ else:
539
+ splits = None
540
+ splits = splits or text.split(' ')
541
+ a, b = resplit_strings(splits)
542
+ return recursive_split(a, voice) + recursive_split(b, voice)
543
+
544
+ def segment_and_tokenize(text, voice, skip_square_brackets=True, newline_split=2):
545
+ lang = resolve_voices(voice)[0][0]
546
+ if skip_square_brackets:
547
+ text = re.sub(r'\[.*?\]', '', text)
548
+ texts = [t.strip() for t in re.split('\n{'+str(newline_split)+',}', normalize_text(text, lang))] if newline_split > 0 else [normalize_text(text, lang)]
549
+ segments = [row for t in texts for row in recursive_split(t, voice)]
550
+ return [(i, *row) for i, row in enumerate(segments)]
551
+
552
+ def lf_generate(segments, voice, speed=1, trim=0, pad_between=0, use_gpu=True, sk=None):
553
+ if sk != os.environ['SK']:
554
+ return
555
+ token_lists = list(map(tokenize, segments['Tokens']))
556
+ voices = resolve_voices(voice)
557
+ speed = clamp_speed(speed)
558
+ trim = clamp_trim(trim)
559
+ pad_between = int(pad_between)
560
+ use_gpu = True
561
+ batch_sizes = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1]
562
+ i = 0
563
+ while i < len(token_lists):
564
+ bs = batch_sizes.pop() if batch_sizes else 100
565
+ tokens = token_lists[i:i+bs]
566
+ print('📖', datetime.now(), len(tokens), voices, use_gpu, ''.join(segments['Text'][i:i+bs]).replace('\n', ' '))
567
+ try:
568
+ if use_gpu:
569
+ outs = lf_forward_gpu(tokens, voices, speed, sk)
570
+ else:
571
+ outs = lf_forward(tokens, voices, speed, sk)
572
+ except gr.exceptions.Error as e:
573
+ if use_gpu:
574
+ gr.Warning(str(e))
575
+ gr.Info('Switching to CPU')
576
+ outs = lf_forward(tokens, voices, speed, sk)
577
+ use_gpu = False
578
+ elif outs:
579
+ gr.Warning(repr(e))
580
+ i = len(token_lists)
581
+ else:
582
+ raise gr.Error(e)
583
+ for out in outs:
584
+ if i > 0 and pad_between > 0:
585
+ yield (SAMPLE_RATE, np.zeros(pad_between))
586
+ out = trim_if_needed(out, trim)
587
+ yield (SAMPLE_RATE, out)
588
+ i += bs
589
+
590
+ def did_change_segments(segments):
591
+ x = len(segments) if segments['Length'].any() else 0
592
+ return [
593
+ gr.Button('Tokenize', variant='secondary' if x else 'primary'),
594
+ gr.Button(f'Generate x{x}', variant='primary' if x else 'secondary', interactive=x > 0),
595
+ ]
596
+
597
+ def extract_text(file):
598
+ if file.endswith('.pdf'):
599
+ with open(file, 'rb') as rb:
600
+ pdf_reader = pypdf.PdfReader(rb)
601
+ return '\n'.join([page.extract_text() for page in pdf_reader.pages])
602
+ elif file.endswith('.txt'):
603
+ with open(file, 'r') as r:
604
+ return '\n'.join([line for line in r])
605
+ return None
606
+
607
+ with gr.Blocks() as lf_tts:
608
+ with gr.Row():
609
+ with gr.Column():
610
+ file_input = gr.File(file_types=['.pdf', '.txt'], label='pdf or txt')
611
+ text = gr.Textbox(label='Input Text', info='Generate speech in batches of 100 text segments and automatically join them together')
612
+ file_input.upload(fn=extract_text, inputs=[file_input], outputs=[text])
613
+ with gr.Row():
614
+ voice = gr.Dropdown(list(CHOICES.items()), value='af', allow_custom_value=True, label='Voice', info='Starred voices are more stable')
615
+ use_gpu = gr.Dropdown(
616
+ [('ZeroGPU 🚀', True), ('CPU 🐌', False)],
617
+ value=CUDA_AVAILABLE,
618
+ label='Hardware',
619
+ info='GPU is >10x faster but has a usage quota',
620
+ interactive=CUDA_AVAILABLE
621
+ )
622
+ with gr.Accordion('Text Settings', open=False):
623
+ skip_square_brackets = gr.Checkbox(True, label='Skip [Square Brackets]', info='Recommended for academic papers, Wikipedia articles, or texts with citations')
624
+ newline_split = gr.Number(2, label='Newline Split', info='Split the input text on this many newlines. Affects how the text is segmented.', precision=0, minimum=0)
625
+ with gr.Column():
626
+ audio_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
627
+ with gr.Accordion('Audio Settings', open=True):
628
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='⚡️ Speed', info='Adjust the speaking speed')
629
+ trim = gr.Slider(minimum=0, maximum=1, value=0, step=0.1, label='✂️ Trim', info='How much to cut from both ends')
630
+ pad_between = gr.Slider(minimum=0, maximum=24000, value=0, step=1000, label='🔇 Pad Between', info='How many silent samples to insert between segments')
631
+ with gr.Row():
632
+ segment_btn = gr.Button('Tokenize', variant='primary')
633
+ generate_btn = gr.Button('Generate x0', variant='secondary', interactive=False)
634
+ stop_btn = gr.Button('Stop', variant='stop')
635
+ with gr.Row():
636
+ segments = gr.Dataframe(headers=['#', 'Text', 'Tokens', 'Length'], row_count=(1, 'dynamic'), col_count=(4, 'fixed'), label='Segments', interactive=False, wrap=True)
637
+ segments.change(fn=did_change_segments, inputs=[segments], outputs=[segment_btn, generate_btn])
638
+ with gr.Row():
639
+ sk = gr.Textbox(visible=False)
640
+ segments.change(lambda: os.environ['SK'], outputs=[sk])
641
+ segment_btn.click(segment_and_tokenize, inputs=[text, voice, skip_square_brackets, newline_split], outputs=[segments])
642
+ generate_event = generate_btn.click(lf_generate, inputs=[segments, voice, speed, trim, pad_between, use_gpu, sk], outputs=[audio_stream])
643
+ stop_btn.click(fn=None, cancels=generate_event)
644
+
645
+ with gr.Blocks() as about:
646
+ gr.Markdown('''
647
+ Kokoro is a frontier TTS model for its size. It has [82 million](https://hf.co/spaces/hexgrad/Kokoro-TTS/blob/main/app.py#L34) parameters, uses a lean [StyleTTS 2](https://github.com/yl4579/StyleTTS2) architecture, and was trained on high-quality data. The weights are currently private, but a free public demo is hosted here, at `https://hf.co/spaces/hexgrad/Kokoro-TTS`. The Community tab is open for feature requests, bug reports, etc. For other inquiries, contact `@rzvzn` on Discord.
648
+
649
+ ### FAQ
650
+ **Will this be open sourced?**<br/>
651
+ v0.19 has been open sourced at [hf.co/hexgrad/Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M) along with the voicepacks Bella, Sarah, and `af`. There currently isn't a release date scheduled for the other voices.
652
+
653
+ **What is the difference between stable and unstable voices?**<br/>
654
+ Unstable voices are more likely to stumble or produce unnatural artifacts, especially on short or strange texts. Stable voices are more likely to deliver natural speech on a wider range of inputs. The first two audio clips in this [blog post](https://hf.co/blog/hexgrad/kokoro-short-burst-upgrade) are examples of unstable and stable speech. Note that even unstable voices can sound fine on medium to long texts.
655
+
656
+ **How can CPU be faster than ZeroGPU?**<br/>
657
+ The CPU is a dedicated resource for this Space, while the ZeroGPU pool is shared and dynamically allocated across all of HF. The ZeroGPU queue/allocator system inevitably adds latency to each request.<br/>
658
+ For Basic TTS under ~100 tokens or characters, only a few seconds of audio need to be generated, so the actual compute is not that heavy. In these short bursts, the dedicated CPU can often compute the result faster than the total time it takes to: enter the ZeroGPU queue, wait to get allocated, and have a GPU compute and deliver the result.<br/>
659
+ ZeroGPU catches up beyond 100 tokens and especially closer to the ~500 token context window. Long Form mode processes batches of 100 segments at a time, so the GPU should outspeed the CPU by 1-2 orders of magnitude.
660
+
661
+ ### Compute
662
+ Kokoro v0.19 was trained on A100 80GB vRAM instances for approximately 500 total GPU hours. The average cost for each GPU hour was around $0.80, so the total cost was around $400.
663
+
664
+ ### Gradio API
665
+ The API has been restricted due to high request volume impacting CPU latency.
666
+
667
+ ### Licenses
668
+ Inference code: MIT<br/>
669
+ [eSpeak NG](https://github.com/espeak-ng/espeak-ng): GPL-3.0<br/>
670
+ Random English texts: Unknown from [Quotable Data](https://github.com/quotable-io/data/blob/master/data/quotes.json)<br/>
671
+ Other random texts: CC0 public domain from [Common Voice](https://github.com/common-voice/common-voice)
672
+ ''')
673
+ '''
674
+ This Space can be used via API. The following code block can be copied and run in one Google Colab cell.
675
+ ```
676
+ # 1️⃣ Install the Gradio Python client
677
+ !pip install -q gradio_client
678
+ # 2️⃣ Initialize the client
679
+ from gradio_client import Client
680
+ client = Client('hexgrad/Kokoro-TTS')
681
+ # 3️⃣ Call the generate endpoint, which returns a pair: an audio path and a string of output phonemes
682
+ audio_path, out_ps = client.predict(
683
+ text="How could I know? It's an unanswerable question. Like asking an unborn child if they'll lead a good life. They haven't even been born.",
684
+ voice='af',
685
+ api_name='/generate'
686
+ )
687
+ # 4️⃣ Display the audio and print the output phonemes
688
+ from IPython.display import display, Audio
689
+ display(Audio(audio_path, autoplay=True))
690
+ print(out_ps)
691
+ ```
692
+ This Space and the underlying Kokoro model are both under development and subject to change. Reliability is not guaranteed. Hugging Face and Gradio might enforce their own rate limits.
693
+ '''
694
+ with gr.Blocks() as changelog:
695
+ gr.Markdown('''
696
+ **25 Dec 2024**<br/>
697
+ 🎄 Kokoro v0.19, Bella, & Sarah have been open sourced at [hf.co/hexgrad/Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M)
698
+
699
+ **11 Dec 2024**<br/>
700
+ 🚀 Multilingual v0.23<br/>
701
+ 🗣️ 85 total voices
702
+
703
+ **8 Dec 2024**<br/>
704
+ 🚀 Multilingual v0.22<br/>
705
+ 🌐 5 languages: English, Chinese, Japanese, Korean, French<br/>
706
+ 🗣️ 68 total voices<br/>
707
+ 📁 Added data card and telemetry notice
708
+
709
+ **30 Nov 2024**<br/>
710
+ ✂️ Better trimming with `librosa.effects.trim`<br/>
711
+ 🏆 https://hf.co/spaces/Pendrokar/TTS-Spaces-Arena
712
+
713
+ **28 Nov 2024**<br/>
714
+ 🥈 CPU fallback<br/>
715
+ 🌊 Long Form streaming and stop button<br/>
716
+ ✋ Restricted API due to high request volume impacting CPU latency
717
+
718
+ **25 Nov 2024**<br/>
719
+ 🎨 Voice Mixer added
720
+
721
+ **24 Nov 2024**<br/>
722
+ 🛑 Model training halted, v0.19 is the current stable version
723
+
724
+ **23 Nov 2024**<br/>
725
+ 🔀 Hardware switching between CPU and GPU<br/>
726
+ 🗣️ Restored old voices, back up to 32 total
727
+
728
+ **22 Nov 2024**<br/>
729
+ 🚀 Model v0.19<br/>
730
+ 🧪 Validation losses: 0.261 mel, 0.627 dur, 1.897 f0<br/>
731
+ 📄 https://hf.co/blog/hexgrad/kokoro-short-burst-upgrade
732
+
733
+ **15 Nov 2024**<br/>
734
+ 🚀 Model v0.16<br/>
735
+ 🧪 Validation losses: 0.263 mel, 0.646 dur, 1.934 f0
736
+
737
+ **12 Nov 2024**<br/>
738
+ 🚀 Model v0.14<br/>
739
+ 🧪 Validation losses: 0.262 mel, 0.642 dur, 1.889 f0
740
+ ''')
741
+
742
+ with gr.Blocks() as data_card:
743
+ gr.Markdown('''
744
+ This data card was last updated on **8 Dec 2024**.
745
+
746
+ Kokoro was trained exclusively on **permissive/non-copyrighted audio data** and IPA phoneme labels. Examples of permissive/non-copyrighted audio include:
747
+ * Public domain audio
748
+ * Audio licensed under Apache, MIT, etc
749
+ * Synthetic audio<sup>[1]</sup> generated by closed<sup>[2]</sup> TTS models from large providers
750
+ * CC BY audio (see below for attribution table)
751
+
752
+ [1] [https://copyright.gov/ai/ai_policy_guidance.pdf](https://copyright.gov/ai/ai_policy_guidance.pdf)<br/>
753
+ [2] No synthetic audio from open TTS models or "custom voice clones"
754
+
755
+ ### Creative Commons Attribution
756
+ The following CC BY audio was part of the dataset used to train Kokoro.
757
+
758
+ | Audio Data | Duration Used | License | Added to Training Set After |
759
+ | ---------- | ------------- | ------- | --------------------------- |
760
+ | [Koniwa](https://github.com/koniwa/koniwa) `tnc` | <1h | [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/deed.ja) | v0.19 / 22 Nov 2024 |
761
+ | [SIWIS](https://datashare.ed.ac.uk/handle/10283/2353) | <11h | [CC BY 4.0](https://datashare.ed.ac.uk/bitstream/handle/10283/2353/license_text) | v0.19 / 22 Nov 2024 |
762
+
763
+ ### Notable Datasets Not Used
764
+ These datasets were **NOT** used to train Kokoro. They may be of interest to academics:
765
+ * Emilia, `cc-by-nc-4.0`: `https://huggingface.co/datasets/amphion/Emilia-Dataset`
766
+ * Expresso, `cc-by-nc-4.0`: `https://huggingface.co/datasets/ylacombe/expresso`
767
+ * JVS, NC clause: `https://sites.google.com/site/shinnosuketakamichi/research-topics/jvs_corpus`
768
+ ''')
769
+
770
+ with gr.Blocks() as app:
771
+ gr.TabbedInterface(
772
+ [ml_tts, basic_tts, lf_tts, about, data_card, changelog],
773
+ ['🔥 Latest v0.23', '🗣️ TTS v0.19', '📖 Long Form v0.19', 'ℹ️ About', '📁 Data', '📝 Changelog'],
774
+ )
775
+
776
+ if __name__ == '__main__':
777
+ app.queue(api_open=True).launch(show_api=False, ssr_mode=True)