-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathmodels.py
More file actions
2802 lines (2493 loc) · 90 KB
/
models.py
File metadata and controls
2802 lines (2493 loc) · 90 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 json
import logging
import re
from enum import Enum
from json import JSONDecodeError
from pathlib import Path
from tempfile import NamedTemporaryFile
from billiard.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded
from celery import signature
from django import forms
from django.conf import settings
from django.core.exceptions import (
MultipleObjectsReturned,
ObjectDoesNotExist,
ValidationError,
)
from django.core.files import File
from django.core.files.base import ContentFile
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
RegexValidator,
)
from django.db import models, transaction
from django.db.models import IntegerChoices, QuerySet
from django.db.transaction import on_commit
from django.forms import ModelChoiceField
from django.template.defaultfilters import truncatewords
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from django.utils.text import get_valid_filename
from django.utils.translation import gettext_lazy as _
from django_deprecate_fields import deprecate_field
from django_extensions.db.fields import AutoSlugField
from panimg.models import MAXIMUM_SEGMENTS_LENGTH
from grandchallenge.cases.models import (
DICOMImageSetUpload,
Image,
ImageFile,
RawImageUploadSession,
)
from grandchallenge.charts.specs import components_line
from grandchallenge.components.backends.exceptions import (
CINotAllowedException,
CIVNotEditableException,
)
from grandchallenge.components.schemas import (
GPUTypeChoices,
generate_component_json_schema,
)
from grandchallenge.components.tasks import (
_repo_login_and_run,
assign_docker_image_from_upload,
deprovision_job,
provision_job,
validate_docker_image,
)
from grandchallenge.components.validators import (
validate_biom_format,
validate_newick_tree_format,
validate_no_slash_at_ends,
validate_relative_path_not_reserved,
validate_safe_path,
)
from grandchallenge.core.celery import acks_late_2xlarge_task
from grandchallenge.core.error_handlers import (
DICOMImageSetUploadErrorHandler,
EvaluationCIVErrorHandler,
FallbackCIVValidationErrorHandler,
JobCIVErrorHandler,
RawImageUploadSessionErrorHandler,
UserUploadCIVErrorHandler,
)
from grandchallenge.core.models import FieldChangeMixin, UUIDModel
from grandchallenge.core.storage import (
private_s3_storage,
protected_s3_storage,
)
from grandchallenge.core.utils.error_messages import (
format_validation_error_message,
)
from grandchallenge.core.validators import (
ExtensionValidator,
JSONSchemaValidator,
JSONValidator,
MimeTypeValidator,
)
from grandchallenge.uploads.models import UserUpload
from grandchallenge.uploads.validators import validate_gzip_mimetype
from grandchallenge.workstation_configs.models import (
OVERLAY_SEGMENTS_SCHEMA,
LookUpTable,
)
logger = logging.getLogger(__name__)
class InterfaceKindChoices(models.TextChoices):
"""Interface kind choices."""
STRING = "STR", _("String")
INTEGER = "INT", _("Integer")
FLOAT = "FLT", _("Float")
BOOL = "BOOL", _("Bool")
ANY = "JSON", _("Anything")
CHART = "CHART", _("Chart")
# Annotation Types
TWO_D_BOUNDING_BOX = "2DBB", _("2D bounding box")
MULTIPLE_TWO_D_BOUNDING_BOXES = "M2DB", _("Multiple 2D bounding boxes")
DISTANCE_MEASUREMENT = "DIST", _("Distance measurement")
MULTIPLE_DISTANCE_MEASUREMENTS = (
"MDIS",
_("Multiple distance measurements"),
)
POINT = "POIN", _("Point")
MULTIPLE_POINTS = "MPOI", _("Multiple points")
POLYGON = "POLY", _("Polygon")
MULTIPLE_POLYGONS = "MPOL", _("Multiple polygons")
LINE = "LINE", _("Line")
MULTIPLE_LINES = "MLIN", _("Multiple lines")
ANGLE = "ANGL", _("Angle")
MULTIPLE_ANGLES = "MANG", _("Multiple angles")
ELLIPSE = "ELLI", _("Ellipse")
MULTIPLE_ELLIPSES = "MELL", _("Multiple ellipses")
THREE_POINT_ANGLE = "3ANG", _("Three-point angle")
MULTIPLE_THREE_POINT_ANGLES = "M3AN", _("Multiple three-point angles")
# Registration types
AFFINE_TRANSFORM_REGISTRATION = "ATRG", _("Affine transform registration")
# Choice Types
CHOICE = "CHOI", _("Choice")
MULTIPLE_CHOICE = "MCHO", _("Multiple choice")
# Image types
PANIMG_IMAGE = "IMG", _("Image")
PANIMG_SEGMENTATION = "SEG", _("Segmentation")
PANIMG_HEAT_MAP = "HMAP", _("Heat Map")
PANIMG_DISPLACEMENT_FIELD = "DSPF", _("Displacement field")
DICOM_IMAGE_SET = "DCMIS", _("DICOM Image Set")
# File types
PDF = "PDF", _("PDF file")
SQREG = "SQREG", _("SQREG file")
THUMBNAIL_JPG = "JPEG", _("Thumbnail jpg")
THUMBNAIL_PNG = "PNG", _("Thumbnail png")
OBJ = "OBJ", _("OBJ file")
MP4 = "MP4", _("MP4 file")
NEWICK = "NEWCK", _("Newick tree-format file")
BIOM = "BIOM", _("BIOM format")
# Legacy support
CSV = "CSV", _("CSV file")
ZIP = "ZIP", _("ZIP file")
class InterfaceSuperKindChoices(models.TextChoices):
IMAGE = "I", "Image"
FILE = "F", "File"
VALUE = "V", "Value"
class InterfaceKinds(set, Enum):
r"""Interface kind sets.
.. exec_code::
:hide_code:
import json
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from grandchallenge.components.models import InterfaceKinds
from grandchallenge.components.models import INTERFACE_KIND_JSON_EXAMPLES
print("Interface kinds that are images:\n")
for member in InterfaceKinds.image:
print(" -", member.label)
print("\n")
print("Interface kinds that are files:\n")
for member in InterfaceKinds.file:
print(" -", member.label)
print("\n")
print("Interface kinds that are json serializable:\n")
for member in InterfaceKinds.json:
print(" -", member.label)
print("\n")
for key, example in INTERFACE_KIND_JSON_EXAMPLES.items():
title = f"Example JSON file contents for {key.label}"
if example.extra_info:
title += f" ({example.extra_info})"
print(f"{title}:")
print(json.dumps(example.value, indent=2))
print("")
"""
json = {
InterfaceKindChoices.STRING,
InterfaceKindChoices.INTEGER,
InterfaceKindChoices.FLOAT,
InterfaceKindChoices.BOOL,
InterfaceKindChoices.TWO_D_BOUNDING_BOX,
InterfaceKindChoices.MULTIPLE_TWO_D_BOUNDING_BOXES,
InterfaceKindChoices.DISTANCE_MEASUREMENT,
InterfaceKindChoices.MULTIPLE_DISTANCE_MEASUREMENTS,
InterfaceKindChoices.POINT,
InterfaceKindChoices.MULTIPLE_POINTS,
InterfaceKindChoices.POLYGON,
InterfaceKindChoices.MULTIPLE_POLYGONS,
InterfaceKindChoices.CHOICE,
InterfaceKindChoices.MULTIPLE_CHOICE,
InterfaceKindChoices.ANY,
InterfaceKindChoices.CHART,
InterfaceKindChoices.LINE,
InterfaceKindChoices.MULTIPLE_LINES,
InterfaceKindChoices.ANGLE,
InterfaceKindChoices.MULTIPLE_ANGLES,
InterfaceKindChoices.ELLIPSE,
InterfaceKindChoices.MULTIPLE_ELLIPSES,
InterfaceKindChoices.THREE_POINT_ANGLE,
InterfaceKindChoices.MULTIPLE_THREE_POINT_ANGLES,
InterfaceKindChoices.AFFINE_TRANSFORM_REGISTRATION,
}
image = {
InterfaceKindChoices.PANIMG_IMAGE,
InterfaceKindChoices.PANIMG_HEAT_MAP,
InterfaceKindChoices.PANIMG_SEGMENTATION,
InterfaceKindChoices.PANIMG_DISPLACEMENT_FIELD,
InterfaceKindChoices.DICOM_IMAGE_SET,
}
file = {
InterfaceKindChoices.CSV,
InterfaceKindChoices.ZIP,
InterfaceKindChoices.PDF,
InterfaceKindChoices.SQREG,
InterfaceKindChoices.THUMBNAIL_JPG,
InterfaceKindChoices.THUMBNAIL_PNG,
InterfaceKindChoices.OBJ,
InterfaceKindChoices.MP4,
InterfaceKindChoices.NEWICK,
InterfaceKindChoices.BIOM,
}
# Interfaces that can only be displayed in isolation.
mandatory_isolation = {
InterfaceKindChoices.CHART,
InterfaceKindChoices.PDF,
InterfaceKindChoices.THUMBNAIL_JPG,
InterfaceKindChoices.THUMBNAIL_PNG,
InterfaceKindChoices.MP4,
}
# Interfaces that cannot be displayed.
undisplayable = {
InterfaceKindChoices.CSV,
InterfaceKindChoices.ZIP,
InterfaceKindChoices.OBJ,
InterfaceKindChoices.NEWICK,
InterfaceKindChoices.BIOM,
}
panimg = {
InterfaceKindChoices.PANIMG_IMAGE,
InterfaceKindChoices.PANIMG_HEAT_MAP,
InterfaceKindChoices.PANIMG_SEGMENTATION,
InterfaceKindChoices.PANIMG_DISPLACEMENT_FIELD,
}
class OverlaySegmentsMixin(models.Model):
overlay_segments = models.JSONField(
blank=True,
default=list,
help_text=(
"The schema that defines how categories of values in the overlay images are differentiated. "
'Example usage: [{"name": "background", "visible": true, "voxel_value": 0},'
'{"name": "tissue", "visible": true, "voxel_value": 1}]. '
"If a categorical overlay is shown, "
"it is possible to show toggles to change the visibility of the different overlay categories. "
"To do so, configure the categories that should be displayed. "
'For example: [{"name": "Level 0", "visible": false, "voxel_value": 0].'
),
validators=[JSONValidator(schema=OVERLAY_SEGMENTS_SCHEMA)],
)
look_up_table = models.ForeignKey(
to=LookUpTable,
blank=True,
null=True,
on_delete=models.SET_NULL,
help_text="The look-up table that is applied when an overlay image is first shown",
)
@property
def overlay_segments_allowed_values(self):
allowed_values = {x["voxel_value"] for x in self.overlay_segments}
# An implicit background value of 0 is always allowed, this saves the
# user having to declare it and the annotator mark it
allowed_values.add(0)
return allowed_values
@property
def overlay_segments_is_contiguous(self):
values = sorted(list(self.overlay_segments_allowed_values))
return all(
values[i] - values[i - 1] == 1 for i in range(1, len(values))
)
def _validate_voxel_values(self, image):
if not self.overlay_segments:
return
if image.segments is None:
raise ValidationError(
"Image segments could not be determined, ensure the voxel values "
"are integers and that it contains no more than "
f"{MAXIMUM_SEGMENTS_LENGTH} segments. Ensure the image has the "
"minimum and maximum voxel values set as tags if the image is a TIFF "
"file."
)
invalid_values = (
set(image.segments) - self.overlay_segments_allowed_values
)
if invalid_values:
raise ValidationError(
f"The valid voxel values for this segmentation are: "
f"{self.overlay_segments_allowed_values}. This segmentation is "
f"invalid as it contains the voxel values: {invalid_values}."
)
def _validate_vector_field(self, image: Image):
if len(image.shape) != 4:
raise ValidationError(
"Deformation and displacement must be 4D images."
)
if image.shape_without_color != image.shape:
raise ValidationError(
"Deformation and displacement fields cannot have a color component."
)
if image.shape[0] != 3:
raise ValidationError(
"Deformation and displacement field's 4th dimension "
"must be a 3-component vector."
)
class Meta:
abstract = True
class ComponentInterface(OverlaySegmentsMixin):
Kind = InterfaceKindChoices
SuperKind = InterfaceSuperKindChoices
title = models.CharField(
max_length=255,
help_text="Human readable name of this input/output field.",
unique=True,
)
slug = AutoSlugField(populate_from="title")
description = models.TextField(
blank=True, help_text="Description of this input/output field."
)
default_value = models.JSONField(
blank=True,
null=True,
default=None,
help_text="Default value for this field, only valid for inputs.",
)
schema = models.JSONField(
default=dict,
blank=True,
help_text=(
"Additional JSON schema that the values for this interface must "
"satisfy. See https://json-schema.org/. "
"Only Draft 7, 6, 4 or 3 are supported."
),
validators=[JSONSchemaValidator()],
)
kind = models.CharField(
blank=False,
max_length=5,
choices=Kind.choices,
help_text=(
"What is the type of this interface? Used to validate interface "
"values and connections between components."
),
)
relative_path = models.CharField(
max_length=255,
help_text=(
"The path to the entity that implements this interface relative "
"to the input or output directory."
),
unique=True,
validators=[
validate_safe_path,
validate_no_slash_at_ends,
validate_relative_path_not_reserved,
# No uuids in path
RegexValidator(
regex=r".*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}.*",
inverse_match=True,
flags=re.IGNORECASE,
),
],
)
store_in_database = models.BooleanField(
default=True,
editable=True,
help_text=(
"Should the value be saved in a database field, "
"only valid for outputs."
),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._overlay_segments_orig = self.overlay_segments
def __str__(self):
return f"{self.title} ({self.get_kind_display()})"
@property
def is_image_kind(self):
return self.kind in InterfaceKinds.image
@property
def is_panimg_kind(self):
return self.kind in InterfaceKinds.panimg
@property
def is_dicom_image_kind(self):
return self.kind == InterfaceKindChoices.DICOM_IMAGE_SET
@property
def is_json_kind(self):
return self.kind in InterfaceKinds.json
@property
def is_file_kind(self):
return self.kind in InterfaceKinds.file
@property
def is_thumbnail_kind(self):
return self.kind in [
InterfaceKindChoices.THUMBNAIL_JPG,
InterfaceKindChoices.THUMBNAIL_PNG,
]
@property
def is_previewable(self):
return self.store_in_database and self.kind in [
InterfaceKindChoices.BOOL,
InterfaceKindChoices.FLOAT,
InterfaceKindChoices.INTEGER,
InterfaceKindChoices.STRING,
]
@property
def json_kind_example(self):
try:
return self.example_value
except ObjectDoesNotExist:
return INTERFACE_KIND_JSON_EXAMPLES.get(self.kind)
@property
def super_kind(self):
if self.is_image_kind:
return InterfaceSuperKindChoices.IMAGE
elif self.is_json_kind and self.store_in_database:
return InterfaceSuperKindChoices.VALUE
else:
return InterfaceSuperKindChoices.FILE
@property
def default_field(self):
if self.super_kind in (
InterfaceSuperKindChoices.FILE,
InterfaceSuperKindChoices.IMAGE,
):
return ModelChoiceField
elif self.kind in {
InterfaceKindChoices.STRING,
InterfaceKindChoices.CHOICE,
}:
return forms.CharField
elif self.kind == InterfaceKindChoices.INTEGER:
return forms.IntegerField
elif self.kind == InterfaceKindChoices.FLOAT:
return forms.FloatField
elif self.kind == InterfaceKindChoices.BOOL:
return forms.BooleanField
else:
return forms.JSONField
@property
def allowed_file_types(self):
"""The allowed file types of the interface that is relevant when uploading"""
try:
return INTERFACE_KIND_TO_ALLOWED_FILE_TYPES[self.kind]
except KeyError as e:
raise RuntimeError(f"Unknown kind {self.kind}") from e
@property
def file_extension(self):
"""The dot filename extension (e.g. '.jpg') of an interface that is relevant when writing"""
try:
return INTERFACE_KIND_TO_FILE_EXTENSION[self.kind]
except KeyError as e:
raise RuntimeError(f"Unknown kind {self.kind}") from e
def create_instance(self, *, image=None, value=None, fileobj=None):
civ = ComponentInterfaceValue.objects.create(interface=self)
if image:
civ.image = image
elif fileobj:
container = File(fileobj)
civ.file.save(Path(self.relative_path).name, container)
elif not self.store_in_database:
civ.file = ContentFile(
json.dumps(value).encode("utf-8"),
name=Path(self.relative_path).name,
)
else:
civ.value = value
civ.full_clean()
civ.save()
return civ
def clean(self):
super().clean()
self._clean_overlay_segments()
self._clean_store_in_database()
self._clean_relative_path()
self._clean_example_value()
self._clean_default_value()
def _clean_overlay_segments(self):
from grandchallenge.reader_studies.models import Question
if (
self.kind == InterfaceKindChoices.PANIMG_SEGMENTATION
and not self.overlay_segments
):
raise ValidationError(
"Overlay segments must be set for this interface"
)
if (
self.kind != InterfaceKindChoices.PANIMG_SEGMENTATION
and self.overlay_segments
):
raise ValidationError(
"Overlay segments should only be set for segmentations"
)
if not self.overlay_segments_is_contiguous:
raise ValidationError(
"Voxel values for overlay segments must be contiguous."
)
if (
self.pk is not None
and self._overlay_segments_orig != self.overlay_segments
and not self._overlay_segments_preserved
and (
ComponentInterfaceValue.objects.filter(interface=self).exists()
or Question.objects.filter(interface=self).exists()
)
):
raise ValidationError(
"Overlay segments cannot be changed, as values or questions "
"for this ComponentInterface exist."
)
@property
def _overlay_segments_preserved(self):
orig_overlay_segments = {
tuple(sorted(d.items())) for d in self._overlay_segments_orig
}
new_overlay_segments = {
tuple(sorted(d.items())) for d in self.overlay_segments
}
return orig_overlay_segments <= new_overlay_segments
def _clean_relative_path(self):
if (
self.is_file_kind or self.is_json_kind
) and not self.relative_path.endswith(self.file_extension):
raise ValidationError(
f"Relative path should end with {self.file_extension}"
)
if self.is_image_kind:
if not self.relative_path.startswith("images/"):
raise ValidationError(
"Relative path should start with images/"
)
if Path(self.relative_path).name != Path(self.relative_path).stem:
raise ValidationError("Images should be a directory")
else:
if self.relative_path.startswith("images/"):
raise ValidationError(
"Relative path should not start with images/"
)
def _clean_store_in_database(self):
allow_store_in_database = self.kind in (
InterfaceKinds.json.difference(
{
# These values can be large, so for any new interfaces
# of this type do not allow storing in the database.
InterfaceKindChoices.MULTIPLE_TWO_D_BOUNDING_BOXES,
InterfaceKindChoices.MULTIPLE_DISTANCE_MEASUREMENTS,
InterfaceKindChoices.MULTIPLE_POINTS,
InterfaceKindChoices.MULTIPLE_POLYGONS,
InterfaceKindChoices.MULTIPLE_LINES,
InterfaceKindChoices.MULTIPLE_ANGLES,
InterfaceKindChoices.MULTIPLE_ELLIPSES,
InterfaceKindChoices.MULTIPLE_THREE_POINT_ANGLES,
}
)
)
if self.store_in_database and not allow_store_in_database:
raise ValidationError(
f"Interface {self.kind} objects cannot be stored in the database"
)
def _clean_example_value(self):
try:
self.example_value.full_clean()
except ObjectDoesNotExist:
pass
except ValidationError as error:
raise ValidationError(
f"The example value for this interface is not valid: {error}"
)
def _clean_default_value(self):
if (
self.super_kind == InterfaceSuperKindChoices.FILE
and self.default_value
):
raise ValidationError(
"A socket that requires a file should not have a default value"
)
def validate_against_schema(self, *, value):
"""Validates values against both default and custom schemas"""
schema = generate_component_json_schema(
component_interface=self, required=True
)
JSONValidator(schema=schema)(value=value)
@cached_property
def value_required(self):
value_required = True
if self.kind == InterfaceKindChoices.BOOL:
value_required = False
elif self.super_kind == InterfaceSuperKindChoices.VALUE:
try:
self.validate_against_schema(value=None)
value_required = False
except ValidationError:
pass
return value_required
class Meta:
ordering = ("pk",)
class ComponentInterfaceExampleValue(UUIDModel):
interface = models.OneToOneField(
to=ComponentInterface,
on_delete=models.CASCADE,
related_name="example_value",
)
value = models.JSONField(
null=True,
blank=True,
default=None,
help_text="Example value for an interface",
)
extra_info = models.TextField(
blank=True, help_text="Extra information about the example value"
)
def clean(self):
super().clean()
if self.interface.is_json_kind:
civ = ComponentInterfaceValue(interface=self.interface)
if self.interface.store_in_database:
civ.value = self.value
else:
file = ContentFile(
json.dumps(self.value).encode("utf-8"),
name=f"{self.interface.kind}.json",
)
civ.file = file
civ.full_clean()
else:
raise ValidationError(
"Example value can be set for interfaces of JSON kind only"
)
INTERFACE_KIND_JSON_EXAMPLES = {
InterfaceKindChoices.STRING: ComponentInterfaceExampleValue(
value="Example String"
),
InterfaceKindChoices.INTEGER: ComponentInterfaceExampleValue(value=42),
InterfaceKindChoices.FLOAT: ComponentInterfaceExampleValue(value=42.0),
InterfaceKindChoices.BOOL: ComponentInterfaceExampleValue(value=True),
InterfaceKindChoices.ANY: ComponentInterfaceExampleValue(
value={"key": "value", "None": None}
),
InterfaceKindChoices.CHART: ComponentInterfaceExampleValue(
value={
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"width": 300,
"height": 300,
"data": {
"values": [
{
"target": "Negative",
"prediction": "Negative",
"value": 198,
},
{
"target": "Negative",
"prediction": "Positive",
"value": 9,
},
{
"target": "Positive",
"prediction": "Negative",
"value": 159,
},
{
"target": "Positive",
"prediction": "Positive",
"value": 376,
},
],
"format": {"type": "json"},
},
"layer": [
{
"mark": "rect",
"encoding": {
"y": {"field": "target", "type": "ordinal"},
"x": {"field": "prediction", "type": "ordinal"},
"color": {
"field": "value",
"type": "quantitative",
"title": "Count of Records",
"legend": {
"direction": "vertical",
"gradientLength": 300,
},
},
},
},
{
"mark": "text",
"encoding": {
"y": {"field": "target", "type": "ordinal"},
"x": {"field": "prediction", "type": "ordinal"},
"text": {"field": "value", "type": "quantitative"},
"color": {
"condition": {
"test": "datum['value'] < 40",
"value": "black",
},
"value": "white",
},
},
},
],
"config": {"axis": {"grid": True, "tickBand": "extent"}},
},
extra_info="For more examples, see https://vega.github.io/vega-lite/examples/",
),
InterfaceKindChoices.TWO_D_BOUNDING_BOX: ComponentInterfaceExampleValue(
value={
"name": "Region of interest",
"type": "2D bounding box",
"corners": [
[130.8, 148.8, 0.5],
[69.7, 148.8, 0.5],
[69.7, 73.1, 0.5],
[130.8, 73.1, 0.5],
],
"probability": 0.95,
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.MULTIPLE_TWO_D_BOUNDING_BOXES: ComponentInterfaceExampleValue(
value={
"name": "Regions of interest",
"type": "Multiple 2D bounding boxes",
"boxes": [
{
"name": "ROI 1",
"corners": [
[92.6, 136.0, 0.5],
[54.8, 136.0, 0.5],
[54.8, 95.5, 0.5],
[92.6, 95.5, 0.5],
],
"probability": 0.95,
},
{
"name": "ROI 2",
"corners": [
[92.6, 136.0, 0.5],
[54.8, 136.0, 0.5],
[54.8, 95.5, 0.5],
[92.6, 95.5, 0.5],
],
"probability": 0.92,
},
],
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.DISTANCE_MEASUREMENT: ComponentInterfaceExampleValue(
value={
"name": "Distance between areas",
"type": "Distance measurement",
"start": [59.8, 78.8, 0.5],
"end": [69.4, 143.8, 0.5],
"probability": 0.92,
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.MULTIPLE_DISTANCE_MEASUREMENTS: ComponentInterfaceExampleValue(
value={
"name": "Distances between areas",
"type": "Multiple distance measurements",
"lines": [
{
"name": "Distance 1",
"start": [49.7, 103.3, 0.5],
"end": [55.1, 139.3, 0.5],
"probability": 0.92,
},
{
"name": "Distance 2",
"start": [49.7, 103.3, 0.5],
"end": [55.1, 139.3, 0.5],
"probability": 0.92,
},
],
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.POINT: ComponentInterfaceExampleValue(
value={
"name": "Point of interest",
"type": "Point",
"point": [152.1, 111.0, 0.5],
"probability": 0.92,
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.MULTIPLE_POINTS: ComponentInterfaceExampleValue(
value={
"name": "Points of interest",
"type": "Multiple points",
"points": [
{
"name": "Point 1",
"point": [96.0, 79.8, 0.5],
"probability": 0.92,
},
{
"name": "Point 2",
"point": [130.1, 115.5, 0.5],
"probability": 0.92,
},
],
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.POLYGON: ComponentInterfaceExampleValue(
value={
"name": "Area of interest",
"type": "Polygon",
"seed_point": [76.4, 124.0, 0.5],
"path_points": [
[76.41, 124.01, 0.5],
[76.41, 124.05, 0.5],
[76.42, 124.08, 0.5],
],
"sub_type": "brush",
"groups": [],
"probability": 0.92,
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.MULTIPLE_POLYGONS: ComponentInterfaceExampleValue(
value={
"name": "Areas of interest",
"type": "Multiple polygons",
"polygons": [
{
"name": "Area 1",
"seed_point": [55.82, 90.46, 0.5],
"path_points": [
[55.82, 90.46, 0.5],
[55.93, 90.88, 0.5],
[56.24, 91.19, 0.5],
[56.66, 91.30, 0.5],
],
"sub_type": "brush",
"groups": ["manual"],
"probability": 0.67,
},
{
"name": "Area 2",
"seed_point": [90.22, 96.06, 0.5],
"path_points": [
[90.22, 96.06, 0.5],
[90.33, 96.48, 0.5],
[90.64, 96.79, 0.5],
],
"sub_type": "brush",
"groups": [],
"probability": 0.92,
},
],
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.LINE: ComponentInterfaceExampleValue(
value={
"name": "Some annotation",
"type": "Line",
"seed_points": [[1, 2, 3], [1, 2, 3]],
"path_point_lists": [
[[5, 6, 7], [8, 9, 10], [1, 0, 10], [2, 4, 2]],
[[5, 6, 7], [8, 9, 10], [1, 0, 10], [2, 4, 2]],
],
"probability": 0.92,
"version": {"major": 1, "minor": 0},
},
extra_info='Optional fields: "name" and "probability"',
),
InterfaceKindChoices.MULTIPLE_LINES: ComponentInterfaceExampleValue(
value={
"name": "Some annotations",
"type": "Multiple lines",
"lines": [
{
"name": "Annotation 1",
"seed_points": [[1, 2, 3], [1, 2, 3]],
"path_point_lists": [
[[5, 6, 7], [8, 9, 10], [1, 0, 10], [2, 4, 2]],
[[5, 6, 7], [8, 9, 10], [1, 0, 10], [2, 4, 2]],
],
"probability": 0.78,
},
{
"name": "Annotation 2",
"seed_points": [[1, 2, 3], [1, 2, 3]],
"path_point_lists": [
[[5, 6, 7], [8, 9, 10], [1, 0, 10], [2, 4, 2]],
[[5, 6, 7], [8, 9, 10], [1, 0, 10], [2, 4, 2]],
],