-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy path__init__.py
More file actions
783 lines (640 loc) · 24.3 KB
/
__init__.py
File metadata and controls
783 lines (640 loc) · 24.3 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
from typing import IO, Dict, Generator, Generic, List, TypeVar, Union
from scaleapi.batches import Batch, BatchStatus
from scaleapi.exceptions import ScaleInvalidRequest
from scaleapi.files import File
from scaleapi.projects import Project
from ._version import __version__ # noqa: F401
from .api import Api
from .tasks import Task, TaskReviewStatus, TaskStatus, TaskType
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):
self.api = Api(
api_key, user_agent_extension=source, api_instance_url=api_instance_url
)
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) -> Task:
"""Cancels a task and returns the associated task.
Raises a ScaleException if it has already been canceled.
Args:
task_id (str):
Task id
Returns:
Task
"""
endpoint = f"task/{task_id}/cancel"
return Task(self.api.post_request(endpoint), 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)
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",
}
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 get_tasks(
self,
project_name: str,
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,
) -> 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):
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.
Yields:
Generator[Task]:
Yields Task objects, can be iterated.
"""
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,
)
while has_more:
tasks_args["next_token"] = next_token
tasks = self.tasks(**tasks_args)
for task in tasks.docs:
yield task
next_token = tasks.next_token
has_more = tasks.has_more
def get_tasks_count(
self,
project_name: str,
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,
) -> int:
"""Returns number of tasks with given filters.
Args:
project_name (str):
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.
Returns:
int:
Returns number of tasks
"""
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,
)
tasks_args["limit"] = 1
tasks = self.tasks(**tasks_args)
return tasks.total
@staticmethod
def _process_tasks_endpoint_args(
project_name: str,
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,
):
"""Generates args for /tasks endpoint."""
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,
}
if status:
tasks_args["status"] = status.value
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 = "",
instruction_batch: bool = False,
) -> 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.
instruction_batch (bool):
Only applicable for self serve projects.
Create an instruction batch by setting
the instruction_batch flag to true.
Returns:
Batch: Created batch object
"""
endpoint = "batches"
payload = dict(
project=project,
name=batch_name,
instruction_batch=instruction_batch,
callback=callback,
)
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'
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",
"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,
) -> 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'
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,
}
if batch_status:
batches_args["status"] = batch_status.value
batches = self.batches(**batches_args)
for batch in batches.docs:
yield batch
offset += batches.limit
has_more = batches.has_more
def create_project(
self,
project_name: str,
task_type: TaskType,
params: Dict = None,
self_serve: bool = False,
) -> 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 specificed.
i.e. `{'instruction':'Please label the kittens'}`
Returns:
Project: [description]
"""
endpoint = "projects"
payload = dict(
type=task_type.value,
name=project_name,
params=params,
self_serve=self_serve,
)
projectdata = self.api.post_request(endpoint, body=payload)
return Project(projectdata, self)
def get_project(self, project_name: str) -> Project:
"""Retrieves a single project with the given name.
https://docs.scale.com/reference#project-retrieval
Args:
project_name (str):
Project name
Returns:
Project
"""
endpoint = f"projects/{Api.quote_string(project_name)}"
projectdata = self.api.get_request(endpoint)
return Project(projectdata, self)
def get_projects(self) -> List[Project]:
"""Returns all projects.
Refer to Projects API Reference:
https://docs.scale.com/reference#list-all-projects
Same as `projects()` method.
Returns:
List[Project]
"""
return self.projects()
def projects(self) -> List[Project]:
"""Returns all projects.
Refer to Projects API Reference:
https://docs.scale.com/reference#list-all-projects
Returns:
List[Project]
"""
endpoint = "projects"
project_list = self.api.get_request(endpoint)
return [Project(project, self) for project in project_list]
def update_project(self, project_name: str, **kwargs) -> Project:
"""You can set parameters on a project. Project-level-parameters
will be set on future tasks created under this project if they
are not set in the task request. Any parameters specified in
the task request will override any project parameter.
https://docs.scale.com/reference#project-update-parameters
Args:
project_name (str):
Project's name
**kwargs:
Project parameters to be set.
Returns:
Project
"""
endpoint = f"projects/{Api.quote_string(project_name)}/setParams"
projectdata = self.api.post_request(endpoint, body=kwargs)
return Project(projectdata, self)
def upload_file(self, file: IO, **kwargs) -> File:
"""Upload file.
Refer to Files API Reference:
https://docs.scale.com/reference#file-upload-1
Args:
file (IO):
File buffer
Returns:
File
"""
endpoint = "files/upload"
files = {"file": file}
filedata = self.api.post_request(endpoint, files=files, data=kwargs)
return File(filedata, self)
def import_file(self, file_url: str, **kwargs) -> File:
"""Import file from a remote url.
Refer to Files API Reference:
https://docs.scale.com/reference#file-import-1
Args:
file_url (str):
File's url
Returns:
File
"""
endpoint = "files/import"
payload = dict(file_url=file_url, **kwargs)
filedata = self.api.post_request(endpoint, body=payload)
return File(filedata, self)