-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathimages.py
More file actions
1794 lines (1642 loc) · 68.8 KB
/
images.py
File metadata and controls
1794 lines (1642 loc) · 68.8 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 concurrent.futures
import copy
import io
import json
import logging
import os.path
import random
import tempfile
import time
import uuid
from collections import defaultdict
from collections import namedtuple
from pathlib import Path
from typing import List
from typing import Optional
import boto3
import cv2
import lib.core as constances
import numpy as np
import requests
from botocore.exceptions import ClientError
from lib.core.conditions import Condition
from lib.core.conditions import CONDITION_EQ as EQ
from lib.core.entities import AnnotationClassEntity
from lib.core.entities import BaseItemEntity
from lib.core.entities import FolderEntity
from lib.core.entities import ImageEntity
from lib.core.entities import ProjectEntity
from lib.core.entities import S3FileEntity
from lib.core.enums import ImageQuality
from lib.core.enums import ProjectType
from lib.core.exceptions import AppException
from lib.core.exceptions import AppValidationException
from lib.core.exceptions import ImageProcessingException
from lib.core.plugin import ImagePlugin
from lib.core.plugin import VideoPlugin
from lib.core.reporter import Progress
from lib.core.reporter import Reporter
from lib.core.repositories import BaseManageableRepository
from lib.core.response import Response
from lib.core.serviceproviders import BaseServiceProvider
from lib.core.types import Attachment
from lib.core.types import AttachmentMeta
from lib.core.usecases.base import BaseInteractiveUseCase
from lib.core.usecases.base import BaseReportableUseCase
from lib.core.usecases.base import BaseUseCase
from PIL import UnidentifiedImageError
from superannotate_core.app import Folder
from superannotate_core.app import Item
from superannotate_core.app import Project
logger = logging.getLogger("sa")
class GetImageUseCase(BaseUseCase):
def __init__(
self,
project: ProjectEntity,
folder: FolderEntity,
image_name: str,
service_provider: BaseServiceProvider,
):
super().__init__()
self._project = project
self._folder = folder
self._image_name = image_name
self._service_provider = service_provider
def execute(self):
images = self._service_provider.items.list_by_names(
project=self._project, folder=self._folder, names=[self._image_name]
).data
if images:
self._response.data = images[0]
else:
raise AppException("Image not found.")
return self._response
class AttachFileUrlsUseCase(BaseUseCase):
def __init__(
self,
project: ProjectEntity,
folder: FolderEntity,
attachments: List[ImageEntity],
service_provider: BaseServiceProvider,
annotation_status: str = None,
upload_state_code: int = constances.UploadState.EXTERNAL.value,
):
super().__init__()
self._attachments = attachments
self._project = project
self._folder = folder
self._service_provider = service_provider
self._annotation_status = annotation_status
self._upload_state_code = upload_state_code
def _validate_limitations(self, to_upload_count):
response = self._service_provider.get_limitations(self._project, self._folder)
if not response.ok:
raise AppValidationException(response.error)
if to_upload_count > response.data.folder_limit.remaining_image_count:
raise AppValidationException(constances.ATTACH_FOLDER_LIMIT_ERROR_MESSAGE)
elif to_upload_count > response.data.project_limit.remaining_image_count:
raise AppValidationException(constances.ATTACH_PROJECT_LIMIT_ERROR_MESSAGE)
elif (
response.data.user_limit
and to_upload_count > response.data.user_limit.remaining_image_count
):
raise AppValidationException(constances.ATTACH_USER_LIMIT_ERROR_MESSAGE)
@property
def annotation_status_code(self):
if self._annotation_status:
if isinstance(self._annotation_status, int):
return self._annotation_status
return constances.AnnotationStatus.get_value(self._annotation_status)
return constances.AnnotationStatus.NOT_STARTED.value
@property
def upload_state_code(self) -> int:
if not self._upload_state_code:
return constances.UploadState.EXTERNAL.value
return self._upload_state_code
def execute(self):
response = self._service_provider.items.list_by_names(
project=self._project,
folder=self._folder,
names=[image.name for image in self._attachments],
)
if not response.ok:
raise AppException(response.error)
duplications = [image.name for image in response.data]
meta = {}
to_upload = []
for image in self._attachments:
if not image.name:
image.name = str(uuid.uuid4())
if image.name not in duplications:
to_upload.append(Attachment(**{"name": image.name, "path": image.path}))
meta[image.name] = AttachmentMeta(
**{
"width": image.meta["width"],
"height": image.meta["height"],
}
)
try:
self._validate_limitations(len(to_upload))
except AppValidationException as e:
self._response.errors = e
return self._response
if to_upload:
backend_response = self._service_provider.items.attach(
project=self._project,
folder=self._folder,
attachments=to_upload,
annotation_status_code=self.annotation_status_code,
upload_state_code=self.upload_state_code,
meta=meta,
)
if isinstance(backend_response, dict) and "error" in backend_response:
self._response.errors = AppException(backend_response["error"])
else:
self._response.data = backend_response.data, duplications
else:
self._response.data = [], duplications
return self._response
class GetImageBytesUseCase(BaseUseCase):
def __init__(
self,
project: ProjectEntity,
folder: FolderEntity,
image: ImageEntity,
service_provider: BaseServiceProvider,
image_variant: str = "original",
):
super().__init__()
self._project = project
self._folder = folder
self._image = image
self._service_provider = service_provider
self._image_variant = image_variant
def execute(self):
auth_data = self._service_provider.get_download_token(
project_id=self._project.id,
folder_id=self._folder.id,
image_id=self._image.id,
include_original=1,
).data
download_url = auth_data[self._image_variant]["url"]
headers = auth_data[self._image_variant]["headers"]
response = requests.get(url=download_url, headers=headers)
self._response.data = io.BytesIO(response.content)
return self._response
class CopyImageAnnotationClasses(BaseUseCase):
def __init__(
self,
from_project: ProjectEntity,
to_project: ProjectEntity,
from_image: BaseItemEntity,
to_image: BaseItemEntity,
from_folder: FolderEntity,
to_folder: FolderEntity,
service_provider: BaseServiceProvider,
from_project_s3_repo: BaseManageableRepository,
to_project_s3_repo: BaseManageableRepository,
annotation_type: str = "MAIN",
):
super().__init__()
self._from_project = from_project
self._to_project = to_project
self._from_folder = from_folder
self._to_folder = to_folder
self._from_image = from_image
self._to_image = to_image
self._service_provider = service_provider
self._from_project_s3_repo = from_project_s3_repo
self.to_project_s3_repo = to_project_s3_repo
self._annotation_type = annotation_type
@property
def default_annotation(self):
return {
"annotation_json": None,
"annotation_json_filename": None,
"annotation_mask": None,
"annotation_mask_filename": None,
}
@property
def download_auth_data(self):
return self._service_provider.get_download_token(
project=self._from_project,
folder=self._from_folder,
image_id=self._from_image.id,
include_original=1,
).data
@property
def upload_auth_data(self):
return self._service_provider.get_upload_token(
project=self._to_project,
folder=self._to_folder,
image_id=self._to_image.id,
).data
def validate_project_type(self):
if self._from_project.type != self._to_project.type:
raise AppValidationException("Projects are different.")
def execute(self):
if self._annotation_type not in self.download_auth_data["annotations"]:
self._response.data = self.default_annotation
return
annotations = self.download_auth_data["annotations"][self._annotation_type][0]
response = requests.get(
url=annotations["annotation_json_path"]["url"],
headers=annotations["annotation_json_path"]["headers"],
)
if not response.ok:
raise AppException("Couldn't load annotations.")
image_annotations = response.json()
from_project_annotation_classes = (
self._service_provider.annotation_classes.list(
Condition("project_id", self._from_project.id, EQ)
).data
)
to_project_annotation_classes = self._service_provider.annotation_classes.list(
Condition("project_id", self._to_project.id, EQ)
).data
annotations_classes_from_copy = {
from_annotation.id: from_annotation
for from_annotation in from_project_annotation_classes
for to_annotation in to_project_annotation_classes
if from_annotation.name == to_annotation.name
}
annotations_classes_to_copy = {
to_annotation.name: to_annotation
for to_annotation in to_project_annotation_classes
for from_annotation in from_project_annotation_classes
if from_annotation.name == to_annotation.name
}
for instance in image_annotations["instances"]:
if instance["classId"] < 0 or not annotations_classes_from_copy.get(
instance["classId"]
):
continue
project_annotation_class = annotations_classes_from_copy[
instance["classId"]
]
instance["className"] = project_annotation_class.name
if instance.get("attributes"):
for attribute in instance["attributes"]:
attribute_group = None
if attribute.get("groupId"):
for group in project_annotation_class.attribute_groups:
if group.id == attribute["groupId"]:
attribute["groupName"] = group.name
attribute_group = group
if attribute.get("id") and attribute_group:
for attr in attribute_group.attributes:
if attr.id == attribute["id"]:
attribute["name"] = attr.name
for instance in image_annotations["instances"]:
if (
"className" not in instance
and instance["className"] not in annotations_classes_to_copy
):
continue
annotation_class = annotations_classes_to_copy.get(instance["className"])
if not annotation_class:
instance["classId"] = -1
continue
attribute_groups_map = {
group.name: group for group in annotation_class.attribute_groups
}
instance["classId"] = annotation_class.id
for attribute in instance["attributes"]:
if attribute_groups_map.get(attribute["groupName"]):
attribute["groupId"] = attribute_groups_map[
attribute["groupName"]
].id
attr_map = {
attr.name: attr
for attr in attribute_groups_map[
attribute["groupName"]
].attributes
}
if attribute["name"] not in attr_map:
del attribute["groupId"]
continue
attribute["id"] = attr_map[attribute["name"]].id
auth_data = self.upload_auth_data
file = S3FileEntity(
uuid=auth_data["annotation_json_path"]["filePath"],
data=json.dumps(image_annotations),
)
self.to_project_s3_repo.insert(file)
if (
self._to_project.type == constances.ProjectType.PIXEL.value
and annotations.get("annotation_bluemap_path")
and annotations["annotation_bluemap_path"]["exist"]
):
response = requests.get(
url=annotations["annotation_bluemap_path"]["url"],
headers=annotations["annotation_bluemap_path"]["headers"],
)
if not response.ok:
raise AppException("Couldn't load annotations.")
self.to_project_s3_repo.insert(
S3FileEntity(
auth_data["annotation_bluemap_path"]["filePath"], response.content
)
)
return self._response
class UpdateItemUseCase(BaseUseCase):
def __init__(
self,
project: ProjectEntity,
item: BaseItemEntity,
service_provider: BaseServiceProvider,
):
super().__init__()
self._project = project
self._service_provider = service_provider
self._item = item
def execute(self):
self._service_provider.items.update(project=self._project, item=self._item)
return self._response
class CreateFuseImageUseCase(BaseUseCase):
TRANSPARENCY = 128
def __init__(
self,
project_type: str,
image_path: str,
classes: list = None,
in_memory: bool = False,
generate_overlay: bool = False,
):
super().__init__()
self._project_type = project_type
self._image_path = image_path
self._annotations = None
self._classes = classes
self._annotation_mask_path = None
self._in_memory = in_memory
self._generate_overlay = generate_overlay
@staticmethod
def generate_color(value: str = None):
if not value:
return (
random.randint(1, 255),
random.randint(1, 255),
random.randint(1, 255),
)
return tuple(int(value.lstrip("#")[i : i + 2], 16) for i in (0, 2, 4))
@property
def annotations(self):
if not self._annotations:
image_path = (
f"{Path(self._image_path).parent}/{Path(self._image_path).name}"
)
self._annotations = json.load(open(f"{image_path}.json"))
return self._annotations
@property
def blue_mask_path(self):
image_path = Path(self._image_path)
if self._project_type.upper() == constances.ProjectType.PIXEL.name.upper():
self._annotation_mask_path = str(
image_path.parent / f"{image_path.name}___save.png"
)
else:
raise AppException("Vector project doesn't have blue mask.")
return self._annotation_mask_path
def execute(self):
with open(self._image_path, "rb") as file:
class_color_map = {}
Image = namedtuple("Image", ["type", "path", "content"])
for annotation_class in self._classes:
class_color_map[annotation_class["name"]] = self.generate_color(
annotation_class["color"]
)
if self._project_type.upper() == constances.ProjectType.VECTOR.name.upper():
image = ImagePlugin(io.BytesIO(file.read()))
images = [
Image(
"fuse",
f"{self._image_path}___fuse.png",
image.get_empty(),
)
]
if self._generate_overlay:
images.append(
Image("overlay", f"{self._image_path}___overlay.png", image)
)
outline_color = 4 * (255,)
for instance in self.annotations["instances"]:
if (not instance.get("className")) or (
not class_color_map.get(instance["className"])
):
continue
color = class_color_map.get(instance["className"])
if not color:
class_color_map[instance["className"]] = self.generate_color()
for image in images:
fill_color = (
*class_color_map[instance["className"]],
255 if image.type == "fuse" else self.TRANSPARENCY,
)
if instance["type"] == "bbox":
image.content.draw_bbox(
**instance["points"],
fill_color=fill_color,
outline_color=outline_color,
)
elif instance["type"] == "polygon":
image.content.draw_polygon(
instance["points"],
fill_color=fill_color,
outline_color=outline_color,
)
elif instance["type"] == "ellipse":
image.content.draw_ellipse(
instance["cx"],
instance["cy"],
instance["rx"],
instance["ry"],
fill_color=fill_color,
outline_color=outline_color,
)
elif instance["type"] == "polyline":
image.content.draw_polyline(
points=instance["points"], fill_color=fill_color
)
elif instance["type"] == "point":
image.content.draw_point(
x=instance["x"],
y=instance["y"],
fill_color=fill_color,
outline_color=outline_color,
)
elif instance["type"] == "template":
point_set = instance["points"]
points_id_map = {}
for points in point_set:
points_id_map[points["id"]] = (points["x"], points["y"])
points = (
points["x"] - 2,
points["y"] - 2,
points["x"] + 2,
points["y"] + 2,
)
image.content.draw_ellipse(
*points, fill_color, fill_color, fixed=True
)
for connection in instance["connections"]:
image.content.draw_line(
points_id_map[connection["from"]],
points_id_map[connection["to"]],
fill_color=fill_color,
)
else:
if not os.path.exists(self.blue_mask_path):
logger.warning(
"There is no blue map to generate fuse or overlay images."
)
return self._response
image = ImagePlugin(io.BytesIO(file.read()))
annotation_mask = np.array(
ImagePlugin(
io.BytesIO(open(self.blue_mask_path, "rb").read())
).content
)
weight, height = image.get_size()
empty_image_arr = np.full((height, weight, 4), [0, 0, 0, 255], np.uint8)
for annotation in self.annotations["instances"]:
if (not annotation.get("className")) or (
not class_color_map.get(annotation["className"])
):
continue
fill_color = *class_color_map[annotation["className"]], 255
for part in annotation["parts"]:
part_color = *self.generate_color(part["color"]), 255
temp_mask = np.all(annotation_mask == part_color, axis=2)
empty_image_arr[temp_mask] = fill_color
images = [
Image(
"fuse",
f"{self._image_path}___fuse.png",
ImagePlugin.from_array(empty_image_arr),
)
]
if self._generate_overlay:
alpha = 0.5 # transparency measure
overlay = copy.copy(empty_image_arr)
overlay[:, :, :3] = np.array(image.content)[:, :, :3]
overlay = ImagePlugin.from_array(
cv2.addWeighted(empty_image_arr, alpha, overlay, 1 - alpha, 0)
)
images.append(
Image("overlay", f"{self._image_path}___overlay.png", overlay)
)
if not self._in_memory:
paths = []
for image in images:
image.content.save(image.path)
paths.append(image.path)
self._response.data = paths
else:
self._response.data = (image.content for image in images)
return self._response
class GetS3ImageUseCase(BaseUseCase):
def __init__(
self,
s3_bucket,
image_path: str,
):
super().__init__()
self._s3_bucket = s3_bucket
self._image_path = image_path
def execute(self):
try:
image = io.BytesIO()
session = boto3.Session()
resource = session.resource("s3")
image_object = resource.Object(self._s3_bucket, self._image_path)
if image_object.content_length > constances.MAX_IMAGE_SIZE:
raise AppValidationException(
f"File size is {image_object.content_length}"
)
image_object.download_fileobj(image)
self._response.data = image
except ClientError as e:
self._response.errors = str(e)
return self._response
class DownloadImageUseCase(BaseReportableUseCase):
def __init__(
self,
reporter: Reporter,
project: ProjectEntity,
folder: FolderEntity,
image: ImageEntity,
service_provider: BaseServiceProvider,
download_path: str,
image_variant: str = "original",
include_annotations: bool = False,
include_fuse: bool = False,
include_overlay: bool = False,
):
super().__init__(reporter)
self._project = project
self._image = image
self._download_path = download_path
self._image_variant = image_variant
self._include_fuse = include_fuse
self._include_overlay = include_overlay
self._include_annotations = include_annotations
self._service_provider = service_provider
self.get_image_use_case = GetImageBytesUseCase(
project=self._project,
folder=folder,
image=image,
service_provider=service_provider,
image_variant=image_variant,
)
self.download_annotation_use_case = DownloadImageAnnotationsUseCase(
service_provider=service_provider,
project=project,
folder=folder,
image_name=self._image.name,
destination=download_path,
)
def validate_project_type(self):
if (
self._project.type in constances.LIMITED_FUNCTIONS
or self._project.upload_state == constances.UploadState.EXTERNAL.value
):
raise AppValidationException(
"The feature does not support projects containing attached URLs."
)
def validate_variant_type(self):
if self._image_variant not in ["original", "lores"]:
raise AppValidationException(
"Image download variant should be either original or lores"
)
def validate_download_path(self):
if not Path(str(self._download_path)).is_dir():
raise AppValidationException(
f"local_dir_path {self._download_path} is not an existing directory"
)
def validate_include_annotations(self):
if (
self._include_fuse or self._include_overlay
) and not self._include_annotations:
raise AppValidationException(
"To download fuse or overlay image need to set include_annotations=True in download_image"
)
def execute(self):
if self.is_valid():
fuse_image = None
annotations = None
image_bytes = self.get_image_use_case.execute().data
download_path = f"{self._download_path}/{self._image.name}"
if self._image_variant == "lores":
download_path = download_path + "___lores.jpg"
with open(download_path, "wb") as image_file:
image_file.write(image_bytes.getbuffer())
if self._include_annotations:
annotations = self.download_annotation_use_case.execute().data
if self._include_annotations and (
self._include_fuse or self._include_overlay
):
classes = self._service_provider.annotation_classes.list(
Condition("project_id", self._project.id, EQ)
).data
fuse_image = (
CreateFuseImageUseCase(
project_type=constances.ProjectType.get_name(
self._project.type
),
image_path=download_path,
classes=[
annotation_class.dict(exclude_unset=True)
for annotation_class in classes
],
generate_overlay=self._include_overlay,
)
.execute()
.data
)
self._response.data = (
download_path,
annotations,
fuse_image,
)
return self._response
class UploadImageToProject(BaseUseCase):
def __init__(
self,
project: ProjectEntity,
folder: FolderEntity,
s3_repo,
service_provider: BaseServiceProvider,
annotation_status: str,
image_bytes: io.BytesIO = None,
image_path: str = None,
image_name: str = None,
from_s3_bucket: str = None,
image_quality_in_editor: str = None,
):
super().__init__()
self._project = project
self._folder = folder
self._image_bytes = image_bytes
self._image_path = image_path
self._image_name = image_name
self._from_s3_bucket = from_s3_bucket
self._image_quality_in_editor = image_quality_in_editor
self._s3_repo = s3_repo
self._service_provider = service_provider
self._annotation_status = annotation_status
self._auth_data = None
@property
def s3_repo(self):
self._auth_data = self._service_provider.get_s3_upload_auth_token(
self._project, self._folder
)
if not self._auth_data.ok:
raise AppException(self._auth_data.data.get("error"))
return self._s3_repo(
self._auth_data.data["accessKeyId"],
self._auth_data.data["secretAccessKey"],
self._auth_data.data["sessionToken"],
self._auth_data.data["bucket"],
self._auth_data.data["region"],
)
def validate_project_type(self):
if self._project.upload_state == constances.UploadState.EXTERNAL.value:
raise AppValidationException(constances.UPLOADING_UPLOAD_STATE_ERROR)
def validate_deprecation(self):
if self._project.type in [
constances.ProjectType.VIDEO.value,
constances.ProjectType.DOCUMENT.value,
]:
raise AppException(constances.LIMITED_FUNCTIONS[self._project.type])
def validate_limitations(self):
response = self._service_provider.get_limitations(self._project, self._folder)
if response.data.folder_limit.remaining_image_count < 1:
raise AppValidationException(constances.UPLOAD_FOLDER_LIMIT_ERROR_MESSAGE)
elif response.data.project_limit.remaining_image_count < 1:
raise AppValidationException(constances.UPLOAD_PROJECT_LIMIT_ERROR_MESSAGE)
elif (
response.data.user_limit
and response.data.user_limit.remaining_image_count < 1
):
raise AppValidationException(constances.UPLOAD_USER_LIMIT_ERROR_MESSAGE)
@property
def auth_data(self):
return self._auth_data
def validate_arguments(self):
if not self._image_path and self._image_bytes is None:
raise AppValidationException("Image data not provided.")
def validate_image_name_uniqueness(self):
image_entities = self._service_provider.items.list_by_names(
project=self._project,
folder=self._folder,
names=[
self._image_name if self._image_name else Path(self._image_path).name
],
).data
if image_entities:
raise AppValidationException("Image with this name already exists.")
def execute(self) -> Response:
if self.is_valid():
if self._image_path and self._from_s3_bucket:
image_bytes = (
GetS3ImageUseCase(
s3_bucket=self._from_s3_bucket, image_path=self._image_path
)
.execute()
.data
)
elif self._image_path:
image_bytes = io.BytesIO(open(self._image_path, "rb").read())
else:
image_bytes = self._image_bytes
s3_upload_response = UploadImageS3UseCase(
project=self._project,
image_path=self._image_name
if self._image_name
else Path(self._image_path).name,
service_provider=self._service_provider,
image=image_bytes,
s3_repo=self.s3_repo,
upload_path=self.auth_data.data["filePath"],
image_quality_in_editor=self._image_quality_in_editor,
).execute()
if s3_upload_response.errors:
raise AppException(s3_upload_response.errors)
AttachFileUrlsUseCase(
project=self._project,
folder=self._folder,
attachments=[s3_upload_response.data],
service_provider=self._service_provider,
annotation_status=self._annotation_status,
upload_state_code=constances.UploadState.BASIC.value,
).execute()
return self._response
class UploadImagesToProject(BaseInteractiveUseCase):
MAX_WORKERS = 10
LIST_NAME_CHUNK_SIZE = 500
def __init__(
self,
project: Project,
folder: Folder,
s3_repo,
service_provider: BaseServiceProvider,
paths: List[str],
extensions=constances.DEFAULT_IMAGE_EXTENSIONS,
annotation_status="NotStarted",
from_s3_bucket=None,
exclude_file_patterns: List[str] = constances.DEFAULT_FILE_EXCLUDE_PATTERNS,
recursive_sub_folders: bool = False,
image_quality_in_editor=None,
):
super().__init__()
self._auth_data = None
self._s3_repo_instance = None
self._images_to_upload = None
self._paths = paths
self._project = project
self._folder = folder
self._service_provider = service_provider
self._s3_repo = s3_repo
self._image_quality_in_editor = image_quality_in_editor
self._from_s3_bucket = from_s3_bucket
self._extensions = extensions
self._recursive_sub_folders = recursive_sub_folders
if exclude_file_patterns:
list(exclude_file_patterns).extend(
list(constances.DEFAULT_FILE_EXCLUDE_PATTERNS)
)
self._exclude_file_patterns = exclude_file_patterns
self._annotation_status = annotation_status
@property
def extensions(self):
if not self._extensions:
return constances.DEFAULT_IMAGE_EXTENSIONS
return self._extensions
@property
def exclude_file_patterns(self):
if not self._exclude_file_patterns:
return constances.DEFAULT_FILE_EXCLUDE_PATTERNS
return self._exclude_file_patterns
def validate_limitations(self):
response = self._service_provider.get_limitations(self._project, self._folder)
if not response.ok:
raise AppValidationException(response.error)
to_upload_count = len(self.images_to_upload[0])
if to_upload_count > response.data.folder_limit.remaining_image_count:
raise AppValidationException(constances.UPLOAD_FOLDER_LIMIT_ERROR_MESSAGE)
elif to_upload_count > response.data.project_limit.remaining_image_count:
raise AppValidationException(constances.UPLOAD_PROJECT_LIMIT_ERROR_MESSAGE)
elif (
response.data.user_limit
and to_upload_count > response.data.user_limit.remaining_image_count
):
raise AppValidationException(constances.UPLOAD_USER_LIMIT_ERROR_MESSAGE)
def validate_annotation_status(self):
if (
self._annotation_status
and self._annotation_status.lower()
not in constances.AnnotationStatus.values()
):
raise AppValidationException("Invalid annotations status")
def validate_extensions(self):
if self._extensions and not all(
[
extension in constances.DEFAULT_IMAGE_EXTENSIONS
for extension in self._extensions
]
):
raise AppValidationException("")
def validate_project_type(self):
if self._project.upload_state == constances.UploadState.EXTERNAL.value:
raise AppValidationException(constances.UPLOADING_UPLOAD_STATE_ERROR)
def validate_deprecation(self):
if self._project.type in constances.LIMITED_FUNCTIONS:
raise AppValidationException(
constances.LIMITED_FUNCTIONS[self._project.type]
)
@property
def auth_data(self):
if not self._auth_data:
response = self._service_provider.get_s3_upload_auth_token(
project=self._project, folder=self._folder
)
if not response.ok:
raise AppException(response.error)
self._auth_data = response.data
return self._auth_data
@property
def s3_repository(self):
if not self._s3_repo_instance:
self._s3_repo_instance = self._s3_repo(
self.auth_data["accessKeyId"],
self.auth_data["secretAccessKey"],
self.auth_data["sessionToken"],
self.auth_data["bucket"],
self.auth_data["region"],
)
return self._s3_repo_instance
def _upload_image(self, image_path: str):
ProcessedImage = namedtuple(
"ProcessedImage", ["uploaded", "path", "entity", "name"]
)
if self._from_s3_bucket:
response = GetS3ImageUseCase(
s3_bucket=self._from_s3_bucket, image_path=image_path
).execute()
if response.errors:
logger.warning(
f"Unable to upload image {image_path} \n{response.errors}"
)
return ProcessedImage(
uploaded=False,
path=image_path,
entity=None,
name=Path(image_path).name,
)
image_bytes = response.data
else:
try:
image_bytes = io.BytesIO(open(image_path, "rb").read())
except OSError:
return ProcessedImage(
uploaded=False,
path=image_path,
entity=None,
name=Path(image_path).name,
)
upload_response = UploadImageS3UseCase(
project=self._project,
image_path=image_path,
image=image_bytes,
s3_repo=self.s3_repository,
upload_path=self.auth_data["filePath"],
service_provider=self._service_provider,
image_quality_in_editor=self._image_quality_in_editor,
).execute()