-
Notifications
You must be signed in to change notification settings - Fork 284
/
client.py
1404 lines (1154 loc) · 54.8 KB
/
client.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
# -*- coding: utf-8 -*-
from __future__ import print_function
import ast
import copy
import glob
import importlib
import os
import pathlib2
import pprint
import re
import shutil
import sys
import tarfile
import tempfile
import time
import warnings
import zipfile
import requests
from verta._tracking.organization import Organization
from ._internal_utils._utils import check_unnecessary_params_warning
from ._protos.public.common import CommonService_pb2 as _CommonCommonService
from ._protos.public.modeldb import CommonService_pb2 as _CommonService
from ._protos.public.modeldb import ProjectService_pb2 as _ProjectService
from ._protos.public.modeldb import ExperimentService_pb2 as _ExperimentService
from ._protos.public.modeldb import ExperimentRunService_pb2 as _ExperimentRunService
from .external import six
from .external.six.moves import cPickle as pickle # pylint: disable=import-error, no-name-in-module
from .external.six.moves.urllib.parse import urlparse # pylint: disable=import-error, no-name-in-module
from ._internal_utils import (
_artifact_utils,
_config_utils,
_git_utils,
_histogram_utils,
_pip_requirements_utils,
_request_utils,
_utils,
)
from . import _repository
from ._repository import commit as commit_module
from . import deployment
from . import utils
from ._tracking import entity
from ._tracking import (
_Context,
Project,
Projects,
Experiment,
Experiments,
ExperimentRun,
ExperimentRuns,
)
from ._registry import (
RegisteredModel,
RegisteredModels,
RegisteredModelVersion,
RegisteredModelVersions,
)
from ._dataset_versioning.dataset import Dataset
from ._dataset_versioning.datasets import Datasets
from ._dataset_versioning.dataset_version import DatasetVersion
from .endpoint._endpoint import Endpoint
from .endpoint._endpoints import Endpoints
from .endpoint.update import DirectUpdateStrategy
class Client(object):
"""
Object for interfacing with the ModelDB backend.
.. deprecated:: 0.12.0
The `port` parameter will removed in v0.17.0; please combine `port` with the first parameter,
e.g. `Client("localhost:8080")`.
.. deprecated:: 0.13.3
The `expt_runs` attribute will removed in v0.17.0; consider using `proj.expt_runs` and
`expt.expt_runs` instead.
This class provides functionality for starting/resuming Projects, Experiments, and Experiment Runs.
Parameters
----------
host : str, optional
Hostname of the Verta Web App.
email : str, optional
Authentication credentials for managed service. If this does not sound familiar, then there
is no need to set it.
dev_key : str, optional
Authentication credentials for managed service. If this does not sound familiar, then there
is no need to set it.
max_retries : int, default 5
Maximum number of times to retry a request on a connection failure. This only attempts retries
on HTTP codes {502, 503, 504} which commonly occur during back end connection lapses.
ignore_conn_err : bool, default False
Whether to ignore connection errors and instead return successes with empty contents.
use_git : bool, default True
Whether to use a local Git repository for certain operations such as Code Versioning.
debug : bool, default False
Whether to print extra verbose information to aid in debugging.
_connect : str, default True
Whether to connect to server (``False`` for unit tests).
Attributes
----------
max_retries : int
Maximum number of times to retry a request on a connection failure. Changes to this value
propagate to any objects that are/were created from this Client.
ignore_conn_err : bool
Whether to ignore connection errors and instead return successes with empty contents. Changes
to this value propagate to any objects that are/were created from this Client.
debug : bool
Whether to print extra verbose information to aid in debugging. Changes to this value propagate
to any objects that are/were created from this Client.
proj : :class:`~verta._tracking.project.Project` or None
Currently active Project.
expt : :class:`~verta._tracking.experiment.Experiment` or None
Currently active Experiment.
"""
def __init__(self, host=None, port=None, email=None, dev_key=None,
max_retries=5, ignore_conn_err=False, use_git=True, debug=False, _connect=True):
self._load_config()
if host is None and 'VERTA_HOST' in os.environ:
host = os.environ['VERTA_HOST']
print("set host from environment")
host = self._set_from_config_if_none(host, "host")
if email is None and 'VERTA_EMAIL' in os.environ:
email = os.environ['VERTA_EMAIL']
print("set email from environment")
email = self._set_from_config_if_none(email, "email")
if dev_key is None and 'VERTA_DEV_KEY' in os.environ:
dev_key = os.environ['VERTA_DEV_KEY']
print("set developer key from environment")
dev_key = self._set_from_config_if_none(dev_key, "dev_key")
if host is None:
raise ValueError("`host` must be provided")
auth = {_utils._GRPC_PREFIX+'source': "PythonClient"}
if email is None and dev_key is None:
if debug:
print("[DEBUG] email and developer key not found; auth disabled")
elif email is not None and dev_key is not None:
if debug:
print("[DEBUG] using email: {}".format(email))
print("[DEBUG] using developer key: {}".format(dev_key[:8] + re.sub(r"[^-]", '*', dev_key[8:])))
auth.update({
_utils._GRPC_PREFIX+'email': email,
_utils._GRPC_PREFIX+'developer_key': dev_key,
# without underscore, for NGINX support
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls#missing-disappearing-http-headers
_utils._GRPC_PREFIX+'developer-key': dev_key,
})
# save credentials to env for other Verta Client features
os.environ['VERTA_EMAIL'] = email
os.environ['VERTA_DEV_KEY'] = dev_key
else:
raise ValueError("`email` and `dev_key` must be provided together")
back_end_url = urlparse(host)
socket = back_end_url.netloc + back_end_url.path.rstrip('/')
if port is not None:
warnings.warn("`port` (the second parameter) will removed in a later version;"
" please combine it with the first parameter, e.g. \"localhost:8080\"",
category=FutureWarning)
socket = "{}:{}".format(socket, port)
scheme = back_end_url.scheme or ("https" if ".verta.ai" in socket else "http")
auth[_utils._GRPC_PREFIX+'scheme'] = scheme
# verify connection
conn = _utils.Connection(scheme, socket, auth, max_retries, ignore_conn_err)
if _connect:
try:
response = _utils.make_request("GET",
"{}://{}/api/v1/modeldb/project/verifyConnection".format(conn.scheme, conn.socket),
conn)
except requests.ConnectionError as err:
err.args = ("connection failed; please check `host` and `port`; error message: \n\n{}".format(err.args[0]),) + err.args[1:]
six.raise_from(err, None)
def is_unauthorized(response): return response.status_code == 401
if is_unauthorized(response):
# response.reason was "Unauthorized"
try:
response.raise_for_status()
except requests.HTTPError as e:
e.args = ("authentication failed; please check `VERTA_EMAIL` and `VERTA_DEV_KEY`\n\n{}".format(
e.args[0]),) + e.args[1:]
raise e
_utils.raise_for_http_error(response)
print("connection successfully established")
self._conn = conn
self._conf = _utils.Configuration(use_git, debug)
self._ctx = _Context(self._conn, self._conf)
@property
def proj(self):
return self._ctx.proj
@property
def expt(self):
return self._ctx.expt
@property
def max_retries(self):
return self._conn.retry.total
@max_retries.setter
def max_retries(self, value):
self._conn.retry.total = value
@property
def ignore_conn_err(self):
return self._conn.ignore_conn_err
@ignore_conn_err.setter
def ignore_conn_err(self, value):
self._conn.ignore_conn_err = value
@property
def use_git(self):
return self._conf.use_git
@use_git.setter
def use_git(self, _):
"""This would mess with state in safe but unexpected ways."""
raise AttributeError("cannot set `use_git` after Client has been initialized")
@property
def debug(self):
return self._conf.debug
@debug.setter
def debug(self, value):
self._conf.debug = value
@property
def projects(self):
return Projects(self._conn, self._conf)
@property
def experiments(self):
return Experiments(self._conn, self._conf)
@property
def expt_runs(self):
return ExperimentRuns(self._conn, self._conf)
def _get_personal_workspace(self):
email = self._conn.auth.get('Grpc-Metadata-email')
if email is not None:
response = _utils.make_request(
"GET",
"{}://{}/api/v1/uac-proxy/uac/getUser".format(self._conn.scheme, self._conn.socket),
self._conn, params={'email': email},
)
if response.ok:
try:
response_json = _utils.body_to_json(response)
except ValueError: # not JSON response
pass
else:
return response_json['verta_info']['username']
else:
if response.status_code == 404: # UAC not found
pass
else:
_utils.raise_for_http_error(response)
return entity._OSS_DEFAULT_WORKSPACE
def _load_config(self):
with _config_utils.read_merged_config() as config:
self._config = config
def _set_from_config_if_none(self, var, resource_name):
if var is None:
var = self._config.get(resource_name)
if var:
print("setting {} from config file".format(resource_name))
return var or None
def get_project(self, name=None, workspace=None, id=None):
"""
Retrieves an already created Project. Only one of `name` or `id` can be provided.
Parameters
----------
name : str, optional
Name of the Project.
workspace : str, optional
Workspace under which the Project with name `name` exists. If not provided, the current
user's personal workspace will be used.
id : str, optional
ID of the Project. This parameter cannot be provided alongside `name`.
Returns
-------
:class:`~verta._tracking.project.Project`
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
name = self._set_from_config_if_none(name, "project")
if name is None and id is None:
raise ValueError("must specify either `name` or `id`")
workspace = self._set_from_config_if_none(workspace, "workspace")
self._ctx = _Context(self._conn, self._conf)
self._ctx.workspace_name = workspace
if id is not None:
self._ctx.proj = Project._get_by_id(self._conn, self._conf, id)
self._ctx.populate()
else:
self._ctx.proj = Project._get_by_name(self._conn, self._conf, name, self._ctx.workspace_name)
if self._ctx.proj is None:
raise ValueError("Project not found")
return self._ctx.proj
def set_project(self, name=None, desc=None, tags=None, attrs=None, workspace=None, public_within_org=None, id=None):
"""
Attaches a Project to this Client.
If an accessible Project with name `name` does not already exist, it will be created
and initialized with specified metadata parameters. If such a Project does already exist,
it will be retrieved; specifying metadata parameters in this case will raise a warning.
If an Experiment is already attached to this Client, it will be detached.
Parameters
----------
name : str, optional
Name of the Project. If no name is provided, one will be generated.
desc : str, optional
Description of the Project.
tags : list of str, optional
Tags of the Project.
attrs : dict of str to {None, bool, float, int, str}, optional
Attributes of the Project.
workspace : str, optional
Workspace under which the Project with name `name` exists. If not provided, the current
user's personal workspace will be used.
public_within_org : bool, default False
If creating a Project in an organization's workspace, whether to make this Project
accessible to all members of that organization.
id : str, optional
ID of the Project. This parameter cannot be provided alongside `name`, and other
parameters will be ignored.
Returns
-------
:class:`~verta._tracking.project.Project`
Raises
------
ValueError
If a Project with `name` already exists, but metadata parameters are passed in.
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
name = self._set_from_config_if_none(name, "project")
workspace = self._set_from_config_if_none(workspace, "workspace")
self._ctx = _Context(self._conn, self._conf)
self._ctx.workspace_name = workspace
resource_name = "Project"
param_names = "`desc`, `tags`, `attrs`, or `public_within_org`"
params = (desc, tags, attrs, public_within_org)
if id is not None:
self._ctx.proj = Project._get_by_id(self._conn, self._conf, id)
check_unnecessary_params_warning(resource_name, "id {}".format(id),
param_names, params)
self._ctx.populate()
else:
self._ctx.proj = Project._get_or_create_by_name(self._conn, name,
lambda name: Project._get_by_name(self._conn, self._conf, name, self._ctx.workspace_name),
lambda name: Project._create(self._conn, self._conf, self._ctx, name=name, desc=desc, tags=tags, attrs=attrs, public_within_org=public_within_org),
lambda: check_unnecessary_params_warning(
resource_name, "name {}".format(name),
param_names, params))
return self._ctx.proj
def get_experiment(self, name=None, id=None):
"""
Retrieves an already created Experiment. Only one of `name` or `id` can be provided.
Parameters
----------
name : str, optional
Name of the Experiment.
id : str, optional
ID of the Experiment. This parameter cannot be provided alongside `name`.
Returns
-------
:class:`~verta._tracking.experiment.Experiment`
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
name = self._set_from_config_if_none(name, "experiment")
if name is None and id is None:
raise ValueError("must specify either `name` or `id`")
if id is not None:
self._ctx.expt = Experiment._get_by_id(self._conn, self._conf, id)
self._ctx.populate()
else:
if self._ctx.proj is None:
self.set_project()
self._ctx.expt = Experiment._get_by_name(self._conn, self._conf, name, self._ctx.proj.id)
if self._ctx.expt is None:
raise ValueError("Experment not found")
return self._ctx.expt
def set_experiment(self, name=None, desc=None, tags=None, attrs=None, id=None):
"""
Attaches an Experiment under the currently active Project to this Client.
If an accessible Experiment with name `name` does not already exist under the currently
active Project, it will be created and initialized with specified metadata parameters. If
such an Experiment does already exist, it will be retrieved; specifying metadata parameters
in this case will raise a warning.
Parameters
----------
name : str, optional
Name of the Experiment. If no name is provided, one will be generated.
desc : str, optional
Description of the Experiment.
tags : list of str, optional
Tags of the Experiment.
attrs : dict of str to {None, bool, float, int, str}, optional
Attributes of the Experiment.
id : str, optional
ID of the Experiment. This parameter cannot be provided alongside `name`, and other
parameters will be ignored.
Returns
-------
:class:`~verta._tracking.experiment.Experiment`
Raises
------
ValueError
If an Experiment with `name` already exists, but metadata parameters are passed in.
AttributeError
If a Project is not yet in progress.
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
name = self._set_from_config_if_none(name, "experiment")
resource_name = "Experiment"
param_names = "`desc`, `tags`, or `attrs`"
params = (desc, tags, attrs)
if id is not None:
self._ctx.expt = Experiment._get_by_id(self._conn, self._conf, id)
check_unnecessary_params_warning(resource_name, "id {}".format(id),
param_names, params)
self._ctx.populate()
else:
if self._ctx.proj is None:
self.set_project()
self._ctx.expt = Experiment._get_or_create_by_name(self._conn, name,
lambda name: Experiment._get_by_name(self._conn, self._conf, name, self._ctx.proj.id),
lambda name: Experiment._create(self._conn, self._conf, self._ctx, name=name, desc=desc, tags=tags, attrs=attrs),
lambda: check_unnecessary_params_warning(
resource_name,
"name {}".format(name),
param_names, params))
return self._ctx.expt
def get_experiment_run(self, name=None, id=None):
"""
Retrieves an already created Experiment Run. Only one of `name` or `id` can be provided.
Parameters
----------
name : str, optional
Name of the Experiment Run.
id : str, optional
ID of the Experiment Run. This parameter cannot be provided alongside `name`.
Returns
-------
:class:`~verta._tracking.experimentrun.ExperimentRun`
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
if name is None and id is None:
raise ValueError("must specify either `name` or `id`")
if id is not None:
self._ctx.expt_run = ExperimentRun._get_by_id(self._conn, self._conf, id)
self._ctx.populate()
else:
if self._ctx.expt is None:
self.set_experiment()
self._ctx.expt_run = ExperimentRun._get_by_name(self._conn, self._conf, name, self._ctx.expt.id)
if self._ctx.expt_run is None:
raise ValueError("ExperimentRun not Found")
return self._ctx.expt_run
def set_experiment_run(self, name=None, desc=None, tags=None, attrs=None, id=None, date_created=None):
"""
Attaches an Experiment Run under the currently active Experiment to this Client.
If an accessible Experiment Run with name `name` does not already exist under the
currently active Experiment, it will be created and initialized with specified metadata
parameters. If such a Experiment Run does already exist, it will be retrieved; specifying
metadata parameters in this case will raise a warning.
Parameters
----------
name : str, optional
Name of the Experiment Run. If no name is provided, one will be generated.
desc : str, optional
Description of the Experiment Run.
tags : list of str, optional
Tags of the Experiment Run.
attrs : dict of str to {None, bool, float, int, str}, optional
Attributes of the Experiment Run.
id : str, optional
ID of the Experiment Run. This parameter cannot be provided alongside `name`, and other
parameters will be ignored.
Returns
-------
:class:`~verta._tracking.experimentrun.ExperimentRun`
Raises
------
ValueError
If an Experiment Run with `name` already exists, but metadata parameters are passed in.
AttributeError
If an Experiment is not yet in progress.
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
resource_name = "Experiment Run"
param_names = "`desc`, `tags`, `attrs`, or `date_created`"
params = (desc, tags, attrs, date_created)
if id is not None:
self._ctx.expt_run = ExperimentRun._get_by_id(self._conn, self._conf, id)
check_unnecessary_params_warning(resource_name, "id {}".format(id),
param_names, params)
self._ctx.populate()
else:
if self._ctx.expt is None:
self.set_experiment()
self._ctx.expt_run = ExperimentRun._get_or_create_by_name(self._conn, name,
lambda name: ExperimentRun._get_by_name(self._conn, self._conf, name, self._ctx.expt.id),
lambda name: ExperimentRun._create(self._conn, self._conf, self._ctx, name=name, desc=desc, tags=tags, attrs=attrs, date_created=date_created),
lambda: check_unnecessary_params_warning(
resource_name,
"name {}".format(name),
param_names, params))
return self._ctx.expt_run
def get_or_create_repository(self, name=None, workspace=None, id=None, public_within_org=None):
"""
Gets or creates a Repository by `name` and `workspace`, or gets a Repository by `id`.
Parameters
----------
name : str
Name of the Repository. This parameter cannot be provided alongside `id`.
workspace : str, optional
Workspace under which the Repository with name `name` exists. If not provided, the
current user's personal workspace will be used.
id : str, optional
ID of the Repository, to be provided instead of `name`.
public_within_org : bool, default False
If creating a Repository in an organization's workspace, whether to make this Repository
accessible to all members of that organization.
Returns
-------
:class:`~verta._repository.Repository`
Specified Repository.
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
elif id is not None:
repo = _repository.Repository._get(self._conn, id_=id)
if repo is None:
raise ValueError("no Repository found with ID {}".format(id))
print("set existing Repository: {}".format(repo.name))
return repo
elif name is not None:
if workspace is None:
workspace_str = "personal workspace"
workspace = self._get_personal_workspace()
else:
workspace_str = "workspace {}".format(workspace)
repo = _repository.Repository._get(self._conn, name=name, workspace=workspace)
if not repo: # not found
try:
repo = _repository.Repository._create(self._conn, name=name, workspace=workspace,
public_within_org=public_within_org)
except requests.HTTPError as e:
if e.response.status_code == 409: # already exists
raise RuntimeError("unable to get Repository from ModelDB;"
" please notify the Verta development team")
else:
six.raise_from(e, None)
print("created new Repository: {} in {}".format(name, workspace_str))
else:
print("set existing Repository: {} from {}".format(name, workspace_str))
return repo
else:
raise ValueError("must specify either `name` or `id`")
# set aliases for get-or-create functions for API compatibility
def get_or_create_project(self, *args, **kwargs):
"""
Alias for :meth:`Client.set_project()`.
"""
return self.set_project(*args, **kwargs)
def get_or_create_experiment(self, *args, **kwargs):
"""
Alias for :meth:`Client.set_experiment()`.
"""
return self.set_experiment(*args, **kwargs)
def get_or_create_experiment_run(self, *args, **kwargs):
"""
Alias for :meth:`Client.set_experiment_run()`.
"""
return self.set_experiment_run(*args, **kwargs)
def set_repository(self, *args, **kwargs):
"""
Alias for :meth:`Client.get_or_create_repository()`.
"""
return self.get_or_create_repository(*args, **kwargs)
# set aliases for get-or-create functions for API compatibility
def get_or_create_registered_model(self, name=None, desc=None, labels=None, workspace=None, public_within_org=None, id=None):
"""
Attaches a registered_model to this Client.
If an accessible registered_model with name `name` does not already exist, it will be created
and initialized with specified metadata parameters. If such a registered_model does already exist,
it will be retrieved; specifying metadata parameters in this case will raise a warning.
Parameters
----------
name : str, optional
Name of the registered_model. If no name is provided, one will be generated.
desc : str, optional
Description of the registered_model.
labels: list of str, optional
Labels of the registered_model.
workspace : str, optional
Workspace under which the registered_model with name `name` exists. If not provided, the current
user's personal workspace will be used.
public_within_org : bool, default False
If creating a registered_model in an organization's workspace, whether to make this registered_model
accessible to all members of that organization.
id : str, optional
ID of the registered_model. This parameter cannot be provided alongside `name`, and other
parameters will be ignored.
Returns
-------
:class:`~verta._registry.model.RegisteredModel`
Raises
------
ValueError
If a registered_model with `name` already exists, but metadata parameters are passed in.
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
name = self._set_from_config_if_none(name, "registered_model")
workspace = self._set_from_config_if_none(workspace, "workspace")
if workspace is None:
workspace = self._get_personal_workspace()
ctx = _Context(self._conn, self._conf)
ctx.workspace_name = workspace
resource_name = "Registered Model"
param_names = "`desc`, `labels`, or `public_within_org`"
params = (desc, labels, public_within_org)
if id is not None:
registered_model = RegisteredModel._get_by_id(self._conn, self._conf, id)
check_unnecessary_params_warning(resource_name, "id {}".format(id),
param_names, params)
else:
registered_model = RegisteredModel._get_or_create_by_name(self._conn, name,
lambda name: RegisteredModel._get_by_name(self._conn, self._conf, name, ctx.workspace_name),
lambda name: RegisteredModel._create(self._conn, self._conf, ctx, name=name, desc=desc, tags=labels, public_within_org=public_within_org),
lambda: check_unnecessary_params_warning(
resource_name,
"name {}".format(name),
param_names, params))
return registered_model
def get_registered_model(self, name=None, workspace=None, id=None):
"""
Retrieve an already created Registered Model. Only one of name or id can be provided.
Parameters
----------
name : str, optional
Name of the Registered Model.
id : str, optional
ID of the Registered Model. This parameter cannot be provided alongside `name`.
Returns
-------
:class:`~verta._registry.model.RegisteredModel`
"""
if name is not None and id is not None:
raise ValueError("cannot specify both `name` and `id`")
name = self._set_from_config_if_none(name, "registered_model")
if name is None and id is None:
raise ValueError("must specify either `name` or `id`")
workspace = self._set_from_config_if_none(workspace, "workspace")
if workspace is None:
workspace = self._get_personal_workspace()
if id is not None:
registered_model = RegisteredModel._get_by_id(self._conn, self._conf, id)
else:
registered_model = RegisteredModel._get_by_name(self._conn, self._conf, name, workspace)
if registered_model is None:
raise ValueError("Registered model not found")
return registered_model
def set_registered_model(self, *args, **kwargs):
"""
Alias for :meth:`Client.get_or_create_registered_model()`.
"""
return self.get_or_create_registered_model(*args, **kwargs)
def get_registered_model_version(self, id):
"""
Retrieve an already created Model Version.
Parameters
----------
id : str
ID of the Model Version.
Returns
-------
:class:`~verta._registry.modelversion.RegisteredModelVersion`
"""
return RegisteredModelVersion._get_by_id(self._conn, self._conf, id)
@property
def registered_models(self):
return RegisteredModels(self._conn, self._conf)
@property
def registered_model_versions(self):
return RegisteredModelVersions(self._conn, self._conf)
def get_or_create_endpoint(self, path=None, description=None, workspace=None, public_within_org=False, id=None):
"""
Attaches an endpoint to this Client.
If an accessible endpoint with name `path` does not already exist, it will be created
and initialized with specified metadata parameters. If such an endpoint does already exist,
it will be retrieved; specifying metadata parameters in this case will raise a warning.
Parameters
----------
path : str, optional
Path for the endpoint.
description : str, optional
Description of the endpoint.
workspace : str, optional
Workspace under which the endpoint with name `name` exists. If not provided, the current
user's personal workspace will be used.
public_within_org : bool, default False
If creating an endpoint in an organization's workspace, whether to make this endpoint
accessible to all members of that organization.
id : str, optional
ID of the endpoint. This parameter cannot be provided alongside `name`, and other
parameters will be ignored.
Returns
-------
:class:`~verta.endpoint._endpoint.Endpoint`
Raises
------
ValueError
If an endpoint with `path` already exists, but metadata parameters are passed in.
"""
if path is not None and id is not None:
raise ValueError("cannot specify both `path` and `id`")
if path is None and id is None:
raise ValueError("must specify either `path` or `id`")
workspace = self._set_from_config_if_none(workspace, "workspace")
if workspace is None:
workspace = self._get_personal_workspace()
resource_name = "Endpoint"
param_names = "`description`"
params = [description]
if id is not None:
check_unnecessary_params_warning(resource_name, "id {}".format(id),
param_names, params)
return Endpoint._get_by_id(self._conn, self._conf, workspace, id)
else:
return Endpoint._get_or_create_by_name(self._conn, path,
lambda path: Endpoint._get_by_path(self._conn, self._conf, workspace, path),
lambda path: Endpoint._create(self._conn, self._conf, workspace, public_within_org, path, description),
lambda: check_unnecessary_params_warning(
resource_name,
"path {}".format(path),
param_names, params))
def get_endpoint(self, path=None, workspace=None, id=None):
"""
Retrieves an already created Endpoint. Only one of `path` or `id` can be provided.
Parameters
----------
path : str, optional
Path of the Endpoint.
workspace : str, optional
Name of the workspace of the Endpoint.
id : str, optional
ID of the Endpoint. This parameter cannot be provided alongside `path`.
Returns
-------
:class:`~verta.endpoint._endpoint.Endpoint`
"""
if path is not None and id is not None:
raise ValueError("cannot specify both `path` and `id`")
if path is None and id is None:
raise ValueError("must specify either `path` or `id`")
workspace = self._set_from_config_if_none(workspace, "workspace")
if workspace is None:
workspace = self._get_personal_workspace()
if id is not None:
endpoint = Endpoint._get_by_id(self._conn, self._conf, workspace, id)
else:
endpoint = Endpoint._get_by_path(self._conn, self._conf, workspace, path)
if endpoint is None:
raise ValueError("Endpoint not found")
return endpoint
def set_endpoint(self, *args, **kwargs):
"""
Alias for :meth:`Client.get_or_create_endpoint()`.
"""
return self.get_or_create_endpoint(*args, **kwargs)
def create_project(self, name=None, desc=None, tags=None, attrs=None, workspace=None, public_within_org=None):
"""
Creates a new Project.
A Project with name `name` will be created and initialized with specified metadata parameters.
If an Experiment is already attached to this Client, it will be detached.
Parameters
----------
name : str, optional
Name of the Project. If no name is provided, one will be generated.
desc : str, optional
Description of the Project.
tags : list of str, optional
Tags of the Project.
attrs : dict of str to {None, bool, float, int, str}, optional
Attributes of the Project.
workspace : str, optional
Workspace under which the Project with name `name` exists. If not provided, the current
user's personal workspace will be used.
public_within_org : bool, default False
If creating a Project in an organization's workspace, whether to make this Project
accessible to all members of that organization.
Returns
-------
:class:`~verta._tracking.project.Project`
Raises
------
ValueError
If a Project with `name` already exists.
"""
name = self._set_from_config_if_none(name, "project")
workspace = self._set_from_config_if_none(workspace, "workspace")
self._ctx = _Context(self._conn, self._conf)
self._ctx.workspace_name = workspace
self._ctx.proj = Project._create(self._conn, self._conf, self._ctx, name=name, desc=desc, tags=tags, attrs=attrs,
public_within_org=public_within_org)
return self._ctx.proj
def create_experiment(self, name=None, desc=None, tags=None, attrs=None):
"""
Creates a new Experiment under the currently active Project.
Experiment with name `name` will be created and initialized with specified metadata parameters.
Parameters
----------
name : str, optional
Name of the Experiment. If no name is provided, one will be generated.
desc : str, optional
Description of the Experiment.
tags : list of str, optional
Tags of the Experiment.
attrs : dict of str to {None, bool, float, int, str}, optional
Attributes of the Experiment.
Returns
-------
:class:`~verta._tracking.experiment.Experiment`
Raises
------
ValueError
If an Experiment with `name` already exists.
AttributeError
If a Project is not yet in progress.
"""
name = self._set_from_config_if_none(name, "experiment")
if self._ctx.proj is None:
self.set_project()
self._ctx.expt = Experiment._create(self._conn, self._conf, self._ctx, name=name, desc=desc, tags=tags, attrs=attrs)
return self._ctx.expt
def create_experiment_run(self, name=None, desc=None, tags=None, attrs=None, date_created=None):