File size: 70,505 Bytes
ddc5368
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08d9093
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
import gradio as gr
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import json
import os
import re
from typing import Dict, List, Optional, Tuple

# Import data loader
from data_loader import data_loader, get_napolab_datasets, get_sample_benchmark_results, get_model_metadata

# Load data from YAML file
NAPOLAB_DATASETS = get_napolab_datasets()
SAMPLE_BENCHMARK_RESULTS = get_sample_benchmark_results()
MODEL_METADATA = get_model_metadata()

def load_portuguese_leaderboard_data() -> pd.DataFrame:
    """Load data from the Portuguese leaderboard CSV file."""
    try:
        csv_path = "portuguese_leaderboard.csv"
        if os.path.exists(csv_path):
            df = pd.read_csv(csv_path)
            # Select only the relevant columns
            relevant_columns = ['model_name', 'model_num_parameters', 'assin2_rte', 'assin2_sts', 'faquad_nli', 'hatebr_offensive']
            df = df[relevant_columns].copy()
            
            # Rename columns to match the existing format
            df = df.rename(columns={
                'assin2_rte': 'ASSIN2 RTE',
                'assin2_sts': 'ASSIN2 STS', 
                'faquad_nli': 'FaQUaD-NLI',
                'hatebr_offensive': 'HateBR'
            })
            
            # Add source information
            df['source'] = 'portuguese_leaderboard'
            
            print(f"Loaded {len(df)} models from Portuguese leaderboard")
            return df
        else:
            print(f"Portuguese leaderboard CSV not found: {csv_path}")
            return pd.DataFrame()
    except Exception as e:
        print(f"Error loading Portuguese leaderboard data: {e}")
        return pd.DataFrame()

def load_external_models_data() -> pd.DataFrame:
    """Load data from the external models CSV file."""
    try:
        csv_path = "external_models.csv"
        if os.path.exists(csv_path):
            df = pd.read_csv(csv_path)
            # Select only the relevant columns
            relevant_columns = ['model', 'link', 'assin2_rte', 'assin2_sts', 'faquad_nli', 'hatebr_offensive']
            df = df[relevant_columns].copy()
            
            # Rename columns to match the existing format
            df = df.rename(columns={
                'model': 'model_name',
                'assin2_rte': 'ASSIN2 RTE',
                'assin2_sts': 'ASSIN2 STS', 
                'faquad_nli': 'FaQUaD-NLI',
                'hatebr_offensive': 'HateBR'
            })
            
            # Add source information
            df['source'] = 'external_models'
            
            # Add model_num_parameters column with 0 for external models
            df['model_num_parameters'] = 0
            
            print(f"Loaded {len(df)} external models")
            return df
        else:
            print(f"External models CSV not found: {csv_path}")
            return pd.DataFrame()
    except Exception as e:
        print(f"Error loading external models data: {e}")
        return pd.DataFrame()

# Load Portuguese leaderboard data
PORTUGUESE_LEADERBOARD_DATA = load_portuguese_leaderboard_data()

# Load external models data
EXTERNAL_MODELS_DATA = load_external_models_data()

def create_simplified_benchmark_table(selected_datasets: List[str] = None, show_napolab_thesis: bool = True, show_teenytinyllama: bool = True, show_portuguese_leaderboard: bool = True, show_external_models: bool = True, hide_incomplete_models: bool = False, min_average_performance: float = 0.0, search_query: str = "", max_num_parameters: int = 0) -> pd.DataFrame:
    """Create a simplified benchmark table with one column per dataset."""
    # Get all dataset names
    dataset_names = sorted(NAPOLAB_DATASETS.keys())
    dataset_display_names = [NAPOLAB_DATASETS[name].get('name', name) for name in dataset_names]
    
    # Use selected datasets if provided, otherwise use all datasets
    if selected_datasets is None:
        selected_datasets = dataset_names
    
    # Collect data for each model
    model_data = {}
    
    # Process existing benchmark results
    for dataset_name, models in SAMPLE_BENCHMARK_RESULTS.items():
        for model_name, metrics in models.items():
            if model_name not in model_data:
                model_data[model_name] = {
                    'dataset_scores': {},
                    'url': None,
                    'source': 'existing'
                }
            
            # Calculate average performance for this dataset
            avg_performance = np.mean(list(metrics.values()))
            model_data[model_name]['dataset_scores'][dataset_name] = avg_performance
    
    # Process Portuguese leaderboard data
    if show_portuguese_leaderboard and not PORTUGUESE_LEADERBOARD_DATA.empty:
        for _, row in PORTUGUESE_LEADERBOARD_DATA.iterrows():
            model_name = row['model_name']
            
            if model_name not in model_data:
                model_data[model_name] = {
                    'dataset_scores': {},
                    'url': None,
                    'source': 'portuguese_leaderboard',
                    'num_parameters': row.get('model_num_parameters', 0)
                }
            
            # Map Portuguese leaderboard columns to dataset names
            column_mapping = {
                'ASSIN2 RTE': 'assin2_rte',
                'ASSIN2 STS': 'assin2_sts',
                'FaQUaD-NLI': 'faquad-nli',
                'HateBR': 'hatebr'
            }
            
            for display_name, dataset_name in column_mapping.items():
                if dataset_name in NAPOLAB_DATASETS:
                    score = row[display_name]
                    if pd.notna(score) and score > 0:
                        model_data[model_name]['dataset_scores'][dataset_name] = score
    
    # Process external models data
    if show_external_models and not EXTERNAL_MODELS_DATA.empty:
        for _, row in EXTERNAL_MODELS_DATA.iterrows():
            model_name = row['model_name']
            
            if model_name not in model_data:
                model_data[model_name] = {
                    'dataset_scores': {},
                    'url': row.get('link', ''),
                    'source': 'external_models',
                    'num_parameters': row.get('model_num_parameters', 0)
                }
            
            # Map external models columns to dataset names
            column_mapping = {
                'ASSIN2 RTE': 'assin2_rte',
                'ASSIN2 STS': 'assin2_sts',
                'FaQUaD-NLI': 'faquad-nli',
                'HateBR': 'hatebr'
            }
            
            for display_name, dataset_name in column_mapping.items():
                if dataset_name in NAPOLAB_DATASETS:
                    score = row[display_name]
                    if pd.notna(score) and score > 0:
                        model_data[model_name]['dataset_scores'][dataset_name] = score
    
    # Get model URLs and source information for existing models
    additional_models = data_loader.get_additional_models()
    for model_name in model_data.keys():
        if model_data[model_name]['source'] == 'existing':
            # Get URL
            for arch_models in additional_models.values():
                if model_name in arch_models:
                    model_data[model_name]['url'] = arch_models[model_name].get('huggingface_url', '')
                    break
            
            # Get source information
            model_metadata = MODEL_METADATA.get(model_name, {})
            source = model_metadata.get('source', 'unknown')
            model_data[model_name]['source'] = source
            
            # Add num_parameters for existing models (set to 0 as they don't have this info)
            model_data[model_name]['num_parameters'] = 0
    
    # Create table data
    table_data = []
    
    for model_name, data in model_data.items():
        # Apply source filtering
        source = data['source']
        
        # Apply show filters - only show models from sources that are checked
        if source == 'napolab_thesis' and not show_napolab_thesis:
            continue
        if source == 'teenytinyllama_paper' and not show_teenytinyllama:
            continue
        if source == 'portuguese_leaderboard' and not show_portuguese_leaderboard:
            continue
        if source == 'external_models' and not show_external_models:
            continue
        # Hide models with unknown source (should not happen with proper data)
        if source == 'unknown':
            continue
        
        # Apply parameter filtering (only for Portuguese leaderboard models)
        if max_num_parameters > 0 and source == 'portuguese_leaderboard':
            num_parameters = data.get('num_parameters', 0)
            if num_parameters > max_num_parameters:
                continue
        
        # Create clickable link for model name
        if data['url']:
            model_display = f"[{model_name}]({data['url']})"
        elif source == 'portuguese_leaderboard' and '/' in model_name:
            # Create Hugging Face link for Portuguese leaderboard models with slashes
            huggingface_url = f"https://huggingface.co/{model_name}"
            model_display = f"[{model_name}]({huggingface_url})"
        else:
            model_display = model_name
        
        # Create row with dataset scores
        row_data = {'Model': model_display}
        
        # Calculate average only over selected datasets
        selected_scores = []
        for dataset_name in selected_datasets:
            score = data['dataset_scores'].get(dataset_name, 0)
            if score > 0:  # Only include non-zero scores in average
                selected_scores.append(score)
        
        overall_avg = np.mean(selected_scores) if selected_scores else 0
        row_data['Average'] = round(overall_avg, 4)
        
        # Add scores for each dataset (only selected ones)
        for dataset_name in dataset_names:
            score = data['dataset_scores'].get(dataset_name, 0)
            display_name = dataset_display_names[dataset_names.index(dataset_name)]
            # Only add columns for selected datasets
            if dataset_name in selected_datasets:
                row_data[display_name] = round(score, 4)
        
        table_data.append(row_data)
    
    df = pd.DataFrame(table_data)
    
    # Filter to show only models that have scores for at least one selected dataset
    if selected_datasets and not df.empty:
        # Get display names for selected datasets
        selected_display_names = [NAPOLAB_DATASETS[name].get('name', name) for name in selected_datasets]
        
        # Filter models based on selection criteria
        models_to_keep = []
        for _, row in df.iterrows():
            has_score = False
            has_all_scores = True
            
            # Only check the datasets that are actually selected for display
            for dataset_name in selected_datasets:
                display_name = NAPOLAB_DATASETS[dataset_name].get('name', dataset_name)
                if display_name in df.columns:
                    score = row[display_name]
                    if score > 0:
                        has_score = True
                    else:
                        has_all_scores = False
            
            # Keep model if it has at least one score
            if has_score:
                # If hide_incomplete_models is True, only keep models with all scores in selected datasets
                if not hide_incomplete_models or has_all_scores:
                    models_to_keep.append(row['Model'])
        
        # Filter dataframe to only include selected models
        if models_to_keep:
            df = df[df['Model'].isin(models_to_keep)]
        else:
            # If no models to keep, create empty DataFrame with proper structure
            # Create columns list first
            columns = ['Model']
            for dataset_name in dataset_names:
                display_name = dataset_display_names[dataset_names.index(dataset_name)]
                if dataset_name in selected_datasets:
                    columns.append(display_name)
            columns.append('Average')
            
            # Create empty DataFrame with correct columns
            df = pd.DataFrame(columns=columns)
    
    # Filter by minimum average performance
    if min_average_performance > 0 and not df.empty:
        df = df[df['Average'] >= min_average_performance]
    
    # Filter by search query
    if search_query and not df.empty:
        # Extract model names from markdown links for searching
        df_filtered = df.copy()
        df_filtered['model_name_clean'] = df_filtered['Model'].str.replace(r'\[([^\]]+)\]\([^)]+\)', r'\1', regex=True)
        try:
            # Use regex pattern matching
            df_filtered = df_filtered[df_filtered['model_name_clean'].str.contains(search_query, case=False, na=False, regex=True)]
        except re.error:
            # Fallback to simple string matching if regex is invalid
            df_filtered = df_filtered[df_filtered['model_name_clean'].str.contains(search_query, case=False, na=False)]
        df = df_filtered.drop('model_name_clean', axis=1)
    
    # Sort by Average (descending)
    if not df.empty:
        df = df.sort_values('Average', ascending=False)
    
    # Add rank column with medal emojis for top 3 and color-coded emojis for others
    if not df.empty:
        df = df.reset_index(drop=True)
        df.index = df.index + 1  # Start ranking from 1
        
        # Create rank column with medal emojis and color-coded emojis
        rank_column = []
        total_models = len(df)
        
        for rank in df.index:
            if rank == 1:
                rank_column.append("🥇 1")
            elif rank == 2:
                rank_column.append("🥈 2")
            elif rank == 3:
                rank_column.append("🥉 3")
            else:
                # Color-code based on position relative to total
                position_ratio = rank / total_models
                if position_ratio <= 0.33:  # Top third
                    rank_column.append("🟢 " + str(rank))
                elif position_ratio <= 0.67:  # Middle third
                    rank_column.append("🟡 " + str(rank))
                else:  # Bottom third
                    rank_column.append("🔴 " + str(rank))
        
        df.insert(0, 'Rank', rank_column)
    
    return df


# Global variable to track the current CSV file
current_csv_file = None

def export_csv(df: pd.DataFrame):
    """Export the benchmark table to CSV."""
    global current_csv_file
    
    print(f"Export function called with dataframe shape: {df.shape}")
    
    if df.empty:
        print("Dataframe is empty, returning None")
        return None
    
    # Clean up previous file if it exists
    if current_csv_file:
        try:
            import os
            if os.path.exists(current_csv_file):
                os.remove(current_csv_file)
                print(f"Deleted previous CSV file: {current_csv_file}")
        except Exception as e:
            print(f"Error deleting previous file {current_csv_file}: {e}")
    
    # Clean the dataframe for CSV export
    df_clean = df.copy()
    
    # Remove markdown formatting from model names for cleaner CSV
    df_clean['Model'] = df_clean['Model'].str.replace(r'\[([^\]]+)\]\([^)]+\)', r'\1', regex=True)
    
    # Create filename with timestamp
    from datetime import datetime
    import tempfile
    import os
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"napolab_benchmark_results_{timestamp}.csv"
    
    # Create file in current directory (simpler approach)
    file_path = filename
    
    print(f"Creating CSV file at: {file_path}")
    
    # Save to CSV file
    df_clean.to_csv(file_path, index=False)
    
    print(f"CSV file created successfully. File exists: {os.path.exists(file_path)}")
    
    # Update current file tracking
    current_csv_file = file_path
    
    return file_path

def cleanup_current_csv():
    """Clean up the current CSV file after download."""
    global current_csv_file
    import os
    
    if current_csv_file and os.path.exists(current_csv_file):
        try:
            os.remove(current_csv_file)
            print(f"Deleted CSV file after download: {current_csv_file}")
            current_csv_file = None
        except Exception as e:
            print(f"Error deleting file {current_csv_file}: {e}")


def create_model_performance_radar(selected_datasets: List[str] = None, show_napolab_thesis: bool = True, show_teenytinyllama: bool = True, show_portuguese_leaderboard: bool = True, show_external_models: bool = True, hide_incomplete_models: bool = False, min_average_performance: float = 0.0, search_query: str = "", max_num_parameters: int = 0) -> go.Figure:
    """Create a radar chart showing model performance across all datasets."""
    # Use selected datasets if provided, otherwise use all datasets
    if selected_datasets is None:
        selected_datasets = list(NAPOLAB_DATASETS.keys())
    
    # Get dataset names for the radar axes (only selected ones)
    dataset_names = selected_datasets
    dataset_display_names = [NAPOLAB_DATASETS[name].get('name', name) for name in dataset_names]
    
    # Collect data for each model
    model_data = {}
    
    # Process existing benchmark results
    for dataset_name, models in SAMPLE_BENCHMARK_RESULTS.items():
        if dataset_name in selected_datasets:
            for model_name, metrics in models.items():
                if model_name not in model_data:
                    model_data[model_name] = {
                        'performances': {},
                        'architecture': MODEL_METADATA.get(model_name, {}).get('architecture', 'Unknown'),
                        'source': 'existing'
                    }
                
                # Calculate average performance for this dataset
                avg_performance = np.mean(list(metrics.values()))
                model_data[model_name]['performances'][dataset_name] = avg_performance
    
    # Process Portuguese leaderboard data
    if show_portuguese_leaderboard and not PORTUGUESE_LEADERBOARD_DATA.empty:
        for _, row in PORTUGUESE_LEADERBOARD_DATA.iterrows():
            model_name = row['model_name']
            
            if model_name not in model_data:
                model_data[model_name] = {
                    'performances': {},
                    'architecture': 'Unknown',
                    'source': 'portuguese_leaderboard',
                    'num_parameters': row.get('model_num_parameters', 0)
                }
            
            # Map Portuguese leaderboard columns to dataset names
            column_mapping = {
                'ASSIN2 RTE': 'assin2_rte',
                'ASSIN2 STS': 'assin2_sts',
                'FaQUaD-NLI': 'faquad-nli',
                'HateBR': 'hatebr'
            }
            
            for display_name, dataset_name in column_mapping.items():
                if dataset_name in selected_datasets:
                    score = row[display_name]
                    if pd.notna(score) and score > 0:
                        model_data[model_name]['performances'][dataset_name] = score
    
    # Process external models data
    if show_external_models and not EXTERNAL_MODELS_DATA.empty:
        for _, row in EXTERNAL_MODELS_DATA.iterrows():
            model_name = row['model_name']
            
            if model_name not in model_data:
                model_data[model_name] = {
                    'performances': {},
                    'architecture': 'Unknown',
                    'source': 'external_models',
                    'num_parameters': row.get('model_num_parameters', 0)
                }
            
            # Map external models columns to dataset names
            column_mapping = {
                'ASSIN2 RTE': 'assin2_rte',
                'ASSIN2 STS': 'assin2_sts',
                'FaQUaD-NLI': 'faquad-nli',
                'HateBR': 'hatebr'
            }
            
            for display_name, dataset_name in column_mapping.items():
                if dataset_name in selected_datasets:
                    score = row[display_name]
                    if pd.notna(score) and score > 0:
                        model_data[model_name]['performances'][dataset_name] = score
    
    # Get model URLs and source information for existing models
    additional_models = data_loader.get_additional_models()
    for model_name in model_data.keys():
        if model_data[model_name]['source'] == 'existing':
            # Get URL
            for arch_models in additional_models.values():
                if model_name in arch_models:
                    model_data[model_name]['url'] = arch_models[model_name].get('huggingface_url', '')
                    break
            
            # Get source information
            model_metadata = MODEL_METADATA.get(model_name, {})
            source = model_metadata.get('source', 'unknown')
            model_data[model_name]['source'] = source
            
            # Add num_parameters for existing models (set to 0 as they don't have this info)
            model_data[model_name]['num_parameters'] = 0
    
    # Apply source filtering
    filtered_model_data = {}
    for model_name, data in model_data.items():
        source = data.get('source', 'existing')
        
        # Apply show filters - only show models from sources that are checked
        if source == 'napolab_thesis' and not show_napolab_thesis:
            continue
        if source == 'teenytinyllama_paper' and not show_teenytinyllama:
            continue
        if source == 'portuguese_leaderboard' and not show_portuguese_leaderboard:
            continue
        if source == 'external_models' and not show_external_models:
            continue
        # Hide models with unknown source (should not happen with proper data)
        if source == 'unknown':
            continue
        
        # Apply parameter filtering (only for Portuguese leaderboard models)
        if max_num_parameters > 0 and source == 'portuguese_leaderboard':
            num_parameters = data.get('num_parameters', 0)
            if num_parameters > max_num_parameters:
                continue
        
        filtered_model_data[model_name] = data
    
    # Apply incomplete model filtering
    if hide_incomplete_models and selected_datasets:
        final_filtered_data = {}
        for model_name, data in filtered_model_data.items():
            has_all_scores = True
            for dataset_name in selected_datasets:
                if data['performances'].get(dataset_name, 0) == 0:
                    has_all_scores = False
                    break
            if has_all_scores:
                final_filtered_data[model_name] = data
        filtered_model_data = final_filtered_data
    
    # Apply minimum average performance filtering
    if min_average_performance > 0 and selected_datasets:
        final_filtered_data = {}
        for model_name, data in filtered_model_data.items():
            # Calculate average performance for selected datasets
            scores = []
            for dataset_name in selected_datasets:
                score = data['performances'].get(dataset_name, 0)
                if score > 0:  # Only include non-zero scores
                    scores.append(score)
            
            if scores:
                avg_performance = np.mean(scores)
                if avg_performance >= min_average_performance:
                    final_filtered_data[model_name] = data
        filtered_model_data = final_filtered_data
    
    # Apply search query filtering
    if search_query:
        final_filtered_data = {}
        try:
            # Use regex pattern matching
            import re
            pattern = re.compile(search_query, re.IGNORECASE)
            for model_name, data in filtered_model_data.items():
                if pattern.search(model_name):
                    final_filtered_data[model_name] = data
        except re.error:
            # Fallback to simple string matching if regex is invalid
            for model_name, data in filtered_model_data.items():
                if search_query.lower() in model_name.lower():
                    final_filtered_data[model_name] = data
        filtered_model_data = final_filtered_data
    
    # Sort models by average performance (descending)
    model_performances = []
    for model_name, data in filtered_model_data.items():
        # Calculate average performance for selected datasets
        scores = []
        for dataset_name in selected_datasets:
            score = data['performances'].get(dataset_name, 0)
            if score > 0:  # Only include non-zero scores
                scores.append(score)
        
        avg_performance = np.mean(scores) if scores else 0
        model_performances.append((model_name, data, avg_performance))
    
    # Sort by average performance (descending)
    model_performances.sort(key=lambda x: x[2], reverse=True)
    
    # Calculate dynamic range based on actual data
    all_performance_values = []
    for model_name, data, avg_performance in model_performances:
        for dataset_name in dataset_names:
            score = data['performances'].get(dataset_name, 0)
            if score > 0:  # Only include non-zero scores
                all_performance_values.append(score)
    
    # Set dynamic range with some padding
    if all_performance_values:
        min_score = min(all_performance_values)
        max_score = max(all_performance_values)
        # Add 5% padding below minimum and ensure minimum is not below 0.5
        range_min = max(0.5, min_score - (max_score - min_score) * 0.05)
        range_max = 1.0
    else:
        # Fallback to default range if no data
        range_min = 0.6
        range_max = 1.0
    
    # Create radar chart
    fig = go.Figure()
    
    # Generate a more distinguishable color palette
    num_models = len(model_performances)
    
    # Create a list of line styles for better differentiation
    line_styles = ['solid', 'dash', 'dot', 'dashdot', 'longdash', 'longdashdot']
    
    # Use highly contrasting colors for better differentiation
    base_colors = [
        '#1f77b4',  # Blue
        '#ff7f0e',  # Orange
        '#2ca02c',  # Green
        '#d62728',  # Red
        '#9467bd',  # Purple
        '#8c564b',  # Brown
        '#e377c2',  # Pink
        '#7f7f7f',  # Gray
        '#bcbd22',  # Olive
        '#17becf',  # Cyan
        '#ff9896',  # Light Red
        '#98df8a',  # Light Green
        '#ffbb78',  # Light Orange
        '#aec7e8',  # Light Blue
        '#c5b0d5',  # Light Purple
    ]
    
    # Ensure we have enough colors
    while len(base_colors) < num_models:
        base_colors.extend(base_colors)
    
    colors = base_colors[:num_models]
    
    for i, (model_name, data, avg_performance) in enumerate(model_performances):
        # Get performance values for all datasets (fill with 0 if missing)
        performance_values = []
        for dataset_name in dataset_names:
            performance_values.append(data['performances'].get(dataset_name, 0))
        
        # Close the polygon by adding the first value at the end
        if performance_values:
            performance_values.append(performance_values[0])
        
        # Assign color and line style based on model index for better differentiation
        color = colors[i % len(colors)]
        line_style = line_styles[i % len(line_styles)]
        
        # Show first two models by default, hide the rest
        visible = True if i < 2 else 'legendonly'
        
        # Create theta values that close the polygon
        theta_values = dataset_display_names + [dataset_display_names[0]] if dataset_display_names else []
        
        fig.add_trace(go.Scatterpolar(
            r=performance_values,
            theta=theta_values,
            fill=None,
            name=model_name,
            line_color=color,
            line_dash=line_style,
            line_width=3,
            opacity=0.8,
            visible=visible,
            hovertemplate=(
                "<b>%{fullData.name}</b><br>" +
                "Dataset: %{theta}<br>" +
                "Performance: %{r:.3f}<br>" +
                "Architecture: " + data['architecture'] + "<br>" +
                "<extra></extra>"
            )
        ))
    
    # Update layout
    fig.update_layout(
        title="Model Performance Radar Chart",
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[range_min, range_max],
                gridcolor='rgba(0, 0, 0, 0.2)',
                linecolor='rgba(0, 0, 0, 0.5)',
                tickcolor='rgba(0, 0, 0, 0.7)',
                tickfont=dict(color='rgba(0, 0, 0, 0.8)')
            ),
            angularaxis=dict(
                tickmode='array',
                tickvals=list(range(len(dataset_display_names))),
                ticktext=dataset_display_names,
                gridcolor='rgba(0, 0, 0, 0.2)',
                linecolor='rgba(0, 0, 0, 0.5)',
                tickcolor='rgba(0, 0, 0, 0.7)',
                tickfont=dict(color='rgba(0, 0, 0, 0.8)')
            ),
            bgcolor='rgba(255, 255, 255, 0)'
        ),
        height=700,
        showlegend=True,
        plot_bgcolor='rgba(255, 255, 255, 0)',
        paper_bgcolor='rgba(255, 255, 255, 0)',
        legend=dict(
            yanchor="top",
            y=-0.15,
            xanchor="center",
            x=0.5,
            bgcolor='rgba(255, 255, 255, 0.95)',
            bordercolor='rgba(0, 0, 0, 0.2)',
            borderwidth=1,
            orientation="h",
            font=dict(color='rgba(0, 0, 0, 0.8)')
        ),
        margin=dict(l=50, r=50, t=100, b=100),
        font=dict(color='rgba(0, 0, 0, 0.8)')
    )
    
    return fig

# Gradio Interface
with gr.Blocks(title="Napolab Leaderboard", theme=gr.themes.Soft()) as app:
    gr.Markdown("""
    # 🌎 Napolab Leaderboard
    
    Stay up to date with the latest advancements in Portuguese language models and their performance across carefully curated Portuguese language tasks.
    
    [⭐ Star us on GitHub](https://github.com/ruanchaves/napolab)
    """)
    
    with gr.Tabs():
        
        # Benchmark Results Tab
        with gr.Tab("🏆 Benchmark Results"):
            gr.Markdown("### Model Performance Benchmarks")
            
            with gr.Accordion("Select Datasets to Include: (Click to expand)", open=False):
                with gr.Row():
                    # Create checkboxes for each dataset
                    dataset_checkboxes = []
                    for dataset_name in sorted(NAPOLAB_DATASETS.keys()):
                        display_name = NAPOLAB_DATASETS[dataset_name].get('name', dataset_name)
                        # Default to selected only for ASSIN 2 STS, FaQUaD-NLI, and HateBR
                        default_value = display_name in ['ASSIN 2 STS', 'FaQUaD-NLI', 'HateBR']
                        checkbox = gr.Checkbox(
                            label=display_name,
                            value=default_value
                        )
                        dataset_checkboxes.append((dataset_name, checkbox))
            
            with gr.Accordion("Filter by Score: (Click to expand)", open=False):
                with gr.Row():
                    hide_incomplete_models = gr.Checkbox(
                        label="Hide models with zero scores in selected datasets",
                        value=True
                    )
                    
                    min_average_performance = gr.Slider(
                        minimum=0,
                        maximum=100,
                        value=80,
                        step=1,
                        label="Minimum Average Performance (%)"
                    )
            
            with gr.Accordion("Filter by Data Source: (Click to expand)", open=False):
                with gr.Row():
                    show_napolab_thesis = gr.Checkbox(
                        label="Napolab Thesis models",
                        value=True
                    )
                    show_teenytinyllama = gr.Checkbox(
                        label="TeenyTinyLlama models",
                        value=True
                    )
                    show_portuguese_leaderboard = gr.Checkbox(
                        label="Open Portuguese LLM Leaderboard models (open-source)",
                        value=True
                    )
                    
                    show_external_models = gr.Checkbox(
                        label="Open Portuguese LLM Leaderboard models (proprietary)",
                        value=True
                    )
            
            # Calculate max parameters for slider
            max_params = 0
            if not PORTUGUESE_LEADERBOARD_DATA.empty:
                max_params = int(PORTUGUESE_LEADERBOARD_DATA['model_num_parameters'].max())
            
            with gr.Accordion("Filter by Model Size: (Click to expand)", open=False):
                with gr.Row():
                    max_num_parameters = gr.Slider(
                        minimum=0,
                        maximum=max_params,
                        value=0,
                        step=1,
                        label="Maximum Number of Parameters",
                        info="This slider is applicable only to Open PT LLM Leaderboard models. For other models, it will have no effect."
                    )
            
            # Search bar for filtering models
            search_query = gr.Textbox(
                label="Search models by name (supports regex)",
                placeholder="Enter model name or regex pattern to filter...",
                value="",
                info="Supports regular expressions. Examples: 'bert.*large', 'gemini|gpt', 'mdeberta.*', '^bert'"
            )
            
            benchmark_table = gr.DataFrame(
                label="Model Performance Benchmarks", 
                wrap=[True, False, False, False, False, False, False, False, False, False], 
                interactive=False,
                datatype=["str", "markdown", "number", "number", "number", "number", "number", "number", "number", "number"],
                column_widths=["80px", "200px", "100px", "120px", "120px", "120px", "120px", "120px", "120px", "120px"]
            )
            
            gr.Markdown("*🥇🥈🥉 = Top 3 | 🟢 = Top 33% | 🟡 = Middle 33% | 🔴 = Bottom 33%*")
            
            # Export to CSV button and file component
            export_button = gr.Button("📥 Export to CSV", variant="secondary")
            csv_file = gr.File(label="Download CSV", interactive=False, visible=True)
        
        # Model Analysis Tab
        with gr.Tab("📈 Model Analysis"):
            gr.Markdown("### Model Performance Radar Chart")
            
            # Dataset Selection Controls
            with gr.Accordion("Select Datasets to Display: (Click to expand)", open=False):
                with gr.Row():
                    # Create checkboxes for each dataset
                    analysis_dataset_checkboxes = []
                    for dataset_name in sorted(NAPOLAB_DATASETS.keys()):
                        display_name = NAPOLAB_DATASETS[dataset_name].get('name', dataset_name)
                        # Default to selected only for ASSIN 2 STS, FaQUaD-NLI, and HateBR
                        default_value = display_name in ['ASSIN 2 STS', 'FaQUaD-NLI', 'HateBR']
                        checkbox = gr.Checkbox(
                            label=display_name,
                            value=default_value
                        )
                        analysis_dataset_checkboxes.append((dataset_name, checkbox))
            
            # Filter Controls
            with gr.Accordion("Filter by Score: (Click to expand)", open=False):
                with gr.Row():
                    hide_incomplete_models_analysis = gr.Checkbox(
                        label="Hide models with zero scores in selected datasets",
                        value=True
                    )
                    
                    min_average_performance_analysis = gr.Slider(
                        minimum=0,
                        maximum=100,
                        value=80,
                        step=1,
                        label="Minimum Average Performance (%)"
                    )
            
            with gr.Accordion("Filter by Data Source: (Click to expand)", open=False):
                with gr.Row():
                    show_napolab_thesis_analysis = gr.Checkbox(
                        label="Napolab Thesis models",
                        value=True
                    )
                    
                    show_teenytinyllama_analysis = gr.Checkbox(
                        label="TeenyTinyLlama models",
                        value=True
                    )
                    
                    show_portuguese_leaderboard_analysis = gr.Checkbox(
                        label="Open Portuguese LLM Leaderboard models (open-source)",
                        value=True
                    )
                    
                    show_external_models_analysis = gr.Checkbox(
                        label="Open Portuguese LLM Leaderboard models (proprietary)",
                        value=True
                    )
            
            # Parameter slider for Model Analysis tab
            with gr.Accordion("Filter by Model Size: (Click to expand)", open=False):
                with gr.Row():
                    max_num_parameters_analysis = gr.Slider(
                        minimum=0,
                        maximum=max_params,
                        value=0,
                        step=1,
                        label="Maximum Number of Parameters",
                        info="This slider is applicable only to Open PT LLM Leaderboard models. For other models, it will have no effect."
                    )

            # Search bar for filtering models in radar chart
            search_query_analysis = gr.Textbox(
                label="Search models by name (supports regex)",
                placeholder="Enter model name or regex pattern to filter...",
                value="",
                info="Supports regular expressions. Examples: 'bert.*large', 'gemini|gpt', 'mdeberta.*', '^bert'"
            )
            
            model_analysis_chart = gr.Plot(label="Model Performance Radar Chart")
            
            # Add scatter plot below radar chart
            model_scatter_plot = gr.Plot(label="Model Performance vs Number of Parameters")
            
            gr.Markdown("""
            **How to interact with the chart:**
            - **Click on legend items** to show/hide specific models.
            - **Double-click on a legend item** to isolate that model (hide all others).
            - **Double-click again** to show all models.

            Models in the legend are sorted in descending order based on their average performance across your chosen datasets.
            """)
        

        
        # About Tab
        with gr.Tab("ℹ️ About"):
            gr.Markdown("""
            ## About Napolab
            
            **Natural Portuguese Language Benchmark (Napolab)** is a comprehensive collection of Portuguese datasets designed for evaluating Large Language Models.
            
            - [GitHub repository](https://github.com/ruanchaves/napolab)
            - [Hugging Face Dataset](https://huggingface.co/datasets/ruanchaves/napolab)
            - Article: ["The Hidden Truth About LLM Performance: Why Your Benchmark Results Might Be Misleading"](https://ruanchaves.medium.com/the-hidden-truth-about-llm-performance-why-your-benchmark-results-might-be-misleading-afd24f40a46c)
            
            ### Data Sources:
            The benchmark results and model evaluations presented in this leaderboard are compiled from multiple sources:
            
            **1. "Lessons learned from the evaluation of Portuguese language models"** by Ruan Chaves Rodrigues (2023). Available at: [University of Malta OAR@UM Repository](https://www.um.edu.mt/library/oar/handle/123456789/120557)

            **2. Open PT LLM Leaderboard** by Eduardo Garcia (2025). Available at: [Hugging Face Spaces](https://huggingface.co/spaces/eduagarcia/open_pt_llm_leaderboard).
            
            **3. "TeenyTinyLlama: Open-source tiny language models trained in Brazilian Portuguese"** by Corrêa et al. (2024). Available at: [arXiv](https://arxiv.org/abs/2401.16640).
            
            ### Thesis Citation:
            ```bibtex
            @mastersthesis{chaves2023lessons,
            title={Lessons learned from the evaluation of Portuguese language models},
            author={Chaves Rodrigues, Ruan},
            year={2023},
            school={University of Malta},
            url={https://www.um.edu.mt/library/oar/handle/123456789/120557}
            }
            ```
            
            ### Napolab Citation:
            ```bibtex
            @software{Chaves_Rodrigues_napolab_2023,
            author = {Chaves Rodrigues, Ruan and Tanti, Marc and Agerri, Rodrigo},
            doi = {10.5281/zenodo.7781848},
            month = {3},
            title = {{Natural Portuguese Language Benchmark (Napolab)}},
            url = {https://github.com/ruanchaves/napolab},
            version = {1.0.0},
            year = {2023}
            }
            ```

            """)
    
    def create_model_performance_scatter(selected_datasets: List[str] = None, show_napolab_thesis: bool = True, show_teenytinyllama: bool = True, show_portuguese_leaderboard: bool = True, show_external_models: bool = True, hide_incomplete_models: bool = False, min_average_performance: float = 0.0, search_query: str = "", max_num_parameters: int = 0) -> go.Figure:
        """Create a scatter plot showing model performance vs number of parameters."""
        # Use selected datasets if provided, otherwise use all datasets
        if selected_datasets is None:
            selected_datasets = list(NAPOLAB_DATASETS.keys())
        
        # Collect data for each model
        model_data = {}
        
        # Process existing benchmark results
        for dataset_name, models in SAMPLE_BENCHMARK_RESULTS.items():
            if dataset_name in selected_datasets:
                for model_name, metrics in models.items():
                    if model_name not in model_data:
                        # Get actual source from MODEL_METADATA
                        model_metadata = MODEL_METADATA.get(model_name, {})
                        actual_source = model_metadata.get('source', 'unknown')
                        
                        model_data[model_name] = {
                            'performances': {},
                            'architecture': model_metadata.get('architecture', 'Unknown'),
                            'source': actual_source,
                            'num_parameters': 0
                        }
                    
                    # Calculate average performance for this dataset
                    avg_performance = np.mean(list(metrics.values()))
                    model_data[model_name]['performances'][dataset_name] = avg_performance
        
        # Process Portuguese leaderboard data
        if show_portuguese_leaderboard and not PORTUGUESE_LEADERBOARD_DATA.empty:
            for _, row in PORTUGUESE_LEADERBOARD_DATA.iterrows():
                model_name = row['model_name']
                
                if model_name not in model_data:
                    model_data[model_name] = {
                        'performances': {},
                        'architecture': 'Unknown',
                        'source': 'portuguese_leaderboard',
                        'num_parameters': row.get('model_num_parameters', 0)
                    }
                
                # Map Portuguese leaderboard columns to dataset names
                column_mapping = {
                    'ASSIN2 RTE': 'assin2_rte',
                    'ASSIN2 STS': 'assin2_sts',
                    'FaQUaD-NLI': 'faquad-nli',
                    'HateBR': 'hatebr'
                }
                
                for display_name, dataset_name in column_mapping.items():
                    if dataset_name in selected_datasets:
                        score = row[display_name]
                        if pd.notna(score) and score > 0:
                            model_data[model_name]['performances'][dataset_name] = score
        
        # Process external models data
        if show_external_models and not EXTERNAL_MODELS_DATA.empty:
            for _, row in EXTERNAL_MODELS_DATA.iterrows():
                model_name = row['model_name']
                
                if model_name not in model_data:
                    model_data[model_name] = {
                        'performances': {},
                        'architecture': 'Unknown',
                        'source': 'external_models',
                        'num_parameters': row.get('model_num_parameters', 0)
                    }
                
                # Map external models columns to dataset names
                column_mapping = {
                    'ASSIN2 RTE': 'assin2_rte',
                    'ASSIN2 STS': 'assin2_sts',
                    'FaQUaD-NLI': 'faquad-nli',
                    'HateBR': 'hatebr'
                }
                
                for display_name, dataset_name in column_mapping.items():
                    if dataset_name in selected_datasets:
                        score = row[display_name]
                        if pd.notna(score) and score > 0:
                            model_data[model_name]['performances'][dataset_name] = score
        
        # Apply source filtering
        filtered_model_data = {}
        for model_name, data in model_data.items():
            source = data.get('source', 'existing')
            
            # Apply show filters - only show models from sources that are checked
            if source == 'napolab_thesis' and not show_napolab_thesis:
                continue
            if source == 'teenytinyllama_paper' and not show_teenytinyllama:
                continue
            if source == 'portuguese_leaderboard' and not show_portuguese_leaderboard:
                continue
            if source == 'external_models' and not show_external_models:
                continue
            # Hide models with unknown source (should not happen with proper data)
            if source == 'unknown':
                continue
            
            # Apply parameter filtering (only for Portuguese leaderboard models)
            if max_num_parameters > 0 and source == 'portuguese_leaderboard':
                num_parameters = data.get('num_parameters', 0)
                if num_parameters > max_num_parameters:
                    continue
            
            filtered_model_data[model_name] = data
        
        # Apply incomplete model filtering
        if hide_incomplete_models and selected_datasets:
            final_filtered_data = {}
            for model_name, data in filtered_model_data.items():
                has_all_scores = True
                for dataset_name in selected_datasets:
                    if data['performances'].get(dataset_name, 0) == 0:
                        has_all_scores = False
                        break
                if has_all_scores:
                    final_filtered_data[model_name] = data
            filtered_model_data = final_filtered_data
        
        # Apply minimum average performance filtering
        if min_average_performance > 0 and selected_datasets:
            final_filtered_data = {}
            for model_name, data in filtered_model_data.items():
                # Calculate average performance for selected datasets
                scores = []
                for dataset_name in selected_datasets:
                    score = data['performances'].get(dataset_name, 0)
                    if score > 0:  # Only include non-zero scores
                        scores.append(score)
                
                if scores:
                    avg_performance = np.mean(scores)
                    if avg_performance >= min_average_performance:
                        final_filtered_data[model_name] = data
            filtered_model_data = final_filtered_data
        
        # Apply search query filtering
        if search_query:
            final_filtered_data = {}
            try:
                # Use regex pattern matching
                import re
                pattern = re.compile(search_query, re.IGNORECASE)
                for model_name, data in filtered_model_data.items():
                    if pattern.search(model_name):
                        final_filtered_data[model_name] = data
            except re.error:
                # Fallback to simple string matching if regex is invalid
                for model_name, data in filtered_model_data.items():
                    if search_query.lower() in model_name.lower():
                        final_filtered_data[model_name] = data
            filtered_model_data = final_filtered_data
        
        # Prepare data for scatter plot
        scatter_data = []
        for model_name, data in filtered_model_data.items():
            # Calculate average performance for selected datasets
            scores = []
            for dataset_name in selected_datasets:
                score = data['performances'].get(dataset_name, 0)
                if score > 0:  # Only include non-zero scores
                    scores.append(score)
            
            if scores:
                avg_performance = np.mean(scores)
                num_parameters = data.get('num_parameters', 0)
                source = data.get('source', 'unknown')
                
                scatter_data.append({
                    'model_name': model_name,
                    'avg_performance': avg_performance,
                    'num_parameters': num_parameters,
                    'source': source
                })
        
        if not scatter_data:
            # Create empty figure if no data
            fig = go.Figure()
            fig.add_annotation(
                text="No data available for the selected filters",
                xref="paper", yref="paper",
                x=0.5, y=0.5, showarrow=False,
                font=dict(size=16)
            )
            fig.update_layout(
                title="Model Performance vs Number of Parameters",
                xaxis_title="Number of Parameters",
                yaxis_title="Average Performance Score",
                height=500
            )
            return fig
        
        # Create scatter plot
        df_scatter = pd.DataFrame(scatter_data)
        
        # Create color mapping for sources
        color_map = {
            'portuguese_leaderboard': '#1f77b4',
            'external_models': '#ff7f0e',
            'napolab_thesis': '#2ca02c',
            'teenytinyllama_paper': '#d62728',
            'unknown': '#9467bd'
        }
        
        # Create display name mapping for sources
        display_name_map = {
            'portuguese_leaderboard': 'Open PT LLM Leaderboard',
            'external_models': 'Proprietary Models',
            'napolab_thesis': 'Napolab Thesis',
            'teenytinyllama_paper': 'TeenyTinyLlama Paper',
            'unknown': 'Unknown Source'
        }
        
        fig = go.Figure()
        
        for source in df_scatter['source'].unique():
            source_data = df_scatter[df_scatter['source'] == source]
            color = color_map.get(source, '#7f7f7f')
            display_name = display_name_map.get(source, source.replace('_', ' ').title())
            
            fig.add_trace(go.Scatter(
                x=source_data['num_parameters'],
                y=source_data['avg_performance'],
                mode='markers',
                name=display_name,
                marker=dict(
                    color=color,
                    size=8,
                    opacity=0.7
                ),
                text=source_data['model_name'],
                hovertemplate=(
                    "<b>%{text}</b><br>" +
                    "Average Performance: %{y:.3f}<br>" +
                    "Number of Parameters: %{x:,}<br>" +
                    "Source: " + display_name + "<br>" +
                    "<extra></extra>"
                )
            ))
        
        fig.update_layout(
            title="Model Performance vs Number of Parameters",
            xaxis_title="Number of Parameters",
            yaxis_title="Average Performance Score",
            height=500,
            showlegend=True,
            plot_bgcolor='rgba(255, 255, 255, 0)',
            paper_bgcolor='rgba(255, 255, 255, 0)',
            legend=dict(
                yanchor="top",
                y=-0.15,
                xanchor="center",
                x=0.5,
                bgcolor='rgba(255, 255, 255, 0.95)',
                bordercolor='rgba(0, 0, 0, 0.2)',
                borderwidth=1,
                orientation="h"
            ),
            margin=dict(l=50, r=50, t=100, b=100)
        )
        
        return fig
    
    # Event handlers
    def update_radar_chart(*args):
        # Extract arguments for radar chart
        dataset_values = args[:len(analysis_dataset_checkboxes)]
        hide_incomplete_models = args[len(analysis_dataset_checkboxes)]
        min_average_performance = args[len(analysis_dataset_checkboxes) + 1] / 100.0  # Convert percentage to decimal
        show_napolab_thesis = args[len(analysis_dataset_checkboxes) + 2]
        show_teenytinyllama = args[len(analysis_dataset_checkboxes) + 3]
        show_portuguese_leaderboard = args[len(analysis_dataset_checkboxes) + 4]
        show_external_models = args[len(analysis_dataset_checkboxes) + 5]
        search_query = args[len(analysis_dataset_checkboxes) + 6]
        max_num_parameters = args[len(analysis_dataset_checkboxes) + 7]
        
        # Convert dataset selections to list of selected dataset names
        selected_datasets = []
        for i, (dataset_name, _) in enumerate(analysis_dataset_checkboxes):
            if dataset_values[i]:
                selected_datasets.append(dataset_name)
        
        return create_model_performance_radar(selected_datasets, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, hide_incomplete_models, min_average_performance, search_query, max_num_parameters)
    
    def update_benchmark_table(*args):
        # Extract arguments
        dataset_values = args[:len(dataset_checkboxes)]
        hide_incomplete_models = args[len(dataset_checkboxes)]
        min_average_performance = args[len(dataset_checkboxes) + 1] / 100.0  # Convert percentage to decimal
        show_napolab_thesis = args[len(dataset_checkboxes) + 2]
        show_teenytinyllama = args[len(dataset_checkboxes) + 3]
        show_portuguese_leaderboard = args[len(dataset_checkboxes) + 4]
        show_external_models = args[len(dataset_checkboxes) + 5]
        search_query = args[len(dataset_checkboxes) + 6]
        max_num_parameters = args[len(dataset_checkboxes) + 7]
        
        # Convert dataset selections to list of selected dataset names
        selected_datasets = []
        for i, (dataset_name, _) in enumerate(dataset_checkboxes):
            if dataset_values[i]:
                selected_datasets.append(dataset_name)
        
        df = create_simplified_benchmark_table(selected_datasets, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, hide_incomplete_models, min_average_performance, search_query, max_num_parameters)
        
        return df
    
    def update_scatter_plot(*args):
        # Extract arguments for scatter plot
        dataset_values = args[:len(analysis_dataset_checkboxes)]
        hide_incomplete_models = args[len(analysis_dataset_checkboxes)]
        min_average_performance = args[len(analysis_dataset_checkboxes) + 1] / 100.0  # Convert percentage to decimal
        show_napolab_thesis = args[len(analysis_dataset_checkboxes) + 2]
        show_teenytinyllama = args[len(analysis_dataset_checkboxes) + 3]
        show_portuguese_leaderboard = args[len(analysis_dataset_checkboxes) + 4]
        show_external_models = args[len(analysis_dataset_checkboxes) + 5]
        search_query = args[len(analysis_dataset_checkboxes) + 6]
        max_num_parameters = args[len(analysis_dataset_checkboxes) + 7]
        
        # Convert dataset selections to list of selected dataset names
        selected_datasets = []
        for i, (dataset_name, _) in enumerate(analysis_dataset_checkboxes):
            if dataset_values[i]:
                selected_datasets.append(dataset_name)
        
        return create_model_performance_scatter(selected_datasets, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, hide_incomplete_models, min_average_performance, search_query, max_num_parameters)
    
    # Connect dataset checkboxes to update table
    for dataset_name, checkbox in dataset_checkboxes:
        checkbox.change(
            update_benchmark_table,
            inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
            outputs=benchmark_table
        )
    
    hide_incomplete_models.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    min_average_performance.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    show_napolab_thesis.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    show_teenytinyllama.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )

    show_portuguese_leaderboard.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    show_external_models.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    # Connect search query to update table
    search_query.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    # Connect max_num_parameters to update table
    max_num_parameters.change(
        update_benchmark_table,
        inputs=[cb for _, cb in dataset_checkboxes] + [hide_incomplete_models, min_average_performance, show_napolab_thesis, show_teenytinyllama, show_portuguese_leaderboard, show_external_models, search_query, max_num_parameters],
        outputs=benchmark_table
    )
    
    # Connect export button
    export_button.click(
        export_csv,
        inputs=benchmark_table,
        outputs=csv_file
    )
    
    # Connect file download to cleanup
    csv_file.change(
        cleanup_current_csv,
        inputs=None,
        outputs=None
    )
    
    # Connect analysis chart events
    # Connect dataset checkboxes to update radar chart
    for dataset_name, checkbox in analysis_dataset_checkboxes:
        checkbox.change(
            update_radar_chart,
            inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
            outputs=model_analysis_chart
        )
    
    hide_incomplete_models_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    min_average_performance_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    show_napolab_thesis_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    show_teenytinyllama_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )

    show_portuguese_leaderboard_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    show_external_models_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    # Connect search query to update radar chart
    search_query_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    # Connect max_num_parameters_analysis to update radar chart
    max_num_parameters_analysis.change(
        update_radar_chart,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_analysis_chart
    )
    
    # Connect all analysis controls to update scatter plot
    for dataset_name, checkbox in analysis_dataset_checkboxes:
        checkbox.change(
            update_scatter_plot,
            inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
            outputs=model_scatter_plot
        )
    
    hide_incomplete_models_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    min_average_performance_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    show_napolab_thesis_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    show_teenytinyllama_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )

    show_portuguese_leaderboard_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    show_external_models_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    search_query_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    max_num_parameters_analysis.change(
        update_scatter_plot,
        inputs=[cb for _, cb in analysis_dataset_checkboxes] + [hide_incomplete_models_analysis, min_average_performance_analysis, show_napolab_thesis_analysis, show_teenytinyllama_analysis, show_portuguese_leaderboard_analysis, show_external_models_analysis, search_query_analysis, max_num_parameters_analysis],
        outputs=model_scatter_plot
    )
    
    # Connect events
    # Load model analysis chart on app start
    app.load(lambda: update_radar_chart(*([display_name in ['ASSIN 2 STS', 'FaQUaD-NLI', 'HateBR'] for _, display_name in [(name, NAPOLAB_DATASETS[name].get('name', name)) for name in sorted(NAPOLAB_DATASETS.keys())]] + [True, 80, True, True, True, True, "", 0])), outputs=model_analysis_chart)
    
    # Load scatter plot on app start
    app.load(lambda: update_scatter_plot(*([display_name in ['ASSIN 2 STS', 'FaQUaD-NLI', 'HateBR'] for _, display_name in [(name, NAPOLAB_DATASETS[name].get('name', name)) for name in sorted(NAPOLAB_DATASETS.keys())]] + [True, 80, True, True, True, True, "", 0])), outputs=model_scatter_plot)
    
    # Load benchmark table on app start
    app.load(lambda: update_benchmark_table(*([display_name in ['ASSIN 2 STS', 'FaQUaD-NLI', 'HateBR'] for _, display_name in [(name, NAPOLAB_DATASETS[name].get('name', name)) for name in sorted(NAPOLAB_DATASETS.keys())]] + [True, 80, True, True, True, True, "", 0])), outputs=benchmark_table)

if __name__ == "__main__":
    app.launch(server_name="0.0.0.0", server_port=7860)