File size: 38,112 Bytes
f417250
 
a1ddac4
f417250
 
23931c3
bbb5601
219886f
 
 
 
 
 
 
 
a1840bf
219886f
d361e71
f417250
ed52286
 
f845d60
 
36141d4
f845d60
033e3d2
 
 
b66f230
f417250
 
b35e51f
 
 
 
 
76b7a19
b35e51f
 
 
 
 
 
b66f230
517ba24
49d6897
d361e71
 
 
 
 
 
 
 
 
 
 
 
 
bc51cbc
03acd37
 
d361e71
bc51cbc
b66f230
d361e71
 
 
 
 
6d1eaa5
 
d361e71
2a4d35b
6268f11
f417250
b35e51f
b66f230
b35e51f
2025339
 
a1ddac4
2025339
41fc211
b35e51f
 
 
f417250
517ba24
80fec9e
36141d4
f845d60
 
4a87adf
b66f230
219886f
 
 
 
 
 
 
272c73f
 
 
219886f
55d31fc
95cfba3
d989cb4
 
 
 
 
 
 
272c73f
 
 
d989cb4
97092f5
0fc2abb
 
f845d60
 
 
 
 
 
 
 
272c73f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219886f
 
f845d60
 
219886f
 
272c73f
 
 
 
219886f
f417250
1c921ec
 
 
 
 
 
 
 
 
 
c355da5
 
1c921ec
f417250
b66f230
 
 
ec6e1e5
 
8f7d195
 
 
 
 
 
 
 
1c921ec
ec6e1e5
219886f
 
 
 
 
 
 
272c73f
 
 
8f7d195
 
219886f
1c921ec
ec6e1e5
1c921ec
219886f
f417250
 
23931c3
97092f5
 
 
219886f
 
 
 
 
 
 
 
272c73f
 
 
219886f
23931c3
 
 
 
219886f
 
 
 
23931c3
8c3991f
a6ec86d
11fbc90
 
 
 
 
 
 
 
8c3991f
3eee636
a6ec86d
3eee636
 
 
 
 
 
 
 
 
6bae7e8
 
 
 
288544e
 
 
 
 
6bae7e8
 
 
10151dc
bc7f740
1c2b941
 
 
31ae9dc
 
 
8c3991f
 
 
 
 
 
3eee636
 
 
bc7f740
1c2b941
6bae7e8
1c2b941
bc7f740
8c3991f
31ae9dc
 
 
 
8c3991f
 
 
 
10151dc
3eee636
bc7f740
8f7d195
 
 
 
 
 
 
 
 
bc7f740
8f7d195
 
1c2b941
31ae9dc
8c3991f
 
3eee636
db6d5bf
23931c3
 
b9a81c7
23931c3
 
 
 
 
49d6897
f0843f2
291b241
 
 
 
 
f0843f2
291b241
 
 
 
49d6897
136803a
 
 
ca14598
 
 
ed52286
 
 
ca14598
 
ed52286
 
 
 
 
ca14598
ed52286
 
ca14598
ed52286
 
 
 
 
 
 
 
 
 
ca14598
136803a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed52286
 
 
bbb5601
ec6e1e5
8f7d195
 
 
 
 
 
 
 
1c921ec
 
 
8f7d195
 
1c921ec
 
 
 
bbb5601
2c5fd3f
ac4b2b4
 
 
 
25b4fc2
 
8f93450
8c07af8
 
25b4fc2
 
ac4b2b4
 
433f7b8
236f418
 
 
7c14c59
bce21fb
 
20b8116
 
375e927
 
 
 
8ef5b4f
efb636e
8ef5b4f
efb636e
 
 
 
 
 
 
34f54a1
d4f7e49
 
efb636e
 
ac4b2b4
 
9cba749
 
 
8ef5b4f
 
9cba749
8ef5b4f
34f54a1
 
 
8ef5b4f
9cba749
8ef5b4f
 
 
 
 
 
 
 
fc05bae
8ef5b4f
 
d4f7e49
 
 
 
8ef5b4f
 
 
 
 
 
 
 
 
 
 
 
 
9cba749
 
 
 
 
 
8ef5b4f
9cba749
 
 
 
5212908
9cba749
5212908
136803a
 
ca14598
 
136803a
 
 
 
 
 
ca14598
 
136803a
 
 
ed52286
 
 
 
 
 
136803a
ca14598
136803a
 
 
ca14598
ed52286
 
 
 
136803a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed52286
 
 
 
 
 
 
136803a
 
 
 
 
 
ca14598
 
ed52286
 
 
 
136803a
 
 
 
5212908
 
 
 
 
 
 
 
 
a6ec86d
b5d384e
 
 
 
 
 
5212908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32a069d
 
 
 
 
 
5212908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3eee636
 
 
 
 
 
a6ec86d
5212908
 
a6ec86d
5212908
 
 
 
8f7d195
5212908
 
 
 
3eee636
305114d
1c921ec
5212908
 
 
 
 
a6ec86d
5212908
 
3eee636
 
 
 
a6ec86d
3eee636
 
8c3991f
5212908
 
 
8c3991f
5212908
a6ec86d
 
 
 
 
23931c3
a6ec86d
 
 
 
 
 
 
 
 
 
 
 
b5d384e
 
 
 
 
a6ec86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5212908
a6ec86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5212908
a6ec86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5212908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26a2ced
49d6897
5212908
 
 
6d1eaa5
272c73f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34e486a
 
 
 
5212908
 
 
6a03b6f
5212908
 
 
 
 
 
 
d10a698
5212908
 
 
 
 
 
 
 
272c73f
 
 
 
5212908
d10a698
5212908
2c5fd3f
5212908
 
 
 
23931c3
5212908
f0843f2
291b241
f0843f2
 
291b241
 
5212908
 
 
 
 
 
 
272c73f
 
 
 
5212908
8f7d195
5212908
a6ec86d
 
5212908
 
291b241
f0843f2
291b241
f0843f2
 
291b241
5212908
23931c3
5212908
2635a46
 
 
 
 
 
5212908
 
2635a46
 
 
 
 
 
5212908
23931c3
5212908
 
 
 
 
 
 
 
272c73f
 
 
 
5212908
 
a1840bf
 
 
5212908
 
 
 
 
8f7d195
a6ec86d
 
5212908
 
 
af06901
5212908
2c5fd3f
5212908
 
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
import os

import regex as re
import gradio as gr
from gradio.themes.utils.sizes import text_md
from gradio_modal import Modal

from content import (
    HEADER_MARKDOWN,
    LEADERBOARD_TAB_TITLE_MARKDOWN,
    SUBMISSION_TAB_TITLE_MARKDOWN,
    MODAL_SUBMIT_MARKDOWN,
    SUBMISSION_DETAILS_MARKDOWN,
    RANKING_AFTER_SUBMISSION_MARKDOWN,
    MORE_DETAILS_MARKDOWN,
    ABOUT_MARKDOWN,
)
from server import LeaderboardServer, xmlAndMarkdownEscape, xmlQuoteAttr, api, requests

HF_SPACE_TOKEN = os.environ["HF_SPACE_TOKEN"]
HF_SPACE_ID = os.environ["HF_SPACE_ID"]
# For testing purpose
HF_DISABLE_SUBMIT = bool(int(os.environ.get("HF_DISABLE_SUBMIT", "0")))
from server import HF_FAKE_TOURNAMENT

from huggingface_hub import dump_environment_info
dump_environment_info()

leaderboard_server = LeaderboardServer()


SUBMISSION_INPUTS = dict.fromkeys((
    "team_name",
    "model_name",
    "model_type",
    "parameters",
    "input_length",
    "precision",
    "description",
    "link_to_model",
    "submission_file",
)).keys()

def on_submit_pressed():
    return gr.update(value='Processing submission…', interactive=False)

def validate_url(url):
    try:
        response = requests.get(url, timeout=5)
    except requests.exceptions.ConnectTimeout:
        pass
    except requests.exceptions.ConnectionError as e:
        return str(e).rsplit(":", 1)[-1].strip()
    except Exception as e:
        return str(e)
    else:
        if response.status_code != 200:
            return f'Failed to get <{url}>. Status code: {response.status_code}'

def validate_submission_inputs(**inputs):
    if any(key for key, value in inputs.items() if key != "description" and value in (None, "")):
        raise ValueError('Please fill in all fields (only the description field is optional)')
    
    if not os.path.exists(inputs["submission_file"]):
        raise ValueError('File does not exist')
    
    error_msg = validate_url(inputs["link_to_model"])
    if error_msg:
        raise ValueError(f'Link to the model is not valid: {error_msg}')
    
    if not inputs["parameters"] > 0:
        raise ValueError('Attribute `Parameters (B)` should be greater than zero')
    
    if not (inputs["input_length"] > 0 and inputs["input_length"] == int(inputs["input_length"])):
        raise ValueError('Attribute `Input length (# tokens)` should be greater than zero and integer type')

def process_submission(*inputs):
    try:
        inputs = dict(zip(SUBMISSION_INPUTS, inputs))
        for key in inputs:
            if key in ("team_name", "model_name"):
                inputs[key] = re.sub(r"""\s+""", " ", inputs[key]).strip()
            elif key in ("description", "link_to_model"):
                inputs[key] = inputs[key].strip()
        validate_submission_inputs(**inputs)
        metadata = SUBMISSION_INPUTS - {"submission_file"}
        metadata = {key: inputs[key] for key in metadata}

        gr.Info('Submission valid, going to queue for the tournament…')

        pre_submit = leaderboard_server.prepare_model_for_submission(inputs["submission_file"], metadata)
        if HF_FAKE_TOURNAMENT:
            pre_submit = None
    except ValueError as err:
        gr.Warning(str(err))
        return (
            gr.update(value='Pre-submit model', visible=True, interactive=True),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
        )
    except Exception as err:
        gr.Warning(str(err), duration=None)
        return (
            gr.update(value='Pre-submit model', visible=True, interactive=True),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
        )
    
    gr.Info('Tournament finished!', duration=5)
    gr.Info('You can see the results of your model below.', duration=15)
    
    if HF_DISABLE_SUBMIT:
        submit_prompt = gr.update(visible=False)
        submission_btn_yes = gr.update(visible=False)
    else:
        submit_prompt = gr.update(visible=True)
        submission_btn_yes = gr.update(interactive=True, visible=True)
    
    pre_submit_leaderboard_table = gr.update(
        value=leaderboard_server.get_leaderboard(pre_submit=pre_submit, category=leaderboard_server.TASKS_CATEGORY_OVERALL_DETAILS),
        visible=True,
    )
    
    pre_submit_leaderboard_table_csv = gr.update(
        value=leaderboard_server.get_leaderboard_csv(pre_submit=pre_submit, category=leaderboard_server.TASKS_CATEGORY_OVERALL_DETAILS),
        visible=True,
    )
    
    pre_submit_model_tournament_results_table = gr.update(
        value=leaderboard_server.get_model_tournament_table(pre_submit.submission_id, leaderboard_server.TASKS_CATEGORY_OVERALL_DETAILS, pre_submit=pre_submit),
        visible=True,
    )
    
    pre_submit_model_tournament_results_table_csv = gr.update(
        value=leaderboard_server.get_model_tournament_table_csv(pre_submit.submission_id, leaderboard_server.TASKS_CATEGORY_OVERALL_DETAILS, pre_submit=pre_submit),
        visible=True,
    )
    
    return (
        gr.update(visible=False),
        submit_prompt,
        submission_btn_yes,
        gr.update(interactive=True, visible=True),
        gr.update(visible=True),
        pre_submit_leaderboard_table,
        pre_submit_leaderboard_table_csv,
        pre_submit_model_tournament_results_table,
        pre_submit_model_tournament_results_table_csv,
    )

def get_submission_ids_and_titles():
    with leaderboard_server.var_lock.ro:
        submission_ids_and_titles = [
            (
                leaderboard_server.submission_id_to_model_title[submission_id],
                submission_id,
            )
            for submission_id in leaderboard_server.submission_ids
        ]
    
    submission_ids_and_titles.sort(key=lambda x: x[0].lower())
    
    return submission_ids_and_titles

def submit_results():
    leaderboard_server.save_pre_submit()
    gr.Info('Submission successful!')
    
    with leaderboard_server.var_lock.ro:
        leaderboard = gr.update(
            value=leaderboard_server.get_leaderboard(category=leaderboard_server.TASKS_CATEGORY_OVERALL),
            visible=True,
        )
        leaderboard_csv = gr.update(
            value=leaderboard_server.get_leaderboard_csv(category=leaderboard_server.TASKS_CATEGORY_OVERALL),
            visible=True,
        )
        submission_ids_and_titles = get_submission_ids_and_titles()
    
    return (
        gr.update(value='Pre-submit model', visible=True, interactive=True),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        leaderboard,
        leaderboard_csv,
        gr.update(visible=False),
        gr.update(choices=submission_ids_and_titles),
        gr.update(value=leaderboard_server.TASKS_CATEGORY_OVERALL),
        gr.update(choices=submission_ids_and_titles),
    )


def erase_pre_submit():
    with leaderboard_server.pre_submit_lock:
        if leaderboard_server.pre_submit:
            leaderboard_server.pre_submit = None  # NOTE: Is it safe? How to confirm that `submission_id` is equal?
    return (
        gr.update(value='Pre-submit model', visible=True, interactive=True),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
    )


def fetch_model_detail(submission_id):
    metadata = leaderboard_server.get_model_detail(submission_id)
    return (
        gr.update(value=metadata['description'], visible=True),
        gr.update(value=metadata['link_to_model'], visible=True)
    )

def fetch_model_tournament_results_table(submission_id, category):
    if submission_id == None or category == None:
        return gr.update(
            visible=False,
        )
    else:
        return gr.update(
            value=leaderboard_server.get_model_tournament_table(submission_id, category),
            visible=True,
        )

def fetch_model_tournament_results_table_csv(submission_id, category):
    if submission_id == None or category == None:
        return gr.update(
            visible=False,
        )
    else:
        return gr.update(
            value=leaderboard_server.get_model_tournament_table_csv(submission_id, category),
            visible=True,
        )

def create_task_abbreviation_legend_table(category):
    task_abbreviation_legend_body = []
    abbreviation2name = leaderboard_server.CATEGORY_TO_TASK_ABBREVIATION_TO_DETAILS[category]
    for abbr, name, url in abbreviation2name.values():
        task_abbreviation_legend_body.append([
            xmlAndMarkdownEscape(abbr),
            xmlAndMarkdownEscape(name),
            f'<a href={xmlQuoteAttr(url)}>{xmlAndMarkdownEscape(url)}</a>',
        ])
    
    return task_abbreviation_legend_body

def change_leaderboard_category(category, selected_submission_id):
    if category == leaderboard_server.TASKS_CATEGORY_OVERALL:
        task_abbreviation_legend = gr.update(
            visible=False,
        )
        tournament_results_title = gr.update(
            visible=False,
        )
        tournament_results_dropdown = gr.update(
            visible=False,
        )
        model_tournament_results_table = gr.update(
            visible=False,
        )
        model_tournament_results_table_csv = gr.update(
            visible=False,
        )
    else:
        task_abbreviation_legend = gr.update(
            value=create_task_abbreviation_legend_table(category),
            visible=True,
        )
        
        tournament_results_title = gr.update(
            visible=True,
        )
        
        tournament_results_dropdown = gr.update(
            visible=True,
        )
        
        model_tournament_results_table = fetch_model_tournament_results_table(selected_submission_id, category)
        model_tournament_results_table_csv = fetch_model_tournament_results_table_csv(selected_submission_id, category)
    
    leaderboard = gr.update(
        value=leaderboard_server.get_leaderboard(category=category),
        visible=True,
    )
    leaderboard_csv = gr.update(
        value=leaderboard_server.get_leaderboard_csv(category=category),
        visible=True,
    )
    
    return (
        leaderboard,
        leaderboard_csv,
        task_abbreviation_legend,
        tournament_results_title,
        tournament_results_dropdown,
        model_tournament_results_table,
        model_tournament_results_table_csv,
    )

def show_modal():
    gr.Info('You are going to submit your model.', duration=5)  # It is used to scroll up
    return gr.update(visible=True)


def hide_modal():
    return gr.update(visible=False)

def disable_submit_buttons():
    return (
        gr.update(interactive=False),
        gr.update(interactive=False),
    )

def enable_submit_buttons():
    return (
        gr.update(interactive=True),
        gr.update(interactive=True),
    )

def results_dataset_integrity_check():
    leaderboard_server.results_dataset_integrity_check(solve=True)

def update_results_dataset_integrity_solving_progress():
    progress = leaderboard_server.tournament_results_integrity_solving_progress * 100
    
    
    if leaderboard_server.tournament_results_corrupted:
        results_dataset_integrity_solving_progress = gr.update(
            value=f"Tournament results is preparing, please wait… {progress:.0f}% done"
        )
        
        results_dataset_integrity_restart_btn = gr.update(
            interactive=False,
            visible=False,
        )
    else:
        results_dataset_integrity_solving_progress = gr.update(
            value="Tournament results is prepared, please restart this space with the button showed below."
        )
        
        results_dataset_integrity_restart_btn = gr.update(
            interactive=True,
            visible=True,
        )
    
    return (
        results_dataset_integrity_solving_progress,
        results_dataset_integrity_restart_btn,
    )

def on_tournament_results_corrupted():
    if leaderboard_server.tournament_results_corrupted and not leaderboard_server.tournament_results_integrity_solving:
        results_dataset_integrity_check_btn = gr.update(
            interactive=True,
            visible=True,
        )
        results_dataset_integrity_solving_progress = gr.update(
            visible=False,
        )
    else:
        results_dataset_integrity_check_btn = gr.update(
            interactive=False,
            visible=False,
        )
        results_dataset_integrity_solving_progress = gr.update(
            visible=True,
        )
    
    return (
        results_dataset_integrity_check_btn,
        results_dataset_integrity_solving_progress,
    )

def restart_space():
    api.restart_space(repo_id=HF_SPACE_ID, token=HF_SPACE_TOKEN)

def on_application_load():
    with leaderboard_server.var_lock.ro:
        leaderboard = gr.update(
            value=leaderboard_server.get_leaderboard(category=leaderboard_server.TASKS_CATEGORY_OVERALL),
            visible=True,
        )
        leaderboard_csv = gr.update(
            value=leaderboard_server.get_leaderboard_csv(category=leaderboard_server.TASKS_CATEGORY_OVERALL),
            visible=True,
        )
        submission_ids_and_titles = get_submission_ids_and_titles()
    
    return (
        leaderboard,
        leaderboard_csv,
        gr.update(choices=submission_ids_and_titles),
        gr.update(value=leaderboard_server.TASKS_CATEGORY_OVERALL),
        gr.update(choices=submission_ids_and_titles),
    )


custom_css = """

footer {visibility: hidden}

tr {
  background-color: var(--table-even-background-fill);
  font-family: "IBM Plex Mono";
}

tr.row_odd {
  background-color: var(--table-odd-background-fill);
}

.leaderboard-table td:first-child p, .leaderboard-table-model-details td:first-child p {
  margin: 0px;
}

.leaderboard-table th:nth-child(5), .leaderboard-table td:nth-child(5) {
  border-right-width: 2px;
  border-right-color: var(--border-color-primary);
}

.leaderboard-table td:nth-child(5) p {
  font-weight: bolder;
}

.leaderboard-table tr[model_title]:hover::after, .leaderboard-table-model-details tr[model_title]:hover::after {
  content: attr(model_title);
  position: fixed;
  background-color: rgba(50, 50, 50, 0.9);
  color: white;
  padding: 5px;
  border-radius: 5px;
  white-space: nowrap;
  z-index: 10;
  pointer-events: none;
  left: var(--table-rect-left, 0px);
  top: var(--row-rect-bottom, 0px);
  transform: translateY(0px);
}

"""

custom_js = """
<script>

function addTitleForEachRowOfLeaderboardTable(){
    const tables = document.querySelectorAll('.leaderboard-table table, .leaderboard-table-model-details table');
    
    tables.forEach(table => {
        const rect = table.getBoundingClientRect();
        table.style.setProperty('--table-rect-left', `${rect.left}px`);
        
        const rows = table.querySelectorAll('tr');
        
        if (table.scrollLeft > 10) {
            rows.forEach(row => {
                // Find the first cell in the row that contains a link
                const firstCellLink = row.querySelector('td a');
                
                if (firstCellLink) {
                    // Get the value of the title attribute from the first link
                    const titleText = firstCellLink.getAttribute('title');
                    
                    // Set the model_title attribute for the row
                    row.setAttribute('model_title', titleText);
                    
                    // Set bottom position
                    const rect = row.getBoundingClientRect();
                    row.style.setProperty('--row-rect-bottom', `${rect.bottom}px`);
                }
            });
        } else {
            rows.forEach(row => {
                // Find the first cell in the row that contains a link
                const firstCellLink = row.querySelector('td a');
                
                if (firstCellLink) {
                    // Get the value of the title attribute from the first link
                    const titleText = firstCellLink.getAttribute('title');
                    
                    // Remove the model_title attribute for the row
                    row.removeAttribute('model_title');
                }
            });
        }
    });
}

const intervalId = setInterval(addTitleForEachRowOfLeaderboardTable, 1000);

</script>
"""

def gradio_app():
    with gr.Blocks(theme=gr.themes.Soft(text_size=text_md), css=custom_css, head=custom_js) as main:
        gr.Markdown(HEADER_MARKDOWN)
        
        if leaderboard_server.tournament_results_corrupted:
            gr.Markdown("## Results dataset integrity solving")
            
            results_dataset_integrity_check_btn = gr.Button(
                value='Check integrity of results dataset',
                interactive=True,
                visible=False,
            )
            
            results_dataset_integrity_solving_progress = gr.Markdown(
                value=None,
                visible=False,
            )
            
            results_dataset_integrity_restart_btn = gr.Button(
                value='Restart this space',
                interactive=False,
                visible=False,
            )
            
            results_dataset_integrity_solving_progress_timer = gr.Timer(
                value=60,  # seconds
            )
            
            results_dataset_integrity_solving_progress_timer.tick(
                fn=update_results_dataset_integrity_solving_progress,
                outputs=[
                    results_dataset_integrity_solving_progress,
                    results_dataset_integrity_restart_btn,
                ]
            )
            
            results_dataset_integrity_check_btn.click(
                fn=lambda: (
                    gr.update(interactive=False, visible=False),
                    gr.update(visible=True),
                ),
                outputs=[
                    results_dataset_integrity_check_btn,
                    results_dataset_integrity_solving_progress,
                ]
            ).then(
                fn=results_dataset_integrity_check
            )
            
            results_dataset_integrity_restart_btn.click(
                fn=lambda: gr.update(interactive=False),
                outputs=results_dataset_integrity_restart_btn
            ).then(
                fn=restart_space
            )
            
            main.load(
                fn=on_tournament_results_corrupted,
                outputs=[
                    results_dataset_integrity_check_btn,
                    results_dataset_integrity_solving_progress,
                ]
            ).then(
                fn=update_results_dataset_integrity_solving_progress,
                outputs=[
                    results_dataset_integrity_solving_progress,
                    results_dataset_integrity_restart_btn,
                ]
            )
            
            return main
        
        with gr.Tabs():
            with leaderboard_server.var_lock.ro:
                submission_ids_and_titles = get_submission_ids_and_titles()
            
            with gr.TabItem('Leaderboard'):
                with gr.Column():
                    gr.Markdown(LEADERBOARD_TAB_TITLE_MARKDOWN)

                    with gr.Row():
                        leaderboard_category_of_tasks = gr.Dropdown(
                            choices=(
                                [
                                    leaderboard_server.TASKS_CATEGORY_OVERALL,
                                    leaderboard_server.TASKS_CATEGORY_OVERALL_DETAILS,
                                ] + sorted(leaderboard_server.TASKS_CATEGORIES)
                            ),
                            value=leaderboard_server.TASKS_CATEGORY_OVERALL,
                            label="Category of benchmarks",
                            interactive=True,
                        )
                    
                    with gr.Row():
                        leaderboard_table = gr.DataFrame(
                            leaderboard_server.get_leaderboard(category=leaderboard_server.TASKS_CATEGORY_OVERALL),
                            interactive=False,
                            label=None,
                            visible=True,
                            datatype="markdown",
                            elem_classes="leaderboard-table",
                        )
                    
                    with gr.Row():
                        leaderboard_table_csv = gr.DownloadButton(
                            label="Download leaderboard in CSV format",
                            value=leaderboard_server.get_leaderboard_csv(category=leaderboard_server.TASKS_CATEGORY_OVERALL),
                        )
                    
                    with gr.Row():
                        leaderboard_table_legend = gr.DataFrame(
                            value=None,
                            headers=[
                                "Abbr.", # "task abbreviation"
                                "Name",
                                "URL",
                            ],
                            column_widths=["150px"],
                            datatype="markdown",
                            label="Descriptions of the tasks",
                            visible=False,
                            interactive=False,
                            elem_classes="leaderboard-table-legend",
                        )
                    
                    with gr.Row():
                        tournament_results_title = gr.Markdown(
                            value="## Tournament results for selected model",
                            visible=False,
                        )
                    
                    with gr.Row():
                        tournament_results_dropdown = gr.Dropdown(
                            value=None,
                            choices=submission_ids_and_titles,
                            label="Select model",
                            visible=False,
                            interactive=True,
                        )
                    
                    with gr.Row():
                        model_tournament_results_table = gr.DataFrame(
                            value=None,
                            datatype="markdown",
                            label="The model won against…",
                            visible=False,
                            interactive=False,
                            elem_classes="leaderboard-table-model-details",
                        )
                    
                    with gr.Row():
                        model_tournament_results_table_csv = gr.DownloadButton(
                            label="Download model tournament results in CSV format",
                            visible=False,
                        )
                    
                    leaderboard_category_of_tasks.change(
                        fn=change_leaderboard_category,
                        inputs=[
                            leaderboard_category_of_tasks,
                            tournament_results_dropdown,
                        ],
                        outputs=[
                            leaderboard_table,
                            leaderboard_table_csv,
                            leaderboard_table_legend,
                            tournament_results_title,
                            tournament_results_dropdown,
                            model_tournament_results_table,
                            model_tournament_results_table_csv,
                        ],
                    )
                    
                    tournament_results_dropdown.change(
                        fn=fetch_model_tournament_results_table,
                        inputs=[
                            tournament_results_dropdown,
                            leaderboard_category_of_tasks,
                        ],
                        outputs=model_tournament_results_table,
                    ).then(
                        fn=fetch_model_tournament_results_table_csv,
                        inputs=[
                            tournament_results_dropdown,
                            leaderboard_category_of_tasks,
                        ],
                        outputs=model_tournament_results_table_csv,
                    )

            with gr.TabItem('Model details'):
                gr.Markdown(MORE_DETAILS_MARKDOWN)
                
                with gr.Row():
                    model_details_model_dropdown = gr.Dropdown(
                        choices=submission_ids_and_titles,
                        label="Select model",
                        interactive=True,
                    )

                with gr.Row():
                    model_details_description = gr.Text(value='', label='Model description', visible=False, interactive=False)
                    model_details_url = gr.Text(value='', label='Model url', visible=False, interactive=False)
                
                with gr.Row():
                    model_details_tournament_results_title = gr.Markdown(
                        value="## Tournament results for selected model",
                        visible=False,
                    )
                
                with gr.Row():
                    model_details_category_of_tasks = gr.Dropdown(
                        choices=(
                            [
                                leaderboard_server.TASKS_CATEGORY_OVERALL,
                            ] + sorted(leaderboard_server.TASKS_CATEGORIES)
                        ),
                        value=None,
                        label="Category of benchmarks",
                        visible=False,
                        interactive=True,
                    )
                
                with gr.Row():
                    model_details_model_tournament_results_table = gr.DataFrame(
                        value=None,
                        datatype="markdown",
                        label="The model won against…",
                        visible=False,
                        interactive=False,
                        elem_classes="leaderboard-table-model-details",
                    )
                
                with gr.Row():
                    model_details_model_tournament_results_table_csv = gr.DownloadButton(
                        label="Download model tournament results in CSV format",
                        visible=False,
                    )
                
                model_details_model_dropdown.change(
                    fn=fetch_model_detail,
                    inputs=[model_details_model_dropdown],
                    outputs=[model_details_description, model_details_url],
                ).then(
                    fn=lambda submission_id: gr.update(visible=True) if submission_id else gr.update(visible=False),
                    inputs=model_details_model_dropdown,
                    outputs=model_details_tournament_results_title
                ).then(
                    fn=lambda submission_id: gr.update(visible=True) if submission_id else gr.update(visible=False),
                    inputs=model_details_model_dropdown,
                    outputs=model_details_category_of_tasks
                ).then(
                    fn=fetch_model_tournament_results_table,
                    inputs=[
                        model_details_model_dropdown,
                        model_details_category_of_tasks,
                    ],
                    outputs=model_details_model_tournament_results_table
                ).then(
                    fn=fetch_model_tournament_results_table_csv,
                    inputs=[
                        model_details_model_dropdown,
                        model_details_category_of_tasks,
                    ],
                    outputs=model_details_model_tournament_results_table_csv
                )
                
                model_details_category_of_tasks.change(
                    fn=fetch_model_tournament_results_table,
                    inputs=[
                        model_details_model_dropdown,
                        model_details_category_of_tasks,
                    ],
                    outputs=model_details_model_tournament_results_table,
                ).then(
                    fn=fetch_model_tournament_results_table_csv,
                    inputs=[
                        model_details_model_dropdown,
                        model_details_category_of_tasks,
                    ],
                    outputs=model_details_model_tournament_results_table_csv,
                )
            
            with gr.TabItem('Submission'):
                with gr.Column():
                    gr.Markdown(SUBMISSION_TAB_TITLE_MARKDOWN)
                    
                    submission_inputs = dict.fromkeys(SUBMISSION_INPUTS)
                    
                    with gr.Row():
                        submission_inputs["team_name"] = gr.Textbox(label='Team name', type='text')
                        submission_inputs["model_name"] = gr.Textbox(label='Model name', type='text')
                        submission_inputs["model_type"] = gr.Dropdown(
                            label="Model type",
                            choices=("chat", "pretrained", "ensemble"),
                        )
                        submission_inputs["parameters"] = gr.Number(
                            label='Parameters (B)',
                            value=0.01,
                            step=0.01,
                        )

                    with gr.Row():
                        submission_inputs["input_length"] = gr.Number(
                            label='Input length (# tokens)',
                            value=0,
                            step=1,
                        )
                        submission_inputs["precision"] = gr.Dropdown(
                            label="Precision",
                            choices=("float32", "bfloat32", "float16", "bfloat16", "8bit", "4bit"),
                        )
                        submission_inputs["description"] = gr.Textbox(label='Description', type='text')
                        submission_inputs["link_to_model"] = gr.Textbox(label='Link to model', type='text')

                    submission_inputs["submission_file"] = gr.File(label='Upload your results', type='filepath')
                    
                    pre_submission_btn = gr.Button(value='Pre-submit model', interactive=True)

                    submit_prompt = gr.Markdown(
                        SUBMISSION_DETAILS_MARKDOWN,
                        visible=False
                    )

                    pre_submit_info = gr.Markdown(
                        RANKING_AFTER_SUBMISSION_MARKDOWN,
                        visible=False
                    )
                    
                    pre_submit_leaderboard_table = gr.DataFrame(
                        value=None,
                        datatype="markdown",
                        label="The leaderboard for this pre-submission",
                        visible=False,
                        interactive=False,
                        elem_classes="leaderboard-table",
                    )
                    
                    pre_submit_leaderboard_table_csv = gr.DownloadButton(
                        label="Download the leaderboard in CSV format",
                        visible=False,
                    )
                    
                    pre_submit_model_tournament_results_table = gr.DataFrame(
                        value=None,
                        datatype="markdown",
                        label="The pre-submited model won against…",
                        visible=False,
                        interactive=False,
                        elem_classes="leaderboard-table-model-details",
                    )
                    
                    pre_submit_model_tournament_results_table_csv = gr.DownloadButton(
                        label="Download the model tournament results in CSV format",
                        visible=False,
                    )
                    
                    # delimiter
                    with gr.Row():
                        pass
                    
                    submission_btn_yes = gr.Button(value='Submit model', interactive=False, visible=False)
                    submission_btn_no = gr.Button(value='Reverse process', interactive=False, visible=False)

                    with Modal(visible=False, allow_user_close=False) as modal_submit:
                        gr.Markdown(MODAL_SUBMIT_MARKDOWN)
                        modal_submit_yes = gr.Button("Yes", interactive=True)
                        modal_submit_no = gr.Button("No", interactive=True)

                    pre_submission_btn.click(
                        fn=on_submit_pressed,
                        outputs=[pre_submission_btn],
                    ).then(
                        fn=process_submission,
                        inputs=list(submission_inputs.values()),
                        outputs=[
                            pre_submission_btn,
                            submit_prompt,
                            submission_btn_yes,
                            submission_btn_no,
                            pre_submit_info,
                            pre_submit_leaderboard_table,
                            pre_submit_leaderboard_table_csv,
                            pre_submit_model_tournament_results_table,
                            pre_submit_model_tournament_results_table_csv,
                        ],
                        concurrency_limit=None,
                    )

                    submission_btn_yes.click(
                        fn=show_modal,
                        outputs=[modal_submit]
                    )

                    modal_submit_yes.click(
                        fn=disable_submit_buttons,
                        outputs=[
                            modal_submit_yes,
                            modal_submit_no,
                        ]
                    ).then(
                        fn=submit_results,
                        outputs=[
                            pre_submission_btn,
                            submission_btn_yes,
                            submission_btn_no,
                            submit_prompt,
                            pre_submit_info,
                            pre_submit_leaderboard_table,
                            pre_submit_leaderboard_table_csv,
                            pre_submit_model_tournament_results_table,
                            pre_submit_model_tournament_results_table_csv,
                            leaderboard_table,
                            leaderboard_table_csv,
                            modal_submit,
                            model_details_model_dropdown,
                            leaderboard_category_of_tasks,
                            tournament_results_dropdown,
                        ],
                    ).then(
                        fn=enable_submit_buttons,
                        outputs=[
                            modal_submit_yes,
                            modal_submit_no,
                        ]
                    )

                    modal_submit_no.click(
                        fn=disable_submit_buttons,
                        outputs=[
                            modal_submit_yes,
                            modal_submit_no,
                        ]
                    ).then(
                        fn=hide_modal,
                        outputs=[modal_submit]
                    ).then(
                        fn=enable_submit_buttons,
                        outputs=[
                            modal_submit_yes,
                            modal_submit_no,
                        ]
                    )

                    submission_btn_no.click(
                        fn=erase_pre_submit,
                        outputs=[
                            pre_submission_btn,
                            submission_btn_yes,
                            submission_btn_no,
                            submit_prompt,
                            pre_submit_info,
                            pre_submit_leaderboard_table,
                            pre_submit_leaderboard_table_csv,
                            pre_submit_model_tournament_results_table,
                            pre_submit_model_tournament_results_table_csv,
                        ],
                    )
            
            with gr.TabItem('About'):
                gr.Markdown(ABOUT_MARKDOWN)
        main.load(
            on_application_load,
            inputs=None,
            outputs=[
                leaderboard_table,
                leaderboard_table_csv,
                model_details_model_dropdown,
                leaderboard_category_of_tasks,
                tournament_results_dropdown,
            ]
        )
    
    return main

app = gradio_app()
app.launch()