File size: 56,440 Bytes
1543414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Main module for the WhisperKit Evaluation Dashboard.
This module sets up and runs the Gradio interface for the WhisperKit Evaluation Dashboard,
allowing users to explore and compare speech recognition model performance across different
devices, operating systems, and datasets.
"""

import json
import os
import re
from math import ceil, floor

import gradio as gr
import pandas as pd
from argmax_gradio_components import RangeSlider
from dotenv import load_dotenv
from huggingface_hub import login

# Import custom constants and utility functions
from constants import (
    BANNER_TEXT,
    CITATION_BUTTON_LABEL,
    CITATION_BUTTON_TEXT,
    COL_NAMES,
    HEADER,
    LANGUAGE_MAP,
    METHODOLOGY_TEXT,
    PERFORMANCE_TEXT,
    QUALITY_TEXT,
)
from utils import (
    add_datasets_to_performance_columns,
    add_datasets_to_quality_columns,
    calculate_parity,
    create_confusion_matrix_plot,
    create_initial_performance_column_dict,
    create_initial_quality_column_dict,
    css,
    fields,
    get_os_name_and_version,
    make_dataset_wer_clickable_link,
    make_model_name_clickable_link,
    make_multilingual_model_clickable_link,
    plot_metric,
    read_json_line_by_line,
)

# Load environment variables
load_dotenv()

# Get the Hugging Face token from the environment variable
HF_TOKEN = os.getenv("HF_TOKEN")

# Use the token for login
login(token=HF_TOKEN, add_to_git_credential=True)

# Define repository and directory information
repo_id = "argmaxinc/whisperkit-evals-dataset"
directory = "xcresults/benchmark_results"
local_dir = ""

# Load benchmark data from JSON files
PERFORMANCE_DATA = read_json_line_by_line("dashboard_data/performance_data.json")
QUALITY_DATA = read_json_line_by_line("dashboard_data/quality_data.json")

# Convert JSON data to pandas DataFrames
quality_df = pd.json_normalize(QUALITY_DATA)
benchmark_df = pd.json_normalize(PERFORMANCE_DATA)

# Process timestamp data
benchmark_df["timestamp"] = pd.to_datetime(benchmark_df["timestamp"]).dt.tz_localize(
    None
)
benchmark_df["timestamp"] = pd.to_datetime(benchmark_df["timestamp"]).dt.tz_localize(
    None
)

# First create a temporary column for model length
sorted_quality_df = (
    quality_df.assign(model_len=quality_df["model"].str.len())
    .sort_values(
        by=["model_len", "model", "timestamp"],
        ascending=[True, True, False],
    )
    .drop(columns=["model_len"])
    .drop_duplicates(subset=["model"], keep="first")
    .reset_index(drop=True)
)

sorted_performance_df = (
    benchmark_df.assign(model_len=benchmark_df["model"].str.len())
    .sort_values(
        by=["model_len", "model", "device", "os", "timestamp"],
        ascending=[True, True, True, True, False],
    )
    .drop(columns=["model_len"])
    .drop_duplicates(subset=["model", "device", "os"], keep="first")
    .reset_index(drop=True)
)

# Identify dataset-specific columns
dataset_wer_columns = [
    col for col in sorted_quality_df.columns if col.startswith("dataset_wer.")
]
dataset_speed_columns = [
    col for col in sorted_performance_df.columns if col.startswith("dataset_speed.")
]
dataset_toks_columns = [
    col
    for col in sorted_performance_df.columns
    if col.startswith("dataset_tokens_per_second.")
]

# Extract dataset names
QUALITY_DATASETS = [col.split(".")[-1] for col in dataset_wer_columns]
PERFORMANCE_DATASETS = [col.split(".")[-1] for col in dataset_speed_columns]

# Prepare DataFrames for display
model_df = sorted_quality_df[
    ["model", "average_wer", "qoi", "timestamp"] + dataset_wer_columns
]
performance_df = sorted_performance_df[
    [
        "model",
        "device",
        "os",
        "average_wer",
        "qoi",
        "speed",
        "tokens_per_second",
        "timestamp",
    ]
    + dataset_speed_columns
    + dataset_toks_columns
].copy()

# Rename columns for clarity
performance_df = performance_df.rename(
    lambda x: COL_NAMES[x] if x in COL_NAMES else x, axis="columns"
)
model_df = model_df.rename(
    lambda x: COL_NAMES[x] if x in COL_NAMES else x, axis="columns"
)

# Process dataset-specific columns
for col in dataset_wer_columns:
    dataset_name = col.split(".")[-1]
    model_df = model_df.rename(columns={col: dataset_name})
    model_df[dataset_name] = model_df.apply(
        lambda x: make_dataset_wer_clickable_link(x, dataset_name), axis=1
    )

for col in dataset_speed_columns:
    dataset_name = col.split(".")[-1]
    performance_df = performance_df.rename(
        columns={
            col: f"{'Short-Form' if dataset_name == 'librispeech-10mins' else 'Long-Form'} Speed"
        }
    )

for col in dataset_toks_columns:
    dataset_name = col.split(".")[-1]
    performance_df = performance_df.rename(
        columns={
            col: f"{'Short-Form' if dataset_name == 'librispeech-10mins' else 'Long-Form'} Tok/s"
        }
    )

# Calculate parity with M2 Ultra
m2_ultra_wer = (
    performance_df[performance_df["Device"] == "Apple M2 Ultra"]
    .groupby("Model")["Average WER"]
    .first()
)
performance_df["Parity %"] = performance_df.apply(
    lambda row: calculate_parity(m2_ultra_wer, row), axis=1
)

# Process model names for display
model_df["model_raw"] = model_df["Model"].copy()
performance_df["model_raw"] = performance_df["Model"].copy()
model_df["Model"] = model_df["Model"].apply(lambda x: make_model_name_clickable_link(x))
performance_df["Model"] = performance_df["Model"].apply(
    lambda x: make_model_name_clickable_link(x)
)

# Extract unique devices and OS versions
PERFORMANCE_DEVICES = performance_df["Device"].unique().tolist()
PERFORMANCE_OS = performance_df["OS"].apply(get_os_name_and_version).unique().tolist()
PERFORMANCE_OS.sort()

# Create initial column dictionaries and update with dataset information
initial_performance_column_dict = create_initial_performance_column_dict()
initial_quality_column_dict = create_initial_quality_column_dict()

performance_column_info = add_datasets_to_performance_columns(
    initial_performance_column_dict, PERFORMANCE_DATASETS
)
quality_column_info = add_datasets_to_quality_columns(
    initial_quality_column_dict, QUALITY_DATASETS
)

# Unpack the returned dictionaries
updated_performance_column_dict = performance_column_info["column_dict"]
updated_quality_column_dict = quality_column_info["column_dict"]

PerformanceAutoEvalColumn = performance_column_info["AutoEvalColumn"]
QualityAutoEvalColumn = quality_column_info["AutoEvalColumn"]

# Define column sets for different views
PERFORMANCE_COLS = performance_column_info["COLS"]
QUALITY_COLS = quality_column_info["COLS"]
PERFORMANCE_TYPES = performance_column_info["TYPES"]
QUALITY_TYPES = quality_column_info["TYPES"]
PERFORMANCE_ALWAYS_HERE_COLS = performance_column_info["ALWAYS_HERE_COLS"]
QUALITY_ALWAYS_HERE_COLS = quality_column_info["ALWAYS_HERE_COLS"]
PERFORMANCE_TOGGLE_COLS = performance_column_info["TOGGLE_COLS"]
QUALITY_TOGGLE_COLS = quality_column_info["TOGGLE_COLS"]
PERFORMANCE_SELECTED_COLS = performance_column_info["SELECTED_COLS"]
QUALITY_SELECTED_COLS = quality_column_info["SELECTED_COLS"]


def performance_filter(
    df,
    columns,
    model_query,
    exclude_models,
    devices,
    os,
    short_speed_slider,
    long_speed_slider,
    short_toks_slider,
    long_toks_slider,
):
    """
    Filters the performance DataFrame based on specified criteria.
    :param df: The DataFrame to be filtered.
    :param columns: The columns to be included in the filtered DataFrame.
    :param model_query: The query string to filter the 'Model' column.
    :param exclude_models: Models to exclude from the results.
    :param devices: The devices to filter the 'Device' column.
    :param os: The list of operating systems to filter the 'OS' column.
    :param short_speed_slider: The range of values to filter the 'Short-Form Speed' column.
    :param long_speed_slider: The range of values to filter the 'Long-Form Speed' column.
    :param short_toks_slider: The range of values to filter the 'Short-Form Tok/s' column.
    :param long_toks_slider: The range of values to filter the 'Long-Form Tok/s' column.
    :return: The filtered DataFrame.
    """
    # Select columns based on input and always-present columns
    filtered_df = df[
        PERFORMANCE_ALWAYS_HERE_COLS
        + [c for c in PERFORMANCE_COLS if c in df.columns and c in columns]
    ]

    # Filter models based on query
    if model_query:
        filtered_df = filtered_df[
            filtered_df["Model"].str.contains(
                "|".join(q.strip() for q in model_query.split(";")), case=False
            )
        ]

    # Exclude specified models
    if exclude_models:
        exclude_list = [m.strip() for m in exclude_models.split(";")]
        filtered_df = filtered_df[
            ~filtered_df["Model"].str.contains("|".join(exclude_list), case=False)
        ]

    # Filter by devices
    filtered_df = (
        filtered_df[
            (
                filtered_df["Device"].str.contains(
                    "|".join(re.escape(q.strip()) for q in devices), case=False
                )
            )
        ]
        if devices
        else pd.DataFrame(columns=filtered_df.columns)
    )

    # Filter by operating systems
    filtered_df = (
        filtered_df[
            (
                filtered_df["OS"].str.contains(
                    "|".join(q.strip() for q in os), case=False
                )
            )
        ]
        if os
        else pd.DataFrame(columns=filtered_df.columns)
    )

    # Apply short-form and long-form speed and tokens per second filters
    min_short_speed, max_short_speed = short_speed_slider
    min_long_speed, max_long_speed = long_speed_slider
    min_short_toks, max_short_toks = short_toks_slider
    min_long_toks, max_long_toks = long_toks_slider

    filtered_df = filtered_df[
        (filtered_df["Short-Form Speed"] >= min_short_speed)
        & (filtered_df["Short-Form Speed"] <= max_short_speed)
        & (filtered_df["Long-Form Speed"] >= min_long_speed)
        & (filtered_df["Long-Form Speed"] <= max_long_speed)
        & (filtered_df["Short-Form Tok/s"] >= min_short_toks)
        & (filtered_df["Short-Form Tok/s"] <= max_short_toks)
        & (filtered_df["Long-Form Tok/s"] >= min_long_toks)
        & (filtered_df["Long-Form Tok/s"] <= max_long_toks)
    ]

    return filtered_df


def quality_filter(df, columns, model_query, wer_slider, qoi_slider, exclude_models):
    """
    Filters the quality DataFrame based on specified criteria.
    :param df: The DataFrame to be filtered.
    :param columns: The columns to be included in the filtered DataFrame.
    :param model_query: The query string to filter the 'Model' column.
    :param wer_slider: The range of values to filter the 'Average WER' column.
    :param qoi_slider: The range of values to filter the 'QoI' column.
    :param exclude_models: Models to exclude from the results.
    :return: The filtered DataFrame.
    """
    # Select columns based on input and always-present columns
    filtered_df = df[
        QUALITY_ALWAYS_HERE_COLS
        + [c for c in QUALITY_COLS if c in df.columns and c in columns]
    ]

    # Filter models based on query
    if model_query:
        filtered_df = filtered_df[
            filtered_df["Model"].str.contains(
                "|".join(q.strip() for q in model_query.split(";")), case=False
            )
        ]

    # Exclude specified models
    if exclude_models:
        exclude_list = [m.strip() for m in exclude_models.split(";")]
        filtered_df = filtered_df[
            ~filtered_df["Model"].str.contains("|".join(exclude_list), case=False)
        ]

    # Apply WER and QoI filters
    min_wer_slider, max_wer_slider = wer_slider
    min_qoi_slider, max_qoi_slider = qoi_slider
    if "Average WER" in filtered_df.columns:
        filtered_df = filtered_df[
            (filtered_df["Average WER"] >= min_wer_slider)
            & (filtered_df["Average WER"] <= max_wer_slider)
        ]
    if "QoI" in filtered_df.columns:
        filtered_df = filtered_df[
            (filtered_df["QoI"] >= min_qoi_slider)
            & (filtered_df["QoI"] <= max_qoi_slider)
        ]

    return filtered_df


diff_tab = gr.TabItem("Difference Checker", elem_id="diff_checker", id=2)
text_diff_elems = []

tabs = gr.Tabs(elem_id="tab-elems")

multilingual_df = pd.read_csv("dashboard_data/multilingual_results.csv")
multilingual_models_df = multilingual_df[["Model"]].drop_duplicates()
multilingual_models_buttons = []
for model in multilingual_models_df["Model"]:
    elem_id = (
        f"{model}".replace(" ", "_").replace('"', "").replace("'", "").replace(",", "")
    )
    multilingual_models_buttons.append(
        gr.Button(value=model, elem_id=elem_id, visible=False)
    )
multilingual_models_df["Model"] = multilingual_models_df["Model"].apply(
    lambda x: make_multilingual_model_clickable_link(x)
)

with open("dashboard_data/multilingual_confusion_matrices.json", "r") as file:
    confusion_matrix_map = dict(json.load(file))


def update_multilingual_results(selected_model):
    """
    Updates the multilingual results display based on the selected model.

    This function processes the multilingual data for the chosen model,
    calculates average WER for different scenarios (language hinted vs. predicted),
    and prepares language-specific WER data for display.

    :param selected_model: The name of the selected model
    :return: A list containing updated components for the Gradio interface
    """
    if selected_model is None:
        return "# Select a model from the dropdown to view results."

    # Filter data for the selected model
    model_data = multilingual_df[multilingual_df["Model"] == selected_model]

    if model_data.empty:
        return f"# No data available for model: {selected_model}"

    # Separate data for forced and not forced scenarios
    forced_data = model_data[model_data["Forced Tokens"] == True]
    not_forced_data = model_data[model_data["Forced Tokens"] == False]

    result_text = f"# Model: {selected_model}\n\n"

    # Prepare average WER data
    average_wer_data = []
    if not forced_data.empty:
        average_wer_data.append(
            {
                "Scenario": "Language Hinted",
                "Average WER": forced_data.iloc[0]["Average WER"],
            }
        )
    if not not_forced_data.empty:
        average_wer_data.append(
            {
                "Scenario": "Language Predicted",
                "Average WER": not_forced_data.iloc[0]["Average WER"],
            }
        )
    average_wer_df = pd.DataFrame(average_wer_data)
    average_wer_df["Average WER"] = average_wer_df["Average WER"].apply(
        lambda x: round(x, 2)
    )

    # Prepare language-specific WER data
    lang_columns = [col for col in model_data.columns if col.startswith("WER_")]
    lang_wer_data = []
    for column in lang_columns:
        lang = column.split("_")[1]
        forced_wer = forced_data[column].iloc[0] if not forced_data.empty else None
        not_forced_wer = (
            not_forced_data[column].iloc[0] if not not_forced_data.empty else None
        )
        if forced_wer is not None or not_forced_wer is not None:
            lang_wer_data.append(
                {
                    "Language": LANGUAGE_MAP[lang],
                    "Language Hinted WER": round(forced_wer, 2)
                    if forced_wer is not None
                    else "N/A",
                    "Language Predicted WER": round(not_forced_wer, 2)
                    if not_forced_wer is not None
                    else "N/A",
                }
            )
    lang_wer_df = pd.DataFrame(lang_wer_data)
    lang_wer_df = lang_wer_df.fillna("No Data")

    # Create confusion matrix plot for unforced scenario
    unforced_plot = None
    if selected_model in confusion_matrix_map:
        if "not_forced" in confusion_matrix_map[selected_model]:
            unforced_plot = create_confusion_matrix_plot(
                confusion_matrix_map[selected_model]["not_forced"]["matrix"],
                confusion_matrix_map[selected_model]["not_forced"]["labels"],
                False,
            )

    # Return updated components for Gradio interface
    return [
        gr.update(value=result_text),
        gr.update(visible=True, value=average_wer_df),
        gr.update(visible=True, value=lang_wer_df),
        gr.update(visible=unforced_plot is not None, value=unforced_plot),
    ]


font = [
    "Zwizz Regular",  # Local font
    "IBM Plex Mono",  # Monospace font
    "ui-sans-serif",
    "system-ui",
    "sans-serif",
]

# Define the Gradio interface
with gr.Blocks(css=css, theme=gr.themes.Base(font=font)) as demo:
    # Add header and banner to the interface
    gr.HTML(HEADER)
    gr.HTML(BANNER_TEXT, elem_classes="markdown-text")

    # Create tabs for different sections of the dashboard
    with tabs.render():
        # Performance Tab
        with gr.TabItem("Performance", elem_id="benchmark", id=0):
            with gr.Row():
                with gr.Column(scale=1):
                    with gr.Row():
                        with gr.Column(scale=6, elem_classes="filter_models_column"):
                            filter_performance_models = gr.Textbox(
                                placeholder="πŸ” Filter Model (separate multiple queries with ';')",
                                label="Filter Models",
                            )
                        with gr.Column(scale=4, elem_classes="exclude_models_column"):
                            exclude_performance_models = gr.Textbox(
                                placeholder="πŸ” Exclude (separate multiple queries with ';')",
                                label="Exclude Models",
                            )
                    with gr.Row():
                        with gr.Accordion("See All Columns", open=False):
                            with gr.Row():
                                with gr.Column(scale=9, elem_id="performance_columns"):
                                    performance_shown_columns = gr.CheckboxGroup(
                                        choices=PERFORMANCE_TOGGLE_COLS,
                                        value=PERFORMANCE_SELECTED_COLS,
                                        label="Toggle Columns",
                                        elem_id="column-select",
                                        interactive=True,
                                    )
                                with gr.Column(
                                    scale=1,
                                    min_width=200,
                                    elem_id="performance_select_columns",
                                ):
                                    with gr.Row():
                                        select_all_button = gr.Button(
                                            "Select All",
                                            elem_id="select-all-button",
                                            interactive=True,
                                        )
                                        deselect_all_button = gr.Button(
                                            "Deselect All",
                                            elem_id="deselect-all-button",
                                            interactive=True,
                                        )

                            def select_all_columns():
                                return PERFORMANCE_TOGGLE_COLS

                            def deselect_all_columns():
                                return []

                            select_all_button.click(
                                select_all_columns,
                                inputs=[],
                                outputs=performance_shown_columns,
                            )
                            deselect_all_button.click(
                                deselect_all_columns,
                                inputs=[],
                                outputs=performance_shown_columns,
                            )

                    with gr.Row():
                        with gr.Accordion("Filter Devices", open=False):
                            with gr.Row():
                                with gr.Column(
                                    scale=9, elem_id="filter_devices_column"
                                ):
                                    performance_shown_devices = gr.CheckboxGroup(
                                        choices=PERFORMANCE_DEVICES,
                                        value=PERFORMANCE_DEVICES,
                                        label="Filter Devices",
                                        interactive=True,
                                    )
                                with gr.Column(
                                    scale=1,
                                    min_width=200,
                                    elem_id="filter_select_devices",
                                ):
                                    with gr.Row():
                                        select_all_devices_button = gr.Button(
                                            "Select All",
                                            elem_id="select-all-devices-button",
                                            interactive=True,
                                        )
                                        deselect_all_devices_button = gr.Button(
                                            "Deselect All",
                                            elem_id="deselect-all-devices-button",
                                            interactive=True,
                                        )

                            def select_all_devices():
                                return PERFORMANCE_DEVICES

                            def deselect_all_devices():
                                return []

                            select_all_devices_button.click(
                                select_all_devices,
                                inputs=[],
                                outputs=performance_shown_devices,
                            )
                            deselect_all_devices_button.click(
                                deselect_all_devices,
                                inputs=[],
                                outputs=performance_shown_devices,
                            )
                    with gr.Row():
                        performance_shown_os = gr.CheckboxGroup(
                            choices=PERFORMANCE_OS,
                            value=PERFORMANCE_OS,
                            label="Filter OS",
                            interactive=True,
                        )
                with gr.Column(scale=1):
                    with gr.Accordion("See Performance Filters"):
                        with gr.Row():
                            with gr.Row():
                                min_short_speed, max_short_speed = floor(
                                    min(performance_df["Short-Form Speed"])
                                ), ceil(max(performance_df["Short-Form Speed"]))
                                short_speed_slider = RangeSlider(
                                    value=[min_short_speed, max_short_speed],
                                    minimum=min_short_speed,
                                    maximum=max_short_speed,
                                    step=0.001,
                                    label="Short-Form Speed",
                                )
                            with gr.Row():
                                min_long_speed, max_long_speed = floor(
                                    min(performance_df["Long-Form Speed"])
                                ), ceil(max(performance_df["Long-Form Speed"]))
                                long_speed_slider = RangeSlider(
                                    value=[min_long_speed, max_long_speed],
                                    minimum=min_long_speed,
                                    maximum=max_long_speed,
                                    step=0.001,
                                    label="Long-Form Speed",
                                )
                        with gr.Row():
                            with gr.Row():
                                min_short_toks, max_short_toks = floor(
                                    min(performance_df["Short-Form Tok/s"])
                                ), ceil(max(performance_df["Short-Form Tok/s"]))
                                short_toks_slider = RangeSlider(
                                    value=[min_short_toks, max_short_toks],
                                    minimum=min_short_toks,
                                    maximum=max_short_toks,
                                    step=0.001,
                                    label="Short-Form Tok/s",
                                )
                            with gr.Row():
                                min_long_toks, max_long_toks = floor(
                                    min(performance_df["Long-Form Tok/s"])
                                ), ceil(max(performance_df["Long-Form Tok/s"]))
                                long_toks_slider = RangeSlider(
                                    value=[min_long_toks, max_long_toks],
                                    minimum=min_long_toks,
                                    maximum=max_long_toks,
                                    step=0.001,
                                    label="Long-Form Tok/s",
                                )
                    with gr.Row():
                        gr.Markdown(PERFORMANCE_TEXT, elem_classes="markdown-text")
            with gr.Row():
                leaderboard_df = gr.components.Dataframe(
                    value=performance_df[
                        PERFORMANCE_ALWAYS_HERE_COLS + performance_shown_columns.value
                    ],
                    headers=[
                        PERFORMANCE_ALWAYS_HERE_COLS + performance_shown_columns.value
                    ],
                    datatype=[
                        c.type
                        for c in fields(PerformanceAutoEvalColumn)
                        if c.name in PERFORMANCE_COLS
                    ],
                    elem_id="leaderboard-table",
                    elem_classes="large-table",
                    interactive=False,
                )

                # Copy of the leaderboard dataframe to apply filters to
                hidden_leaderboard_df = gr.components.Dataframe(
                    value=performance_df,
                    headers=PERFORMANCE_COLS,
                    datatype=[
                        c.type
                        for c in fields(PerformanceAutoEvalColumn)
                        if c.name in PERFORMANCE_COLS
                    ],
                    visible=False,
                )

                # Inputs for the dataframe filter function
                performance_filter_inputs = [
                    hidden_leaderboard_df,
                    performance_shown_columns,
                    filter_performance_models,
                    exclude_performance_models,
                    performance_shown_devices,
                    performance_shown_os,
                    short_speed_slider,
                    long_speed_slider,
                    short_toks_slider,
                    long_toks_slider,
                ]

                filter_output = leaderboard_df
                filter_performance_models.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                exclude_performance_models.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                performance_shown_columns.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                performance_shown_devices.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                performance_shown_os.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                short_speed_slider.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                long_speed_slider.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                short_toks_slider.change(
                    performance_filter, performance_filter_inputs, filter_output
                )
                long_toks_slider.change(
                    performance_filter, performance_filter_inputs, filter_output
                )

        # English Quality Tab
        with gr.TabItem("English Quality", elem_id="timeline", id=1):
            with gr.Row():
                with gr.Column(scale=1):
                    with gr.Row():
                        with gr.Column(scale=6, elem_classes="filter_models_column"):
                            filter_quality_models = gr.Textbox(
                                placeholder="πŸ” Filter Model (separate multiple queries with ';')",
                                label="Filter Models",
                            )
                        with gr.Column(scale=4, elem_classes="exclude_models_column"):
                            exclude_quality_models = gr.Textbox(
                                placeholder="πŸ” Exclude Model (separate multiple models with ';')",
                                label="Exclude Models",
                            )
                    with gr.Row():
                        with gr.Accordion("See All Columns", open=False):
                            quality_shown_columns = gr.CheckboxGroup(
                                choices=QUALITY_TOGGLE_COLS,
                                value=QUALITY_SELECTED_COLS,
                                label="Toggle Columns",
                                elem_id="column-select",
                                interactive=True,
                            )
                with gr.Column(scale=1):
                    with gr.Accordion("See Quality Filters"):
                        with gr.Row():
                            with gr.Row():
                                quality_min_avg_wer, quality_max_avg_wer = (
                                    floor(min(model_df["Average WER"])),
                                    ceil(max(model_df["Average WER"])) + 1,
                                )
                                wer_slider = RangeSlider(
                                    value=[quality_min_avg_wer, quality_max_avg_wer],
                                    minimum=quality_min_avg_wer,
                                    maximum=quality_max_avg_wer,
                                    label="Average WER",
                                )
                            with gr.Row():
                                quality_min_qoi, quality_max_qoi = floor(
                                    min(model_df["QoI"])
                                ), ceil(max(model_df["QoI"] + 1))
                                qoi_slider = RangeSlider(
                                    value=[quality_min_qoi, quality_max_qoi],
                                    minimum=quality_min_qoi,
                                    maximum=quality_max_qoi,
                                    label="QoI",
                                )
                    with gr.Row():
                        gr.Markdown(QUALITY_TEXT)
            with gr.Row():
                quality_leaderboard_df = gr.components.Dataframe(
                    value=model_df[
                        QUALITY_ALWAYS_HERE_COLS + quality_shown_columns.value
                    ],
                    headers=[QUALITY_ALWAYS_HERE_COLS + quality_shown_columns.value],
                    datatype=[
                        c.type
                        for c in fields(QualityAutoEvalColumn)
                        if c.name in QUALITY_COLS
                    ],
                    elem_id="leaderboard-table",
                    elem_classes="large-table",
                    interactive=False,
                )

                # Copy of the leaderboard dataframe to apply filters to
                hidden_quality_leaderboard_df = gr.components.Dataframe(
                    value=model_df,
                    headers=QUALITY_COLS,
                    datatype=[
                        c.type
                        for c in fields(QualityAutoEvalColumn)
                        if c.name in QUALITY_COLS
                    ],
                    visible=False,
                )

                # Inputs for the dataframe filter function
                filter_inputs = [
                    hidden_quality_leaderboard_df,
                    quality_shown_columns,
                    filter_quality_models,
                    wer_slider,
                    qoi_slider,
                    exclude_quality_models,
                ]
                filter_output = quality_leaderboard_df
                filter_quality_models.change(
                    quality_filter, filter_inputs, filter_output
                )
                exclude_quality_models.change(
                    quality_filter, filter_inputs, filter_output
                )
                quality_shown_columns.change(
                    quality_filter, filter_inputs, filter_output
                )
                wer_slider.change(quality_filter, filter_inputs, filter_output)
                qoi_slider.change(quality_filter, filter_inputs, filter_output)

        # Timeline Tab
        with gr.TabItem("Timeline", elem_id="timeline", id=4):
            # Create subtabs for different metrics
            with gr.Tabs():
                with gr.TabItem("QoI", id=0):
                    with gr.Row():
                        with gr.Column(scale=6):
                            filter_qoi = gr.Textbox(
                                placeholder="πŸ” Filter Model-Device-OS (separate multiple queries with ';')",
                                label="Filter",
                            )
                        with gr.Column(scale=4):
                            exclude_qoi = gr.Textbox(
                                placeholder="πŸ” Exclude Model-Device-OS (separate multiple with ';')",
                                label="Exclude",
                            )
                    with gr.Row():
                        with gr.Column():
                            qoi_plot = gr.Plot(container=True)
                            demo.load(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "qoi",
                                    "QoI",
                                    "QoI Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_qoi,
                                    exclude_qoi,
                                ],
                                qoi_plot,
                            )
                            filter_qoi.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "qoi",
                                    "QoI",
                                    "QoI Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_qoi,
                                    exclude_qoi,
                                ],
                                qoi_plot,
                            )
                            exclude_qoi.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "qoi",
                                    "QoI",
                                    "QoI Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_qoi,
                                    exclude_qoi,
                                ],
                                qoi_plot,
                            )

                with gr.TabItem("Average WER", id=1):
                    with gr.Row():
                        with gr.Column(scale=6):
                            filter_average_wer = gr.Textbox(
                                placeholder="πŸ” Filter Model-Device-OS (separate multiple queries with ';')",
                                label="Filter",
                            )
                        with gr.Column(scale=4):
                            exclude_average_wer = gr.Textbox(
                                placeholder="πŸ” Exclude Model-Device-OS (separate multiple with ';')",
                                label="Exclude",
                            )
                    with gr.Row():
                        with gr.Column():
                            average_wer_plot = gr.Plot(container=True)
                            demo.load(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "average_wer",
                                    "Average WER",
                                    "Average WER Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_average_wer,
                                    exclude_average_wer,
                                ],
                                average_wer_plot,
                            )
                            filter_average_wer.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "average_wer",
                                    "Average WER",
                                    "Average WER Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_average_wer,
                                    exclude_average_wer,
                                ],
                                average_wer_plot,
                            )
                            exclude_average_wer.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "average_wer",
                                    "Average WER",
                                    "Average WER Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_average_wer,
                                    exclude_average_wer,
                                ],
                                average_wer_plot,
                            )

                with gr.TabItem("Speed", id=2):
                    with gr.Row():
                        with gr.Column(scale=6):
                            filter_speed = gr.Textbox(
                                placeholder="πŸ” Filter Model-Device-OS (separate multiple queries with ';')",
                                label="Filter",
                            )
                        with gr.Column(scale=4):
                            exclude_speed = gr.Textbox(
                                placeholder="πŸ” Exclude Model-Device-OS (separate multiple with ';')",
                                label="Exclude",
                            )
                    with gr.Row():
                        with gr.Column():
                            speed_plot = gr.Plot(container=True)
                            demo.load(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "speed",
                                    "Speed",
                                    "Speed Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_speed,
                                    exclude_speed,
                                ],
                                speed_plot,
                            )
                            filter_speed.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "speed",
                                    "Speed",
                                    "Speed Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_speed,
                                    exclude_speed,
                                ],
                                speed_plot,
                            )
                            exclude_speed.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "speed",
                                    "Speed",
                                    "Speed Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_speed,
                                    exclude_speed,
                                ],
                                speed_plot,
                            )

                with gr.TabItem("Tok/s", id=3):
                    with gr.Row():
                        with gr.Column(scale=6):
                            filter_toks = gr.Textbox(
                                placeholder="πŸ” Filter Model-Device-OS (separate multiple queries with ';')",
                                label="Filter",
                            )
                        with gr.Column(scale=4):
                            exclude_toks = gr.Textbox(
                                placeholder="πŸ” Exclude Model-Device-OS (separate multiple with ';')",
                                label="Exclude",
                            )
                    with gr.Row():
                        with gr.Column():
                            toks_plot = gr.Plot(container=True)
                            demo.load(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "tokens_per_second",
                                    "Tok/s",
                                    "Tok/s Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_toks,
                                    exclude_toks,
                                ],
                                toks_plot,
                            )
                            filter_toks.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "tokens_per_second",
                                    "Tok/s",
                                    "Tok/s Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_toks,
                                    exclude_toks,
                                ],
                                toks_plot,
                            )
                            exclude_toks.change(
                                lambda x, y, z: plot_metric(
                                    x,
                                    "tokens_per_second",
                                    "Tok/s",
                                    "Tok/s Over Time for Model-Device-OS Combinations",
                                    y,
                                    z,
                                ),
                                [
                                    gr.Dataframe(benchmark_df, visible=False),
                                    filter_toks,
                                    exclude_toks,
                                ],
                                toks_plot,
                            )

        # Multilingual Quality Tab
        with gr.TabItem("Multilingual Quality", elem_id="multilingual", id=5):
            if multilingual_df is not None:
                with gr.Row():
                    with gr.Column(scale=1):
                        # Display table of multilingual models
                        model_table = gr.Dataframe(
                            value=multilingual_models_df,
                            headers=["Model"],
                            datatype=["html"],
                            elem_classes="left-side-table",
                        )
                        # Placeholders for confusion matrix plots
                        with gr.Row():
                            unforced_confusion_matrix = gr.Plot(visible=False)
                        with gr.Row():
                            forced_confusion_matrix = gr.Plot(visible=False)

                    with gr.Column(scale=1):
                        # Display area for selected model results
                        results_markdown = gr.Markdown(
                            "# Select a model from the table on the left to view results.",
                            elem_id="multilingual-results",
                        )
                        # Tables for displaying average WER and language-specific WER
                        average_wer_table = gr.Dataframe(
                            value=None, elem_id="average-wer-table", visible=False
                        )
                        language_wer_table = gr.Dataframe(
                            value=None, elem_id="general-wer-table", visible=False
                        )

                    # Set up click event to update results when a model is selected
                    for button in multilingual_models_buttons:
                        button.render()
                        button.click(
                            fn=lambda x: update_multilingual_results(x),
                            inputs=[button],
                            outputs=[
                                results_markdown,
                                average_wer_table,
                                language_wer_table,
                                unforced_confusion_matrix,
                            ],
                        )
            else:
                # Display message if no multilingual data is available
                gr.Markdown("No multilingual benchmark results available.")

        # Device Support Tab
        with gr.TabItem("Device Support", elem_id="device_support", id=6):
            # Load device support data from CSV
            support_data = pd.read_csv("dashboard_data/support_data.csv")
            support_data.set_index(support_data.columns[0], inplace=True)
            support_data["Model"] = support_data["Model"].apply(
                lambda x: x.replace("_", "/")
            )
            support_data["Model"] = support_data["Model"].apply(
                lambda x: make_model_name_clickable_link(x)
            )
            support_data = (
                support_data.assign(model_len=support_data["Model"].str.len())
                .sort_values(
                    by=["model_len"],
                    ascending=[True],
                )
                .drop(columns=["model_len"])
            )

            with gr.Row():
                with gr.Column(scale=1):
                    with gr.Row():
                        with gr.Column(scale=6, elem_id="filter_models_column"):
                            filter_support_models = gr.Textbox(
                                placeholder="πŸ” Filter Model (separate multiple queries with ';')",
                                label="Filter Models",
                            )
                        with gr.Column(scale=4, elem_classes="exclude_models_column"):
                            exclude_support_models = gr.Textbox(
                                placeholder="πŸ” Exclude Model (separate multiple models with ';')",
                                label="Exclude Models",
                            )
                    with gr.Row():
                        with gr.Accordion("See All Columns", open=False):
                            with gr.Row():
                                with gr.Column(scale=9):
                                    support_shown_columns = gr.CheckboxGroup(
                                        choices=support_data.columns.tolist()[
                                            1:
                                        ],  # Exclude 'Model' column
                                        value=support_data.columns.tolist()[1:],
                                        label="Toggle Columns",
                                        elem_id="support-column-select",
                                        interactive=True,
                                    )
                                with gr.Column(scale=1, min_width=200):
                                    with gr.Row():
                                        select_all_support_button = gr.Button(
                                            "Select All",
                                            elem_id="select-all-support-button",
                                            interactive=True,
                                        )
                                        deselect_all_support_button = gr.Button(
                                            "Deselect All",
                                            elem_id="deselect-all-support-button",
                                            interactive=True,
                                        )
            with gr.Column():
                gr.Markdown(
                    """
                ### Legend
                - βœ… Supported: The model is supported and tested on this device.
                - ⚠️ Failed: Either The model tests failed on this device or the Speed Factor for the test is less than 1.
                - ? Not Tested: The model is supported on this device but no test information available.
                - Not Supported: The model is not supported on this device as per the [WhisperKit configuration](https://huggingface.co/argmaxinc/whisperkit-coreml/blob/main/config.json).
                """
                )

            # Display device support data in a table
            device_support_table = gr.Dataframe(
                value=support_data,
                headers=support_data.columns.tolist(),
                datatype=["html" for _ in support_data.columns],
                elem_id="device-support-table",
                elem_classes="large-table",
                interactive=False,
            )

            # Hidden dataframe to store the original data
            hidden_support_df = gr.Dataframe(value=support_data, visible=False)

            def filter_support_data(df, columns, model_query, exclude_models):
                filtered_df = df.copy()

                # Filter models based on query
                if model_query:
                    filtered_df = filtered_df[
                        filtered_df["Model"].str.contains(
                            "|".join(q.strip() for q in model_query.split(";")),
                            case=False,
                            regex=True,
                        )
                    ]

                # Exclude specified models
                if exclude_models:
                    exclude_list = [
                        re.escape(m.strip()) for m in exclude_models.split(";")
                    ]
                    filtered_df = filtered_df[
                        ~filtered_df["Model"].str.contains(
                            "|".join(exclude_list), case=False, regex=True
                        )
                    ]

                # Select columns
                selected_columns = ["Model"] + [
                    col for col in columns if col in df.columns
                ]
                filtered_df = filtered_df[selected_columns]

                return filtered_df

            def select_all_support_columns():
                return support_data.columns.tolist()[1:]  # Exclude 'Model' column

            def deselect_all_support_columns():
                return []

            # Connect the filter function to the input components
            filter_inputs = [
                hidden_support_df,
                support_shown_columns,
                filter_support_models,
                exclude_support_models,
            ]
            filter_support_models.change(
                filter_support_data, filter_inputs, device_support_table
            )
            exclude_support_models.change(
                filter_support_data, filter_inputs, device_support_table
            )
            support_shown_columns.change(
                filter_support_data, filter_inputs, device_support_table
            )

            # Connect select all and deselect all buttons
            select_all_support_button.click(
                select_all_support_columns,
                inputs=[],
                outputs=support_shown_columns,
            )
            deselect_all_support_button.click(
                deselect_all_support_columns,
                inputs=[],
                outputs=support_shown_columns,
            )

        # Methodology Tab
        with gr.TabItem("Methodology", elem_id="methodology", id=7):
            gr.Markdown(METHODOLOGY_TEXT, elem_id="methodology-text")

    # Citation section
    with gr.Accordion("πŸ“™ Citation", open=False):
        citation_button = gr.Textbox(
            value=CITATION_BUTTON_TEXT,
            label=CITATION_BUTTON_LABEL,
            lines=7,
            elem_id="citation-button",
            show_copy_button=True,
        )

# Launch the Gradio interface
demo.launch(debug=True, share=True, ssr_mode=False)