Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
638 lines (506 loc) · 20.6 KB
/
Copy pathutils.py
File metadata and controls
638 lines (506 loc) · 20.6 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
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import json
from abc import ABCMeta, abstractmethod
from collections.abc import Hashable, Iterator, Sequence
from copy import deepcopy
from http import HTTPStatus
from io import BytesIO
from time import sleep
from typing import Any, Callable, Iterable, Optional, TypeVar, Union
import requests
from cvat_sdk.api_client import apis, models
from cvat_sdk.api_client.api.jobs_api import JobsApi
from cvat_sdk.api_client.api.projects_api import ProjectsApi
from cvat_sdk.api_client.api.tasks_api import TasksApi
from cvat_sdk.api_client.api_client import ApiClient, Endpoint
from cvat_sdk.api_client.exceptions import ForbiddenException
from cvat_sdk.core.helpers import get_paginated_collection
from deepdiff import DeepDiff
from urllib3 import HTTPResponse
from shared.utils.config import USER_PASS, make_api_client, post_method
DEFAULT_RETRIES = 50
DEFAULT_INTERVAL = 0.1
def initialize_export(endpoint: Endpoint, *, expect_forbidden: bool = False, **kwargs) -> str:
(_, response) = endpoint.call_with_http_info(
**kwargs, _parse_response=False, _check_status=False
)
if expect_forbidden:
assert (
response.status == HTTPStatus.FORBIDDEN
), f"Request should be forbidden, status: {response.status}"
raise ForbiddenException()
assert response.status == HTTPStatus.ACCEPTED, f"Status: {response.status}"
# define background request ID returned in the server response
rq_id = json.loads(response.data).get("rq_id")
assert rq_id, "The rq_id parameter was not found in the server response"
return rq_id
def wait_background_request(
api_client: ApiClient,
rq_id: str,
*,
max_retries: int = DEFAULT_RETRIES,
interval: float = DEFAULT_INTERVAL,
) -> tuple[models.Request, HTTPResponse]:
for _ in range(max_retries):
(background_request, response) = api_client.requests_api.retrieve(rq_id)
assert response.status == HTTPStatus.OK
if (
background_request.status.value
== models.RequestStatus.allowed_values[("value",)]["FINISHED"]
):
return background_request, response
sleep(interval)
assert False, (
f"Export process was not finished within allowed time ({interval * max_retries}, sec). "
+ f"Last status was: {background_request.status.value}"
)
def wait_and_download_v2(
api_client: ApiClient,
rq_id: str,
*,
max_retries: int = DEFAULT_RETRIES,
interval: float = DEFAULT_INTERVAL,
) -> bytes:
background_request, _ = wait_background_request(
api_client, rq_id, max_retries=max_retries, interval=interval
)
# return downloaded file in case of local downloading
assert background_request.result_url
headers = api_client.get_common_headers()
query_params = []
api_client.update_params_for_auth(headers=headers, queries=query_params)
assert not query_params # query auth is not expected
response = requests.get(background_request.result_url, headers=headers)
assert response.status_code == HTTPStatus.OK, f"Status: {response.status_code}"
return response.content
def export_v2(
endpoint: Endpoint,
*,
max_retries: int = DEFAULT_RETRIES,
interval: float = DEFAULT_INTERVAL,
expect_forbidden: bool = False,
wait_result: bool = True,
download_result: bool = True,
**kwargs,
) -> Union[bytes, str]:
"""Export datasets|annotations|backups using the second version of export API
Args:
endpoint (Endpoint): Export endpoint, will be called only to initialize export process
max_retries (int, optional): Number of retries when checking process status. Defaults to 30.
interval (float, optional): Interval in seconds between retries. Defaults to 0.1.
expect_forbidden (bool, optional): Should export request be forbidden or not. Defaults to False.
download_result (bool, optional): Download exported file. Defaults to True.
Returns:
bytes: The content of the file if downloaded locally.
str: If `wait_result` or `download_result` were False.
"""
# initialize background process and ensure that the first request returns 403 code if request should be forbidden
rq_id = initialize_export(endpoint, expect_forbidden=expect_forbidden, **kwargs)
if not wait_result:
return rq_id
# check status of background process
if download_result:
return wait_and_download_v2(
endpoint.api_client,
rq_id,
max_retries=max_retries,
interval=interval,
)
background_request, _ = wait_background_request(
endpoint.api_client, rq_id, max_retries=max_retries, interval=interval
)
return background_request.id
def export_dataset(
api: Union[ProjectsApi, TasksApi, JobsApi],
*,
save_images: bool,
max_retries: int = 300,
interval: float = DEFAULT_INTERVAL,
format: str = "CVAT for images 1.1", # pylint: disable=redefined-builtin
**kwargs,
) -> Optional[bytes]:
return export_v2(
api.create_dataset_export_endpoint,
max_retries=max_retries,
interval=interval,
save_images=save_images,
format=format,
**kwargs,
)
# FUTURE-TODO: support username: optional, api_client: optional
# tODO: make func signature more userfrendly
def export_project_dataset(username: str, *args, **kwargs) -> Optional[bytes]:
with make_api_client(username) as api_client:
return export_dataset(api_client.projects_api, *args, **kwargs)
def export_task_dataset(username: str, *args, **kwargs) -> Optional[bytes]:
with make_api_client(username) as api_client:
return export_dataset(api_client.tasks_api, *args, **kwargs)
def export_job_dataset(username: str, *args, **kwargs) -> Optional[bytes]:
with make_api_client(username) as api_client:
return export_dataset(api_client.jobs_api, *args, **kwargs)
def export_backup(
api: Union[ProjectsApi, TasksApi],
*,
max_retries: int = DEFAULT_RETRIES,
interval: float = DEFAULT_INTERVAL,
**kwargs,
) -> Optional[bytes]:
endpoint = api.create_backup_export_endpoint
return export_v2(endpoint, max_retries=max_retries, interval=interval, **kwargs)
def export_project_backup(username: str, *args, **kwargs) -> Optional[bytes]:
with make_api_client(username) as api_client:
return export_backup(api_client.projects_api, *args, **kwargs)
def export_task_backup(username: str, *args, **kwargs) -> Optional[bytes]:
with make_api_client(username) as api_client:
return export_backup(api_client.tasks_api, *args, **kwargs)
def import_resource(
endpoint: Endpoint,
*,
max_retries: int = DEFAULT_RETRIES,
interval: float = DEFAULT_INTERVAL,
expect_forbidden: bool = False,
wait_result: bool = True,
**kwargs,
) -> Optional[models.Request]:
# initialize background process and ensure that the first request returns 403 code if request should be forbidden
(_, response) = endpoint.call_with_http_info(
**kwargs,
_parse_response=False,
_check_status=False,
_content_type="multipart/form-data",
)
if expect_forbidden:
assert response.status == HTTPStatus.FORBIDDEN, "Request should be forbidden"
raise ForbiddenException()
assert response.status == HTTPStatus.ACCEPTED
if not wait_result:
return None
# define background request ID returned in the server response
rq_id = json.loads(response.data).get("rq_id")
assert rq_id, "The rq_id parameter was not found in the server response"
# check status of background process
for _ in range(max_retries):
(background_request, response) = endpoint.api_client.requests_api.retrieve(rq_id)
assert response.status == HTTPStatus.OK
if background_request.status.value in (
models.RequestStatus.allowed_values[("value",)]["FINISHED"],
models.RequestStatus.allowed_values[("value",)]["FAILED"],
):
break
sleep(interval)
else:
assert False, (
f"Import process was not finished within allowed time ({interval * max_retries}, sec). "
+ f"Last status was: {background_request.status.value}"
)
return background_request
def import_backup(
api: Union[ProjectsApi, TasksApi],
*,
max_retries: int = DEFAULT_RETRIES,
interval: float = DEFAULT_INTERVAL,
**kwargs,
):
endpoint = api.create_backup_endpoint
return import_resource(endpoint, max_retries=max_retries, interval=interval, **kwargs)
def import_project_backup(username: str, file_content: BytesIO, **kwargs):
with make_api_client(username) as api_client:
return import_backup(
api_client.projects_api, project_file_request={"project_file": file_content}, **kwargs
)
def import_task_backup(username: str, file_content: BytesIO, **kwargs):
with make_api_client(username) as api_client:
return import_backup(
api_client.tasks_api, task_file_request={"task_file": file_content}, **kwargs
)
def import_project_dataset(username: str, file_content: BytesIO, **kwargs):
with make_api_client(username) as api_client:
return import_resource(
api_client.projects_api.create_dataset_endpoint,
dataset_file_request={"dataset_file": file_content},
**kwargs,
)
def import_task_annotations(username: str, file_content: BytesIO, **kwargs):
with make_api_client(username) as api_client:
return import_resource(
api_client.tasks_api.create_annotations_endpoint,
annotation_file_request={"annotation_file": file_content},
**kwargs,
)
def import_job_annotations(username: str, file_content: BytesIO, **kwargs):
with make_api_client(username) as api_client:
return import_resource(
api_client.jobs_api.create_annotations_endpoint,
annotation_file_request={"annotation_file": file_content},
**kwargs,
)
FieldPath = Sequence[Union[str, Callable]]
class CollectionSimpleFilterTestBase(metaclass=ABCMeta):
# These fields need to be defined in the subclass
user: str
samples: list[dict[str, Any]]
field_lookups: dict[str, FieldPath] = None
cmp_ignore_keys: list[str] = ["updated_date"]
@abstractmethod
def _get_endpoint(self, api_client: ApiClient) -> Endpoint: ...
def _retrieve_collection(self, **kwargs) -> list:
kwargs["return_json"] = True
with make_api_client(self.user) as api_client:
return get_paginated_collection(self._get_endpoint(api_client), **kwargs)
@classmethod
def _get_field(cls, d: dict[str, Any], path: Union[str, FieldPath]) -> Optional[Any]:
assert path
for key in path:
if isinstance(d, dict):
assert isinstance(key, str)
d = d.get(key)
else:
if callable(key):
assert isinstance(d, str)
d = key(d)
else:
d = None
return d
def _map_field(self, name: str) -> FieldPath:
return (self.field_lookups or {}).get(name, [name])
@classmethod
def _find_valid_field_value(
cls, samples: Iterator[dict[str, Any]], field_path: FieldPath
) -> Any:
value = None
for sample in samples:
value = cls._get_field(sample, field_path)
if value:
break
assert value, f"Failed to find a sample for the '{'.'.join(field_path)}' field"
return value
def _get_field_samples(self, field: str) -> tuple[Any, list[dict[str, Any]]]:
field_path = self._map_field(field)
field_value = self._find_valid_field_value(self.samples, field_path)
gt_objects = filter(lambda p: field_value == self._get_field(p, field_path), self.samples)
return field_value, gt_objects
def _compare_results(self, gt_objects, received_objects):
if self.cmp_ignore_keys:
ignore_keys = [f"root['{k}']" for k in self.cmp_ignore_keys]
else:
ignore_keys = None
diff = DeepDiff(
list(gt_objects),
received_objects,
exclude_paths=ignore_keys,
ignore_order=True,
)
assert diff == {}, diff
def _test_can_use_simple_filter_for_object_list(
self, field: str, field_values: Optional[list[Any]] = None
):
gt_objects = []
field_path = self._map_field(field)
if not field_values:
value, gt_objects = self._get_field_samples(field)
field_values = [value]
are_gt_objects_initialized = bool(gt_objects)
for value in field_values:
if not are_gt_objects_initialized:
gt_objects = [
sample
for sample in self.samples
if value == self._get_field(sample, field_path)
]
received_items = self._retrieve_collection(**{field: value})
self._compare_results(gt_objects, received_items)
def get_attrs(obj: Any, attributes: Sequence[str]) -> tuple[Any, ...]:
"""Returns 1 or more object attributes as a tuple"""
return (getattr(obj, attr) for attr in attributes)
def build_exclude_paths_expr(ignore_fields: Iterator[str]) -> list[str]:
exclude_expr_parts = []
for key in ignore_fields:
if "." in key:
key_parts = key.split(".")
expr = r"root\['{}'\]".format(key_parts[0])
expr += "".join(r"\[.*\]\['{}'\]".format(part) for part in key_parts[1:])
else:
expr = r"root\['{}'\]".format(key)
exclude_expr_parts.append(expr)
return exclude_expr_parts
def wait_until_task_is_created(api: apis.RequestsApi, rq_id: str) -> models.Request:
for _ in range(100):
(request_details, _) = api.retrieve(rq_id)
if request_details.status.value in ("finished", "failed"):
return request_details
sleep(1)
raise Exception("Cannot create task")
def create_task(username, spec, data, content_type="application/json", **kwargs):
with make_api_client(username) as api_client:
(task, response_) = api_client.tasks_api.create(spec, **kwargs)
assert response_.status == HTTPStatus.CREATED
sent_upload_start = False
data_kwargs = (kwargs or {}).copy()
data_kwargs.pop("org", None)
data_kwargs.pop("org_id", None)
if data.get("client_files") and "json" in content_type:
(_, response) = api_client.tasks_api.create_data(
task.id,
data_request=models.DataRequest(image_quality=data["image_quality"]),
upload_start=True,
_content_type=content_type,
**data_kwargs,
)
assert response.status == HTTPStatus.ACCEPTED
sent_upload_start = True
# Can't encode binary files in json
(_, response) = api_client.tasks_api.create_data(
task.id,
data_request=models.DataRequest(
client_files=data["client_files"],
image_quality=data["image_quality"],
),
upload_multiple=True,
_content_type="multipart/form-data",
**data_kwargs,
)
assert response.status == HTTPStatus.OK
data = data.copy()
del data["client_files"]
last_kwargs = {}
if sent_upload_start:
last_kwargs["upload_finish"] = True
(result, response) = api_client.tasks_api.create_data(
task.id,
data_request=deepcopy(data),
_content_type=content_type,
**data_kwargs,
**last_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 == "finished", request_details.message
return task.id, response_.headers.get("X-Request-Id")
def compare_annotations(a: dict, b: dict) -> dict:
def _exclude_cb(obj, path: str):
# ignoring track elements which do not have shapes
split_path = path.rsplit("['elements']", maxsplit=1)
if len(split_path) == 2:
if split_path[1].count("[") == 1 and not obj["shapes"]:
return True
return path.endswith("['elements']") and not obj
return DeepDiff(
a,
b,
ignore_order=True,
significant_digits=2, # annotations are stored with 2 decimal digit precision
exclude_obj_callback=_exclude_cb,
exclude_regex_paths=[
r"root\['version|updated_date'\]",
r"root(\['\w+'\]\[\d+\])+\['id'\]",
r"root(\['\w+'\]\[\d+\])+\['label_id'\]",
r"root(\['\w+'\]\[\d+\])+\['attributes'\]\[\d+\]\['spec_id'\]",
r"root(\['\w+'\]\[\d+\])+\['source'\]",
],
)
DATUMARO_FORMAT_FOR_DIMENSION = {
"2d": "Datumaro 1.0",
"3d": "Datumaro 3D 1.0",
}
def calc_end_frame(start_frame: int, stop_frame: int, frame_step: int) -> int:
return stop_frame - ((stop_frame - start_frame) % frame_step) + frame_step
_T = TypeVar("_T")
_T2 = TypeVar("_T2")
def unique(
it: Union[Iterator[_T], Iterable[_T]], *, key: Callable[[_T], Hashable] = None
) -> Iterable[_T]:
return {key(v): v for v in it}.values()
def register_new_user(username: str) -> dict[str, Any]:
response = post_method(
"admin1",
"auth/register",
data={
"username": username,
"password1": USER_PASS,
"password2": USER_PASS,
"email": f"{username}@email.com",
},
)
assert response.status_code == HTTPStatus.CREATED
return response.json()
def invite_user_to_org(
user_email: str,
org_id: int,
role: str,
):
with make_api_client("admin1") as api_client:
invitation, _ = api_client.invitations_api.create(
models.InvitationWriteRequest(
role=role,
email=user_email,
),
org_id=org_id,
)
return invitation
def get_cloud_storage_content(
username: str,
cloud_storage_id: int,
*,
manifest: Optional[str] = None,
prefix: Optional[str] = None,
) -> list[str]:
kwargs = {}
if manifest is not None:
kwargs["manifest_path"] = manifest
if prefix is not None:
kwargs["prefix"] = prefix
prefix = (prefix or "").rstrip("/") + "/"
with make_api_client(username) as api_client:
(data, _) = api_client.cloudstorages_api.retrieve_content_v2(cloud_storage_id, **kwargs)
return [
f"{prefix}{f['name']}{'/' if str(f['type']) == 'DIR' else ''}" for f in data["content"]
]
def export_events(
api_client: ApiClient,
*,
api_version: int,
max_retries: int = 100,
interval: float = 0.1,
**kwargs,
) -> Optional[bytes]:
if api_version == 1:
endpoint = api_client.events_api.list_endpoint
query_id = ""
for _ in range(max_retries):
(_, response) = endpoint.call_with_http_info(
**kwargs, query_id=query_id, _parse_response=False
)
if response.status == HTTPStatus.CREATED:
break
assert response.status == HTTPStatus.ACCEPTED
if not query_id:
response_json = json.loads(response.data)
query_id = response_json["query_id"]
sleep(interval)
assert response.status == HTTPStatus.CREATED
(_, response) = endpoint.call_with_http_info(
**kwargs, query_id=query_id, action="download", _parse_response=False
)
assert response.status == HTTPStatus.OK
return response.data
assert api_version == 2
request_id, response = api_client.events_api.create_export(**kwargs, _check_status=False)
assert response.status == HTTPStatus.ACCEPTED
if "location" in kwargs and "cloud_storage_id" in kwargs:
background_request, response = wait_background_request(
api_client, rq_id=request_id.rq_id, max_retries=max_retries, interval=interval
)
assert background_request.result_url is None
return None
return wait_and_download_v2(
api_client, rq_id=request_id.rq_id, max_retries=max_retries, interval=interval
)
def iter_exclude(
it: Iterable[_T], excludes: Iterable[_T2], *, key: Optional[Callable[[_T], _T2]] = None
) -> Iterable[_T]:
excludes = set(excludes)
if not key:
key = lambda v: v
return (v for v in it if key(v) not in excludes)