-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path__init__.py
More file actions
1303 lines (1152 loc) · 43.6 KB
/
__init__.py
File metadata and controls
1303 lines (1152 loc) · 43.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
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
"""
Nucleus Python Library.
Data formats used:
_____________________________________________________________________________________________________
DatasetItem
image_url | str | The URL containing the image for the given row of data.\n
reference_id | str | An optional user-specified identifier to reference this given image.\n
metadata | dict | All of column definitions for this item.
| | The keys should match the user-specified column names,
| | and the corresponding values will populate the cell under the column.\n
_____________________________________________________________________________________________________
Box2DGeometry:
x | float | The distance, in pixels, between the left border of the bounding box
| | and the left border of the image.\n
y | float | The distance, in pixels, between the top border of the bounding box
| | and the top border of the image.\n
width | float | The width in pixels of the annotation.\n
height | float | The height in pixels of the annotation.\n
Box2DAnnotation:
item_id | str | The internally-controlled item identifier to associate this annotation with.
| | The reference_id field should be empty if this field is populated.\n
reference_id | str | The user-specified reference identifier to associate this annotation with.\n
| | The item_id field should be empty if this field is populated.
label | str | The label for this annotation (e.g. car, pedestrian, bicycle).\n
type | str | The type of this annotation. It should always be the box string literal.\n
geometry | dict | Representation of the bounding box in the Box2DGeometry format.\n
metadata | dict | An arbitrary metadata blob for the annotation.\n
_____________________________________________________________________________________________________
Box2DDetection:
item_id | str | The internally-controlled item identifier to associate this annotation with.
| | The reference_id field should be empty if this field is populated.\n
reference_id | str | The user-specified reference identifier to associate this annotation with.
| | The item_id field should be empty if this field is populated.\n
label | str | The label for this annotation (e.g. car, pedestrian, bicycle).\n
type | str | The type of this annotation. It should always be the box string literal.\n
confidence | float | The optional confidence level of this annotation.
| | It should be between 0 and 1 (inclusive).\n
geometry | dict | Representation of the bounding box in the Box2DGeometry format.\n
metadata | dict | An arbitrary metadata blob for the annotation.\n
"""
import asyncio
import json
import logging
import os
import urllib.request
from asyncio.tasks import Task
from typing import Any, Dict, List, Optional, Union
import aiohttp
import nest_asyncio
import pkg_resources
import requests
import tqdm
import tqdm.notebook as tqdm_notebook
from nucleus.url_utils import sanitize_string_args
from .annotation import (
BoxAnnotation,
CuboidAnnotation,
Point,
Point3D,
PolygonAnnotation,
Segment,
SegmentationAnnotation,
)
from .constants import (
ANNOTATION_METADATA_SCHEMA_KEY,
ANNOTATIONS_IGNORED_KEY,
ANNOTATIONS_PROCESSED_KEY,
AUTOTAGS_KEY,
DATASET_ID_KEY,
DATASET_ITEM_IDS_KEY,
DEFAULT_NETWORK_TIMEOUT_SEC,
EMBEDDING_DIMENSION_KEY,
EMBEDDINGS_URL_KEY,
ERROR_ITEMS,
ERROR_PAYLOAD,
ERRORS_KEY,
JOB_ID_KEY,
JOB_LAST_KNOWN_STATUS_KEY,
JOB_TYPE_KEY,
JOB_CREATION_TIME_KEY,
IMAGE_KEY,
IMAGE_URL_KEY,
INDEX_CONTINUOUS_ENABLE_KEY,
ITEM_METADATA_SCHEMA_KEY,
ITEMS_KEY,
KEEP_HISTORY_KEY,
MESSAGE_KEY,
MODEL_RUN_ID_KEY,
NAME_KEY,
NUCLEUS_ENDPOINT,
PREDICTIONS_IGNORED_KEY,
PREDICTIONS_PROCESSED_KEY,
REFERENCE_IDS_KEY,
SLICE_ID_KEY,
STATUS_CODE_KEY,
UPDATE_KEY,
)
from .dataset import Dataset
from .dataset_item import DatasetItem, CameraParams, Quaternion
from .errors import (
DatasetItemRetrievalError,
ModelCreationError,
ModelRunCreationError,
NotFoundError,
NucleusAPIError,
)
from .job import AsyncJob
from .model import Model
from .model_run import ModelRun
from .payload_constructor import (
construct_annotation_payload,
construct_append_payload,
construct_box_predictions_payload,
construct_model_creation_payload,
construct_segmentation_payload,
)
from .prediction import (
BoxPrediction,
CuboidPrediction,
PolygonPrediction,
SegmentationPrediction,
)
from .slice import Slice
from .upload_response import UploadResponse
from .scene import Frame, LidarScene
# pylint: disable=E1101
# TODO: refactor to reduce this file to under 1000 lines.
# pylint: disable=C0302
__version__ = pkg_resources.get_distribution("scale-nucleus").version
logger = logging.getLogger(__name__)
logging.basicConfig()
logging.getLogger(requests.packages.urllib3.__package__).setLevel(
logging.ERROR
)
class NucleusClient:
"""
Nucleus client.
"""
def __init__(
self,
api_key: str,
use_notebook: bool = False,
endpoint: str = None,
):
self.api_key = api_key
self.tqdm_bar = tqdm.tqdm
if endpoint is None:
self.endpoint = os.environ.get(
"NUCLEUS_ENDPOINT", NUCLEUS_ENDPOINT
)
else:
self.endpoint = endpoint
self._use_notebook = use_notebook
if use_notebook:
self.tqdm_bar = tqdm_notebook.tqdm
def __repr__(self):
return f"NucleusClient(api_key='{self.api_key}', use_notebook={self._use_notebook}, endpoint='{self.endpoint}')"
def __eq__(self, other):
if self.api_key == other.api_key:
if self._use_notebook == other._use_notebook:
return True
return False
def list_models(self) -> List[Model]:
"""
Lists available models in your repo.
:return: model_ids
"""
model_objects = self.make_request({}, "models/", requests.get)
return [
Model(
model_id=model["id"],
name=model["name"],
reference_id=model["ref_id"],
metadata=model["metadata"] or None,
client=self,
)
for model in model_objects["models"]
]
def list_datasets(self) -> Dict[str, Union[str, List[str]]]:
"""
Lists available datasets in your repo.
:return: { datasets_ids }
"""
return self.make_request({}, "dataset/", requests.get)
def list_jobs(
self, show_completed=None, date_limit=None
) -> List[AsyncJob]:
"""
Lists jobs for user.
:return: jobs
"""
payload = {show_completed: show_completed, date_limit: date_limit}
job_objects = self.make_request(payload, "jobs/", requests.get)
return [
AsyncJob(
job_id=job[JOB_ID_KEY],
job_last_known_status=job[JOB_LAST_KNOWN_STATUS_KEY],
job_type=job[JOB_TYPE_KEY],
job_creation_time=job[JOB_CREATION_TIME_KEY],
client=self,
)
for job in job_objects
]
def get_dataset_items(self, dataset_id) -> List[DatasetItem]:
"""
Gets all the dataset items inside your repo as a json blob.
:return [ DatasetItem ]
"""
response = self.make_request(
{}, f"dataset/{dataset_id}/datasetItems", requests.get
)
dataset_items = response.get("dataset_items", None)
error = response.get("error", None)
constructed_dataset_items = []
if dataset_items:
for item in dataset_items:
image_url = item.get("original_image_url")
metadata = item.get("metadata", None)
item_id = item.get("id", None)
ref_id = item.get("ref_id", None)
dataset_item = DatasetItem(
image_url, ref_id, item_id, metadata
)
constructed_dataset_items.append(dataset_item)
elif error:
raise DatasetItemRetrievalError(message=error)
return constructed_dataset_items
def get_dataset(self, dataset_id: str) -> Dataset:
"""
Fetches a dataset for given id
:param dataset_id: internally controlled dataset_id
:return: dataset
"""
return Dataset(dataset_id, self)
def get_model(self, model_id: str) -> Model:
"""
Fetched a model for a given id
:param model_id: internally controlled dataset_id
:return: model
"""
payload = self.make_request(
payload={},
route=f"model/{model_id}",
requests_command=requests.get,
)
return Model.from_json(payload=payload, client=self)
def get_model_run(self, model_run_id: str, dataset_id: str) -> ModelRun:
"""
Fetches a model_run for given id
:param model_run_id: internally controlled model_run_id
:param dataset_id: the dataset id which may determine the prediction schema
for this model run if present on the dataset.
:return: model_run
"""
return ModelRun(model_run_id, dataset_id, self)
def delete_model_run(self, model_run_id: str):
"""
Fetches a model_run for given id
:param model_run_id: internally controlled model_run_id
:return: model_run
"""
return self.make_request(
{}, f"modelRun/{model_run_id}", requests.delete
)
def create_dataset_from_project(
self,
project_id: str,
name: str = None,
last_n_tasks: int = None,
exclude_pending: bool = None,
) -> Tuple[Dataset, AsyncJob]:
"""
Creates a new dataset based on payload params:
name -- A human-readable name of the dataset.
Returns a response with internal id and name for a new dataset.
:param payload: { "name": str }
:return: new Dataset object
"""
payload = {"project_id": project_id}
if last_n_tasks:
payload["last_n_tasks"] = str(last_n_tasks)
if name:
payload["name"] = name
if exclude_pending:
payload["exclude_pending"] = exclude_pending
response = self.make_request(payload, "dataset/create_from_project")
return Dataset(response[DATASET_ID_KEY], self), AsyncJob(
job_id=response[JOB_ID_KEY],
job_last_known_status=response[JOB_LAST_KNOWN_STATUS_KEY],
job_type=response[JOB_TYPE_KEY],
job_creation_time=response[JOB_CREATION_TIME_KEY],
client=self,
)
def create_dataset(
self,
name: str,
item_metadata_schema: Optional[Dict] = None,
annotation_metadata_schema: Optional[Dict] = None,
) -> Dataset:
"""
Creates a new dataset:
Returns a response with internal id and name for a new dataset.
:param name -- A human-readable name of the dataset.
:param item_metadata_schema -- optional dictionary to define item metadata schema
:param annotation_metadata_schema -- optional dictionary to define annotation metadata schema
:return: new Dataset object
"""
response = self.make_request(
{
NAME_KEY: name,
ANNOTATION_METADATA_SCHEMA_KEY: annotation_metadata_schema,
ITEM_METADATA_SCHEMA_KEY: item_metadata_schema,
},
"dataset/create",
)
return Dataset(response[DATASET_ID_KEY], self)
def delete_dataset(self, dataset_id: str) -> dict:
"""
Deletes a private dataset based on datasetId.
Returns an empty payload where response status `200` indicates
the dataset has been successfully deleted.
:param payload: { "name": str }
:return: { "dataset_id": str, "name": str }
"""
return self.make_request({}, f"dataset/{dataset_id}", requests.delete)
@sanitize_string_args
def delete_dataset_item(
self, dataset_id: str, item_id: str = None, reference_id: str = None
) -> dict:
"""
Deletes a private dataset based on datasetId.
Returns an empty payload where response status `200` indicates
the dataset has been successfully deleted.
:param payload: { "name": str }
:return: { "dataset_id": str, "name": str }
"""
if item_id:
return self.make_request(
{}, f"dataset/{dataset_id}/{item_id}", requests.delete
)
else: # Assume reference_id is provided
return self.make_request(
{},
f"dataset/{dataset_id}/refloc/{reference_id}",
requests.delete,
)
def populate_dataset(
self,
dataset_id: str,
dataset_items: List[DatasetItem],
batch_size: int = 100,
update: bool = False,
):
"""
Appends images to a dataset with given dataset_id.
Overwrites images on collision if updated.
:param dataset_id: id of a dataset
:param payload: { "items": List[DatasetItem], "update": bool }
:param local: flag if images are stored locally
:param batch_size: size of the batch for long payload
:return:
{
"dataset_id: str,
"new_items": int,
"updated_items": int,
"ignored_items": int,
"upload_errors": int
}
"""
local_items = []
remote_items = []
# Check local files exist before sending requests
for item in dataset_items:
if item.local:
if not item.local_file_exists():
raise NotFoundError()
local_items.append(item)
else:
remote_items.append(item)
local_batches = [
local_items[i : i + batch_size]
for i in range(0, len(local_items), batch_size)
]
remote_batches = [
remote_items[i : i + batch_size]
for i in range(0, len(remote_items), batch_size)
]
agg_response = UploadResponse(json={DATASET_ID_KEY: dataset_id})
async_responses: List[Any] = []
if local_batches:
tqdm_local_batches = self.tqdm_bar(
local_batches, desc="Local file batches"
)
for batch in tqdm_local_batches:
payload = construct_append_payload(batch, update)
responses = self._process_append_requests_local(
dataset_id, payload, update
)
async_responses.extend(responses)
if remote_batches:
tqdm_remote_batches = self.tqdm_bar(
remote_batches, desc="Remote file batches"
)
for batch in tqdm_remote_batches:
payload = construct_append_payload(batch, update)
responses = self._process_append_requests(
dataset_id=dataset_id,
payload=payload,
update=update,
batch_size=batch_size,
)
async_responses.extend(responses)
for response in async_responses:
agg_response.update_response(response)
return agg_response
def _process_append_requests_local(
self,
dataset_id: str,
payload: dict,
update: bool, # TODO: understand how to pass this in.
local_batch_size: int = 10,
):
def get_files(batch):
for item in batch:
item[UPDATE_KEY] = update
request_payload = [
(
ITEMS_KEY,
(
None,
json.dumps(batch, allow_nan=False),
"application/json",
),
)
]
for item in batch:
image = open( # pylint: disable=R1732
item.get(IMAGE_URL_KEY), "rb" # pylint: disable=R1732
) # pylint: disable=R1732
img_name = os.path.basename(image.name)
img_type = (
f"image/{os.path.splitext(image.name)[1].strip('.')}"
)
request_payload.append(
(IMAGE_KEY, (img_name, image, img_type))
)
return request_payload
items = payload[ITEMS_KEY]
responses: List[Any] = []
files_per_request = []
payload_items = []
for i in range(0, len(items), local_batch_size):
batch = items[i : i + local_batch_size]
files_per_request.append(get_files(batch))
payload_items.append(batch)
future = self.make_many_files_requests_asynchronously(
files_per_request,
f"dataset/{dataset_id}/append",
)
try:
loop = asyncio.get_event_loop()
except RuntimeError: # no event loop running:
loop = asyncio.new_event_loop()
responses = loop.run_until_complete(future)
else:
nest_asyncio.apply(loop)
return loop.run_until_complete(future)
def close_files(request_items):
for item in request_items:
# file buffer in location [1][1]
if item[0] == IMAGE_KEY:
item[1][1].close()
# don't forget to close all open files
for p in files_per_request:
close_files(p)
return responses
async def make_many_files_requests_asynchronously(
self, files_per_request, route
):
"""
Makes an async post request with files to a Nucleus endpoint.
:param files_per_request: A list of lists of tuples (name, (filename, file_pointer, content_type))
name will become the name by which the multer can build an array.
:param route: route for the request
:return: awaitable list(response)
"""
async with aiohttp.ClientSession() as session:
tasks = [
asyncio.ensure_future(
self._make_files_request(
files=files, route=route, session=session
)
)
for files in files_per_request
]
return await asyncio.gather(*tasks)
async def _make_files_request(
self,
files,
route: str,
session: aiohttp.ClientSession,
):
"""
Makes an async post request with files to a Nucleus endpoint.
:param files: A list of tuples (name, (filename, file_pointer, file_type))
:param route: route for the request
:param session: Session to use for post.
:return: response
"""
endpoint = f"{self.endpoint}/{route}"
logger.info("Posting to %s", endpoint)
form = aiohttp.FormData()
for file in files:
form.add_field(
name=file[0],
filename=file[1][0],
value=file[1][1],
content_type=file[1][2],
)
async with session.post(
endpoint,
data=form,
auth=aiohttp.BasicAuth(self.api_key, ""),
timeout=DEFAULT_NETWORK_TIMEOUT_SEC,
) as response:
logger.info("API request has response code %s", response.status)
try:
data = await response.json()
except aiohttp.client_exceptions.ContentTypeError:
# In case of 404, the server returns text
data = await response.text()
if not response.ok:
self.handle_bad_response(
endpoint,
session.post,
aiohttp_response=(response.status, response.reason, data),
)
return data
def _process_append_requests(
self,
dataset_id: str,
payload: dict,
update: bool,
batch_size: int = 20,
):
items = payload[ITEMS_KEY]
payloads = [
# batch_size images per request
{ITEMS_KEY: items[i : i + batch_size], UPDATE_KEY: update}
for i in range(0, len(items), batch_size)
]
return [
self.make_request(
payload,
f"dataset/{dataset_id}/append",
)
for payload in payloads
]
def annotate_dataset(
self,
dataset_id: str,
annotations: List[
Union[
BoxAnnotation,
PolygonAnnotation,
CuboidAnnotation,
SegmentationAnnotation,
]
],
update: bool,
batch_size: int = 5000,
):
"""
Uploads ground truth annotations for a given dataset.
:param dataset_id: id of the dataset
:param annotations: List[Union[BoxAnnotation, PolygonAnnotation, CuboidAnnotation, SegmentationAnnotation]]
:param update: whether to update or ignore conflicting annotations
:return: {"dataset_id: str, "annotations_processed": int}
"""
# Split payload into segmentations and Box/Polygon
segmentations = [
ann
for ann in annotations
if isinstance(ann, SegmentationAnnotation)
]
other_annotations = [
ann
for ann in annotations
if not isinstance(ann, SegmentationAnnotation)
]
batches = [
other_annotations[i : i + batch_size]
for i in range(0, len(other_annotations), batch_size)
]
semseg_batches = [
segmentations[i : i + batch_size]
for i in range(0, len(segmentations), batch_size)
]
agg_response = {
DATASET_ID_KEY: dataset_id,
ANNOTATIONS_PROCESSED_KEY: 0,
ANNOTATIONS_IGNORED_KEY: 0,
}
total_batches = len(batches) + len(semseg_batches)
tqdm_batches = self.tqdm_bar(batches)
with self.tqdm_bar(total=total_batches) as pbar:
for batch in tqdm_batches:
payload = construct_annotation_payload(batch, update)
response = self.make_request(
payload, f"dataset/{dataset_id}/annotate"
)
pbar.update(1)
if STATUS_CODE_KEY in response:
agg_response[ERRORS_KEY] = response
else:
agg_response[ANNOTATIONS_PROCESSED_KEY] += response[
ANNOTATIONS_PROCESSED_KEY
]
agg_response[ANNOTATIONS_IGNORED_KEY] += response[
ANNOTATIONS_IGNORED_KEY
]
for s_batch in semseg_batches:
payload = construct_segmentation_payload(s_batch, update)
response = self.make_request(
payload, f"dataset/{dataset_id}/annotate_segmentation"
)
pbar.update(1)
if STATUS_CODE_KEY in response:
agg_response[ERRORS_KEY] = response
else:
agg_response[ANNOTATIONS_PROCESSED_KEY] += response[
ANNOTATIONS_PROCESSED_KEY
]
agg_response[ANNOTATIONS_IGNORED_KEY] += response[
ANNOTATIONS_IGNORED_KEY
]
return agg_response
def ingest_tasks(self, dataset_id: str, payload: dict):
"""
If you already submitted tasks to Scale for annotation this endpoint ingests your completed tasks
annotated by Scale into your Nucleus Dataset.
Right now we support ingestion from Videobox Annotation and 2D Box Annotation projects.
:param payload: {"tasks" : List[task_ids]}
:param dataset_id: id of the dataset
:return: {"ingested_tasks": int, "ignored_tasks": int, "pending_tasks": int}
"""
return self.make_request(payload, f"dataset/{dataset_id}/ingest_tasks")
def add_model(
self, name: str, reference_id: str, metadata: Optional[Dict] = None
) -> Model:
"""
Adds a model info to your repo based on payload params:
name -- A human-readable name of the model project.
reference_id -- An optional user-specified identifier to reference this given model.
metadata -- An arbitrary metadata blob for the model.
:param name: A human-readable name of the model project.
:param reference_id: An user-specified identifier to reference this given model.
:param metadata: An optional arbitrary metadata blob for the model.
:return: { "model_id": str }
"""
response = self.make_request(
construct_model_creation_payload(name, reference_id, metadata),
"models/add",
)
model_id = response.get("model_id", None)
if not model_id:
raise ModelCreationError(response.get("error"))
return Model(model_id, name, reference_id, metadata, self)
def create_model_run(self, dataset_id: str, payload: dict) -> ModelRun:
"""
Creates model run for dataset_id based on the given parameters specified in the payload:
'reference_id' -- The user-specified reference identifier to associate with the model.
The 'model_id' field should be empty if this field is populated.
'model_id' -- The internally-controlled identifier of the model.
The 'reference_id' field should be empty if this field is populated.
'name' -- An optional name for the model run.
'metadata' -- An arbitrary metadata blob for the current run.
:param
dataset_id: id of the dataset
payload:
{
"reference_id": str,
"model_id": str,
"name": Optional[str],
"metadata": Optional[Dict[str, Any]],
}
:return: new ModelRun object
"""
response = self.make_request(
payload, f"dataset/{dataset_id}/modelRun/create"
)
if response.get(STATUS_CODE_KEY, None):
raise ModelRunCreationError(response.get("error"))
return ModelRun(
response[MODEL_RUN_ID_KEY], dataset_id=dataset_id, client=self
)
def predict(
self,
model_run_id: str,
annotations: List[
Union[
BoxPrediction,
PolygonPrediction,
CuboidPrediction,
SegmentationPrediction,
]
],
update: bool,
batch_size: int = 5000,
):
"""
Uploads model outputs as predictions for a model_run. Returns info about the upload.
:param annotations: List[Union[BoxPrediction, PolygonPrediction, CuboidPrediction, SegmentationPrediction]],
:param update: bool
:return:
{
"dataset_id": str,
"model_run_id": str,
"predictions_processed": int,
"predictions_ignored": int,
}
"""
segmentations = [
ann
for ann in annotations
if isinstance(ann, SegmentationPrediction)
]
other_predictions = [
ann
for ann in annotations
if not isinstance(ann, SegmentationPrediction)
]
s_batches = [
segmentations[i : i + batch_size]
for i in range(0, len(segmentations), batch_size)
]
batches = [
other_predictions[i : i + batch_size]
for i in range(0, len(other_predictions), batch_size)
]
agg_response = {
MODEL_RUN_ID_KEY: model_run_id,
PREDICTIONS_PROCESSED_KEY: 0,
PREDICTIONS_IGNORED_KEY: 0,
}
tqdm_batches = self.tqdm_bar(batches)
for batch in tqdm_batches:
batch_payload = construct_box_predictions_payload(
batch,
update,
)
response = self.make_request(
batch_payload, f"modelRun/{model_run_id}/predict"
)
if STATUS_CODE_KEY in response:
agg_response[ERRORS_KEY] = response
else:
agg_response[PREDICTIONS_PROCESSED_KEY] += response[
PREDICTIONS_PROCESSED_KEY
]
agg_response[PREDICTIONS_IGNORED_KEY] += response[
PREDICTIONS_IGNORED_KEY
]
for s_batch in s_batches:
payload = construct_segmentation_payload(s_batch, update)
response = self.make_request(
payload, f"modelRun/{model_run_id}/predict_segmentation"
)
# pbar.update(1)
if STATUS_CODE_KEY in response:
agg_response[ERRORS_KEY] = response
else:
agg_response[PREDICTIONS_PROCESSED_KEY] += response[
PREDICTIONS_PROCESSED_KEY
]
agg_response[PREDICTIONS_IGNORED_KEY] += response[
PREDICTIONS_IGNORED_KEY
]
return agg_response
def commit_model_run(
self, model_run_id: str, payload: Optional[dict] = None
):
"""
Commits the model run. Starts matching algorithm defined by payload.
class_agnostic -- A flag to specify if matching algorithm should be class-agnostic or not.
Default value: True
allowed_label_matches -- An optional list of AllowedMatch objects to specify allowed matches
for ground truth and model predictions.
If specified, 'class_agnostic' flag is assumed to be False
Type 'AllowedMatch':
{
ground_truth_label: string, # A label for ground truth annotation.
model_prediction_label: string, # A label for model prediction that can be matched with
# corresponding ground truth label.
}
payload:
{
"class_agnostic": boolean,
"allowed_label_matches": List[AllowedMatch],
}
:return: {"model_run_id": str}
"""
if payload is None:
payload = {}
return self.make_request(payload, f"modelRun/{model_run_id}/commit")
def dataset_info(self, dataset_id: str):
"""
Returns information about existing dataset
:param dataset_id: dataset id
:return: dictionary of the form
{
'name': str,
'length': int,
'model_run_ids': List[str],
'slice_ids': List[str]
}
"""
return self.make_request(
{}, f"dataset/{dataset_id}/info", requests.get
)
def model_run_info(self, model_run_id: str):
"""
provides information about a Model Run with given model_run_id:
model_id -- Model Id corresponding to the run
name -- A human-readable name of the model project.
status -- Status of the Model Run.
metadata -- An arbitrary metadata blob specified for the run.
:return:
{
"model_id": str,
"name": str,
"status": str,
"metadata": Dict[str, Any],
}
"""
return self.make_request(
{}, f"modelRun/{model_run_id}/info", requests.get
)
@sanitize_string_args
def dataitem_ref_id(self, dataset_id: str, reference_id: str):
"""
:param dataset_id: internally controlled dataset id
:param reference_id: reference_id of a dataset_item
:return:
"""
return self.make_request(
{}, f"dataset/{dataset_id}/refloc/{reference_id}", requests.get
)
@sanitize_string_args
def predictions_ref_id(self, model_run_id: str, ref_id: str):
"""
Returns Model Run info For Dataset Item by model_run_id and item reference_id.
:param model_run_id: id of the model run.
:param reference_id: reference_id of a dataset item.
:return:
{
"annotations": List[Union[BoxPrediction, PolygonPrediction, CuboidPrediction, SegmentationPrediction]],
}
"""
return self.make_request(
{}, f"modelRun/{model_run_id}/refloc/{ref_id}", requests.get
)
def dataitem_iloc(self, dataset_id: str, i: int):
"""
Returns Dataset Item info by dataset_id and absolute number of the dataset item.
:param dataset_id: internally controlled dataset id
:param i: absolute number of the dataset_item
:return:
"""
return self.make_request(
{}, f"dataset/{dataset_id}/iloc/{i}", requests.get
)
def predictions_iloc(self, model_run_id: str, i: int):
"""
Returns Model Run Info For Dataset Item by model_run_id and absolute number of an item.
:param model_run_id: id of the model run.
:param i: absolute number of Dataset Item for a dataset corresponding to the model run.
:return:
{
"annotations": List[Union[BoxPrediction, PolygonPrediction, CuboidPrediction, SegmentationPrediction]],
}
"""
return self.make_request(
{}, f"modelRun/{model_run_id}/iloc/{i}", requests.get
)
def dataitem_loc(self, dataset_id: str, dataset_item_id: str):
"""
Returns Dataset Item Info By dataset_item_id and dataset_id
:param dataset_id: internally controlled id for the dataset.
:param dataset_item_id: internally controlled id for the dataset item.
:return: