-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdataset.py
More file actions
1601 lines (1362 loc) · 62.2 KB
/
dataset.py
File metadata and controls
1601 lines (1362 loc) · 62.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
import os
from typing import Any, Dict, Iterable, List, Optional, Sequence, Union
import requests
from nucleus.annotation_uploader import AnnotationUploader, PredictionUploader
from nucleus.job import AsyncJob
from nucleus.prediction import (
BoxPrediction,
CategoryPrediction,
CuboidPrediction,
PolygonPrediction,
SegmentationPrediction,
from_json,
)
from nucleus.url_utils import sanitize_string_args
from nucleus.utils import (
convert_export_payload,
format_dataset_item_response,
format_prediction_response,
paginate_generator,
serialize_and_write_to_presigned_url,
)
from .annotation import Annotation, check_all_mask_paths_remote
from .constants import (
ANNOTATIONS_KEY,
AUTOTAG_SCORE_THRESHOLD,
BACKFILL_JOB_KEY,
DATASET_ID_KEY,
DATASET_IS_SCENE_KEY,
DEFAULT_ANNOTATION_UPDATE_MODE,
EMBEDDING_DIMENSION_KEY,
EMBEDDINGS_URL_KEY,
EXPORTED_ROWS,
ITEMS_KEY,
KEEP_HISTORY_KEY,
MESSAGE_KEY,
NAME_KEY,
REFERENCE_IDS_KEY,
REQUEST_ID_KEY,
SLICE_ID_KEY,
UPDATE_KEY,
VIDEO_UPLOAD_TYPE_KEY,
)
from .data_transfer_object.dataset_info import DatasetInfo
from .data_transfer_object.dataset_size import DatasetSize
from .data_transfer_object.scenes_list import ScenesList, ScenesListEntry
from .dataset_item import (
DatasetItem,
check_all_paths_remote,
check_for_duplicate_reference_ids,
)
from .dataset_item_uploader import DatasetItemUploader
from .deprecation_warning import deprecated
from .errors import NucleusAPIError
from .metadata_manager import ExportMetadataType, MetadataManager
from .payload_constructor import (
construct_append_scenes_payload,
construct_model_run_creation_payload,
construct_taxonomy_payload,
)
from .scene import LidarScene, Scene, VideoScene, check_all_scene_paths_remote
from .slice import Slice
from .upload_response import UploadResponse
# TODO: refactor to reduce this file to under 1000 lines.
# pylint: disable=C0302
WARN_FOR_LARGE_UPLOAD = 50000
WARN_FOR_LARGE_SCENES_UPLOAD = 5
class Dataset:
"""Datasets are collections of your data that can be associated with models.
You can append :class:`DatasetItems<DatasetItem>` or :class:`Scenes<LidarScene>`
with metadata to your dataset, annotate it with ground truth, and upload
model predictions to evaluate and compare model performance on your data.
Make sure that the dataset is set up correctly supporting the required datatype (see code sample below).
Datasets cannot be instantiated directly and instead must be created via API
endpoint using :meth:`NucleusClient.create_dataset`, or in the dashboard.
::
import nucleus
client = nucleus.NucleusClient(YOUR_SCALE_API_KEY)
# Create new dataset supporting DatasetItems
dataset = client.create_dataset(YOUR_DATASET_NAME, is_scene=False)
# OR create new dataset supporting LidarScenes
dataset = client.create_dataset(YOUR_DATASET_NAME, is_scene=True)
# Or, retrieve existing dataset by ID
# This ID can be fetched using client.list_datasets() or from a dashboard URL
existing_dataset = client.get_dataset("YOUR_DATASET_ID")
"""
def __init__(self, dataset_id, client, name=None):
self.id = dataset_id
self._client = client
# NOTE: Optionally set name on creation such that the property access doesn't need to hit the server
self._name = name
def __repr__(self):
if os.environ.get("NUCLEUS_DEBUG", None):
return f"Dataset(name='{self.name}, dataset_id='{self.id}', is_scene='{self.is_scene}', client={self._client})"
else:
return f"Dataset(name='{self.name}, dataset_id='{self.id}', is_scene='{self.is_scene}')"
def __eq__(self, other):
if self.id == other.id:
if self._client == other._client:
return True
return False
@property
def name(self) -> str:
"""User-defined name of the Dataset."""
if self._name is None:
self._name = self._client.make_request(
{}, f"dataset/{self.id}/name", requests.get
)["name"]
return self._name
@property
def is_scene(self) -> bool:
"""If the dataset can contain scenes or not."""
response = self._client.make_request(
{}, f"dataset/{self.id}/is_scene", requests.get
)[DATASET_IS_SCENE_KEY]
return response
@property
def model_runs(self) -> List[str]:
"""List of all model runs associated with the Dataset."""
# TODO: model_runs -> models
response = self._client.make_request(
{}, f"dataset/{self.id}/model_runs", requests.get
)
return response
@property
def slices(self) -> List[str]:
"""List of all Slice IDs created from the Dataset."""
response = self._client.make_request(
{}, f"dataset/{self.id}/slices", requests.get
)
return response
@property
def size(self) -> int:
"""Number of items in the Dataset."""
response = self._client.make_request(
{}, f"dataset/{self.id}/size", requests.get
)
dataset_size = DatasetSize.parse_obj(response)
return dataset_size.count
def items_generator(self, page_size=100000) -> Iterable[DatasetItem]:
"""Generator yielding all dataset items in the dataset.
::
sum_example_field = 0
for item in dataset.items_generator():
sum += item.metadata["example_field"]
Args:
page_size (int, optional): Number of items to return per page. If you are
experiencing timeouts while using this generator, you can try lowering
the page size.
Yields:
an iterable of DatasetItem objects.
"""
json_generator = paginate_generator(
client=self._client,
endpoint=f"dataset/{self.id}/itemsPage",
result_key=ITEMS_KEY,
page_size=page_size,
)
for item_json in json_generator:
yield DatasetItem.from_json(item_json)
@property
def items(self) -> List[DatasetItem]:
"""List of all DatasetItem objects in the Dataset.
For fetching more than 200k items see :meth:`NucleusDataset.items_generator`.
"""
try:
response = self._client.make_request(
{}, f"dataset/{self.id}/datasetItems", requests.get
)
except NucleusAPIError as e:
if e.status_code == 503:
e.message += "\nThe server timed out while trying to load your items. Please try iterating over dataset.items_generator() instead."
raise e
dataset_item_jsons = response.get("dataset_items", None)
return [
DatasetItem.from_json(item_json)
for item_json in dataset_item_jsons
]
@property
def scenes(self) -> List[ScenesListEntry]:
"""List of ID, reference ID, type, and metadata for all scenes in the Dataset."""
response = self._client.make_request(
{}, f"dataset/{self.id}/scenes_list", requests.get
)
scenes_list = ScenesList.parse_obj(response)
return scenes_list.scenes
@sanitize_string_args
def autotag_items(self, autotag_name, for_scores_greater_than=0):
"""Fetches the autotag's items above the score threshold, sorted by descending score.
Parameters:
autotag_name: The user-defined name of the autotag.
for_scores_greater_than (Optional[int]): Score threshold between -1
and 1 above which to include autotag items.
Returns:
List of autotagged items above the given score threshold, sorted by
descending score, and autotag info, packaged into a dict as follows::
{
"autotagItems": List[{
ref_id: str,
score: float,
model_prediction_annotation_id: str | None
ground_truth_annotation_id: str | None,
}],
"autotag": {
id: str,
name: str,
status: "started" | "completed",
autotag_level: "Image" | "Object"
}
}
Note ``model_prediction_annotation_id`` and ``ground_truth_annotation_id``
are only relevant for object autotags.
"""
response = self._client.make_request(
payload={AUTOTAG_SCORE_THRESHOLD: for_scores_greater_than},
route=f"dataset/{self.id}/autotag/{autotag_name}/taggedItems",
requests_command=requests.get,
)
return response
def autotag_training_items(self, autotag_name):
"""Fetches items that were manually selected during refinement of the autotag.
Parameters:
autotag_name: The user-defined name of the autotag.
Returns:
List of user-selected positives and autotag info, packaged into a
dict as follows::
{
"autotagPositiveTrainingItems": {
ref_id: str,
model_prediction_annotation_id: str | None,
ground_truth_annotation_id: str | None,
}[],
"autotag": {
id: str,
name: str,
status: "started" | "completed",
autotag_level: "Image" | "Object"
}
}
Note ``model_prediction_annotation_id`` and ``ground_truth_annotation_id``
are only relevant for object autotags.
"""
response = self._client.make_request(
payload={},
route=f"dataset/{self.id}/autotag/{autotag_name}/trainingItems",
requests_command=requests.get,
)
return response
def info(self) -> DatasetInfo:
"""Retrieve information about the dataset
Returns:
:class:`DatasetInfo`
"""
response = self._client.make_request(
{}, f"dataset/{self.id}/info", requests.get
)
dataset_info = DatasetInfo.parse_obj(response)
return dataset_info
@deprecated(
"Model runs have been deprecated and will be removed. Use a Model instead"
)
def create_model_run(
self,
name: str,
reference_id: Optional[str] = None,
model_id: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
annotation_metadata_schema: Optional[Dict] = None,
):
payload = construct_model_run_creation_payload(
name,
reference_id,
model_id,
metadata,
annotation_metadata_schema,
)
return self._client.create_model_run(self.id, payload)
def annotate(
self,
annotations: Sequence[Annotation],
update: bool = DEFAULT_ANNOTATION_UPDATE_MODE,
batch_size: int = 5000,
asynchronous: bool = False,
remote_files_per_upload_request: int = 20,
local_files_per_upload_request: int = 10,
local_file_upload_concurrency: int = 30,
) -> Union[Dict[str, Any], AsyncJob]:
"""Uploads ground truth annotations to the dataset.
Adding ground truth to your dataset in Nucleus allows you to visualize
annotations, query dataset items based on the annotations they contain,
and evaluate models by comparing their predictions to ground truth.
Nucleus supports :class:`Box<BoxAnnotation>`, :class:`Polygon<PolygonAnnotation>`,
:class:`Cuboid<CuboidAnnotation>`, :class:`Segmentation<SegmentationAnnotation>`,
and :class:`Category<CategoryAnnotation>` annotations. Cuboid annotations
can only be uploaded to a :class:`pointcloud DatasetItem<LidarScene>`.
When uploading an annotation, you need to specify which item you are
annotating via the reference_id you provided when uploading the image
or pointcloud.
Ground truth uploads can be made idempotent by specifying an optional
annotation_id for each annotation. This id should be unique within the
dataset_item so that (reference_id, annotation_id) is unique within the
dataset.
See :class:`SegmentationAnnotation` for specific requirements to upload
segmentation annotations.
For ingesting large annotation payloads, see the `Guide for Large Ingestions
<https://nucleus.scale.com/docs/large-ingestion>`_.
Parameters:
annotations (Sequence[:class:`Annotation`]): List of annotation
objects to upload.
update: Whether to ignore or overwrite metadata for conflicting annotations.
batch_size: Number of annotations processed in each concurrent batch.
Default is 5000. If you get timeouts when uploading geometric annotations,
you can try lowering this batch size.
asynchronous: Whether or not to process the upload asynchronously (and
return an :class:`AsyncJob` object). Default is False.
remote_files_per_upload_request: Number of remote files to upload in each
request. Segmentations have either local or remote files, if you are
getting timeouts while uploading segmentations with remote urls, you
should lower this value from its default of 20.
local_files_per_upload_request: Number of local files to upload in each
request. Segmentations have either local or remote files, if you are
getting timeouts while uploading segmentations with local files, you
should lower this value from its default of 10. The maximum is 10.
local_file_upload_concurrency: Number of concurrent local file uploads.
Returns:
If synchronous, payload describing the upload result::
{
"dataset_id": str,
"annotations_processed": int
}
Otherwise, returns an :class:`AsyncJob` object.
"""
if asynchronous:
check_all_mask_paths_remote(annotations)
request_id = serialize_and_write_to_presigned_url(
annotations, self.id, self._client
)
response = self._client.make_request(
payload={REQUEST_ID_KEY: request_id, UPDATE_KEY: update},
route=f"dataset/{self.id}/annotate?async=1",
)
return AsyncJob.from_json(response, self._client)
uploader = AnnotationUploader(dataset_id=self.id, client=self._client)
return uploader.upload(
annotations=annotations,
update=update,
batch_size=batch_size,
remote_files_per_upload_request=remote_files_per_upload_request,
local_files_per_upload_request=local_files_per_upload_request,
local_file_upload_concurrency=local_file_upload_concurrency,
)
def ingest_tasks(self, task_ids: List[str]) -> dict:
"""Ingest specific tasks from an existing Scale or Rapid project into the dataset.
Note: if you would like to create a new Dataset from an exisiting Scale
labeling project, use :meth:`NucleusClient.create_dataset_from_project`.
For more info, see our `Ingest From Labeling Guide
<https://nucleus.scale.com/docs/ingest-from-labeling>`_.
Parameters:
task_ids: List of task IDs to ingest.
Returns:
Payload describing the asynchronous upload result::
{
"ingested_tasks": int,
"ignored_tasks": int,
"pending_tasks": int
}
"""
# TODO(gunnar): Validate right behaviour. Pydantic?
return self._client.make_request(
{"tasks": task_ids}, f"dataset/{self.id}/ingest_tasks"
)
def append(
self,
items: Union[
Sequence[DatasetItem], Sequence[LidarScene], Sequence[VideoScene]
],
update: bool = False,
batch_size: int = 20,
asynchronous: bool = False,
local_files_per_upload_request: int = 10,
local_file_upload_concurrency: int = 30,
) -> Union[Dict[Any, Any], AsyncJob, UploadResponse]:
"""Appends items or scenes to a dataset.
.. note::
Datasets can only accept one of DatasetItems or Scenes, never both.
This behavior is set during Dataset :meth:`creation
<NucleusClient.create_dataset>` with the ``is_scene`` flag.
::
import nucleus
client = nucleus.NucleusClient("YOUR_SCALE_API_KEY")
dataset = client.get_dataset("YOUR_DATASET_ID")
local_item = nucleus.DatasetItem(
image_location="./1.jpg",
reference_id="image_1",
metadata={"key": "value"}
)
remote_item = nucleus.DatasetItem(
image_location="s3://your-bucket/2.jpg",
reference_id="image_2",
metadata={"key": "value"}
)
# default is synchronous upload
sync_response = dataset.append(items=[local_item])
# async jobs have higher throughput but can be more difficult to debug
async_job = dataset.append(
items=[remote_item], # all items must be remote for async
asynchronous=True
)
print(async_job.status())
A :class:`Dataset` can be populated with labeled and unlabeled
data. Using Nucleus, you can filter down the data inside your dataset
using custom metadata about your images.
For instance, your local dataset may contain ``Sunny``, ``Foggy``, and
``Rainy`` folders of images. All of these images can be uploaded into a
single Nucleus ``Dataset``, with (queryable) metadata like ``{"weather":
"Sunny"}``.
To update an item's metadata, you can re-ingest the same items with the
``update`` argument set to true. Existing metadata will be overwritten
for ``DatasetItems`` in the payload that share a ``reference_id`` with a
previously uploaded ``DatasetItem``. To retrieve your existing
``reference_ids``, use :meth:`Dataset.items`.
::
# overwrite metadata by reuploading the item
remote_item.metadata["weather"] = "Sunny"
async_job_2 = dataset.append(
items=[remote_item],
update=True,
asynchronous=True
)
Parameters:
dataset_items ( \
Union[ \
Sequence[:class:`DatasetItem`], \
Sequence[:class:`LidarScene`] \
Sequence[:class:`VideoScene`]
]): List of items or scenes to upload.
batch_size: Size of the batch for larger uploads. Default is 20. This is
for items that have a remote URL and do not require a local upload.
If you get timeouts for uploading remote urls, try decreasing this.
update: Whether or not to overwrite metadata on reference ID collision.
Default is False.
asynchronous: Whether or not to process the upload asynchronously (and
return an :class:`AsyncJob` object). This is required when uploading
scenes. Default is False.
files_per_upload_request: How large to make each upload request when your
files are local. If you get timeouts, you may need to lower this from
its default of 10. The default is 10.
local_file_upload_concurrency: How many local file requests to send
concurrently. If you start to see gateway timeouts or cloudflare related
errors, you may need to lower this from its default of 30.
Returns:
For scenes
If synchronous, returns a payload describing the upload result::
{
"dataset_id: str,
"new_items": int,
"updated_items": int,
"ignored_items": int,
"upload_errors": int
}
Otherwise, returns an :class:`AsyncJob` object.
For images
If synchronous returns UploadResponse otherwise :class:`AsyncJob`
"""
assert (
batch_size is None or batch_size < 30
), "Please specify a batch size smaller than 30 to avoid timeouts."
dataset_items = [
item for item in items if isinstance(item, DatasetItem)
]
lidar_scenes = [item for item in items if isinstance(item, LidarScene)]
video_scenes = [item for item in items if isinstance(item, VideoScene)]
if dataset_items and (lidar_scenes or video_scenes):
raise Exception(
"You must append either DatasetItems or Scenes to the dataset."
)
if lidar_scenes:
assert (
asynchronous
), "In order to avoid timeouts, you must set asynchronous=True when uploading 3D scenes."
return self._append_scenes(lidar_scenes, update, asynchronous)
if video_scenes:
assert (
asynchronous
), "In order to avoid timeouts, you must set asynchronous=True when uploading videos."
return self._append_video_scenes(
video_scenes, update, asynchronous
)
check_for_duplicate_reference_ids(dataset_items)
if len(dataset_items) > WARN_FOR_LARGE_UPLOAD and not asynchronous:
print(
"Tip: for large uploads, get faster performance by importing your data "
"into Nucleus directly from a cloud storage provider. See "
"https://dashboard.scale.com/nucleus/docs/api?language=python#guide-for-large-ingestions"
" for details."
)
if asynchronous:
check_all_paths_remote(dataset_items)
request_id = serialize_and_write_to_presigned_url(
dataset_items, self.id, self._client
)
response = self._client.make_request(
payload={REQUEST_ID_KEY: request_id, UPDATE_KEY: update},
route=f"dataset/{self.id}/append?async=1",
)
return AsyncJob.from_json(response, self._client)
return self._upload_items(
dataset_items,
update=update,
batch_size=batch_size,
local_files_per_upload_request=local_files_per_upload_request,
local_file_upload_concurrency=local_file_upload_concurrency,
)
@deprecated("Prefer using Dataset.append instead.")
def append_scenes(
self,
scenes: List[LidarScene],
update: Optional[bool] = False,
asynchronous: Optional[bool] = False,
) -> Union[dict, AsyncJob]:
return self._append_scenes(scenes, update, asynchronous)
def _append_scenes(
self,
scenes: List[LidarScene],
update: Optional[bool] = False,
asynchronous: Optional[bool] = False,
) -> Union[dict, AsyncJob]:
# TODO: make private in favor of Dataset.append invocation
if not self.is_scene:
raise Exception(
"Your dataset is not a scene dataset but only supports single dataset items. "
"In order to be able to add scenes, please create another dataset with "
"client.create_dataset(<dataset_name>, is_scene=True) or add the scenes to "
"an existing scene dataset."
)
for scene in scenes:
scene.validate()
if not asynchronous:
print(
"WARNING: Processing lidar pointclouds usually takes several seconds. As a result, sychronous scene upload"
"requests are likely to timeout. For large uploads, we recommend using the flag asynchronous=True "
"to avoid HTTP timeouts. Please see"
"https://dashboard.scale.com/nucleus/docs/api?language=python#guide-for-large-ingestions"
" for details."
)
if asynchronous:
check_all_scene_paths_remote(scenes)
request_id = serialize_and_write_to_presigned_url(
scenes, self.id, self._client
)
response = self._client.make_request(
payload={REQUEST_ID_KEY: request_id, UPDATE_KEY: update},
route=f"{self.id}/upload_scenes?async=1",
)
return AsyncJob.from_json(response, self._client)
payload = construct_append_scenes_payload(scenes, update)
response = self._client.make_request(
payload=payload,
route=f"{self.id}/upload_scenes",
)
return response
def _append_video_scenes(
self,
scenes: List[VideoScene],
update: Optional[bool] = False,
asynchronous: Optional[bool] = False,
) -> Union[dict, AsyncJob]:
# TODO: make private in favor of Dataset.append invocation
if not self.is_scene:
raise Exception(
"Your dataset is not a scene dataset but only supports single dataset items. "
"In order to be able to add scenes, please create another dataset with "
"client.create_dataset(<dataset_name>, is_scene=True) or add the scenes to "
"an existing scene dataset."
)
for scene in scenes:
scene.validate()
if not asynchronous:
print(
"WARNING: Processing videos usually takes several seconds. As a result, synchronous video scene upload"
"requests are likely to timeout. For large uploads, we recommend using the flag asynchronous=True "
"to avoid HTTP timeouts. Please see"
"https://dashboard.scale.com/nucleus/docs/api?language=python#guide-for-large-ingestions"
" for details."
)
if asynchronous:
check_all_scene_paths_remote(scenes)
request_id = serialize_and_write_to_presigned_url(
scenes, self.id, self._client
)
response = self._client.make_request(
payload={REQUEST_ID_KEY: request_id, UPDATE_KEY: update},
route=f"{self.id}/upload_video_scenes?async=1",
)
return AsyncJob.from_json(response, self._client)
payload = construct_append_scenes_payload(scenes, update)
response = self._client.make_request(
payload=payload,
route=f"{self.id}/upload_video_scenes",
)
return response
def iloc(self, i: int) -> dict:
"""Retrieves dataset item by absolute numerical index.
Parameters:
i: Absolute numerical index of the dataset item within the dataset.
Returns:
Payload describing the dataset item and associated annotations::
{
"item": DatasetItem
"annotations": {
"box": Optional[List[BoxAnnotation]],
"cuboid": Optional[List[CuboidAnnotation]],
"line": Optional[List[LineAnnotation]],
"polygon": Optional[List[PolygonAnnotation]],
"keypoints": Optional[List[KeypointsAnnotation]],
"segmentation": Optional[List[SegmentationAnnotation]],
"category": Optional[List[CategoryAnnotation]],
}
}
"""
response = self._client.make_request(
{}, f"dataset/{self.id}/iloc/{i}", requests.get
)
return format_dataset_item_response(response)
@sanitize_string_args
def refloc(self, reference_id: str) -> dict:
"""Retrieves a dataset item by reference ID.
Parameters:
reference_id: User-defined reference ID of the dataset item.
Returns:
Payload containing the dataset item and associated annotations::
{
"item": DatasetItem
"annotations": {
"box": Optional[List[BoxAnnotation]],
"cuboid": Optional[List[CuboidAnnotation]],
"line": Optional[List[LineAnnotation]],
"polygon": Optional[List[PolygonAnnotation]],
"keypoints": Option[List[KeypointsAnnotation]],
"segmentation": Optional[List[SegmentationAnnotation]],
"category": Optional[List[CategoryAnnotation]],
}
}
"""
response = self._client.make_request(
{}, f"dataset/{self.id}/refloc/{reference_id}", requests.get
)
return format_dataset_item_response(response)
def loc(self, dataset_item_id: str) -> dict:
"""Retrieves a dataset item by Nucleus-generated ID.
Parameters:
dataset_item_id: Nucleus-generated dataset item ID (starts with ``di_``).
This can be retrieved via :meth:`Dataset.items` or a Nucleus dashboard URL.
Returns:
Payload containing the dataset item and associated annotations::
{
"item": DatasetItem
"annotations": {
"box": Optional[List[BoxAnnotation]],
"cuboid": Optional[List[CuboidAnnotation]],
"line": Optional[List[LineAnnotation]],
"polygon": Optional[List[PolygonAnnotation]],
"keypoints": Optional[List[KeypointsAnnotation]],
"segmentation": Optional[List[SegmentationAnnotation]],
"category": Optional[List[CategoryAnnotation]],
}
}
"""
response = self._client.make_request(
{}, f"dataset/{self.id}/loc/{dataset_item_id}", requests.get
)
return format_dataset_item_response(response)
def ground_truth_loc(self, reference_id: str, annotation_id: str):
"""Fetches a single ground truth annotation by id.
Parameters:
reference_id: User-defined reference ID of the dataset item associated
with the ground truth annotation.
annotation_id: User-defined ID of the ground truth annotation.
Returns:
Union[\
:class:`BoxAnnotation`, \
:class:`LineAnnotation`, \
:class:`PolygonAnnotation`, \
:class:`KeypointsAnnotation`, \
:class:`CuboidAnnotation`, \
:class:`SegmentationAnnotation` \
:class:`CategoryAnnotation` \
]: Ground truth annotation object with the specified annotation ID.
"""
response = self._client.make_request(
{},
f"dataset/{self.id}/groundTruth/loc/{reference_id}/{annotation_id}",
requests.get,
)
return Annotation.from_json(response)
def create_slice(
self,
name: str,
reference_ids: List[str],
) -> Slice:
"""Creates a :class:`Slice` of dataset items within a dataset.
Parameters:
name: A human-readable name for the slice.
reference_ids: List of reference IDs of dataset items to add to the slice::
Returns:
:class:`Slice`: The newly constructed slice item.
"""
payload = {NAME_KEY: name, REFERENCE_IDS_KEY: reference_ids}
response = self._client.make_request(
payload, f"dataset/{self.id}/create_slice"
)
return Slice(response[SLICE_ID_KEY], self._client)
@sanitize_string_args
def delete_item(self, reference_id: str) -> dict:
"""Deletes an item from the dataset by item reference ID.
All annotations and predictions associated with the item will be deleted
as well.
Parameters:
reference_id: The user-defined reference ID of the item to delete.
Returns:
Payload to indicate deletion invocation.
"""
return self._client.make_request(
{},
f"dataset/{self.id}/refloc/{reference_id}",
requests.delete,
)
@sanitize_string_args
def delete_scene(self, reference_id: str):
"""Deletes a Scene associated with the Dataset
All items, annotations and predictions associated with the scene will be
deleted as well.
Parameters:
reference_id: The user-defined reference ID of the item to delete.
"""
self._client.delete(f"dataset/{self.id}/scene/{reference_id}")
def list_autotags(self):
# TODO: prefer Dataset.autotags @property
"""Fetches all autotags of the dataset.
Returns:
List of autotag payloads::
List[{
"id": str,
"name": str,
"status": "completed" | "pending",
"autotag_level": "Image" | "Object"
}]
"""
return self._client.list_autotags(self.id)
def update_autotag(self, autotag_id: str) -> AsyncJob:
"""Rerun autotag inference on all items in the dataset.
Currently this endpoint does not try to skip already inferenced items,
but this improvement is planned for the future. This means that for
now, you can only have one job running at a time, so please await the
result using job.sleep_until_complete() before launching another job.
Parameters:
autotag_id: ID of the autotag to re-inference. You can retrieve the
ID you want with :meth:`list_autotags`, or from its URL in the
"Manage Autotags" page in the dashboard.
Returns:
:class:`AsyncJob`: Asynchronous job object to track processing status.
"""
return AsyncJob.from_json(
payload=self._client.make_request(
{}, f"autotag/{autotag_id}", requests.post
),
client=self._client,
)
def create_custom_index(
self, embeddings_urls: List[str], embedding_dim: int
):
"""Processes user-provided embeddings for the dataset to use with autotag and simsearch.
::
import nucleus
client = nucleus.NucleusClient("YOUR_SCALE_API_KEY")
dataset = client.get_dataset("YOUR_DATASET_ID")
embeddings = {
"reference_id_0": [0.1, 0.2, 0.3],
"reference_id_1": [0.4, 0.5, 0.6],
} # uploaded to s3 with the below URL
embeddings_url = "s3://dataset/embeddings_map.json"
response = dataset.create_custom_index(
embeddings_url=[embeddings_url],
embedding_dim=3
)
Parameters:
embeddings_urls: List of URLs, each of which pointing to
a JSON mapping reference_id -> embedding vector.
embedding_dim: The dimension of the embedding vectors. Must be consistent
across all embedding vectors in the index.
Returns:
:class:`AsyncJob`: Asynchronous job object to track processing status.
"""
res = self._client.post(
{
EMBEDDINGS_URL_KEY: embeddings_urls,
EMBEDDING_DIMENSION_KEY: embedding_dim,
},
f"indexing/{self.id}",
)
return AsyncJob.from_json(
res,
self._client,
)
def delete_custom_index(self):
"""Deletes the custom index uploaded to the dataset.
Returns:
Payload containing information that can be used to track the job's status::
{
"dataset_id": str,
"job_id": str,
"message": str
}
"""
return self._client.delete_custom_index(self.id)
def set_continuous_indexing(self, enable: bool = True):
"""Toggle whether embeddings are automatically generated for new data.
Sets continuous indexing for a given dataset, which will automatically
generate embeddings for use with autotag whenever new images are uploaded.
Parameters:
enable: Whether to enable or disable continuous indexing. Default is
True.
Returns:
Response payload::
{
"dataset_id": str,
"message": str
"backfill_job": AsyncJob,
}
"""
preprocessed_response = self._client.set_continuous_indexing(
self.id, enable
)
response = {
DATASET_ID_KEY: preprocessed_response[DATASET_ID_KEY],
MESSAGE_KEY: preprocessed_response[MESSAGE_KEY],
}
if enable:
response[BACKFILL_JOB_KEY] = (
AsyncJob.from_json(preprocessed_response, self._client),
)
return response
def create_image_index(self):
"""Creates or updates image index by generating embeddings for images that do not already have embeddings.
The embeddings are used for autotag and similarity search.
This endpoint is limited to index up to 2 million images at a time and the
job will fail for payloads that exceed this limit.