-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathmodels.py
More file actions
1933 lines (1639 loc) · 60 KB
/
models.py
File metadata and controls
1933 lines (1639 loc) · 60 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
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 logging
import secrets
from datetime import datetime, timedelta
from actstream.actions import follow, is_following
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Count, Q, Sum, TextChoices
from django.db.models.signals import post_delete
from django.db.transaction import on_commit
from django.dispatch import receiver
from django.template.defaultfilters import truncatechars
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import get_valid_filename
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from django_extensions.db.models import TitleSlugDescriptionModel
from guardian.shortcuts import assign_perm, remove_perm
from pictures.models import PictureField
from grandchallenge.algorithms.tasks import update_algorithm_average_duration
from grandchallenge.anatomy.models import BodyStructure
from grandchallenge.charts.specs import stacked_bar
from grandchallenge.components.backends.amazon_sagemaker_endpoint import (
EndpointOrchestrator,
)
from grandchallenge.components.backends.base import duration_to_millicents
from grandchallenge.components.models import ( # noqa: F401
APIMethodChoices,
CIVForObjectMixin,
ComponentImage,
ComponentInterface,
ComponentInterfaceValue,
ComponentJob,
ComponentJobManager,
ImportStatusChoices,
Tarball,
)
from grandchallenge.components.schemas import GPUTypeChoices
from grandchallenge.components.tasks import start_endpoint
from grandchallenge.core.guardian import (
GroupObjectPermissionBase,
UserObjectPermissionBase,
)
from grandchallenge.core.models import FieldChangeMixin, RequestBase, UUIDModel
from grandchallenge.core.storage import (
get_logo_path,
get_social_image_path,
protected_s3_storage,
public_s3_storage,
)
from grandchallenge.core.utils.access_requests import (
AccessRequestHandlingOptions,
process_access_request,
)
from grandchallenge.core.validators import ExtensionValidator
from grandchallenge.forge.models import ForgeAlgorithm, ForgeInterface
from grandchallenge.hanging_protocols.models import HangingProtocolMixin
from grandchallenge.modalities.models import ImagingModality
from grandchallenge.organizations.models import Organization
from grandchallenge.publications.models import Publication
from grandchallenge.subdomains.utils import reverse
from grandchallenge.utilization.models import (
EndpointUtilization,
JobUtilization,
)
from grandchallenge.workstations.models import Workstation
from grandchallenge.workstations.utils import reassign_workstation_permissions
logger = logging.getLogger(__name__)
def annotate_input_output_counts(queryset, inputs=None, outputs=None):
return queryset.annotate(
input_count=Count("inputs", distinct=True),
output_count=Count("outputs", distinct=True),
relevant_input_count=Count(
"inputs",
filter=Q(inputs__in=inputs) if inputs is not None else Q(),
distinct=True,
),
relevant_output_count=Count(
"outputs",
filter=Q(outputs__in=outputs) if outputs is not None else Q(),
distinct=True,
),
)
class AlgorithmInterfaceManager(models.Manager):
def create(
self,
*,
inputs,
outputs,
**kwargs,
):
if not inputs or not outputs:
raise ValidationError(
"An interface must have at least one input and one output."
)
obj = get_existing_interface_for_inputs_and_outputs(
inputs=inputs, outputs=outputs
)
if not obj:
obj = super().create(**kwargs)
obj.inputs.set(inputs)
obj.outputs.set(outputs)
return obj
def delete(self):
raise NotImplementedError("Bulk delete is not allowed.")
class AlgorithmInterface(UUIDModel):
inputs = models.ManyToManyField(
to=ComponentInterface,
related_name="inputs",
through="algorithms.AlgorithmInterfaceInput",
)
outputs = models.ManyToManyField(
to=ComponentInterface,
related_name="outputs",
through="algorithms.AlgorithmInterfaceOutput",
)
objects = AlgorithmInterfaceManager()
@cached_property
def forge_model(self):
return ForgeInterface(
inputs=[socket.forge_model for socket in self.inputs.all()],
outputs=[socket.forge_model for socket in self.outputs.all()],
)
class Meta:
ordering = ("created",)
def delete(self, *args, **kwargs):
raise ValidationError("AlgorithmInterfaces cannot be deleted.")
class AlgorithmInterfaceInput(models.Model):
input = models.ForeignKey(ComponentInterface, on_delete=models.CASCADE)
interface = models.ForeignKey(AlgorithmInterface, on_delete=models.CASCADE)
class Meta:
unique_together = (("input", "interface"),)
class AlgorithmInterfaceOutput(models.Model):
output = models.ForeignKey(ComponentInterface, on_delete=models.CASCADE)
interface = models.ForeignKey(AlgorithmInterface, on_delete=models.CASCADE)
class Meta:
unique_together = (("output", "interface"),)
def get_existing_interface_for_inputs_and_outputs(
*, inputs, outputs, model=AlgorithmInterface
):
annotated_qs = annotate_input_output_counts(
model.objects.all(), inputs=inputs, outputs=outputs
)
try:
return annotated_qs.get(
relevant_input_count=len(inputs),
relevant_output_count=len(outputs),
input_count=len(inputs),
output_count=len(outputs),
)
except ObjectDoesNotExist:
return None
class AlgorithmQuerySet(models.QuerySet):
def with_user_roles(self, *, user):
User = get_user_model() # noqa: N806
return self.annotate(
user_is_algorithm_editor=models.Exists(
User.objects.filter(
groups=models.OuterRef("editors_group"),
pk=user.pk,
)
),
user_is_algorithm_user=models.Exists(
User.objects.filter(
groups=models.OuterRef("users_group"),
pk=user.pk,
)
),
)
class Algorithm(UUIDModel, TitleSlugDescriptionModel, HangingProtocolMixin):
GPUTypeChoices = GPUTypeChoices
editors_group = models.OneToOneField(
Group,
on_delete=models.PROTECT,
editable=False,
related_name="editors_of_algorithm",
)
users_group = models.OneToOneField(
Group,
on_delete=models.PROTECT,
editable=False,
related_name="users_of_algorithm",
)
logo = PictureField(
upload_to=get_logo_path,
storage=public_s3_storage,
aspect_ratios=["1/1"],
width_field="logo_width",
height_field="logo_height",
max_length=255,
)
logo_width = models.PositiveSmallIntegerField(editable=False, null=True)
logo_height = models.PositiveSmallIntegerField(editable=False, null=True)
social_image = PictureField(
upload_to=get_social_image_path,
storage=public_s3_storage,
blank=True,
help_text="An image for this algorithm which is displayed when you post the link for this algorithm on social media. Should have a resolution of 640x320 px (1280x640 px for best display).",
aspect_ratios=[None],
width_field="social_image_width",
height_field="social_image_height",
max_length=255,
)
social_image_width = models.PositiveSmallIntegerField(
editable=False, null=True
)
social_image_height = models.PositiveSmallIntegerField(
editable=False, null=True
)
workstation = models.ForeignKey(
"workstations.Workstation", on_delete=models.PROTECT
)
workstation_config = models.ForeignKey(
"workstation_configs.WorkstationConfig",
null=True,
blank=True,
on_delete=models.SET_NULL,
)
optional_hanging_protocols = models.ManyToManyField(
"hanging_protocols.HangingProtocol",
through="OptionalHangingProtocolAlgorithm",
related_name="optional_for_algorithm",
blank=True,
help_text="Optional alternative hanging protocols for this algorithm",
)
public = models.BooleanField(
default=False,
help_text=(
"Should this algorithm be visible to all users on the algorithm "
"overview page? This does not grant all users permission to use "
"this algorithm. Users will still need to be added to the "
"algorithm users group in order to do that."
),
)
access_request_handling = models.CharField(
max_length=25,
choices=AccessRequestHandlingOptions.choices,
default=AccessRequestHandlingOptions.MANUAL_REVIEW,
help_text=("How would you like to handle access requests?"),
)
detail_page_markdown = models.TextField(blank=True)
job_create_page_markdown = models.TextField(blank=True)
additional_terms_markdown = models.TextField(
blank=True,
help_text=(
"By using this algorithm, users agree to the site wide "
"terms of service. If your algorithm has any additional "
"terms of usage, define them here."
),
)
interfaces = models.ManyToManyField(
to=AlgorithmInterface,
related_name="algorithm_interfaces",
through="algorithms.AlgorithmAlgorithmInterface",
)
publications = models.ManyToManyField(
Publication,
blank=True,
help_text="The publications associated with this algorithm",
)
modalities = models.ManyToManyField(
ImagingModality,
blank=True,
help_text="The imaging modalities supported by this algorithm",
)
structures = models.ManyToManyField(
BodyStructure,
blank=True,
help_text="The structures supported by this algorithm",
)
organizations = models.ManyToManyField(
Organization,
blank=True,
help_text="The organizations associated with this algorithm",
related_name="algorithms",
)
minimum_credits_per_job = models.PositiveIntegerField(
default=20,
help_text=(
"The minimum number of credits that are required for each execution of this algorithm. "
"The actual number of credits required may be higher than this depending on the "
"algorithms configuration."
),
validators=[
MinValueValidator(limit_value=20),
MaxValueValidator(limit_value=1000),
],
)
time_limit = models.PositiveIntegerField(
default=60 * 60,
help_text="Time limit for inference jobs in seconds",
validators=[
MinValueValidator(
limit_value=settings.COMPONENTS_MINIMUM_JOB_DURATION
),
MaxValueValidator(
limit_value=settings.COMPONENTS_MAXIMUM_JOB_DURATION
),
],
)
job_requires_gpu_type = models.CharField(
max_length=4,
blank=True,
default=GPUTypeChoices.NO_GPU,
choices=GPUTypeChoices.choices,
help_text="What GPU to attach to this algorithms inference jobs",
)
job_requires_memory_gb = models.PositiveSmallIntegerField(
default=8,
help_text="How much main memory (DRAM) to assign to this algorithms inference jobs",
)
average_duration = models.DurationField(
null=True,
default=None,
editable=False,
help_text="The average duration of successful jobs.",
)
repo_name = models.CharField(blank=True, max_length=512)
recurse_submodules = models.BooleanField(
default=False,
help_text="Do a recursive git pull when a GitHub repo is linked to this algorithm.",
)
highlight = models.BooleanField(
default=False,
help_text="Should this algorithm be advertised on the home page?",
)
contact_email = models.EmailField(
blank=True,
help_text="This email will be listed as the contact email for the algorithm and will be visible to all users of Grand Challenge.",
)
display_editors = models.BooleanField(
null=True,
blank=True,
help_text="Should the editors of this algorithm be listed on the information page?",
)
summary = models.TextField(
blank=True,
help_text="Briefly describe your algorithm and how it was developed.",
)
mechanism = models.TextField(
blank=True,
help_text="Provide a short technical description of your algorithm.",
)
validation_and_performance = models.TextField(
blank=True,
help_text="If you have performance metrics about your algorithm, you can report them here.",
)
uses_and_directions = models.TextField(
blank=True,
default="This algorithm was developed for research purposes only.",
help_text="Describe what your algorithm can be used for, but also what it should not be used for.",
)
warnings = models.TextField(
blank=True,
help_text="Describe potential risks and inappropriate settings for using the algorithm.",
)
common_error_messages = models.TextField(
blank=True,
help_text="Describe common error messages a user might encounter when trying out your algorithm and provide solutions for them.",
)
editor_notes = models.TextField(
blank=True,
help_text="Add internal notes such as the deployed version number, code and data locations, etc. Only visible to editors.",
)
objects = AlgorithmQuerySet.as_manager()
class Meta(UUIDModel.Meta, TitleSlugDescriptionModel.Meta):
ordering = ("created",)
permissions = [("execute_algorithm", "Can execute algorithm")]
constraints = [
models.UniqueConstraint(
fields=["repo_name"],
name="unique_repo_name",
condition=~Q(repo_name=""),
)
]
def __str__(self):
return f"{self.title}"
def get_absolute_url(self):
return reverse("algorithms:detail", kwargs={"slug": self.slug})
@property
def api_url(self) -> str:
return reverse("api:algorithm-detail", kwargs={"pk": self.pk})
@property
def algorithm_interfaces_locked(self):
if self.reader_study_algorithm_implementations.exists():
return True
else:
return False
@property
def algorithm_interfaces_locked_message(self):
return (
"Interfaces cannot be changed because this is an implementation of a reader study algorithm. "
"Please contact support if this algorithm requires changes to its "
"interfaces."
)
def save(self, *args, **kwargs):
adding = self._state.adding
if adding:
self.create_groups()
self.workstation_id = (
self.workstation_id or self.default_workstation.pk
)
super().save(*args, **kwargs)
self.assign_permissions()
reassign_workstation_permissions(
groups=(self.users_group, self.editors_group),
workstation=self.workstation,
)
def create_groups(self):
self.editors_group = Group.objects.create(
name=f"{self._meta.app_label}_{self._meta.model_name}_{self.pk}_editors"
)
self.users_group = Group.objects.create(
name=f"{self._meta.app_label}_{self._meta.model_name}_{self.pk}_users"
)
def assign_permissions(self):
# Editors and users can view this algorithm
assign_perm("view_algorithm", self.editors_group, self)
assign_perm("view_algorithm", self.users_group, self)
# Editors and users can execute this algorithm
assign_perm("execute_algorithm", self.editors_group, self)
assign_perm("execute_algorithm", self.users_group, self)
# Editors can change this algorithm
assign_perm("change_algorithm", self.editors_group, self)
reg_and_anon = Group.objects.get(
name=settings.REGISTERED_AND_ANON_USERS_GROUP_NAME
)
if self.public:
assign_perm("view_algorithm", reg_and_anon, self)
else:
remove_perm("view_algorithm", reg_and_anon, self)
@cached_property
def active_image(self):
"""
Returns
-------
The desired version for this algorithm or None
"""
try:
return (
self.algorithm_container_images.executable_images()
.filter(is_desired_version=True)
.get()
)
except ObjectDoesNotExist:
return None
@cached_property
def active_model(self):
"""
Returns
-------
The desired model version for this algorithm or None
"""
try:
return self.algorithm_models.filter(is_desired_version=True).get()
except ObjectDoesNotExist:
return None
@cached_property
def credits_per_job(self):
job = Job(
algorithm_image=self.active_image,
time_limit=self.time_limit,
requires_gpu_type=self.job_requires_gpu_type,
requires_memory_gb=self.job_requires_memory_gb,
)
job.init_credits_consumed()
return job.credits_consumed
@property
def image_upload_in_progress(self):
return self.algorithm_container_images.filter(
import_status__in=(
ImportStatusChoices.STARTED,
ImportStatusChoices.QUEUED,
)
).exists()
@property
def model_upload_in_progress(self):
return self.algorithm_models.filter(
import_status__in=(ImportStatusChoices.INITIALIZED,)
).exists()
@cached_property
def default_workstation(self):
"""
Returns the default workstation, creating it if it does not already
exist.
"""
w, created = Workstation.objects.get_or_create(
slug=settings.DEFAULT_WORKSTATION_SLUG
)
if created:
w.title = settings.DEFAULT_WORKSTATION_SLUG
w.save()
return w
@property
def algorithm_interface_manager(self):
return self.interfaces
@property
def algorithm_interface_through_model_manager(self):
return AlgorithmAlgorithmInterface.objects.filter(algorithm=self)
@property
def additional_inputs_field(self):
return None
@property
def additional_outputs_field(self):
return None
@property
def algorithm_interface_create_url(self):
return reverse(
"algorithms:interface-create", kwargs={"slug": self.slug}
)
@property
def algorithm_interface_delete_viewname(self):
return "algorithms:interface-delete"
@property
def algorithm_interface_list_url(self):
return reverse("algorithms:interface-list", kwargs={"slug": self.slug})
@cached_property
def forge_model(self):
return ForgeAlgorithm(
title=self.title,
slug=self.slug,
url=self.get_absolute_url(),
algorithm_interfaces=[
interface.forge_model for interface in self.interfaces.all()
],
)
def is_editor(self, user):
return user.groups.filter(pk=self.editors_group.pk).exists()
def add_editor(self, user):
return user.groups.add(self.editors_group)
def remove_editor(self, user):
return user.groups.remove(self.editors_group)
def is_user(self, user):
return user.groups.filter(pk=self.users_group.pk).exists()
def add_user(self, user):
return user.groups.add(self.users_group)
def remove_user(self, user):
return user.groups.remove(self.users_group)
@cached_property
def linked_component_interfaces(self):
return (
ComponentInterface.objects.filter(
Q(inputs__in=self.interfaces.all())
| Q(outputs__in=self.interfaces.all())
)
.distinct()
.order_by("pk")
)
@cached_property
def user_statistics(self):
return (
get_user_model()
.objects.select_related("verification", "user_profile")
.annotate(
job_count=Count(
"pk", filter=Q(job__algorithm_image__algorithm=self)
)
)
.filter(job_count__gt=0)
.order_by("-job_count")[:10]
)
@property
def usage_chart_statuses(self):
"""What statuses should be included on the chart"""
return [Job.SUCCESS, Job.CANCELLED, Job.FAILURE]
@cached_property
def usage_statistics(self):
"""The number of jobs for this algorithm faceted by month and status"""
return (
Job.objects.filter(
algorithm_image__algorithm=self,
status__in=self.usage_chart_statuses,
)
.values("status", "created__year", "created__month")
.annotate(job_count=Count("status"))
.order_by("created__year", "created__month", "status")
)
@cached_property
def usage_chart(self):
"""Vega lite chart of the usage of this algorithm"""
choices = dict(Job.status.field.choices)
domain = {
choice: choices[choice] for choice in self.usage_chart_statuses
}
return stacked_bar(
values=[
{
"Status": datum["status"],
"Month": datetime(
datum["created__year"], datum["created__month"], 1
).isoformat(),
"Jobs Count": datum["job_count"],
}
for datum in self.usage_statistics
],
lookup="Jobs Count",
title="Algorithm Usage",
facet="Status",
domain=domain,
)
@cached_property
def public_test_case(self):
try:
return self.active_image.job_set.filter(
status=Job.SUCCESS,
public=True,
algorithm_model=self.active_model,
).exists()
except AttributeError:
return False
def form_field_label(self):
title = f"{self.title}"
title += f" (Active image: {' - '.join(filter(None, [truncatechars(self.active_image_comment, 25), str(self.active_image_pk)]))})"
if self.active_model_pk:
title += f" (Active model: {' - '.join(filter(None, [truncatechars(self.active_model_comment, 25), str(self.active_model_pk)]))})"
else:
title += " (Active model: None)"
return title
class AlgorithmAlgorithmInterface(models.Model):
algorithm = models.ForeignKey(Algorithm, on_delete=models.CASCADE)
interface = models.ForeignKey(AlgorithmInterface, on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["algorithm", "interface"],
name="unique_algorithm_interface_combination",
),
]
def clean(self):
super().clean()
if self.algorithm.algorithm_interfaces_locked:
raise ValidationError(
self.algorithm.algorithm_interfaces_locked_message
)
def save(self, *args, **kwargs):
self.clean()
return super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.clean()
return super().delete(*args, **kwargs)
def __str__(self):
return str(self.interface)
class AlgorithmUserObjectPermission(UserObjectPermissionBase):
allowed_permissions = frozenset()
content_object = models.ForeignKey(Algorithm, on_delete=models.CASCADE)
class AlgorithmGroupObjectPermission(GroupObjectPermissionBase):
allowed_permissions = frozenset(
{"view_algorithm", "execute_algorithm", "change_algorithm"}
)
content_object = models.ForeignKey(Algorithm, on_delete=models.CASCADE)
@receiver(post_delete, sender=Algorithm)
def delete_algorithm_groups_hook(*_, instance: Algorithm, using, **__):
"""
Deletes the related groups.
We use a signal rather than overriding delete() to catch usages of
bulk_delete.
"""
try:
instance.editors_group.delete(using=using)
except ObjectDoesNotExist:
pass
try:
instance.users_group.delete(using=using)
except ObjectDoesNotExist:
pass
class AlgorithmUserCreditManager(models.QuerySet):
def active_credits(self):
today = now().date()
return self.filter(
valid_from__lte=today,
valid_until__gte=today,
)
class AlgorithmUserCredit(UUIDModel):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=False,
on_delete=models.CASCADE,
help_text="The user who these credits are applied to",
)
algorithm = models.ForeignKey(
Algorithm,
blank=False,
on_delete=models.CASCADE,
help_text="The algorithm that these credits can be used with",
)
credits = models.PositiveIntegerField(
blank=False,
help_text="The credits that a user can spend during the validity period on running this algorithm",
)
valid_from = models.DateField(
blank=False,
help_text="Inclusive date from which these credits are valid",
)
valid_until = models.DateField(
blank=False,
help_text="Inclusive date until these credits are valid",
)
comment = models.TextField(
blank=False,
help_text="Who agreed to these credits have been assigned and where the costs are coming from",
)
objects = AlgorithmUserCreditManager.as_manager()
class Meta:
unique_together = ("user", "algorithm")
def __str__(self):
return f"Credits for {self.user} for {self.algorithm}"
@property
def is_active(self):
today = now().date()
return self.valid_from <= today and self.valid_until >= today
def clean(self):
super().clean()
try:
if self.user.username == settings.ANONYMOUS_USER_NAME:
raise ValidationError(
{"user": "The anonymous user cannot be assigned credits"}
)
except ObjectDoesNotExist:
raise ValidationError("The user must be set")
try:
if self.valid_until < self.valid_from:
raise ValidationError(
{
"valid_from": "This must be less than or equal to Valid Until",
"valid_until": "This must be greater than or equal to Valid From",
}
)
except TypeError:
raise ValidationError("The validity period must be set")
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
class AlgorithmImage(UUIDModel, ComponentImage):
algorithm = models.ForeignKey(
Algorithm,
on_delete=models.PROTECT,
related_name="algorithm_container_images",
)
class Meta(UUIDModel.Meta, ComponentImage.Meta):
ordering = ("created",)
permissions = [
("download_algorithmimage", "Can download algorithm image")
]
def get_absolute_url(self):
return reverse(
"algorithms:image-detail",
kwargs={"slug": self.algorithm.slug, "pk": self.pk},
)
@property
def import_status_url(self) -> str:
return reverse(
"algorithms:image-import-status-detail",
kwargs={"slug": self.algorithm.slug, "pk": self.pk},
)
@property
def build_status_url(self) -> str:
return reverse(
"algorithms:image-build-status-detail",
kwargs={"slug": self.algorithm.slug, "pk": self.pk},
)
@property
def api_url(self) -> str:
return reverse("api:algorithms-image-detail", kwargs={"pk": self.pk})
def get_remaining_complimentary_jobs(self, *, user):
if self.algorithm.is_editor(user=user):
return max(
settings.ALGORITHM_IMAGES_COMPLIMENTARY_EDITOR_JOBS
- Job.objects.filter(
algorithm_image=self, is_complimentary=True
).count(),
0,
)
else:
return 0
def get_remaining_non_complimentary_jobs(self, *, user):
try:
credits_left = self.get_remaining_specific_credits(
user=user, algorithm=self.algorithm
)
except ObjectDoesNotExist:
credits_left = self.get_remaining_general_credits(user=user)
return max(credits_left, 0) // max(self.algorithm.credits_per_job, 1)
@staticmethod
def get_remaining_specific_credits(*, user, algorithm):
user_credit = AlgorithmUserCredit.objects.active_credits().get(
user=user,
algorithm=algorithm,
)
spent_credits = Job.objects.filter(
creator=user_credit.user,
is_complimentary=False,
created__date__gte=user_credit.valid_from,
created__date__lte=user_credit.valid_until,
algorithm_image__algorithm=user_credit.algorithm,
).aggregate(
total=Sum("credits_consumed", default=0),
)
return user_credit.credits - spent_credits["total"]
@staticmethod
def get_remaining_general_credits(*, user):
if user.username == settings.ANONYMOUS_USER_NAME:
return 0
user_credits = settings.ALGORITHMS_GENERAL_CREDITS_PER_MONTH_PER_USER
user_algorithms_with_active_credits = (
AlgorithmUserCredit.objects.active_credits()
.filter(
user=user,
)
.values_list("algorithm__pk", flat=True)
)
spent_credits = (
Job.objects.filter(
creator=user,
is_complimentary=False,
created__gte=timezone.now() - relativedelta(months=1),
)
.exclude(
algorithm_image__algorithm__pk__in=user_algorithms_with_active_credits
)
.aggregate(
total=Sum("credits_consumed", default=0),
)
)
return user_credits - spent_credits["total"]
def get_remaining_jobs(self, *, user):
return self.get_remaining_non_complimentary_jobs(
user=user
) + self.get_remaining_complimentary_jobs(user=user)
def save(self, *args, **kwargs):
adding = self._state.adding
super().save(*args, **kwargs)
if adding:
self.assign_permissions()
def assign_permissions(self):
# Editors and users can view this algorithm image
assign_perm("view_algorithmimage", self.algorithm.editors_group, self)
# Editors can change this algorithm image
assign_perm(
"change_algorithmimage", self.algorithm.editors_group, self
)
def get_peer_images(self):
return AlgorithmImage.objects.filter(algorithm=self.algorithm)
def mark_desired_version(self):
if (
self.algorithm.reader_study_algorithm_implementations.exists()
and self.api_method != APIMethodChoices.INVOKE
):
raise ValidationError(
"Only algorithm images that implement the invoke API can be activated because this is an implementation of a reader study algorithm."
)
super().mark_desired_version()
class AlgorithmImageUserObjectPermission(UserObjectPermissionBase):
allowed_permissions = frozenset()
content_object = models.ForeignKey(
AlgorithmImage, on_delete=models.CASCADE
)
class AlgorithmImageGroupObjectPermission(GroupObjectPermissionBase):
allowed_permissions = frozenset(
{
"change_algorithmimage",