Repository navigation
Expand file tree
/
Copy pathtest_task_data.py
More file actions
2311 lines (2024 loc) · 90.1 KB
/
Copy pathtest_task_data.py
File metadata and controls
2311 lines (2024 loc) · 90.1 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
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import io
import json
import math
import os
import os.path as osp
import zipfile
from collections import Counter
from collections.abc import Iterable, Sequence
from copy import deepcopy
from functools import partial
from http import HTTPStatus
from itertools import chain, groupby, product
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Optional
import numpy as np
import pytest
from cvat_sdk import exceptions
from cvat_sdk.api_client import models
from cvat_sdk.core.helpers import get_paginated_collection
from deepdiff import DeepDiff
from PIL import Image
from pytest_cases import parametrize
import shared.utils.s3 as s3
from rest_api._test_base import TestTasksBase
from rest_api.utils import create_task, get_cloud_storage_content, wait_until_task_is_created
from shared.tasks.enums import SourceDataType
from shared.tasks.interface import ITaskSpec
from shared.tasks.types import ImagesTaskSpec
from shared.tasks.utils import parse_frame_step
from shared.utils.config import get_method, make_api_client, patch_method, post_method
from shared.utils.helpers import (
generate_image_file,
generate_image_files,
generate_manifest,
generate_video_file,
read_video_file,
)
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.usefixtures("restore_cvat_data_per_function")
@pytest.mark.usefixtures("restore_redis_ondisk_per_function")
@pytest.mark.usefixtures("restore_redis_ondisk_after_class")
@pytest.mark.usefixtures("restore_redis_inmem_per_function")
class TestPostTaskData:
_USERNAME = "admin1"
def _test_cannot_create_task(self, username, spec, data, **kwargs):
with make_api_client(username) as api_client:
(task, response) = api_client.tasks_api.create(spec, **kwargs)
assert response.status == HTTPStatus.CREATED
(result, response) = api_client.tasks_api.create_data(
task.id, data_request=deepcopy(data), _content_type="application/json", **kwargs
)
assert response.status == HTTPStatus.ACCEPTED
request_details = wait_until_task_is_created(api_client.requests_api, result.rq_id)
assert request_details.status.value == "failed"
return request_details
def test_can_create_task_with_defined_start_and_stop_frames(self):
task_spec = {
"name": f"test {self._USERNAME} to create a task with defined start and stop frames",
"labels": [
{
"name": "car",
"color": "#ff00ff",
"attributes": [
{
"name": "a",
"mutable": True,
"input_type": "number",
"default_value": "5",
"values": ["4", "5", "6"],
}
],
}
],
}
task_data = {
"image_quality": 75,
"start_frame": 2,
"stop_frame": 5,
"client_files": generate_image_files(7),
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
# check task size
with make_api_client(self._USERNAME) as api_client:
(task, _) = api_client.tasks_api.retrieve(task_id)
assert task.size == 4
def test_default_overlap_for_small_segment_size(self):
task_spec = {
"name": f"test {self._USERNAME} with default overlap and small segment_size",
"labels": [{"name": "car"}],
"segment_size": 5,
}
task_data = {
"image_quality": 75,
"client_files": [generate_video_file(8)],
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
# check task size
with make_api_client(self._USERNAME) as api_client:
paginated_job_list, _ = api_client.jobs_api.list(task_id=task_id)
jobs = paginated_job_list.results
jobs.sort(key=lambda job: job.start_frame)
assert len(jobs) == 2
# overlap should be 2 frames (frames 3 & 4)
assert jobs[0].start_frame == 0
assert jobs[0].stop_frame == 4
assert jobs[1].start_frame == 3
assert jobs[1].stop_frame == 7
@pytest.mark.parametrize(
"size,expected_segments",
[
(2, [(0, 1)]),
(3, [(0, 2)]),
(4, [(0, 2), (2, 3)]),
(5, [(0, 2), (2, 4)]),
(6, [(0, 2), (2, 4), (4, 5)]),
],
)
def test_task_segmentation(self, size, expected_segments):
task_spec = {
"name": f"test {self._USERNAME} to check segmentation into jobs",
"labels": [{"name": "car"}],
"segment_size": 3,
"overlap": 1,
}
task_data = {
"image_quality": 75,
"client_files": generate_image_files(size),
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
# check task size
with make_api_client(self._USERNAME) as api_client:
paginated_job_list, _ = api_client.jobs_api.list(task_id=task_id)
jobs = paginated_job_list.results
jobs.sort(key=lambda job: job.start_frame)
assert [(j.start_frame, j.stop_frame) for j in jobs] == expected_segments
def test_can_create_task_with_exif_rotated_images(self):
task_spec = {
"name": f"test {self._USERNAME} to create a task with exif rotated images",
"labels": [
{
"name": "car",
}
],
}
image_files = ["images/exif_rotated/left.jpg", "images/exif_rotated/right.jpg"]
task_data = {
"server_files": image_files,
"image_quality": 70,
"segment_size": 500,
"use_cache": True,
"sorting_method": "natural",
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
# check that the frames have correct width and height
for chunk_quality in ["original", "compressed"]:
with make_api_client(self._USERNAME) as api_client:
_, response = api_client.tasks_api.retrieve_data(
task_id, number=0, type="chunk", quality=chunk_quality
)
data_meta, _ = api_client.tasks_api.retrieve_data_meta(task_id)
with zipfile.ZipFile(io.BytesIO(response.data)) as zip_file:
for name, frame_meta in zip(zip_file.namelist(), data_meta.frames):
with zip_file.open(name) as zipped_img:
im = Image.open(zipped_img)
# original is 480x640 with 90/-90 degrees rotation
assert frame_meta.height == 640 and frame_meta.width == 480
assert im.height == 640 and im.width == 480
assert im.getexif().get(274, 1) == 1
def test_can_create_task_with_big_images(self):
# Checks for regressions about the issue
# https://github.com/cvat-ai/cvat/issues/6878
# In the case of big files (>2.5 MB by default),
# uploaded files could be write-appended twice,
# leading to bigger raw file sizes than expected.
task_spec = {
"name": f"test {self._USERNAME} to create a task with big images",
"labels": [
{
"name": "car",
}
],
}
# We need a big file to reproduce the problem
image_file = generate_image_file("big_image.bmp", size=(4000, 4000), color=(100, 200, 30))
image_bytes = image_file.getvalue()
file_size = len(image_bytes)
assert 10 * 2**20 < file_size
task_data = {
"client_files": [image_file],
"image_quality": 70,
"use_cache": False,
"use_zip_chunks": True,
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
# check that the original chunk image have the original size
# this is less accurate than checking the uploaded file directly, but faster
with make_api_client(self._USERNAME) as api_client:
_, response = api_client.tasks_api.retrieve_data(
task_id, number=0, quality="original", type="chunk", _parse_response=False
)
chunk_file = io.BytesIO(response.data)
with zipfile.ZipFile(chunk_file) as chunk_zip:
infos = chunk_zip.infolist()
assert len(infos) == 1
assert infos[0].file_size == file_size
chunk_image = chunk_zip.read(infos[0])
assert chunk_image == image_bytes
def test_can_create_task_with_exif_rotated_tif_image(self):
task_spec = {
"name": f"test {self._USERNAME} to create a task with exif rotated tif image",
"labels": [
{
"name": "car",
}
],
}
image_files = ["images/exif_rotated/tif_left.tif"]
task_data = {
"server_files": image_files,
"image_quality": 70,
"segment_size": 500,
"use_cache": False,
"sorting_method": "natural",
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
for chunk_quality in ["original", "compressed"]:
# check that the frame has correct width and height
with make_api_client(self._USERNAME) as api_client:
_, response = api_client.tasks_api.retrieve_data(
task_id, number=0, type="chunk", quality=chunk_quality
)
with zipfile.ZipFile(io.BytesIO(response.data)) as zip_file:
assert len(zip_file.namelist()) == 1
name = zip_file.namelist()[0]
assert name == "000000.tif" if chunk_quality == "original" else "000000.jpeg"
with zip_file.open(name) as zipped_img:
im = Image.open(zipped_img)
# raw image is horizontal 100x150 with -90 degrees rotation
assert im.height == 150 and im.width == 100
assert im.getexif().get(274, 1) == 1
def test_can_create_task_with_sorting_method_natural(self):
task_spec = {
"name": f"test {self._USERNAME} to create a task with a custom sorting method",
"labels": [
{
"name": "car",
}
],
}
image_files = generate_image_files(15)
task_data = {
"client_files": image_files[5:] + image_files[:5], # perturb the order
"image_quality": 70,
"sorting_method": "natural",
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
# check that the frames were sorted again
with make_api_client(self._USERNAME) as api_client:
data_meta, _ = api_client.tasks_api.retrieve_data_meta(task_id)
# generate_image_files produces files that are already naturally sorted
for image_file, frame in zip(image_files, data_meta.frames):
assert image_file.name == frame.name
def test_can_create_task_with_video_without_keyframes(self):
task_spec = {
"name": f"test {self._USERNAME} to create a task with a video without keyframes",
"labels": [
{
"name": "label1",
}
],
}
task_data = {
"server_files": [osp.join("videos", "video_without_valid_keyframes.mp4")],
"image_quality": 70,
}
task_id, _ = create_task(self._USERNAME, task_spec, task_data)
with make_api_client(self._USERNAME) as api_client:
(_, response) = api_client.tasks_api.retrieve(task_id)
assert response.status == HTTPStatus.OK
@pytest.mark.parametrize("data_source", ["client_files", "server_files"])
def test_can_create_task_with_sorting_method_predefined(self, data_source):
task_spec = {
"name": f"test {self._USERNAME} to create a task with a custom sorting method",
"labels": [
{
"name": "car",
}
],
}
if data_source == "client_files":
image_files = generate_image_files(15)
# shuffle to check for occasional sorting, e.g. in the DB
image_files = image_files[7:] + image_files[5:7] + image_files[:5]
elif data_source == "server_files":
# Files from the test file share
image_files = ["images/image_3.jpg", "images/image_1.jpg", "images/image_2.jpg"]
else:
assert False
task_data = {
data_source: image_files,
"image_quality": 70,
"sorting_method": "predefined",
}
(task_id, _) = create_task(self._USERNAME, task_spec, task_data)
# check that the frames were sorted again
with make_api_client(self._USERNAME) as api_client:
(data_meta, _) = api_client.tasks_api.retrieve_data_meta(task_id)
for image_file, frame in zip(image_files, data_meta.frames):
if isinstance(image_file, str):
image_name = image_file
else:
image_name = image_file.name
assert image_name == frame.name
def test_can_get_annotations_from_new_task_with_skeletons(self):
spec = {
"name": f"test admin1 to create a task with skeleton",
"labels": [
{
"name": "s1",
"color": "#5c5eba",
"attributes": [],
"type": "skeleton",
"sublabels": [
{"name": "1", "color": "#d12345", "attributes": [], "type": "points"},
{"name": "2", "color": "#350dea", "attributes": [], "type": "points"},
],
"svg": '<line x1="19.464284896850586" y1="21.922269821166992" x2="54.08613586425781" y2="43.60293960571289" '
'stroke="black" data-type="edge" data-node-from="1" stroke-width="0.5" data-node-to="2"></line>'
'<circle r="1.5" stroke="black" fill="#b3b3b3" cx="19.464284896850586" cy="21.922269821166992" '
'stroke-width="0.1" data-type="element node" data-element-id="1" data-node-id="1" data-label-id="103"></circle>'
'<circle r="1.5" stroke="black" fill="#b3b3b3" cx="54.08613586425781" cy="43.60293960571289" '
'stroke-width="0.1" data-type="element node" data-element-id="2" data-node-id="2" data-label-id="104"></circle>',
}
],
}
task_data = {
"image_quality": 75,
"client_files": generate_image_files(3),
}
task_id, _ = create_task(self._USERNAME, spec, task_data)
response = get_method(self._USERNAME, "labels", task_id=f"{task_id}")
label_ids = {}
for root_label in response.json()["results"]:
for label in [root_label] + root_label["sublabels"]:
label_ids.setdefault(label["type"], []).append(label["id"])
response = get_method(self._USERNAME, "jobs", task_id=f"{task_id}")
job_id = response.json()["results"][0]["id"]
patch_data = {
"shapes": [
{
"type": "skeleton",
"occluded": False,
"outside": False,
"z_order": 0,
"rotation": 0,
"points": [],
"frame": 0,
"label_id": label_ids["skeleton"][0],
"group": 0,
"source": "manual",
"attributes": [],
"elements": [
{
"type": "points",
"occluded": False,
"outside": False,
"z_order": 0,
"rotation": 0,
"points": [131.63947368421032, 165.0868421052637],
"frame": 0,
"label_id": label_ids["points"][0],
"group": 0,
"source": "manual",
"attributes": [],
},
{
"type": "points",
"occluded": False,
"outside": False,
"z_order": 0,
"rotation": 0,
"points": [354.98157894736823, 304.2710526315795],
"frame": 0,
"label_id": label_ids["points"][1],
"group": 0,
"source": "manual",
"attributes": [],
},
],
}
],
"tracks": [
{
"frame": 0,
"label_id": label_ids["skeleton"][0],
"group": 0,
"source": "manual",
"shapes": [
{
"type": "skeleton",
"occluded": False,
"outside": False,
"z_order": 0,
"rotation": 0,
"points": [],
"frame": 0,
"attributes": [],
}
],
"attributes": [],
"elements": [
{
"frame": 0,
"label_id": label_ids["points"][0],
"group": 0,
"source": "manual",
"shapes": [
{
"type": "points",
"occluded": False,
"outside": False,
"z_order": 0,
"rotation": 0,
"points": [295.6394736842103, 472.5868421052637],
"frame": 0,
"attributes": [],
}
],
"attributes": [],
},
{
"frame": 0,
"label_id": label_ids["points"][1],
"group": 0,
"source": "manual",
"shapes": [
{
"type": "points",
"occluded": False,
"outside": False,
"z_order": 0,
"rotation": 0,
"points": [619.3236842105262, 846.9815789473689],
"frame": 0,
"attributes": [],
}
],
"attributes": [],
},
],
}
],
"tags": [],
"version": 0,
}
response = patch_method(
self._USERNAME, f"jobs/{job_id}/annotations", patch_data, action="create"
)
response = get_method(self._USERNAME, f"jobs/{job_id}/annotations")
assert response.status_code == HTTPStatus.OK
@pytest.mark.with_external_services
@pytest.mark.parametrize(
"use_cache, cloud_storage_id, manifest, use_bucket_content",
[
(True, 1, "images_with_manifest/manifest.jsonl", False), # public bucket
(True, 2, "sub/images_with_manifest/manifest.jsonl", True), # private bucket
(False, 1, "images_with_manifest/manifest.jsonl", False), # public bucket
(False, 2, "sub/images_with_manifest/manifest.jsonl", True), # private bucket
(True, 1, None, False),
(True, 2, None, True),
(False, 1, None, False),
(False, 2, None, True),
],
)
def test_create_task_with_cloud_storage_files(
self,
use_cache: bool,
cloud_storage_id: int,
cloud_storages,
manifest: str,
use_bucket_content: bool,
):
org_id = cloud_storages[cloud_storage_id]["organization"]
bucket_prefix = "sub/" if cloud_storage_id == 2 else ""
if use_bucket_content:
cloud_storage_content = get_cloud_storage_content(
self._USERNAME,
cloud_storage_id,
manifest=manifest,
prefix=bucket_prefix,
)
cloud_storage_content = [
p for p in cloud_storage_content if "images_with_manifest/" in p
]
else:
cloud_storage_content = [
f"{bucket_prefix}images_with_manifest/image_case_65_1.png",
f"{bucket_prefix}images_with_manifest/image_case_65_2.png",
]
if manifest:
cloud_storage_content.append(manifest)
task_spec = {
"name": f"Task with files from cloud storage {cloud_storage_id}",
"labels": [
{
"name": "car",
}
],
}
data_spec = {
"image_quality": 75,
"use_cache": use_cache,
"cloud_storage_id": cloud_storage_id,
"server_files": cloud_storage_content,
}
kwargs = {"org_id": org_id} if org_id else {}
create_task(self._USERNAME, task_spec, data_spec, **kwargs)
def _create_task_with_cloud_data(
self,
request,
cloud_storage: Any,
use_manifest: bool,
server_files: list[str],
use_cache: bool = True,
sorting_method: str = "lexicographical",
data_type: str = "image",
video_frame_count: int = 10,
server_files_exclude: Optional[list[str]] = None,
org: str = "",
filenames: Optional[list[str]] = None,
task_spec_kwargs: Optional[dict[str, Any]] = None,
data_spec_kwargs: Optional[dict[str, Any]] = None,
) -> tuple[int, Any]:
s3_client = s3.make_client(bucket=cloud_storage["resource"])
if data_type == "video":
video = generate_video_file(video_frame_count)
s3_client.create_file(
data=video,
filename=f"test/video/{video.name}",
)
request.addfinalizer(
partial(
s3_client.remove_file,
filename=f"test/video/{video.name}",
)
)
else:
images = generate_image_files(
3,
sizes=[(100, 50) if i % 2 else (50, 100) for i in range(3)],
**({"prefixes": ["img_"] * 3} if not filenames else {"filenames": filenames}),
)
for image in images:
for i in range(2):
image.seek(0)
s3_client.create_file(
data=image,
filename=f"test/sub_{i}/{image.name}",
)
request.addfinalizer(
partial(
s3_client.remove_file,
filename=f"test/sub_{i}/{image.name}",
)
)
if use_manifest:
with TemporaryDirectory() as tmp_dir:
manifest_root_path = f"{tmp_dir}/test/"
for i in range(2):
path_with_sub_folders = f"{tmp_dir}/test/sub_{i}/"
os.makedirs(path_with_sub_folders)
for image in images:
with open(osp.join(path_with_sub_folders, image.name), "wb") as f:
f.write(image.getvalue())
generate_manifest(manifest_root_path)
with open(osp.join(manifest_root_path, "manifest.jsonl"), mode="rb") as m_file:
s3_client.create_file(
data=m_file.read(),
filename="test/manifest.jsonl",
)
request.addfinalizer(
partial(
s3_client.remove_file,
filename="test/manifest.jsonl",
)
)
task_spec = {
"name": f"Task created from directories from cloud storage {cloud_storage['id']}",
"labels": [
{
"name": "car",
}
],
**(task_spec_kwargs or {}),
}
data_spec = {
"image_quality": 75,
"use_cache": use_cache,
"cloud_storage_id": cloud_storage["id"],
"server_files": (
server_files if not use_manifest else server_files + ["test/manifest.jsonl"]
),
"sorting_method": sorting_method,
**(data_spec_kwargs or {}),
}
if server_files_exclude:
data_spec["server_files_exclude"] = server_files_exclude
return create_task(self._USERNAME, task_spec, data_spec, org=org)
@pytest.mark.with_external_services
@pytest.mark.parametrize("cloud_storage_id", [2])
@pytest.mark.parametrize(
"use_cache, use_manifest, server_files, server_files_exclude, task_size",
[
(True, False, ["test/"], None, 6),
(True, False, ["test/sub_0/", "test/sub_1/"], None, 6),
(True, False, ["test/"], ["test/sub_0/", "test/sub_1/img_1.jpeg"], 2),
(True, True, ["test/"], None, 6),
(True, True, ["test/sub_0/", "test/sub_1/"], None, 6),
(True, True, ["test/"], ["test/sub_0/", "test/sub_1/img_1.jpeg"], 2),
(False, False, ["test/"], None, 6),
(False, False, ["test/sub_0/", "test/sub_1/"], None, 6),
(False, False, ["test/"], ["test/sub_0/", "test/sub_1/img_1.jpeg"], 2),
],
)
@pytest.mark.parametrize("org", [""])
def test_create_task_with_cloud_storage_directories_and_excluded_files(
self,
cloud_storage_id: int,
use_cache: bool,
use_manifest: bool,
server_files: list[str],
server_files_exclude: Optional[list[str]],
task_size: int,
org: str,
cloud_storages,
request,
):
cloud_storage = cloud_storages[cloud_storage_id]
task_id, _ = self._create_task_with_cloud_data(
request,
cloud_storage,
use_manifest,
server_files,
use_cache=use_cache,
server_files_exclude=server_files_exclude,
org=org,
)
with make_api_client(self._USERNAME) as api_client:
(task, response) = api_client.tasks_api.retrieve(task_id)
assert response.status == HTTPStatus.OK
assert task.size == task_size
@pytest.mark.with_external_services
@pytest.mark.parametrize("cloud_storage_id", [2])
@pytest.mark.parametrize("use_manifest", [True, False])
@pytest.mark.parametrize(
"server_files, expected_result",
[
(
["test/sub_1/", "test/sub_0/"],
[
"test/sub_1/img_0.jpeg",
"test/sub_1/img_1.jpeg",
"test/sub_1/img_2.jpeg",
"test/sub_0/img_0.jpeg",
"test/sub_0/img_1.jpeg",
"test/sub_0/img_2.jpeg",
],
)
],
)
@pytest.mark.parametrize("org", [""])
def test_create_task_with_cloud_storage_directories_and_predefined_sorting(
self,
cloud_storage_id: int,
use_manifest: bool,
server_files: list[str],
expected_result: list[str],
org: str,
cloud_storages,
request,
):
cloud_storage = cloud_storages[cloud_storage_id]
task_id, _ = self._create_task_with_cloud_data(
request, cloud_storage, use_manifest, server_files, sorting_method="predefined", org=org
)
with make_api_client(self._USERNAME) as api_client:
(_, response) = api_client.tasks_api.retrieve(task_id)
assert response.status == HTTPStatus.OK
# check sequence of frames
(data_meta, _) = api_client.tasks_api.retrieve_data_meta(task_id)
assert expected_result == [x.name for x in data_meta.frames]
@pytest.mark.with_external_services
@pytest.mark.parametrize(
"storage_id, manifest",
[
(1, "images_with_manifest/manifest.jsonl"), # public bucket
(2, "sub/images_with_manifest/manifest.jsonl"), # private bucket
],
)
@pytest.mark.parametrize(
"spec, field",
[
("spec", "source_storage"),
("spec", "target_storage"),
("data", "cloud_storage_id"),
],
)
def test_user_cannot_create_task_with_cloud_storage_without_access(
self, storage_id, spec, field, manifest, regular_lonely_user
):
user = regular_lonely_user
task_spec = {
"name": f"Task with files from foreign cloud storage {storage_id}",
"labels": [
{
"name": "car",
}
],
}
data_spec = {
"image_quality": 75,
"use_cache": True,
}
if spec == "spec":
task_spec.update(
{
field: {
"location": "cloud_storage",
"cloud_storage_id": storage_id,
}
}
)
data_spec["server_files"] = ["images/image_1.jpg"]
elif spec == "data":
data_spec.update(
{
field: storage_id,
"filename_pattern": "*",
"server_files": [manifest],
}
)
else:
assert False
with pytest.raises(exceptions.ApiException) as capture:
create_task(user, task_spec, data_spec)
assert capture.value.status == HTTPStatus.FORBIDDEN
@pytest.mark.with_external_services
@pytest.mark.parametrize("cloud_storage_id", [1])
@pytest.mark.parametrize(
"manifest, filename_pattern, sub_dir, task_size, expected_error",
[
("manifest.jsonl", "*", True, 3, ""), # public bucket
("manifest.jsonl", "test/*", True, 3, ""),
("manifest.jsonl", "test/sub*1.jpeg", True, 1, ""),
("manifest.jsonl", "*image*.jpeg", True, 3, ""),
("manifest.jsonl", "wrong_pattern", True, 0, "No media data found"),
("abc_manifest.jsonl", "[a-c]*.jpeg", False, 2, ""),
("abc_manifest.jsonl", "[d]*.jpeg", False, 1, ""),
("abc_manifest.jsonl", "[e-z]*.jpeg", False, 0, "No media data found"),
(None, "*", True, 0, "Combined media types are not supported"),
(None, "test/*", True, 3, ""),
(None, "test/sub*1.jpeg", True, 1, ""),
(None, "*image*.jpeg", True, 3, ""),
(None, "wrong_pattern", True, 0, "No media data found"),
(None, "[a-c]*.jpeg", False, 2, ""),
(None, "[d]*.jpeg", False, 1, ""),
(None, "[e-z]*.jpeg", False, 0, "No media data found"),
],
)
def test_create_task_with_file_pattern(
self,
cloud_storage_id,
manifest,
filename_pattern,
sub_dir,
task_size,
expected_error,
cloud_storages,
request,
):
# prepare dataset on the bucket
prefixes = ("test_image_",) * 3 if sub_dir else ("a_", "b_", "d_")
images = generate_image_files(3, prefixes=prefixes)
s3_client = s3.make_client()
cloud_storage = cloud_storages[cloud_storage_id]
for image in images:
s3_client.create_file(
data=image,
bucket=cloud_storage["resource"],
filename=f"{'test/sub/' if sub_dir else ''}{image.name}",
)
request.addfinalizer(
partial(
s3_client.remove_file,
bucket=cloud_storage["resource"],
filename=f"{'test/sub/' if sub_dir else ''}{image.name}",
)
)
if manifest:
with TemporaryDirectory() as tmp_dir:
for image in images:
with open(osp.join(tmp_dir, image.name), "wb") as f:
f.write(image.getvalue())
generate_manifest(tmp_dir)
with open(osp.join(tmp_dir, "manifest.jsonl"), mode="rb") as m_file:
s3_client.create_file(
data=m_file.read(),
bucket=cloud_storage["resource"],
filename=f"test/sub/{manifest}" if sub_dir else manifest,
)
request.addfinalizer(
partial(
s3_client.remove_file,
bucket=cloud_storage["resource"],
filename=f"test/sub/{manifest}" if sub_dir else manifest,
)
)
task_spec = {
"name": f"Task with files from cloud storage {cloud_storage_id}",
"labels": [
{
"name": "car",
}
],
}
data_spec = {
"image_quality": 75,
"use_cache": True,
"cloud_storage_id": cloud_storage_id,
"filename_pattern": filename_pattern,
}
if manifest:
data_spec["server_files"] = [f"test/sub/{manifest}" if sub_dir else manifest]
if task_size:
task_id, _ = create_task(self._USERNAME, task_spec, data_spec)
with make_api_client(self._USERNAME) as api_client:
(task, response) = api_client.tasks_api.retrieve(task_id)
assert response.status == HTTPStatus.OK
assert task.size == task_size
else:
rq_job_details = self._test_cannot_create_task(self._USERNAME, task_spec, data_spec)
assert expected_error and expected_error in rq_job_details.message
@pytest.mark.with_external_services
@pytest.mark.parametrize("use_manifest", [True, False])
@pytest.mark.parametrize("use_cache", [True, False])
@pytest.mark.parametrize(
"sorting_method", ["natural", "predefined", "lexicographical", "random"]
)
@pytest.mark.parametrize(
"cloud_storage_id, org",
[
(1, ""),
],
)
def test_create_task_with_cloud_storage_and_retrieve_data(
self,
use_manifest: bool,
use_cache: bool,
sorting_method: str,
cloud_storage_id: int,
org: str,
cloud_storages,
request,
):
cloud_storage = cloud_storages[cloud_storage_id]
task_id, _ = self._create_task_with_cloud_data(
request=request,
cloud_storage=cloud_storage,
# manifest file should not be uploaded if random sorting is used or if cache is not used
use_manifest=use_manifest and use_cache and (sorting_method != "random"),
use_cache=use_cache,
server_files=[f"test/sub_{i}/img_{j}.jpeg" for i in range(2) for j in range(3)],
org=org,
sorting_method=sorting_method,
)
with make_api_client(self._USERNAME) as api_client:
(_, response) = api_client.tasks_api.retrieve_data(
task_id, type="chunk", quality="compressed", number=0
)
assert response.status == HTTPStatus.OK
@pytest.mark.with_external_services
@pytest.mark.parametrize(
"filenames, sorting_method",
[
(["img_1.jpeg", "img_2.jpeg", "img_10.jpeg"], "natural"),
(["img_10.jpeg", "img_1.jpeg", "img_2.jpeg"], "predefined"),
(["img_1.jpeg", "img_10.jpeg", "img_2.jpeg"], "lexicographical"),
],
)
@pytest.mark.parametrize(
"cloud_storage_id, org",
[