mrfakename commited on
Commit
d40e945
1 Parent(s): 7fd1c76

Updates to TTS Arena!

Browse files
Files changed (17) hide show
  1. LICENSE +0 -2
  2. README.md +8 -7
  3. app.py +3 -796
  4. app/__init__.py +0 -0
  5. app/config.py +38 -0
  6. app/db.py +54 -0
  7. app/init.py +30 -0
  8. app/leaderboard.py +55 -0
  9. app/messages.py +62 -0
  10. app/models.py +46 -0
  11. app/synth.py +240 -0
  12. app/ui.py +19 -0
  13. app/ui_battle.py +59 -0
  14. app/ui_leaderboard.py +17 -0
  15. app/ui_vote.py +80 -0
  16. app/utils.py +20 -0
  17. app/vote.py +114 -0
LICENSE CHANGED
@@ -1,5 +1,3 @@
1
- ZLIB/LIBPNG LICENSE
2
-
3
  Copyright (c) 2024 TTS-AGI Contributors
4
 
5
  This software is provided ‘as-is’, without any express or implied
 
 
 
1
  Copyright (c) 2024 TTS-AGI Contributors
2
 
3
  This software is provided ‘as-is’, without any express or implied
README.md CHANGED
@@ -1,15 +1,16 @@
1
  ---
2
  title: TTS Arena
3
- sdk_version: 4.36.1
4
  sdk: gradio
5
  app_file: app.py
6
  license: zlib
7
  tags:
8
  - arena
9
- emoji: 🏆
10
- colorFrom: blue
11
- colorTo: blue
12
- pinned: true
13
  header: mini
14
- short_description: Vote on the top TTS models!
15
- ---
 
 
 
1
  ---
2
  title: TTS Arena
 
3
  sdk: gradio
4
  app_file: app.py
5
  license: zlib
6
  tags:
7
  - arena
8
+ emoji: 🧪
9
+ colorFrom: yellow
10
+ colorTo: yellow
11
+ pinned: false
12
  header: mini
13
+ sdk_version: 5.0.1
14
+ short_description: Vote on the latest TTS models!
15
+ ---
16
+ # TTS Arena
app.py CHANGED
@@ -1,797 +1,4 @@
1
- import gradio as gr
2
- import pandas as pd
3
- from langdetect import detect
4
- from datasets import load_dataset
5
- import threading, time, uuid, sqlite3, shutil, os, random, asyncio, threading
6
- from pathlib import Path
7
- from huggingface_hub import CommitScheduler, delete_file, hf_hub_download
8
- from gradio_client import Client
9
- import pyloudnorm as pyln
10
- import soundfile as sf
11
- import librosa
12
- from detoxify import Detoxify
13
- import os
14
- import tempfile
15
- from pydub import AudioSegment
16
 
17
- def match_target_amplitude(sound, target_dBFS):
18
- change_in_dBFS = target_dBFS - sound.dBFS
19
- return sound.apply_gain(change_in_dBFS)
20
-
21
- # from gradio_space_ci import enable_space_ci
22
-
23
- # enable_space_ci()
24
-
25
-
26
-
27
- toxicity = Detoxify('original')
28
- with open('harvard_sentences.txt') as f:
29
- sents = f.read().strip().splitlines()
30
- ####################################
31
- # Constants
32
- ####################################
33
- AVAILABLE_MODELS = {
34
- 'XTTSv2': 'xtts',
35
- # 'WhisperSpeech': 'whisperspeech',
36
- 'ElevenLabs': 'eleven',
37
- # 'OpenVoice': 'openvoice',
38
- 'OpenVoice V2': 'openvoicev2',
39
- 'Play.HT 2.0': 'playht',
40
- # 'MetaVoice': 'metavoice',
41
- 'MeloTTS': 'melo',
42
- 'StyleTTS 2': 'styletts2',
43
- 'GPT-SoVITS': 'sovits',
44
- # 'Vokan TTS': 'vokan',
45
- 'VoiceCraft 2.0': 'voicecraft',
46
- 'Parler TTS': 'parler'
47
- }
48
-
49
- SPACE_ID = os.getenv('SPACE_ID')
50
- MAX_SAMPLE_TXT_LENGTH = 300
51
- MIN_SAMPLE_TXT_LENGTH = 10
52
- DB_DATASET_ID = os.getenv('DATASET_ID')
53
- DB_NAME = "database.db"
54
-
55
- # If /data available => means local storage is enabled => let's use it!
56
- DB_PATH = f"/data/{DB_NAME}" if os.path.isdir("/data") else DB_NAME
57
- print(f"Using {DB_PATH}")
58
- # AUDIO_DATASET_ID = "ttseval/tts-arena-new"
59
- CITATION_TEXT = """@misc{tts-arena,
60
- title = {Text to Speech Arena},
61
- author = {mrfakename and Srivastav, Vaibhav and Fourrier, Clémentine and Pouget, Lucain and Lacombe, Yoach and main and Gandhi, Sanchit},
62
- year = 2024,
63
- publisher = {Hugging Face},
64
- howpublished = "\\url{https://huggingface.co/spaces/TTS-AGI/TTS-Arena}"
65
- }"""
66
-
67
- ####################################
68
- # Functions
69
- ####################################
70
-
71
- def create_db_if_missing():
72
- conn = get_db()
73
- cursor = conn.cursor()
74
- cursor.execute('''
75
- CREATE TABLE IF NOT EXISTS model (
76
- name TEXT UNIQUE,
77
- upvote INTEGER,
78
- downvote INTEGER
79
- );
80
- ''')
81
- cursor.execute('''
82
- CREATE TABLE IF NOT EXISTS vote (
83
- id INTEGER PRIMARY KEY AUTOINCREMENT,
84
- username TEXT,
85
- model TEXT,
86
- vote INTEGER,
87
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
88
- );
89
- ''')
90
- cursor.execute('''
91
- CREATE TABLE IF NOT EXISTS votelog (
92
- id INTEGER PRIMARY KEY AUTOINCREMENT,
93
- username TEXT,
94
- chosen TEXT,
95
- rejected TEXT,
96
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
97
- );
98
- ''')
99
- cursor.execute('''
100
- CREATE TABLE IF NOT EXISTS spokentext (
101
- id INTEGER PRIMARY KEY AUTOINCREMENT,
102
- spokentext TEXT,
103
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
104
- );
105
- ''')
106
- def get_db():
107
- return sqlite3.connect(DB_PATH)
108
-
109
-
110
-
111
- ####################################
112
- # Space initialization
113
- ####################################
114
-
115
- # Download existing DB
116
- if not os.path.isfile(DB_PATH):
117
- print("Downloading DB...")
118
- try:
119
- cache_path = hf_hub_download(repo_id=DB_DATASET_ID, repo_type='dataset', filename=DB_NAME)
120
- shutil.copyfile(cache_path, DB_PATH)
121
- print("Downloaded DB")
122
- except Exception as e:
123
- print("Error while downloading DB:", e)
124
-
125
- # Create DB table (if doesn't exist)
126
- create_db_if_missing()
127
-
128
- # Sync local DB with remote repo every 5 minute (only if a change is detected)
129
- scheduler = CommitScheduler(
130
- repo_id=DB_DATASET_ID,
131
- repo_type="dataset",
132
- folder_path=Path(DB_PATH).parent,
133
- every=5,
134
- allow_patterns=DB_NAME,
135
- )
136
-
137
- # Load audio dataset
138
- # audio_dataset = load_dataset(AUDIO_DATASET_ID)
139
-
140
- ####################################
141
- # Router API
142
- ####################################
143
- router = Client("TTS-AGI/tts-router", hf_token=os.getenv('HF_TOKEN'))
144
- ####################################
145
- # Gradio app
146
- ####################################
147
- MUST_BE_LOGGEDIN = "Please login with Hugging Face to participate in the TTS Arena."
148
- DESCR = """
149
- # TTS Arena: Benchmarking TTS Models in the Wild
150
-
151
- Vote to help the community find the best available text-to-speech model!
152
- """.strip()
153
- # INSTR = """
154
- # ## Instructions
155
-
156
- # * Listen to two anonymous models
157
- # * Vote on which synthesized audio sounds more natural to you
158
- # * If there's a tie, click Skip
159
-
160
- # **When you're ready to begin, login and begin voting!** The model names will be revealed once you vote.
161
- # """.strip()
162
- INSTR = """
163
- ## 🗳️ Vote
164
-
165
- * Input text (English only) to synthesize audio (or press 🎲 for random text).
166
- * Listen to the two audio clips, one after the other.
167
- * Vote on which audio sounds more natural to you.
168
- * _Note: Model names are revealed after the vote is cast._
169
-
170
- Note: It may take up to 30 seconds to synthesize audio.
171
- """.strip()
172
- request = ''
173
- if SPACE_ID:
174
- request = f"""
175
- ### Request a model
176
-
177
- Please [create a Discussion](https://huggingface.co/spaces/{SPACE_ID}/discussions/new) to request a model.
178
- """
179
- ABOUT = f"""
180
- ## 📄 About
181
-
182
- The TTS Arena evaluates leading speech synthesis models. It is inspired by LMsys's [Chatbot Arena](https://chat.lmsys.org/).
183
-
184
- ### Motivation
185
-
186
- The field of speech synthesis has long lacked an accurate method to measure the quality of different models. Objective metrics like WER (word error rate) are unreliable measures of model quality, and subjective measures such as MOS (mean opinion score) are typically small-scale experiments conducted with few listeners. As a result, these measurements are generally not useful for comparing two models of roughly similar quality. To address these drawbacks, we are inviting the community to rank models in an easy-to-use interface, and opening it up to the public in order to make both the opportunity to rank models, as well as the results, more easily accessible to everyone.
187
-
188
- ### The Arena
189
-
190
- The leaderboard allows a user to enter text, which will be synthesized by two models. After listening to each sample, the user can vote on which model sounds more natural. Due to the risks of human bias and abuse, model names are revealed only after a vote is submitted.
191
-
192
- ### Credits
193
-
194
- Thank you to the following individuals who helped make this project possible:
195
-
196
- * VB ([Twitter](https://twitter.com/reach_vb) / [Hugging Face](https://huggingface.co/reach-vb))
197
- * Clémentine Fourrier ([Twitter](https://twitter.com/clefourrier) / [Hugging Face](https://huggingface.co/clefourrier))
198
- * Lucain Pouget ([Twitter](https://twitter.com/Wauplin) / [Hugging Face](https://huggingface.co/Wauplin))
199
- * Yoach Lacombe ([Twitter](https://twitter.com/yoachlacombe) / [Hugging Face](https://huggingface.co/ylacombe))
200
- * Main Horse ([Twitter](https://twitter.com/main_horse) / [Hugging Face](https://huggingface.co/main-horse))
201
- * Sanchit Gandhi ([Twitter](https://twitter.com/sanchitgandhi99) / [Hugging Face](https://huggingface.co/sanchit-gandhi))
202
- * Apolinário Passos ([Twitter](https://twitter.com/multimodalart) / [Hugging Face](https://huggingface.co/multimodalart))
203
- * Pedro Cuenca ([Twitter](https://twitter.com/pcuenq) / [Hugging Face](https://huggingface.co/pcuenq))
204
-
205
- {request}
206
-
207
- ### Privacy statement
208
-
209
- We may store text you enter and generated audio. We store a unique ID for each session. You agree that we may collect, share, and/or publish any data you input for research and/or commercial purposes.
210
-
211
- ### License
212
-
213
- Generated audio clips cannot be redistributed and may be used for personal, non-commercial use only.
214
-
215
- Random sentences are sourced from a filtered subset of the [Harvard Sentences](https://www.cs.columbia.edu/~hgs/audio/harvard.html).
216
- """.strip()
217
- LDESC = """
218
- ## 🏆 Leaderboard
219
-
220
- Vote to help the community determine the best text-to-speech (TTS) models.
221
-
222
- The leaderboard displays models in descending order of how natural they sound (based on votes cast by the community).
223
-
224
- Important: In order to help keep results fair, the leaderboard hides results by default until the number of votes passes a threshold. Tick the `Reveal preliminary results` to show models without sufficient votes. Please note that preliminary results may be inaccurate.
225
- """.strip()
226
-
227
-
228
-
229
-
230
- # def reload_audio_dataset():
231
- # global audio_dataset
232
- # audio_dataset = load_dataset(AUDIO_DATASET_ID)
233
- # return 'Reload Audio Dataset'
234
-
235
- def del_db(txt):
236
- if not txt.lower() == 'delete db':
237
- raise gr.Error('You did not enter "delete db"')
238
-
239
- # Delete local + remote
240
- os.remove(DB_PATH)
241
- delete_file(path_in_repo=DB_NAME, repo_id=DB_DATASET_ID, repo_type='dataset')
242
-
243
- # Recreate
244
- create_db_if_missing()
245
- return 'Delete DB'
246
-
247
- theme = gr.themes.Base(
248
- font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif'],
249
- )
250
-
251
- model_names = {
252
- 'styletts2': 'StyleTTS 2',
253
- 'tacotron': 'Tacotron',
254
- 'tacotronph': 'Tacotron Phoneme',
255
- 'tacotrondca': 'Tacotron DCA',
256
- 'speedyspeech': 'Speedy Speech',
257
- 'overflow': 'Overflow TTS',
258
- 'vits': 'VITS',
259
- 'vitsneon': 'VITS Neon',
260
- 'neuralhmm': 'Neural HMM',
261
- 'glow': 'Glow TTS',
262
- 'fastpitch': 'FastPitch',
263
- 'jenny': 'Jenny',
264
- 'tortoise': 'Tortoise TTS',
265
- 'xtts2': 'Coqui XTTSv2',
266
- 'xtts': 'Coqui XTTS',
267
- 'openvoice': 'MyShell OpenVoice',
268
- 'elevenlabs': 'ElevenLabs',
269
- 'openai': 'OpenAI',
270
- 'hierspeech': 'HierSpeech++',
271
- 'pheme': 'PolyAI Pheme',
272
- 'speecht5': 'SpeechT5',
273
- 'metavoice': 'MetaVoice-1B',
274
- }
275
- model_licenses = {
276
- 'styletts2': 'MIT',
277
- 'tacotron': 'BSD-3',
278
- 'tacotronph': 'BSD-3',
279
- 'tacotrondca': 'BSD-3',
280
- 'speedyspeech': 'BSD-3',
281
- 'overflow': 'MIT',
282
- 'vits': 'MIT',
283
- 'openvoice': 'MIT',
284
- 'vitsneon': 'BSD-3',
285
- 'neuralhmm': 'MIT',
286
- 'glow': 'MIT',
287
- 'fastpitch': 'Apache 2.0',
288
- 'jenny': 'Jenny License',
289
- 'tortoise': 'Apache 2.0',
290
- 'xtts2': 'CPML (NC)',
291
- 'xtts': 'CPML (NC)',
292
- 'elevenlabs': 'Proprietary',
293
- 'eleven': 'Proprietary',
294
- 'openai': 'Proprietary',
295
- 'hierspeech': 'MIT',
296
- 'pheme': 'CC-BY',
297
- 'speecht5': 'MIT',
298
- 'metavoice': 'Apache 2.0',
299
- 'elevenlabs': 'Proprietary',
300
- 'whisperspeech': 'MIT',
301
- }
302
- model_links = {
303
- 'styletts2': 'https://github.com/yl4579/StyleTTS2',
304
- 'tacotron': 'https://github.com/NVIDIA/tacotron2',
305
- 'speedyspeech': 'https://github.com/janvainer/speedyspeech',
306
- 'overflow': 'https://github.com/shivammehta25/OverFlow',
307
- 'vits': 'https://github.com/jaywalnut310/vits',
308
- 'openvoice': 'https://github.com/myshell-ai/OpenVoice',
309
- 'neuralhmm': 'https://github.com/ketranm/neuralHMM',
310
- 'glow': 'https://github.com/jaywalnut310/glow-tts',
311
- 'fastpitch': 'https://fastpitch.github.io/',
312
- 'tortoise': 'https://github.com/neonbjb/tortoise-tts',
313
- 'xtts2': 'https://huggingface.co/coqui/XTTS-v2',
314
- 'xtts': 'https://huggingface.co/coqui/XTTS-v1',
315
- 'elevenlabs': 'https://elevenlabs.io/',
316
- 'openai': 'https://help.openai.com/en/articles/8555505-tts-api',
317
- 'hierspeech': 'https://github.com/sh-lee-prml/HierSpeechpp',
318
- 'pheme': 'https://github.com/PolyAI-LDN/pheme',
319
- 'speecht5': 'https://github.com/microsoft/SpeechT5',
320
- 'metavoice': 'https://github.com/metavoiceio/metavoice-src',
321
- }
322
- # def get_random_split(existing_split=None):
323
- # choice = random.choice(list(audio_dataset.keys()))
324
- # if existing_split and choice == existing_split:
325
- # return get_random_split(choice)
326
- # else:
327
- # return choice
328
-
329
- # def get_random_splits():
330
- # choice1 = get_random_split()
331
- # choice2 = get_random_split(choice1)
332
- # return (choice1, choice2)
333
- def model_license(name):
334
- print(name)
335
- for k, v in AVAILABLE_MODELS.items():
336
- if k == name:
337
- if v in model_licenses:
338
- return model_licenses[v]
339
- print('---')
340
- return 'Unknown'
341
- def get_leaderboard(reveal_prelim = False):
342
- conn = get_db()
343
- cursor = conn.cursor()
344
- sql = 'SELECT name, upvote, downvote FROM model'
345
- # if not reveal_prelim: sql += ' WHERE EXISTS (SELECT 1 FROM model WHERE (upvote + downvote) > 750)'
346
- if not reveal_prelim: sql += ' WHERE (upvote + downvote) > 500'
347
- cursor.execute(sql)
348
- data = cursor.fetchall()
349
- df = pd.DataFrame(data, columns=['name', 'upvote', 'downvote'])
350
- # df['license'] = df['name'].map(model_license)
351
- df['name'] = df['name'].replace(model_names)
352
- df['votes'] = df['upvote'] + df['downvote']
353
- # df['score'] = round((df['upvote'] / df['votes']) * 100, 2) # Percentage score
354
-
355
- ## ELO SCORE
356
- df['score'] = 1200
357
- for i in range(len(df)):
358
- for j in range(len(df)):
359
- if i != j:
360
- expected_a = 1 / (1 + 10 ** ((df['score'][j] - df['score'][i]) / 400))
361
- expected_b = 1 / (1 + 10 ** ((df['score'][i] - df['score'][j]) / 400))
362
- actual_a = df['upvote'][i] / df['votes'][i]
363
- actual_b = df['upvote'][j] / df['votes'][j]
364
- df.at[i, 'score'] += 32 * (actual_a - expected_a)
365
- df.at[j, 'score'] += 32 * (actual_b - expected_b)
366
- df['score'] = round(df['score'])
367
- ## ELO SCORE
368
- df = df.sort_values(by='score', ascending=False)
369
- df['order'] = ['#' + str(i + 1) for i in range(len(df))]
370
- # df = df[['name', 'score', 'upvote', 'votes']]
371
- # df = df[['order', 'name', 'score', 'license', 'votes']]
372
- df = df[['order', 'name', 'score', 'votes']]
373
- return df
374
- def mkuuid(uid):
375
- if not uid:
376
- uid = uuid.uuid4()
377
- return uid
378
- def upvote_model(model, uname):
379
- conn = get_db()
380
- cursor = conn.cursor()
381
- cursor.execute('UPDATE model SET upvote = upvote + 1 WHERE name = ?', (model,))
382
- if cursor.rowcount == 0:
383
- cursor.execute('INSERT OR REPLACE INTO model (name, upvote, downvote) VALUES (?, 1, 0)', (model,))
384
- cursor.execute('INSERT INTO vote (username, model, vote) VALUES (?, ?, ?)', (uname, model, 1,))
385
- with scheduler.lock:
386
- conn.commit()
387
- cursor.close()
388
- def log_text(text):
389
- conn = get_db()
390
- cursor = conn.cursor()
391
- cursor.execute('INSERT INTO spokentext (spokentext) VALUES (?)', (text,))
392
- with scheduler.lock:
393
- conn.commit()
394
- cursor.close()
395
- def downvote_model(model, uname):
396
- conn = get_db()
397
- cursor = conn.cursor()
398
- cursor.execute('UPDATE model SET downvote = downvote + 1 WHERE name = ?', (model,))
399
- if cursor.rowcount == 0:
400
- cursor.execute('INSERT OR REPLACE INTO model (name, upvote, downvote) VALUES (?, 0, 1)', (model,))
401
- cursor.execute('INSERT INTO vote (username, model, vote) VALUES (?, ?, ?)', (uname, model, -1,))
402
- with scheduler.lock:
403
- conn.commit()
404
- cursor.close()
405
-
406
- def a_is_better(model1, model2, userid):
407
- print("A is better", model1, model2)
408
- if not model1 in AVAILABLE_MODELS.keys() and not model1 in AVAILABLE_MODELS.values():
409
- raise gr.Error('Sorry, please try voting again.')
410
- userid = mkuuid(userid)
411
- if model1 and model2:
412
- conn = get_db()
413
- cursor = conn.cursor()
414
- cursor.execute('INSERT INTO votelog (username, chosen, rejected) VALUES (?, ?, ?)', (str(userid), model1, model2,))
415
- with scheduler.lock:
416
- conn.commit()
417
- cursor.close()
418
- upvote_model(model1, str(userid))
419
- downvote_model(model2, str(userid))
420
- return reload(model1, model2, userid, chose_a=True)
421
- def b_is_better(model1, model2, userid):
422
- print("B is better", model1, model2)
423
- if not model1 in AVAILABLE_MODELS.keys() and not model1 in AVAILABLE_MODELS.values():
424
- raise gr.Error('Sorry, please try voting again.')
425
- userid = mkuuid(userid)
426
- if model1 and model2:
427
- conn = get_db()
428
- cursor = conn.cursor()
429
- cursor.execute('INSERT INTO votelog (username, chosen, rejected) VALUES (?, ?, ?)', (str(userid), model2, model1,))
430
- with scheduler.lock:
431
- conn.commit()
432
- cursor.close()
433
- upvote_model(model2, str(userid))
434
- downvote_model(model1, str(userid))
435
- return reload(model1, model2, userid, chose_b=True)
436
- def both_bad(model1, model2, userid):
437
- userid = mkuuid(userid)
438
- if model1 and model2:
439
- downvote_model(model1, str(userid))
440
- downvote_model(model2, str(userid))
441
- return reload(model1, model2, userid)
442
- def both_good(model1, model2, userid):
443
- userid = mkuuid(userid)
444
- if model1 and model2:
445
- upvote_model(model1, str(userid))
446
- upvote_model(model2, str(userid))
447
- return reload(model1, model2, userid)
448
- def reload(chosenmodel1=None, chosenmodel2=None, userid=None, chose_a=False, chose_b=False):
449
- # Select random splits
450
- # row = random.choice(list(audio_dataset['train']))
451
- # options = list(random.choice(list(audio_dataset['train'])).keys())
452
- # split1, split2 = random.sample(options, 2)
453
- # choice1, choice2 = (row[split1], row[split2])
454
- # if chosenmodel1 in model_names:
455
- # chosenmodel1 = model_names[chosenmodel1]
456
- # if chosenmodel2 in model_names:
457
- # chosenmodel2 = model_names[chosenmodel2]
458
- # out = [
459
- # (choice1['sampling_rate'], choice1['array']),
460
- # (choice2['sampling_rate'], choice2['array']),
461
- # split1,
462
- # split2
463
- # ]
464
- # if userid: out.append(userid)
465
- # if chosenmodel1: out.append(f'This model was {chosenmodel1}')
466
- # if chosenmodel2: out.append(f'This model was {chosenmodel2}')
467
- # return out
468
- # return (f'This model was {chosenmodel1}', f'This model was {chosenmodel2}', gr.update(visible=False), gr.update(visible=False))
469
- # return (gr.update(variant='secondary', value=chosenmodel1, interactive=False), gr.update(variant='secondary', value=chosenmodel2, interactive=False))
470
- out = [
471
- gr.update(interactive=False, visible=False),
472
- gr.update(interactive=False, visible=False)
473
- ]
474
- if chose_a == True:
475
- out.append(gr.update(value=f'Your vote: {chosenmodel1}', interactive=False, visible=True))
476
- out.append(gr.update(value=f'{chosenmodel2}', interactive=False, visible=True))
477
- else:
478
- out.append(gr.update(value=f'{chosenmodel1}', interactive=False, visible=True))
479
- out.append(gr.update(value=f'Your vote: {chosenmodel2}', interactive=False, visible=True))
480
- out.append(gr.update(visible=True))
481
- return out
482
-
483
- with gr.Blocks() as leaderboard:
484
- gr.Markdown(LDESC)
485
- # df = gr.Dataframe(interactive=False, value=get_leaderboard())
486
- df = gr.Dataframe(interactive=False, min_width=0, wrap=True, column_widths=[30, 200, 50, 50])
487
- with gr.Row():
488
- reveal_prelim = gr.Checkbox(label="Reveal preliminary results", info="Show all models, including models with very few human ratings.", scale=1)
489
- reloadbtn = gr.Button("Refresh", scale=3)
490
- reveal_prelim.input(get_leaderboard, inputs=[reveal_prelim], outputs=[df])
491
- leaderboard.load(get_leaderboard, inputs=[reveal_prelim], outputs=[df])
492
- reloadbtn.click(get_leaderboard, inputs=[reveal_prelim], outputs=[df])
493
- # gr.Markdown("DISCLAIMER: The licenses listed may not be accurate or up to date, you are responsible for checking the licenses before using the models. Also note that some models may have additional usage restrictions.")
494
-
495
- # with gr.Blocks() as vote:
496
- # useridstate = gr.State()
497
- # gr.Markdown(INSTR)
498
- # # gr.LoginButton()
499
- # with gr.Row():
500
- # gr.HTML('<div align="left"><h3>Model A</h3></div>')
501
- # gr.HTML('<div align="right"><h3>Model B</h3></div>')
502
- # model1 = gr.Textbox(interactive=False, visible=False, lines=1, max_lines=1)
503
- # model2 = gr.Textbox(interactive=False, visible=False, lines=1, max_lines=1)
504
- # # with gr.Group():
505
- # # with gr.Row():
506
- # # prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A")
507
- # # prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="right")
508
- # # with gr.Row():
509
- # # aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
510
- # # aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
511
- # with gr.Group():
512
- # with gr.Row():
513
- # with gr.Column():
514
- # with gr.Group():
515
- # prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A", lines=1, max_lines=1)
516
- # aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
517
- # with gr.Column():
518
- # with gr.Group():
519
- # prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="right", lines=1, max_lines=1)
520
- # aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
521
-
522
-
523
- # with gr.Row():
524
- # abetter = gr.Button("A is Better", variant='primary', scale=4)
525
- # # skipbtn = gr.Button("Skip", scale=1)
526
- # bbetter = gr.Button("B is Better", variant='primary', scale=4)
527
- # with gr.Row():
528
- # bothbad = gr.Button("Both are Bad", scale=2)
529
- # skipbtn = gr.Button("Skip", scale=1)
530
- # bothgood = gr.Button("Both are Good", scale=2)
531
- # outputs = [aud1, aud2, model1, model2, useridstate, prevmodel1, prevmodel2]
532
- # abetter.click(a_is_better, outputs=outputs, inputs=[model1, model2, useridstate])
533
- # bbetter.click(b_is_better, outputs=outputs, inputs=[model1, model2, useridstate])
534
- # skipbtn.click(b_is_better, outputs=outputs, inputs=[model1, model2, useridstate])
535
-
536
- # bothbad.click(both_bad, outputs=outputs, inputs=[model1, model2, useridstate])
537
- # bothgood.click(both_good, outputs=outputs, inputs=[model1, model2, useridstate])
538
-
539
- # vote.load(reload, outputs=[aud1, aud2, model1, model2])
540
- def doloudnorm(path):
541
- data, rate = sf.read(path)
542
- meter = pyln.Meter(rate)
543
- loudness = meter.integrated_loudness(data)
544
- loudness_normalized_audio = pyln.normalize.loudness(data, loudness, -12.0)
545
- sf.write(path, loudness_normalized_audio, rate)
546
-
547
- def doresample(path_to_wav):
548
- pass
549
- ##########################
550
- # 2x speedup (hopefully) #
551
- ##########################
552
-
553
- def synthandreturn(text):
554
- text = text.strip()
555
- if len(text) > MAX_SAMPLE_TXT_LENGTH:
556
- raise gr.Error(f'You exceeded the limit of {MAX_SAMPLE_TXT_LENGTH} characters')
557
- if len(text) < MIN_SAMPLE_TXT_LENGTH:
558
- raise gr.Error(f'Please input a text longer than {MIN_SAMPLE_TXT_LENGTH} characters')
559
- if (
560
- # test toxicity if not prepared text
561
- text not in sents
562
- and toxicity.predict(text)['toxicity'] > 0.8
563
- ):
564
- print(f'Detected toxic content! "{text}"')
565
- raise gr.Error('Your text failed the toxicity test')
566
- if not text:
567
- raise gr.Error(f'You did not enter any text')
568
- # Check language
569
- try:
570
- if not detect(text) == "en":
571
- gr.Warning('Warning: The input text may not be in English')
572
- except:
573
- pass
574
- # Get two random models
575
- mdl1, mdl2 = random.sample(list(AVAILABLE_MODELS.keys()), 2)
576
- log_text(text)
577
- print("[debug] Using", mdl1, mdl2)
578
- def predict_and_update_result(text, model, result_storage):
579
- try:
580
- if model in AVAILABLE_MODELS:
581
- result = router.predict(text, AVAILABLE_MODELS[model].lower(), api_name="/synthesize")
582
- else:
583
- result = router.predict(text, model.lower(), api_name="/synthesize")
584
- except:
585
- raise gr.Error('Unable to call API, please try again :)')
586
- print('Done with', model)
587
- # try:
588
- # doresample(result)
589
- # except:
590
- # pass
591
- try:
592
- with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
593
- audio = AudioSegment.from_file(result)
594
- current_sr = audio.frame_rate
595
- if current_sr > 24000:
596
- audio = audio.set_frame_rate(24000)
597
- try:
598
- print('Trying to normalize audio')
599
- audio = match_target_amplitude(audio, -20)
600
- except:
601
- print('[WARN] Unable to normalize audio')
602
- audio.export(f.name, format="wav")
603
- os.unlink(result)
604
- result = f.name
605
- except:
606
- pass
607
- if model in AVAILABLE_MODELS.keys(): model = AVAILABLE_MODELS[model]
608
- print(model)
609
- print(f"Running model {model}")
610
- result_storage[model] = result
611
- # try:
612
- # doloudnorm(result)
613
- # except:
614
- # pass
615
- mdl1k = mdl1
616
- mdl2k = mdl2
617
- print(mdl1k, mdl2k)
618
- if mdl1 in AVAILABLE_MODELS.keys(): mdl1k=AVAILABLE_MODELS[mdl1]
619
- if mdl2 in AVAILABLE_MODELS.keys(): mdl2k=AVAILABLE_MODELS[mdl2]
620
- results = {}
621
- print(f"Sending models {mdl1k} and {mdl2k} to API")
622
- thread1 = threading.Thread(target=predict_and_update_result, args=(text, mdl1k, results))
623
- thread2 = threading.Thread(target=predict_and_update_result, args=(text, mdl2k, results))
624
-
625
- thread1.start()
626
- thread2.start()
627
- thread1.join()
628
- thread2.join()
629
- #debug
630
- # print(results)
631
- # print(list(results.keys())[0])
632
- # y, sr = librosa.load(results[list(results.keys())[0]], sr=None)
633
- # print(sr)
634
- # print(list(results.keys())[1])
635
- # y, sr = librosa.load(results[list(results.keys())[1]], sr=None)
636
- # print(sr)
637
- #debug
638
- # outputs = [text, btn, r2, model1, model2, aud1, aud2, abetter, bbetter, prevmodel1, prevmodel2, nxtroundbtn]
639
-
640
- print(f"Retrieving models {mdl1k} and {mdl2k} from API")
641
- return (
642
- text,
643
- "Synthesize",
644
- gr.update(visible=True), # r2
645
- mdl1, # model1
646
- mdl2, # model2
647
- gr.update(visible=True, value=results[mdl1k]), # aud1
648
- gr.update(visible=True, value=results[mdl2k]), # aud2
649
- gr.update(visible=True, interactive=False), #abetter
650
- gr.update(visible=True, interactive=False), #bbetter
651
- gr.update(visible=False), #prevmodel1
652
- gr.update(visible=False), #prevmodel2
653
- gr.update(visible=False), #nxt round btn
654
- )
655
- # return (
656
- # text,
657
- # "Synthesize",
658
- # gr.update(visible=True), # r2
659
- # mdl1, # model1
660
- # mdl2, # model2
661
- # # 'Vote to reveal model A', # prevmodel1
662
- # gr.update(visible=True, value=router.predict(
663
- # text,
664
- # AVAILABLE_MODELS[mdl1],
665
- # api_name="/synthesize"
666
- # )), # aud1
667
- # # 'Vote to reveal model B', # prevmodel2
668
- # gr.update(visible=True, value=router.predict(
669
- # text,
670
- # AVAILABLE_MODELS[mdl2],
671
- # api_name="/synthesize"
672
- # )), # aud2
673
- # gr.update(visible=True, interactive=True),
674
- # gr.update(visible=True, interactive=True),
675
- # gr.update(visible=False),
676
- # gr.update(visible=False),
677
- # gr.update(visible=False), #nxt round btn
678
- # )
679
-
680
- def unlock_vote(btn_index, aplayed, bplayed):
681
- # sample played
682
- if btn_index == 0:
683
- aplayed = gr.State(value=True)
684
- if btn_index == 1:
685
- bplayed = gr.State(value=True)
686
-
687
- # both audio samples played
688
- if bool(aplayed) and bool(bplayed):
689
- print('Both audio samples played, voting unlocked')
690
- return [gr.update(interactive=True), gr.update(interactive=True), gr.update(), gr.update()]
691
-
692
- return [gr.update(), gr.update(), aplayed, bplayed]
693
-
694
- def randomsent():
695
- return random.choice(sents), '🎲'
696
- def clear_stuff():
697
- return "", "Synthesize", gr.update(visible=False), '', '', gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
698
-
699
- def disable():
700
- return [gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False)]
701
- def enable():
702
- return [gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)]
703
- with gr.Blocks() as vote:
704
- # sample played
705
- #aplayed = gr.State(value=False)
706
- #bplayed = gr.State(value=False)
707
- # voter ID
708
- useridstate = gr.State()
709
- gr.Markdown(INSTR)
710
- with gr.Group():
711
- with gr.Row():
712
- text = gr.Textbox(container=False, show_label=False, placeholder="Enter text to synthesize", lines=1, max_lines=1, scale=9999999, min_width=0)
713
- randomt = gr.Button('🎲', scale=0, min_width=0, variant='tool')
714
- randomt.click(randomsent, outputs=[text, randomt])
715
- btn = gr.Button("Synthesize", variant='primary')
716
- model1 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
717
- #model1 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=True)
718
- model2 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
719
- #model2 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=True)
720
- with gr.Row(visible=False) as r2:
721
- with gr.Column():
722
- with gr.Group():
723
- aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
724
- abetter = gr.Button("A is better", variant='primary')
725
- prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A", text_align="center", lines=1, max_lines=1, visible=False)
726
- with gr.Column():
727
- with gr.Group():
728
- aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
729
- bbetter = gr.Button("B is better", variant='primary')
730
- prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="center", lines=1, max_lines=1, visible=False)
731
- nxtroundbtn = gr.Button('Next round', visible=False)
732
- # outputs = [text, btn, r2, model1, model2, prevmodel1, aud1, prevmodel2, aud2, abetter, bbetter]
733
- outputs = [
734
- text,
735
- btn,
736
- r2,
737
- model1,
738
- model2,
739
- aud1,
740
- aud2,
741
- abetter,
742
- bbetter,
743
- prevmodel1,
744
- prevmodel2,
745
- nxtroundbtn
746
- ]
747
- """
748
- text,
749
- "Synthesize",
750
- gr.update(visible=True), # r2
751
- mdl1, # model1
752
- mdl2, # model2
753
- gr.update(visible=True, value=results[mdl1]), # aud1
754
- gr.update(visible=True, value=results[mdl2]), # aud2
755
- gr.update(visible=True, interactive=False), #abetter
756
- gr.update(visible=True, interactive=False), #bbetter
757
- gr.update(visible=False), #prevmodel1
758
- gr.update(visible=False), #prevmodel2
759
- gr.update(visible=False), #nxt round btn"""
760
- btn.click(disable, outputs=[btn, abetter, bbetter]).then(synthandreturn, inputs=[text], outputs=outputs).then(enable, outputs=[btn, abetter, bbetter])
761
- nxtroundbtn.click(clear_stuff, outputs=outputs)
762
-
763
- # Allow interaction with the vote buttons only when both audio samples have finished playing
764
- #aud1.stop(unlock_vote, outputs=[abetter, bbetter, aplayed, bplayed], inputs=[gr.State(value=0), aplayed, bplayed])
765
- #aud2.stop(unlock_vote, outputs=[abetter, bbetter, aplayed, bplayed], inputs=[gr.State(value=1), aplayed, bplayed])
766
-
767
- # nxt_outputs = [prevmodel1, prevmodel2, abetter, bbetter]
768
- nxt_outputs = [abetter, bbetter, prevmodel1, prevmodel2, nxtroundbtn]
769
- abetter.click(a_is_better, outputs=nxt_outputs, inputs=[model1, model2, useridstate])
770
- bbetter.click(b_is_better, outputs=nxt_outputs, inputs=[model1, model2, useridstate])
771
- # skipbtn.click(b_is_better, outputs=outputs, inputs=[model1, model2, useridstate])
772
-
773
- # bothbad.click(both_bad, outputs=outputs, inputs=[model1, model2, useridstate])
774
- # bothgood.click(both_good, outputs=outputs, inputs=[model1, model2, useridstate])
775
-
776
- # vote.load(reload, outputs=[aud1, aud2, model1, model2])
777
-
778
- with gr.Blocks() as about:
779
- gr.Markdown(ABOUT)
780
- # with gr.Blocks() as admin:
781
- # rdb = gr.Button("Reload Audio Dataset")
782
- # # rdb.click(reload_audio_dataset, outputs=rdb)
783
- # with gr.Group():
784
- # dbtext = gr.Textbox(label="Type \"delete db\" to confirm", placeholder="delete db")
785
- # ddb = gr.Button("Delete DB")
786
- # ddb.click(del_db, inputs=dbtext, outputs=ddb)
787
- with gr.Blocks(theme=theme, css="footer {visibility: hidden}textbox{resize:none}", title="TTS Arena") as demo:
788
- gr.Markdown(DESCR)
789
- # gr.TabbedInterface([vote, leaderboard, about, admin], ['Vote', 'Leaderboard', 'About', 'Admin (ONLY IN BETA)'])
790
- gr.TabbedInterface([vote, leaderboard, about], ['🗳️ Vote', '🏆 Leaderboard', '📄 About'])
791
- if CITATION_TEXT:
792
- with gr.Row():
793
- with gr.Accordion("Citation", open=False):
794
- gr.Markdown(f"If you use this data in your publication, please cite us!\n\nCopy the BibTeX citation to cite this source:\n\n```bibtext\n{CITATION_TEXT}\n```\n\nPlease remember that all generated audio clips should be assumed unsuitable for redistribution or commercial use.")
795
-
796
-
797
- demo.queue(api_open=False, default_concurrency_limit=40).launch(show_api=False)
 
1
+ from app.ui import app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ if __name__ == "__main__":
4
+ app.queue(default_concurrency_limit=50, api_open=False).launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/__init__.py ADDED
File without changes
app/config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # NOTE: Configure models in `models.py`
4
+
5
+ #########################
6
+ # General Configuration #
7
+ #########################
8
+
9
+ DB_NAME = "database.db"
10
+
11
+ TOXICITY_CHECK = False
12
+
13
+ MAX_SAMPLE_TXT_LENGTH = 300 # Maximum text length (characters)
14
+ MIN_SAMPLE_TXT_LENGTH = 10 # Minimum text length (characters)
15
+
16
+ DB_PATH = f"/data/{DB_NAME}" if os.path.isdir("/data") else DB_NAME # If /data available => means local storage is enabled => let's use it!
17
+
18
+ ROUTER_ID = "TTS-AGI/tts-router" # You should use a router space to route TTS models to avoid exposing your API keys!
19
+
20
+ SYNC_DB = True # Sync DB to HF dataset?
21
+ DB_DATASET_ID = os.getenv('DATASET_ID') # HF dataset ID, can be None if not syncing
22
+
23
+ SPACE_ID = os.getenv('SPACE_ID') # Don't change this! It detects if we're running in a HF Space
24
+
25
+ with open(os.path.dirname(__file__) + '/../harvard_sentences.txt', 'r') as f:
26
+ sents = f.read().strip().splitlines()
27
+
28
+ ######################
29
+ # TTS Arena Settings #
30
+ ######################
31
+
32
+ CITATION_TEXT = """@misc{tts-arena,
33
+ title = {Text to Speech Arena},
34
+ author = {mrfakename and Srivastav, Vaibhav and Fourrier, Clémentine and Pouget, Lucain and Lacombe, Yoach and main and Gandhi, Sanchit},
35
+ year = 2024,
36
+ publisher = {Hugging Face},
37
+ howpublished = "\\url{https://huggingface.co/spaces/TTS-AGI/TTS-Arena}"
38
+ }"""
app/db.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ from .config import *
3
+ import os
4
+ import shutil
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ def download_db():
8
+ if not os.path.isfile(DB_PATH):
9
+ print("Downloading DB...")
10
+ try:
11
+ cache_path = hf_hub_download(repo_id=DB_DATASET_ID, repo_type='dataset', filename=DB_NAME)
12
+ shutil.copyfile(cache_path, DB_PATH)
13
+ print("Downloaded DB")
14
+ except Exception as e:
15
+ print("Error while downloading DB:", e)
16
+
17
+ def get_db():
18
+ return sqlite3.connect(DB_PATH)
19
+
20
+ def create_db():
21
+ conn = get_db()
22
+ cursor = conn.cursor()
23
+ cursor.execute('''
24
+ CREATE TABLE IF NOT EXISTS model (
25
+ name TEXT UNIQUE,
26
+ upvote INTEGER,
27
+ downvote INTEGER
28
+ );
29
+ ''')
30
+ cursor.execute('''
31
+ CREATE TABLE IF NOT EXISTS vote (
32
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
33
+ username TEXT,
34
+ model TEXT,
35
+ vote INTEGER,
36
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
37
+ );
38
+ ''')
39
+ cursor.execute('''
40
+ CREATE TABLE IF NOT EXISTS votelog (
41
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
42
+ username TEXT,
43
+ chosen TEXT,
44
+ rejected TEXT,
45
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
46
+ );
47
+ ''')
48
+ cursor.execute('''
49
+ CREATE TABLE IF NOT EXISTS spokentext (
50
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
51
+ spokentext TEXT,
52
+ timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
53
+ );
54
+ ''')
app/init.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .config import *
2
+ from .db import *
3
+ from huggingface_hub import CommitScheduler
4
+ from pathlib import Path
5
+ from gradio_client import Client
6
+ import os
7
+
8
+
9
+ scheduler = None
10
+
11
+ if SYNC_DB:
12
+ download_db()
13
+ # Sync local DB with remote repo every 5 minute (only if a change is detected)
14
+ scheduler = CommitScheduler(
15
+ repo_id=DB_DATASET_ID,
16
+ repo_type="dataset",
17
+ folder_path=Path(DB_PATH).parent,
18
+ every=5,
19
+ allow_patterns=DB_NAME,
20
+ )
21
+
22
+ create_db()
23
+
24
+ # Load TTS Router
25
+ router = Client(ROUTER_ID, hf_token=os.getenv('HF_TOKEN'))
26
+
27
+ if TOXICITY_CHECK:
28
+ # Load toxicity model
29
+ from detoxify import Detoxify
30
+ toxicity = Detoxify('original')
app/leaderboard.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .config import *
2
+ from .db import *
3
+ from .models import *
4
+
5
+ import pandas as pd
6
+ def get_leaderboard(reveal_prelim = False, hide_battle_votes = False):
7
+ conn = get_db()
8
+ cursor = conn.cursor()
9
+
10
+ if hide_battle_votes:
11
+ sql = '''
12
+ SELECT m.name,
13
+ SUM(CASE WHEN v.username NOT LIKE '%_battle' AND v.vote = 1 THEN 1 ELSE 0 END) as upvote,
14
+ SUM(CASE WHEN v.username NOT LIKE '%_battle' AND v.vote = -1 THEN 1 ELSE 0 END) as downvote
15
+ FROM model m
16
+ LEFT JOIN vote v ON m.name = v.model
17
+ GROUP BY m.name
18
+ '''
19
+ else:
20
+ sql = '''
21
+ SELECT name,
22
+ SUM(CASE WHEN vote = 1 THEN 1 ELSE 0 END) as upvote,
23
+ SUM(CASE WHEN vote = -1 THEN 1 ELSE 0 END) as downvote
24
+ FROM model
25
+ LEFT JOIN vote ON model.name = vote.model
26
+ GROUP BY name
27
+ '''
28
+
29
+ cursor.execute(sql)
30
+ data = cursor.fetchall()
31
+ df = pd.DataFrame(data, columns=['name', 'upvote', 'downvote'])
32
+ df['name'] = df['name'].replace(model_names)
33
+ df['votes'] = df['upvote'] + df['downvote']
34
+
35
+ # Filter out rows with insufficient votes if not revealing preliminary results
36
+ if not reveal_prelim:
37
+ df = df[df['votes'] > 500]
38
+
39
+ ## ELO SCORE
40
+ df['score'] = 1200
41
+ for i in range(len(df)):
42
+ for j in range(len(df)):
43
+ if i != j:
44
+ expected_a = 1 / (1 + 10 ** ((df['score'][j] - df['score'][i]) / 400))
45
+ expected_b = 1 / (1 + 10 ** ((df['score'][i] - df['score'][j]) / 400))
46
+ actual_a = df['upvote'][i] / df['votes'][i] if df['votes'][i] > 0 else 0.5
47
+ actual_b = df['upvote'][j] / df['votes'][j] if df['votes'][j] > 0 else 0.5
48
+ df.at[i, 'score'] += 32 * (actual_a - expected_a)
49
+ df.at[j, 'score'] += 32 * (actual_b - expected_b)
50
+ df['score'] = round(df['score'])
51
+ ## ELO SCORE
52
+ df = df.sort_values(by='score', ascending=False)
53
+ df['order'] = ['#' + str(i + 1) for i in range(len(df))]
54
+ df = df[['order', 'name', 'score', 'votes']]
55
+ return df
app/messages.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .config import *
2
+
3
+ ############
4
+ # Messages #
5
+ ############
6
+
7
+ MUST_BE_LOGGEDIN = "Please login with Hugging Face to participate in the TTS Arena."
8
+ DESCR = """
9
+ # TTS Arena: Benchmarking TTS Models in the Wild
10
+ Vote to help the community find the best available text-to-speech model!
11
+ """.strip()
12
+ BATTLE_INSTR = """
13
+ ## Battle
14
+ Choose 2 candidates and vote on which one is better! Currently in beta.
15
+ * Input text (English only) to synthesize audio (or press 🎲 for random text).
16
+ * Listen to the two audio clips, one after the other.
17
+ * Vote on which audio sounds more natural to you.
18
+ """
19
+ INSTR = """
20
+ ## Vote
21
+ * Input text (English only) to synthesize audio (or press 🎲 for random text).
22
+ * Listen to the two audio clips, one after the other.
23
+ * Vote on which audio sounds more natural to you.
24
+ * _Note: Model names are revealed after the vote is cast._
25
+ Note: It may take up to 30 seconds to synthesize audio.
26
+ """.strip()
27
+ request = ""
28
+ if SPACE_ID:
29
+ request = f"""
30
+ ### Request a model
31
+ Please [create a Discussion](https://huggingface.co/spaces/{SPACE_ID}/discussions/new) to request a model.
32
+ """
33
+ ABOUT = f"""
34
+ ## About
35
+ The TTS Arena evaluates leading speech synthesis models. It is inspired by LMsys's [Chatbot Arena](https://chat.lmsys.org/).
36
+ ### Motivation
37
+ The field of speech synthesis has long lacked an accurate method to measure the quality of different models. Objective metrics like WER (word error rate) are unreliable measures of model quality, and subjective measures such as MOS (mean opinion score) are typically small-scale experiments conducted with few listeners. As a result, these measurements are generally not useful for comparing two models of roughly similar quality. To address these drawbacks, we are inviting the community to rank models in an easy-to-use interface, and opening it up to the public in order to make both the opportunity to rank models, as well as the results, more easily accessible to everyone.
38
+ ### The Arena
39
+ The leaderboard allows a user to enter text, which will be synthesized by two models. After listening to each sample, the user can vote on which model sounds more natural. Due to the risks of human bias and abuse, model names are revealed only after a vote is submitted.
40
+ ### Credits
41
+ Thank you to the following individuals who helped make this project possible:
42
+ * VB ([Twitter](https://twitter.com/reach_vb) / [Hugging Face](https://huggingface.co/reach-vb))
43
+ * Clémentine Fourrier ([Twitter](https://twitter.com/clefourrier) / [Hugging Face](https://huggingface.co/clefourrier))
44
+ * Lucain Pouget ([Twitter](https://twitter.com/Wauplin) / [Hugging Face](https://huggingface.co/Wauplin))
45
+ * Yoach Lacombe ([Twitter](https://twitter.com/yoachlacombe) / [Hugging Face](https://huggingface.co/ylacombe))
46
+ * Main Horse ([Twitter](https://twitter.com/main_horse) / [Hugging Face](https://huggingface.co/main-horse))
47
+ * Sanchit Gandhi ([Twitter](https://twitter.com/sanchitgandhi99) / [Hugging Face](https://huggingface.co/sanchit-gandhi))
48
+ * Apolinário Passos ([Twitter](https://twitter.com/multimodalart) / [Hugging Face](https://huggingface.co/multimodalart))
49
+ * Pedro Cuenca ([Twitter](https://twitter.com/pcuenq) / [Hugging Face](https://huggingface.co/pcuenq))
50
+ {request}
51
+ ### Privacy statement
52
+ We may store text you enter and generated audio. We store a unique ID for each session. You agree that we may collect, share, and/or publish any data you input for research and/or commercial purposes.
53
+ ### License
54
+ Generated audio clips cannot be redistributed and may be used for personal, non-commercial use only.
55
+ Random sentences are sourced from a filtered subset of the [Harvard Sentences](https://www.cs.columbia.edu/~hgs/audio/harvard.html).
56
+ """.strip()
57
+ LDESC = """
58
+ ## 🏆 Leaderboard
59
+ Vote to help the community determine the best text-to-speech (TTS) models.
60
+ The leaderboard displays models in descending order of how natural they sound (based on votes cast by the community).
61
+ Important: In order to help keep results fair, the leaderboard hides results by default until the number of votes passes a threshold. Tick the `Reveal preliminary results` to show models without sufficient votes. Please note that preliminary results may be inaccurate.
62
+ """.strip()
app/models.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Models to include in the leaderboard, only include models that users can vote on
2
+ AVAILABLE_MODELS = {
3
+ 'XTTSv2': 'xtts',
4
+ # 'WhisperSpeech': 'whisperspeech',
5
+ 'ElevenLabs': 'eleven',
6
+ # 'OpenVoice': 'openvoice',
7
+ 'OpenVoice V2': 'openvoicev2',
8
+ 'Play.HT 2.0': 'playht',
9
+ 'Play.HT 3.0 Mini': 'playht3',
10
+ # 'MetaVoice': 'metavoice',
11
+ 'MeloTTS': 'melo',
12
+ 'StyleTTS 2': 'styletts2',
13
+ 'GPT-SoVITS': 'sovits',
14
+ # 'Vokan TTS': 'vokan',
15
+ 'VoiceCraft 2.0': 'voicecraft',
16
+ 'Parler TTS': 'parler',
17
+ 'Parler TTS Large': 'parlerlarge',
18
+ 'Fish Speech v1.4': 'fish',
19
+ }
20
+
21
+
22
+ # Model name mapping, can include models that users cannot vote on
23
+ model_names = {
24
+ 'styletts2': 'StyleTTS 2',
25
+ 'tacotron': 'Tacotron',
26
+ 'tacotronph': 'Tacotron Phoneme',
27
+ 'tacotrondca': 'Tacotron DCA',
28
+ 'speedyspeech': 'Speedy Speech',
29
+ 'overflow': 'Overflow TTS',
30
+ 'vits': 'VITS',
31
+ 'vitsneon': 'VITS Neon',
32
+ 'neuralhmm': 'Neural HMM',
33
+ 'glow': 'Glow TTS',
34
+ 'fastpitch': 'FastPitch',
35
+ 'jenny': 'Jenny',
36
+ 'tortoise': 'Tortoise TTS',
37
+ 'xtts2': 'Coqui XTTSv2',
38
+ 'xtts': 'Coqui XTTS',
39
+ 'openvoice': 'MyShell OpenVoice',
40
+ 'elevenlabs': 'ElevenLabs',
41
+ 'openai': 'OpenAI',
42
+ 'hierspeech': 'HierSpeech++',
43
+ 'pheme': 'PolyAI Pheme',
44
+ 'speecht5': 'SpeechT5',
45
+ 'metavoice': 'MetaVoice-1B',
46
+ }
app/synth.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .models import *
2
+ from .utils import *
3
+ from .config import *
4
+ from .init import *
5
+
6
+ import gradio as gr
7
+ from pydub import AudioSegment
8
+ import random, os, threading, tempfile
9
+ from langdetect import detect
10
+ from .vote import log_text
11
+
12
+ def random_m():
13
+ return random.sample(list(set(AVAILABLE_MODELS.keys())), 2)
14
+
15
+ def check_toxicity(text):
16
+ if not TOXICITY_CHECK:
17
+ return False
18
+ return toxicity.predict(text)['toxicity'] > 0.8
19
+
20
+ def synthandreturn(text):
21
+ text = text.strip()
22
+ if len(text) > MAX_SAMPLE_TXT_LENGTH:
23
+ raise gr.Error(f'You exceeded the limit of {MAX_SAMPLE_TXT_LENGTH} characters')
24
+ if len(text) < MIN_SAMPLE_TXT_LENGTH:
25
+ raise gr.Error(f'Please input a text longer than {MIN_SAMPLE_TXT_LENGTH} characters')
26
+ if (
27
+ # test toxicity if not prepared text
28
+ text not in sents
29
+ and check_toxicity(text)
30
+ ):
31
+ print(f'Detected toxic content! "{text}"')
32
+ raise gr.Error('Your text failed the toxicity test')
33
+ if not text:
34
+ raise gr.Error(f'You did not enter any text')
35
+ # Check language
36
+ try:
37
+ if not detect(text) == "en":
38
+ gr.Warning('Warning: The input text may not be in English')
39
+ except:
40
+ pass
41
+ # Get two random models
42
+ mdl1, mdl2 = random.sample(list(AVAILABLE_MODELS.keys()), 2)
43
+ log_text(text)
44
+ print("[debug] Using", mdl1, mdl2)
45
+ def predict_and_update_result(text, model, result_storage):
46
+ try:
47
+ if model in AVAILABLE_MODELS:
48
+ result = router.predict(text, AVAILABLE_MODELS[model].lower(), api_name="/synthesize")
49
+ else:
50
+ result = router.predict(text, model.lower(), api_name="/synthesize")
51
+ except:
52
+ raise gr.Error('Unable to call API, please try again :)')
53
+ print('Done with', model)
54
+ # try:
55
+ # doresample(result)
56
+ # except:
57
+ # pass
58
+ try:
59
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
60
+ audio = AudioSegment.from_file(result)
61
+ current_sr = audio.frame_rate
62
+ if current_sr > 24000:
63
+ audio = audio.set_frame_rate(24000)
64
+ try:
65
+ print('Trying to normalize audio')
66
+ audio = match_target_amplitude(audio, -20)
67
+ except:
68
+ print('[WARN] Unable to normalize audio')
69
+ audio.export(f.name, format="wav")
70
+ os.unlink(result)
71
+ result = f.name
72
+ except:
73
+ pass
74
+ if model in AVAILABLE_MODELS.keys(): model = AVAILABLE_MODELS[model]
75
+ print(model)
76
+ print(f"Running model {model}")
77
+ result_storage[model] = result
78
+ # try:
79
+ # doloudnorm(result)
80
+ # except:
81
+ # pass
82
+ mdl1k = mdl1
83
+ mdl2k = mdl2
84
+ print(mdl1k, mdl2k)
85
+ if mdl1 in AVAILABLE_MODELS.keys(): mdl1k=AVAILABLE_MODELS[mdl1]
86
+ if mdl2 in AVAILABLE_MODELS.keys(): mdl2k=AVAILABLE_MODELS[mdl2]
87
+ results = {}
88
+ print(f"Sending models {mdl1k} and {mdl2k} to API")
89
+ thread1 = threading.Thread(target=predict_and_update_result, args=(text, mdl1k, results))
90
+ thread2 = threading.Thread(target=predict_and_update_result, args=(text, mdl2k, results))
91
+
92
+ thread1.start()
93
+ thread2.start()
94
+ thread1.join()
95
+ thread2.join()
96
+ #debug
97
+ # print(results)
98
+ # print(list(results.keys())[0])
99
+ # y, sr = librosa.load(results[list(results.keys())[0]], sr=None)
100
+ # print(sr)
101
+ # print(list(results.keys())[1])
102
+ # y, sr = librosa.load(results[list(results.keys())[1]], sr=None)
103
+ # print(sr)
104
+ #debug
105
+ # outputs = [text, btn, r2, model1, model2, aud1, aud2, abetter, bbetter, prevmodel1, prevmodel2, nxtroundbtn]
106
+
107
+ print(f"Retrieving models {mdl1k} and {mdl2k} from API")
108
+ return (
109
+ text,
110
+ "Synthesize",
111
+ gr.update(visible=True), # r2
112
+ mdl1, # model1
113
+ mdl2, # model2
114
+ gr.update(visible=True, value=results[mdl1k]), # aud1
115
+ gr.update(visible=True, value=results[mdl2k]), # aud2
116
+ gr.update(visible=True, interactive=False), #abetter
117
+ gr.update(visible=True, interactive=False), #bbetter
118
+ gr.update(visible=False), #prevmodel1
119
+ gr.update(visible=False), #prevmodel2
120
+ gr.update(visible=False), #nxt round btn
121
+ )
122
+
123
+ # Battle Mode
124
+
125
+ def synthandreturn_battle(text, mdl1, mdl2):
126
+ if mdl1 == mdl2:
127
+ raise gr.Error('You can\'t pick two of the same models.')
128
+ text = text.strip()
129
+ if len(text) > MAX_SAMPLE_TXT_LENGTH:
130
+ raise gr.Error(f'You exceeded the limit of {MAX_SAMPLE_TXT_LENGTH} characters')
131
+ if len(text) < MIN_SAMPLE_TXT_LENGTH:
132
+ raise gr.Error(f'Please input a text longer than {MIN_SAMPLE_TXT_LENGTH} characters')
133
+ if (
134
+ # test toxicity if not prepared text
135
+ text not in sents
136
+ and check_toxicity(text)
137
+ ):
138
+ print(f'Detected toxic content! "{text}"')
139
+ raise gr.Error('Your text failed the toxicity test')
140
+ if not text:
141
+ raise gr.Error(f'You did not enter any text')
142
+ # Check language
143
+ try:
144
+ if not detect(text) == "en":
145
+ gr.Warning('Warning: The input text may not be in English')
146
+ except:
147
+ pass
148
+ # Get two random models
149
+ log_text(text)
150
+ print("[debug] Using", mdl1, mdl2)
151
+ def predict_and_update_result(text, model, result_storage):
152
+ try:
153
+ if model in AVAILABLE_MODELS:
154
+ result = router.predict(text, AVAILABLE_MODELS[model].lower(), api_name="/synthesize")
155
+ else:
156
+ result = router.predict(text, model.lower(), api_name="/synthesize")
157
+ except:
158
+ raise gr.Error('Unable to call API, please try again :)')
159
+ print('Done with', model)
160
+ # try:
161
+ # doresample(result)
162
+ # except:
163
+ # pass
164
+ try:
165
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
166
+ audio = AudioSegment.from_file(result)
167
+ current_sr = audio.frame_rate
168
+ if current_sr > 24000:
169
+ audio = audio.set_frame_rate(24000)
170
+ try:
171
+ print('Trying to normalize audio')
172
+ audio = match_target_amplitude(audio, -20)
173
+ except:
174
+ print('[WARN] Unable to normalize audio')
175
+ audio.export(f.name, format="wav")
176
+ os.unlink(result)
177
+ result = f.name
178
+ except:
179
+ pass
180
+ if model in AVAILABLE_MODELS.keys(): model = AVAILABLE_MODELS[model]
181
+ print(model)
182
+ print(f"Running model {model}")
183
+ result_storage[model] = result
184
+ # try:
185
+ # doloudnorm(result)
186
+ # except:
187
+ # pass
188
+ mdl1k = mdl1
189
+ mdl2k = mdl2
190
+ print(mdl1k, mdl2k)
191
+ if mdl1 in AVAILABLE_MODELS.keys(): mdl1k=AVAILABLE_MODELS[mdl1]
192
+ if mdl2 in AVAILABLE_MODELS.keys(): mdl2k=AVAILABLE_MODELS[mdl2]
193
+ results = {}
194
+ print(f"Sending models {mdl1k} and {mdl2k} to API")
195
+ thread1 = threading.Thread(target=predict_and_update_result, args=(text, mdl1k, results))
196
+ thread2 = threading.Thread(target=predict_and_update_result, args=(text, mdl2k, results))
197
+
198
+ thread1.start()
199
+ thread2.start()
200
+ thread1.join()
201
+ thread2.join()
202
+
203
+ print(f"Retrieving models {mdl1k} and {mdl2k} from API")
204
+ return (
205
+ text,
206
+ "Synthesize",
207
+ gr.update(visible=True), # r2
208
+ mdl1, # model1
209
+ mdl2, # model2
210
+ gr.update(visible=True, value=results[mdl1k]), # aud1
211
+ gr.update(visible=True, value=results[mdl2k]), # aud2
212
+ gr.update(visible=True, interactive=False), #abetter
213
+ gr.update(visible=True, interactive=False), #bbetter
214
+ gr.update(visible=False), #prevmodel1
215
+ gr.update(visible=False), #prevmodel2
216
+ gr.update(visible=False), #nxt round btn
217
+ )
218
+
219
+ # Unlock vote
220
+
221
+ def unlock_vote(btn_index, aplayed, bplayed):
222
+ # sample played
223
+ if btn_index == 0:
224
+ aplayed = gr.State(value=True)
225
+ if btn_index == 1:
226
+ bplayed = gr.State(value=True)
227
+
228
+ # both audio samples played
229
+ if bool(aplayed) and bool(bplayed):
230
+ print('Both audio samples played, voting unlocked')
231
+ return [gr.update(interactive=True), gr.update(interactive=True), gr.update(), gr.update()]
232
+
233
+ return [gr.update(), gr.update(), aplayed, bplayed]
234
+
235
+ def randomsent():
236
+ return random.choice(sents), '🎲'
237
+ def randomsent_battle():
238
+ return tuple(randomsent()) + tuple(random_m())
239
+ def clear_stuff():
240
+ return "", "Synthesize", gr.update(visible=False), '', '', gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
app/ui.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from .config import *
3
+ from .messages import *
4
+ from .ui_vote import *
5
+ from .ui_battle import *
6
+ from .ui_leaderboard import *
7
+
8
+
9
+ with gr.Blocks() as about:
10
+ gr.Markdown(ABOUT)
11
+ gr.DownloadButton("DL", DB_PATH)
12
+
13
+ with gr.Blocks(css="footer {visibility: hidden}textbox{resize:none}", title="TTS Arena") as app:
14
+ gr.Markdown(DESCR)
15
+ gr.TabbedInterface([vote, battle, leaderboard, about], ['Vote', 'Battle', 'Leaderboard', 'About'])
16
+ if CITATION_TEXT:
17
+ with gr.Row():
18
+ with gr.Accordion("Citation", open=False):
19
+ gr.Markdown(f"If you use this data in your publication, please cite us!\n\nCopy the BibTeX citation to cite this source:\n\n```bibtext\n{CITATION_TEXT}\n```\n\nPlease note that all generated audio clips should be assumed unsuitable for redistribution or commercial use.")
app/ui_battle.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from .config import *
3
+ from .ui import *
4
+ from .synth import *
5
+ from .vote import *
6
+ from .messages import *
7
+
8
+ def disable():
9
+ return [gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False)]
10
+ def enable():
11
+ return [gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)]
12
+
13
+
14
+ with gr.Blocks() as battle:
15
+ battle_useridstate = gr.State()
16
+
17
+ gr.Markdown(BATTLE_INSTR)
18
+ model1 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
19
+ model2 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
20
+ with gr.Group():
21
+ with gr.Row():
22
+ text = gr.Textbox(container=False, show_label=False, placeholder="Enter text to synthesize", lines=1, max_lines=1, scale=9999999, min_width=0)
23
+ randomt_battle = gr.Button('🎲', scale=0, min_width=0, variant='tool')
24
+ with gr.Row():
25
+ with gr.Column(scale=10):
26
+ model1s = gr.Dropdown(label="Model 1", container=False, show_label=False, choices=AVAILABLE_MODELS.keys(), interactive=True, value=list(AVAILABLE_MODELS.keys())[0])
27
+ with gr.Column(scale=10):
28
+ model2s = gr.Dropdown(label="Model 2", container=False, show_label=False, choices=AVAILABLE_MODELS.keys(), interactive=True, value=list(AVAILABLE_MODELS.keys())[1])
29
+ randomt_battle.click(randomsent_battle, outputs=[text, randomt_battle, model1s, model2s])
30
+ btn = gr.Button("Synthesize", variant='primary')
31
+ with gr.Row(visible=False) as r2:
32
+ with gr.Column():
33
+ with gr.Group():
34
+ aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False)
35
+ abetter = gr.Button("A is better", variant='primary')
36
+ prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A", text_align="center", lines=1, max_lines=1, visible=False)
37
+ with gr.Column():
38
+ with gr.Group():
39
+ aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False)
40
+ bbetter = gr.Button("B is better", variant='primary')
41
+ prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="center", lines=1, max_lines=1, visible=False)
42
+ outputs = [
43
+ text,
44
+ btn,
45
+ r2,
46
+ model1,
47
+ model2,
48
+ aud1,
49
+ aud2,
50
+ abetter,
51
+ bbetter,
52
+ prevmodel1,
53
+ prevmodel2,
54
+ ]
55
+ btn.click(disable, outputs=[btn, abetter, bbetter]).then(synthandreturn_battle, inputs=[text, model1s, model2s], outputs=outputs).then(enable, outputs=[btn, abetter, bbetter])
56
+ nxt_outputs = [abetter, bbetter, prevmodel1, prevmodel2]
57
+ abetter.click(a_is_better_battle, outputs=nxt_outputs, inputs=[model1, model2, battle_useridstate])
58
+ bbetter.click(b_is_better_battle, outputs=nxt_outputs, inputs=[model1, model2, battle_useridstate])
59
+ battle.load(random_m, outputs=[model1s, model2s])
app/ui_leaderboard.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from .config import *
3
+ from .leaderboard import *
4
+ from .messages import *
5
+
6
+ with gr.Blocks() as leaderboard:
7
+ gr.Markdown(LDESC)
8
+ df = gr.Dataframe(interactive=False, min_width=0, wrap=True, column_widths=[30, 200, 50, 50])
9
+ reloadbtn = gr.Button("Refresh")
10
+ with gr.Row():
11
+ reveal_prelim = gr.Checkbox(label="Reveal preliminary results", info="Show all models, including models with very few human ratings.", scale=1)
12
+ hide_battle_votes = gr.Checkbox(label="Hide Battle Mode votes", info="Exclude votes obtained through Battle Mode.", scale=1)
13
+ reveal_prelim.input(get_leaderboard, inputs=[reveal_prelim, hide_battle_votes], outputs=[df])
14
+ hide_battle_votes.input(get_leaderboard, inputs=[reveal_prelim, hide_battle_votes], outputs=[df])
15
+ leaderboard.load(get_leaderboard, inputs=[reveal_prelim, hide_battle_votes], outputs=[df])
16
+ reloadbtn.click(get_leaderboard, inputs=[reveal_prelim, hide_battle_votes], outputs=[df])
17
+ # gr.Markdown("DISCLAIMER: The licenses listed may not be accurate or up to date, you are responsible for checking the licenses before using the models. Also note that some models may have additional usage restrictions.")
app/ui_vote.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from .config import *
3
+ from .synth import *
4
+ from .vote import *
5
+ from .messages import *
6
+
7
+ def disable():
8
+ return [gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False)]
9
+ def enable():
10
+ return [gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)]
11
+
12
+
13
+ with gr.Blocks() as vote:
14
+ # sample played
15
+ #aplayed = gr.State(value=False)
16
+ #bplayed = gr.State(value=False)
17
+ # voter ID
18
+ useridstate = gr.State()
19
+ gr.Markdown(INSTR)
20
+ with gr.Group():
21
+ with gr.Row():
22
+ text = gr.Textbox(container=False, show_label=False, placeholder="Enter text to synthesize", lines=1, max_lines=1, scale=9999999, min_width=0)
23
+ randomt = gr.Button('🎲', scale=0, min_width=0, variant='tool')
24
+ randomt.click(randomsent, outputs=[text, randomt])
25
+ btn = gr.Button("Synthesize", variant='primary')
26
+ model1 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
27
+ #model1 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=True)
28
+ model2 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
29
+ #model2 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=True)
30
+ with gr.Row(visible=False) as r2:
31
+ with gr.Column():
32
+ with gr.Group():
33
+ aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False)
34
+ abetter = gr.Button("A is better", variant='primary')
35
+ prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A", text_align="center", lines=1, max_lines=1, visible=False)
36
+ with gr.Column():
37
+ with gr.Group():
38
+ aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False)
39
+ bbetter = gr.Button("B is better", variant='primary')
40
+ prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="center", lines=1, max_lines=1, visible=False)
41
+ nxtroundbtn = gr.Button('Next round', visible=False)
42
+ # outputs = [text, btn, r2, model1, model2, prevmodel1, aud1, prevmodel2, aud2, abetter, bbetter]
43
+ outputs = [
44
+ text,
45
+ btn,
46
+ r2,
47
+ model1,
48
+ model2,
49
+ aud1,
50
+ aud2,
51
+ abetter,
52
+ bbetter,
53
+ prevmodel1,
54
+ prevmodel2,
55
+ nxtroundbtn
56
+ ]
57
+ """
58
+ text,
59
+ "Synthesize",
60
+ gr.update(visible=True), # r2
61
+ mdl1, # model1
62
+ mdl2, # model2
63
+ gr.update(visible=True, value=results[mdl1]), # aud1
64
+ gr.update(visible=True, value=results[mdl2]), # aud2
65
+ gr.update(visible=True, interactive=False), #abetter
66
+ gr.update(visible=True, interactive=False), #bbetter
67
+ gr.update(visible=False), #prevmodel1
68
+ gr.update(visible=False), #prevmodel2
69
+ gr.update(visible=False), #nxt round btn"""
70
+ btn.click(disable, outputs=[btn, abetter, bbetter]).then(synthandreturn, inputs=[text], outputs=outputs).then(enable, outputs=[btn, abetter, bbetter])
71
+ nxtroundbtn.click(clear_stuff, outputs=outputs)
72
+
73
+ # Allow interaction with the vote buttons only when both audio samples have finished playing
74
+ #aud1.stop(unlock_vote, outputs=[abetter, bbetter, aplayed, bplayed], inputs=[gr.State(value=0), aplayed, bplayed])
75
+ #aud2.stop(unlock_vote, outputs=[abetter, bbetter, aplayed, bplayed], inputs=[gr.State(value=1), aplayed, bplayed])
76
+
77
+ # nxt_outputs = [prevmodel1, prevmodel2, abetter, bbetter]
78
+ nxt_outputs = [abetter, bbetter, prevmodel1, prevmodel2, nxtroundbtn]
79
+ abetter.click(a_is_better, outputs=nxt_outputs, inputs=[model1, model2, useridstate])
80
+ bbetter.click(b_is_better, outputs=nxt_outputs, inputs=[model1, model2, useridstate])
app/utils.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ import soundfile as sf
3
+ import pydub
4
+ import pyloudnorm as pyln
5
+
6
+ def match_target_amplitude(sound, target_dBFS):
7
+ change_in_dBFS = target_dBFS - sound.dBFS
8
+ return sound.apply_gain(change_in_dBFS)
9
+
10
+ def mkuuid(uid):
11
+ if not uid:
12
+ uid = uuid.uuid4()
13
+ return uid
14
+
15
+ def doloudnorm(path):
16
+ data, rate = sf.read(path)
17
+ meter = pyln.Meter(rate)
18
+ loudness = meter.integrated_loudness(data)
19
+ loudness_normalized_audio = pyln.normalize.loudness(data, loudness, -12.0)
20
+ sf.write(path, loudness_normalized_audio, rate)
app/vote.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import *
2
+ from .config import *
3
+ from .models import *
4
+ from .db import *
5
+ from .init import *
6
+
7
+ import gradio as gr
8
+
9
+ # Logging
10
+
11
+ def log_text(text):
12
+ conn = get_db()
13
+ cursor = conn.cursor()
14
+ cursor.execute('INSERT INTO spokentext (spokentext) VALUES (?)', (text,))
15
+ if scheduler:
16
+ with scheduler.lock:
17
+ conn.commit()
18
+ else:
19
+ conn.commit()
20
+ cursor.close()
21
+
22
+ # Vote
23
+
24
+ def upvote_model(model, uname, battle=False):
25
+ conn = get_db()
26
+ cursor = conn.cursor()
27
+ if battle: uname = "unknown_battle"
28
+ cursor.execute('UPDATE model SET upvote = upvote + 1 WHERE name = ?', (model,))
29
+ if cursor.rowcount == 0:
30
+ cursor.execute('INSERT OR REPLACE INTO model (name, upvote, downvote) VALUES (?, 1, 0)', (model,))
31
+ cursor.execute('INSERT INTO vote (username, model, vote) VALUES (?, ?, ?)', (uname, model, 1,))
32
+ if scheduler:
33
+ with scheduler.lock:
34
+ conn.commit()
35
+ else:
36
+ conn.commit()
37
+ cursor.close()
38
+
39
+ def downvote_model(model, uname, battle=False):
40
+ conn = get_db()
41
+ cursor = conn.cursor()
42
+ if battle: uname = "unknown_battle"
43
+ cursor.execute('UPDATE model SET downvote = downvote + 1 WHERE name = ?', (model,))
44
+ if cursor.rowcount == 0:
45
+ cursor.execute('INSERT OR REPLACE INTO model (name, upvote, downvote) VALUES (?, 0, 1)', (model,))
46
+ cursor.execute('INSERT INTO vote (username, model, vote) VALUES (?, ?, ?)', (uname, model, -1,))
47
+ if scheduler:
48
+ with scheduler.lock:
49
+ conn.commit()
50
+ else:
51
+ conn.commit()
52
+ cursor.close()
53
+
54
+ # Battle Mode
55
+
56
+ def a_is_better_battle(model1, model2, userid):
57
+ return a_is_better(model1, model2, 'unknown_battle', True)
58
+ def b_is_better_battle(model1, model2, userid):
59
+ return b_is_better(model1, model2, 'unknown_battle', True)
60
+
61
+ # A/B better
62
+
63
+ def a_is_better(model1, model2, userid, battle=False):
64
+ print("A is better", model1, model2)
65
+ if not model1 in AVAILABLE_MODELS.keys() and not model1 in AVAILABLE_MODELS.values():
66
+ raise gr.Error('Sorry, please try voting again.')
67
+ userid = mkuuid(userid)
68
+ if model1 and model2:
69
+ conn = get_db()
70
+ cursor = conn.cursor()
71
+ cursor.execute('INSERT INTO votelog (username, chosen, rejected) VALUES (?, ?, ?)', (str(userid), model1, model2,))
72
+ if scheduler:
73
+ with scheduler.lock:
74
+ conn.commit()
75
+ else:
76
+ conn.commit()
77
+ cursor.close()
78
+ upvote_model(model1, str(userid), battle)
79
+ downvote_model(model2, str(userid), battle)
80
+ return reload(model1, model2, userid, chose_a=True)
81
+ def b_is_better(model1, model2, userid, battle=False):
82
+ print("B is better", model1, model2)
83
+ if not model1 in AVAILABLE_MODELS.keys() and not model1 in AVAILABLE_MODELS.values():
84
+ raise gr.Error('Sorry, please try voting again.')
85
+ userid = mkuuid(userid)
86
+ if model1 and model2:
87
+ conn = get_db()
88
+ cursor = conn.cursor()
89
+ cursor.execute('INSERT INTO votelog (username, chosen, rejected) VALUES (?, ?, ?)', (str(userid), model2, model1,))
90
+ if scheduler:
91
+ with scheduler.lock:
92
+ conn.commit()
93
+ else:
94
+ conn.commit()
95
+ cursor.close()
96
+ upvote_model(model2, str(userid), battle)
97
+ downvote_model(model1, str(userid), battle)
98
+ return reload(model1, model2, userid, chose_b=True)
99
+
100
+ # Reload
101
+
102
+ def reload(chosenmodel1=None, chosenmodel2=None, userid=None, chose_a=False, chose_b=False):
103
+ out = [
104
+ gr.update(interactive=False, visible=False),
105
+ gr.update(interactive=False, visible=False)
106
+ ]
107
+ if chose_a == True:
108
+ out.append(gr.update(value=f'Your vote: {chosenmodel1}', interactive=False, visible=True))
109
+ out.append(gr.update(value=f'{chosenmodel2}', interactive=False, visible=True))
110
+ else:
111
+ out.append(gr.update(value=f'{chosenmodel1}', interactive=False, visible=True))
112
+ out.append(gr.update(value=f'Your vote: {chosenmodel2}', interactive=False, visible=True))
113
+ out.append(gr.update(visible=True))
114
+ return out