File size: 43,476 Bytes
24a059f
 
e109361
24a059f
 
d24563e
aeeda1a
18bd6ff
24a059f
13e4c4d
 
7fcd557
c308901
13e4c4d
d24563e
13e4c4d
 
 
d24563e
f5e8de3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9803b0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e109361
fb73da9
e109361
fb73da9
e109361
 
9803b0e
b0b8450
e109361
13e4c4d
 
9803b0e
b0b8450
13e4c4d
6bcbc7b
e109361
 
 
 
 
13e4c4d
24a059f
8b80c42
9803b0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f7748a
8b80c42
 
 
2f1a209
f5e8de3
2f1a209
1f7b6e5
 
2f1a209
70ae509
2f1a209
 
d67bb93
8b80c42
d67bb93
8b80c42
 
2f1a209
 
 
 
8b80c42
2f1a209
8b80c42
 
 
 
 
 
 
 
 
9803b0e
8b80c42
 
d30a8bb
 
8b80c42
d67bb93
8b80c42
2f1a209
9e3da0c
 
 
 
 
 
 
 
 
 
 
 
d67bb93
9e3da0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f7748a
9803b0e
 
 
 
 
 
 
 
 
 
 
 
 
 
e109361
 
 
 
 
1f7b6e5
 
e109361
b0b8450
 
e109361
 
9803b0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f7748a
8b5944b
d24563e
 
 
13e4c4d
 
d24563e
 
 
13e4c4d
 
d24563e
 
 
8f89713
104bf5a
8f89713
 
9803b0e
8f89713
9803b0e
aabd188
 
 
 
 
 
 
 
 
8f89713
 
 
 
 
 
 
 
 
 
1fe4357
8f89713
f5e8de3
 
803487b
8f89713
 
1fe4357
 
 
 
 
2f1a209
8f89713
 
e109361
1f0c8bc
f5e8de3
9e3da0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8ab1fc
7bdeca8
e359f0e
a1ee136
 
 
54685aa
aad6765
54685aa
a1ee136
d55e531
 
a1ee136
 
 
 
 
 
 
7d75ad8
a1ee136
 
8fbfd67
a1ee136
 
 
 
 
 
 
 
 
 
 
c755c1e
a1ee136
 
 
 
07aee39
7098daa
ea94a6e
d55e531
a1ee136
7098daa
 
a1ee136
 
 
 
 
 
09f2be6
a1ee136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df5438f
 
2039721
 
 
59f9966
3165694
df5438f
 
2039721
59f9966
3165694
df5438f
 
 
2039721
df5438f
3165694
f85f3da
df5438f
a1ee136
b4ac62c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bee0fa5
b4ac62c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f292c79
b4ac62c
 
 
 
 
 
 
df5438f
b4ac62c
f292c79
b4ac62c
 
 
 
f292c79
b4ac62c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d5d159
b4ac62c
 
 
 
 
 
 
 
9d5d159
da61d55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60b5137
 
 
 
4df948d
54685aa
f85f3da
 
0f7ef29
f85f3da
 
0f7ef29
4cf45d5
6b2d15e
582f8ec
 
f85f3da
4cf45d5
 
 
 
 
 
0f7ef29
706851c
f85f3da
 
 
 
0f7ef29
706851c
f85f3da
 
 
 
0f7ef29
f85f3da
706851c
f85f3da
0f7ef29
f85f3da
706851c
f85f3da
0f7ef29
f85f3da
 
 
0f7ef29
f85f3da
 
866c2f8
 
 
 
 
 
54685aa
fa8abad
5dc58a0
87904ff
e359f0e
87904ff
e359f0e
87904ff
3ab70ce
 
87904ff
 
 
26a9076
 
 
 
1f35a2e
 
 
26a9076
 
 
 
 
 
 
 
 
 
 
 
2039721
87904ff
ecfd2b0
7e020a6
ecfd2b0
e359f0e
3898c96
 
30cb266
 
 
 
 
 
 
 
 
 
 
 
8db9450
6b80f8b
30cb266
a0dbb90
30cb266
 
 
 
fbde589
 
 
30cb266
3898c96
bfda7ed
5d7850e
40a6d25
4996c56
42ad0a2
 
 
d6777ef
4df948d
4996c56
d0dba04
 
5578c3c
d6777ef
4996c56
d0dba04
d6777ef
4996c56
d0dba04
 
 
aa88144
8e8d6c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa88144
8e8d6c7
9e3da0c
 
8e8d6c7
aa88144
8e8d6c7
aa88144
5578c3c
d6777ef
 
 
 
5578c3c
 
d6777ef
 
 
 
 
aa88144
d6777ef
 
 
 
 
 
aa88144
 
 
 
 
 
 
 
 
 
 
 
203177b
 
 
 
 
 
 
 
 
 
 
 
 
 
cd3118d
9e3da0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce757f
d6777ef
5578c3c
d6777ef
5578c3c
d6777ef
9e3da0c
 
 
 
 
 
d6777ef
 
 
 
5578c3c
d6777ef
 
9e3da0c
 
 
 
 
 
 
 
 
 
 
 
d6777ef
 
 
5578c3c
d6777ef
 
 
5ede32f
d24563e
73c3f03
35ad686
5dc58a0
35ad686
 
5dc58a0
 
514663d
35ad686
5dc58a0
35ad686
 
 
9e3da0c
 
b11f8d5
9e3da0c
 
 
 
 
 
b11f8d5
9e3da0c
 
 
3d8b2b7
ecfd2b0
e51b169
 
 
 
 
 
 
 
 
 
 
ecfd2b0
 
e51b169
 
 
 
 
ecfd2b0
 
e51b169
18bd6ff
 
 
 
 
 
 
ecfd2b0
 
 
bfda7ed
ecfd2b0
 
 
 
 
35ba041
027dd6e
09f2be6
a4a4c08
bfda7ed
5376412
5dc58a0
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
import gradio as gr
import pandas as pd
import os
import re
from datetime import datetime
from huggingface_hub import hf_hub_download
from huggingface_hub import HfApi, HfFolder
from constants import CITATION_TEXT

LEADERBOARD_FILE = "leaderboard.csv"
GROUND_TRUTH_FILE = "ground_truth.csv"
LAST_UPDATED = datetime.now().strftime("%B %d, %Y")

# Ensure authentication and suppress warnings
os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
    raise ValueError("HF_TOKEN environment variable is not set or invalid.")

# def initialize_leaderboard_file():
#     """
#     Ensure the leaderboard file exists and has the correct headers.
#     """
#     if not os.path.exists(LEADERBOARD_FILE):
#         pd.DataFrame(columns=[
#            "Model Name", "Overall Accuracy", "Valid Accuracy",
#             "Correct Predictions", "Total Questions", "Timestamp"
#         ]).to_csv(LEADERBOARD_FILE, index=False)
#     elif os.stat(LEADERBOARD_FILE).st_size == 0:
#         pd.DataFrame(columns=[
#             "Model Name", "Overall Accuracy", "Valid Accuracy",
#             "Correct Predictions", "Total Questions", "Timestamp"
#         ]).to_csv(LEADERBOARD_FILE, index=False)

# def clean_answer(answer):
#     if pd.isna(answer):
#         return None
#     answer = str(answer)
#     clean = re.sub(r'[^A-Da-d]', '', answer)
#     return clean[0].upper() if clean else None


# def update_leaderboard(results):
#     """
#     Append new submission results to the leaderboard file and push updates to the Hugging Face repository.
#     """
#     new_entry = {
#        "Model Name": results['model_name'],
#         "Overall Accuracy": round(results['overall_accuracy'] * 100, 2),
#         "Valid Accuracy": round(results['valid_accuracy'] * 100, 2),
#         "Correct Predictions": results['correct_predictions'],
#         "Total Questions": results['total_questions'],
#         "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
#     }

#     try:
#         # Update the local leaderboard file
#         new_entry_df = pd.DataFrame([new_entry])
#         file_exists = os.path.exists(LEADERBOARD_FILE)
        
#         new_entry_df.to_csv(
#             LEADERBOARD_FILE,
#             mode='a',  # Append mode
#             index=False,
#             header=not file_exists  # Write header only if the file is new
#         )
#         print(f"Leaderboard updated successfully at {LEADERBOARD_FILE}")

#         # Push the updated file to the Hugging Face repository using HTTP API
#         api = HfApi()
#         token = HfFolder.get_token()
        
#         api.upload_file(
#             path_or_fileobj=LEADERBOARD_FILE,
#             path_in_repo="leaderboard.csv",
#             repo_id="SondosMB/ss",  # Your Space repository
#             repo_type="space",
#             token=token
#         )
#         print("Leaderboard changes pushed to Hugging Face repository.")
        
#     except Exception as e:
#         print(f"Error updating leaderboard file: {e}")



# def load_leaderboard():
#     if not os.path.exists(LEADERBOARD_FILE) or os.stat(LEADERBOARD_FILE).st_size == 0:
#         return pd.DataFrame({
#             "Model Name": [],
#             "Overall Accuracy": [],
#             "Valid Accuracy": [],
#             "Correct Predictions": [],
#             "Total Questions": [],
#             "Timestamp": [],
#         })
#     return pd.read_csv(LEADERBOARD_FILE)

# def evaluate_predictions(prediction_file, model_name, add_to_leaderboard):
#     try:
#         ground_truth_path = hf_hub_download(
#             repo_id="SondosMB/ground-truth-dataset",
#             filename="ground_truth.csv",
#             repo_type="dataset",
#             use_auth_token=True
#         )
#         ground_truth_df = pd.read_csv(ground_truth_path)
#     except FileNotFoundError:
#         return "Ground truth file not found in the dataset repository.", load_leaderboard()
#     except Exception as e:
#         return f"Error loading ground truth: {e}", load_leaderboard()

#     if not prediction_file:
#         return "Prediction file not uploaded.", load_leaderboard()

#     try:
#         #load predition file
#         predictions_df = pd.read_csv(prediction_file.name)
#          # Validate required columns in prediction file
#         required_columns = ['question_id', 'predicted_answer']
#         missing_columns = [col for col in required_columns if col not in predictions_df.columns]
#         if missing_columns:
#             return (f"Error: Missing required columns in prediction file: {', '.join(missing_columns)}.",
#                     load_leaderboard())

#         # Validate 'Answer' column in ground truth file
#         if 'Answer' not in ground_truth_df.columns:
#             return "Error: 'Answer' column is missing in the ground truth dataset.", load_leaderboard()
#         merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
#         merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)

#         valid_predictions = merged_df.dropna(subset=['pred_answer'])
#         correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
#         total_predictions = len(merged_df)
#         total_valid_predictions = len(valid_predictions)

#         overall_accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0
#         valid_accuracy = correct_predictions / total_valid_predictions if total_valid_predictions > 0 else 0

#         results = {
#             'model_name': model_name if model_name else "Unknown Model",
#             'overall_accuracy': overall_accuracy,
#         }

#         if add_to_leaderboard:
#             update_leaderboard(results)
#             return "Evaluation completed and added to leaderboard.", load_leaderboard()
#         else:
#             return "Evaluation completed but not added to leaderboard.", load_leaderboard()
  
#     except Exception as e:
#         return f"Error during evaluation: {str(e)}", load_leaderboard()

# initialize_leaderboard_file()
# def initialize_leaderboard_file():
#     """
#     Ensure the leaderboard file exists and has the correct headers.
#     """
#     if not os.path.exists(LEADERBOARD_FILE):
#         pd.DataFrame(columns=[
#             "Model Name", "Overall Accuracy", "Valid Accuracy",
#             "Correct Predictions", "Total Questions", "Timestamp"
#         ]).to_csv(LEADERBOARD_FILE, index=False)
#     elif os.stat(LEADERBOARD_FILE).st_size == 0:
#         pd.DataFrame(columns=[
#             "Model Name", "Overall Accuracy", "Valid Accuracy",
#             "Correct Predictions", "Total Questions", "Timestamp"
#         ]).to_csv(LEADERBOARD_FILE, index=False)

def initialize_leaderboard_file():
    """
    Ensure the leaderboard file exists and has the correct headers.
    """
    if not os.path.exists(LEADERBOARD_FILE):
        pd.DataFrame(columns=[
            "Model Name", "Overall Accuracy", "Correct Predictions", 
            "Total Questions", "Timestamp", "Team Name"
        ]).to_csv(LEADERBOARD_FILE, index=False)
    elif os.stat(LEADERBOARD_FILE).st_size == 0:
        pd.DataFrame(columns=[
            "Model Name", "Overall Accuracy", "Correct Predictions", 
            "Total Questions", "Timestamp", "Team Name"
        ]).to_csv(LEADERBOARD_FILE, index=False)

def clean_answer(answer):
    if pd.isna(answer):
        return None
    answer = str(answer)
    clean = re.sub(r'[^A-Da-d]', '', answer)
    return clean[0].upper() if clean else None


# def update_leaderboard(results):
#     """
#     Append new submission results to the leaderboard file and push updates to the Hugging Face repository.
#     """
#     new_entry = {
#         "Model Name": results['model_name'],
#         "Overall Accuracy": round(results['overall_accuracy'] * 100, 2),
#         "Valid Accuracy": round(results['valid_accuracy'] * 100, 2),
#         "Correct Predictions": results['correct_predictions'],
#         "Total Questions": results['total_questions'],
#         "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
#     }

#     try:
#         # Update the local leaderboard file
#         new_entry_df = pd.DataFrame([new_entry])
#         file_exists = os.path.exists(LEADERBOARD_FILE)
        
#         new_entry_df.to_csv(
#             LEADERBOARD_FILE,
#             mode='a',  # Append mode
#             index=False,
#             header=not file_exists  # Write header only if the file is new
#         )
#         print(f"Leaderboard updated successfully at {LEADERBOARD_FILE}")

#         # Push the updated file to the Hugging Face repository using HTTP API
#         api = HfApi()
#         token = HfFolder.get_token()
        
#         api.upload_file(
#             path_or_fileobj=LEADERBOARD_FILE,
#             path_in_repo="leaderboard.csv",
#             repo_id="SondosMB/ss",  # Your Space repository
#             repo_type="space",
#             token=token
#         )
#         print("Leaderboard changes pushed to Hugging Face repository.")
        
#     except Exception as e:
#         print(f"Error updating leaderboard file: {e}")

def update_leaderboard(results):
    """
    Append new submission results to the leaderboard file and push updates to the Hugging Face repository.
    """
    new_entry = {
        "Model Name": results['model_name'],
        "Overall Accuracy": round(results['overall_accuracy'] * 100, 2),
        "Correct Predictions": results['correct_predictions'],
        "Total Questions": results['total_questions'],
        "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "Team Name": results['Team_name']
    }

    try:
        # Update the local leaderboard file
        new_entry_df = pd.DataFrame([new_entry])
        file_exists = os.path.exists(LEADERBOARD_FILE)
        
        new_entry_df.to_csv(
            LEADERBOARD_FILE,
            mode='a',  # Append mode
            index=False,
            header=not file_exists  # Write header only if the file is new
        )
        print(f"Leaderboard updated successfully at {LEADERBOARD_FILE}")

        # Push the updated file to the Hugging Face repository using HTTP API
        api = HfApi()
        token = HfFolder.get_token()
        
        api.upload_file(
            path_or_fileobj=LEADERBOARD_FILE,
            path_in_repo="leaderboard.csv",
            repo_id="SondosMB/Mobile-MMLU",  # Your Space repository
            repo_type="space",
            token=token
        )
        print("Leaderboard changes pushed to Hugging Face repository.")
        
    except Exception as e:
        print(f"Error updating leaderboard file: {e}")

def update_leaderboard_pro(results):
    """
    Append new submission results to the leaderboard file and push updates to the Hugging Face repository.
    """
    new_entry = {
        "Model Name": results['model_name'],
        "Overall Accuracy": round(results['overall_accuracy'] * 100, 2),
        "Correct Predictions": results['correct_predictions'],
        "Total Questions": results['total_questions'],
        "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "Team Name": results['Team_name']
    }

    try:
        # Update the local leaderboard file
        new_entry_df = pd.DataFrame([new_entry])
        file_exists = os.path.exists(LEADERBOARD_FILE)
        
        new_entry_df.to_csv(
            LEADERBOARD_FILE,
            mode='a',  # Append mode
            index=False,
            header=not file_exists  # Write header only if the file is new
        )
        print(f"Leaderboard updated successfully at {LEADERBOARD_FILE}")

        # Push the updated file to the Hugging Face repository using HTTP API
        api = HfApi()
        token = HfFolder.get_token()
        
        api.upload_file(
            path_or_fileobj=LEADERBOARD_FILE,
            path_in_repo="leaderboardPro.csv",
            repo_id="SondosMB/Mobile-MMLU",  # Your Space repository
            repo_type="space",
            token=token
        )
        print("Leaderboard changes pushed to Hugging Face repository.")
        
    except Exception as e:
        print(f"Error updating leaderboard file: {e}")


# def load_leaderboard():
#     if not os.path.exists(LEADERBOARD_FILE) or os.stat(LEADERBOARD_FILE).st_size == 0:
#         return pd.DataFrame({
#             "Model Name": [],
#             "Overall Accuracy": [],
#             "Valid Accuracy": [],
#             "Correct Predictions": [],
#             "Total Questions": [],
#             "Timestamp": [],
#         })
#     return pd.read_csv(LEADERBOARD_FILE)


def load_leaderboard():
    if not os.path.exists(LEADERBOARD_FILE) or os.stat(LEADERBOARD_FILE).st_size == 0:
        return pd.DataFrame({
            "Model Name": [],
            "Overall Accuracy": [],
            "Correct Predictions": [],
            "Total Questions": [],
            "Timestamp": [],
            "Team Name": [],
            
        })
    return pd.read_csv(LEADERBOARD_FILE)
    
# def evaluate_predictions(prediction_file, model_name, add_to_leaderboard):
#     try:
#         ground_truth_path = hf_hub_download(
#             repo_id="SondosMB/ground-truth-dataset",
#             filename="ground_truth.csv",
#             repo_type="dataset",
#             use_auth_token=True
#         )
#         ground_truth_df = pd.read_csv(ground_truth_path)
#     except FileNotFoundError:
#         return "Ground truth file not found in the dataset repository.", load_leaderboard()
#     except Exception as e:
#         return f"Error loading ground truth: {e}", load_leaderboard()

#     if not prediction_file:
#         return "Prediction file not uploaded.", load_leaderboard()

#     try:
#         #load predition file
#         predictions_df = pd.read_csv(prediction_file.name)
#          # Validate required columns in prediction file
#         required_columns = ['question_id', 'predicted_answer']
#         missing_columns = [col for col in required_columns if col not in predictions_df.columns]
#         if missing_columns:
#             return (f"Error: Missing required columns in prediction file: {', '.join(missing_columns)}.",
#                     load_leaderboard())

#         # Validate 'Answer' column in ground truth file
#         if 'Answer' not in ground_truth_df.columns:
#             return "Error: 'Answer' column is missing in the ground truth dataset.", load_leaderboard()
#         merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
#         merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)

#         valid_predictions = merged_df.dropna(subset=['pred_answer'])
#         correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
#         total_predictions = len(merged_df)
#         total_valid_predictions = len(valid_predictions)

#         overall_accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0
#         valid_accuracy = correct_predictions / total_valid_predictions if total_valid_predictions > 0 else 0

#         results = {
#             'model_name': model_name if model_name else "Unknown Model",
#             'overall_accuracy': overall_accuracy,
#             'valid_accuracy': valid_accuracy,
#             'correct_predictions': correct_predictions,
#             'total_questions': total_predictions,
#         }

#         if add_to_leaderboard:
#             update_leaderboard(results)
#             return "Evaluation completed and added to leaderboard.", load_leaderboard()
#         else:
#             return "Evaluation completed but not added to leaderboard.", load_leaderboard()
  
#     except Exception as e:
#         return f"Error during evaluation: {str(e)}", load_leaderboard()

def evaluate_predictions(prediction_file, model_name,Team_name ,add_to_leaderboard):
    try:
        ground_truth_path = hf_hub_download(
            repo_id="SondosMB/ground-truth-dataset",
            filename="ground_truth.csv",
            repo_type="dataset",
            use_auth_token=True
        )
        ground_truth_df = pd.read_csv(ground_truth_path)
    except FileNotFoundError:
        return "Ground truth file not found in the dataset repository.", load_leaderboard()
    except Exception as e:
        return f"Error loading ground truth: {e}", load_leaderboard()

    if not prediction_file:
        return "Prediction file not uploaded.", load_leaderboard()

    try:
        #load prediction file
        predictions_df = pd.read_csv(prediction_file.name)
        # Validate required columns in prediction file
        required_columns = ['question_id', 'predicted_answer']
        missing_columns = [col for col in required_columns if col not in predictions_df.columns]
        if missing_columns:
            return (f"Error: Missing required columns in prediction file: {', '.join(missing_columns)}.",
                    load_leaderboard())

        # Validate 'Answer' column in ground truth file
        if 'Answer' not in ground_truth_df.columns:
            return "Error: 'Answer' column is missing in the ground truth dataset.", load_leaderboard()
        merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
        merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)

        valid_predictions = merged_df.dropna(subset=['pred_answer'])
        correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
        total_predictions = len(merged_df)

        overall_accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0

        results = {
            'model_name': model_name if model_name else "Unknown Model",
            'overall_accuracy': overall_accuracy,
            'correct_predictions': correct_predictions,
            'total_questions': total_predictions,
            'Team_name': Team_name if Team_name else "Unknown Team",
        }

        if add_to_leaderboard:
            update_leaderboard(results)
            return "Evaluation completed and added to leaderboard.", load_leaderboard()
        else:
            return "Evaluation completed but not added to leaderboard.", load_leaderboard()
  
    except Exception as e:
        return f"Error during evaluation: {str(e)}", load_leaderboard()
initialize_leaderboard_file()



def evaluate_predictions_pro(prediction_file, model_name,Team_name ,add_to_leaderboard):
    try:
        ground_truth_path = hf_hub_download(
            repo_id="SondosMB/ground-truth-dataset",
            filename="ground_truth.csv",
            repo_type="dataset",
            use_auth_token=True
        )
        ground_truth_df = pd.read_csv(ground_truth_path)
    except FileNotFoundError:
        return "Ground truth file not found in the dataset repository.", load_leaderboard_pro()
    except Exception as e:
        return f"Error loading ground truth: {e}", load_leaderboard_pro()

    if not prediction_file:
        return "Prediction file not uploaded.", load_leaderboard_pro()

    try:
        #load prediction file
        predictions_df = pd.read_csv(prediction_file.name)
        # Validate required columns in prediction file
        required_columns = ['question_id', 'predicted_answer']
        missing_columns = [col for col in required_columns if col not in predictions_df.columns]
        if missing_columns:
            return (f"Error: Missing required columns in prediction file: {', '.join(missing_columns)}.",
                    load_leaderboard())

        # Validate 'Answer' column in ground truth file
        if 'Answer' not in ground_truth_df.columns:
            return "Error: 'Answer' column is missing in the ground truth dataset.", load_leaderboard_pro()
        merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
        merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)

        valid_predictions = merged_df.dropna(subset=['pred_answer'])
        correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
        total_predictions = len(merged_df)

        overall_accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0

        results = {
            'model_name': model_name if model_name else "Unknown Model",
            'overall_accuracy': overall_accuracy,
            'correct_predictions': correct_predictions,
            'total_questions': total_predictions,
            'Team_name': Team_name if Team_name else "Unknown Team",
        }

        if add_to_leaderboard:
            update_leaderboard_pro(results)
            return "Evaluation completed and added to leaderboard.", load_leaderboard_pro()
        else:
            return "Evaluation completed but not added to leaderboard.", load_leaderboard_pro()
  
    except Exception as e:
        return f"Error during evaluation: {str(e)}", load_leaderboard_pro()
initialize_leaderboard_file()


# Function to set default mode
# Function to set default mode
import gradio as gr
# # Custom CSS to match website style
# # Define CSS to match a modern, professional design
# # Define enhanced CSS for the entire layout

css_tech_theme = """
body {
    font-family: 'Roboto', sans-serif;
    background-color: #f4f6fa;
    color: #333333;
    margin: 0;
    padding: 0;
}

/* Header Styling */
header {
    text-align: center;
    padding: 60px 20px;
    background: linear-gradient(135deg, #6a1b9a, #64b5f6);
    color: #ffffff;
    border-radius: 12px;
    margin-bottom: 30px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

header h1 {
    font-size: 3.5em;
    font-weight: bold;
    margin-bottom: 10px;
}

header h2 {
    font-size: 2em;
    margin-bottom: 15px;
}

header p {
    font-size: 1em;
    line-height: 1.8;
}

.header-buttons {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 20px;
}

.header-buttons a {
    text-decoration: none;
    font-size: 1.5em;
    padding: 15px 30px;
    border-radius: 30px;
    font-weight: bold;
    background: #ffffff;
    color: #6a1b9a;
    transition: transform 0.3s, background 0.3s;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.header-buttons a:hover {
    background: #64b5f6;
    color: #ffffff;
    transform: scale(1.05);
}

/* Pre-Tabs Section */



#pre-tabs{
    text-align: left !important;
    color:#6a1b9a
}

#pre-tabs h2 {
    font-size: 3em
    font-color:#6a1b9a
    margin-bottom: 15px;
}

#pre-tabs p {
    color: #555555;
    line-height: 1.5;
    font-size: 1.5em
}

/* Tabs Section */
.tabs {
    margin: 0 auto;
    padding: 20px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    /* max-width: 1300px; /* change 1 */ */
}

/* Post-Tabs Section */
.post-tabs {
    text-align: center;
    padding: 40px 20px;
    background: linear-gradient(135deg, #64b5f6, #6a1b9a);
    color: #ffffff;
    border-radius: 12px;
    margin-top: 30px;
}

.post-tabs h2 {
color: blue;
    font-size: 3.4em;
    margin-bottom: 15px;
}

.post-tabs p {
    font-size: 2em;
    line-height: 1.8;
    margin-bottom: 20px;
}

.post-tabs a {
    text-decoration: none;
    font-size: 1.1em;
    padding: 15px 30px;
    border-radius: 30px;
    font-weight: bold;
    background: #ffffff;
    color: #6a1b9a;
    transition: transform 0.3s, background 0.3s;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.post-tabs a:hover {
    background: #6a1b9a;
    color: #ffffff;
    transform: scale(1.05);
}

/* Footer */
#custom-footer {
    background: linear-gradient(135deg, #6a1b9a, #8e44ad);
    color: #ffffff;
    text-align: center;
    padding: 40px 20px;
    margin-top: 30px;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

#custom-footer h2 {
    font-size: 1.5em;
    margin-bottom: 15px;
}

#custom-footer p {
    font-size: 0.8em;
    line-height: 1.6;
    margin-bottom: 20px;
}
/* Link Styling */
.social-links {
    display: flex;
    justify-content: center;
    gap: 15px; /* Space between links */
}

.social-link {
    display: inline-block;
    text-decoration: none;
    color: #ffffff;
    background-color: #6a1b9a; /* Purple button background */
    padding: 10px 20px;
    border-radius: 30px;
    font-size: 16px;
    font-weight: bold;
    transition: all 0.3s ease;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.social-link:hover {
    background-color: #8c52d3; /* Darker shade on hover */
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
    transform: translateY(-2px);
}

.social-link:active {
    transform: translateY(1px);
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}


#submission-buttons {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 20px;
}



/* Buttons Styling */
#submission-buttons button {
    padding: 12px 25px;
    font-size: 1.1em;
    color: #ffffff;
    background: #6a1b9a;
    border: none;
    border-radius: 30px;
    cursor: pointer;
    font-weight: bold;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
#submission-buttons button:hover {
    background: #8c52d3; /* Slightly lighter purple */
    transform: scale(1.05);
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
}
#submission-buttons button:active {
    background: #5e1287; /* Darker purple */
    transform: scale(0.98);
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}
.gradio-container {
    padding-bottom: 0 !important;
    margin-bottom: 0 !important;
}



/* overview */
#overview {
    border-radius: 12px;
}
#overview h2 {
    font-size: 2.5em;
    color: #6a1b9a  !important;
    text-align: left;
    margin-bottom: 10px;
}
#overview h3 {
    font-size: 2.2em;
    color: #6a1b9a  !important;
    text-align: left;
    margin-bottom: 20px;
}
#overview p {
    font-size: 1.2em;
    color: #333333;
    line-height: 1.8;
    margin-bottom: 15px;
}
#overview ul, #Overview ol {
    font-size: 1.2em;
    color: #555555;
    margin: 20px 0;
    padding-left: 40px;
}
#overview ul li, #Overview ol li {
    margin-bottom: 10px;
    font-size: 1.2em;
}
#overview ul li::marker, Overview ol li::marker {
    color: #6a1b9a;
    font-size: 1.2em;
}
overview a {
    color: #6a1b9a;
    text-decoration: underline;
}
overview a:hover {
    color: #8c52d3;
}

footer {
        margin-top: 0; /* Reduce space above the footer */
        padding: 10px; /* Optional: Adjust padding inside the footer */
    }

"""

# Create the Gradio Interface

with gr.Blocks(css=css_tech_theme) as demo:
    # Header Section
    gr.Markdown("""
    <header>
        <h1>πŸ† Mobile-MMLU Challenge</h1>
        <h2>πŸš€ Pushing the Limits of Mobile LLMs</h2>
    </header>
    """)
#     # Pre-Tabs Section
    gr.Markdown("""
    <section class="pre-tabs">
    <h2 style="color: #6a1b9a; text-align: center; font-size: 2.5em; margin-bottom: 15px;">🌟 Why Participate? 🌟</h2>
    <p style="font-size: 1.4em; text-align: center; color: #555555; line-height: 1.8; margin-bottom: 20px;">
        The <strong>Mobile-MMLU Benchmark Competition</strong> provides an exceptional platform to showcase your 
        skills in mobile AI. Compete with innovators worldwide, drive technological advancements, and contribute 
        to shaping the future of mobile intelligence.
    </p>
    </section>""", elem_id="pre-tabs")

     # gr.Markdown("""
     # <section class="pre-tabs">
     # <h2 style="color: #6a1b9a; text-align: center; font-size: 2.5em; margin-bottom: 15px;">🌟 Why Participate? 🌟</h2>
     # <p style="font-size: 1.4em; text-align: center; color: #555555; line-height: 1.8; margin-bottom: 20px;">
     #    The <strong>Mobile-MMLU Benchmark Competition</strong> provides an exceptional platform to showcase your 
     #    skills in mobile AI. Compete with innovators worldwide, drive technological advancements, and contribute 
     #    to shaping the future of mobile intelligence.
     # </p>
     # </section>""", elem_id="pre-tabs")

    
 # Tabs Section
    with gr.Tabs(elem_id="tabs"):
        # Overview Tab
        with gr.TabItem("πŸ“– Overview"):
            gr.Markdown( """
        <div class="tabs">
            <h2 style="color: #6a1b9a; text-align: center;">About the Competition</h2>
            <p>The <strong>Mobile-MMLU Benchmark Competition</strong> is a premier challenge designed to evaluate and advance mobile-optimized Large Language Models (LLMs). This competition is an excellent opportunity to showcase your model's ability to handle real-world scenarios and excel in mobile intelligence.</p>
            <p>With a dataset spanning <strong>80 distinct fields</strong> and featuring <strong>16,186 questions</strong>, the competition emphasizes practical applications, from education and healthcare to technology and daily life.</p>
            <h3 style="color: #8e44ad;">Why Compete?</h3>
            <p>Participating in this competition allows you to:</p>
            <ul>
                <li>🌟 Showcase your expertise in developing and optimizing LLMs for mobile platforms.</li>
                <li>πŸš€ Benchmark your model’s performance against others in a highly competitive environment.</li>
                <li>πŸ“ˆ Contribute to advancements in mobile AI, shaping the future of user-centric AI systems.</li>
            </ul>
            <h3 style="color: #6a1b9a;">How It Works</h3>
            <ol>
                <li>1️⃣ <strong>Download the Dataset:</strong> Access the dataset and detailed instructions on the <a href="https://github.com/VILA-Lab/Mobile-MMLU" target="_blank">GitHub page</a>. Follow the steps to ensure your environment is set up correctly.</li>
                <li>2️⃣ <strong>Generate Predictions:</strong> Use the provided script in the GitHub repository to generate answers. Ensure the output file matches the format in the github </li>
                <li>3️⃣ <strong>Submit Predictions:</strong> Upload your CSV file to the <strong>Submission Page</strong> on this platform.</li>
                <li>4️⃣ <strong>Evaluation:</strong> Your submission will be scored based on accuracy. The results will include overall accuracy metric.</li>
                <li>5️⃣ <strong>Leaderboard:</strong> Optionally, add your results to the real-time leaderboard to compare your model's performance with others.</li>
            </ol>
            <h3 style="color: #8e44ad;">Resources</h3>
            <ul>
                <li>πŸ“‚ <a href="https://github.com/VILA-Lab/Mobile-MMLU" target="_blank">GitHub Repository</a>: Contains the dataset, scripts, and detailed instructions.</li>
                <li>πŸ“Š <a href="https://huggingface.co/datasets/aidar-myrzakhan/Mobile-MMLU" target="_blank">Dataset Link</a>: Direct access to the competition dataset.</li>
                <li>❓ <a href="https://github.com/VILA-Lab/Mobile-MMLU" target="_blank">Support Page</a>: Use this for queries or issues during participation.</li>
            </ul>
        </div>
        """,elem_id="overview")
            
        with gr.TabItem("πŸ“€ Submission"):
            gr.Markdown("""
            <div class="submission-section" style="border: 3px solid #6a1b9a; padding: 20px; border-radius: 12px; box-shadow: 0 4px 10px rgba(106, 27, 154, 0.2);">
            <h2 style="color: #6a1b9a; text-align: center;">Submit Your Predictions</h2>
            <p style="font-size: 1.2em; color: #333; text-align: center;">Upload your prediction file and provide your model name to evaluate and optionally submit your results to the leaderboard.</p>
            </div>
            """)
            with gr.Row(elem_id="submission-fields"):
                file_input = gr.File(label="πŸ“‚ Upload Prediction CSV", file_types=[".csv"], interactive=True,scale=1, min_width=12000)
                model_name_input = gr.Textbox(label="🏷️ Model Name", placeholder="Enter your model name",scale=1,  min_width=800)
                Team_name_input = gr.Textbox(label="🏷️ Team Name", placeholder="Enter your Team name",scale=1,  min_width=800)
        
            with gr.Row(elem_id="submission-results"):
                overall_accuracy_display = gr.Number(label="πŸ“Š Overall Accuracy (%)", interactive=False,scale=1,min_width=1200)
        
            with gr.Row(elem_id="submission-buttons"):
                eval_button = gr.Button("πŸ“ˆ Evaluate",scale=1,min_width=1200)
                submit_button = gr.Button("πŸ“€ Prove and Submit to Leaderboard", elem_id="evaluation-status", visible=False,scale=1,min_width=1200)
                eval_status = gr.Textbox(label="πŸ› οΈ Evaluation Status", interactive=False,scale=1,min_width=1200)


        with gr.TabItem("πŸ“€ Submission-Pro"):
            gr.Markdown("""
            <div class="submission-section" style="border: 3px solid #6a1b9a; padding: 20px; border-radius: 12px; box-shadow: 0 4px 10px rgba(106, 27, 154, 0.2);">
            <h2 style="color: #6a1b9a; text-align: center;">Submit Your Predictions</h2>
            <p style="font-size: 1.2em; color: #333; text-align: center;">Upload your prediction file and provide your model name to evaluate and optionally submit your results to the leaderboard.</p>
            </div>
            """)
            with gr.Row(elem_id="submission-fields"):
                file_input = gr.File(label="πŸ“‚ Upload Prediction CSV for Mobile-MMLU-Pro", file_types=[".csv"], interactive=True,scale=1, min_width=12000)
                model_name_input = gr.Textbox(label="🏷️ Model Name", placeholder="Enter your model name",scale=1,  min_width=800)
                Team_name_input = gr.Textbox(label="🏷️ Team Name", placeholder="Enter your Team name",scale=1,  min_width=800)
        
            with gr.Row(elem_id="submission-results"):
                overall_accuracy_display = gr.Number(label="πŸ“Š Overall Accuracy (%)", interactive=False,scale=1,min_width=1200)
        
            with gr.Row(elem_id="submission-buttons"):
                eval_button_pro = gr.Button("πŸ“ˆ Evaluate",scale=1,min_width=1200)
                submit_button_pro = gr.Button("πŸ“€ Prove and Submit to Leaderboard", elem_id="evaluation-status", visible=False,scale=1,min_width=1200)
                eval_status = gr.Textbox(label="πŸ› οΈ Evaluation Status", interactive=False,scale=1,min_width=1200)
        
       

        def handle_evaluation(file, model_name, Team_name):
            if not file:
                return "Error: Please upload a prediction file.", 0, gr.update(visible=False)
            if not model_name or model_name.strip() == "":
                return "Error: Please enter a model name.", 0, gr.update(visible=False)
            if not Team_name or Team_name.strip() == "":
                return "Error: Please enter a Team name.", 0, gr.update(visible=False)    
        
            try:
                # Load predictions file
                predictions_df = pd.read_csv(file.name)
        
                # Validate required columns
                required_columns = ['question_id', 'predicted_answer']
                missing_columns = [col for col in required_columns if col not in predictions_df.columns]
                if missing_columns:
                    return (f"Error: Missing required columns in prediction file: {', '.join(missing_columns)}.",
                            0, gr.update(visible=False))
        
                # Load ground truth
                try:
                    ground_truth_path = hf_hub_download(
                        repo_id="SondosMB/ground-truth-dataset",
                        filename="ground_truth.csv",
                        repo_type="dataset",
                        use_auth_token=True
                    )
                    ground_truth_df = pd.read_csv(ground_truth_path)
                except Exception as e:
                    return f"Error loading ground truth: {e}", 0, gr.update(visible=False)

                # Perform evaluation calculations
                merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
                merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)
        
                valid_predictions = merged_df.dropna(subset=['pred_answer'])
                correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
                total_predictions = len(merged_df)
        
                overall_accuracy = (correct_predictions / total_predictions * 100) if total_predictions > 0 else 0
        
                return "Evaluation completed successfully.", overall_accuracy, gr.update(visible=True)
        
            except Exception as e:
                return f"Error during evaluation: {str(e)}", 0, gr.update(visible=False)

        def handle_evaluation_pro(file, model_name, Team_name):
            if not file:
                return "Error: Please upload a prediction file.", 0, gr.update(visible=False)
            if not model_name or model_name.strip() == "":
                return "Error: Please enter a model name.", 0, gr.update(visible=False)
            if not Team_name or Team_name.strip() == "":
                return "Error: Please enter a Team name.", 0, gr.update(visible=False)    
        
            try:
                # Load predictions file
                predictions_df = pd.read_csv(file.name)
        
                # Validate required columns
                required_columns = ['question_id', 'predicted_answer']
                missing_columns = [col for col in required_columns if col not in predictions_df.columns]
                if missing_columns:
                    return (f"Error: Missing required columns in prediction file: {', '.join(missing_columns)}.",
                            0, gr.update(visible=False))
        
                # Load ground truth
                try:
                    ground_truth_path = hf_hub_download(
                        repo_id="SondosMB/ground-truth-dataset",
                        filename="ground_truth.csv",
                        repo_type="dataset",
                        use_auth_token=True
                    )
                    ground_truth_df = pd.read_csv(ground_truth_path)
                except Exception as e:
                    return f"Error loading ground truth: {e}", 0, gr.update(visible=False)

                # Perform evaluation calculations
                merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
                merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)
        
                valid_predictions = merged_df.dropna(subset=['pred_answer'])
                correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
                total_predictions = len(merged_df)
        
                overall_accuracy = (correct_predictions / total_predictions * 100) if total_predictions > 0 else 0
        
                return "Evaluation completed successfully.", overall_accuracy, gr.update(visible=True)
        
            except Exception as e:
                return f"Error during evaluation: {str(e)}", 0, gr.update(visible=False)        


        
        def handle_submission(file, model_name,Team_name):
            # Handle leaderboard submission
            status, _ = evaluate_predictions(file, model_name,Team_name, add_to_leaderboard=True)
            return f"Submission to leaderboard completed: {status}"

        def handle_submission_pro(file, model_name,Team_name):
            # Handle leaderboard submission
            status, _ = evaluate_predictions_pro(file, model_name,Team_name, add_to_leaderboard=True)
            return f"Submission to leaderboard completed: {status}"
            
        
        # Connect button clicks to the functions
        eval_button.click(
            handle_evaluation,
            inputs=[file_input, model_name_input,Team_name_input],
            outputs=[eval_status, overall_accuracy_display, submit_button],
        )

        eval_button_pro.click(
            handle_evaluation_pro,
            inputs=[file_input, model_name_input,Team_name_input],
            outputs=[eval_status, overall_accuracy_display, submit_button_pro],
        )

        submit_button_pro.click(
            handle_submission_pro,
            inputs=[file_input, model_name_input,Team_name_input],
            outputs=[eval_status],
        )
        
        submit_button.click(
            handle_submission,
            inputs=[file_input, model_name_input,Team_name_input],
            outputs=[eval_status],
        )



        with gr.TabItem("πŸ… Leaderboard"):
            leaderboard_table = gr.Dataframe(
                value=load_leaderboard(),
                label="Leaderboard",
                interactive=False,
                wrap=True,
            )
            refresh_button = gr.Button("Refresh Leaderboard")
            refresh_button.click(
                lambda: load_leaderboard(),
                inputs=[],
                outputs=[leaderboard_table],
            )
        with gr.TabItem("πŸ… Leaderboard-pro"):
            leaderboard_table = gr.Dataframe(
                value=load_leaderboard,
                label="Leaderboard",
                interactive=False,
                wrap=True,
            )
            refresh_button = gr.Button("Refresh Leaderboard")
            refresh_button.click(
                lambda: load_leaderboard,
                inputs=[],
                outputs=[leaderboard_table],
            )    

     # Post-Tabs Section
    # gr.Markdown("""
    # <section class="post-tabs">
    #     <h2>Ready to Compete?</h2>
    #     <h3>
    #         Submit your predictions today and make your mark in advancing mobile AI technologies. 
    #         Show the world what your model can achieve!
    #     <h3>
    # </section>
    # """)

    # Post-Tabs Section
    gr.Markdown("""
    <section class="post-tabs">
        <h2 style="color: #6a1b9a; text-align: center; font-size: 2.5em; margin-bottom: 15px;">🌟 Ready to Compete? 🌟</h2>
        <p style="font-size: 1.5em; text-align: center; color: #ffffff; line-height: 1.6; margin-bottom: 20px;">
            Don't miss this opportunity to showcase your expertise in mobile AI! Participate in the competition, 
            submit your predictions, and compare your results with the best in the field.
        </p>
    </section>
    """)

    
    with gr.Row():
        with gr.Accordion("πŸ“™ Citation", open=False):
            gr.Textbox(
                    value=CITATION_TEXT, lines=18,
                    label="",elem_id="citation-button",
                    show_copy_button=True)

    # Footer Section
    gr.Markdown("""
    <footer>
        <h2>Stay Connected</h2>
        <p>
            Follow us on social media or contact us for any queries. Let's shape the future of AI together!
        </p>
        <div class="social-links">
        <a href="https://vila-lab.github.io/Mobile_MMLU/" target="_blank" class="social-link">🌐 Website</a>
        <a href="https://github.com/VILA-Lab/Mobile-MMLU">πŸ’» GitHub</a>
    </div>
    </footer>
    """,elem_id="custom-footer")

demo.launch()