|
| 1 | +import requests |
| 2 | + |
| 3 | +from .tasks import Task |
| 4 | +from .batches import Batch |
| 5 | + |
| 6 | +TASK_TYPES = [ |
| 7 | + 'annotation', |
| 8 | + 'audiotranscription', |
| 9 | + 'categorization', |
| 10 | + 'comparison', |
| 11 | + 'cuboidannotation', |
| 12 | + 'datacollection', |
| 13 | + 'imageannotation', |
| 14 | + 'lineannotation', |
| 15 | + 'namedentityrecognition', |
| 16 | + 'pointannotation', |
| 17 | + 'polygonannotation', |
| 18 | + 'segmentannotation', |
| 19 | + 'transcription', |
| 20 | + 'videoannotation', |
| 21 | + 'videoboxannotation', |
| 22 | + 'videocuboidannotation' |
| 23 | +] |
| 24 | +SCALE_ENDPOINT = 'https://api.scale.com/v1/' |
| 25 | +DEFAULT_LIMIT = 100 |
| 26 | +DEFAULT_OFFSET = 0 |
| 27 | + |
| 28 | + |
| 29 | +class ScaleException(Exception): |
| 30 | + def __init__(self, message, errcode): |
| 31 | + super(ScaleException, self).__init__( |
| 32 | + '<Response [{}]> {}'.format(errcode, message)) |
| 33 | + self.code = errcode |
| 34 | + |
| 35 | + |
| 36 | +class ScaleInvalidRequest(ScaleException, ValueError): |
| 37 | + pass |
| 38 | + |
| 39 | + |
| 40 | +class Paginator(list): |
| 41 | + def __init__(self, docs, total, limit, offset, has_more, next_token=None): |
| 42 | + super(Paginator, self).__init__(docs) |
| 43 | + self.docs = docs |
| 44 | + self.total = total |
| 45 | + self.limit = limit |
| 46 | + self.offset = offset |
| 47 | + self.has_more = has_more |
| 48 | + self.next_token = next_token |
| 49 | + |
| 50 | + |
| 51 | +class Tasklist(Paginator): |
| 52 | + pass |
| 53 | + |
| 54 | + |
| 55 | +class Batchlist(Paginator): |
| 56 | + pass |
| 57 | + |
| 58 | + |
| 59 | +class ScaleClient(object): |
| 60 | + def __init__(self, api_key): |
| 61 | + self.api_key = api_key |
| 62 | + |
| 63 | + def _getrequest(self, endpoint, params=None): |
| 64 | + """Makes a get request to an endpoint. |
| 65 | +
|
| 66 | + If an error occurs, assumes that endpoint returns JSON as: |
| 67 | + { 'status_code': XXX, |
| 68 | + 'error': 'I failed' } |
| 69 | + """ |
| 70 | + params = params or {} |
| 71 | + r = requests.get(SCALE_ENDPOINT + endpoint, |
| 72 | + headers={"Content-Type": "application/json"}, |
| 73 | + auth=(self.api_key, ''), params=params) |
| 74 | + |
| 75 | + if r.status_code == 200: |
| 76 | + return r.json() |
| 77 | + else: |
| 78 | + try: |
| 79 | + error = r.json()['error'] |
| 80 | + except ValueError: |
| 81 | + error = r.text |
| 82 | + if r.status_code == 400: |
| 83 | + raise ScaleInvalidRequest(error, r.status_code) |
| 84 | + else: |
| 85 | + raise ScaleException(error, r.status_code) |
| 86 | + |
| 87 | + def _postrequest(self, endpoint, payload=None): |
| 88 | + """Makes a post request to an endpoint. |
| 89 | +
|
| 90 | + If an error occurs, assumes that endpoint returns JSON as: |
| 91 | + { 'status_code': XXX, |
| 92 | + 'error': 'I failed' } |
| 93 | + """ |
| 94 | + payload = payload or {} |
| 95 | + r = requests.post(SCALE_ENDPOINT + endpoint, json=payload, |
| 96 | + headers={"Content-Type": "application/json"}, |
| 97 | + auth=(self.api_key, '')) |
| 98 | + |
| 99 | + if r.status_code == 200: |
| 100 | + return r.json() |
| 101 | + else: |
| 102 | + try: |
| 103 | + error = r.json()['error'] |
| 104 | + except ValueError: |
| 105 | + error = r.text |
| 106 | + if r.status_code == 400: |
| 107 | + raise ScaleInvalidRequest(error, r.status_code) |
| 108 | + else: |
| 109 | + raise ScaleException(error, r.status_code) |
| 110 | + |
| 111 | + def fetch_task(self, task_id): |
| 112 | + """Fetches a task. |
| 113 | +
|
| 114 | + Returns the associated task. |
| 115 | + """ |
| 116 | + return Task(self._getrequest('task/%s' % task_id), self) |
| 117 | + |
| 118 | + def cancel_task(self, task_id): |
| 119 | + """Cancels a task. |
| 120 | +
|
| 121 | + Returns the associated task. |
| 122 | + Raises a ScaleException if it has already been canceled. |
| 123 | + """ |
| 124 | + return Task(self._postrequest('task/%s/cancel' % task_id), self) |
| 125 | + |
| 126 | + def tasks(self, **kwargs): |
| 127 | + """Returns a list of your tasks. |
| 128 | + Returns up to 100 at a time, to get more, use the next_token param passed back. |
| 129 | +
|
| 130 | + Note that offset is deprecated. |
| 131 | +
|
| 132 | + start/end_time are ISO8601 dates, the time range of tasks to fetch. |
| 133 | + status can be 'completed', 'pending', or 'canceled'. |
| 134 | + type is the task type. |
| 135 | + limit is the max number of results to display per page, |
| 136 | + next_token can be use to fetch the next page of tasks. |
| 137 | + customer_review_status can be 'pending', 'fixed', 'accepted' or 'rejected'. |
| 138 | + offset (deprecated) is the number of results to skip (for showing more pages). |
| 139 | + """ |
| 140 | + allowed_kwargs = {'start_time', 'end_time', 'status', 'type', 'project', |
| 141 | + 'batch', 'limit', 'offset', 'completed_before', 'completed_after', |
| 142 | + 'next_token', 'customer_review_status', 'updated_before', 'updated_after'} |
| 143 | + for key in kwargs: |
| 144 | + if key not in allowed_kwargs: |
| 145 | + raise ScaleInvalidRequest('Illegal parameter %s for ScaleClient.tasks()' |
| 146 | + % key, None) |
| 147 | + response = self._getrequest('tasks', params=kwargs) |
| 148 | + docs = [Task(json, self) for json in response['docs']] |
| 149 | + return Tasklist(docs, response['total'], response['limit'], |
| 150 | + response['offset'], response['has_more'], response.get('next_token')) |
| 151 | + |
| 152 | + def create_task(self, task_type, **kwargs): |
| 153 | + endpoint = 'task/' + task_type |
| 154 | + taskdata = self._postrequest(endpoint, payload=kwargs) |
| 155 | + return Task(taskdata, self) |
| 156 | + |
| 157 | + def create_batch(self, project, batch_name, callback): |
| 158 | + payload = dict(project=project, name=batch_name, callback=callback) |
| 159 | + batchdata = self._postrequest('batches', payload) |
| 160 | + return Batch(batchdata, self) |
| 161 | + |
| 162 | + def get_batch(self, batch_name: str): |
| 163 | + batchdata = self._getrequest('batches/%s' % batch_name) |
| 164 | + return Batch(batchdata, self) |
| 165 | + |
| 166 | + def list_batches(self, **kwargs): |
| 167 | + allowed_kwargs = {'start_time', 'end_time', 'status', 'project', |
| 168 | + 'batch', 'limit', 'offset', } |
| 169 | + for key in kwargs: |
| 170 | + if key not in allowed_kwargs: |
| 171 | + raise ScaleInvalidRequest('Illegal parameter %s for ScaleClient.tasks()' |
| 172 | + % key, None) |
| 173 | + response = self._getrequest('tasks', params=kwargs) |
| 174 | + docs = [Batch(doc, self) for doc in response['docs']] |
| 175 | + return Batchlist( |
| 176 | + docs, response['total'], response['limit'], response['offset'], |
| 177 | + response['has_more'], response.get('next_token'), |
| 178 | + ) |
| 179 | + |
| 180 | + |
| 181 | +def _AddTaskTypeCreator(task_type): |
| 182 | + def create_task_wrapper(self, **kwargs): |
| 183 | + return self.create_task(task_type, **kwargs) |
| 184 | + setattr(ScaleClient, 'create_' + task_type + '_task', create_task_wrapper) |
| 185 | + |
| 186 | + |
| 187 | +for taskType in TASK_TYPES: |
| 188 | + _AddTaskTypeCreator(taskType) |
0 commit comments