-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathproject.py
More file actions
1948 lines (1581 loc) · 84.1 KB
/
project.py
File metadata and controls
1948 lines (1581 loc) · 84.1 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 warnings, os.path as osp
from ..dss_plugin_mlflow import MLflowHandle
from .dataset import DSSDataset, DSSDatasetListItem, DSSManagedDatasetCreationHelper
from .modelcomparison import DSSModelComparison
from .jupyternotebook import DSSJupyterNotebook, DSSJupyterNotebookListItem
from .notebook import DSSNotebook
from .streaming_endpoint import DSSStreamingEndpoint, DSSStreamingEndpointListItem, DSSManagedStreamingEndpointCreationHelper
from .recipe import DSSRecipeListItem, DSSRecipe
from . import recipe
from .managedfolder import DSSManagedFolder
from .savedmodel import DSSSavedModel
from .modelevaluationstore import DSSModelEvaluationStore
from .mlflow import DSSMLflowExtension
from .job import DSSJob, DSSJobWaiter
from .scenario import DSSScenario, DSSScenarioListItem
from .continuousactivity import DSSContinuousActivity
from .apiservice import DSSAPIService
from .future import DSSFuture
from .macro import DSSMacro
from .wiki import DSSWiki
from .discussion import DSSObjectDiscussions
from .ml import DSSMLTask, DSSMLTaskQueues
from .analysis import DSSAnalysis
from .flow import DSSProjectFlow
from .app import DSSAppManifest
from .webapp import DSSWebApp
from .codestudio import DSSCodeStudioObject, DSSCodeStudioObjectListItem
class DSSProject(object):
"""
A handle to interact with a project on the DSS instance.
Do not create this class directly, instead use :meth:`dataikuapi.DSSClient.get_project`
"""
def __init__(self, client, project_key):
self.client = client
self.project_key = project_key
def get_summary(self):
"""
Returns a summary of the project. The summary is a read-only view of some of the state of the project.
You cannot edit the resulting dict and use it to update the project state on DSS, you must use the other more
specific methods of this :class:`dataikuapi.dss.project.DSSProject` object
:returns: a dict containing a summary of the project. Each dict contains at least a 'projectKey' field
:rtype: dict
"""
return self.client._perform_json("GET", "/projects/%s" % self.project_key)
def get_project_folder(self):
"""
Returns the :class:`dataikuapi.dss.projectfolder.DSSProjectFolder` containing this project
:rtype: :class:`dataikuapi.dss.projectfolder.DSSProjectFolder`
"""
root = self.client.get_root_project_folder()
def rec(pf):
if self.project_key in pf.list_project_keys():
return pf
else:
for spf in pf.list_child_folders():
found_in_child = rec(spf)
if found_in_child:
return found_in_child
return None
found_in = rec(root)
if found_in:
return found_in
else:
return root
def move_to_folder(self, folder):
"""
Moves this project to a project folder
:param folder :class:`dataikuapi.dss.projectfolder.DSSProjectFolder`
"""
current_folder = self.get_project_folder()
current_folder.move_project_to(self.project_key, folder)
########################################################
# Project deletion
########################################################
def delete(self, clear_managed_datasets=False, clear_output_managed_folders=False, clear_job_and_scenario_logs=True, **kwargs):
"""
Delete the project
This call requires an API key with admin rights
:param bool clear_managed_datasets: Should the data of managed datasets be cleared
:param bool clear_output_managed_folders: Should the data of managed folders used as outputs of recipes be cleared
:param bool clear_job_and_scenario_logs: Should the job and scenario logs be cleared
"""
# For backwards compatibility
if 'drop_data' in kwargs and kwargs['drop_data']:
clear_managed_datasets = True
return self.client._perform_empty(
"DELETE", "/projects/%s" % self.project_key, params={
"clearManagedDatasets": clear_managed_datasets,
"clearOutputManagedFolders": clear_output_managed_folders,
"clearJobAndScenarioLogs": clear_job_and_scenario_logs
})
########################################################
# Project export
########################################################
def get_export_stream(self, options=None):
"""
Return a stream of the exported project
You need to close the stream after download. Failure to do so will result in the DSSClient becoming unusable.
:param dict options: Dictionary of export options (defaults to `{}`). The following options are available:
* exportUploads (boolean): Exports the data of Uploaded datasets - default False
* exportManagedFS (boolean): Exports the data of managed Filesystem datasets - default False
* exportAnalysisModels (boolean): Exports the models trained in analysis - default False
* exportSavedModels (boolean): Exports the models trained in saved models - default False
* exportManagedFolders (boolean): Exports the data of managed folders - default False
* exportAllInputDatasets (boolean): Exports the data of all input datasets - default False
* exportAllDatasets (boolean): Exports the data of all datasets - default False
* exportAllInputManagedFolders (boolean): Exports the data of all input managed folders - default False
* exportGitRepositoy (boolean): Exports the Git repository history - default False
* exportInsightsData (boolean): Exports the data of static insights - default False
:returns: a file-like obbject that is a stream of the export archive
:rtype: file-like
"""
if options is None:
options = {}
return self.client._perform_raw(
"POST", "/projects/%s/export" % self.project_key, body=options).raw
def export_to_file(self, path, options=None):
"""
Export the project to a file
:param str path: the path of the file in which the exported project should be saved
:param dict options: Dictionary of export options (defaults to `{}`). The following options are available:
* exportUploads (boolean): Exports the data of Uploaded datasets - default False
* exportManagedFS (boolean): Exports the data of managed Filesystem datasets - default False
* exportAnalysisModels (boolean): Exports the models trained in analysis - default False
* exportSavedModels (boolean): Exports the models trained in saved models - default False
* exportModelEvaluationStores (boolean): Exports the evaluation stores - default False
* exportManagedFolders (boolean): Exports the data of managed folders - default False
* exportAllInputDatasets (boolean): Exports the data of all input datasets - default False
* exportAllDatasets (boolean): Exports the data of all datasets - default False
* exportAllInputManagedFolders (boolean): Exports the data of all input managed folders - default False
* exportGitRepository (boolean): Exports the Git repository history - default False
* exportInsightsData (boolean): Exports the data of static insights - default False
"""
if options is None:
options = {}
with open(path, 'wb') as f:
export_stream = self.client._perform_raw(
"POST", "/projects/%s/export" % self.project_key, body=options)
for chunk in export_stream.iter_content(chunk_size=32768):
if chunk:
f.write(chunk)
f.flush()
########################################################
# Project duplicate
########################################################
def duplicate(self, target_project_key,
target_project_name,
duplication_mode="MINIMAL",
export_analysis_models=True,
export_saved_models=True,
export_git_repository=True,
export_insights_data=True,
remapping=None,
target_project_folder=None):
"""
Duplicate the project
:param string target_project_key: The key of the new project
:param string target_project_name: The name of the new project
:param string duplication_mode: can be one of the following values: MINIMAL, SHARING, FULL, NONE
:param bool export_analysis_models:
:param bool export_saved_models:
:param bool export_git_repository:
:param bool export_insights_data:
:param dict remapping: dict of connections to be remapped for the new project (defaults to `{}`)
:param target_project_folder: the project folder where to put the duplicated project
:type target_project_folder: A :class:`dataikuapi.dss.projectfolder.DSSProjectFolder
:returns: A dict containing the original and duplicated project's keys
:rtype: :class:`ProjectDuplicateResult`
"""
if remapping is None:
remapping = {}
obj = {
"targetProjectName": target_project_name,
"targetProjectKey": target_project_key,
"duplicationMode": duplication_mode,
"exportAnalysisModels": export_analysis_models,
"exportSavedModels": export_saved_models,
"exportGitRepository": export_git_repository,
"exportInsightsData": export_insights_data,
"remapping": remapping
}
if target_project_folder is not None:
obj["targetProjectFolderId"] = target_project_folder.project_folder_id
ref = self.client._perform_json("POST", "/projects/%s/duplicate/" % self.project_key, body = obj)
return ref
########################################################
# Project infos
########################################################
def get_metadata(self):
"""
Get the metadata attached to this project. The metadata contains label, description
checklists, tags and custom metadata of the project.
For more information on available metadata, please see https://doc.dataiku.com/dss/api/6.0/rest/
:returns: a dict object containing the project metadata.
:rtype: dict
"""
return self.client._perform_json("GET", "/projects/%s/metadata" % self.project_key)
def set_metadata(self, metadata):
"""
Set the metadata on this project.
:param metadata dict: the new state of the metadata for the project. You should only set a metadata object that has been retrieved using the :meth:`get_metadata` call.
"""
return self.client._perform_empty(
"PUT", "/projects/%s/metadata" % self.project_key, body = metadata)
def get_settings(self):
"""
Gets the settings of this project. This does not contain permissions. See :meth:`get_permissions`
:returns a handle to read, modify and save the settings
:rtype: :class:`DSSProjectSettings`
"""
ret = self.client._perform_json("GET", "/projects/%s/settings" % self.project_key)
return DSSProjectSettings(self.client, self.project_key, ret)
def get_permissions(self):
"""
Get the permissions attached to this project
:returns: A dict containing the owner and the permissions, as a list of pairs of group name and permission type
"""
return self.client._perform_json(
"GET", "/projects/%s/permissions" % self.project_key)
def set_permissions(self, permissions):
"""
Sets the permissions on this project
:param permissions dict: a permissions object with the same structure as the one returned by :meth:`get_permissions` call
"""
return self.client._perform_empty(
"PUT", "/projects/%s/permissions" % self.project_key, body = permissions)
def get_interest(self):
"""
Get the interest of this project. The interest means the number of watchers and the number of stars.
:returns: a dict object containing the interest of the project with two fields:
- starCount: number of stars for this project
- watchCount: number of users watching this project
:rtype: dict
"""
return self.client._perform_json("GET","/projects/%s/interest" % self.project_key)
def get_timeline(self, item_count=100):
"""
Get the timeline of this project. The timeline consists of information about the creation of this project
(by whom, and when), the last modification of this project (by whom and when), a list of contributors,
and a list of modifications. This list of modifications contains a maximum of `item_count` elements (default: 100).
If `item_count` is greater than the real number of modification, `item_count` is adjusted.
:return: a dict object containing a timeline where the top-level fields are :
- allContributors: all contributors who have been involve in this project
- items: a history of the modifications of the project
- createdBy: who created this project
- createdOn: when the project was created
- lastModifiedBy: who modified this project for the last time
- lastModifiedOn: when this modification took place
:rtype: dict
"""
return self.client._perform_json("GET", "/projects/%s/timeline" % self.project_key, params = {
"itemCount": item_count
})
########################################################
# Datasets
########################################################
def list_datasets(self, as_type="listitems"):
"""
List the datasets in this project.
:param str as_type: How to return the list. Supported values are "listitems" and "objects".
:returns: The list of the datasets. If "as_type" is "listitems", each one as a :class:`dataset.DSSDatasetListItem`.
If "as_type" is "objects", each one as a :class:`dataset.DSSDataset`
:rtype: list
"""
items = self.client._perform_json("GET", "/projects/%s/datasets/" % self.project_key)
if as_type == "listitems" or as_type == "listitem":
return [DSSDatasetListItem(self.client, item) for item in items]
elif as_type == "objects" or as_type == "object":
return [DSSDataset(self.client, self.project_key, item["name"]) for item in items]
else:
raise ValueError("Unknown as_type")
def get_dataset(self, dataset_name):
"""
Get a handle to interact with a specific dataset
:param string dataset_name: the name of the desired dataset
:returns: A :class:`dataikuapi.dss.dataset.DSSDataset` dataset handle
"""
return DSSDataset(self.client, self.project_key, dataset_name)
def create_dataset(self, dataset_name, type,
params=None, formatType=None, formatParams=None):
"""
Create a new dataset in the project, and return a handle to interact with it.
The precise structure of ``params`` and ``formatParams`` depends on the specific dataset
type and dataset format type. To know which fields exist for a given dataset type and format type,
create a dataset from the UI, and use :meth:`get_dataset` to retrieve the configuration
of the dataset and inspect it. Then reproduce a similar structure in the :meth:`create_dataset` call.
Not all settings of a dataset can be set at creation time (for example partitioning). After creation,
you'll have the ability to modify the dataset
:param string dataset_name: the name for the new dataset
:param string type: the type of the dataset
:param dict params: the parameters for the type, as a JSON object (defaults to `{}`)
:param string formatType: an optional format to create the dataset with (only for file-oriented datasets)
:param dict formatParams: the parameters to the format, as a JSON object (only for file-oriented datasets, default to `{}`)
Returns:
A :class:`dataikuapi.dss.dataset.DSSDataset` dataset handle
"""
if params is None:
params = {}
if formatParams is None:
formatParams = {}
obj = {
"name" : dataset_name,
"projectKey" : self.project_key,
"type" : type,
"params" : params,
"formatType" : formatType,
"formatParams" : formatParams
}
self.client._perform_json("POST", "/projects/%s/datasets/" % self.project_key,
body = obj)
return DSSDataset(self.client, self.project_key, dataset_name)
def create_upload_dataset(self, dataset_name, connection=None):
obj = {
"name" : dataset_name,
"projectKey" : self.project_key,
"type" : "UploadedFiles",
"params" : {}
}
if connection is not None:
obj["params"]["uploadConnection"] = connection
self.client._perform_json("POST", "/projects/%s/datasets/" % self.project_key,
body = obj)
return DSSDataset(self.client, self.project_key, dataset_name)
def create_filesystem_dataset(self, dataset_name, connection, path_in_connection):
return self.create_fslike_dataset(dataset_name, "Filesystem", connection, path_in_connection)
def create_s3_dataset(self, dataset_name, connection, path_in_connection, bucket=None):
"""
Creates a new external S3 dataset in the project and returns a :class:`~dataikuapi.dss.dataset.DSSDataset` to interact with it.
The created dataset doesn not have its format and schema initialized, it is recommend to use
:meth:`~dataikuapi.dss.dataset.DSSDataset.autodetect_settings` on the returned object
:param dataset_name: Name of the dataset to create. Must not already exist
:rtype: `~dataikuapi.dss.dataset.DSSDataset`
"""
extra_params = {}
if bucket is not None:
extra_params["bucket"] = bucket
return self.create_fslike_dataset(dataset_name, "S3", connection, path_in_connection, extra_params)
def create_fslike_dataset(self, dataset_name, dataset_type, connection, path_in_connection, extra_params=None):
body = {
"name" : dataset_name,
"projectKey" : self.project_key,
"type" : dataset_type,
"params" : {
"connection" : connection,
"path": path_in_connection
}
}
if extra_params is not None:
body["params"].update(extra_params)
self.client._perform_json("POST", "/projects/%s/datasets/" % self.project_key, body = body)
return DSSDataset(self.client, self.project_key, dataset_name)
def create_sql_table_dataset(self, dataset_name, type, connection, table, schema):
obj = {
"name" : dataset_name,
"projectKey" : self.project_key,
"type" : type,
"params" : {
"connection" : connection,
"mode": "table",
"table" : table,
"schema" : schema
}
}
self.client._perform_json("POST", "/projects/%s/datasets/" % self.project_key,
body = obj)
return DSSDataset(self.client, self.project_key, dataset_name)
def new_managed_dataset_creation_helper(self, dataset_name):
"""Deprecated. Please use :meth:`new_managed_dataset`"""
warnings.warn("new_managed_dataset_creation_helper is deprecated, please use new_managed_dataset", DeprecationWarning)
return DSSManagedDatasetCreationHelper(self, dataset_name)
def new_managed_dataset(self, dataset_name):
"""
Initializes the creation of a new managed dataset. Returns a :class:`dataikuapi.dss.dataset.DSSManagedDatasetCreationHelper`
or one of its subclasses to complete the creation of the managed dataset.
Usage example:
.. code-block:: python
builder = project.new_managed_dataset("my_dataset")
builder.with_store_into("target_connection")
dataset = builder.create()
:param str dataset_name: Name of the dataset to create
:rtype: :class:`dataikuapi.dss.dataset.DSSManagedDatasetCreationHelper`
:return: A :class:`dataikuapi.dss.dataset.DSSManagedDatasetCreationHelper` object to create the managed dataset
"""
return DSSManagedDatasetCreationHelper(self, dataset_name)
########################################################
# Streaming endpoints
########################################################
def list_streaming_endpoints(self, as_type="listitems"):
"""
List the streaming endpoints in this project.
:param str as_type: How to return the list. Supported values are "listitems" and "objects".
:returns: The list of the streaming endpoints. If "as_type" is "listitems", each one as a :class:`streaming_endpoint.DSSStreamingEndpointListItem`.
If "as_type" is "objects", each one as a :class:`streaming_endpoint.DSSStreamingEndpoint`
:rtype: list
"""
items = self.client._perform_json("GET", "/projects/%s/streamingendpoints/" % self.project_key)
if as_type == "listitems" or as_type == "listitem":
return [DSSStreamingEndpointListItem(self.client, item) for item in items]
elif as_type == "objects" or as_type == "object":
return [DSSStreamingEndpoint(self.client, self.project_key, item["id"]) for item in items]
else:
raise ValueError("Unknown as_type")
def get_streaming_endpoint(self, streaming_endpoint_name):
"""
Get a handle to interact with a specific streaming endpoint
:param string streaming_endpoint_name: the name of the desired streaming endpoint
:returns: A :class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpoint` streaming endpoint handle
"""
return DSSStreamingEndpoint(self.client, self.project_key, streaming_endpoint_name)
def create_streaming_endpoint(self, streaming_endpoint_name, type, params=None):
"""
Create a new streaming endpoint in the project, and return a handle to interact with it.
The precise structure of ``params`` depends on the specific streaming endpoint
type. To know which fields exist for a given streaming endpoint type,
create a streaming endpoint from the UI, and use :meth:`get_streaming_endpoint` to retrieve the configuration
of the streaming endpoint and inspect it. Then reproduce a similar structure in the :meth:`create_streaming_endpoint` call.
Not all settings of a streaming endpoint can be set at creation time (for example partitioning). After creation,
you'll have the ability to modify the streaming endpoint
:param string streaming_endpoint_name: the name for the new streaming endpoint
:param string type: the type of the streaming endpoint
:param dict params: the parameters for the type, as a JSON object (defaults to `{}`)
Returns:
A :class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpoint` streaming endpoint handle
"""
if params is None:
params = {}
obj = {
"id" : streaming_endpoint_name,
"projectKey" : self.project_key,
"type" : type,
"params" : params
}
self.client._perform_json("POST", "/projects/%s/streamingendpoints/" % self.project_key,
body = obj)
return DSSStreamingEndpoint(self.client, self.project_key, streaming_endpoint_name)
def create_kafka_streaming_endpoint(self, streaming_endpoint_name, connection=None, topic=None):
obj = {
"id" : streaming_endpoint_name,
"projectKey" : self.project_key,
"type" : "kafka",
"params" : {}
}
if connection is not None:
obj["params"]["connection"] = connection
if topic is not None:
obj["params"]["topic"] = topic
self.client._perform_json("POST", "/projects/%s/streamingendpoints/" % self.project_key,
body = obj)
return DSSStreamingEndpoint(self.client, self.project_key, streaming_endpoint_name)
def create_httpsse_streaming_endpoint(self, streaming_endpoint_name, url=None):
obj = {
"id" : streaming_endpoint_name,
"projectKey" : self.project_key,
"type" : "httpsse",
"params" : {}
}
if url is not None:
obj["params"]["url"] = url
self.client._perform_json("POST", "/projects/%s/streamingendpoints/" % self.project_key,
body = obj)
return DSSStreamingEndpoint(self.client, self.project_key, streaming_endpoint_name)
def new_managed_streaming_endpoint(self, streaming_endpoint_name, streaming_endpoint_type=None):
"""
Initializes the creation of a new streaming endpoint. Returns a :class:`dataikuapi.dss.streaming_endpoint.DSSManagedStreamingEndpointCreationHelper`
to complete the creation of the streaming endpoint
:param string streaming_endpoint_name: Name of the new streaming endpoint - must be unique in the project
:param string streaming_endpoint_type: Type of the new streaming endpoint (optional if it can be inferred from a connection type)
:return: A :class:`dataikuapi.dss.streaming_endpoint.DSSManagedStreamingEndpointCreationHelper` object to create the streaming endpoint
"""
return DSSManagedStreamingEndpointCreationHelper(self, streaming_endpoint_name, streaming_endpoint_type)
########################################################
# Lab and ML
# Don't forget to synchronize with DSSDataset.*
########################################################
def create_prediction_ml_task(self, input_dataset, target_variable,
ml_backend_type="PY_MEMORY",
guess_policy="DEFAULT",
prediction_type=None,
wait_guess_complete=True):
"""Creates a new prediction task in a new visual analysis lab
for a dataset.
:param string input_dataset: the dataset to use for training/testing the model
:param string target_variable: the variable to predict
:param string ml_backend_type: ML backend to use, one of PY_MEMORY, MLLIB or H2O
:param string guess_policy: Policy to use for setting the default parameters. Valid values are: DEFAULT, SIMPLE_FORMULA, DECISION_TREE, EXPLANATORY and PERFORMANCE
:param string prediction_type: The type of prediction problem this is. If not provided the prediction type will be guessed. Valid values are: BINARY_CLASSIFICATION, REGRESSION, MULTICLASS
:param boolean wait_guess_complete: if False, the returned ML task will be in 'guessing' state, i.e. analyzing the input dataset to determine feature handling and algorithms.
You should wait for the guessing to be completed by calling
``wait_guess_complete`` on the returned object before doing anything
else (in particular calling ``train`` or ``get_settings``)
"""
obj = {
"inputDataset": input_dataset,
"taskType": "PREDICTION",
"targetVariable": target_variable,
"backendType": ml_backend_type,
"guessPolicy": guess_policy
}
if prediction_type is not None:
obj["predictionType"] = prediction_type
ref = self.client._perform_json("POST", "/projects/%s/models/lab/" % self.project_key, body=obj)
ret = DSSMLTask(self.client, self.project_key, ref["analysisId"], ref["mlTaskId"])
if wait_guess_complete:
ret.wait_guess_complete()
return ret
def create_clustering_ml_task(self, input_dataset,
ml_backend_type = "PY_MEMORY",
guess_policy = "KMEANS",
wait_guess_complete=True):
"""Creates a new clustering task in a new visual analysis lab
for a dataset.
The returned ML task will be in 'guessing' state, i.e. analyzing
the input dataset to determine feature handling and algorithms.
You should wait for the guessing to be completed by calling
``wait_guess_complete`` on the returned object before doing anything
else (in particular calling ``train`` or ``get_settings``)
:param string ml_backend_type: ML backend to use, one of PY_MEMORY, MLLIB or H2O
:param string guess_policy: Policy to use for setting the default parameters. Valid values are: KMEANS and ANOMALY_DETECTION
:param boolean wait_guess_complete: if False, the returned ML task will be in 'guessing' state, i.e. analyzing the input dataset to determine feature handling and algorithms.
You should wait for the guessing to be completed by calling
``wait_guess_complete`` on the returned object before doing anything
else (in particular calling ``train`` or ``get_settings``)
"""
obj = {
"inputDataset" : input_dataset,
"taskType" : "CLUSTERING",
"backendType": ml_backend_type,
"guessPolicy": guess_policy
}
ref = self.client._perform_json("POST", "/projects/%s/models/lab/" % self.project_key, body=obj)
mltask = DSSMLTask(self.client, self.project_key, ref["analysisId"], ref["mlTaskId"])
if wait_guess_complete:
mltask.wait_guess_complete()
return mltask
def list_ml_tasks(self):
"""
List the ML tasks in this project
Returns:
the list of the ML tasks summaries, each one as a JSON object
"""
return self.client._perform_json("GET", "/projects/%s/models/lab/" % self.project_key)
def get_ml_task(self, analysis_id, mltask_id):
"""
Get a handle to interact with a specific ML task
Args:
analysis_id: the identifier of the visual analysis containing the desired ML task
mltask_id: the identifier of the desired ML task
Returns:
A :class:`dataikuapi.dss.ml.DSSMLTask` ML task handle
"""
return DSSMLTask(self.client, self.project_key, analysis_id, mltask_id)
def list_mltask_queues(self):
"""
List non-empty ML task queues in this project
:returns: an iterable :class:`DSSMLTaskQueues` listing of MLTask queues (each a dict)
:rtype: :class:`DSSMLTaskQueues`
"""
data = self.client._perform_json("GET", "/projects/%s/models/labs/mltask-queues" % self.project_key)
return DSSMLTaskQueues(data)
def create_analysis(self, input_dataset):
"""
Creates a new visual analysis lab for a dataset.
"""
obj = {
"inputDataset" : input_dataset
}
ref = self.client._perform_json("POST", "/projects/%s/lab/" % self.project_key, body=obj)
return DSSAnalysis(self.client, self.project_key, ref["id"])
def list_analyses(self):
"""
List the visual analyses in this project
Returns:
the list of the visual analyses summaries, each one as a JSON object
"""
return self.client._perform_json("GET", "/projects/%s/lab/" % self.project_key)
def get_analysis(self, analysis_id):
"""
Get a handle to interact with a specific visual analysis
Args:
analysis_id: the identifier of the desired visual analysis
Returns:
A :class:`dataikuapi.dss.analysis.DSSAnalysis` visual analysis handle
"""
return DSSAnalysis(self.client, self.project_key, analysis_id)
########################################################
# Saved models
########################################################
def list_saved_models(self):
"""
List the saved models in this project
Returns:
the list of the saved models, each one as a JSON object
"""
return self.client._perform_json(
"GET", "/projects/%s/savedmodels/" % self.project_key)
def get_saved_model(self, sm_id):
"""
Get a handle to interact with a specific saved model
Args:
sm_id: the identifier of the desired saved model
Returns:
A :class:`dataikuapi.dss.savedmodel.DSSSavedModel` saved model handle
"""
return DSSSavedModel(self.client, self.project_key, sm_id)
def create_mlflow_pyfunc_model(self, name, prediction_type = None):
"""
Creates a new external saved model for storing and managing MLFlow models
:param string name: Human readable name for the new saved model in the flow
:param string prediction_type: Optional (but needed for most operations). One of BINARY_CLASSIFICATION, MULTICLASS or REGRESSION
"""
model = {
"savedModelType" : "MLFLOW_PYFUNC",
"predictionType" : prediction_type,
"name": name
}
id = self.client._perform_json("POST", "/projects/%s/savedmodels/" % self.project_key, body = model)["id"]
return self.get_saved_model(id)
########################################################
# Managed folders
########################################################
def list_managed_folders(self):
"""
List the managed folders in this project
Returns:
the list of the managed folders, each one as a JSON object
"""
return self.client._perform_json(
"GET", "/projects/%s/managedfolders/" % self.project_key)
def get_managed_folder(self, odb_id):
"""
Get a handle to interact with a specific managed folder
Args:
odb_id: the identifier of the desired managed folder
Returns:
A :class:`dataikuapi.dss.managedfolder.DSSManagedFolder` managed folder handle
"""
return DSSManagedFolder(self.client, self.project_key, odb_id)
def create_managed_folder(self, name, folder_type=None, connection_name="filesystem_folders"):
"""
Create a new managed folder in the project, and return a handle to interact with it
Args:
name: the name of the managed folder
Returns:
A :class:`dataikuapi.dss.managedfolder.DSSManagedFolder` managed folder handle
"""
obj = {
"name" : name,
"projectKey" : self.project_key,
"type" : folder_type,
"params" : {
"connection" : connection_name,
"path" : "/${projectKey}/${odbId}"
}
}
res = self.client._perform_json("POST", "/projects/%s/managedfolders/" % self.project_key,
body = obj)
odb_id = res['id']
return DSSManagedFolder(self.client, self.project_key, odb_id)
########################################################
# Model evaluation stores
########################################################
def list_model_evaluation_stores(self):
"""
List the model evaluation stores in this project.
:returns: The list of the model evaluation stores
:rtype: list of :class:`dataikuapi.dss.modelevaluationstore.DSSModelEvaluationStore`
"""
items = self.client._perform_json("GET", "/projects/%s/modelevaluationstores/" % self.project_key)
return [DSSModelEvaluationStore(self.client, self.project_key, item["id"]) for item in items]
def get_model_evaluation_store(self, mes_id):
"""
Get a handle to interact with a specific model evaluation store
:param string mes_id: the id of the desired model evaluation store
:returns: A :class:`dataikuapi.dss.modelevaluationstore.DSSModelEvaluationStore` model evaluation store handle
"""
return DSSModelEvaluationStore(self.client, self.project_key, mes_id)
def create_model_evaluation_store(self, name):
"""
Create a new model evaluation store in the project, and return a handle to interact with it.
:param string name: the name for the new model evaluation store
:returns: A :class:`dataikuapi.dss.modelevaluationstore.DSSModelEvaluationStore` model evaluation store handle
"""
obj = {
"projectKey" : self.project_key,
"name" : name
}
res = self.client._perform_json("POST", "/projects/%s/modelevaluationstores/" % self.project_key,
body = obj)
mes_id = res['id']
return DSSModelEvaluationStore(self.client, self.project_key, mes_id)
########################################################
# Model comparisons
########################################################
def list_model_comparisons(self):
"""
List the model comparisons in this project.
:returns: The list of the model comparisons
:rtype: list
"""
items = self.client._perform_json("GET", "/projects/%s/modelcomparisons/" % self.project_key)
return [DSSModelComparison(self.client, self.project_key, item["id"]) for item in items]
def get_model_comparison(self, mec_id):
"""
Get a handle to interact with a specific model comparison
:param string mec_id: the id of the desired model comparison
:returns: A handle on a model comparison
:rtype: :class:`dataikuapi.dss.modelcomparison.DSSModelComparison`
"""
return DSSModelComparison(self.client, self.project_key, mec_id)
def create_model_comparison(self, name, prediction_type):
"""
Create a new model comparison in the project, and return a handle to interact with it.
:param string name: the name for the new model comparison
:param string prediction_type: one of BINARY_CLASSIFICATION, REGRESSION and MULTICLASS
:returns: A handle on a new model comparison
:rtype: :class:`dataikuapi.dss.modelcomparison.DSSModelComparison`
"""
obj = {
"projectKey": self.project_key,
"displayName": name,
"predictionType": prediction_type
}
res = self.client._perform_json("POST", "/projects/%s/modelcomparisons/" % self.project_key,
body = obj)
mec_id = res['id']
return DSSModelComparison(self.client, self.project_key, mec_id)
########################################################
# Jobs
########################################################
def list_jobs(self):
"""
List the jobs in this project
Returns:
a list of the jobs, each one as a JSON object, containing both the definition and the state
"""
return self.client._perform_json(
"GET", "/projects/%s/jobs/" % self.project_key)
def get_job(self, id):
"""
Get a handler to interact with a specific job
Returns:
A :class:`dataikuapi.dss.job.DSSJob` job handle
"""
return DSSJob(self.client, self.project_key, id)
def start_job(self, definition):
"""
Create a new job, and return a handle to interact with it
:param dict definition: The definition should contain:
* the type of job (RECURSIVE_BUILD, NON_RECURSIVE_FORCED_BUILD, RECURSIVE_FORCED_BUILD, RECURSIVE_MISSING_ONLY_BUILD)
* a list of outputs to build from the available types: (DATASET, MANAGED_FOLDER, SAVED_MODEL, STREAMING_ENDPOINT)
* (Optional) a refreshHiveMetastore field (True or False) to specify whether to re-synchronize the Hive metastore for recomputed HDFS datasets.
:returns: A :class:`dataikuapi.dss.job.DSSJob` job handle
"""
job_def = self.client._perform_json("POST", "/projects/%s/jobs/" % self.project_key, body = definition)
return DSSJob(self.client, self.project_key, job_def['id'])
def start_job_and_wait(self, definition, no_fail=False):
"""
Starts a new job and waits for it to complete.
:param dict definition: The definition should contain:
* the type of job (RECURSIVE_BUILD, NON_RECURSIVE_FORCED_BUILD, RECURSIVE_FORCED_BUILD, RECURSIVE_MISSING_ONLY_BUILD)
* a list of outputs to build from the available types: (DATASET, MANAGED_FOLDER, SAVED_MODEL, STREAMING_ENDPOINT)
* (Optional) a refreshHiveMetastore field (True or False) to specify whether to re-synchronize the Hive metastore for recomputed HDFS datasets.
"""
job_def = self.client._perform_json("POST", "/projects/%s/jobs/" % self.project_key, body = definition)
job = DSSJob(self.client, self.project_key, job_def['id'])
waiter = DSSJobWaiter(job)
return waiter.wait(no_fail)
def new_job(self, job_type='NON_RECURSIVE_FORCED_BUILD'):
"""
Create a job to be run
You need to add outputs to the job (i.e. what you want to build) before running it.
.. code-block:: python
job_builder = project.new_job()
job_builder.with_output("mydataset")
complete_job = job_builder.start_and_wait()
print("Job %s done" % complete_job.id)
:rtype: :class:`JobDefinitionBuilder`
"""
return JobDefinitionBuilder(self, job_type)
def new_job_definition_builder(self, job_type='NON_RECURSIVE_FORCED_BUILD'):
"""Deprecated. Please use :meth:`new_job`"""
warnings.warn("new_job_definition_builder is deprecated, please use new_job", DeprecationWarning)
return JobDefinitionBuilder(self, job_type)
########################################################
# Jupyter Notebooks
########################################################
def list_jupyter_notebooks(self, active=False, as_type="object"):
"""
List the jupyter notebooks of a project.
:param bool as_type: How to return the list. Supported values are "listitems" and "objects".
:param bool active: if True, only return currently running jupyter notebooks.
:returns: The list of the notebooks. If "as_type" is "listitems", each one as a :class:`dataikuapi.dss.notebook.DSSJupyterNotebookListItem`, if "as_type" is "objects", each one as a :class:`dataikuapi.dss.notebook.DSSJupyterNotebook`
:rtype: list of :class:`dataikuapi.dss.notebook.DSSJupyterNotebook` or list of :class:`dataikuapi.dss.notebook.DSSJupyterNotebookListItem`
"""
notebook_items = self.client._perform_json("GET", "/projects/%s/jupyter-notebooks/" % self.project_key, params={"active": active})
if as_type == "listitems" or as_type == "listitem":
return [DSSJupyterNotebookListItem(self.client, notebook_item) for notebook_item in notebook_items]
elif as_type == "objects" or as_type == "object":
return [DSSJupyterNotebook(self.client, self.project_key, notebook_item["name"]) for notebook_item in notebook_items]
else:
raise ValueError("Unknown as_type")
def get_jupyter_notebook(self, notebook_name):
"""
Get a handle to interact with a specific jupyter notebook
:param str notebook_name: The name of the jupyter notebook to retrieve
:returns: A handle to interact with this jupyter notebook
:rtype: :class:`~dataikuapi.dss.notebook.DSSNotebook` jupyter notebook handle
"""
return DSSJupyterNotebook(self.client, self.project_key, notebook_name)
def create_jupyter_notebook(self, notebook_name, notebook_content):
"""
Create a new jupyter notebook and get a handle to interact with it
:param str notebook_name: the name of the notebook to create
:param dict notebook_content: the data of the notebook to create, as a dict.
The data will be converted to a JSON string internally.
Use ``get_content()`` on a similar existing ``DSSNotebook`` object in order to get a sample definition object
:returns: A handle to interact with the newly created jupyter notebook
:rtype: :class:`~dataikuapi.dss.notebook.DSSNotebook` jupyter notebook handle
"""
self.client._perform_json("POST", "/projects/%s/jupyter-notebooks/%s" % (self.project_key, notebook_name), body=notebook_content)
return self.get_jupyter_notebook(notebook_name)