-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy path__init__.py
More file actions
1456 lines (1241 loc) · 47.2 KB
/
__init__.py
File metadata and controls
1456 lines (1241 loc) · 47.2 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
from datetime import datetime
from typing import IO, Dict, Generator, Generic, List, Optional, TypeVar, Union
from pydantic import Field, StrictStr
from typing_extensions import Annotated
from scaleapi.api_client.v2 import ApiClient, Configuration, ExpandableEnumTask, Option
from scaleapi.api_client.v2 import Task as V2Task
from scaleapi.api_client.v2 import V2Api
from scaleapi.batches import Batch, BatchStatus
from scaleapi.evaluation_tasks import EvaluationTask
from scaleapi.exceptions import ScaleInvalidRequest
from scaleapi.files import File
from scaleapi.projects import Project, TaskTemplate
from scaleapi.training_tasks import TrainingTask
from ._version import __version__ # noqa: F401
from .api import Api
from .studio import StudioBatch, StudioLabelerAssignment, StudioProjectGroup
from .tasks import Task, TaskReviewStatus, TaskStatus, TaskType
from .teams import Teammate, TeammateRole
T = TypeVar("T")
class Paginator(list, Generic[T]):
"""Paginator for list endpoints"""
def __init__(
self,
docs: List[T],
total: int,
limit: int,
offset: int,
has_more: bool,
next_token=None,
):
super().__init__(docs)
self.docs = docs
self.total = total
self.limit = limit
self.offset = offset
self.has_more = has_more
self.next_token = next_token
class Tasklist(Paginator[Task]):
"""Tasks Paginator"""
class Batchlist(Paginator[Batch]):
"""Batches Paginator"""
class ScaleClient:
"""Main class serves as an interface for Scale API"""
def __init__(
self,
api_key,
source=None,
api_instance_url=None,
verify=None,
proxies=None,
cert=None,
):
self.api = Api(
api_key,
user_agent_extension=source,
api_instance_url=api_instance_url,
verify=verify,
proxies=proxies,
cert=cert,
)
configuration = Configuration(access_token=api_key)
api_client = ApiClient(configuration)
api_client.user_agent = Api._generate_useragent(source)
self.v2 = V2Api(api_client)
def get_task(self, task_id: str) -> Task:
"""Fetches a task.
Returns the associated task.
Args:
task_id (str):
Task identifier
Returns:
Task:
"""
endpoint = f"task/{task_id}"
return Task(self.api.get_request(endpoint), self)
def cancel_task(self, task_id: str, clear_unique_id: bool = False) -> Task:
"""Cancels a task and returns the associated task.
Raises a ScaleException if it has already been canceled.
Args:
task_id (str):
Task id
clear_unique_id (boolean):
Option to clear unique id when the task is deleted
Returns:
Task
"""
if clear_unique_id:
endpoint = f"task/{task_id}/cancel?clear_unique_id=true"
else:
endpoint = f"task/{task_id}/cancel"
return Task(self.api.post_request(endpoint), self)
def audit_task(self, task_id: str, accepted: bool, comments: str = None):
"""Allows you to accept or reject completed tasks.
Along with support for adding comments about the reason
for the given audit status, mirroring our Audit UI.
Args:
task_id (str):
Task id
accepted (boolean):
Optional, additional feedback to record the reason
for the audit status
"""
payload = {"accepted": accepted, "comments": comments}
endpoint = f"task/{task_id}/audit"
self.api.post_request(endpoint, body=payload)
def update_task_unique_id(self, task_id: str, unique_id: str) -> Task:
"""Updates a task's unique_id and returns the associated task.
Raises a ScaleDuplicateResource exception if unique_id
is already in use.
Args:
task_id (str):
Task id
unique_id (str):
unique_id to set
Returns:
Task
"""
payload = {"unique_id": unique_id}
endpoint = f"task/{task_id}/unique_id"
return Task(self.api.post_request(endpoint, body=payload), self)
def clear_task_unique_id(self, task_id: str) -> Task:
"""Clears a task's unique_id and returns the associated task.
Args:
task_id (str):
Task id
Returns:
Task
"""
endpoint = f"task/{task_id}/unique_id"
return Task(self.api.delete_request(endpoint), self)
def set_task_metadata(self, task_id: str, metadata: Dict) -> Task:
"""Sets a task's metadata and returns the associated task.
Args:
task_id (str):
Task id
metadata (Dict):
metadata to set
Returns:
Task
"""
endpoint = f"task/{task_id}/setMetadata"
return Task(self.api.post_request(endpoint, body=metadata), self)
def set_task_tags(self, task_id: str, tags: List[str]) -> Task:
"""Sets completely new list of tags to a task and returns the
associated task.
Args:
task_id (str):
Task id
tags (List[str]):
List of new tags to set
Returns:
Task
"""
endpoint = f"task/{task_id}/tags"
return Task(self.api.post_request(endpoint, body=tags), self)
def add_task_tags(self, task_id: str, tags: List[str]) -> Task:
"""Adds a list of tags to a task and returns the
associated task.
Args:
task_id (str):
Task id
tags (List[str]):
List of tags to add.
Already present tags will be ignored.
Returns:
Task
"""
endpoint = f"task/{task_id}/tags"
return Task(self.api.put_request(endpoint, body=tags), self)
def delete_task_tags(self, task_id: str, tags: List[str]) -> Task:
"""Deletes a list of tags from a task and returns the
associated task.
Args:
task_id (str):
Task id
tags (List[str]):
List of tags to delete. Nonpresent tags will be ignored.
Returns:
Task
"""
endpoint = f"task/{task_id}/tags"
return Task(self.api.delete_request(endpoint, body=tags), self)
def tasks(self, **kwargs) -> Tasklist:
"""Returns a list of your tasks.
Returns up to 100 at a time, to get more, use the
next_token param passed back.
Valid Args:
start_time (str):
The minimum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
end_time (str):
The maximum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
status (str):
Status to filter tasks, can be 'completed', 'pending',
or 'canceled'
type (str):
Task type to filter. i.e. 'imageannotation'
project (str):
Project name to filter tasks by
batch (str):
Batch name to filter tasks by
customer_review_status (str):
Audit status of task, can be 'pending', 'fixed',
'accepted' or 'rejected'.
unique_id (List[str] | str):
The unique_id of a task.
completed_after (str):
The minimum value of `completed_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
completed_before (str):
The maximum value of `completed_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
updated_after (str):
The minimum value of `updated_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
updated_before (str):
The maximum value of `updated_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_after (str):
The minimum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_before (str):
The maximum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
tags (List[str] | str):
The tags of a task; multiple tags can be
specified as a list.
limit (int):
Determines the page size (1-100)
include_attachment_url (bool):
If true, returns a pre-signed s3 url for the
attachment used to create the task.
limited_response (bool):
If true, returns task response of the following fields:
task_id, status, metadata, project, otherVersion.
next_token (str):
Can be use to fetch the next page of tasks
"""
allowed_kwargs = {
"start_time",
"end_time",
"status",
"type",
"project",
"batch",
"limit",
"completed_before",
"completed_after",
"next_token",
"customer_review_status",
"tags",
"updated_before",
"updated_after",
"unique_id",
"include_attachment_url",
"limited_response",
}
for key in kwargs:
if key not in allowed_kwargs:
raise ScaleInvalidRequest(
f"Illegal parameter {key} for ScaleClient.tasks()"
)
response = self.api.get_request("tasks", params=kwargs)
docs = [Task(json, self) for json in response["docs"]]
return Tasklist(
docs,
response["total"],
response["limit"],
response["offset"],
response["has_more"],
response.get("next_token"),
)
def v2_get_tasks(
self,
project_id: Optional[StrictStr] = None,
project_name: Optional[StrictStr] = None,
batch_id: Optional[StrictStr] = None,
batch_name: Optional[StrictStr] = None,
status: Optional[TaskStatus] = None,
completed_after: Optional[datetime] = None,
completed_before: Optional[datetime] = None,
limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = None,
expand: Optional[List[ExpandableEnumTask]] = None,
opts: Optional[List[Option]] = None,
) -> Generator[V2Task, None, None]:
"""Retrieve all tasks as a `generator` method, with the
given parameters. This methods handles pagination of
v2.get_tasks() method.
In order to retrieve results as a list, please use:
`task_list = list(v2_get_tasks(...))`
:param project_id: Scale's unique identifier for the
project.
:type project_id: str
:param project_name: The name of the project.
:type project_name: str
:param batch_id: Scale's unique identifier for the
batch.
:type batch_id: str
:param batch_name: The name of the batch.
:type batch_name: str
:param status: The current status of the task, indicating
whether it is pending, completed, error, or canceled.
:type status: TaskStatus
:param completed_after: Tasks with a `completed_at` after
the given date will be returned. A timestamp formatted
as an ISO 8601 date-time string.
:type completed_after: datetime
:param completed_before: Tasks with a `completed_at` before
the given date will be returned. A timestamp formatted
as an ISO 8601 date-time string.
:type completed_before: datetime
:param limit: Limit the number of entities returned.
:type limit: int
:param expand: List of fields to
[expand](/api-reference/expanding-entities) in the response.
:type expand: List[ExpandableEnumTask]
:param opts: List of properties to include in the task response.
:type opts: List[Option]
Yields:
Generator[V2Task]:
Yields Task objects, can be iterated.
"""
tasks_args = {
"project_id": project_id,
"project_name": project_name,
"batch_id": batch_id,
"batch_name": batch_name,
"status": status,
"completed_after": completed_after,
"completed_before": completed_before,
"limit": limit,
"expand": expand,
"opts": opts,
}
next_token = None
has_more = True
while has_more:
tasks_args["next_token"] = next_token
tasks = self.v2.get_tasks(**tasks_args)
yield from tasks.tasks
next_token = tasks.next_token
has_more = tasks.next_token is not None
def get_tasks(
self,
project_name: str = None,
batch_name: str = None,
task_type: TaskType = None,
status: TaskStatus = None,
review_status: Union[List[TaskReviewStatus], TaskReviewStatus] = None,
unique_id: Union[List[str], str] = None,
completed_after: str = None,
completed_before: str = None,
updated_after: str = None,
updated_before: str = None,
created_after: str = None,
created_before: str = None,
tags: Union[List[str], str] = None,
include_attachment_url: bool = True,
limited_response: bool = None,
limit: int = None,
) -> Generator[Task, None, None]:
"""Retrieve all tasks as a `generator` method, with the
given parameters. This methods handles pagination of
tasks() method.
In order to retrieve results as a list, please use:
`task_list = list(get_tasks(...))`
Args:
project_name (str, optional):
Project Name
batch_name (str, optional):
Batch Name
task_type (TaskType, optional):
Task type to filter i.e. `TaskType.TextCollection`
status (TaskStatus, optional):
Task status i.e. `TaskStatus.Completed`
review_status (List[TaskReviewStatus] | TaskReviewStatus):
The status of the audit result of the task.
Input can be a single element or a list of
TaskReviewStatus. i.e. `TaskReviewStatus.Accepted` to
filter the tasks that you accepted after audit.
unique_id (List[str] | str, optional):
The unique_id of a task. Multiple unique IDs can be
specified at the same time as a list.
completed_after (str, optional):
The minimum value of `completed_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
completed_before (str, optional):
The maximum value of `completed_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
updated_after (str, optional):
The minimum value of `updated_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
updated_before (str, optional):
The maximum value of `updated_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_after (str, optional):
The minimum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_before (str, optional):
The maximum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
tags (List[str] | str, optional):
The tags of a task; multiple tags can be
specified as a list.
include_attachment_url (bool):
If true, returns a pre-signed s3 url for the
attachment used to create the task.
limited_response (bool):
If true, returns task response of the following fields:
task_id, status, metadata, project, otherVersion.
limit (int):
Determines the task count per request (1-100)
For large sized tasks, use a smaller limit
Yields:
Generator[Task]:
Yields Task objects, can be iterated.
"""
if not project_name and not batch_name:
raise ValueError(
"At least one of project_name or batch_name must be provided."
)
next_token = None
has_more = True
tasks_args = self._process_tasks_endpoint_args(
project_name,
batch_name,
task_type,
status,
review_status,
unique_id,
completed_after,
completed_before,
updated_after,
updated_before,
created_after,
created_before,
tags,
include_attachment_url,
limited_response,
)
if limit:
tasks_args["limit"] = limit
while has_more:
tasks_args["next_token"] = next_token
tasks = self.tasks(**tasks_args)
yield from tasks.docs
next_token = tasks.next_token
has_more = tasks.has_more
def get_tasks_count(
self,
project_name: str = None,
batch_name: str = None,
task_type: TaskType = None,
status: TaskStatus = None,
review_status: Union[List[TaskReviewStatus], TaskReviewStatus] = None,
unique_id: Union[List[str], str] = None,
completed_after: str = None,
completed_before: str = None,
updated_after: str = None,
updated_before: str = None,
created_after: str = None,
created_before: str = None,
tags: Union[List[str], str] = None,
include_attachment_url: bool = True,
) -> int:
"""Returns number of tasks with given filters.
Args:
project_name (str, optional):
Project Name
batch_name (str, optional):
Batch Name
task_type (TaskType, optional):
Task type to filter i.e. `TaskType.TextCollection`
status (TaskStatus, optional):
Task status i.e. `TaskStatus.Completed`
review_status (List[TaskReviewStatus] | TaskReviewStatus):
The status of the audit result of the task.
Input can be a single element or a list of
TaskReviewStatus. i.e. `TaskReviewStatus.Accepted` to
filter the tasks that you accepted after audit.
unique_id (List[str] | str, optional):
The unique_id of a task. Multiple unique IDs can be
specified at the same time as a list.
completed_after (str, optional):
The minimum value of `completed_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
completed_before (str, optional):
The maximum value of `completed_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
updated_after (str, optional):
The minimum value of `updated_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
updated_before (str, optional):
The maximum value of `updated_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_after (str, optional):
The minimum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_before (str, optional):
The maximum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
tags (List[str] | str, optional):
The tags of a task; multiple tags can be
specified as a list.
include_attachment_url (bool):
If true, returns a pre-signed s3 url for the
attachment used to create the task.
Returns:
int:
Returns number of tasks
"""
if not project_name and not batch_name:
raise ValueError(
"At least one of project_name or batch_name must be provided."
)
tasks_args = self._process_tasks_endpoint_args(
project_name,
batch_name,
task_type,
status,
review_status,
unique_id,
completed_after,
completed_before,
updated_after,
updated_before,
created_after,
created_before,
tags,
include_attachment_url,
)
tasks_args["limit"] = 1
tasks = self.tasks(**tasks_args)
return tasks.total
@staticmethod
def _process_tasks_endpoint_args(
project_name: str = None,
batch_name: str = None,
task_type: TaskType = None,
status: TaskStatus = None,
review_status: Union[List[TaskReviewStatus], TaskReviewStatus] = None,
unique_id: Union[List[str], str] = None,
completed_after: str = None,
completed_before: str = None,
updated_after: str = None,
updated_before: str = None,
created_after: str = None,
created_before: str = None,
tags: Union[List[str], str] = None,
include_attachment_url: bool = True,
limited_response: bool = None,
):
"""Generates args for /tasks endpoint."""
if not project_name and not batch_name:
raise ValueError(
"At least one of project_name or batch_name must be provided."
)
tasks_args = {
"start_time": created_after,
"end_time": created_before,
"project": project_name,
"batch": batch_name,
"completed_before": completed_before,
"completed_after": completed_after,
"tags": tags,
"updated_before": updated_before,
"updated_after": updated_after,
"unique_id": unique_id,
"include_attachment_url": include_attachment_url,
}
if status:
tasks_args["status"] = status.value
if limited_response:
tasks_args["limited_response"] = limited_response
if task_type:
tasks_args["type"] = task_type.value
if review_status:
if isinstance(review_status, List):
value = ",".join(map(lambda x: x.value, review_status))
else:
value = review_status.value
tasks_args["customer_review_status"] = value
return tasks_args
def create_task(self, task_type: TaskType, **kwargs) -> Task:
"""This method can be used for any Scale supported task type.
Parameters may differ based on the given task_type.
https://github.com/scaleapi/scaleapi-python-client#create-task
Args:
task_type (TaskType):
Task type to be created
i.e. `TaskType.ImageAnnotation`
**kwargs:
Passing in the applicable values into thefunction
definition. The applicable fields and further
information for each task type can be found in
Scale's API documentation.
https://docs.scale.com/reference
Returns:
Task:
Returns created task.
"""
endpoint = f"task/{task_type.value}"
taskdata = self.api.post_request(endpoint, body=kwargs)
return Task(taskdata, self)
def create_batch(
self,
project: str,
batch_name: str,
callback: str = "",
calibration_batch: bool = False,
self_label_batch: bool = False,
metadata: Dict = None,
) -> Batch:
"""Create a new Batch within a project.
https://docs.scale.com/reference#batch-creation
Args:
project (str):
Project name to create batch in
batch_name (str):
Batch name
callback (str, optional):
Email to notify, or URL to POST to
when a batch is complete.
calibration_batch (bool):
Only applicable for self serve projects.
Create a calibration_batch batch by setting
the calibration_batch flag to true.
self_label_batch (bool):
Only applicable for self serve projects.
Create a self_label batch by setting
the self_label_batch flag to true.
metadata (Dict):
Optional metadata to be stored at the TaskBatch level
Returns:
Batch: Created batch object
"""
endpoint = "batches"
payload = {
"project": project,
"name": batch_name,
"calibration_batch": calibration_batch,
"self_label_batch": self_label_batch,
"callback": callback,
"metadata": metadata or {},
}
batchdata = self.api.post_request(endpoint, body=payload)
return Batch(batchdata, self)
def finalize_batch(self, batch_name: str) -> Batch:
"""Finalizes a batch so its tasks can be worked on.
https://docs.scale.com/reference#batch-finalization
Args:
batch_name (str):
Batch name
Returns:
Batch
"""
endpoint = f"batches/{Api.quote_string(batch_name)}/finalize"
batchdata = self.api.post_request(endpoint)
return Batch(batchdata, self)
def batch_status(self, batch_name: str) -> Dict:
"""Returns the status of a batch with the counts of
its tasks grouped by task status.
https://docs.scale.com/reference#batch-status
Args:
batch_name (str):
Batch name
Returns:
Dict {
status: Batch status
pending (optional): # of tasks in pending stage
error (optional): # of tasks in error stage
completed (optional): # of tasks in completed stage
canceled (optional): # of tasks in canceled stage
}
"""
endpoint = f"batches/{Api.quote_string(batch_name)}/status"
status_data = self.api.get_request(endpoint)
return status_data
def get_batch(self, batch_name: str) -> Batch:
"""Returns the details of a batch with the given name.
https://docs.scale.com/reference#batch-retrieval
Args:
batch_name (str):
Batch name
Returns:
Batch
"""
endpoint = f"batches/{Api.quote_string(batch_name)}"
batchdata = self.api.get_request(endpoint)
return Batch(batchdata, self)
def batches(self, **kwargs) -> Batchlist:
"""This is a paged endpoint for all of your batches.
Pagination is based off limit and offset parameters,
which determine the page size and how many results to skip.
Returns up to 100 batches at a time (limit).
https://docs.scale.com/reference#batch-list
Valid Args:
start_time (str):
The minimum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
end_time (str):
The maximum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
exclude_archived (bool):
A flag to exclude archived batches if True
status (str):
Status to filter batches by
project (str):
Project name to filter batches by
limit (int):
Determines the page size (1-100)
offset (int):
How many results to skip
Returns:
Batchlist:
Paginated result. Batchlist.docs provides access
to batches list. Batchlist.limit and Batchlist.offset
are helpers for pagination.
"""
allowed_kwargs = {
"start_time",
"end_time",
"exclude_archived",
"status",
"project",
"limit",
"offset",
}
for key in kwargs:
if key not in allowed_kwargs:
raise ScaleInvalidRequest(
f"Illegal parameter {key} for ScaleClient.batches()"
)
endpoint = "batches"
response = self.api.get_request(endpoint, params=kwargs)
docs = [Batch(doc, self) for doc in response["docs"]]
return Batchlist(
docs,
response["totalDocs"],
response["limit"],
response["offset"],
response["has_more"],
)
def get_batches(
self,
project_name: str = None,
batch_status: BatchStatus = None,
created_after: str = None,
created_before: str = None,
exclude_archived: bool = False,
) -> Generator[Batch, None, None]:
"""`Generator` method to yield all batches with the given
parameters.
In order to retrieve results as a list, please use:
`batches_list = list(get_batches(...))`
Args:
project_name (str):
Project Name to filter batches
batch_status (BatchStatus, optional):
i.e. `BatchStatus.Completed`
created_after (str, optional):
The minimum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
created_before (str, optional):
The maximum value of `created_at` in UTC timezone
ISO format: 'YYYY-MM-DD HH:MM:SS.mmmmmm'
exclude_archived (bool):
A flag to exclude archived batches if True
Yields:
Generator[Batch]:
Yields Batch, can be iterated.
"""
has_more = True
offset = 0
while has_more:
batches_args = {
"start_time": created_after,
"end_time": created_before,
"project": project_name,
"offset": offset,
"exclude_archived": exclude_archived,
}
if batch_status:
batches_args["status"] = batch_status.value
batches = self.batches(**batches_args)
yield from batches.docs
offset += batches.limit
has_more = batches.has_more
def set_batch_metadata(self, batch_name: str, metadata: Dict) -> Batch:
"""Sets metadata for a TaskBatch.
Args:
batch_name (str):
Batch name
metadata (Dict):
Metadata to set for TaskBatch
Returns:
Batch
"""
endpoint = f"batches/{Api.quote_string(batch_name)}/setMetadata"
batchdata = self.api.post_request(endpoint, body=metadata)
return Batch(batchdata, self)
def create_project(
self,
project_name: str,
task_type: TaskType,
params: Dict = None,
rapid: bool = False,
studio: bool = False,
dataset_id: Optional[str] = None,
) -> Project:
"""Creates a new project.
https://docs.scale.com/reference#project-creation
Args:
project_name (str):
Project name
task_type (TaskType):
Task Type i.e. `TaskType.ImageAnnotation`
params (Dict):
Project parameters to be specified.
i.e. `{'instruction':'Please label the kittens'}`
rapid (bool):
Whether the project being created is a
Scale Rapid project
studio (bool):
Whether the project being created is a
Scale Studio project
dataset_id (str):
Link this project to an existing Nucleus dataset.
All tasks annotated in this project will
be synced to the given dataset.
Returns:
Project: [description]
"""
endpoint = "projects"
payload = {
"type": task_type.value,
"name": project_name,
"params": params,
"rapid": rapid,
"studio": studio,