-
Notifications
You must be signed in to change notification settings - Fork 809
/
Copy pathviews.py
3009 lines (2744 loc) · 117 KB
/
views.py
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
import botocore
import datetime
import json
import logging
import os
import uuid
from rest_framework import permissions, status
from rest_framework.decorators import (
api_view,
authentication_classes,
permission_classes,
throttle_classes,
)
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import transaction, IntegrityError
from django.db.models import Count
from django.utils import timezone
from rest_framework_expiring_authtoken.authentication import (
ExpiringTokenAuthentication,
)
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from accounts.permissions import HasVerifiedEmail
from base.utils import (
StandardResultSetPagination,
get_boto3_client,
get_or_create_sqs_queue,
paginated_queryset,
is_user_a_staff,
)
from challenges.models import (
ChallengePhase,
Challenge,
ChallengeEvaluationCluster,
ChallengePhaseSplit,
LeaderboardData,
)
from challenges.utils import (
complete_s3_multipart_file_upload,
generate_presigned_url_for_multipart_upload,
get_aws_credentials_for_challenge,
get_challenge_model,
get_challenge_phase_model,
get_challenge_phase_split_model,
get_participant_model,
)
from hosts.models import ChallengeHost
from hosts.utils import is_user_a_host_of_challenge, is_user_a_staff_or_host
from participants.models import ParticipantTeam
from participants.utils import (
get_participant_team_model,
get_participant_team_id_of_user_for_a_challenge,
get_participant_team_of_user_for_a_challenge,
is_user_part_of_participant_team,
)
from .aws_utils import generate_aws_eks_bearer_token
from .filters import SubmissionFilter
from .models import Submission
from .sender import publish_submission_message
from .serializers import (
CreateLeaderboardDataSerializer,
LeaderboardDataSerializer,
RemainingSubmissionDataSerializer,
SubmissionSerializer,
)
from .tasks import download_file_and_publish_submission_message
from .utils import (
calculate_distinct_sorted_leaderboard_data,
get_leaderboard_data_model,
get_remaining_submission_for_a_phase,
get_submission_model,
handle_submission_rerun,
handle_submission_resume,
is_url_valid,
reorder_submissions_comparator,
reorder_submissions_comparator_to_key,
)
logger = logging.getLogger(__name__)
@swagger_auto_schema(
methods=["post"],
manual_parameters=[
openapi.Parameter(
name="challenge_id",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge ID",
required=True,
),
openapi.Parameter(
name="challenge_phase_id",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge Phase ID",
required=True,
),
],
responses={status.HTTP_201_CREATED: openapi.Response("")},
)
@swagger_auto_schema(
methods=["get"],
manual_parameters=[
openapi.Parameter(
name="challenge_id",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge ID",
required=True,
),
openapi.Parameter(
name="challenge_phase_id",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge Phase ID",
required=True,
),
],
responses={status.HTTP_201_CREATED: openapi.Response("")},
)
@api_view(["GET", "POST"])
@throttle_classes([UserRateThrottle])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
@authentication_classes((JWTAuthentication, ExpiringTokenAuthentication))
def challenge_submission(request, challenge_id, challenge_phase_id):
"""API Endpoint for making a submission to a challenge"""
# check if the challenge exists or not
try:
challenge = Challenge.objects.get(pk=challenge_id)
except Challenge.DoesNotExist:
response_data = {"error": "Challenge does not exist"}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
# check if the challenge phase exists or not
try:
challenge_phase = ChallengePhase.objects.get(
pk=challenge_phase_id, challenge=challenge
)
except ChallengePhase.DoesNotExist:
response_data = {"error": "Challenge Phase does not exist"}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
if request.method == "GET":
# getting participant team object for the user for a particular challenge.
participant_team_id = get_participant_team_id_of_user_for_a_challenge(
request.user, challenge_id
)
# check if participant team exists or not.
try:
ParticipantTeam.objects.get(pk=participant_team_id)
except ParticipantTeam.DoesNotExist:
response_data = {
"error": "You haven't participated in the challenge"
}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
submission = Submission.objects.filter(
participant_team=participant_team_id,
challenge_phase=challenge_phase,
ignore_submission=False,
).order_by("-submitted_at")
filtered_submissions = SubmissionFilter(
request.GET, queryset=submission
)
# rerank in progress submissions in ascending order of submitted_at
reordered_submissions = sorted(
filtered_submissions.qs,
key=reorder_submissions_comparator_to_key(
reorder_submissions_comparator
),
)
paginator, result_page = paginated_queryset(
reordered_submissions, request
)
serializer = SubmissionSerializer(
result_page, many=True, context={"request": request}
)
response_data = serializer.data
return paginator.get_paginated_response(response_data)
elif request.method == "POST":
# check if the challenge is active or not
if not challenge.is_active:
response_data = {"error": "Challenge is not active"}
return Response(
response_data, status=status.HTTP_406_NOT_ACCEPTABLE
)
# check if challenge phase is active
if not challenge_phase.is_active:
response_data = {
"error": "Sorry, cannot accept submissions since challenge phase is not active"
}
return Response(
response_data, status=status.HTTP_406_NOT_ACCEPTABLE
)
# check if user is a challenge host or a participant
if not is_user_a_host_of_challenge(request.user, challenge_id):
# check if challenge phase is public and accepting solutions
if not challenge_phase.is_public:
response_data = {
"error": "Sorry, cannot accept submissions since challenge phase is not public"
}
return Response(
response_data, status=status.HTTP_403_FORBIDDEN
)
# if allowed email ids list exist, check if the user exist in that list or not
if challenge_phase.allowed_email_ids:
if request.user.email not in challenge_phase.allowed_email_ids:
response_data = {
"error": "Sorry, you are not allowed to participate in this challenge phase"
}
return Response(
response_data, status=status.HTTP_403_FORBIDDEN
)
participant_team_id = get_participant_team_id_of_user_for_a_challenge(
request.user, challenge_id
)
try:
participant_team = ParticipantTeam.objects.get(
pk=participant_team_id
)
except ParticipantTeam.DoesNotExist:
response_data = {
"error": "You haven't participated in the challenge"
}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
# check if manual approval is enabled and team is approved
if challenge.manual_participant_approval and not challenge.approved_participant_teams.filter(pk=participant_team_id).exists():
response_data = {
"error": "Your team is not approved by challenge host"
}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
all_participants_email = participant_team.get_all_participants_email()
for participant_email in all_participants_email:
if participant_email in challenge.banned_email_ids:
message = "You're a part of {} team and it has been banned from this challenge. \
Please contact the challenge host.".format(
participant_team.team_name
)
response_data = {"error": message}
return Response(
response_data, status=status.HTTP_403_FORBIDDEN
)
# Fetch the number of submissions under progress.
submissions_in_progress_status = [
Submission.SUBMITTED,
Submission.SUBMITTING,
Submission.RESUMING,
Submission.QUEUED,
Submission.RUNNING,
]
submissions_in_progress = Submission.objects.filter(
participant_team=participant_team_id,
challenge_phase=challenge_phase,
status__in=submissions_in_progress_status,
).count()
if (
submissions_in_progress
>= challenge_phase.max_concurrent_submissions_allowed
):
message = "You have {} submissions that are being processed. \
Please wait for them to finish and then try again."
response_data = {"error": message.format(submissions_in_progress)}
return Response(
response_data, status=status.HTTP_406_NOT_ACCEPTABLE
)
if not request.FILES:
if request.data.get("file_url") is None:
response_data = {"error": "The file URL is missing!"}
return Response(
response_data, status=status.HTTP_400_BAD_REQUEST
)
if not is_url_valid(request.data["file_url"]):
response_data = {"error": "The file URL does not exists!"}
return Response(
response_data, status=status.HTTP_400_BAD_REQUEST
)
download_file_and_publish_submission_message.delay(
request.data,
request.user.id,
request.method,
challenge_phase_id,
)
response_data = {
"message": "Please wait while your submission being evaluated!"
}
return Response(response_data, status=status.HTTP_200_OK)
if request.data.get("submission_meta_attributes"):
submission_meta_attributes = json.load(
request.data.get("submission_meta_attributes")
)
request.data[
"submission_meta_attributes"
] = submission_meta_attributes
if request.data.get("is_public") is None:
request.data["is_public"] = (
True if challenge_phase.is_submission_public else False
)
else:
request.data["is_public"] = json.loads(request.data["is_public"])
if (
request.data.get("is_public")
and challenge_phase.is_restricted_to_select_one_submission
):
# Handle corner case for restrict one public lb submission
submissions_already_public = Submission.objects.filter(
is_public=True,
participant_team=participant_team,
challenge_phase=challenge_phase,
)
# Make the existing public submission private before making the new submission public
if submissions_already_public.count() == 1:
# Case when the phase is restricted to make only one submission as public
submission_serializer = SubmissionSerializer(
submissions_already_public[0],
data={"is_public": False},
context={
"participant_team": participant_team,
"challenge_phase": challenge_phase,
"request": request,
},
partial=True,
)
if submission_serializer.is_valid():
submission_serializer.save()
# Override submission visibility if leaderboard_public = False for a challenge phase
if not challenge_phase.leaderboard_public:
request.data["is_public"] = challenge_phase.is_submission_public
serializer = SubmissionSerializer(
data=request.data,
context={
"participant_team": participant_team,
"challenge_phase": challenge_phase,
"request": request,
},
)
message = {
"challenge_pk": challenge_id,
"phase_pk": challenge_phase_id,
"is_static_dataset_code_upload_submission": False,
}
if challenge.is_docker_based:
try:
file_content = json.loads(request.FILES["input_file"].read())
message["submitted_image_uri"] = file_content[
"submitted_image_uri"
]
if challenge.is_static_dataset_code_upload:
message["is_static_dataset_code_upload_submission"] = True
except Exception as ex:
response_data = {
"error": "Error {} in submitted_image_uri from submission file".format(
ex
)
}
return Response(
response_data, status=status.HTTP_400_BAD_REQUEST
)
if serializer.is_valid():
serializer.save()
response_data = serializer.data
submission = serializer.instance
message["submission_pk"] = submission.id
# publish message in the queue
publish_submission_message(message)
return Response(response_data, status=status.HTTP_201_CREATED)
return Response(
serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE
)
@api_view(["PATCH"])
@throttle_classes([UserRateThrottle])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
@authentication_classes((JWTAuthentication, ExpiringTokenAuthentication))
def change_submission_data_and_visibility(
request, challenge_pk, challenge_phase_pk, submission_pk
):
"""
API Endpoint for updating the submission meta data
and changing submission visibility.
"""
# check if the challenge exists or not
challenge = get_challenge_model(challenge_pk)
# check if the challenge phase exists or not
challenge_phase = get_challenge_phase_model(challenge_phase_pk)
if not challenge.is_active:
response_data = {"error": "Challenge is not active"}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
# check if challenge phase is public and accepting solutions
if not is_user_a_host_of_challenge(request.user, challenge_pk):
if not challenge_phase.is_public:
response_data = {
"error": "Sorry, cannot accept submissions since challenge phase is not public"
}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
elif request.data.get("is_baseline"):
response_data = {
"error": "Sorry, you are not authorized to make this request"
}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
participant_team_pk = get_participant_team_id_of_user_for_a_challenge(
request.user, challenge_pk
)
try:
participant_team = ParticipantTeam.objects.get(pk=participant_team_pk)
except ParticipantTeam.DoesNotExist:
response_data = {"error": "You haven't participated in the challenge"}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
try:
submission = Submission.objects.get(
participant_team=participant_team,
challenge_phase=challenge_phase,
id=submission_pk,
)
except Submission.DoesNotExist:
response_data = {"error": "Submission does not exist"}
return Response(response_data, status=status.HTTP_403_FORBIDDEN)
try:
is_public = request.data["is_public"]
if is_public is True:
when_made_public = datetime.datetime.now()
request.data["when_made_public"] = when_made_public
submissions_already_public = Submission.objects.filter(
is_public=True,
participant_team=participant_team,
challenge_phase=challenge_phase,
)
# Make the existing public submission private before making the new submission public
if (
challenge_phase.is_restricted_to_select_one_submission
and is_public
and submissions_already_public.count() == 1
):
# Case when the phase is restricted to make only one submission as public
submission_serializer = SubmissionSerializer(
submissions_already_public[0],
data={"is_public": False},
context={
"participant_team": participant_team,
"challenge_phase": challenge_phase,
"request": request,
},
partial=True,
)
if submission_serializer.is_valid():
submission_serializer.save()
except KeyError:
pass
serializer = SubmissionSerializer(
submission,
data=request.data,
context={
"participant_team": participant_team,
"challenge_phase": challenge_phase,
"request": request,
},
partial=True,
)
if serializer.is_valid():
serializer.save()
response_data = serializer.data
return Response(response_data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@swagger_auto_schema(
methods=["get"],
manual_parameters=[
openapi.Parameter(
name="challenge_phase_split_id",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge Phase Split ID",
required=True,
)
],
operation_id="leaderboard",
responses={
status.HTTP_200_OK: openapi.Response(
description="",
schema=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"count": openapi.Schema(
type=openapi.TYPE_STRING,
description="Count of values on the leaderboard",
),
"next": openapi.Schema(
type=openapi.TYPE_STRING,
description="URL of next page of results",
),
"previous": openapi.Schema(
type=openapi.TYPE_STRING,
description="URL of previous page of results",
),
"results": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Array of results object",
items=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"submission__participant_team__team_name": openapi.Schema(
type=openapi.TYPE_STRING,
description="Participant Team Name",
),
"challenge_phase_split": openapi.Schema(
type=openapi.TYPE_STRING,
description="Challenge Phase Split ID",
),
"filtering_score": openapi.Schema(
type=openapi.TYPE_STRING,
description="Default filtering score for results",
),
"leaderboard__schema": openapi.Schema(
type=openapi.TYPE_STRING,
description="Leaderboard Schema of the corresponding challenge",
),
"result": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Leaderboard Metrics values according to leaderboard schema",
items=openapi.Schema(
type=openapi.TYPE_OBJECT
),
),
"submission__submitted_at": openapi.Schema(
type=openapi.TYPE_STRING,
description="Time stamp when submission was submitted at",
),
},
),
),
},
),
)
},
)
@api_view(["GET"])
@throttle_classes([AnonRateThrottle, UserRateThrottle])
def leaderboard(request, challenge_phase_split_id):
"""
Returns leaderboard for a corresponding Challenge Phase Split
- Arguments:
``challenge_phase_split_id``: Primary key for the challenge phase split for which leaderboard is to be fetched
- Returns:
Leaderboard entry objects in a list
"""
# check if the challenge exists or not
challenge_phase_split = get_challenge_phase_split_model(
challenge_phase_split_id
)
challenge_obj = challenge_phase_split.challenge_phase.challenge
order_by = request.GET.get("order_by")
(
response_data,
http_status_code,
) = calculate_distinct_sorted_leaderboard_data(
request.user,
challenge_obj,
challenge_phase_split,
only_public_entries=True,
order_by=order_by,
)
# The response 400 will be returned if the leaderboard isn't public or `default_order_by` key is missing in leaderboard.
if http_status_code == status.HTTP_400_BAD_REQUEST:
return Response(response_data, status=http_status_code)
paginator, result_page = paginated_queryset(
response_data, request, pagination_class=StandardResultSetPagination()
)
response_data = result_page
return paginator.get_paginated_response(response_data)
@swagger_auto_schema(
methods=["get"],
manual_parameters=[
openapi.Parameter(
name="challenge_phase_split_pk",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge Phase Split Primary Key",
required=True,
)
],
operation_id="get_all_entries_on_public_leaderboard",
responses={
status.HTTP_200_OK: openapi.Response(
description="",
schema=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"count": openapi.Schema(
type=openapi.TYPE_STRING,
description="Count of values on the leaderboard",
),
"next": openapi.Schema(
type=openapi.TYPE_STRING,
description="URL of next page of results",
),
"previous": openapi.Schema(
type=openapi.TYPE_STRING,
description="URL of previous page of results",
),
"results": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Array of results object",
items=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"id": openapi.Schema(
type=openapi.TYPE_STRING,
description="Result ID",
),
"submission__participant_team": openapi.Schema(
type=openapi.TYPE_STRING,
description="Participant Team ID",
),
"submission__participant_team__team_name": openapi.Schema(
type=openapi.TYPE_STRING,
description="Participant Team Name",
),
"submission__participant_team__team_url": openapi.Schema(
type=openapi.TYPE_STRING,
description="Participant Team URL",
),
"submission__is_baseline": openapi.Schema(
type=openapi.TYPE_BOOLEAN,
description="Boolean to decide if submission is baseline",
),
"submission__is_public": openapi.Schema(
type=openapi.TYPE_BOOLEAN,
description="Boolean to decide if submission is public",
),
"challenge_phase_split": openapi.Schema(
type=openapi.TYPE_STRING,
description="Challenge Phase Split ID",
),
"result": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Leaderboard Metrics values according to leaderboard schema",
items=openapi.Schema(
type=openapi.TYPE_STRING
),
),
"error": openapi.Schema(
type=openapi.TYPE_STRING,
description="Error returned for the result",
),
"leaderboard__schema": openapi.Schema(
type=openapi.TYPE_OBJECT,
description="Leaderboard Schema of the corresponding challenge",
properties={
"labels": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Labels of leaderboard schema",
items=openapi.Schema(
type=openapi.TYPE_STRING
),
),
"default_order_by": openapi.Schema(
type=openapi.TYPE_STRING,
description="Default ordering label for the leaderboard schema",
),
},
),
"submission__submitted_at": openapi.Schema(
type=openapi.TYPE_STRING,
description="Time stamp when submission was submitted at",
),
"submission__method_name": openapi.Schema(
type=openapi.TYPE_STRING,
description="Method of submission",
),
"submission__id": openapi.Schema(
type=openapi.TYPE_STRING,
description="ID of submission",
),
"submission__submission_metadata": openapi.Schema(
type=openapi.TYPE_STRING,
description="Metadata and other info about submission",
),
"filtering_score": openapi.Schema(
type=openapi.TYPE_STRING,
description="Default filtering score for results",
),
"filtering_error": openapi.Schema(
type=openapi.TYPE_STRING,
description="Default filtering error for results",
),
},
),
),
},
),
),
status.HTTP_400_BAD_REQUEST: openapi.Response(
"{'error': 'Error message goes here'}"
),
},
)
@api_view(["GET"])
@throttle_classes([AnonRateThrottle])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
@authentication_classes((JWTAuthentication, ExpiringTokenAuthentication))
def get_all_entries_on_public_leaderboard(request, challenge_phase_split_pk):
"""
Returns public/private leaderboard entries to corresponding challenge phase split for a challenge host
- Arguments:
``challenge_phase_split_pk``: Primary key for the challenge phase split for which leaderboard is to be fetched
- Returns:
All Leaderboard entry objects in a list
Below is the sample response returned by the API
```
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"submission__participant_team": 2,
"submission__participant_team__team_name": "Sanchezview Participant Team",
"submission__participant_team__team_url": "",
"submission__is_baseline": true,
"submission__is_public": true,
"challenge_phase_split": 1,
"result": [
26
],
"error": null,
"leaderboard__schema": {
"labels": [
"score"
],
"default_order_by": "score"
},
"submission__submitted_at": "2021-01-12T10:14:58.764572Z",
"submission__method_name": "Vernon",
"submission__id": 10,
"submission__submission_metadata": null,
"filtering_score": 26.0,
"filtering_error": 0
}
]
}
```
"""
# check if the challenge exists or not
challenge_phase_split = get_challenge_phase_split_model(
challenge_phase_split_pk
)
challenge_obj = challenge_phase_split.challenge_phase.challenge
# Allow access only to challenge host
if not is_user_a_staff_or_host(request.user, challenge_obj.pk):
response_data = {
"error": "Sorry, you are not authorized to make this request!"
}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
order_by = request.GET.get("order_by")
(
response_data,
http_status_code,
) = calculate_distinct_sorted_leaderboard_data(
request.user,
challenge_obj,
challenge_phase_split,
only_public_entries=False,
order_by=order_by,
)
# The response 400 will be returned if the leaderboard isn't public or `default_order_by` key is missing in leaderboard.
if http_status_code == status.HTTP_400_BAD_REQUEST:
return Response(response_data, status=http_status_code)
paginator, result_page = paginated_queryset(
response_data, request, pagination_class=StandardResultSetPagination()
)
response_data = result_page
return paginator.get_paginated_response(response_data)
@api_view(["GET"])
@throttle_classes([UserRateThrottle])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
@authentication_classes((JWTAuthentication, ExpiringTokenAuthentication))
def get_remaining_submissions(request, challenge_pk):
"""
API to get the number of remaining submission for all phases.
Below is the sample response returned by the API
{
"participant_team": "Sample_Participant_Team",
"participant_team_id": 2,
"phases": [
{
"id": 1,
"slug": "megan-phase-1",
"name": "Megan Phase",
"start_date": "2018-10-28T14:22:53.022639Z",
"end_date": "2020-06-19T14:22:53.022660Z",
"limits": {
"remaining_submissions_this_month_count": 9,
"remaining_submissions_today_count": 5,
"remaining_submissions_count": 29
}
},
{
"id": 2,
"slug": "molly-phase-2",
"name": "Molly Phase",
"start_date": "2018-10-28T14:22:53Z",
"end_date": "2020-06-19T14:22:53Z",
"limits": {
"message": "You have exhausted this month's submission limit!",
"remaining_time": "1481076.929224" // remaining_time is in seconds
}
}
]
}
"""
phases_data = {}
challenge = get_challenge_model(challenge_pk)
challenge_phases = ChallengePhase.objects.filter(
challenge=challenge
).order_by("pk")
if not is_user_a_host_of_challenge(request.user, challenge_pk):
challenge_phases = challenge_phases.filter(
challenge=challenge, is_public=True
).order_by("pk")
phase_data_list = list()
for phase in challenge_phases:
(
remaining_submission_message,
response_status,
) = get_remaining_submission_for_a_phase(
request.user, phase.id, challenge_pk
)
if response_status != status.HTTP_200_OK:
return Response(
remaining_submission_message, status=response_status
)
phase_data_list.append(
RemainingSubmissionDataSerializer(
phase, context={"limits": remaining_submission_message}
).data
)
phases_data["phases"] = phase_data_list
participant_team = get_participant_team_of_user_for_a_challenge(
request.user, challenge_pk
)
phases_data["participant_team"] = participant_team.team_name
phases_data["participant_team_id"] = participant_team.id
return Response(phases_data, status=status.HTTP_200_OK)
@api_view(["GET", "DELETE"])
@throttle_classes([UserRateThrottle])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail))
@authentication_classes((JWTAuthentication, ExpiringTokenAuthentication))
def get_submission_by_pk(request, submission_id):
"""
API endpoint to fetch the details of a submission.
Only the submission owner or the challenge hosts are allowed.
"""
try:
submission = Submission.objects.get(pk=submission_id)
except Submission.DoesNotExist:
response_data = {
"error": "Submission {} does not exist".format(submission_id)
}
return Response(response_data, status=status.HTTP_404_NOT_FOUND)
host_team = submission.challenge_phase.challenge.creator
if (
request.user.id == submission.created_by.id
or ChallengeHost.objects.filter(
user=request.user.id, team_name__pk=host_team.pk
).exists()
):
if request.method == "GET":
serializer = SubmissionSerializer(
submission, context={"request": request}
)
response_data = serializer.data
return Response(response_data, status=status.HTTP_200_OK)
elif request.method == "DELETE":
serializer = SubmissionSerializer(
submission,
data=request.data,
context={"ignore_submission": True, "request": request},
partial=True,
)
if serializer.is_valid():
serializer.save()
response_data = serializer.data
return Response(response_data, status=status.HTTP_200_OK)
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
response_data = {
"error": "Sorry, you are not authorized to access this submission."
}
return Response(response_data, status=status.HTTP_401_UNAUTHORIZED)
@swagger_auto_schema(
methods=["put"],
manual_parameters=[
openapi.Parameter(
name="challenge_pk",
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
description="Challenge ID",
required=True,
)
],
operation_id="update_submission",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"challenge_phase": openapi.Schema(
type=openapi.TYPE_STRING, description="Challenge Phase ID"
),
"submission": openapi.Schema(
type=openapi.TYPE_STRING, description="Submission ID"
),
"stdout": openapi.Schema(
type=openapi.TYPE_STRING,
description="Submission output file content",
),
"stderr": openapi.Schema(
type=openapi.TYPE_STRING,
description="Submission error file content",
),
"submission_status": openapi.Schema(
type=openapi.TYPE_STRING,
description="Final status of submission (can take one of these values): CANCELLED/FAILED/FINISHED",
),
"result": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Submission results in array format."
" API will throw an error if any split and/or metric is missing)",
items=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"split1": openapi.Schema(
type=openapi.TYPE_STRING,
description="dataset split 1 codename",
),
"show_to_participant": openapi.Schema(
type=openapi.TYPE_BOOLEAN,