-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathchallenges.py
More file actions
669 lines (589 loc) · 20.3 KB
/
challenges.py
File metadata and controls
669 lines (589 loc) · 20.3 KB
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
import json
import requests
import sys
from bs4 import BeautifulSoup
from beautifultable import BeautifulTable
from click import echo, style
from datetime import datetime
from termcolor import colored
from evalai.utils.auth import get_request_header, get_host_url
from evalai.utils.common import (
clean_data,
validate_token,
convert_UTC_date_to_local,
validate_date_format,
)
from evalai.utils.config import EVALAI_ERROR_CODES
from evalai.utils.urls import URLS
requests.packages.urllib3.disable_warnings()
def pretty_print_challenge_data(challenges):
"""
Function to print the challenge data
"""
table = BeautifulTable(max_width=200)
attributes = ["id", "title", "short_description"]
columns_attributes = [
"ID",
"Title",
"Short Description",
"Creator",
"Start Date",
"End Date",
]
table.column_headers = columns_attributes
for challenge in reversed(challenges):
values = list(map(lambda item: challenge[item], attributes))
creator = challenge["creator"]["team_name"]
start_date = convert_UTC_date_to_local(challenge["start_date"])
end_date = convert_UTC_date_to_local(challenge["end_date"])
values.extend([creator, start_date, end_date])
table.append_row([colored(values[0], 'white'),
colored(values[1], 'yellow'),
colored(values[2], 'cyan'),
colored(values[3], 'white'),
colored(values[4], 'green'),
colored(values[5], 'red'),
])
echo(table, color='yes')
def display_challenges(url):
"""
Function to fetch & display the challenge list based on API
"""
header = get_request_header()
try:
response = requests.get(url, headers=header)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code == 401:
validate_token(response.json())
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
challenges = response["results"]
if len(challenges) != 0:
pretty_print_challenge_data(challenges)
else:
echo(style("Sorry, no challenges found.", bold=True, fg="red"))
def display_all_challenge_list():
"""
Displays the list of all challenges from the backend
"""
url = "{}{}".format(get_host_url(), URLS.challenge_list.value)
display_challenges(url)
def display_past_challenge_list():
"""
Displays the list of past challenges from the backend
"""
url = "{}{}".format(get_host_url(), URLS.past_challenge_list.value)
display_challenges(url)
def display_ongoing_challenge_list():
"""
Displays the list of ongoing challenges from the backend
"""
url = "{}{}".format(get_host_url(), URLS.challenge_list.value)
header = get_request_header()
try:
response = requests.get(url, headers=header)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code == 401:
validate_token(response.json())
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
challenges = response["results"]
# Filter out past/unapproved/unpublished challenges.
challenges = list(
filter(
lambda challenge: validate_date_format(challenge["end_date"])
> datetime.now()
and challenge["approved_by_admin"]
and challenge["published"],
challenges,
)
)
if len(challenges) != 0:
pretty_print_challenge_data(challenges)
else:
echo(style("Sorry, no challenges found.", bold=True, fg="red"))
def display_future_challenge_list():
"""
Displays the list of future challenges from the backend
"""
url = "{}{}".format(get_host_url(), URLS.future_challenge_list.value)
display_challenges(url)
def get_participant_or_host_teams(url):
"""
Returns the participant or host teams corresponding to the user
"""
header = get_request_header()
try:
response = requests.get(url, headers=header)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code == 401:
validate_token(response.json())
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
return response["results"]
def get_participant_or_host_team_challenges(url, teams):
"""
Returns the challenges corresponding to the participant or host teams
"""
challenges = []
for team in teams:
header = get_request_header()
try:
response = requests.get(url.format(team["id"]), headers=header)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code == 401:
validate_token(response.json())
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
challenges += response["results"]
return challenges
def display_participated_or_hosted_challenges(
is_host=False, is_participant=False
):
"""
Function to display the participated or hosted challenges by a user
"""
challenges = []
if is_host:
team_url = "{}{}".format(get_host_url(), URLS.host_teams.value)
challenge_url = "{}{}".format(
get_host_url(), URLS.host_challenges.value
)
teams = get_participant_or_host_teams(team_url)
challenges = get_participant_or_host_team_challenges(
challenge_url, teams
)
echo(style("\nHosted Challenges\n", bold=True))
if len(challenges) != 0:
pretty_print_challenge_data(challenges)
else:
echo(style("Sorry, no challenges found.", bold=True, fg="red"))
if is_participant:
team_url = "{}{}".format(get_host_url(), URLS.participant_teams.value)
challenge_url = "{}{}".format(
get_host_url(), URLS.participant_challenges.value
)
teams = get_participant_or_host_teams(team_url)
challenges = get_participant_or_host_team_challenges(
challenge_url, teams
)
if len(challenges) != 0:
# Filter out past/unapproved/unpublished challenges.
challenges = list(
filter(
lambda challenge: validate_date_format(
challenge["end_date"]
)
> datetime.now()
and challenge["approved_by_admin"]
and challenge["published"],
challenges,
)
)
if challenges:
echo(style("\nParticipated Challenges\n", bold=True))
pretty_print_challenge_data(challenges)
else:
echo(style("Sorry, no challenges found.", bold=True, fg="red"))
else:
echo(style("Sorry, no challenges found.", bold=True, fg="red"))
def pretty_print_challenge_details(challenge):
table = BeautifulTable(max_width=200)
attributes = [
"description",
"submission_guidelines",
"evaluation_details",
"terms_and_conditions",
]
table.column_headers = [
"Start Date",
"End Date",
"Description",
"Submission Guidelines",
"Evaluation Details",
"Terms and Conditions",
]
values = []
start_date = convert_UTC_date_to_local(challenge["start_date"]).split(" ")[
0
]
end_date = convert_UTC_date_to_local(challenge["end_date"]).split(" ")[0]
values.extend([start_date, end_date])
values.extend(
list(map(lambda item: clean_data(challenge[item]), attributes))
)
table.append_row(values)
echo(table)
def display_challenge_details(challenge):
"""
Function to display challenge details.
"""
url = URLS.challenge_details.value
url = "{}{}".format(get_host_url(), url)
url = url.format(challenge)
header = get_request_header()
try:
response = requests.get(url, headers=header)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code in EVALAI_ERROR_CODES:
validate_token(response.json())
echo(
style(
"\nError: {}".format(response.json()["error"]),
fg="red",
bold=True,
)
)
echo(
style(
"\nUse `evalai challenges` to fetch the active challenges.\n",
fg="red",
bold=True,
)
)
else:
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
pretty_print_challenge_details(response)
def pretty_print_all_challenge_phases(phases):
"""
Function to print all the challenge phases of a challenge
"""
table = BeautifulTable(max_width=150)
attributes = ["id", "name", "challenge"]
columns_attributes = [
"Phase ID",
"Phase Name",
"Challenge ID",
"Description",
]
table.column_headers = columns_attributes
for phase in phases:
values = list(map(lambda item: phase[item], attributes))
description = clean_data(phase["description"])
values.append(description)
table.append_row(values)
echo(table)
def display_challenge_phase_list(challenge_id):
"""
Function to display all challenge phases for a particular challenge.
"""
url = URLS.challenge_phase_list.value
url = "{}{}".format(get_host_url(), url)
url = url.format(challenge_id)
headers = get_request_header()
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code in EVALAI_ERROR_CODES:
validate_token(response.json())
echo(
style(
"\nError: {}".format(response.json()["error"]),
fg="red",
bold=True,
)
)
echo(
style(
"\nUse `evalai challenges` to fetch the active challenges.",
fg="red",
bold=True,
)
)
echo(
style(
"\nUse `evalai challenge CHALLENGE phases` to fetch the active phases.\n",
fg="red",
bold=True,
)
)
else:
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
challenge_phases = response["results"]
pretty_print_all_challenge_phases(challenge_phases)
def pretty_print_challenge_phase_data(phase):
"""
Function to print the details of a challenge phase.
"""
phase_title = "\n{}".format(style(phase["name"], bold=True, fg="green"))
challenge_id = "Challenge ID: {}".format(
style(str(phase["challenge"]), bold=True, fg="blue")
)
phase_id = "Phase ID: {}\n\n".format(
style(str(phase["id"]), bold=True, fg="blue")
)
title = "{} {} {}".format(phase_title, challenge_id, phase_id)
cleaned_desc = BeautifulSoup(phase["description"], "lxml").text
description = "{}\n".format(cleaned_desc)
start_date = "Start Date : {}".format(
style(phase["start_date"].split("T")[0], fg="green")
)
start_date = "\n{}\n".format(style(start_date, bold=True))
end_date = "End Date : {}".format(
style(phase["end_date"].split("T")[0], fg="red")
)
end_date = "\n{}\n".format(style(end_date, bold=True))
max_submissions_per_day = style(
"\nMaximum Submissions per day : {}\n".format(
str(phase["max_submissions_per_day"])
),
bold=True,
)
max_submissions = style(
"\nMaximum Submissions : {}\n".format(str(phase["max_submissions"])),
bold=True,
)
codename = style("\nCode Name : {}\n".format(phase["codename"]), bold=True)
leaderboard_public = style(
"\nLeaderboard Public : {}\n".format(phase["leaderboard_public"]),
bold=True,
)
is_active = style("\nActive : {}\n".format(phase["is_active"]), bold=True)
is_public = style("\nPublic : {}\n".format(phase["is_public"]), bold=True)
challenge_phase = "{}{}{}{}{}{}{}{}{}{}".format(
title,
description,
start_date,
end_date,
max_submissions_per_day,
max_submissions,
leaderboard_public,
codename,
is_active,
is_public,
)
echo(challenge_phase)
def display_challenge_phase_detail(challenge_id, phase_id, is_json):
"""
Function to print details of a challenge phase.
"""
url = URLS.challenge_phase_detail.value
url = "{}{}".format(get_host_url(), url)
url = url.format(challenge_id, phase_id)
headers = get_request_header()
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code in EVALAI_ERROR_CODES:
validate_token(response.json())
echo(
style(
"\nError: {}\n"
"\nUse `evalai challenges` to fetch the active challenges.\n"
"\nUse `evalai challenge CHALLENGE phases` to fetch the "
"active phases.\n".format(response.json()["error"]),
fg="red",
bold=True,
)
)
else:
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
phase = response
if is_json:
phase_json = json.dumps(phase, indent=4, sort_keys=True)
echo(phase_json)
else:
pretty_print_challenge_phase_data(phase)
def pretty_print_challenge_phase_split_data(phase_splits):
"""
Function to print the details of a Challenge Phase Split.
"""
table = BeautifulTable(max_width=100)
attributes = ["id", "dataset_split_name", "challenge_phase_name"]
columns_attributes = [
"Challenge Phase ID",
"Dataset Split",
"Challenge Phase Name",
]
table.column_headers = columns_attributes
for split in phase_splits:
if split["visibility"] == 3:
values = list(map(lambda item: split[item], attributes))
table.append_row(values)
echo(table)
def display_challenge_phase_split_list(challenge_id):
"""
Function to display Challenge Phase Splits of a particular challenge.
"""
url = URLS.challenge_phase_split_detail.value
url = "{}{}".format(get_host_url(), url)
url = url.format(challenge_id)
headers = get_request_header()
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code in EVALAI_ERROR_CODES:
validate_token(response.json())
echo(
style(
"\nError: {}\n"
"\nUse `evalai challenges` to fetch the active challenges.\n"
"\nUse `evalai challenge CHALLENGE phases` to fetch the "
"active phases.\n".format(response.json()["error"]),
fg="red",
bold=True,
)
)
else:
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
phase_splits = response.json()
if len(phase_splits) != 0:
pretty_print_challenge_phase_split_data(phase_splits)
else:
echo(style("Sorry, no Challenge Phase Splits found.", bold=True, fg="red"))
def pretty_print_leaderboard_data(attributes, results):
"""
Pretty print the leaderboard for a particular CPS.
"""
leaderboard_table = BeautifulTable(max_width=150)
attributes = ["Rank", "Participant Team"] + attributes + ["Last Submitted"]
attributes = list(map(lambda item: str(item), attributes))
leaderboard_table.column_headers = attributes
for rank, result in enumerate(results, start=1):
name = result["submission__participant_team__team_name"]
scores = result["result"]
last_submitted = convert_UTC_date_to_local(
result["submission__submitted_at"]
)
leaderboard_row = [rank, name] + scores + [last_submitted]
leaderboard_table.append_row(leaderboard_row)
echo(leaderboard_table)
def display_leaderboard(challenge_id, phase_split_id):
"""
Function to display the Leaderboard of a particular CPS.
"""
url = "{}{}".format(get_host_url(), URLS.leaderboard.value)
url = url.format(phase_split_id)
headers = get_request_header()
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
if response.status_code in EVALAI_ERROR_CODES:
validate_token(response.json())
echo(
style(
"Error: {}".format(response.json()["error"]),
fg="red",
bold=True,
)
)
else:
echo(style(str(err), bold=True, fg="red"))
sys.exit(1)
except requests.exceptions.RequestException:
echo(
style(
"\nCould not establish a connection to EvalAI."
" Please check the Host URL.\n",
bold=True,
fg="red",
)
)
sys.exit(1)
response = response.json()
results = response["results"]
if len(results) != 0:
attributes = results[0]["leaderboard__schema"]["labels"]
pretty_print_leaderboard_data(attributes, results)
else:
echo(style("Sorry, no Leaderboard results found.", bold=True, fg="red"))