-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathproject.py
3260 lines (2646 loc) · 144 KB
/
project.py
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.path as osp
import warnings
from . import recipe
from .analysis import DSSAnalysis
from .apiservice import DSSAPIService, DSSAPIServiceListItem
from .app import DSSAppManifest
from .codestudio import DSSCodeStudioObject, DSSCodeStudioObjectListItem
from .continuousactivity import DSSContinuousActivity
from .dashboard import DSSDashboard, DSSDashboardListItem, DASHBOARDS_URI_FORMAT
from .dataset import DSSDataset, DSSDatasetListItem, DSSManagedDatasetCreationHelper
from .discussion import DSSObjectDiscussions
from .document_extractor import DocumentExtractor
from .flow import DSSProjectFlow
from .future import DSSFuture
from .insight import DSSInsight, DSSInsightListItem, INSIGHTS_URI_FORMAT
from .job import DSSJob, DSSJobWaiter
from .jupyternotebook import DSSJupyterNotebook, DSSJupyterNotebookListItem
from .labeling_task import DSSLabelingTask
from .macro import DSSMacro
from .managedfolder import DSSManagedFolder
from .ml import DSSMLTask, DSSMLTaskQueues
from .mlflow import DSSMLflowExtension
from .modelcomparison import DSSModelComparison
from .modelevaluationstore import DSSModelEvaluationStore
from .notebook import DSSNotebook
from .projectlibrary import DSSLibrary
from .recipe import DSSRecipeListItem, DSSRecipe
from .savedmodel import DSSSavedModel
from .scenario import DSSScenario, DSSScenarioListItem, DSSTestingStatus
from .sqlnotebook import DSSSQLNotebook, DSSSQLNotebookListItem
from .streaming_endpoint import DSSStreamingEndpoint, DSSStreamingEndpointListItem, \
DSSManagedStreamingEndpointCreationHelper
from .webapp import DSSWebApp, DSSWebAppListItem
from .wiki import DSSWiki
from .llm import DSSLLM, DSSLLMListItem
from .agent_tool import DSSAgentTool, DSSAgentToolListItem
from .knowledgebank import DSSKnowledgeBank, DSSKnowledgeBankListItem
from ..dss_plugin_mlflow import MLflowHandle
class DSSProject(object):
"""
A handle to interact with a project on the DSS instance.
.. important::
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):
"""
Get the folder 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: destination folder
:type 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
.. attention::
This call requires an API key with admin rights
:param bool clear_managed_datasets: Should the data of managed datasets be cleared (defaults to **False**)
:param bool clear_output_managed_folders: Should the data of managed folders used as outputs of recipes be cleared (defaults to **False**)
:param bool clear_job_and_scenario_logs: Should the job and scenario logs be cleared (defaults to **True**)
"""
# 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
.. warning::
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 to **False**)
- **exportManagedFS** (boolean): Exports the data of managed Filesystem datasets (default to **False**)
- **exportAnalysisModels** (boolean): Exports the models trained in analysis (default to **False**)
- **exportSavedModels** (boolean): Exports the models trained in saved models (default to **False**)
- **exportManagedFolders** (boolean): Exports the data of managed folders (default to **False**)
- **exportAllInputDatasets** (boolean): Exports the data of all input datasets (default to **False**)
- **exportAllDatasets** (boolean): Exports the data of all datasets (default to **False**)
- **exportAllInputManagedFolders** (boolean):
Exports the data of all input managed folders (default to **False**)
- **exportGitRepository** (boolean): Exports the Git repository history (you must be project admin if a git remote with credentials is configured, defaults to **False**)
- **exportInsightsData** (boolean): Exports the data of static insights (default to **False**)
:returns: a stream of the export archive
:rtype: file-like object
"""
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 to **False**)
* **exportManagedFS** (boolean): Exports the data of managed Filesystem datasets (default to **False**)
* **exportAnalysisModels** (boolean): Exports the models trained in analysis (default to **False**)
* **exportSavedModels** (boolean): Exports the models trained in saved models (default to **False**)
* **exportModelEvaluationStores** (boolean): Exports the evaluation stores (default to **False**)
* **exportManagedFolders** (boolean): Exports the data of managed folders (default to **False**)
* **exportAllInputDatasets** (boolean): Exports the data of all input datasets (default to **False**)
* **exportAllDatasets** (boolean): Exports the data of all datasets (default to **False**)
* **exportAllInputManagedFolders** (boolean): \
Exports the data of all input managed folders (default to **False**)
* **exportGitRepository** (boolean): Exports the Git repository history (you must be project admin if git contains a remote with credentials, defaults to **False**)
* **exportInsightsData** (boolean): Exports the data of static insights (default to **False**)
* **exportPromptStudioHistories** (boolean): Exports the prompt studio execution histories (default to **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=None,
export_insights_data=True,
remapping=None,
target_project_folder=None):
"""
Duplicate the project
:param str target_project_key: The key of the new project
:param str target_project_name: The name of the new project
:param str duplication_mode: can be one of the following values: MINIMAL, SHARING, FULL, NONE (defaults to **MINIMAL**)
:param bool export_analysis_models: (defaults to **True**)
:param bool export_saved_models: (defaults to **True**)
:param bool export_git_repository: (you must be project admin if git contains a remote with credentials, defaults to **True** if authorized)
:param bool export_insights_data: (defaults to **True**)
: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 (defaults to **None**)
:type target_project_folder: A :class:`dataikuapi.dss.projectfolder.DSSProjectFolder`
:returns: A dict containing the original and duplicated project's keys
:rtype: dict
"""
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.
.. note::
For more information on available metadata, please see https://doc.dataiku.com/dss/api/latest/rest/
:returns: 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.
Usage example:
.. code-block:: python
project_metadata = project.get_metadata()
project_metadata['tags'] = ['tag1','tag2']
project.set_metadata(project_metadata)
:param dict metadata: 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:`dataikuapi.dss.project.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
:rtype: dict
"""
return self.client._perform_json(
"GET", "/projects/%s/permissions" % self.project_key)
def set_permissions(self, permissions):
"""
Sets the permissions on this project
Usage example:
.. code-block:: python
project_permissions = project.get_permissions()
project_permissions['permissions'].append({'group':'data_scientists',
'readProjectContent': True,
'readDashboards': True})
project.set_permissions(project_permissions)
:param dict permissions: 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 to 100). If **item_count** is greater than the real number of modification, **item_count** is adjusted.
:param int item_count: maximum number of modifications to retrieve in the items list
:returns: a timeline where the top-level fields are :
* **allContributors**: all contributors who have been involved 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" (defaults to **listitems**).
:returns: The list of the datasets. If "as_type" is "listitems",
each one as a :class:`dataikuapi.dss.dataset.DSSDatasetListItem`. If "as_type" is "objects",
each one as a :class:`dataikuapi.dss.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 str dataset_name: the name of the desired dataset
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
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 str dataset_name: the name of the dataset to create. Must not already exist
:param str type: the type of the dataset
:param dict params: the parameters for the type, as a python dict (defaults to **{}**)
:param str formatType: an optional format to create the dataset with (only for file-oriented datasets)
:param dict formatParams: the parameters to the format, as a python dict (only for file-oriented datasets, default to **{}**)
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
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):
"""
Create a new dataset of type 'UploadedFiles' in the project, and return a handle to interact with it.
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str connection: the name of the upload connection (defaults to **None**)
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
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):
"""
Create a new filesystem dataset in the project, and return a handle to interact with it.
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str connection: the name of the connection
:param str path_in_connection: the path of the dataset in the connection
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
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 does not have its format and schema initialized, it is recommended to use
:meth:`~dataikuapi.dss.dataset.DSSDataset.autodetect_settings` on the returned object
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str connection: the name of the connection
:param str path_in_connection: the path of the dataset in the connection
:param str bucket: the name of the s3 bucket (defaults to **None**)
:returns: A dataset handle
:rtype: :class:`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_gcs_dataset(self, dataset_name, connection, path_in_connection, bucket=None):
"""
Creates a new external GCS dataset in the project and returns a :class:`dataikuapi.dss.dataset.DSSDataset` to
interact with it.
The created dataset does not have its format and schema initialized, it is recommended to use
:meth:`~dataikuapi.dss.dataset.DSSDataset.autodetect_settings` on the returned object
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str connection: the name of the connection
:param str path_in_connection: the path of the dataset in the connection
:param str bucket: the name of the GCS bucket (defaults to **None**)
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
extra_params = {}
if bucket is not None:
extra_params["bucket"] = bucket
return self.create_fslike_dataset(dataset_name, "GCS", connection, path_in_connection, extra_params)
def create_azure_blob_dataset(self, dataset_name, connection, path_in_connection, container=None):
"""
Creates a new external Azure dataset in the project and returns a :class:`dataikuapi.dss.dataset.DSSDataset` to
interact with it.
The created dataset does not have its format and schema initialized, it is recommended to use
:meth:`~dataikuapi.dss.dataset.DSSDataset.autodetect_settings` on the returned object
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str connection: the name of the connection
:param str path_in_connection: the path of the dataset in the connection
:param str container: the name of the storage account container (defaults to **None**)
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
extra_params = {}
if container is not None:
extra_params["container"] = container
return self.create_fslike_dataset(dataset_name, "Azure", connection, path_in_connection, extra_params)
def create_fslike_dataset(self, dataset_name, dataset_type, connection, path_in_connection, extra_params=None):
"""
Create a new file-based dataset in the project, and return a handle to interact with it.
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str dataset_type: the type of the dataset
:param str connection: the name of the connection
:param str path_in_connection: the path of the dataset in the connection
:param dict extra_params: a python dict of extra parameters (defaults to **None**)
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
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, catalog=None):
"""
Create a new SQL table dataset in the project, and return a handle to interact with it.
:param str dataset_name: the name of the dataset to create. Must not already exist
:param str type: the type of the dataset
:param str connection: the name of the connection
:param str table: the name of the table in the connection
:param str schema: the schema of the table
:param str catalog: [optional] the catalog of the table
:returns: A dataset handle
:rtype: :class:`dataikuapi.dss.dataset.DSSDataset`
"""
obj = {
"name": dataset_name,
"projectKey": self.project_key,
"type": type,
"params": {
"connection": connection,
"mode": "table",
"table": table,
"schema": schema,
"catalog": catalog
}
}
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):
"""
.. caution::
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
:returns: An object to create the managed dataset
:rtype: :class:`dataikuapi.dss.dataset.DSSManagedDatasetCreationHelper`
"""
return DSSManagedDatasetCreationHelper(self, dataset_name)
################
# Labeling tasks
################
def get_labeling_task(self, labeling_task_id):
"""
Get a handle to interact with a specific labeling task
:param str labeling_task_id: the id of the desired labeling task
:returns: A labeling task handle
:rtype: :class:`dataikuapi.dss.labeling_task.DSSLabelingTask`
"""
return DSSLabelingTask(self.client, self.project_key, labeling_task_id)
########################################################
# 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"
(defaults to **listitems**).
:returns: The list of the streaming endpoints. If "as_type" is "listitems", each one as a
:class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpointListItem`. If "as_type" is "objects",
each one as a :class:`dataikuapi.dss.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 str streaming_endpoint_name: the name of the desired streaming endpoint
:returns: A streaming endpoint handle
:rtype: :class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpoint`
"""
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 str streaming_endpoint_name: the name for the new streaming endpoint
:param str type: the type of the streaming endpoint
:param dict params: the parameters for the type, as a python dict (defaults to **{}**)
:returns: A streaming endpoint handle
:rtype: :class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpoint`
"""
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):
"""
Create a new kafka streaming endpoint in the project, and return a handle to interact with it.
:param str streaming_endpoint_name: the name for the new streaming endpoint
:param str connection: the name of the kafka connection (defaults to **None**)
:param str topic: the name of the kafka topic (defaults to **None**)
:returns: A streaming endpoint handle
:rtype: :class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpoint`
"""
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):
"""
Create a new https streaming endpoint in the project, and return a handle to interact with it.
:param str streaming_endpoint_name: the name for the new streaming endpoint
:param str url: the url of the endpoint (defaults to **None**)
:returns: A streaming endpoint handle
:rtype: :class:`dataikuapi.dss.streaming_endpoint.DSSStreamingEndpoint`
"""
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 str streaming_endpoint_name: Name of the new streaming endpoint - must be unique in the project
:param str streaming_endpoint_type: Type of the new streaming endpoint (optional if it can be inferred from a
connection type)
:returns: An object to create the streaming endpoint
:rtype: :class:`~dataikuapi.dss.streaming_endpoint.DSSManagedStreamingEndpointCreationHelper`
"""
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 str input_dataset: the dataset to use for training/testing the model
:param str target_variable: the variable to predict
:param str ml_backend_type: ML backend to use, one of PY_MEMORY, MLLIB or H2O (defaults to **PY_MEMORY**)
:param str guess_policy: Policy to use for setting the default parameters. Valid values are: DEFAULT,
SIMPLE_FORMULA, DECISION_TREE, EXPLANATORY and PERFORMANCE (defaults to **DEFAULT**)
:param str 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 (defaults to **None**)
: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 (defaults to **True**). 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**)
:returns: A ML task handle of type 'PREDICTION'
:rtype: :class:`dataikuapi.dss.ml.DSSMLTask`
"""
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 str ml_backend_type: ML backend to use, one of PY_MEMORY, MLLIB or H2O (defaults to **PY_MEMORY**)
:param str guess_policy: Policy to use for setting the default parameters. Valid values are: KMEANS and
ANOMALY_DETECTION (defaults to **KMEANS**)
: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 (defaults to **True**). 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**)
:returns: A ML task handle of type 'CLUSTERING'
:rtype: :class:`dataikuapi.dss.ml.DSSMLTask`
"""
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 create_timeseries_forecasting_ml_task(self, input_dataset, target_variable,
time_variable,
timeseries_identifiers=None,
guess_policy="TIMESERIES_DEFAULT",
wait_guess_complete=True):
"""Creates a new time series forecasting 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 forecast
:param string time_variable: Column to be used as time variable. Should be a Date (parsed) column.
:param list timeseries_identifiers: List of columns to be used as time series identifiers (when the dataset has multiple series)
:param string guess_policy: Policy to use for setting the default parameters.
Valid values are: TIMESERIES_DEFAULT, TIMESERIES_STATISTICAL, and TIMESERIES_DEEP_LEARNING
: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``)
:return: :class:`dataiku.dss.ml.DSSMLTask`
"""
obj = {
"inputDataset": input_dataset,
"taskType": "PREDICTION",
"targetVariable": target_variable,
"timeVariable": time_variable,
"timeseriesIdentifiers": timeseries_identifiers,
"backendType": "PY_MEMORY",
"guessPolicy": guess_policy,
"predictionType": "TIMESERIES_FORECAST"
}
ref = self.client._perform_json(
"POST",
"/projects/{project_key}/models/lab/".format(project_key=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_causal_prediction_ml_task(self, input_dataset, outcome_variable,
treatment_variable,
prediction_type=None,
wait_guess_complete=True):
"""Creates a new causal 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 outcome_variable: The outcome to predict.
:param string treatment_variable: Column to be used as treatment variable.
:param string or None prediction_type: Valid values are: "CAUSAL_BINARY_CLASSIFICATION", "CAUSAL_REGRESSION" or None (in this case prediction_type will be set by the Guesser)
: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``)
:return: :class:`dataiku.dss.ml.DSSMLTask`
"""
obj = {
"inputDataset": input_dataset,
"taskType": "PREDICTION",
"targetVariable": outcome_variable,
"treatmentVariable": treatment_variable,
"backendType": "PY_MEMORY",
"guessPolicy": "CAUSAL_PREDICTION",
"predictionType": prediction_type # If None, predictionType will be set by the Guesser
}
ref = self.client._perform_json(
"POST",
"/projects/{project_key}/models/lab/".format(project_key=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 list_ml_tasks(self):
"""
List the ML tasks in this project
:returns: the list of the ML tasks summaries, each one as a python dict
:rtype: list
"""
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
:param str analysis_id: the identifier of the visual analysis containing the desired ML task
:param str mltask_id: the identifier of the desired ML task
:returns: A ML task handle
:rtype: :class:`dataikuapi.dss.ml.DSSMLTask`
"""
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 listing of MLTask queues (each a dict)
:rtype: :class:`dataikuapi.dss.ml.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.
:param str input_dataset: the dataset to use for the analysis
:returns: A visual analysis handle
:rtype: :class:`dataikuapi.dss.analysis.DSSAnalysis`
"""
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 python dict
:rtype: list
"""
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
:param str analysis_id: the identifier of the desired visual analysis
:returns: A visual analysis handle
:rtype: :class:`dataikuapi.dss.analysis.DSSAnalysis`
"""
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 python dict
:rtype: list
"""
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