-
Notifications
You must be signed in to change notification settings - Fork 61
/
__init__.py
406 lines (294 loc) 路 12.6 KB
/
__init__.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
#
# Copyright (c) 2019, Neptune Labs Sp. z o.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import os
import threading
from neptune import constants, envs
from neptune._version import get_versions
from neptune.exceptions import (
InvalidNeptuneBackend,
NeptuneIncorrectImportException,
NeptuneUninitializedException,
)
from neptune.internal.api_clients import backend_factory
from neptune.internal.api_clients.offline_backend import OfflineBackend
from neptune.internal.backends.hosted_neptune_backend import HostedNeptuneBackend
from neptune.projects import Project
from neptune.sessions import Session
from neptune.utils import assure_project_qualified_name
__version__ = get_versions()["version"]
del get_versions
session = None
project = None
__lock = threading.RLock()
_logger = logging.getLogger(__name__)
"""Access Neptune as an anonymous user.
You can pass this value as api_token during init() call, either by an environment variable or passing it directly
"""
ANONYMOUS = constants.ANONYMOUS
"""Anonymous user API token.
You can pass this value as api_token during init() call, either by an environment variable or passing it directly
"""
ANONYMOUS_API_TOKEN = constants.ANONYMOUS_API_TOKEN
CURRENT_KWARGS = (
"project",
"run",
"custom_run_id",
"mode",
"name",
"description",
"tags",
"source_files",
"capture_stdout",
"capture_stderr",
"capture_hardware_metrics",
"fail_on_exception",
"monitoring_namespace",
"flush_period",
)
def _check_for_extra_kwargs(caller_name, kwargs: dict):
for name in CURRENT_KWARGS:
if name in kwargs:
raise NeptuneIncorrectImportException()
if kwargs:
first_key = next(iter(kwargs.keys()))
raise TypeError(f"{caller_name}() got an unexpected keyword argument '{first_key}'")
def init(project_qualified_name=None, api_token=None, proxies=None, backend=None, **kwargs):
"""Initialize `Neptune client library <https://github.com/neptune-ai/neptune-client>`_ to work with
specific project.
Authorize user, sets value of global variable ``project`` to :class:`~neptune.projects.Project` object
that can be used to create or list experiments, notebooks, etc.
Args:
project_qualified_name (:obj:`str`, optional, default is ``None``):
Qualified name of a project in a form of ``namespace/project_name``.
If ``None``, the value of ``NEPTUNE_PROJECT`` environment variable will be taken.
api_token (:obj:`str`, optional, default is ``None``):
User's API token. If ``None``, the value of ``NEPTUNE_API_TOKEN`` environment variable will be taken.
.. note::
It is strongly recommended to use ``NEPTUNE_API_TOKEN`` environment variable rather than
placing your API token in plain text in your source code.
proxies (:obj:`dict`, optional, default is ``None``):
Argument passed to HTTP calls made via the `Requests <https://2.python-requests.org/en/master/>`_ library.
For more information see their proxies
`section <https://2.python-requests.org/en/master/user/advanced/#proxies>`_.
.. note::
Only `http` and `https` keys are supported by all features.
.. deprecated :: 0.4.4
Instead, use:
.. code :: python3
from neptune import HostedNeptuneBackendApiClient
neptune.init(backend=HostedNeptuneBackendApiClient(proxies=...))
backend (:class:`~neptune.ApiClient`, optional, default is ``None``):
By default, Neptune client library sends logs, metrics, images, etc to Neptune servers:
either publicly available SaaS, or an on-premises installation.
You can also pass the default backend instance explicitly to specify its parameters:
.. code :: python3
from neptune import HostedNeptuneBackendApiClient
neptune.init(backend=HostedNeptuneBackendApiClient(...))
Passing an instance of :class:`~neptune.OfflineApiClient` makes your code run without communicating
with Neptune servers.
.. code :: python3
from neptune import OfflineApiClient
neptune.init(backend=OfflineApiClient())
.. note::
Instead of passing a ``neptune.OfflineApiClient`` instance as ``backend``, you can set an
environment variable ``NEPTUNE_BACKEND=offline`` to override the default behaviour.
Returns:
:class:`~neptune.projects.Project` object that is used to create or list experiments, notebooks, etc.
Raises:
`NeptuneMissingApiTokenException`: When ``api_token`` is None
and ``NEPTUNE_API_TOKEN`` environment variable was not set.
`NeptuneMissingProjectQualifiedNameException`: When ``project_qualified_name`` is None
and ``NEPTUNE_PROJECT`` environment variable was not set.
`InvalidApiKey`: When given ``api_token`` is malformed.
`Unauthorized`: When given ``api_token`` is invalid.
Examples:
.. code:: python3
# minimal invoke
neptune.init()
# specifying project name
neptune.init('jack/sandbox')
# running offline
neptune.init(backend=neptune.OfflineApiClient())
"""
_check_for_extra_kwargs(init.__name__, kwargs)
project_qualified_name = assure_project_qualified_name(project_qualified_name)
# pylint: disable=global-statement
with __lock:
global session, project
if backend is None:
backend_name = os.getenv(envs.BACKEND)
backend = backend_factory(
backend_name=backend_name,
api_token=api_token,
proxies=proxies,
)
session = Session(backend=backend)
project = session.get_project(project_qualified_name)
return project
def set_project(project_qualified_name):
"""Setups `Neptune client library <https://github.com/neptune-ai/neptune-client>`_ to work with specific project.
| Sets value of global variable ``project`` to :class:`~neptune.projects.Project` object
that can be used to create or list experiments, notebooks, etc.
| If Neptune client library was not previously initialized via :meth:`~neptune.init` call
it will be initialized with API token taken from ``NEPTUNE_API_TOKEN`` environment variable.
Args:
project_qualified_name (:obj:`str`):
Qualified name of a project in a form of ``namespace/project_name``.
Returns:
:class:`~neptune.projects.Project` object that is used to create or list experiments, notebooks, etc.
Raises:
`NeptuneMissingApiTokenException`: When library was not initialized previously by ``init`` call and
``NEPTUNE_API_TOKEN`` environment variable is not set.
Examples:
.. code:: python3
# minimal invoke
neptune.set_project('jack/sandbox')
"""
# pylint: disable=global-statement
with __lock:
global session, project
if session is None:
init(project_qualified_name=project_qualified_name)
else:
project = session.get_project(project_qualified_name)
return project
def create_experiment(
name=None,
description=None,
params=None,
properties=None,
tags=None,
upload_source_files=None,
abort_callback=None,
logger=None,
upload_stdout=True,
upload_stderr=True,
send_hardware_metrics=True,
run_monitoring_thread=True,
handle_uncaught_exceptions=True,
git_info=None,
hostname=None,
notebook_id=None,
):
"""Create and start Neptune experiment.
Alias for: :meth:`~neptune.projects.Project.create_experiment`
"""
# pylint: disable=global-statement
global project
if project is None:
raise NeptuneUninitializedException()
return project.create_experiment(
name=name,
description=description,
params=params,
properties=properties,
tags=tags,
upload_source_files=upload_source_files,
abort_callback=abort_callback,
logger=logger,
upload_stdout=upload_stdout,
upload_stderr=upload_stderr,
send_hardware_metrics=send_hardware_metrics,
run_monitoring_thread=run_monitoring_thread,
handle_uncaught_exceptions=handle_uncaught_exceptions,
git_info=git_info,
hostname=hostname,
notebook_id=notebook_id,
)
def get_experiment():
# pylint: disable=global-statement
global project
if project is None:
raise NeptuneUninitializedException()
# pylint: disable=protected-access
return project._get_current_experiment()
def append_tag(tag, *tags):
"""Append tag(s) to the experiment on the top of experiments view.
Alias for: :meth:`~neptune.experiments.Experiment.append_tag`
"""
get_experiment().append_tag(tag, *tags)
def append_tags(tag, *tags):
"""Append tag(s) to the experiment on the top of experiments view.
Alias for: :meth:`~neptune.experiments.Experiment.append_tags`
"""
get_experiment().append_tag(tag, *tags)
def remove_tag(tag):
"""Removes single tag from experiment.
Alias for: :meth:`~neptune.experiments.Experiment.remove_tag`
"""
get_experiment().remove_tag(tag)
def set_property(key, value):
"""Set `key-value` pair as an experiment property.
If property with given ``key`` does not exist, it adds a new one.
Alias for: :meth:`~neptune.experiments.Experiment.set_property`
"""
get_experiment().set_property(key, value)
def remove_property(key):
"""Removes a property with given key.
Alias for: :meth:`~neptune.experiments.Experiment.remove_property`
"""
get_experiment().remove_property(key)
def send_metric(channel_name, x, y=None, timestamp=None):
"""Log metrics (numeric values) in Neptune.
Alias for :meth:`~neptune.experiments.Experiment.log_metric`
"""
return get_experiment().send_metric(channel_name, x, y, timestamp)
def log_metric(log_name, x, y=None, timestamp=None):
"""Log metrics (numeric values) in Neptune.
Alias for :meth:`~neptune.experiments.Experiment.log_metric`
"""
return get_experiment().log_metric(log_name, x, y, timestamp)
def send_text(channel_name, x, y=None, timestamp=None):
"""Log text data in Neptune.
Alias for :meth:`~neptune.experiments.Experiment.log_text`
"""
return get_experiment().send_text(channel_name, x, y, timestamp)
def log_text(log_name, x, y=None, timestamp=None):
"""Log text data in Neptune.
Alias for :meth:`~neptune.experiments.Experiment.log_text`
"""
return get_experiment().send_text(log_name, x, y, timestamp)
def send_image(channel_name, x, y=None, name=None, description=None, timestamp=None):
"""Log image data in Neptune.
Alias for :meth:`~neptune.experiments.Experiment.log_image`
"""
return get_experiment().send_image(channel_name, x, y, name, description, timestamp)
def log_image(log_name, x, y=None, image_name=None, description=None, timestamp=None):
"""Log image data in Neptune.
Alias for :meth:`~neptune.experiments.Experiment.log_image`
"""
return get_experiment().send_image(log_name, x, y, image_name, description, timestamp)
def send_artifact(artifact, destination=None):
"""Save an artifact (file) in experiment storage.
Alias for :meth:`~neptune.experiments.Experiment.log_artifact`
"""
return get_experiment().log_artifact(artifact, destination)
def delete_artifacts(path):
"""Delete an artifact (file/directory) from experiment storage.
Alias for :meth:`~neptune.experiments.Experiment.delete_artifacts`
"""
return get_experiment().delete_artifacts(path)
def log_artifact(artifact, destination=None):
"""Save an artifact (file) in experiment storage.
Alias for :meth:`~neptune.experiments.Experiment.log_artifact`
"""
return get_experiment().log_artifact(artifact, destination)
def stop(traceback=None):
"""Marks experiment as finished (succeeded or failed).
Alias for :meth:`~neptune.experiments.Experiment.stop`
"""
get_experiment().stop(traceback)