-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsdk_interface.py
More file actions
4828 lines (4055 loc) · 176 KB
/
sdk_interface.py
File metadata and controls
4828 lines (4055 loc) · 176 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 collections
import copy
import io
import json
import logging
import os
import sys
import typing
import warnings
from pathlib import Path
from typing import Any
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from typing_extensions import Literal
if sys.version_info < (3, 11):
from typing_extensions import TypedDict, NotRequired, Required # noqa
else:
from typing import TypedDict, NotRequired, Required # noqa
import boto3
from tqdm import tqdm
import lib.core as constants
from lib.infrastructure.controller import Controller
from lib.app.helpers import get_annotation_paths
from lib.app.helpers import get_name_url_duplicated_from_csv
from lib.app.helpers import wrap_error as wrap_validation_errors
from lib.app.interface.base_interface import BaseInterfaceFacade
from lib.app.interface.base_interface import TrackableMeta
from lib.app.interface.types import EmailStr
from lib.app.serializers import BaseSerializer
from lib.app.serializers import FolderSerializer
from lib.app.serializers import ProjectSerializer
from lib.app.serializers import SettingsSerializer
from lib.app.serializers import TeamSerializer
from lib.core import LIMITED_FUNCTIONS
from lib.core import entities
from lib.core.conditions import CONDITION_EQ as EQ
from lib.core.conditions import Condition
from lib.core.jsx_conditions import Filter, OperatorEnum
from lib.core.conditions import EmptyCondition
from lib.core.entities import AttachmentEntity, FolderEntity, BaseItemEntity
from lib.core.entities import SettingEntity
from lib.core.entities.classes import AnnotationClassEntity
from lib.core.entities.classes import AttributeGroup
from lib.core.entities.integrations import IntegrationEntity
from lib.core.entities.integrations import IntegrationTypeEnum
from lib.core.enums import ImageQuality
from lib.core.enums import CustomFieldEntityEnum
from lib.core.enums import ProjectType
from lib.core.enums import ClassTypeEnum
from lib.core.exceptions import AppException
from lib.core.types import PriorityScoreEntity
from lib.core.types import Project
from lib.core.pydantic_v1 import ValidationError
from lib.core.pydantic_v1 import constr
from lib.core.pydantic_v1 import conlist
from lib.core.pydantic_v1 import parse_obj_as
from lib.infrastructure.annotation_adapter import BaseMultimodalAnnotationAdapter
from lib.infrastructure.annotation_adapter import MultimodalSmallAnnotationAdapter
from lib.infrastructure.annotation_adapter import MultimodalLargeAnnotationAdapter
from lib.infrastructure.utils import extract_project_folder
from lib.infrastructure.validators import wrap_error
from lib.app.serializers import WMProjectSerializer
from lib.core.entities.work_managament import WMUserTypeEnum
from lib.core.jsx_conditions import EmptyQuery
logger = logging.getLogger("sa")
NotEmptyStr = constr(strict=True, min_length=1)
PROJECT_STATUS = Literal["NotStarted", "InProgress", "Completed", "OnHold"]
PROJECT_TYPE = Literal[
"Vector",
"Pixel",
"Video",
"Document",
"Tiled",
"PointCloud",
"Multimodal",
]
APPROVAL_STATUS = Literal["Approved", "Disapproved", None]
IMAGE_QUALITY = Literal["compressed", "original"]
ANNOTATION_TYPE = Literal["bbox", "polygon", "point", "tag"]
ANNOTATOR_ROLE = Literal["Admin", "Annotator", "QA"]
FOLDER_STATUS = Literal["NotStarted", "InProgress", "Completed", "OnHold"]
class Setting(TypedDict):
attribute: str
value: Union[str, float, int]
class PriorityScore(TypedDict):
name: str
priority: float
class Attachment(TypedDict, total=False):
url: Required[str] # noqa
name: NotRequired[str] # noqa
integration: NotRequired[str] # noqa
class ItemContext:
"""
A context manager for handling annotations and metadata of an item.
The ItemContext class provides methods to retrieve and manage metadata and component
values for items in the specified context. Below are the descriptions and usage examples for each method.
Example:
::
with sa_client.item_context("project_name/folder_name", "item_name") as context:
metadata = context.get_metadata()
print(metadata)
"""
def __init__(
self,
controller: Controller,
project: Project,
folder: FolderEntity,
item: BaseItemEntity,
overwrite: bool = True,
):
self.controller = controller
self.project = project
self.folder = folder
self.item = item
self._annotation_adapter: Optional[BaseMultimodalAnnotationAdapter] = None
self._overwrite = overwrite
self._annotation = None
def _set_small_annotation_adapter(self, annotation: dict = None):
self._annotation_adapter = MultimodalSmallAnnotationAdapter(
project=self.project,
folder=self.folder,
item=self.item,
controller=self.controller,
overwrite=self._overwrite,
annotation=annotation,
)
def _set_large_annotation_adapter(self, annotation: dict = None):
self._annotation_adapter = MultimodalLargeAnnotationAdapter(
project=self.project,
folder=self.folder,
item=self.item,
controller=self.controller,
annotation=annotation,
)
@property
def annotation_adapter(self) -> BaseMultimodalAnnotationAdapter:
if self._annotation_adapter is None:
res = self.controller.service_provider.annotations.get_upload_chunks(
project=self.project, item_ids=[self.item.id]
)
small_item = next(iter(res["small"]), None)
if small_item:
self._set_small_annotation_adapter()
else:
self._set_large_annotation_adapter()
return self._annotation_adapter
@property
def annotation(self):
return self.annotation_adapter.annotation
def __enter__(self):
"""
Enters the context manager.
Returns:
ItemContext: The instance itself.
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Exits the context manager, saving changes if no exception occurred.
Args:
exc_type (Optional[Type[BaseException]]): Exception type if raised.
exc_val (Optional[BaseException]): Exception instance if raised.
exc_tb (Optional[TracebackType]): Traceback if an exception occurred.
Returns:
bool: True if no exception occurred, False otherwise.
"""
if exc_type:
return False
self.save()
return True
def save(self):
if len(json.dumps(self.annotation).encode("utf-8")) > 15 * 1024 * 1024:
self._set_large_annotation_adapter(self.annotation)
else:
self._set_small_annotation_adapter(self.annotation)
self._annotation_adapter.save()
def get_metadata(self):
"""
Retrieves the metadata associated with the current item context.
:return: A dictionary containing metadata for the current item.
:rtype: dict
Request Example:
::
with client.item_context(("project_name", "folder_name"), 12345) as context:
metadata = context.get_metadata()
print(metadata)
"""
return self.annotation["metadata"]
def get_component_value(self, component_id: str):
"""
Retrieves the value of a specific component within the item context.
:param component_id: The name of the component whose value is to be retrieved.
:type component_id: str
:return: The value of the specified component.
:rtype: Any
Request Example:
::
with client.item_context((101, 202), "item_name") as context: # (101, 202) project and folder IDs
value = context.get_component_value("component_id")
print(value)
"""
return self.annotation_adapter.get_component_value(component_id)
def set_component_value(self, component_id: str, value: Any):
"""
Updates the value of a specific component within the item context.
:param component_id: The component identifier.
:type component_id: str
:param value: The new value to set for the specified component.
:type value: Any
:return: The instance itself to allow method chaining.
:rtype: ItemContext
Request Example:
::
with client.item_context("project_name/folder_name", "item_name") as item_context:
metadata = item_context.get_metadata()
value = item_context.get_component_value("component_id")
item_context.set_component_value("component_id", value)
"""
self.annotation_adapter.set_component_value(component_id, value)
return self
class SAClient(BaseInterfaceFacade, metaclass=TrackableMeta):
"""Create SAClient instance to authorize SDK in a team scope.
In case of no argument has been provided, SA_TOKEN environmental variable
will be checked or $HOME/.superannotate/config.json will be used.
:param token: team token
:type token: str
:param config_path: path to config file
:type config_path: path-like (str or Path)
"""
def __init__(
self,
token: str = None,
config_path: str = None,
):
super().__init__(token, config_path)
def get_project_by_id(self, project_id: int):
"""Returns the project metadata
:param project_id: the id of the project
:type project_id: int
:return: project metadata
:rtype: dict
"""
response = self.controller.get_project_by_id(project_id=project_id)
return ProjectSerializer(response.data).serialize()
def get_folder_by_id(self, project_id: int, folder_id: int):
"""Returns the folder metadata
:param project_id: the id of the project
:type project_id: int
:param folder_id: the id of the folder
:type folder_id: int
:return: folder metadata
:rtype: dict
"""
response = self.controller.get_folder_by_id(
folder_id=folder_id, project_id=project_id
)
response.raise_for_status()
return FolderSerializer(response.data).serialize(
exclude={"completedCount", "is_root"}
)
def get_item_by_id(self, project_id: int, item_id: int):
"""Returns the item metadata
:param project_id: the id of the project
:type project_id: int
:param item_id: the id of the item
:type item_id: int
:return: item metadata
:rtype: dict
"""
project_response = self.controller.get_project_by_id(project_id=project_id)
project_response.raise_for_status()
item = self.controller.get_item_by_id(
item_id=item_id, project=project_response.data
)
return BaseSerializer(item).serialize(exclude={"url", "meta"})
def get_team_metadata(self):
"""Returns team metadata
:return: team metadata
:rtype: dict
"""
response = self.controller.get_team()
return TeamSerializer(response.data).serialize()
def get_user_metadata(
self, pk: Union[int, str], include: List[Literal["custom_fields"]] = None
):
"""
Returns user metadata including optionally, custom fields
:param pk: The email address or ID of the team user.
:type pk: str or int
:param include: Specifies additional fields to include in the response.
Possible values are
- "custom_fields": If provided, the response will include custom fields associated with the team user.
:type include: list of str, optional
:return: metadata of team user.
:rtype: dict
Request Example:
::
client.get_user_metadata(
"example@email.com",
include=["custom_fields"]
)
Response Example:
::
{
"createdAt": "2023-11-27T07:10:24.000Z",
"updatedAt": "2025-02-03T13:35:09.000Z",
"custom_fields": {
"ann_quality_threshold": 80,
"tag": ["Tag1", "Tag2", "Tag3"],
"due_date": 1738671238.7,
},
"email": "example@email.com",
"id": 124341,
"role": "Contributor",
"state": "Confirmed",
"team_id": 23245,
}
"""
user = self.controller.work_management.get_user_metadata(pk=pk, include=include)
return BaseSerializer(user).serialize(by_alias=False)
def set_user_custom_field(
self, pk: Union[int, str], custom_field_name: str, value: Any
):
"""
Set the custom field for team user.
:param pk: The email address or ID of the team user.
:type pk: str or int
:param custom_field_name: The name of the existing custom field assigned to the user.
:type custom_field_name: str
:param value: The new value for the custom field.
- This can be a string, a list of strings, a number, or None depending on the custom field type.
- Multi-select fields must be provided as a list of strings (e.g., ["Tag1", "Tag2"]).
- Date fields must be in Unix timestamp format (e.g., "1738281600").
- Other fields (e.g., text, numbers) should match the expected type as defined in the project schema.
:type value: Any
Request Example:
::
client.set_user_custom_field(
"example@email.com",
custom_field_name="due_date",
value=1738671238.7
)
"""
user = self.controller.work_management.get_user_metadata(pk=pk)
if user.role == WMUserTypeEnum.TeamOwner:
raise AppException(
"Setting custom fields for the Team Owner is not allowed."
)
self.controller.work_management.set_custom_field_value(
entity_id=user.id,
field_name=custom_field_name,
value=value,
entity=CustomFieldEntityEnum.CONTRIBUTOR,
parent_entity=CustomFieldEntityEnum.TEAM,
)
def list_users(
self,
*,
project: Union[int, str] = None,
include: List[Literal["custom_fields"]] = None,
**filters,
):
"""
Search users, including their scores, by filtering criteria.
:param project: Project name or ID, if provided, results will be for project-level,
otherwise results will be for team level.
:type project: str or int
:param include: Specifies additional fields to be included in the response.
Possible values are
- "custom_fields": Includes custom fields and scores assigned to each user.
:param filters: Specifies filtering criteria, with all conditions combined using logical AND.
- Only users matching all filter conditions are returned.
- If no filter operation is provided, an exact match is applied
Supported operations:
- __in: Value is in the provided list.
- __notin: Value is not in the provided list.
- __ne: Value is not equal to the given value.
- __contains: Value contains the specified substring.
- __starts: Value starts with the given prefix.
- __ends: Value ends with the given suffix.
- __gt: Value is greater than the given number.
- __gte: Value is greater than or equal to the given number.
- __lt: Value is less than the given number.
- __lte: Value is less than or equal to the given number.
Filter params::
- id: int
- id__in: list[int]
- email: str
- email__in: list[str]
- email__contains: str
- email__starts: str
- email__ends: str
Following params if project is not selected::
- state: Literal[“Confirmed”, “Pending”]
- state__in: List[Literal[“Confirmed”, “Pending”]]
- role: Literal[“admin”, “contributor”]
- role__in: List[Literal[“admin”, “contributor”]]
Scores and Custom Field Filtering:
- Scores and other custom fields must be prefixed with `custom_field__` .
- Example: custom_field__Due_date__gte="1738281600" (filtering users whose Due_date is after the given Unix timestamp).
- **Text** custom field only works with the following filter params: __in, __notin, __contains
- **Numeric** custom field only works with the following filter params: __in, __notin, __ne, __gt, __gte, __lt, __lte
- **Single-select** custom field only works with the following filter params: __in, __notin, __contains
- **Multi-select** custom field only works with the following filter params: __in, __notin
- **Date picker** custom field only works with the following filter params: __gt, __gte, __lt, __lte
**If custom field has a space, please use the following format to filter them**:
::
user_filters = {"custom_field__accuracy score 30D__lt": 90}
client.list_users(include=["custom_fields"], **user_filters)
:type filters: UserFilters, optional
:return: A list of team/project users metadata that matches the filtering criteria
:rtype: list of dicts
Request Example:
::
client.list_users(
email__contains="@superannotate.com",
include=["custom_fields"],
state__in=["Confirmed"]
custom_fields__Tag__in=["Tag1", "Tag3"]
)
Response Example:
::
[
{
"createdAt": "2023-02-02T14:25:42.000Z",
"updatedAt": "2025-01-23T16:39:03.000Z",
"custom_fields": {
"Ann Quality threshold": 80,
"Tag": ["Tag1", "Tag2", "Tag3"],
},
"email": "example@superannotate.com",
"id": 30328,
"role": "TeamOwner",
"state": "Confirmed",
"team_id": 44311,
}
]
Request Example:
::
# Project level scores
scores = client.list_users(
include=["custom_fields"],
project="my_multimodal",
email__contains="@superannotate.com",
custom_field__speed__gte=90,
custom_field__weight__lte=1,
)
Response Example:
::
# Project level scores
[
{
"createdAt": "2025-03-07T13:19:59.000Z",
"updatedAt": "2025-03-07T13:19:59.000Z",
"custom_fields": {"speed": 92, "weight": 0.8},
"email": "example@superannotate.com",
"id": 715121,
"role": "Annotator",
"state": "Confirmed",
"team_id": 1234,
}
]
Request Example:
::
# Team level scores
user_filters = {
"custom_field__accuracy score 30D__lt": 95,
"custom_field__speed score 7D__lt": 15
}
scores = client.list_users(
include=["custom_fields"],
email__contains="@superannotate.com",
role="Contributor",
**user_filters
)
Response Example:
::
# Team level scores
[
{
"createdAt": "2025-03-07T13:19:59.000Z",
"updatedAt": "2025-03-07T13:19:59.000Z",
"custom_fields": {
"Test custom field": 80,
"Tag custom fields": ["Tag1", "Tag2"],
"accuracy score 30D": 95,
"accuracy score 14D": 47,
"accuracy score 7D": 24,
"speed score 30D": 33,
"speed score 14D": 22,
"speed score 7D": 11,
},
"email": "example@superannotate.com",
"id": 715121,
"role": "Contributor",
"state": "Confirmed",
"team_id": 1234,
}
]
"""
if project is not None:
if isinstance(project, int):
project = self.controller.get_project_by_id(project)
else:
project = self.controller.get_project(project)
response = BaseSerializer.serialize_iterable(
self.controller.work_management.list_users(
project=project, include=include, **filters
)
)
if project:
for user in response:
user["role"] = self.controller.service_provider.get_role_name(
project, user["role"]
)
return response
def pause_user_activity(
self, pk: Union[int, str], projects: Union[List[int], List[str], Literal["*"]]
):
"""
Block the team contributor from requesting items from the projects.
:param pk: The email address or user ID of the team contributor.
:type pk: str or int
:param projects: A list of project names or IDs from which the user should be blocked.
The special value "*" means block access to all projects
:type projects: Union[List[int], List[str], Literal["*"]]
"""
user = self.controller.work_management.get_user_metadata(pk=pk)
if user.role is not WMUserTypeEnum.Contributor:
raise AppException("User must have a contributor role to pause activity.")
self.controller.work_management.update_user_activity(
user_email=user.email, provided_projects=projects, action="pause"
)
logger.info(
f"User with email {user.email} has been successfully paused from the specified projects: {projects}."
)
def resume_user_activity(
self, pk: Union[int, str], projects: Union[List[int], List[str], Literal["*"]]
):
"""
Resume the team contributor from requesting items from the projects.
:param pk: The email address or user ID of the team contributor.
:type pk: str or int
:param projects: A list of project names or IDs from which the user should be resumed.
The special value "*" means resume access to all projects
:type projects: Union[List[int], List[str], Literal["*"]]
"""
user = self.controller.work_management.get_user_metadata(pk=pk)
if user.role is not WMUserTypeEnum.Contributor:
raise AppException("User must have a contributor role to resume activity.")
self.controller.work_management.update_user_activity(
user_email=user.email, provided_projects=projects, action="resume"
)
logger.info(
f"User with email {user.email} has been successfully unblocked from the specified projects: {projects}."
)
def get_user_scores(
self,
project: Union[NotEmptyStr, Tuple[int, int], Tuple[str, str]],
item: Union[NotEmptyStr, int],
scored_user: NotEmptyStr,
*,
score_names: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""
Retrieve score metadata for a user for a specific item in a specific project.
:param project: Project and folder as a tuple, folder is optional.
:type project: Union[str, Tuple[int, int], Tuple[str, str]]
:param item: The unique ID or name of the item.
:type item: Union[str, int]
:param scored_user: The email address of the project user.
:type scored_user: str
:param score_names: A list of score names to filter by. If None, returns all scores.
:type score_names: Optional[List[str]]
:return: A list of dictionaries containing score metadata for the user.
:rtype: list of dicts
Request Example:
::
client.get_user_scores(
project=("my_multimodal", "folder1"),
item="item1",
scored_user="example@superannotate.com",
score_names=["Accuracy Score", "Speed"]
)
Response Example:
::
[
{
"createdAt": "2024-06-01T13:00:00",
"updatedAt": "2024-06-01T13:00:00",
"id": 3217575,
"name": "Accuracy Score",
"value": 98,
"weight": 4,
},
{
"createdAt": "2024-06-01T13:00:00",
"updatedAt": "2024-06-01T13:00:00",
"id": 5657575,
"name": "Speed",
"value": 9,
"weight": 0.4,
},
]
"""
project, folder = self.controller.get_project_folder(project)
if project.type != ProjectType.MULTIMODAL:
raise AppException(
"This function is only supported for Multimodal projects."
)
item = self.controller.get_item(project=project, folder=folder, item=item)
response = BaseSerializer.serialize_iterable(
self.controller.work_management.get_user_scores(
project=project,
item=item,
scored_user=scored_user,
provided_score_names=score_names,
)
)
return response
def set_user_scores(
self,
project: Union[NotEmptyStr, Tuple[int, int], Tuple[str, str]],
item: Union[NotEmptyStr, int],
scored_user: NotEmptyStr,
scores: List[Dict[str, Any]],
):
"""
Assign score metadata for a user in a scoring component.
:param project: Project and folder as a tuple, folder is optional.
:type project: Union[str, Tuple[int, int], Tuple[str, str]]
:param item: The unique ID or name of the item.
:type item: Union[str, int]
:param scored_user: Set the email of the user being scored.
:type scored_user: str
:param scores: A list of dictionaries containing the following key-value pairs:
* **component_id** (*str*): The component_id of the score (required).
* **value** (*Any*): The score value (required).
* **weight** (*Union[float, int]*, optional): The weight of the score. Defaults to `1` if not provided.
**Example**:
::
scores = [
{
"component_id": "<component_id_for_score>", # str (required)
"value": 90, # Any (required)
"weight": 1 # Union[float, int] (optional, defaults to 1.0 if not provided)
}
]
:type scores: List[Dict[str, Any]
Request Example:
::
client.set_user_scores(
project=("my_multimodal", "folder1"),
item_=12345,
scored_user="example@superannotate.com",
scores=[
{"component_id": "r_kfrp3n", "value": 90},
{"component_id": "h_jbrp4v", "value": 9, "weight": 4.0},
{"component_id": "m_kf8pss", "value": None, "weight": None},
]
)
"""
project, folder = self.controller.get_project_folder(project)
if project.type != ProjectType.MULTIMODAL:
raise AppException(
"This function is only supported for Multimodal projects."
)
item = self.controller.get_item(project=project, folder=folder, item=item)
editor_template = self.controller.projects.get_editor_template(project.id)
components = editor_template.get("components", [])
self.controller.work_management.set_user_scores(
project=project,
item=item,
scored_user=scored_user,
scores=scores,
components=components,
)
logger.info("Scores successfully set.")
def get_component_config(self, project: Union[NotEmptyStr, int], component_id: str):
"""
Retrieves the configuration for a given project and component ID.
:param project: The identifier of the project, which can be a string or an integer representing the project ID.
:type project: Union[str, int]
:param component_id: The ID of the component for which the context is to be retrieved.
:type component_id: str
:return: The context associated with the `webComponent`.
:rtype: Any
:raises AppException: If the project type is not `MULTIMODAL` or no `webComponent` context is found.
"""
def retrieve_context(
component_data: List[dict], component_pk: str
) -> Tuple[bool, typing.Any]:
try:
for component in component_data:
if "children" in component:
found, val = retrieve_context(
component["children"], component_pk
)
if found:
return found, val
if (
"id" in component
and component["id"] == component_pk
and component["type"] == "webComponent"
):
context = component.get("context")
if context is None or context == "":
return False, None
return True, json.loads(component.get("context"))
except KeyError as e:
logger.debug("Got key error:", component_data)
raise e
return False, None
project = (
self.controller.get_project_by_id(project).data
if isinstance(project, int)
else self.controller.get_project(project)
)
if project.type != ProjectType.MULTIMODAL:
raise AppException(
"This function is only supported for Multimodal projects."
)
editor_template = self.controller.projects.get_editor_template(project.id)
components = editor_template.get("components", [])
_found, _context = retrieve_context(components, component_id)
if not _found:
raise AppException("No component context found for project.")
return _context
def search_team_contributors(
self,
email: EmailStr = None,
first_name: NotEmptyStr = None,
last_name: NotEmptyStr = None,
return_metadata: bool = True,
):
"""Search for contributors in the team
:param email: filter by email
:type email: str
:param first_name: filter by first name
:type first_name: str
:param last_name: filter by last name
:type last_name: str
:param return_metadata: return metadata of contributors instead of names
:type return_metadata: bool
:return: metadata of found users
:rtype: list of dicts
"""
contributors = self.controller.search_team_contributors(
email=email, first_name=first_name, last_name=last_name
).data
if not return_metadata:
return [contributor["email"] for contributor in contributors]
return contributors
def search_projects(
self,
name: Optional[NotEmptyStr] = None,
return_metadata: bool = False,
include_complete_item_count: bool = False,
status: Optional[Union[PROJECT_STATUS, List[PROJECT_STATUS]]] = None,
):
"""
Project name based case-insensitive search for projects.
If **name** is None, all the projects will be returned.
:param name: search string
:type name: str
:param return_metadata: return metadata of projects instead of names
:type return_metadata: bool
:param include_complete_item_count: return projects that have completed items and include
the number of completed items in response.
:type include_complete_item_count: bool
:param status: search projects via project status
:type status: str
:return: project names or metadatas
:rtype: list of strs or dicts
"""
statuses = []
if status:
if isinstance(status, (list, tuple, set)):
statuses = list(status)
else:
statuses = [status]
condition = Condition.get_empty_condition()
if name:
condition &= Condition("name", name, EQ)
if include_complete_item_count:
condition &= Condition(
"completeImagesCount", include_complete_item_count, EQ
)
for _status in statuses:
condition &= Condition("status", constants.ProjectStatus(_status).value, EQ)
response = self.controller.projects.list(condition)
if response.errors:
raise AppException(response.errors)
if return_metadata:
return [
ProjectSerializer(project).serialize(
exclude={
"settings",
"workflows",
"contributors",
"classes",
"item_count",
}
)
for project in response.data
]
return [project.name for project in response.data]