-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathassets.py
More file actions
2410 lines (2136 loc) · 83.4 KB
/
assets.py
File metadata and controls
2410 lines (2136 loc) · 83.4 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
"""Assets domain namespace for the Kili Python SDK."""
# pylint: disable=too-many-lines,too-many-public-methods
import warnings
from collections.abc import Generator
from typing import (
TYPE_CHECKING,
Any,
List,
Literal,
Optional,
TypedDict,
Union,
cast,
overload,
)
from typeguard import typechecked
from typing_extensions import deprecated
from kili.core.helpers import is_url
from kili.domain.asset import (
AssetStatus,
)
from kili.domain.asset.asset import StatusInStep
from kili.domain.issue import IssueStatus, IssueType
from kili.domain.label import LabelType
from kili.domain.types import ListOrTuple
from kili.domain_api.base import DomainNamespace
from kili.domain_api.namespace_utils import get_available_methods
if TYPE_CHECKING:
import pandas as pd
class AssetFilter(TypedDict, total=False):
"""Filter options for querying assets.
This TypedDict defines all available filter parameters that can be used
when listing or counting assets. All fields are optional.
Use this filter with `kili.assets.list()` and `kili.assets.count()` methods
to filter assets based on various criteria such as status, assignee, labels,
metadata, and more.
"""
asset_id_in: Optional[list[str]]
asset_id_not_in: Optional[list[str]]
assignee_in: Optional[ListOrTuple[str]]
assignee_not_in: Optional[ListOrTuple[str]]
consensus_mark_gt: Optional[float]
consensus_mark_gte: Optional[float]
consensus_mark_lt: Optional[float]
consensus_mark_lte: Optional[float]
created_at_gte: Optional[str]
created_at_lte: Optional[str]
external_id_in: Optional[list[str]]
external_id_strictly_in: Optional[list[str]]
honeypot_mark_gt: Optional[float]
honeypot_mark_gte: Optional[float]
honeypot_mark_lt: Optional[float]
honeypot_mark_lte: Optional[float]
inference_mark_gte: Optional[float]
inference_mark_lte: Optional[float]
issue_status: Optional[IssueStatus]
issue_type: Optional[IssueType]
label_author_in: Optional[list[str]]
label_category_search: Optional[str]
label_consensus_mark_gt: Optional[float]
label_consensus_mark_gte: Optional[float]
label_consensus_mark_lt: Optional[float]
label_consensus_mark_lte: Optional[float]
label_created_at_gt: Optional[str]
label_created_at_gte: Optional[str]
label_created_at_lt: Optional[str]
label_created_at_lte: Optional[str]
label_created_at: Optional[str]
label_honeypot_mark_gt: Optional[float]
label_honeypot_mark_gte: Optional[float]
label_honeypot_mark_lt: Optional[float]
label_honeypot_mark_lte: Optional[float]
label_labeler_in: Optional[ListOrTuple[str]]
label_labeler_not_in: Optional[ListOrTuple[str]]
label_reviewer_in: Optional[ListOrTuple[str]]
label_reviewer_not_in: Optional[ListOrTuple[str]]
label_type_in: Optional[list[LabelType]]
metadata_where: Optional[dict[str, Any]]
skipped: Optional[bool]
status_in: Optional[list[AssetStatus]]
step_name_in: Optional[list[str]]
step_name_not_in: Optional[list[str]]
step_status_in: Optional[list[StatusInStep]]
step_status_not_in: Optional[list[StatusInStep]]
updated_at_gte: Optional[str]
updated_at_lte: Optional[str]
class VideoProcessingParameters(TypedDict, total=False):
"""Processing parameters for video assets.
These parameters control how video assets are processed and displayed in Kili.
Attributes:
frames_played_per_second: Frame rate for video playback (frames per second)
number_of_frames: Total number of frames in the video
start_time: Starting time offset in seconds
"""
frames_played_per_second: int
number_of_frames: int
start_time: float
class ImageLayerParam(TypedDict, total=False):
"""Parameters of an image or geospatial layer.
Attributes:
path: local path to the file to use as a layer
name: Optional name for the layer
"""
path: str
name: Optional[str]
class GeospatialLayerParam(ImageLayerParam, total=False):
"""Parameters for geospatial layers, extending ImageLayerParam.
Attributes:
path: URL or local path to the geospatial layer file
name: Optional name for the layer
bounds: Optional bounding box coordinates [[minX, minY], [maxX, maxY]]
epsg: Optional coordinate reference system (EPSG3857 or EPSG4326)
"""
bounds: Optional[list[list[float]]]
epsg: Optional[Literal["EPSG3857", "EPSG4326"]]
def convert_to_web_layer(layer: GeospatialLayerParam) -> dict[str, Any]:
"""Convert a GeospatialLayerParam to web layer format for URL-based geospatial layers.
Args:
layer: Layer parameter dictionary with name, path, bounds, and epsg
Returns:
Dictionary with web layer configuration including tileLayerUrl and coordinates settings
"""
res = {
"bounds": layer.get("bounds"),
"epsg": layer.get("epsg") if layer.get("epsg") else "EPSG3857",
"name": layer.get("name"),
"tileLayerUrl": layer.get("path"),
"useClassicCoordinates": False,
"isBaseLayer": False,
}
return res
def convert_to_local_layer(layer: GeospatialLayerParam) -> dict[str, Any]:
"""Convert a GeospatialLayerParam to local layer format for file-based geospatial layers.
Args:
layer: Layer parameter dictionary with name and path
Returns:
Dictionary with local layer configuration containing name and path
"""
if layer.get("bounds"):
warnings.warn(
"Custom bounds are not yet supported for local layers.",
stacklevel=1,
)
if layer.get("epsg"):
warnings.warn(
"Forced epsg are not yet supported for local layers.",
stacklevel=1,
)
res = {
"name": layer.get("name"),
"path": layer.get("path"),
}
return res
def _snake_to_camel_case(snake_str: str) -> str:
"""Convert snake_case string to camelCase.
Args:
snake_str: String in snake_case format
Returns:
String in camelCase format
"""
components = snake_str.split("_")
return components[0] + "".join(x.title() for x in components[1:])
def _transform_processing_parameters(
params: dict[str, Any],
) -> dict[str, Any]:
"""Transform processing parameter keys from snake_case to camelCase.
Args:
params: Processing parameters with snake_case keys (video or GeoTIFF)
Returns:
Dictionary with camelCase keys
"""
return {_snake_to_camel_case(key): value for key, value in params.items()}
def _prepare_video_processing_parameters(
params: VideoProcessingParameters, use_native_video: bool
) -> dict[str, Any]:
"""Prepare video processing parameters with defaults.
Transforms keys from snake_case to camelCase and adds default parameters:
- shouldUseNativeVideo: True for native video, False for frame-based video
- shouldKeepNativeFrameRate: False (if framesPlayedPerSecond is specified)
Args:
params: Video processing parameters with snake_case keys
use_native_video: True for native video, False for frame-based video
Returns:
Dictionary with camelCase keys and default parameters added
"""
# Transform to camelCase
transformed = _transform_processing_parameters(cast(dict[str, Any], params))
# Add shouldUseNativeVideo based on the method
transformed["shouldUseNativeVideo"] = use_native_video
# Add shouldKeepNativeFrameRate=False if framesPlayedPerSecond is defined
if "framesPlayedPerSecond" in transformed:
transformed["shouldKeepNativeFrameRate"] = False
return transformed
class AssetsNamespace(DomainNamespace): # pylint: disable=too-many-public-methods
"""Assets domain namespace providing asset-related operations.
This namespace provides access to all asset-related functionality
including creating, updating, querying, and managing assets.
The namespace provides the following main operations:
- list(): Query and list assets
- count(): Count assets matching filters
- create_image(): Create image assets
- create_video_native(): Create video assets from video files
- create_video_frame(): Create video assets from frame sequences
- create_geospatial(): Create multi-layer geospatial imagery assets
- create_pdf(): Create PDF assets
- create_text(): Create plain text assets
- create_rich_text(): Create rich-text formatted text assets
- create_audio(): Create audio assets
- delete(): Delete assets from projects
- add_metadata(): Add metadata to assets
- set_metadata(): Set metadata on assets
- update_external_id(): Update asset external IDs
- update_processing_parameter(): Update video processing parameters
- invalidate(): Send assets back to queue (invalidate current step)
- move_to_next_step(): Move assets to the next workflow step
- assign(): Assign assets to labelers
- update_priority(): Update asset priorities
- skip(): Skip an asset
- unskip(): Unskip an asset
- add_consensus(): Activate or deactivate consensus on an asset
Examples:
>>> kili = Kili()
>>> # List assets
>>> assets = kili.assets.list(project_id="my_project")
>>> # Count assets
>>> count = kili.assets.count(project_id="my_project")
>>> # Create image assets
>>> result = kili.assets.create_image(
... project_id="my_project",
... content_array=["https://example.com/image.png"]
... )
>>> # Create video from video file
>>> result = kili.assets.create_video_native(
... project_id="my_project",
... content="https://example.com/video.mp4",
... processing_parameters={"frames_played_per_second": 25}
... )
>>> # Add asset metadata
>>> kili.assets.add_metadata(
... json_metadata={"key": "value"},
... project_id="my_project",
... asset_id="asset_id"
... )
>>> # Assign assets to labelers
>>> kili.assets.assign(
... asset_ids=["asset_id"],
... to_be_labeled_by_array=[["user_id"]]
... )
"""
def __init__(self, client, gateway):
"""Initialize the assets namespace.
Args:
client: The Kili client instance
gateway: The KiliAPIGateway instance for API operations
"""
super().__init__(client, gateway, "assets")
@deprecated(
"'assets' is a namespace, not a callable method. "
"Use kili.assets.list() or other available methods instead."
)
def __call__(self, *args, **kwargs):
"""Raise a helpful error when namespace is called like a method.
This provides guidance to users migrating from the legacy API
where assets were accessed via kili.assets(...) to the new domain API
where they use kili.assets.list(...) or other methods.
"""
available_methods = get_available_methods(self)
methods_str = ", ".join(f"kili.{self._domain_name}.{m}()" for m in available_methods)
raise TypeError(
f"'{self._domain_name}' is a namespace, not a callable method. "
f"The legacy API 'kili.{self._domain_name}(...)' has been replaced with the domain API.\n"
f"Available methods: {methods_str}\n"
f"Example: kili.{self._domain_name}.list(...)"
)
@typechecked
def list(
self,
project_id: str,
disable_tqdm: Optional[bool] = None,
download_media: bool = False,
fields: Optional[ListOrTuple[str]] = None,
filter: Optional[AssetFilter] = None,
first: Optional[int] = None,
format: Optional[str] = None,
label_output_format: Literal["dict", "parsed_label"] = "dict",
local_media_dir: Optional[str] = None,
skip: int = 0,
) -> Union[list[dict], "pd.DataFrame"]:
"""List assets from a project.
Args:
project_id: Identifier of the project.
skip: Number of assets to skip (ordered by creation date).
fields: List of fields to return. If None, returns default fields.
filter: Additional asset filters to apply (see `AssetFilter` for available keys).
disable_tqdm: If True, the progress bar will be disabled.
first: Maximum number of assets to return.
format: Output format; when set to `"pandas"` returns a DataFrame.
download_media: If True, downloads media files locally.
local_media_dir: Directory used when `download_media` is True.
label_output_format: Format of the returned labels ("dict" or "parsed_label").
Returns:
A list of assets or a pandas DataFrame depending on `format`.
"""
filter_kwargs = filter or {}
return self._client.assets(
as_generator=False,
disable_tqdm=disable_tqdm,
download_media=download_media,
fields=fields,
first=first,
format=format,
label_output_format=label_output_format,
local_media_dir=local_media_dir,
project_id=project_id,
skip=skip,
**filter_kwargs,
)
@typechecked
def list_as_generator(
self,
project_id: str,
disable_tqdm: Optional[bool] = None,
download_media: bool = False,
fields: Optional[ListOrTuple[str]] = None,
filter: Optional[AssetFilter] = None,
first: Optional[int] = None,
label_output_format: Literal["dict", "parsed_label"] = "dict",
local_media_dir: Optional[str] = None,
skip: int = 0,
) -> Generator[dict, None, None]:
"""List assets from a project.
Args:
project_id: Identifier of the project.
skip: Number of assets to skip (ordered by creation date).
fields: List of fields to return. If None, returns default fields.
filter: Additional asset filters to apply (see `AssetFilter` for available keys).
disable_tqdm: If True, the progress bar will be disabled.
first: Maximum number of assets to return.
download_media: If True, downloads media files locally.
local_media_dir: Directory used when `download_media` is True.
label_output_format: Format of the returned labels ("dict" or "parsed_label").
Returns:
A generator of a list of assets.
"""
filter_kwargs = filter or {}
return self._client.assets(
as_generator=True,
disable_tqdm=disable_tqdm,
download_media=download_media,
fields=fields,
first=first,
label_output_format=label_output_format,
local_media_dir=local_media_dir,
project_id=project_id,
skip=skip,
**filter_kwargs,
)
@typechecked
def count(
self,
project_id: str,
filter: Optional[AssetFilter] = None,
) -> int:
"""Count assets in a project.
Args:
project_id: Identifier of the project.
filter: Additional asset filters to apply (see `AssetFilter` for available keys).
Returns:
The number of assets matching the filters.
Examples:
>>> # Count all assets in project
>>> count = kili.assets.count(project_id="my_project")
>>> # Count assets with specific status
>>> count = kili.assets.count(
... project_id="my_project",
... filter={"status_in": ["TODO", "ONGOING"]}
... )
"""
filter_kwargs = filter or {}
return self._client.count_assets(
project_id=project_id,
**filter_kwargs,
)
@overload
def create_image(
self,
*,
project_id: str,
content: Union[str, dict],
external_id: Optional[str] = None,
json_metadata: Optional[dict] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@overload
def create_image(
self,
*,
project_id: str,
content_array: Union[List[str], List[dict]],
external_id_array: Optional[List[str]] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@typechecked
def create_image(
self,
*,
project_id: str,
content: Optional[Union[str, dict]] = None,
content_array: Optional[Union[List[str], List[dict]]] = None,
external_id: Optional[str] = None,
external_id_array: Optional[List[str]] = None,
json_metadata: Optional[dict] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
"""Create image assets in a project.
Args:
project_id: Identifier of the project
content: URL or local file path to an image
content_array: List of URLs or local file paths to images
external_id: External id to identify the asset
external_id_array: List of external ids given to identify the assets
json_metadata: The metadata given to the asset
json_metadata_array: The metadata given to each asset
disable_tqdm: If True, the progress bar will be disabled
wait_until_availability: If True, waits until assets are fully processed
**kwargs: Additional arguments (e.g., is_honeypot)
Returns:
A dictionary with project id and list of created asset ids
Examples:
>>> # Create single image asset
>>> result = kili.assets.create_image(
... project_id="my_project",
... content="https://example.com/image.png"
... )
>>> # Create multiple image assets
>>> result = kili.assets.create_image(
... project_id="my_project",
... content_array=["https://example.com/image1.png", "https://example.com/image2.png"]
... )
>>> # Create single asset with metadata
>>> result = kili.assets.create_image(
... project_id="my_project",
... content="https://example.com/image.png",
... json_metadata={"description": "Sample image"}
... )
"""
# Convert singular to plural
if content is not None:
content_array = cast(Union[list[str], list[dict]], [content])
if external_id is not None:
external_id_array = [external_id]
if json_metadata is not None:
json_metadata_array = [json_metadata]
# Call the legacy method directly through the client
return self._client.append_many_to_dataset(
project_id=project_id,
content_array=content_array,
external_id_array=external_id_array,
json_metadata_array=json_metadata_array,
disable_tqdm=disable_tqdm,
wait_until_availability=wait_until_availability,
**kwargs,
)
@overload
def create_layered_image(
self,
*,
project_id: str,
layers: List[ImageLayerParam],
external_id: Optional[str] = None,
json_metadata: Optional[dict] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@overload
def create_layered_image(
self,
*,
project_id: str,
layers_array: List[List[ImageLayerParam]],
external_id_array: Optional[List[str]] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@typechecked
def create_layered_image(
self,
*,
project_id: str,
layers: Optional[List[ImageLayerParam]] = None,
layers_array: Optional[List[List[ImageLayerParam]]] = None,
external_id: Optional[str] = None,
external_id_array: Optional[List[str]] = None,
json_metadata: Optional[dict] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
"""Create image assets in a project.
Args:
project_id: Identifier of the project
layers: List of image layers for a single asset
layers_array: List of image layer lists for multiple assets
external_id: External id to identify the asset
external_id_array: List of external ids given to identify the assets
json_metadata: The metadata given to the asset
json_metadata_array: The metadata given to each asset
disable_tqdm: If True, the progress bar will be disabled
wait_until_availability: If True, waits until assets are fully processed
**kwargs: Additional arguments (e.g., is_honeypot)
Returns:
A dictionary with project id and list of created asset ids
Examples:
>>> # Create single image asset
>>> result = kili.assets.create_image(
... project_id="my_project",
... content="https://example.com/image.png"
... )
>>> # Create multiple image assets
>>> result = kili.assets.create_image(
... project_id="my_project",
... content_array=["https://example.com/image1.png", "https://example.com/image2.png"]
... )
>>> # Create single asset with metadata
>>> result = kili.assets.create_image(
... project_id="my_project",
... content="https://example.com/image.png",
... json_metadata={"description": "Sample image"}
... )
"""
# Convert singular to plural
if layers is not None:
layers_array = [layers]
if external_id is not None:
external_id_array = [external_id]
if json_metadata is not None:
json_metadata_array = [json_metadata]
# Call the legacy method directly through the client
return self._client.append_many_to_dataset(
project_id=project_id,
multi_layer_content_array=cast(Optional[list[list[dict]]], layers_array),
external_id_array=external_id_array,
json_metadata_array=json_metadata_array,
disable_tqdm=disable_tqdm,
wait_until_availability=wait_until_availability,
**kwargs,
)
@overload
def create_video_native(
self,
*,
project_id: str,
content: Union[str, dict],
processing_parameters: Optional[VideoProcessingParameters] = None,
external_id: Optional[str] = None,
json_metadata: Optional[dict] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@overload
def create_video_native(
self,
*,
project_id: str,
content_array: Union[List[str], List[dict]],
processing_parameters_array: Optional[List[VideoProcessingParameters]] = None,
external_id_array: Optional[List[str]] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@typechecked
def create_video_native(
self,
*,
project_id: str,
content: Optional[Union[str, dict]] = None,
content_array: Optional[Union[List[str], List[dict]]] = None,
processing_parameters: Optional[VideoProcessingParameters] = None,
processing_parameters_array: Optional[List[VideoProcessingParameters]] = None,
external_id: Optional[str] = None,
external_id_array: Optional[List[str]] = None,
json_metadata: Optional[dict] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
"""Create video assets from video files in a project.
If processing parameters are incomplete, Kili will probe the videos to determine missing parameters.
Args:
project_id: Identifier of the project
content: URL or local file path to a video file
content_array: List of URLs or local file paths to video files
processing_parameters: Video processing configuration
processing_parameters_array: List of video processing configurations for each asset
external_id: External id to identify the asset
external_id_array: List of external ids given to identify the assets
json_metadata: The metadata given to the asset
json_metadata_array: The metadata given to each asset
disable_tqdm: If True, the progress bar will be disabled
wait_until_availability: If True, waits until assets are fully processed
**kwargs: Additional arguments (e.g., is_honeypot)
Returns:
A dictionary with project id and list of created asset ids
Examples:
>>> # Create single video asset
>>> result = kili.assets.create_video_native(
... project_id="my_project",
... content="https://example.com/video.mp4"
... )
>>> # Create video with processing parameters
>>> result = kili.assets.create_video_native(
... project_id="my_project",
... content="https://example.com/video.mp4",
... processing_parameters={"frames_played_per_second": 25}
... )
>>> # Create multiple video assets
>>> result = kili.assets.create_video_native(
... project_id="my_project",
... content_array=["https://example.com/video1.mp4", "https://example.com/video2.mp4"],
... processing_parameters_array=[{"frames_played_per_second": 25}, {"frames_played_per_second": 30}]
... )
"""
# Convert singular to plural
if content is not None:
content_array = cast(Union[list[str], list[dict]], [content])
if external_id is not None:
external_id_array = [external_id]
if json_metadata is not None:
json_metadata_array = [json_metadata]
if processing_parameters is not None:
processing_parameters_array = [processing_parameters]
# Merge processing parameters into json_metadata
if processing_parameters_array is not None:
if json_metadata_array is None:
json_metadata_array = [{} for _ in processing_parameters_array]
for i, params in enumerate(processing_parameters_array):
if i < len(json_metadata_array):
json_metadata_array[i][
"processingParameters"
] = _prepare_video_processing_parameters(params, use_native_video=True)
# Call the legacy method directly through the client
return self._client.append_many_to_dataset(
project_id=project_id,
content_array=content_array,
external_id_array=external_id_array,
json_metadata_array=json_metadata_array,
disable_tqdm=disable_tqdm,
wait_until_availability=wait_until_availability,
**kwargs,
)
@overload
def create_video_frame(
self,
*,
project_id: str,
json_content: Union[List[Union[dict, str]], None],
processing_parameters: Optional[VideoProcessingParameters] = None,
external_id: Optional[str] = None,
json_metadata: Optional[dict] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@overload
def create_video_frame(
self,
*,
project_id: str,
json_content_array: List[Union[List[Union[dict, str]], None]],
processing_parameters_array: Optional[List[VideoProcessingParameters]] = None,
external_id_array: Optional[List[str]] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@typechecked
def create_video_frame(
self,
*,
project_id: str,
json_content: Optional[Union[List[Union[dict, str]], None]] = None,
json_content_array: Optional[List[Union[List[Union[dict, str]], None]]] = None,
processing_parameters: Optional[VideoProcessingParameters] = None,
processing_parameters_array: Optional[List[VideoProcessingParameters]] = None,
external_id: Optional[str] = None,
external_id_array: Optional[List[str]] = None,
json_metadata: Optional[dict] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
"""Create video assets from frame sequences in a project.
If processing parameters are incomplete, Kili will probe the videos to determine missing parameters.
Args:
project_id: Identifier of the project
json_content: Sequence of frames (list of URLs or paths to images)
json_content_array: List of frame sequences for each video
processing_parameters: Video processing configuration
processing_parameters_array: List of video processing configurations for each asset
external_id: External id to identify the asset
external_id_array: List of external ids given to identify the assets
json_metadata: The metadata given to the asset
json_metadata_array: The metadata given to each asset
disable_tqdm: If True, the progress bar will be disabled
wait_until_availability: If True, waits until assets are fully processed
**kwargs: Additional arguments (e.g., is_honeypot)
Returns:
A dictionary with project id and list of created asset ids
Examples:
>>> # Create single video from frames
>>> result = kili.assets.create_video_frame(
... project_id="my_project",
... json_content=["https://example.com/frame1.png", "https://example.com/frame2.png"]
... )
>>> # Create video from frames with processing parameters
>>> result = kili.assets.create_video_frame(
... project_id="my_project",
... json_content=["https://example.com/frame1.png", "https://example.com/frame2.png"],
... processing_parameters={"frames_played_per_second": 25}
... )
>>> # Create multiple videos from frames
>>> result = kili.assets.create_video_frame(
... project_id="my_project",
... json_content_array=[
... ["https://example.com/video1/frame1.png", "https://example.com/video1/frame2.png"],
... ["https://example.com/video2/frame1.png", "https://example.com/video2/frame2.png"]
... ]
... )
"""
# Convert singular to plural
if json_content is not None:
json_content_array = [json_content]
if external_id is not None:
external_id_array = [external_id]
if json_metadata is not None:
json_metadata_array = [json_metadata]
if processing_parameters is not None:
processing_parameters_array = [processing_parameters]
# Merge processing parameters into json_metadata
if processing_parameters_array is not None:
if json_metadata_array is None:
json_metadata_array = [{} for _ in processing_parameters_array]
for i, params in enumerate(processing_parameters_array):
if i < len(json_metadata_array):
json_metadata_array[i][
"processingParameters"
] = _prepare_video_processing_parameters(params, use_native_video=False)
# Call the legacy method directly through the client
return self._client.append_many_to_dataset(
project_id=project_id,
json_content_array=json_content_array,
external_id_array=external_id_array,
json_metadata_array=json_metadata_array,
disable_tqdm=disable_tqdm,
wait_until_availability=wait_until_availability,
**kwargs,
)
@overload
def create_geospatial(
self,
*,
project_id: str,
layer_array: Optional[List[GeospatialLayerParam]] = None,
external_id: Optional[str] = None,
json_metadata: Optional[dict] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@overload
def create_geospatial(
self,
*,
project_id: str,
layer_arrays: Optional[List[List[GeospatialLayerParam]]] = None,
external_id_array: Optional[List[str]] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
...
@typechecked
def create_geospatial(
self,
*,
project_id: str,
layer_array: Optional[List[GeospatialLayerParam]] = None,
layer_arrays: Optional[List[List[GeospatialLayerParam]]] = None,
external_id: Optional[str] = None,
external_id_array: Optional[List[str]] = None,
json_metadata: Optional[dict] = None,
json_metadata_array: Optional[List[dict]] = None,
disable_tqdm: Optional[bool] = None,
wait_until_availability: bool = True,
**kwargs,
) -> dict[Literal["id", "asset_ids"], Union[str, List[str]]]:
"""Create single/multi-layer geospatial imagery assets in a project.
Args:
project_id: Identifier of the project
layer_array: List of layer paths for a single geospatial asset
layer_arrays: List of multi-layer content for each geospatial asset
external_id: External id to identify the asset
external_id_array: List of external ids given to identify the assets
json_metadata: The metadata given to the asset
json_metadata_array: The metadata given to each asset
disable_tqdm: If True, the progress bar will be disabled
wait_until_availability: If True, waits until assets are fully processed
**kwargs: Additional arguments (e.g., is_honeypot)
Returns:
A dictionary with project id and list of created asset ids
Examples:
>>> # Create single geospatial asset
>>> result = kili.assets.create_geospatial(
... project_id="my_project",
... layer_array=[
... {"path": "/path/to/layer1.tif"},
... {"path": "/path/to/layer2.tif"}
... ]
... )
>>> # Create multiple geospatial assets
>>> result = kili.assets.create_geospatial(
... project_id="my_project",
... layer_arrays=[
... [{"path": "/path/to/asset1/layer1.tif"}, {"path": "/path/to/asset1/layer2.tif"}],
... [{"path": "/path/to/asset2/layer1.tif"}]
... ]
... )
"""
# Convert singular to plural
if layer_array is not None:
layer_arrays = [layer_array]
if external_id is not None:
external_id_array = [external_id]
if json_metadata is not None:
json_metadata_array = [json_metadata]
multi_layer_content_array = []
json_content_array = []
if layer_arrays is None:
raise ValueError(
"One of layer_array or layer_arrays parameter need to be filled"
" to create a geospatial asset"
)
# Split layers into 2 arrays, depending on path parameter
for layers in layer_arrays:
multi_layer_contents = []
json_contents = []
for layer in layers:
if is_url(layer.get("path")):
# is web url, check mandatory params
web_layer = convert_to_web_layer(layer)
json_contents.append(web_layer)
else:
local_layer = convert_to_local_layer(layer)
multi_layer_contents.append(local_layer)