-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathtest_client.py
More file actions
402 lines (317 loc) · 11.6 KB
/
test_client.py
File metadata and controls
402 lines (317 loc) · 11.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
# pylint: disable=missing-function-docstring
import os
import time
import uuid
from datetime import datetime
import pytest
import scaleapi
from scaleapi.batches import BatchStatus
from scaleapi.exceptions import (
ScaleDuplicateResource,
ScaleInvalidRequest,
ScaleResourceNotFound,
ScaleUnauthorized,
)
from scaleapi.tasks import TaskType
TEST_PROJECT_NAME = "scaleapi-python-sdk"
try:
print(f"SDK Version: {scaleapi.__version__}")
test_api_key = os.environ["SCALE_TEST_API_KEY"]
if test_api_key.startswith("test_") or test_api_key.endswith("|test"):
client = scaleapi.ScaleClient(test_api_key, "pytest")
else:
raise Exception("Please provide a valid TEST environment key.")
except KeyError as err:
raise Exception(
"Please set the environment variable SCALE_TEST_API_KEY to run tests."
) from err
try:
project = client.get_project(TEST_PROJECT_NAME)
except ScaleResourceNotFound:
client.create_project(
project_name=TEST_PROJECT_NAME, task_type=TaskType.ImageAnnotation
)
def test_invalidkey_fail():
client_fail = scaleapi.ScaleClient("dummy_api_key", "pytest")
with pytest.raises(ScaleUnauthorized):
client_fail.batches(limit=1)
def make_a_task(unique_id: str = None, batch: str = None):
args = {
"callback_url": "http://www.example.com/callback",
"instruction": "Draw a box around each baby cow and big cow.",
"attachment_type": "image",
"attachment": "http://i.imgur.com/v4cBreD.jpg",
"geometries": {
"box": {
"objects_to_annotate": ["Baby Cow", "Big Cow"],
"min_height": 10,
"min_width": 10,
}
},
}
if unique_id:
args["unique_id"] = unique_id
if batch:
args["batch"] = batch
return client.create_task(TaskType.ImageAnnotation, **args)
def test_uniquekey_fail():
unique_key = str(uuid.uuid4())
make_a_task(unique_key)
with pytest.raises(ScaleDuplicateResource):
make_a_task(unique_key)
def test_categorize_ok():
client.create_task(
TaskType.Categorization,
callback_url="http://www.example.com/callback",
instruction="Is this company public or private?",
attachment_type="website",
force=True,
attachment="http://www.google.com/",
categories=["public", "private"],
)
def test_categorize_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.Categorization,
callback_url="http://www.example.com/callback",
categories=["public", "private"],
)
def test_transcription_ok():
client.create_task(
TaskType.Transcription,
callback_url="http://www.example.com/callback",
instruction="Transcribe the given fields. Then for each news item on the page, "
"transcribe the information for the row.",
attachment_type="website",
attachment="http://www.google.com/",
fields={"title": "Title of Webpage", "top_result": "Title of the top result"},
repeatable_fields={
"username": "Username of submitter",
"comment_count": "Number of comments",
},
)
def test_transcription_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.Transcription,
callback_url="http://www.example.com/callback",
attachment_type="website",
)
def test_imageannotation_ok():
client.create_task(
TaskType.ImageAnnotation,
callback_url="http://www.example.com/callback",
instruction="Draw a box around each baby cow and big cow.",
attachment_type="image",
attachment="http://i.imgur.com/v4cBreD.jpg",
geometries={
"box": {
"objects_to_annotate": ["Baby Cow", "Big Cow"],
"min_height": 10,
"min_width": 10,
}
},
)
def test_imageannotation_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.ImageAnnotation,
callback_url="http://www.example.com/callback",
instruction="Draw a box around each **baby cow** and **big cow**",
attachment_type="image",
)
def test_documenttranscription_ok():
client.create_task(
TaskType.DocumentTranscription,
callback_url="http://www.example.com/callback",
instruction="Please transcribe this receipt.",
attachment="http://document.scale.com/receipt-20200519.jpg",
features=[{"type": "block", "label": "barcode"}],
)
def test_documenttranscription_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.DocumentTranscription,
callback_url="http://www.example.com/callback",
instruction="Please transcribe this receipt.",
)
def test_annotation_ok():
client.create_task(
TaskType.Annotation,
callback_url="http://www.example.com/callback",
instruction="Draw a box around each **baby cow** and **big cow**",
attachment_type="image",
attachment="http://i.imgur.com/v4cBreD.jpg",
min_width="30",
min_height="30",
objects_to_annotate=["baby cow", "big cow"],
with_labels=True,
)
def test_annotation_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.Annotation,
callback_url="http://www.example.com/callback",
instruction="Draw a box around each **baby cow** and **big cow**",
attachment_type="image",
)
def test_polygonannotation_ok():
client.create_task(
TaskType.PolygonAnnotation,
callback_url="http://www.example.com/callback",
instruction="Draw a tight shape around the big cow",
attachment_type="image",
attachment="http://i.imgur.com/v4cBreD.jpg",
objects_to_annotate=["big cow"],
with_labels=True,
)
def test_polygonannotation_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.PolygonAnnotation,
callback_url="http://www.example.com/callback",
instruction="Draw a tight shape around the big cow",
attachment_type="image",
)
def test_lineannotation_ok():
client.create_task(
TaskType.LineAnnotation,
callback_url="http://www.example.com/callback",
instruction="Draw a tight shape around the big cow",
attachment_type="image",
attachment="http://i.imgur.com/v4cBreD.jpg",
objects_to_annotate=["big cow"],
with_labels=True,
)
def test_lineannotation_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.LineAnnotation,
callback_url="http://www.example.com/callback",
instruction="Draw a tight shape around the big cow",
attachment_type="image",
)
def test_datacollection_ok():
client.create_task(
TaskType.DataCollection,
callback_url="http://www.example.com/callback",
instruction="Find the URL for the hiring page for the company"
" with attached website.",
attachment_type="website",
attachment="http://www.google.com/",
fields={"hiring_page": "Hiring Page URL"},
)
def test_datacollection_fail():
with pytest.raises(ScaleInvalidRequest):
client.create_task(
TaskType.DataCollection,
callback_url="http://www.example.com/callback",
attachment_type="website",
)
def test_namedentityrecognition_ok():
return client.create_task(
TaskType.NamedEntityRecognition,
callback_url="http://www.example.com/callback",
instruction="Do the objects in these images have the same pattern?",
text="Example text to label with NER tool",
labels=[{"name": "Label_A", "description": "the first label"}],
)
def test_cancel():
task = make_a_task()
# raises a scaleexception, because test tasks complete instantly
with pytest.raises(ScaleInvalidRequest):
task.cancel()
def test_task_retrieval():
task = make_a_task()
task2 = client.get_task(task.id)
assert task2.status == "completed"
assert task2.id == task.id
assert task2.callback_url == task.callback_url
assert task2.instruction == task.instruction
assert task2.params["attachment_type"] == task.params["attachment_type"]
assert task2.params["attachment"] == task.params["attachment"]
assert task2.params["geometries"] == task.params["geometries"]
assert task2.metadata == task.metadata
assert task2.type == task.type
assert task2.created_at == task.created_at
def test_task_retrieval_time():
make_a_task()
time.sleep(0.5)
start_time = datetime.utcnow().isoformat()
time.sleep(0.5)
end_time = datetime.utcnow().isoformat()
tasks = client.tasks(start_time=start_time, end_time=end_time)
assert tasks.docs == []
def test_task_retrieval_fail():
with pytest.raises(ScaleResourceNotFound):
client.get_task("fake_id_qwertyuiop")
def test_tasks():
tasks = []
for _ in range(3):
tasks.append(make_a_task())
task_ids = {task.id for task in tasks}
for task in client.tasks(limit=3):
assert task.id in task_ids
def test_tasks_invalid():
with pytest.raises(ScaleInvalidRequest):
client.tasks(bogus=0)
def create_a_batch():
return client.create_batch(
callback="http://www.example.com/callback",
batch_name=str(uuid.uuid4()),
project=TEST_PROJECT_NAME,
)
def test_get_tasks():
batch = create_a_batch()
tasks = []
for _ in range(3):
tasks.append(make_a_task(batch=batch.name))
task_ids = {task.id for task in tasks}
for task in client.get_tasks(project_name=TEST_PROJECT_NAME, batch_name=batch.name):
assert task.id in task_ids
def test_get_tasks_count():
tasks_count = client.tasks(project=TEST_PROJECT_NAME).total
get_tasks_count = client.get_tasks_count(project_name=TEST_PROJECT_NAME)
assert tasks_count == get_tasks_count
def test_finalize_batch():
batch = create_a_batch()
batch = client.finalize_batch(batch.name)
batch2 = create_a_batch()
batch2.finalize()
def test_get_batch_status():
batch = create_a_batch()
client.batch_status(batch.name)
assert batch.status == BatchStatus.InProgress.value
batch2 = client.get_batch(batch.name)
batch2.get_status() # Test status update
assert batch2.status == BatchStatus.InProgress.value
def test_get_batch():
batch = create_a_batch()
batch2 = client.get_batch(batch.name)
assert batch.name == batch2.name
assert batch2.status == BatchStatus.InProgress.value
def test_batches():
batches = []
for _ in range(3):
batches.append(create_a_batch())
batch_names = {batch.name for batch in batches}
for batch in client.batches(limit=3):
assert batch.name in batch_names
def test_get_batches():
# Get count of all batches
batchlist = client.batches(project=TEST_PROJECT_NAME, limit=1)
total_batches = batchlist.total
# Download all batches to check total count
all_batches = list(client.get_batches(project_name=TEST_PROJECT_NAME))
assert total_batches == len(all_batches)
def test_files_upload():
with open("tests/test_image.png", "rb") as f:
client.upload_file(
file=f,
project_name=TEST_PROJECT_NAME,
)
def test_files_import():
client.import_file(
file_url="https://static.scale.com/uploads/selfserve-sample-image.png",
project_name=TEST_PROJECT_NAME,
)