File size: 62,786 Bytes
c055e89
 
8e14d20
c055e89
7927ab2
cd5bd26
 
a886688
1ace391
 
ebd29b9
74744eb
5fed627
 
 
ee7a278
 
0fc7cd1
ee7a278
 
 
 
 
 
 
 
 
 
 
5fed627
60b0d11
 
 
 
c58df40
f0afce4
c58df40
f0afce4
 
 
74744eb
0f5cb56
f1fda32
0f5cb56
bcb8cb1
 
f0c72ad
 
bcb8cb1
0f5cb56
f0c72ad
 
 
cc70457
bcb8cb1
cc70457
ca8a2ca
 
 
 
6636280
 
 
 
234e026
 
 
2d0cccd
 
234e026
 
 
 
 
89b92be
 
 
 
 
 
 
a7cda23
234e026
89b92be
 
6636280
a886688
 
 
 
89b92be
115ef4c
89b92be
115ef4c
 
 
 
9464b47
89b92be
 
bd001a3
89b92be
 
234e026
89b92be
234e026
 
89b92be
 
234e026
 
6636280
234e026
 
 
bd001a3
234e026
 
 
 
 
 
bd001a3
234e026
 
 
 
 
 
bd001a3
234e026
 
 
 
 
 
bd001a3
234e026
 
 
 
 
 
bd001a3
234e026
 
 
 
6636280
8a87cd6
bd001a3
234e026
 
 
 
6636280
234e026
bd001a3
234e026
 
 
 
 
 
bd001a3
234e026
 
 
 
 
 
bd001a3
234e026
bba8af9
234e026
 
b2154bf
e4825c2
 
108f645
e4825c2
 
 
115ef4c
e4825c2
89b92be
115ef4c
 
 
 
 
 
 
108f645
9464b47
181f667
9464b47
 
 
115ef4c
9464b47
 
bd001a3
 
 
 
 
 
181f667
bd001a3
9464b47
a886688
1e7417b
 
 
 
 
 
 
a886688
 
 
 
 
 
115ef4c
a886688
 
b2154bf
dcf88fb
 
b2154bf
 
 
 
6636280
64e5e5a
ca8a2ca
c055e89
a886688
 
 
 
b2154bf
ede53f4
 
 
a886688
667a0d3
ede53f4
 
 
 
 
b2154bf
a455f97
ede53f4
 
 
 
89b92be
ede53f4
234e026
89b92be
 
234e026
ede53f4
 
 
 
 
8a87cd6
89b92be
ede53f4
 
b2154bf
bba8af9
b2154bf
 
bba8af9
b2154bf
 
a886688
b2154bf
 
 
 
 
 
 
 
c9dc57d
bba8af9
c9dc57d
 
b2154bf
234e026
0e92849
bba8af9
234e026
 
cc70457
 
 
 
 
 
 
e4825c2
108f645
e4825c2
 
e4da5b1
e4825c2
bd001a3
 
 
 
 
1e7417b
 
 
a886688
c9dc57d
e4da5b1
1e7417b
 
 
 
 
 
 
a886688
 
 
 
 
 
 
ede53f4
 
bba8af9
ee7a278
 
 
 
 
 
 
 
494526e
ee7a278
 
 
 
 
 
 
 
 
 
 
 
 
bba8af9
53a98fd
7b5c32e
74744eb
cd5bd26
 
0e3778b
c50a443
ede53f4
0e3778b
 
9dd70a7
69be213
1d58cd7
5cd0e1e
5e35153
5cd0e1e
 
6433dba
1d58cd7
cd5bd26
 
abcae38
cd5bd26
 
1ec31d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f95f048
 
1ec31d9
 
67d05e3
 
 
 
 
 
 
 
 
2ca5c30
 
 
878ff6b
f95f048
878ff6b
f95f048
2ca5c30
 
878ff6b
 
 
 
abcae38
 
 
 
 
 
 
 
 
 
0e3778b
 
 
 
 
 
 
 
1ec31d9
cd5bd26
 
cc85f78
6636280
cd5bd26
 
 
 
 
 
 
 
 
 
69be213
cd5bd26
ca8a2ca
 
 
6636280
bba8af9
cd5bd26
 
 
e5109be
18d89f0
e4da5b1
18d89f0
7524c65
20dc216
375d701
 
 
 
 
 
 
 
 
20dc216
cde05f1
18d89f0
f5a93f9
cc70457
69b2485
c991ae0
cc70457
 
18d89f0
cc70457
18d89f0
c055e89
cd5bd26
0217d78
7524c65
c055e89
264149b
c055e89
 
3a0e8ae
c055e89
7524c65
29a5f2c
f7860cf
 
 
29a5f2c
76df6f6
 
7524c65
76df6f6
83020c7
29a5f2c
83020c7
29a5f2c
83020c7
 
ccf5c81
83020c7
 
 
ccf5c81
83020c7
c055e89
 
0636bf7
7524c65
0636bf7
cea913e
c62c303
 
 
7524c65
2a9845b
7524c65
c055e89
3d5f02b
a2f2037
20dc216
2987626
 
 
aea0389
108f645
20dc216
9ba8b9d
 
c055e89
9ba8b9d
20dc216
9ba8b9d
 
 
 
 
 
 
 
 
 
cd5bd26
69be213
 
 
 
cd5bd26
1cb88a1
 
 
cd5bd26
 
 
ca8a2ca
cd5bd26
 
 
1cb88a1
cd5bd26
18d89f0
 
 
cd5bd26
18d89f0
 
 
20dc216
 
18d89f0
 
 
 
 
 
 
20dc216
 
29a5f2c
 
 
20dc216
1cb88a1
 
 
20dc216
e080e91
18d89f0
29a5f2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48707ff
29a5f2c
 
 
 
e080e91
ee22100
9952550
6636280
e080e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29a5f2c
2bb5d82
cd5bd26
2bb5d82
 
 
 
20dc216
2bb5d82
 
 
 
2c89463
ecca97f
9068c64
71abf2f
9952550
 
ecca97f
2c89463
0c804b7
2c89463
 
 
40f7a3f
56450a7
2c89463
 
 
03d6969
2c89463
bece061
181f667
2c89463
 
 
 
 
 
 
 
 
 
 
 
193c0b7
 
2c89463
 
 
56450a7
 
 
 
 
 
 
 
 
 
 
 
 
 
03d6969
2c89463
abf1e6b
181f667
abf1e6b
aea65b3
bd001a3
 
aea65b3
 
bd001a3
aea65b3
 
181f667
bd001a3
 
 
 
 
181f667
 
 
 
 
 
 
 
 
 
abf1e6b
409225a
aea65b3
bece061
 
181f667
bece061
 
 
 
abf1e6b
 
181f667
433517c
 
af37f5e
 
3425a41
20dc216
 
 
 
 
63f3958
cd5bd26
 
20dc216
878ff6b
 
 
 
 
2ca5c30
 
878ff6b
 
2ca5c30
 
 
3425a41
20dc216
 
 
 
 
63f3958
cd5bd26
 
20dc216
cd5bd26
878ff6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0903ad6
878ff6b
 
af37f5e
99f01ee
8ae6da1
 
878ff6b
 
 
 
 
 
8ae6da1
 
878ff6b
 
 
8ae6da1
878ff6b
 
 
 
 
 
 
 
 
 
 
433517c
af37f5e
99f01ee
af37f5e
 
10801ae
433517c
af37f5e
99f01ee
af37f5e
 
10801ae
2b0c2d0
18d89f0
5404187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7fbc
ee22100
abf1e6b
 
2b0c2d0
ee22100
6aa0fa6
2b0c2d0
abf1e6b
009ac4f
abf1e6b
 
009ac4f
abf1e6b
 
1925e72
2b0c2d0
b0986f3
20dc216
 
cd5bd26
bece061
 
 
 
 
 
 
aea0389
b33525a
6691dd6
b33525a
 
 
637cb4e
b0986f3
0636bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ace391
4478ce8
1ace391
 
 
4478ce8
ebd29b9
0408757
 
dc46588
 
 
09cd5ce
462fbb0
619c449
c3e4d11
 
74744eb
637cb4e
29f8edc
 
 
 
 
dc46588
b72e390
375d701
 
8e14d20
 
09d8f48
 
 
 
8f8bb42
8e14d20
 
ca8a2ca
878ff6b
abf1e6b
bba8af9
878ff6b
bba8af9
abf1e6b
878ff6b
abf1e6b
bba8af9
878ff6b
abf1e6b
bba8af9
878ff6b
 
2ca5c30
462fbb0
8a40d1b
 
 
115ef4c
 
8a40d1b
 
2e114a1
 
502ca44
8a40d1b
502ca44
 
 
 
2e114a1
 
bba8af9
 
bd001a3
502ca44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bba8af9
 
502ca44
bba8af9
502ca44
1e7417b
 
 
 
 
 
 
6636280
502ca44
 
6636280
502ca44
 
a455f97
4cca697
a455f97
bba8af9
2e114a1
f5a93f9
bba8af9
a455f97
8a40d1b
2e114a1
a455f97
bba8af9
 
 
 
 
5fed627
 
 
0408757
 
bba8af9
0408757
60b0d11
bba8af9
60b0d11
 
bba8af9
5fed627
 
 
 
1e7417b
5fed627
c908a11
5fed627
6636280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ede53f4
 
 
 
a455f97
ede53f4
 
 
 
 
ac01906
 
 
 
 
73c86b6
294e0bf
462fbb0
 
234e026
c823dc3
 
d36b523
 
0408d22
0eaad07
 
 
 
 
 
 
0408d22
53e5e28
234e026
ee7a278
 
0fc7cd1
 
 
 
ee7a278
 
 
 
 
 
 
 
 
 
 
82bcf4e
 
 
 
ee7a278
0fc7cd1
ee7a278
294e0bf
7927ab2
 
 
 
 
 
64e5e5a
 
760f182
 
 
 
7927ab2
bbfb485
 
 
7927ab2
09cd5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760f182
 
 
 
bbfb485
760f182
bbfb485
760f182
 
 
1e7417b
09d8f48
760f182
09d8f48
760f182
09d8f48
 
 
f5a93f9
 
 
 
 
 
ee7a278
494526e
f5a93f9
 
ee7a278
494526e
f5a93f9
 
 
 
 
 
0fc7cd1
 
f5a93f9
0fc7cd1
 
f5a93f9
ee7a278
 
 
 
 
0fc7cd1
ee7a278
 
 
 
0fc7cd1
 
 
 
 
 
 
 
ee7a278
 
 
 
 
f5a93f9
 
 
 
 
ee7a278
 
69b2485
ee7a278
 
 
 
64e5e5a
 
ee7a278
 
 
 
 
 
0fc7cd1
 
ee7a278
 
 
0fc7cd1
 
f5a93f9
 
e4da5b1
494526e
0fc7cd1
 
 
 
 
 
 
3617d86
0fc7cd1
f1fda32
ee7a278
1f4eba7
ee7a278
69b2485
ee7a278
bbfb485
ee7a278
 
0fc7cd1
 
bbfb485
 
ee7a278
 
 
bbfb485
 
ee7a278
bbfb485
bc21678
0fc7cd1
22d84e7
0fc7cd1
69b2485
 
f5a93f9
1eae8c6
5de1947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eae8c6
20dc216
f5a93f9
 
09d8f48
 
 
760f182
5147f0b
20dc216
7366b46
f1fda32
0fc7cd1
1eae8c6
 
 
 
 
 
 
 
 
 
c09bde4
69b2485
 
1eae8c6
7366b46
1ba9e48
 
a629389
 
 
64e5e5a
 
 
 
 
09d8f48
64e5e5a
 
5de1947
 
 
 
 
 
abf1e6b
a629389
 
64e5e5a
 
 
 
 
09d8f48
64e5e5a
 
5de1947
 
 
 
 
 
abf1e6b
5de1947
 
 
 
 
c4e7fbc
b0de8ae
 
 
 
 
 
 
 
 
 
 
 
ee7a278
 
 
b0de8ae
 
 
 
 
 
 
 
 
 
 
 
 
 
0fc7cd1
 
 
69b2485
1eae8c6
f5a93f9
 
 
 
ee7a278
 
0fc7cd1
 
f5a93f9
 
 
9594ec2
760f182
09d8f48
 
 
 
 
 
 
 
 
3617d86
09d8f48
64e5e5a
09d8f48
 
 
 
 
69b2485
1eae8c6
69b2485
 
 
 
 
 
 
 
760f182
c4e7fbc
6b71cc7
0fc7cd1
3617d86
 
0fc7cd1
3617d86
 
0636bf7
 
 
 
20dc216
cc70457
 
 
 
 
 
 
 
 
 
 
20dc216
c055e89
 
9ba8b9d
 
 
9983762
 
 
 
 
 
 
cc70457
3617d86
20dc216
9983762
9ba8b9d
2519d7f
 
d0dc5de
353a56a
2519d7f
cd5bd26
f5a93f9
c177a79
f5a93f9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
import gradio as gr
import pandas as pd
from langdetect import detect
from datasets import load_dataset
import threading, time, uuid, sqlite3, shutil, os, random, asyncio, threading
from pathlib import Path
from huggingface_hub import CommitScheduler, delete_file, hf_hub_download
from gradio_client import Client, handle_file
import pyloudnorm as pyln
import soundfile as sf
import librosa
from detoxify import Detoxify
import os
import tempfile
from pydub import AudioSegment
import itertools
from typing import List, Tuple, Set, Dict
from hashlib import md5, sha1

class User:
    def __init__(self, user_id: str):
        self.user_id = user_id
        self.voted_pairs: Set[Tuple[str, str]] = set()

class Sample:
    def __init__(self, filename: str, transcript: str, modelName: str):
        self.filename = filename
        self.transcript = transcript
        self.modelName = modelName

def match_target_amplitude(sound, target_dBFS):
    change_in_dBFS = target_dBFS - sound.dBFS
    return sound.apply_gain(change_in_dBFS)

# from gradio_space_ci import enable_space_ci

# enable_space_ci()



toxicity = Detoxify('original')
sents = []
with open('harvard_sentences.txt') as f:
    sents += f.read().strip().splitlines()
with open('llama3_command-r_sentences_1st_person.txt') as f:
    sents += f.read().strip().splitlines()
# With other punctuation marks
# Exclamations - # conversational characters/animation entertainment/tv
with open('llama3_command-r_sentences_excla.txt') as f:
    sents += f.read().strip().splitlines()
# Questions - # conversational characters/animation entertainment/tv
with open('llama3_command-r_questions.txt') as f:
    sents += f.read().strip().splitlines()

# Credit: llama3_command-r sentences generated by user KingNish

####################################
# Constants
####################################
AVAILABLE_MODELS = {
    # 'XTTSv2': 'xtts',
    # 'WhisperSpeech': 'whisperspeech',
    # 'ElevenLabs': 'eleven',
    # 'OpenVoice': 'openvoice',
    # 'OpenVoice V2': 'openvoicev2',
    # 'Play.HT 2.0': 'playht',
    # 'MetaVoice': 'metavoice',
    # 'MeloTTS': 'melo',
    # 'StyleTTS 2': 'styletts2',
    # 'GPT-SoVITS': 'sovits',
    # 'Vokan TTS': 'vokan',
    # 'VoiceCraft 2.0': 'voicecraft',
    # 'Parler TTS': 'parler'

    # HF Gradio Spaces: # <works with gradio version #>
    # gravio version that works with most spaces: 4.29
    'coqui/xtts': 'coqui/xtts', # 4.29 4.32
    'collabora/WhisperSpeech': 'collabora/WhisperSpeech', # 4.32 4.36.1
    # 'myshell-ai/OpenVoice': 'myshell-ai/OpenVoice', # same devs as MeloTTS, which scores higher # 4.29
    # 'myshell-ai/OpenVoiceV2': 'myshell-ai/OpenVoiceV2', # same devs as MeloTTS, which scores higher # 4.29
    'mrfakename/MetaVoice-1B-v0.1': 'mrfakename/MetaVoice-1B-v0.1', # 4.29 4.32
    'Pendrokar/xVASynth-TTS': 'Pendrokar/xVASynth-TTS', # 4.29 4.32 4.42.0
    # 'coqui/CoquiTTS': 'coqui/CoquiTTS',
    'mrfakename/MeloTTS': 'mrfakename/MeloTTS', # 4.29 4.32
    'fishaudio/fish-speech-1': 'fishaudio/fish-speech-1', # 4.29 4.32 4.36.1

    # E2 & F5 TTS
    # F5 model
    'mrfakename/E2-F5-TTS': 'mrfakename/E2-F5-TTS', # 5.0

    # # Parler
    # Parler Large model
    'parler-tts/parler_tts': 'parler-tts/parler_tts', # 4.29 4.32 4.36.1 4.42.0
    # Parler Mini model
    # 'parler-tts/parler_tts': 'parler-tts/parler_tts', # 4.29 4.32 4.36.1 4.42.0
    # 'parler-tts/parler_tts_mini': 'parler-tts/parler_tts_mini', # Mini is the default model of parler_tts
    # 'parler-tts/parler-tts-expresso': 'parler-tts/parler-tts-expresso', # 4.29 4.32 4.36.1 4.42.0

    # # Microsoft Edge TTS
    'innoai/Edge-TTS-Text-to-Speech': 'innoai/Edge-TTS-Text-to-Speech', # 4.29

    # HF TTS w issues
    # 'LeeSangHoon/HierSpeech_TTS': 'LeeSangHoon/HierSpeech_TTS', # irresponsive to exclamation marks # 4.29
    # 'PolyAI/pheme': '/predict#0', # sleepy HF Space
    # 'amphion/Text-to-Speech': '/predict#0', # disabled also on original HF space due to poor ratings
    # 'suno/bark': '3#0', # Hallucinates
    # 'shivammehta25/Matcha-TTS': '5#0', # seems to require multiple requests for setup
    # 'styletts2/styletts2': '0#0', # API disabled, awaiting approval of PR #15
    # 'Manmay/tortoise-tts': '/predict#0', # Cannot retrieve streamed file; 403
    # 'pytorch/Tacotron2': '0#0', # old gradio
}

HF_SPACES = {
    # XTTS v2
    'coqui/xtts': {
        'name': 'XTTS v2',
        'function': '1',
        'text_param_index': 0,
        'return_audio_index': 1,
    },
    # WhisperSpeech
    'collabora/WhisperSpeech': {
        'name': 'WhisperSpeech',
        'function': '/whisper_speech_demo',
        'text_param_index': 0,
        'return_audio_index': 0,
    },
    # OpenVoice (MyShell.ai)
    'myshell-ai/OpenVoice': {
        'name':'OpenVoice',
        'function': '1',
        'text_param_index': 0,
        'return_audio_index': 1,
    },
    # OpenVoice v2 (MyShell.ai)
    'myshell-ai/OpenVoiceV2': {
        'name':'OpenVoice v2',
        'function': '1',
        'text_param_index': 0,
        'return_audio_index': 1,
    },
    # MetaVoice
    'mrfakename/MetaVoice-1B-v0.1': {
        'name':'MetaVoice',
        'function': '/tts',
        'text_param_index': 0,
        'return_audio_index': 0,
    },
    # xVASynth (CPU)
    'Pendrokar/xVASynth-TTS': {
        'name': 'xVASynth v3',
        'function': '/predict',
        'text_param_index': 0,
        'return_audio_index': 0,
    },
    # CoquiTTS (CPU)
    'coqui/CoquiTTS': {
        'name': 'CoquiTTS',
        'function': '0',
        'text_param_index': 0,
        'return_audio_index': 0,
    },
    # HierSpeech_TTS
    'LeeSangHoon/HierSpeech_TTS': {
        'name': 'HierSpeech++',
        'function': '/predict',
        'text_param_index': 0,
        'return_audio_index': 0,
    },
    # MeloTTS (MyShell.ai)
    'mrfakename/MeloTTS': {
        'name': 'MeloTTS',
        'function': '/synthesize',
        'text_param_index': 0,
        'return_audio_index': 0,
    },

    # Parler
    'parler-tts/parler_tts': {
        'name': 'Parler Mini',
        'function': '/gen_tts',
        'text_param_index': 0,
        'return_audio_index': 0,
        'is_zero_gpu_space': True,
    },
    # Parler Mini
    # 'parler-tts/parler_tts': {
    #     'name': 'Parler Large',
    #     'function': '/gen_tts',
    #     'text_param_index': 0,
    #     'return_audio_index': 0,
    #     'is_zero_gpu_space': True,
    # },
    # Parler Mini which using Expresso dataset
    'parler-tts/parler-tts-expresso': {
        'name': 'Parler Mini Expresso',
        'function': '/gen_tts',
        'text_param_index': 0,
        'return_audio_index': 0,
        'is_zero_gpu_space': True,
    },

    # Microsoft Edge TTS
    'innoai/Edge-TTS-Text-to-Speech': {
        'name': 'Edge TTS',
        'function': '/predict',
        'text_param_index': 0,
        'return_audio_index': 0,
        'is_proprietary': True,
    },

    # Fish Speech
    'fishaudio/fish-speech-1': {
        'name': 'Fish Speech',
        'function': '/inference_wrapper',
        'text_param_index': 0,
        'return_audio_index': 1,
    },

    # E2/F5 TTS
    'mrfakename/E2-F5-TTS': {
        'name': 'F5 of E2 TTS',
        'function': '/infer',
        'text_param_index': 2,
        'return_audio_index': 0,
        'is_zero_gpu_space': True,
    },

    # TTS w issues
    # 'PolyAI/pheme': '/predict#0', #sleepy HF Space
    # 'amphion/Text-to-Speech': '/predict#0', #takes a whole minute to synthesize
    # 'suno/bark': '3#0', # Hallucinates
    # 'shivammehta25/Matcha-TTS': '5#0', #seems to require multiple requests for setup
    # 'styletts2/styletts2': '0#0', #API disabled
    # 'Manmay/tortoise-tts': '/predict#0', #Cannot skip text-from-file parameter
    # 'pytorch/Tacotron2': '0#0', #old gradio
    # 'fishaudio/fish-speech-1': '/inference_wrapper#0', heavy hallucinations
}

# for zero-shot TTS - voice sample used by XTTS (11 seconds)
DEFAULT_VOICE_SAMPLE_STR = 'https://cdn-uploads.huggingface.co/production/uploads/63d52e0c4e5642795617f668/V6-rMmI-P59DA4leWDIcK.wav'
DEFAULT_VOICE_SAMPLE = handle_file(DEFAULT_VOICE_SAMPLE_STR)
DEFAULT_VOICE_TRANSCRIPT = "The Hispaniola was rolling scuppers under in the ocean swell. The booms were tearing at the blocks, the rudder was banging to and fro, and the whole ship creaking, groaning, and jumping like a manufactory."

OVERRIDE_INPUTS = {
    'coqui/xtts': {
        1: 'en',
        2: DEFAULT_VOICE_SAMPLE_STR, # voice sample
        3: None, # mic voice sample
        4: False, #use_mic
        5: False, #cleanup_reference
        6: False, #auto_detect
    },
    'collabora/WhisperSpeech': {
        1: DEFAULT_VOICE_SAMPLE, # voice sample
        2: DEFAULT_VOICE_SAMPLE, # voice sample URL
        3: 14.0, #Tempo - Gradio Slider issue: takes min. rather than value
    },
    'myshell-ai/OpenVoice': {
        1: 'default', # style
        2: 'https://huggingface.co/spaces/myshell-ai/OpenVoiceV2/resolve/main/examples/speaker0.mp3', # voice sample
    },
    'myshell-ai/OpenVoiceV2': {
        1: 'en_us', # style
        2: 'https://huggingface.co/spaces/myshell-ai/OpenVoiceV2/resolve/main/examples/speaker0.mp3', # voice sample
    },
    'PolyAI/pheme': {
        1: 'YOU1000000044_S0000798', # voice
        2: 210,
        3: 0.7, #Tempo - Gradio Slider issue: takes min. rather than value
    },
    'Pendrokar/xVASynth-TTS': {
        1: 'x_ex04', #fine-tuned voice model name
        3: 1.0, #pacing/duration - Gradio Slider issue: takes min. rather than value
    },
    'suno/bark': {
        1: 'Speaker 3 (en)', # voice
    },
    'amphion/Text-to-Speech': {
        1: 'LikeManyWaters', # voice
    },
    'LeeSangHoon/HierSpeech_TTS': {
        1: handle_file('https://huggingface.co/spaces/LeeSangHoon/HierSpeech_TTS/resolve/main/example/female.wav'), # voice sample
        2: 0.333,
        3: 0.333,
        4: 1,
        5: 1,
        6: 0,
        7: 1111,
    },
    'Manmay/tortoise-tts': {
        1: None, # text-from-file
        2: 'angie', # voice
        3: 'disabled', # second voice for a dialogue
        4: 'No', # split by newline
    },
    'mrfakename/MeloTTS': {
        1: 'EN-Default',	# speaker; DEFAULT_VOICE_SAMPLE=EN-Default
        2: 1, # speed
        3: 'EN',	# language
    },
    'mrfakename/MetaVoice-1B-v0.1': {
		1: 5,	# float (numeric value between 0.0 and 10.0) in 'Speech Stability - improves text following for a challenging speaker' Slider component
		2: 5,	# float (numeric value between 1.0 and 5.0) in 'Speaker similarity - How closely to match speaker identity and speech style.' Slider component
		3: "Preset voices",	# Literal['Preset voices', 'Upload target voice']  in 'Choose voice' Radio component
		4: "Bria",	# Literal['Bria', 'Alex', 'Jacob']  in 'Preset voices' Dropdown component
		5: None,	# filepath  in 'Upload a clean sample to clone. Sample should contain 1 speaker, be between 30-90 seconds and not contain background noise.' Audio component
    },
    'parler-tts/parler_tts': {
        1: 'Laura; Laura\'s female voice; very clear audio', # description/prompt
    },
    'parler-tts/parler-tts-expresso': {
        1: 'Elisabeth; Elisabeth\'s female voice; very clear audio', # description/prompt
    },
    'innoai/Edge-TTS-Text-to-Speech': {
        1: 'en-US-EmmaMultilingualNeural - en-US (Female)', # voice
        2: 0, # pace rate
        3: 0, # pitch
    },

    'fishaudio/fish-speech-1': {
		1: True, # enable_reference_audio
		2: handle_file('https://huggingface.co/spaces/fishaudio/fish-speech-1/resolve/main/examples/English.wav'), # reference_audio
		3: 'In the ancient land of Eldoria, where the skies were painted with shades of mystic hues and the forests whispered secrets of old, there existed a dragon named Zephyros. Unlike the fearsome tales of dragons that plagued human hearts with terror, Zephyros was a creature of wonder and wisdom, revered by all who knew of his existence.', # reference_text
		4: 0, # max_new_tokens
		5: 200, # chunk_length
		6: 0.7, # top_p
		7: 1.2, # repetition_penalty
		8: 0.7, # temperature
		9: 1, # batch_infer_num
		10: False, # if_load_asr_model
    },

    'mrfakename/E2-F5-TTS': {
		0: DEFAULT_VOICE_SAMPLE, # voice sample
		1: DEFAULT_VOICE_TRANSCRIPT, # transcript of sample (< 15 seconds required)
		3: "F5-TTS", # model
		4: False, # cleanup silence
    },
}

hf_clients = {}
# cache audio samples for quick voting
cached_samples: List[Sample] = []
voting_users = {
    # userid as the key and USER() as the value
}

def generate_matching_pairs(samples: List[Sample]) -> List[Tuple[Sample, Sample]]:
    transcript_groups: Dict[str, List[Sample]] = {}
    samples = random.sample(samples, k=len(samples))
    for sample in samples:
        if sample.transcript not in transcript_groups:
            transcript_groups[sample.transcript] = []
        transcript_groups[sample.transcript].append(sample)

    matching_pairs: List[Tuple[Sample, Sample]] = []
    for group in transcript_groups.values():
        matching_pairs.extend(list(itertools.combinations(group, 2)))

    return matching_pairs

# List[Tuple[Sample, Sample]]
all_pairs = []

SPACE_ID = os.getenv('SPACE_ID')
MAX_SAMPLE_TXT_LENGTH = 300
MIN_SAMPLE_TXT_LENGTH = 10
DB_DATASET_ID = os.getenv('DATASET_ID')
DB_NAME = "database.db"

SPACE_ID = 'TTS-AGI/TTS-Arena'

# If /data available => means local storage is enabled => let's use it!
DB_PATH = f"/data/{DB_NAME}" if os.path.isdir("/data") else DB_NAME
print(f"Using {DB_PATH}")
# AUDIO_DATASET_ID = "ttseval/tts-arena-new"
CITATION_TEXT = """@misc{tts-arena,
	title        = {Text to Speech Arena},
	author       = {mrfakename and Srivastav, Vaibhav and Fourrier, ClΓ©mentine and Pouget, Lucain and Lacombe, Yoach and main and Gandhi, Sanchit},
	year         = 2024,
	publisher    = {Hugging Face},
	howpublished = "\\url{https://huggingface.co/spaces/TTS-AGI/TTS-Arena}"
}"""

####################################
# Functions
####################################

def create_db_if_missing():
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS model (
            name TEXT UNIQUE,
            upvote INTEGER,
            downvote INTEGER
        );
    ''')
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS vote (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT,
            model TEXT,
            vote INTEGER,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    ''')
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS votelog (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT,
            chosen TEXT,
            rejected TEXT,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    ''')
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS spokentext (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            votelog_id INTEGER UNIQUE,
            spokentext TEXT,
            lang TEXT,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    ''')
    # foreign keys
    cursor.execute('''
        CREATE UNIQUE INDEX IF NOT EXISTS st_to_vl ON spokentext(votelog_id);
    ''')
def get_db():
    return sqlite3.connect(DB_PATH)



####################################
# Space initialization
####################################

# Download existing DB
if not os.path.isfile(DB_PATH):
    print("Downloading DB...")
    try:
        cache_path = hf_hub_download(repo_id=DB_DATASET_ID, repo_type='dataset', filename=DB_NAME)
        shutil.copyfile(cache_path, DB_PATH)
        print("Downloaded DB")
    except Exception as e:
        print("Error while downloading DB:", e)

# Create DB table (if doesn't exist)
create_db_if_missing()

hf_token = os.getenv('HF_TOKEN')
# Sync local DB with remote repo every 5 minute (only if a change is detected)
scheduler = CommitScheduler(
    repo_id=DB_DATASET_ID,
    repo_type="dataset",
    folder_path=Path(DB_PATH).parent,
    every=5,
    allow_patterns=DB_NAME,
)

# Load audio dataset
# audio_dataset = load_dataset(AUDIO_DATASET_ID)

####################################
# Router API
####################################
# router = Client("TTS-AGI/tts-router", hf_token=hf_token)
router = {}
####################################
# Gradio app
####################################
MUST_BE_LOGGEDIN = "Please login with Hugging Face to participate in the TTS Arena."
DESCR = """
# TTS Spaces Arena: Benchmarking Gradio hosted TTS Models in the Wild

Vote to help the community find the best available text-to-speech model!
""".strip()
# INSTR = """
# ## Instructions

# * Listen to two anonymous models
# * Vote on which synthesized audio sounds more natural to you
# * If there's a tie, click Skip

# **When you're ready to begin, login and begin voting!** The model names will be revealed once you vote.
# """.strip()
INSTR = """
## πŸ—³οΈ Vote

* Press ⚑ to get cached sample pairs you've yet to vote on. (Fast πŸ‡)
* Or press 🎲 to randomly use a sentence from the list. (Slow 🐒)
* Or input text (πŸ‡ΊπŸ‡Έ English only) to synthesize audio. (Slowest 🐌 due to _Toxicity_ test)
* Listen to the two audio clips, one after the other.
* _Vote on which audio sounds more natural to you._
* Model names are revealed after the vote is cast.

⚠ Note: It **may take up to 30 seconds** to ***synthesize*** audio.
""".strip()
request = ''
if SPACE_ID:
    request = f"""
### Request a model

Please [create a Discussion](https://huggingface.co/spaces/{SPACE_ID}/discussions/new) to request a model.
"""
ABOUT = f"""
## πŸ“„ About

The TTS Arena evaluates leading speech synthesis models. It is inspired by LMsys's [Chatbot Arena](https://chat.lmsys.org/).

### Motivation

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.

### The Arena

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.

### Credits

Thank you to the following individuals who helped make this project possible:

* VB ([Twitter](https://twitter.com/reach_vb) / [Hugging Face](https://huggingface.co/reach-vb))
* ClΓ©mentine Fourrier ([Twitter](https://twitter.com/clefourrier) / [Hugging Face](https://huggingface.co/clefourrier))
* Lucain Pouget ([Twitter](https://twitter.com/Wauplin) / [Hugging Face](https://huggingface.co/Wauplin))
* Yoach Lacombe ([Twitter](https://twitter.com/yoachlacombe) / [Hugging Face](https://huggingface.co/ylacombe))
* Main Horse ([Twitter](https://twitter.com/main_horse) / [Hugging Face](https://huggingface.co/main-horse))
* Sanchit Gandhi ([Twitter](https://twitter.com/sanchitgandhi99) / [Hugging Face](https://huggingface.co/sanchit-gandhi))
* ApolinΓ‘rio Passos ([Twitter](https://twitter.com/multimodalart) / [Hugging Face](https://huggingface.co/multimodalart))
* Pedro Cuenca ([Twitter](https://twitter.com/pcuenq) / [Hugging Face](https://huggingface.co/pcuenq))

{request}

### Privacy statement

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.

### License

Generated audio clips cannot be redistributed and may be used for personal, non-commercial use only.

Random sentences are sourced from a filtered subset of the [Harvard Sentences](https://www.cs.columbia.edu/~hgs/audio/harvard.html).
""".strip()
LDESC = f"""
## πŸ† Leaderboard

Vote to help the community determine the best text-to-speech (TTS) models.

The leaderboard displays models in descending order of how natural they sound (based on votes cast by the community).

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. [This dataset is public](https://huggingface.co/datasets/{DB_DATASET_ID}) and only saves the hardcoded sentences while keeping the voters anonymous.
""".strip()
TTS_INFO = f"""
## πŸ—£ Contenders

### Open Source TTS Capabilities table

See the Dataset itself for more in depth information for each model.
""".strip()
TTS_IFRAME = """
<iframe
  src="https://huggingface.co/datasets/Pendrokar/open_tts_tracker/embed/viewer/default/train"
  frameborder="0"
  width="100%"
  height="560px"
></iframe>
""".strip()

# def reload_audio_dataset():
#     global audio_dataset
#     audio_dataset = load_dataset(AUDIO_DATASET_ID)
#     return 'Reload Audio Dataset'

def del_db(txt):
    if not txt.lower() == 'delete db':
        raise gr.Error('You did not enter "delete db"')

    # Delete local + remote
    os.remove(DB_PATH)
    delete_file(path_in_repo=DB_NAME, repo_id=DB_DATASET_ID, repo_type='dataset')

    # Recreate
    create_db_if_missing()
    return 'Delete DB'

theme = gr.themes.Base(
    font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif'],
)

model_names = {
    'styletts2': 'StyleTTS 2',
    'tacotron': 'Tacotron',
    'tacotronph': 'Tacotron Phoneme',
    'tacotrondca': 'Tacotron DCA',
    'speedyspeech': 'Speedy Speech',
    'overflow': 'Overflow TTS',
    'vits': 'VITS',
    'vitsneon': 'VITS Neon',
    'neuralhmm': 'Neural HMM',
    'glow': 'Glow TTS',
    'fastpitch': 'FastPitch',
    'jenny': 'Jenny',
    'tortoise': 'Tortoise TTS',
    'xtts2': 'Coqui XTTSv2',
    'xtts': 'Coqui XTTS',
    'openvoice': 'MyShell OpenVoice',
    'elevenlabs': 'ElevenLabs',
    'openai': 'OpenAI',
    'hierspeech': 'HierSpeech++',
    'pheme': 'PolyAI Pheme',
    'speecht5': 'SpeechT5',
    'metavoice': 'MetaVoice-1B',
}
model_licenses = {
    'styletts2': 'MIT',
    'tacotron': 'BSD-3',
    'tacotronph': 'BSD-3',
    'tacotrondca': 'BSD-3',
    'speedyspeech': 'BSD-3',
    'overflow': 'MIT',
    'vits': 'MIT',
    'openvoice': 'MIT',
    'vitsneon': 'BSD-3',
    'neuralhmm': 'MIT',
    'glow': 'MIT',
    'fastpitch': 'Apache 2.0',
    'jenny': 'Jenny License',
    'tortoise': 'Apache 2.0',
    'xtts2': 'CPML (NC)',
    'xtts': 'CPML (NC)',
    'elevenlabs': 'Proprietary',
    'eleven': 'Proprietary',
    'openai': 'Proprietary',
    'hierspeech': 'MIT',
    'pheme': 'CC-BY',
    'speecht5': 'MIT',
    'metavoice': 'Apache 2.0',
    'elevenlabs': 'Proprietary',
    'whisperspeech': 'MIT',
    'Pendrokar/xVASynth': 'GPT3',
}
model_links = {
    'styletts2': 'https://github.com/yl4579/StyleTTS2',
    'tacotron': 'https://github.com/NVIDIA/tacotron2',
    'speedyspeech': 'https://github.com/janvainer/speedyspeech',
    'overflow': 'https://github.com/shivammehta25/OverFlow',
    'vits': 'https://github.com/jaywalnut310/vits',
    'openvoice': 'https://github.com/myshell-ai/OpenVoice',
    'neuralhmm': 'https://github.com/ketranm/neuralHMM',
    'glow': 'https://github.com/jaywalnut310/glow-tts',
    'fastpitch': 'https://fastpitch.github.io/',
    'tortoise': 'https://github.com/neonbjb/tortoise-tts',
    'xtts2': 'https://huggingface.co/coqui/XTTS-v2',
    'xtts': 'https://huggingface.co/coqui/XTTS-v1',
    'elevenlabs': 'https://elevenlabs.io/',
    'openai': 'https://help.openai.com/en/articles/8555505-tts-api',
    'hierspeech': 'https://github.com/sh-lee-prml/HierSpeechpp',
    'pheme': 'https://github.com/PolyAI-LDN/pheme',
    'speecht5': 'https://github.com/microsoft/SpeechT5',
    'metavoice': 'https://github.com/metavoiceio/metavoice-src',
}
# def get_random_split(existing_split=None):
#     choice = random.choice(list(audio_dataset.keys()))
#     if existing_split and choice == existing_split:
#         return get_random_split(choice)
#     else:
#         return choice

# def get_random_splits():
#     choice1 = get_random_split()
#     choice2 = get_random_split(choice1)
#     return (choice1, choice2)
def model_license(name):
    print(name)
    for k, v in AVAILABLE_MODELS.items():
        if k == name:
            if v in model_licenses:
                return model_licenses[v]
    print('---')
    return 'Unknown'
def get_leaderboard(reveal_prelim = False):
    conn = get_db()
    cursor = conn.cursor()
    sql = 'SELECT name, upvote, downvote FROM model'
    # if not reveal_prelim: sql += ' WHERE EXISTS (SELECT 1 FROM model WHERE (upvote + downvote) > 750)'
    if not reveal_prelim: sql += ' WHERE (upvote + downvote) > 300'
    cursor.execute(sql)
    data = cursor.fetchall()
    df = pd.DataFrame(data, columns=['name', 'upvote', 'downvote'])
    # df['license'] = df['name'].map(model_license)
    df['name'] = df['name'].replace(model_names)
    for i in range(len(df)):
        df.loc[i, "name"] = make_link_to_space(df['name'][i], True)
    df['votes'] = df['upvote'] + df['downvote']
    # df['score'] = round((df['upvote'] / df['votes']) * 100, 2) # Percentage score

    ## ELO SCORE
    df['score'] = 1200
    for i in range(len(df)):
        for j in range(len(df)):
            if i != j:
                expected_a = 1 / (1 + 10 ** ((df['score'][j] - df['score'][i]) / 400))
                expected_b = 1 / (1 + 10 ** ((df['score'][i] - df['score'][j]) / 400))
                actual_a = df['upvote'][i] / df['votes'][i]
                actual_b = df['upvote'][j] / df['votes'][j]
                df.at[i, 'score'] += round(32 * (actual_a - expected_a))
                df.at[j, 'score'] += round(32 * (actual_b - expected_b))
    df['score'] = round(df['score'])
    ## ELO SCORE
    df = df.sort_values(by='score', ascending=False)
    # medals
    def assign_medal(rank, assign):
        rank = str(rank + 1)
        if assign:
            if rank == '1':
                rank += 'πŸ₯‡'
            elif rank == '2':
                rank += 'πŸ₯ˆ'
            elif rank == '3':
                rank += 'πŸ₯‰'

        return '#'+ rank

    df['order'] = [assign_medal(i, not reveal_prelim and len(df) > 2) for i in range(len(df))]
    df = df[['order', 'name', 'score', 'votes']]
    return df

def make_link_to_space(model_name, for_leaderboard=False):
    # create a anchor link if a HF space
    style = 'text-decoration: underline;text-decoration-style: dotted;'
    title = ''

    if model_name in AVAILABLE_MODELS:
        style += 'color: var(--link-text-color);'
        title = model_name
    else:
        style += 'font-style: italic;'
        title = 'Disabled for Arena (See AVAILABLE_MODELS within code for why)'

    model_basename = model_name
    if model_name in HF_SPACES:
        model_basename = HF_SPACES[model_name]['name']

    try:
        if(
            for_leaderboard
            and HF_SPACES[model_name]['is_proprietary']
        ):
            model_basename += ' πŸ”'
            title += '; πŸ” = online only or proprietary'
    except:
        pass

    if '/' in model_name:
        return 'πŸ€— <a target="_blank" style="'+ style +'" title="'+ title +'" href="'+ 'https://huggingface.co/spaces/'+ model_name +'">'+ model_basename +'</a>'

    # otherwise just return the model name
    return model_name

def markdown_link_to_space(model_name):
    # create a anchor link if a HF space using markdown syntax
    if '/' in model_name:
        return 'πŸ€— [' + model_name + '](https://huggingface.co/spaces/' + model_name + ')'
    # otherwise just return the model name
    return model_name

def mkuuid(uid):
    if not uid:
        uid = uuid.uuid4()
    return uid
def upvote_model(model, uname):
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute('UPDATE model SET upvote = upvote + 1 WHERE name = ?', (model,))
    if cursor.rowcount == 0:
        cursor.execute('INSERT OR REPLACE INTO model (name, upvote, downvote) VALUES (?, 1, 0)', (model,))
    cursor.execute('INSERT INTO vote (username, model, vote) VALUES (?, ?, ?)', (uname, model, 1,))
    with scheduler.lock:
        conn.commit()
    cursor.close()
def log_text(text, voteid):
    # log only hardcoded sentences
    if (text not in sents):
        return

    conn = get_db()
    cursor = conn.cursor()
    # TODO: multilang
    cursor.execute('INSERT INTO spokentext (spokentext, lang, votelog_id) VALUES (?,?,?)', (text,'en',voteid))
    with scheduler.lock:
        conn.commit()
    cursor.close()
def downvote_model(model, uname):
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute('UPDATE model SET downvote = downvote + 1 WHERE name = ?', (model,))
    if cursor.rowcount == 0:
        cursor.execute('INSERT OR REPLACE INTO model (name, upvote, downvote) VALUES (?, 0, 1)', (model,))
    cursor.execute('INSERT INTO vote (username, model, vote) VALUES (?, ?, ?)', (uname, model, -1,))
    with scheduler.lock:
        conn.commit()
    cursor.close()

def a_is_better(model1, model2, userid, text):
    return is_better(model1, model2, userid, text, True)
def b_is_better(model1, model2, userid, text):
    return is_better(model1, model2, userid, text, False)

def is_better(model1, model2, userid, text, chose_a):
    if(
        (
            not model1 in AVAILABLE_MODELS.keys()
            and not model1 in AVAILABLE_MODELS.values()
        )
        or (
            not model2 in AVAILABLE_MODELS.keys()
            and not model2 in AVAILABLE_MODELS.values()
        )
    ):
        raise gr.Error('Sorry, please try voting again.')

    # userid is unique for each cast vote pair
    userid = mkuuid(userid)
    if model1 and model2:
        conn = get_db()
        cursor = conn.cursor()
        sql_query = 'INSERT INTO votelog (username, chosen, rejected) VALUES (?, ?, ?)'
        if chose_a:
            cursor.execute(sql_query, (str(userid), model1, model2))
        else:
            cursor.execute(sql_query, (str(userid), model2, model1))

        with scheduler.lock:
            conn.commit()
            # also retrieve primary key ID
            cursor.execute('SELECT last_insert_rowid()')
            votelogid = cursor.fetchone()[0]
            cursor.close()

        if chose_a:
            upvote_model(model1, str(userid))
            downvote_model(model2, str(userid))
        else:
            upvote_model(model2, str(userid))
            downvote_model(model1, str(userid))
        log_text(text, votelogid)

    return reload(model1, model2, userid, chose_a=chose_a, chose_b=(not chose_a))

def both_bad(model1, model2, userid):
    userid = mkuuid(userid)
    if model1 and model2:
        downvote_model(model1, str(userid))
        downvote_model(model2, str(userid))
    return reload(model1, model2, userid)
def both_good(model1, model2, userid):
    userid = mkuuid(userid)
    if model1 and model2:
        upvote_model(model1, str(userid))
        upvote_model(model2, str(userid))
    return reload(model1, model2, userid)
def reload(chosenmodel1=None, chosenmodel2=None, userid=None, chose_a=False, chose_b=False):
    # Select random splits
    # row = random.choice(list(audio_dataset['train']))
    # options = list(random.choice(list(audio_dataset['train'])).keys())
    # split1, split2 = random.sample(options, 2)
    # choice1, choice2 = (row[split1], row[split2])
    # if chosenmodel1 in model_names:
    #     chosenmodel1 = model_names[chosenmodel1]
    # if chosenmodel2 in model_names:
    #     chosenmodel2 = model_names[chosenmodel2]
    # out = [
    #     (choice1['sampling_rate'], choice1['array']),
    #     (choice2['sampling_rate'], choice2['array']),
    #     split1,
    #     split2
    # ]
    # if userid: out.append(userid)
    # if chosenmodel1: out.append(f'This model was {chosenmodel1}')
    # if chosenmodel2: out.append(f'This model was {chosenmodel2}')
    # return out
    # return (f'This model was {chosenmodel1}', f'This model was {chosenmodel2}', gr.update(visible=False), gr.update(visible=False))
    # return (gr.update(variant='secondary', value=chosenmodel1, interactive=False), gr.update(variant='secondary', value=chosenmodel2, interactive=False))
    chosenmodel1 = make_link_to_space(chosenmodel1)
    chosenmodel2 = make_link_to_space(chosenmodel2)
    out = [
        gr.update(interactive=False, visible=False),
        gr.update(interactive=False, visible=False)
    ]
    style = 'text-align: center; font-size: 1rem; margin-bottom: 0; padding: var(--input-padding)'
    if chose_a == True:
        out.append(gr.update(value=f'<p style="{style}">Your vote: {chosenmodel1}</p>', visible=True))
        out.append(gr.update(value=f'<p style="{style}">{chosenmodel2}</p>', visible=True))
    else:
        out.append(gr.update(value=f'<p style="{style}">{chosenmodel1}</p>', visible=True))
        out.append(gr.update(value=f'<p style="{style}">Your vote: {chosenmodel2}</p>', visible=True))
    out.append(gr.update(visible=True))
    return out

with gr.Blocks() as leaderboard:
    gr.Markdown(LDESC)
    # df = gr.Dataframe(interactive=False, value=get_leaderboard())
    df = gr.Dataframe(
        interactive=False,
        min_width=0,
        wrap=True,
        column_widths=[30, 200, 50, 50],
        datatype=["str", "html", "number", "number"]
    )
    with gr.Row():
        reveal_prelim = gr.Checkbox(label="Reveal preliminary results", info="Show all models, including models with very few human ratings.", scale=1)
        reloadbtn = gr.Button("Refresh", scale=3)
    reveal_prelim.input(get_leaderboard, inputs=[reveal_prelim], outputs=[df])
    leaderboard.load(get_leaderboard, inputs=[reveal_prelim], outputs=[df])
    reloadbtn.click(get_leaderboard, inputs=[reveal_prelim], outputs=[df])
    # 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.")

# with gr.Blocks() as vote:
#     useridstate = gr.State()
#     gr.Markdown(INSTR)
#     # gr.LoginButton()
#     with gr.Row():
#         gr.HTML('<div align="left"><h3>Model A</h3></div>')
#         gr.HTML('<div align="right"><h3>Model B</h3></div>')
#     model1 = gr.Textbox(interactive=False, visible=False, lines=1, max_lines=1)
#     model2 = gr.Textbox(interactive=False, visible=False, lines=1, max_lines=1)
#     # with gr.Group():
#     #     with gr.Row():
#     #         prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A")
#     #         prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="right")
#     #     with gr.Row():
#     #         aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
#     #         aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
#     with gr.Group():
#         with gr.Row():
#             with gr.Column():
#                 with gr.Group():
#                     prevmodel1 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model A", lines=1, max_lines=1)
#                     aud1 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})
#             with gr.Column():
#                 with gr.Group():
#                     prevmodel2 = gr.Textbox(interactive=False, show_label=False, container=False, value="Vote to reveal model B", text_align="right", lines=1, max_lines=1)
#                     aud2 = gr.Audio(interactive=False, show_label=False, show_download_button=False, show_share_button=False, waveform_options={'waveform_progress_color': '#3C82F6'})


#     with gr.Row():
#         abetter = gr.Button("A is Better", variant='primary', scale=4)
#         # skipbtn = gr.Button("Skip", scale=1)
#         bbetter = gr.Button("B is Better", variant='primary', scale=4)
#     with gr.Row():
#         bothbad = gr.Button("Both are Bad", scale=2)
#         skipbtn = gr.Button("Skip", scale=1)
#         bothgood = gr.Button("Both are Good", scale=2)
#     outputs = [aud1, aud2, model1, model2, useridstate, prevmodel1, prevmodel2]
#     abetter.click(a_is_better, outputs=outputs, inputs=[model1, model2, useridstate])
#     bbetter.click(b_is_better, outputs=outputs, inputs=[model1, model2, useridstate])
#     skipbtn.click(b_is_better, outputs=outputs, inputs=[model1, model2, useridstate])

#     bothbad.click(both_bad, outputs=outputs, inputs=[model1, model2, useridstate])
#     bothgood.click(both_good, outputs=outputs, inputs=[model1, model2, useridstate])

#     vote.load(reload, outputs=[aud1, aud2, model1, model2])
def doloudnorm(path):
    data, rate = sf.read(path)
    meter = pyln.Meter(rate)
    loudness = meter.integrated_loudness(data)
    loudness_normalized_audio = pyln.normalize.loudness(data, loudness, -12.0)
    sf.write(path, loudness_normalized_audio, rate)

def doresample(path_to_wav):
    pass
##########################
# 2x speedup (hopefully) #
##########################

def synthandreturn(text, request: gr.Request):
    text = text.strip()
    if len(text) > MAX_SAMPLE_TXT_LENGTH:
        raise gr.Error(f'You exceeded the limit of {MAX_SAMPLE_TXT_LENGTH} characters')
    if len(text) < MIN_SAMPLE_TXT_LENGTH:
        raise gr.Error(f'Please input a text longer than {MIN_SAMPLE_TXT_LENGTH} characters')
    if (
        # test toxicity if not prepared text
        text not in sents
        and toxicity.predict(text)['toxicity'] > 0.8
    ):
        print(f'Detected toxic content! "{text}"')
        raise gr.Error('Your text failed the toxicity test')
    if not text:
        raise gr.Error(f'You did not enter any text')
    # Check language
    try:
        if (
            text not in sents
            and not detect(text) == "en"
        ):
            gr.Warning('Warning: The input text may not be in English')
    except:
        pass
    # Get two random models

    # forced model: your TTS model versus The World!!!
    # mdl1 = 'Pendrokar/xVASynth'
    # vsModels = dict(AVAILABLE_MODELS)
    # del vsModels[mdl1]
    # randomize position of the forced model
    # mdl2 = random.sample(list(vsModels.keys()), 1)
    # forced random
    # mdl1, mdl2 = random.sample(list([mdl1, mdl2[0]]), 2)

    # actual random
    mdl1, mdl2 = random.sample(list(AVAILABLE_MODELS.keys()), 2)
    # pointless saving of text to DB
    # log_text(text)
    print("[debug] Using", mdl1, mdl2)
    def predict_and_update_result(text, model, result_storage, request:gr.Request):

        hf_headers = {}
        try:
            if HF_SPACES[model]['is_zero_gpu_space']:
                hf_headers = {"X-IP-Token": request.headers['x-ip-token']}
        except:
            pass

        # 2 attempts
        attempt_count = 0
        while attempt_count < 2:
            try:
                if model in AVAILABLE_MODELS:
                    if '/' in model:
                        # Use public HF Space
                        if (model not in hf_clients):
                            hf_clients[model] = Client(model, hf_token=hf_token, headers=hf_headers)
                        mdl_space = hf_clients[model]

                        # print(f"{model}: Fetching endpoints of HF Space")
                        # assume the index is one of the first 9 return params
                        return_audio_index = int(HF_SPACES[model]['return_audio_index'])
                        endpoints = mdl_space.view_api(all_endpoints=True, print_info=False, return_format='dict')
    
                        api_name = None
                        fn_index = None
                        end_parameters = None
                        # has named endpoint
                        if '/' == HF_SPACES[model]['function'][0]:
                            # audio sync function name
                            api_name = HF_SPACES[model]['function']
    
                            end_parameters = _get_param_examples(
                                endpoints['named_endpoints'][api_name]['parameters']
                            )
                        # has unnamed endpoint
                        else:
                            # endpoint index is the first character
                            fn_index = int(HF_SPACES[model]['function'])
    
                            end_parameters = _get_param_examples(
                                endpoints['unnamed_endpoints'][str(fn_index)]['parameters']
                            )
    
                        space_inputs = _override_params(end_parameters, model)
    
                        # force text
                        space_inputs[HF_SPACES[model]['text_param_index']] = text

                        print(f"{model}: Sending request to HF Space")
                        results = mdl_space.predict(*space_inputs, api_name=api_name, fn_index=fn_index)

                        # return path to audio
                        result = results
                        if (not isinstance(results, str)):
                            # return_audio_index may be a filepath string
                            result = results[return_audio_index]
                        if (isinstance(result, dict)):
                            # return_audio_index is a dictionary
                            result = results[return_audio_index]['value']
                    else:
                        # Use the private HF Space
                        result = router.predict(text, AVAILABLE_MODELS[model].lower(), api_name="/synthesize")
                else:
                    result = router.predict(text, model.lower(), api_name="/synthesize")
                break
            except Exception as e:
                attempt_count += 1
                print(repr(e))
                print(f"{model}: Unable to call API (attempt: {attempt_count})")
                # sleep for three seconds to avoid spamming the server with requests
                time.sleep(3)

                # Fetch and store client again
                hf_headers = {}
                hf_clients[model] = Client(model, hf_token=hf_token)

        if attempt_count > 2:
            raise gr.Error(f"{model}: Failed to call model")
        else:
            print('Done with', model)

        try:
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
                audio = AudioSegment.from_file(result)
                current_sr = audio.frame_rate
                if current_sr > 24000:
                    print(f"{model}: Resampling")
                    audio = audio.set_frame_rate(24000)
                try:
                    print(f"{model}: Trying to normalize audio")
                    audio = match_target_amplitude(audio, -20)
                except:
                    print(f"{model}: [WARN] Unable to normalize audio")
                audio.export(f.name, format="wav")
                os.unlink(result)
                result = f.name
        except:
            print(f"{model}: [WARN] Unable to resample audio")
            pass
        if model in AVAILABLE_MODELS.keys(): model = AVAILABLE_MODELS[model]
        result_storage[model] = result

    def _get_param_examples(parameters):
        example_inputs = []
        for param_info in parameters:
            if (
                param_info['component'] == 'Radio'
                or param_info['component'] == 'Dropdown'
                or param_info['component'] == 'Audio'
                or param_info['python_type']['type'] == 'str'
            ):
                example_inputs.append(str(param_info['example_input']))
                continue
            if param_info['python_type']['type'] == 'int':
                example_inputs.append(int(param_info['example_input']))
                continue
            if param_info['python_type']['type'] == 'float':
                example_inputs.append(float(param_info['example_input']))
                continue
            if param_info['python_type']['type'] == 'bool':
                example_inputs.append(bool(param_info['example_input']))
                continue

        return example_inputs

    def _override_params(inputs, modelname):
        try:
            for key,value in OVERRIDE_INPUTS[modelname].items():
                inputs[key] = value
            print(f"{modelname}: Default inputs overridden by Arena")
        except:
            pass

        return inputs

    mdl1k = mdl1
    mdl2k = mdl2
    print(mdl1k, mdl2k)
    if mdl1 in AVAILABLE_MODELS.keys(): mdl1k=AVAILABLE_MODELS[mdl1]
    if mdl2 in AVAILABLE_MODELS.keys(): mdl2k=AVAILABLE_MODELS[mdl2]
    results = {}
    print(f"Sending models {mdl1k} and {mdl2k} to API")
    thread1 = threading.Thread(target=predict_and_update_result, args=(text, mdl1k, results, request))
    thread2 = threading.Thread(target=predict_and_update_result, args=(text, mdl2k, results, request))

    thread1.start()
    thread2.start()
    thread1.join(180)
    thread2.join(180)
    #debug
    # print(results)
    # print(list(results.keys())[0])
    # y, sr = librosa.load(results[list(results.keys())[0]], sr=None)
    # print(sr)
    # print(list(results.keys())[1])
    # y, sr = librosa.load(results[list(results.keys())[1]], sr=None)
    # print(sr)
    #debug
    #     outputs = [text, btn, r2, model1, model2, aud1, aud2, abetter, bbetter, prevmodel1, prevmodel2, nxtroundbtn]

    # cache the result
    for model in [mdl1k, mdl2k]:
        # skip caching if not hardcoded sentence
        if (text not in sents):
            break

        already_cached = False
        # check if already cached
        for cached_sample in cached_samples:
            # TODO:replace cached
            if (cached_sample.transcript == text and cached_sample.modelName == model):
                already_cached = True
                break

        if (already_cached):
            continue

        try:
            cached_samples.append(Sample(results[model], text, model))
        except:
            pass

    # all_pairs = generate_matching_pairs(cached_samples)

    print(f"Retrieving models {mdl1k} and {mdl2k} from API")
    return (
        text,
        "Synthesize",
        gr.update(visible=True), # r2
        mdl1, # model1
        mdl2, # model2
        gr.update(visible=True, value=results[mdl1k], interactive=False, autoplay=True), # aud1
        gr.update(visible=True, value=results[mdl2k], interactive=False, autoplay=False), # aud2
        gr.update(visible=True, interactive=False), #abetter
        gr.update(visible=True, interactive=False), #bbetter
        gr.update(visible=False), #prevmodel1
        gr.update(visible=False), #prevmodel2
        gr.update(visible=False), #nxt round btn
        # reset gr.State aplayed & bplayed
        False, #aplayed
        False, #bplayed
    )
    # return (
    #     text,
    #     "Synthesize",
    #     gr.update(visible=True), # r2
    #     mdl1, # model1
    #     mdl2, # model2
    #     # 'Vote to reveal model A', # prevmodel1
    #     gr.update(visible=True, value=router.predict(
    #         text,
    #         AVAILABLE_MODELS[mdl1],
    #         api_name="/synthesize"
    #     )), # aud1
    #     # 'Vote to reveal model B', # prevmodel2
    #     gr.update(visible=True, value=router.predict(
    #         text,
    #         AVAILABLE_MODELS[mdl2],
    #         api_name="/synthesize"
    #     )), # aud2
    #     gr.update(visible=True, interactive=True),
    #     gr.update(visible=True, interactive=True),
    #     gr.update(visible=False),
    #     gr.update(visible=False),
    #     gr.update(visible=False), #nxt round btn
    # )

def unlock_vote(btn_index, aplayed, bplayed):
    # sample played
    if btn_index == 0:
        aplayed = True
    if btn_index == 1:
        bplayed = True

    # both audio samples played
    if bool(aplayed) and bool(bplayed):
        # print('Both audio samples played, voting unlocked')
        return [gr.update(interactive=True), gr.update(interactive=True), True, True]

    return [gr.update(), gr.update(), aplayed, bplayed]

def play_other(bplayed):
    return bplayed

def get_userid(session_hash: str, request):
    # JS cookie
    if (session_hash != ''):
        # print('auth by session cookie')
        return sha1(bytes(session_hash.encode('ascii')), usedforsecurity=False).hexdigest()

    if request.username:
        # print('auth by username')
        # by HuggingFace username - requires `auth` to be enabled therefore denying access to anonymous users
        return sha1(bytes(request.username.encode('ascii')), usedforsecurity=False).hexdigest()
    else:
        # print('auth by ip')
        # by IP address - unreliable when gradio within HTML iframe
        # return sha1(bytes(request.client.host.encode('ascii')), usedforsecurity=False).hexdigest()
        # by browser session cookie - Gradio on HF is run in an HTML iframe, access to parent session required to reach session token
        # return sha1(bytes(request.headers.encode('ascii'))).hexdigest()
        # by browser session hash - Not a cookie, session hash changes on page reload
        return sha1(bytes(request.session_hash.encode('ascii')), usedforsecurity=False).hexdigest()

# Give user a cached audio sample pair they have yet to vote on
def give_cached_sample(session_hash: str, request: gr.Request):
    # add new userid to voting_users from Browser session hash
    # stored only in RAM
    userid = get_userid(session_hash, request)

    if userid not in voting_users:
        voting_users[userid] = User(userid)

    def get_next_pair(user: User):
        # FIXME: all_pairs var out of scope
        # all_pairs = generate_matching_pairs(cached_samples)

        # for pair in all_pairs:
        for pair in generate_matching_pairs(cached_samples):
            hash1 = md5(bytes((pair[0].modelName + pair[0].transcript).encode('ascii'))).hexdigest()
            hash2 = md5(bytes((pair[1].modelName + pair[1].transcript).encode('ascii'))).hexdigest()
            pair_key = (hash1, hash2)
            if (
                pair_key not in user.voted_pairs
                # or in reversed order
                and (pair_key[1], pair_key[0]) not in user.voted_pairs
            ):
                return pair
        return None

    pair = get_next_pair(voting_users[userid])
    if pair is None:
        return [
            *clear_stuff(),
            # disable get cached sample button
            gr.update(interactive=False)
        ]

    return (
        gr.update(visible=True, value=pair[0].transcript, elem_classes=['blurred-text']),
        "Synthesize",
        gr.update(visible=True), # r2
        pair[0].modelName, # model1
        pair[1].modelName, # model2
        gr.update(visible=True, value=pair[0].filename, interactive=False, autoplay=True), # aud1
        gr.update(visible=True, value=pair[1].filename, interactive=False, autoplay=False), # aud2
        gr.update(visible=True, interactive=False), #abetter
        gr.update(visible=True, interactive=False), #bbetter
        gr.update(visible=False), #prevmodel1
        gr.update(visible=False), #prevmodel2
        gr.update(visible=False), #nxt round btn
        # reset aplayed, bplayed audio playback events
        False, #aplayed
        False, #bplayed
        # fetch cached btn
        gr.update(interactive=True)
    )

# note the vote on cached sample pair
def voted_on_cached(modelName1: str, modelName2: str, transcript: str, session_hash: str, request: gr.Request):
    userid = get_userid(session_hash, request)
    # print(f'userid voted on cached: {userid}')

    if userid not in voting_users:
        voting_users[userid] = User(userid)

    hash1 = md5(bytes((modelName1 + transcript).encode('ascii'))).hexdigest()
    hash2 = md5(bytes((modelName2 + transcript).encode('ascii'))).hexdigest()

    voting_users[userid].voted_pairs.add((hash1, hash2))
    return []

def randomsent():
    return '⚑', random.choice(sents), '🎲'
def clear_stuff():
    return [
        gr.update(visible=True, value="", elem_classes=[]),
        "Synthesize",
        gr.update(visible=False), # r2
        '', # model1
        '', # model2
        gr.update(visible=False, interactive=False, autoplay=False), # aud1
        gr.update(visible=False, interactive=False, autoplay=False), # aud2
        gr.update(visible=False, interactive=False), #abetter
        gr.update(visible=False, interactive=False), #bbetter
        gr.update(visible=False), #prevmodel1
        gr.update(visible=False), #prevmodel2
        gr.update(visible=False), #nxt round btn
        False, #aplayed
        False, #bplayed
    ]

def disable():
    return [gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False)]
def enable():
    return [gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True)]
def unblur_text():
    return gr.update(elem_classes=[])

unblur_js = 'document.getElementById("arena-text-input").classList.remove("blurred-text")'
shortcut_js = """
<script>
function shortcuts(e) {
    var event = document.all ? window.event : e;
    switch (e.target.tagName.toLowerCase()) {
        case "input":
        case "textarea":
            break;
        default:
            switch (e.key.toLowerCase()) {
                case "a":
                    document.getElementById("arena-a-better").click();
                    break;
                case "b":
                    document.getElementById("arena-b-better").click();
                    break;
                case "n":
                    document.getElementById("arena-next-round").click();
                    break;
            }
    }
}
document.addEventListener('keypress', shortcuts, false);
</script>
"""

with gr.Blocks() as vote:
    session_hash = gr.Textbox(visible=False, value='')

    # sample played, using Checkbox so that JS can fetch the value
    aplayed = gr.Checkbox(visible=False, value=False)
    bplayed = gr.Checkbox(visible=False, value=False)
    # voter ID
    useridstate = gr.State()
    gr.Markdown(INSTR)
    with gr.Group():
        with gr.Row():
            cachedt = gr.Button('⚑', scale=0, min_width=0, variant='tool', interactive=True)
            text = gr.Textbox(
                container=False,
                show_label=False,
                placeholder="Enter text to synthesize",
                lines=1,
                max_lines=1,
                scale=9999999,
                min_width=0,
                elem_id="arena-text-input",
            )
            randomt = gr.Button('🎲', scale=0, min_width=0, variant='tool')
        randomt\
            .click(randomsent, outputs=[cachedt, text, randomt])\
            .then(None, js="() => "+ unblur_js)
        btn = gr.Button("Synthesize", variant='primary')
    model1 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
    model2 = gr.Textbox(interactive=False, lines=1, max_lines=1, visible=False)
    with gr.Row(visible=False) as r2:
        with gr.Column():
            with gr.Group():
                aud1 = gr.Audio(
                    interactive=False,
                    show_label=False,
                    show_download_button=False,
                    show_share_button=False,
                    waveform_options={'waveform_progress_color': '#EF4444'},
                    # var(--color-red-500)'}); gradio only accepts HEX and CSS color
                )
                abetter = gr.Button(
                    "A is better [a]",
                    elem_id='arena-a-better',
                    variant='primary',
                    interactive=False,
                )
                prevmodel1 = gr.HTML(show_label=False, value="Vote to reveal model A", visible=False)
        with gr.Column():
            with gr.Group():
                aud2 = gr.Audio(
                    interactive=False,
                    show_label=False,
                    show_download_button=False,
                    show_share_button=False,
                    waveform_options={'waveform_progress_color': '#3C82F6'},
                    # var(--secondary-500)'}); gradio only accepts HEX and CSS color
                )
                bbetter = gr.Button(
                    "B is better [b]",
                    elem_id='arena-b-better',
                    variant='primary',
                    interactive=False
                )
                prevmodel2 = gr.HTML(show_label=False, value="Vote to reveal model B", visible=False)
    nxtroundbtn = gr.Button(
        '⚑ Next round [n]',
        elem_id='arena-next-round',
        visible=False
    )
    # outputs = [text, btn, r2, model1, model2, prevmodel1, aud1, prevmodel2, aud2, abetter, bbetter]
    outputs = [
        text,
        btn,
        r2,
        model1,
        model2,
        aud1,
        aud2,
        abetter,
        bbetter,
        prevmodel1,
        prevmodel2,
        nxtroundbtn,
        aplayed,
        bplayed,
    ]
    """
    text,
        "Synthesize",
        gr.update(visible=True), # r2
        mdl1, # model1
        mdl2, # model2
        gr.update(visible=True, value=results[mdl1]), # aud1
        gr.update(visible=True, value=results[mdl2]), # aud2
        gr.update(visible=True, interactive=False), #abetter
        gr.update(visible=True, interactive=False), #bbetter
        gr.update(visible=False), #prevmodel1
        gr.update(visible=False), #prevmodel2
        gr.update(visible=False), #nxt round btn"""
    btn\
        .click(disable, outputs=[btn, abetter, bbetter, cachedt])\
        .then(synthandreturn, inputs=[text], outputs=outputs)\
        .then(enable, outputs=[btn, gr.State(), gr.State(), cachedt])\
        .then(None, js="() => "+ unblur_js)
    nxtroundbtn\
        .click(disable, outputs=[btn, abetter, bbetter, cachedt])\
        .then(give_cached_sample, inputs=[session_hash], outputs=[*outputs, cachedt])\
        .then(enable, outputs=[btn, gr.State(), gr.State(), gr.State()])

    # fetch a comparison pair from cache
    cachedt\
        .click(disable, outputs=[btn, abetter, bbetter, cachedt])\
        .then(give_cached_sample, inputs=[session_hash], outputs=[*outputs, cachedt])\
        .then(enable, outputs=[btn, gr.State(), gr.State(), gr.State()])
    # TODO: await download of sample before allowing playback

    # Allow interaction with the vote buttons only when both audio samples have finished playing
    aud1\
        .stop(
            unlock_vote,
            outputs=[abetter, bbetter, aplayed, bplayed],
            inputs=[gr.State(value=0), aplayed, bplayed],
        )\
        .then(
            None,
            inputs=[bplayed],
            js="(b) => b ? 0 : document.querySelector('.row .gap+.gap button.play-pause-button').click()",
        )
    # autoplay if unplayed
    aud2\
        .stop(
            unlock_vote,
            outputs=[abetter, bbetter, aplayed, bplayed],
            inputs=[gr.State(value=1), aplayed, bplayed],
        )\
        .then(None, js="() => "+ unblur_js)
    # aud1.input(
    #     None,
    #     js="() => {console.log(new Date().getTime().toString()+'input')}",
    # )
    # aud1.change(
    #     None,
    #     js="() => {console.log(new Date().getTime().toString()+'change')}",
    # )

    # nxt_outputs = [prevmodel1, prevmodel2, abetter, bbetter]
    nxt_outputs = [abetter, bbetter, prevmodel1, prevmodel2, nxtroundbtn]
    abetter\
        .click(a_is_better, outputs=nxt_outputs, inputs=[model1, model2, useridstate, text])\
        .then(voted_on_cached, inputs=[model1, model2, text, session_hash], outputs=[])
    bbetter\
        .click(b_is_better, outputs=nxt_outputs, inputs=[model1, model2, useridstate, text])\
        .then(voted_on_cached, inputs=[model1, model2, text, session_hash], outputs=[])
    # skipbtn.click(b_is_better, outputs=outputs, inputs=[model1, model2, useridstate])

    # bothbad.click(both_bad, outputs=outputs, inputs=[model1, model2, useridstate])
    # bothgood.click(both_good, outputs=outputs, inputs=[model1, model2, useridstate])

    # get session cookie
    vote\
        .load(
            None,
            None,
            session_hash,
            js="() => { return getArenaCookie('session') }",
        )
    # give a cached sample pair to voter; .then() did not work here
    vote\
        .load(give_cached_sample, inputs=[session_hash], outputs=[*outputs, cachedt])

with gr.Blocks() as about:
    gr.Markdown(ABOUT)
with gr.Blocks() as tts_info:
    gr.Markdown(TTS_INFO)
    gr.HTML(TTS_IFRAME)
# with gr.Blocks() as admin:
#     rdb = gr.Button("Reload Audio Dataset")
#     # rdb.click(reload_audio_dataset, outputs=rdb)
#     with gr.Group():
#         dbtext = gr.Textbox(label="Type \"delete db\" to confirm", placeholder="delete db")
#         ddb = gr.Button("Delete DB")
#     ddb.click(del_db, inputs=dbtext, outputs=ddb)
# Blur cached sample text so the voting user picks up mispronouncements
with gr.Blocks(theme=theme, css="footer {visibility: hidden}textbox{resize:none} .blurred-text {filter: blur(0.15em);}", head=shortcut_js, title="TTS Arena") as demo:
    gr.Markdown(DESCR)
    # gr.TabbedInterface([vote, leaderboard, about, admin], ['Vote', 'Leaderboard', 'About', 'Admin (ONLY IN BETA)'])
    gr.TabbedInterface([vote, leaderboard, about, tts_info], ['πŸ—³οΈ Vote', 'πŸ† Leaderboard', 'πŸ“„ About', 'πŸ—£ Contenders'])
    if CITATION_TEXT:
        with gr.Row():
            with gr.Accordion("Citation", open=False):
                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.")


demo\
    .queue(api_open=False, default_concurrency_limit=3)\
    .launch(show_api=False, show_error=True)