-
Notifications
You must be signed in to change notification settings - Fork 89
/
watermark.py
357 lines (294 loc) · 9.88 KB
/
watermark.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
# -*- coding: utf-8 -*-
"""
Function to print date/time stamps and
various system information.
Authors: Sebastian Raschka <sebastianraschka.com>, Tymoteusz Wołodźko
License: BSD 3 clause
"""
from __future__ import absolute_import
import datetime
import importlib
import os
import platform
import subprocess
import time
import types
from multiprocessing import cpu_count
from socket import gethostname
import platform
try:
from py3nvml import py3nvml
except ImportError:
py3nvml = None
try:
import importlib.metadata as importlib_metadata
except ImportError:
# Running on pre-3.8 Python; use importlib-metadata package
import importlib_metadata
import IPython
from .version import __version__
def watermark(
author=None,
email=None,
github_username=None,
website=None,
current_date=False,
datename=False,
current_time=False,
iso8601=False,
timezone=False,
updated=False,
custom_time=None,
python=False,
packages=None,
conda=False,
hostname=False,
machine=False,
githash=False,
gitrepo=False,
gitbranch=False,
watermark=False,
iversions=False,
gpu=False,
watermark_self=None,
globals_=None
):
'''Function to print date/time stamps and various system information.
Parameters:
===========
author :
prints author name
github_username :
prints author github username
email :
prints author email
website :
prints author or project website
current_date :
prints current date as YYYY-mm-dd
datename :
prints date with abbrv. day and month names
current_time :
prints current time as HH-MM-SS
iso8601 :
prints the combined date and time including the time zone
in the ISO 8601 standard with UTC offset
timezone :
appends the local time zone
updated :
appends a string "Last updated: "
custom_time :
prints a valid strftime() string
python :
prints Python and IPython version (if running from Jupyter)
packages :
prints versions of specified Python modules and packages
conda :
prints name of current conda environment
hostname :
prints the host name
machine :
prints system and machine info
githash :
prints current Git commit hash
gitrepo :
prints current Git remote address
gitbranch :
prints current Git branch
watermark :
prints the current version of watermark
iversions :
prints the name/version of all imported modules
gpu :
prints GPU information (currently limited to NVIDIA GPUs), if available
watermark_self :
instance of the watermark magics class, which is required
for iversions.
'''
output = []
args = locals()
watermark_self = args['watermark_self']
del args['watermark_self']
if not any(args.values()) or args['iso8601']:
iso_dt = _get_datetime()
if not any(args.values()):
args['updated'] = True
output.append({"Last updated": iso_dt})
output.append(_get_pyversions())
output.append(_get_sysinfo())
else:
if args['author']:
output.append({"Author": args['author'].strip("'\"")})
if args['github_username']:
output.append({"Github username": \
args['github_username'].strip("'\"")})
if args['email']:
output.append({"Email": args['email'].strip("'\"")})
if args['website']:
output.append({"Website": args['website'].strip("'\"")})
if args['updated']:
value = ""
if args['custom_time']:
value = time.strftime(args['custom_time'])
elif args['iso8601']:
value = iso_dt
else:
values = []
if args['current_date']:
values.append(time.strftime("%Y-%m-%d"))
elif args['datename']:
values.append(time.strftime("%a %b %d %Y"))
if args['current_time']:
time_str = time.strftime("%H:%M:%S")
if args['timezone']:
time_str += time.strftime("%Z")
values.append(time_str)
value = " ".join(values)
output.append({"Last updated": value})
if args['python']:
output.append(_get_pyversions())
if args['packages']:
output.append(_get_packages(args['packages']))
if args['conda']:
output.append(_get_conda_env())
if args['machine']:
output.append(_get_sysinfo())
if args['hostname']:
output.append({"Hostname": gethostname()})
if args['githash']:
output.append(_get_commit_hash(bool(args['machine'])))
if args['gitrepo']:
output.append(_get_git_remote_origin(bool(args['machine'])))
if args['gitbranch']:
output.append(_get_git_branch(bool(args['machine'])))
if args['iversions']:
if watermark_self:
ns = watermark_self.shell.user_ns
elif globals_:
ns = globals_
else:
raise RuntimeError(
"Either `watermark_self` or `globals_` must be provided "
"to show imported package versions."
)
output.append(_get_all_import_versions(ns))
if args['gpu']:
output.append(_get_gpu_info())
if args['watermark']:
output.append({"Watermark": __version__})
return _generate_formatted_text(output)
def _generate_formatted_text(list_of_dicts):
result = []
for section in list_of_dicts:
if section:
text = ""
longest = max(len(key) for key in section)
for key, value in section.items():
text += f"{key.ljust(longest)}: {value}\n"
result.append(text)
return "\n".join(result)
def _get_datetime(pattern="%Y-%m-%dT%H:%M:%S"):
try:
dt = datetime.datetime.now(tz=datetime.timezone.utc)
iso_dt = dt.astimezone().isoformat()
except AttributeError: # timezone only supported by Py >=3.2:
iso_dt = time.strftime(pattern)
return iso_dt
def _get_packages(pkgs):
packages = pkgs.split(",")
return {package: _get_package_version(package)
for package in packages}
def _get_package_version(pkg_name):
"""Return the version of a given package"""
if pkg_name == "scikit-learn":
pkg_name = "sklearn"
try:
imported = importlib.import_module(pkg_name)
except ImportError:
version = "not installed"
else:
try:
version = importlib_metadata.version(pkg_name)
except importlib_metadata.PackageNotFoundError:
try:
version = imported.__version__
except AttributeError:
try:
version = imported.version
except AttributeError:
try:
version = imported.version_info
except AttributeError:
version = "unknown"
return version
def _get_pyversions():
return {
"Python implementation": platform.python_implementation(),
"Python version": platform.python_version(),
"IPython version": IPython.__version__,
}
def _get_sysinfo():
return {
"Compiler": platform.python_compiler(),
"OS": platform.system(),
"Release": platform.release(),
"Machine": platform.machine(),
"Processor": platform.processor(),
"CPU cores": cpu_count(),
"Architecture": platform.architecture()[0],
}
def _get_commit_hash(machine):
process = subprocess.Popen(
["git", "rev-parse", "HEAD"], shell=False, stdout=subprocess.PIPE
)
git_head_hash = process.communicate()[0].strip()
return {"Git hash": git_head_hash.decode("utf-8")}
def _get_git_remote_origin(machine):
process = subprocess.Popen(
["git", "config", "--get", "remote.origin.url"],
shell=False,
stdout=subprocess.PIPE,
)
git_remote_origin = process.communicate()[0].strip()
return {"Git repo": git_remote_origin.decode("utf-8")}
def _get_git_branch(machine):
process = subprocess.Popen(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
shell=False,
stdout=subprocess.PIPE,
)
git_branch = process.communicate()[0].strip()
return {"Git branch": git_branch.decode("utf-8")}
def _get_all_import_versions(vars):
to_print = {}
imported_pkgs = {
val.__name__.split(".")[0]
for val in list(vars.values())
if isinstance(val, types.ModuleType)
}
imported_pkgs.discard("builtins")
for pkg_name in imported_pkgs:
pkg_version = _get_package_version(pkg_name)
if pkg_version not in ("not installed", "unknown"):
to_print[pkg_name] = pkg_version
return to_print
def _get_conda_env():
name = os.getenv('CONDA_DEFAULT_ENV', 'n/a')
return {"conda environment": name}
def _get_gpu_info():
try:
gpu_info = [""]
py3nvml.nvmlInit()
num_gpus = py3nvml.nvmlDeviceGetCount()
for i in range(num_gpus):
handle = py3nvml.nvmlDeviceGetHandleByIndex(i)
gpu_name = py3nvml.nvmlDeviceGetName(handle)
gpu_info.append(f"GPU {i}: {gpu_name}")
py3nvml.nvmlShutdown()
return {"GPU Info": "\n ".join(gpu_info)}
except py3nvml.NVMLError_LibraryNotFound:
return {"GPU Info": "NVIDIA drivers do not appear "
"to be installed on this machine."}
except:
return {"GPU Info": "GPU information is not "
"available for this machine."}