-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy path__init__.py
More file actions
4401 lines (3834 loc) · 158 KB
/
Copy path__init__.py
File metadata and controls
4401 lines (3834 loc) · 158 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2017-present, The Visdom Authors
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from visdom.utils.shared_utils import get_new_window_id, _coerce_image_slider_index
from visdom import server
import os
import os.path
import requests
import ssl
import traceback
import threading
import websocket # type: ignore
import json
import hashlib
import math
import re
import base64
import binascii
import numpy as np # type: ignore
from PIL import Image # type: ignore
import base64 as b64 # type: ignore
import numbers
from urllib.parse import urlparse, urlunparse
import logging
import warnings
import time
import errno
from io import BytesIO, StringIO
from functools import wraps
import html
try:
import bs4 # type: ignore
BS4_AVAILABLE = True
except ImportError:
BS4_AVAILABLE = False
import sys
if sys.version_info < (3, 12):
raise RuntimeError("Visdom requires Python 3.12 or newer.")
def _normalize_tsne(Y):
Y = np.asarray(Y)
xmin, xmax = np.min(Y[:, 0]), np.max(Y[:, 0])
ymin, ymax = np.min(Y[:, 1]), np.max(Y[:, 1])
xrange = xmax - xmin
yrange = ymax - ymin
normx = (
((Y[:, 0] - xmin) / xrange) * 2 - 1 if xrange > 0 else np.zeros_like(Y[:, 0])
)
normy = (
((Y[:, 1] - ymin) / yrange) * 2 - 1 if yrange > 0 else np.zeros_like(Y[:, 1])
)
return list(zip(normx, normy))
def _get_perplexity(num_entities):
if num_entities >= 150:
base = 50
elif num_entities >= 21:
base = num_entities // 3
else:
base = 7
max_perplexity = max(1, (num_entities - 1) // 3)
return min(base, max_perplexity)
try:
from openTSNE import TSNE as TSNE_OPEN
def do_tsne(X):
perplexity = _get_perplexity(len(X))
tsne = TSNE_OPEN(n_components=2, perplexity=perplexity, verbose=True)
Y = tsne.fit(X)
return _normalize_tsne(Y)
except ImportError:
try:
import visdom.extra_deps.bhtsne.bhtsne as bhtsne
def do_tsne(X):
perplexity = _get_perplexity(len(X))
Y = bhtsne.run_bh_tsne(
X, initial_dims=X.shape[1], perplexity=perplexity, verbose=True
)
return _normalize_tsne(Y)
except ImportError:
def do_tsne(X):
raise Exception(
"In order to use the embeddings feature, you'll "
"need to install a backend to support the calculation. "
"Currently we support openTSNE "
"(https://github.com/pavlin-policar/openTSNE) for "
"t-SNE computation, or the bhtsne implementation at "
"https://github.com/lvdmaaten/bhtsne/. Install openTSNE via "
"pip install openTSNE, or install bhtsne by cloning it into "
"the /py/visdom/extra_deps/ directory and running the "
"installation steps as listed on that github "
"in the created /py/visdom/extra_deps/bhtsne directory."
)
here = os.path.abspath(os.path.dirname(__file__))
try:
with open(os.path.join(here, "VERSION")) as version_file:
__version__ = version_file.read().strip()
except Exception:
__version__ = "no_version_file"
logging.getLogger("requests").setLevel(logging.CRITICAL)
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logger = logging.getLogger(__name__)
SESSION_IDLE_TIMEOUT = 600
SESSION_IDLE_CHECK_INTERVAL = 60
def get_rand_id():
return str(hex(int(time.time() * 10000000))[2:])
def isstr(s):
return isinstance(s, (str,))
def isnum(n):
return isinstance(n, numbers.Number) and not isinstance(n, bool)
def isndarray(n):
return isinstance(n, (np.ndarray))
from visdom.utils.shared_utils import NanSafeEncoder
# TODO: In appropriate places, we need to change many numpy calls to use
# nan-aware ones, e.g., `X.max` => `np.nanmax(X)`.
def loadfile(filename):
assert os.path.isfile(filename), "could not find file %s" % filename
fileobj = open(filename, "rb")
assert fileobj, "could not open file %s" % filename
str = fileobj.read()
fileobj.close()
return str
def _title2str(opts):
if opts.get("title") is not None:
if isnum(opts.get("title")):
title = str(opts.get("title"))
logger.warning("Numerical title %s has been cast to a string" % title)
opts["title"] = title
return opts
else:
return opts
def _scrub_dict(d):
if isinstance(d, dict):
return {
k: _scrub_dict(v)
for k, v in list(d.items())
if v is not None and _scrub_dict(v) is not None
}
else:
return d
def _axisformat(xy, opts):
fields = [
"type",
"label",
"tickmin",
"tickmax",
"tickvals",
"ticklabels",
"tick",
"tickfont",
]
if any(opts.get(xy + i) is not None for i in fields):
has_ticks = (
opts.get(xy + "tickmin") is not None
and opts.get(xy + "tickmax") is not None
)
return {
"type": opts.get(xy + "type"),
"title": opts.get(xy + "label"),
"range": (
[opts.get(xy + "tickmin"), opts.get(xy + "tickmax")]
if has_ticks
else None
),
"tickvals": opts.get(xy + "tickvals"),
"ticktext": opts.get(xy + "ticklabels"),
"dtick": opts.get(xy + "tickstep"),
"showticklabels": opts.get(xy + "tick"),
"tickfont": opts.get(xy + "tickfont"),
"automargin": opts.get("tight_layout", False) or None,
}
def _axisformat3d(xyz, opts):
fields = [
"type",
"label",
"tickmin",
"tickmax",
"tickvals",
"ticklabels",
"tick",
"tickfont",
]
if any(opts.get(xyz + i) is not None for i in fields):
has_ticks = (
opts.get(xyz + "tickmin") is not None
and opts.get(xyz + "tickmax") is not None
)
has_step = has_ticks and opts.get(xyz + "tickstep") is not None
return {
"type": opts.get(xyz + "type"),
"title": opts.get(xyz + "label"),
"range": (
[opts.get(xyz + "tickmin"), opts.get(xyz + "tickmax")]
if has_ticks
else None
),
"tickvals": opts.get(xyz + "tickvals"),
"ticktext": opts.get(xyz + "ticklabels"),
"nticks": (
(
(opts.get(xyz + "tickmax") - opts.get(xyz + "tickmin"))
/ opts.get(xyz + "tickstep")
)
if has_step
else None
),
"tickfont": opts.get(xyz + "tickfont"),
}
def _opts2layout(opts, is3d=False):
tight = opts.get("tight_layout", False)
layout = {
"showlegend": opts.get("showlegend", "legend" in opts),
"title": opts.get("title"),
"margin": {
"l": opts.get("marginleft", 0 if (is3d or tight) else 60),
"r": opts.get("marginright", 0 if tight else 60),
"t": opts.get("margintop", 20 if is3d else (30 if tight else 60)),
"b": opts.get("marginbottom", 0 if (is3d or tight) else 60),
},
}
if is3d:
layout["scene"] = {
"xaxis": _axisformat3d("x", opts),
"yaxis": _axisformat3d("y", opts),
"zaxis": _axisformat3d("z", opts),
}
else:
layout["xaxis"] = _axisformat("x", opts)
layout["yaxis"] = _axisformat("y", opts)
if opts.get("stacked"):
layout["barmode"] = "stack" if opts.get("stacked") else "group"
layout_opts = opts.get("layoutopts")
if layout_opts is not None:
if "plotly" in layout_opts:
layout.update(layout_opts["plotly"])
return _scrub_dict(layout)
def _normalize_labels(Y):
"""
Normalizes arbitrary labels (int, float, string) to 1-based indices.
Returns:
Y_normalized (np.ndarray): 1-based integer labels
label_values (np.ndarray or None): Original unique label values, or None if Y
was already a valid set of 1-based integer labels.
K (int): Number of unique labels
"""
Y = np.ravel(Y)
try:
is_integer_labels = (
np.issubdtype(Y.dtype, np.number)
and np.equal(np.mod(Y, 1), 0).all()
and np.nanmin(Y) >= 1
)
except TypeError:
is_integer_labels = False
if is_integer_labels:
Y_normalized = Y.astype(int, copy=False)
K = int(np.nanmax(Y_normalized))
label_values = None
else:
if np.issubdtype(Y.dtype, np.number):
assert np.isfinite(Y).all(), "labels must be finite (no NaN/Inf)"
label_values = np.unique(Y)
K = len(label_values)
Y_normalized = (np.searchsorted(label_values, Y) + 1).astype(int)
return Y_normalized, label_values, K
def _markerColorCheck(mc, X, Y, L):
assert isndarray(mc), "mc should be a numpy ndarray"
if mc.ndim == 1:
valid = (mc.shape[0] >= L) or (mc.shape[0] == X.shape[0])
elif mc.ndim == 2:
valid = (mc.shape[1] == 3) and (
(mc.shape[0] >= L) or (mc.shape[0] == X.shape[0])
)
else:
valid = False
assert valid, (
"marker colors have to be of size `%d` or `%d x 3` "
"(per-point) or at least `%d` or at least `%d x 3` "
"(palette), but got: %s"
) % (
X.shape[0],
X.shape[0],
L,
L,
"x".join(map(str, mc.shape)),
)
assert (mc >= 0).all(), "marker colors have to be >= 0"
assert (mc <= 255).all(), "marker colors have to be <= 255"
assert (mc == np.floor(mc)).all(), "marker colors are assumed to be ints"
mc = np.uint8(mc)
if mc.ndim == 1:
markercolor = ["rgba(0, 0, 255, %s)" % (mc[i] / 255.0) for i in range(len(mc))]
else:
markercolor = ["#%02x%02x%02x" % (i[0], i[1], i[2]) for i in mc]
if mc.shape[0] != X.shape[0]:
markercolor = [markercolor[Y[i] - 1] for i in range(Y.shape[0])]
ret = {}
for k, v in enumerate(markercolor):
ret[Y[k]] = ret.get(Y[k], []) + [v]
return ret
def _markerSizeCheck(ms, X, Y):
"""Validate and return per-point marker sizes as a numpy array."""
if isinstance(ms, (list, tuple)):
ms = np.array(ms, dtype=float)
assert isndarray(ms), "markersize array should be a numpy ndarray"
assert ms.ndim == 1, "markersize array should be 1-dimensional"
assert (ms > 0).all(), "all marker sizes must be positive"
if ms.shape[0] == X.shape[0]:
return np.array(ms, dtype=float)
K = int(np.nanmax(Y)) if len(Y) > 0 else 0
assert ms.shape[0] >= K, (
"markersize should be of size `%d` (per-point) or at least `%d` "
"(per-label), but got: %d" % (X.shape[0], K, ms.shape[0])
)
return np.array([ms[Y[i] - 1] for i in range(len(Y))], dtype=float)
def _lineColorCheck(lc, K):
assert isndarray(lc), "lc should be a numpy ndarray"
assert lc.shape[0] == K, "lc should be same shape as K"
assert (lc >= 0).all(), "line colors have to be >= 0"
assert (lc <= 255).all(), "line colors have to be <= 255"
assert (lc == np.floor(lc)).all(), "line colors are assumed to be ints"
return ["#%02x%02x%02x" % (i[0], i[1], i[2]) for i in lc]
def _dashCheck(dash, K):
assert isndarray(dash), "dash should be a numpy ndarray"
assert dash.shape[0] == K, "dash should be same shape as K"
return dash
def _assert_opts(opts):
remove_nones = ["title"]
for to_remove in remove_nones:
if to_remove in opts and opts[to_remove] is None:
logger.warning(
"None-incompatible opt {} was provided None value "
"and was thus ignored".format(to_remove)
)
del opts[to_remove]
if opts.get("color"):
assert isstr(opts.get("color")), "color should be a string"
if opts.get("colormap"):
assert isstr(opts.get("colormap")), "colormap should be string"
if opts.get("mode"):
assert isstr(opts.get("mode")), "mode should be a string"
if opts.get("markersymbol"):
assert isstr(opts.get("markersymbol")), "marker symbol should be string"
if opts.get("markersize") is not None:
ms = opts.get("markersize")
if isinstance(ms, (list, tuple, np.ndarray)):
assert all(m > 0 for m in ms), "all marker sizes must be positive"
else:
assert isnum(ms) and ms > 0, "marker size should be a positive number"
if opts.get("markerborderwidth"):
assert (
isnum(opts.get("markerborderwidth")) and opts.get("markerborderwidth") >= 0
), "marker border width should be a nonnegative number"
if opts.get("columnnames"):
assert isinstance(
opts.get("columnnames"), list
), "columnnames should be a list with column names"
if opts.get("rownames"):
assert isinstance(
opts.get("rownames"), list
), "rownames should be a list with row names"
if opts.get("jpgquality"):
assert isnum(opts.get("jpgquality")), "JPG quality should be a number"
assert (
opts.get("jpgquality") > 0 and opts.get("jpgquality") <= 100
), "JPG quality should be number between 0 and 100"
if opts.get("opacity"):
assert isnum(opts.get("opacity")), "opacity should be a number"
assert (
0 <= opts.get("opacity") <= 1
), "opacity should be a number between 0 and 1"
if opts.get("fps"):
assert isnum(opts.get("fps")), "fps should be a number"
assert opts.get("fps") > 0, "fps must be greater than 0"
if "title" in opts and opts.get("title") is not None:
assert isstr(opts.get("title")), "title should be a string"
torch_types = []
try:
import torch
torch_types.append(torch.Tensor)
torch_types.append(torch.nn.Parameter)
except (ImportError, AttributeError):
pass
def _to_numpy(a):
if isinstance(a, list):
return np.array(a)
for kind in torch_types:
if isinstance(a, kind):
return a.detach().cpu().numpy()
return a
def pytorch_wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
args = (_to_numpy(arg) for arg in args)
kwargs = {k: _to_numpy(v) for (k, v) in kwargs.items()}
return f(*args, **kwargs)
return wrapped_f
def _binary_clf_curve(y_true, y_score, pos_label=1):
"""Compute true/false positives per distinct score threshold."""
y_true = np.asarray(y_true)
y_score = np.asarray(y_score)
if y_true.ndim != 1:
raise ValueError("y_true should have 1 dim")
if y_score.ndim != 1:
raise ValueError("y_score should have 1 dim")
if y_true.shape[0] != y_score.shape[0]:
raise ValueError("y_true and y_score should match")
if y_true.shape[0] == 0:
raise ValueError("y_true and y_score should be non-empty")
if not np.all(np.isfinite(y_score)):
raise ValueError("y_score should only contain finite values")
y_true = y_true == pos_label
desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1]
y_score = y_score[desc_score_indices]
y_true = y_true[desc_score_indices]
distinct_value_indices = np.where(np.diff(y_score))[0]
threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1]
tps = np.cumsum(y_true, dtype=float)[threshold_idxs]
fps = 1 + threshold_idxs - tps
return fps, tps
def _compute_roc_curve(y_true, y_score, pos_label=1):
"""Compute ROC curve (fpr, tpr) from raw labels and scores."""
fps, tps = _binary_clf_curve(y_true=y_true, y_score=y_score, pos_label=pos_label)
pos_total = float(tps[-1])
neg_total = float(fps[-1])
if pos_total <= 0:
raise ValueError("y_true has no positive samples")
if neg_total <= 0:
raise ValueError("y_true has no negative samples")
fpr = np.r_[0.0, fps / neg_total]
tpr = np.r_[0.0, tps / pos_total]
return fpr, tpr
def _compute_pr_curve(y_true, y_score, pos_label=1):
"""Compute precision-recall curve from raw labels and scores."""
fps, tps = _binary_clf_curve(y_true=y_true, y_score=y_score, pos_label=pos_label)
pos_total = float(tps[-1])
if pos_total <= 0:
raise ValueError("y_true has no positive samples")
precision = tps / (tps + fps)
recall = tps / pos_total
precision = np.r_[1.0, precision]
recall = np.r_[0.0, recall]
return precision, recall
def _coerce_curve_xy(x, y, x_name, y_name):
"""Validate and sort precomputed curve arrays by x."""
x = np.asarray(x)
y = np.asarray(y)
if x.ndim != 1:
raise ValueError("{} should have 1 dim".format(x_name))
if y.ndim != 1:
raise ValueError("{} should have 1 dim".format(y_name))
if x.shape[0] != y.shape[0]:
raise ValueError("{} and {} should match".format(x_name, y_name))
if x.shape[0] <= 1:
raise ValueError(
"{} and {} should have at least 2 points".format(x_name, y_name)
)
order = np.argsort(x, kind="mergesort")
return x[order], y[order]
def _validate_curve_range(values, name):
"""Validate that values are finite and within [0, 1]."""
values = np.asarray(values)
if not np.all(np.isfinite(values)):
raise ValueError("{} should only contain finite values".format(name))
if not np.all((values >= 0.0) & (values <= 1.0)):
raise ValueError("{} should be within [0, 1]".format(name))
def _curve_legend(legend, default_legend):
"""Return user-provided legend or default 2-element list."""
if not isinstance(legend, (tuple, list)) or len(legend) < 2:
if legend is not None:
warnings.warn(
"legend should be a list/tuple with at least 2 elements, "
"falling back to default: {}".format(default_legend),
UserWarning,
)
return list(default_legend)
return list(legend)
def _trapz_area(y, x):
"""Compute trapezoidal area under curve, compatible with numpy >= 2.0."""
trapezoid = getattr(np, "trapezoid", None)
if trapezoid is not None:
return float(trapezoid(y, x))
return float(np.trapz(y, x))
def _average_precision(precision, recall):
"""Compute average precision: AP = sum((R_n - R_{n-1}) * P_n)."""
precision = np.asarray(precision)
recall = np.asarray(recall)
return float(np.sum(np.diff(recall) * precision[1:]))
def _compute_confusion_matrix(y_true, y_pred, labels):
"""Build an NxN confusion matrix from label vectors (numpy only).
``y_true``/``y_pred`` are expected to be 1-D numpy arrays; the public
``confusion_matrix`` caller ravels them before calling this helper.
"""
if y_true.shape[0] != y_pred.shape[0]:
raise ValueError("y_true and y_pred must have the same length")
if y_true.shape[0] == 0:
raise ValueError("y_true and y_pred must be non-empty")
label_to_idx = {label: i for i, label in enumerate(labels)}
n = len(labels)
cm = np.zeros((n, n), dtype=int)
skipped = 0
for t, p in zip(y_true, y_pred):
if t in label_to_idx and p in label_to_idx:
cm[label_to_idx[t], label_to_idx[p]] += 1
else:
skipped += 1
if skipped > 0:
warnings.warn(
"{} samples had labels not in the provided labels list "
"and were ignored".format(skipped),
UserWarning,
)
return cm
def _decode_binary_arrays(obj):
"""Decode Plotly 6+ binary-encoded arrays back to plain Python lists."""
if isinstance(obj, dict):
if "dtype" in obj and "bdata" in obj:
try:
arr = np.frombuffer(
base64.b64decode(obj["bdata"]), dtype=np.dtype(obj["dtype"])
)
if "shape" in obj:
arr = arr.reshape(obj["shape"])
return arr.tolist()
except (binascii.Error, ValueError, TypeError):
return obj
return {k: _decode_binary_arrays(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_decode_binary_arrays(v) for v in obj]
return obj
class Visdom(object):
def __init__(
self,
server="http://localhost",
endpoint="events",
port=8097,
base_url="/",
ipv6=True,
http_proxy_host=None,
http_proxy_port=None,
env="main",
send=True,
raise_exceptions=None,
use_incoming_socket=True,
log_to_filename=None,
username=None,
password=None,
proxies=None,
offline=False,
use_polling=False,
session_idle_timeout=SESSION_IDLE_TIMEOUT,
session_idle_check_interval=SESSION_IDLE_CHECK_INTERVAL,
ssl_verify=None,
):
parsed_url = urlparse(server)
if not parsed_url.scheme:
parsed_url = urlparse("http://{}".format(server))
if parsed_url.scheme == "http" and ssl_verify is not None:
raise ValueError(
"ssl_verify is only valid with HTTPS. "
"Use server='https://...' to enable HTTPS."
)
if ssl_verify is None:
ssl_verify = True
self.ssl_verify = ssl_verify
self.server_base_name = parsed_url.netloc
self.server = urlunparse((parsed_url.scheme, parsed_url.netloc, "", "", "", ""))
self.endpoint = endpoint
self.port = port
# preprocess base_url
self.base_url = base_url if base_url != "/" else ""
assert self.base_url == "" or self.base_url.startswith(
"/"
), "base_url should start with /"
assert self.base_url == "" or not self.base_url.endswith(
"/"
), "base_url should not end with / as it is appended automatically"
self.ipv6 = ipv6
self.env = (
env.replace("/", "_")
.replace("\\", "_")
.replace("\n", "-")
.replace("\r", "-")
)
self.env_list = {self.env} # default env
self.send = send
self.event_handlers = {} # Haven't registered any events
self.socket_alive = False
self.socket_connection_achieved = False
self.use_socket = use_incoming_socket or use_polling
# Flag to indicate whether to raise errors or suppress them
self.raise_exceptions = raise_exceptions
self.log_to_filename = log_to_filename
self.offline = offline
self._session = None
self._pid = os.getpid()
self._session_lock = threading.Lock()
self._last_post_time = time.time()
self.session_idle_timeout = session_idle_timeout
self.session_idle_check_interval = session_idle_check_interval
self.proxies = proxies
self.http_proxy_host = None
self.http_proxy_port = None
if proxies is not None and "http" in proxies:
self.http_proxy_host, self.http_proxy_port = proxies["http"].split(":")
if http_proxy_host is not None or http_proxy_port is not None:
warnings.warn(
"HTTP Proxy Port and Host args Deprecated. " "Please use proxies arg.",
DeprecationWarning,
)
self.http_proxy_host = http_proxy_host
self.http_proxy_port = http_proxy_port
self.username = username
if self.username:
assert password, "no password given for authentication"
self.password = hashlib.sha256(password.encode("utf-8")).hexdigest()
self.win_data = {}
if self.offline:
self.use_socket = False
assert (
self.log_to_filename is not None
), "Must use a log_to_filename for offline visdom"
return # No need for the rest of this setup in offline visdom
# storage for data associated with specific windows
# Setup for online interactions
result = self._send({"eid": env}, endpoint="env/" + env)
if self.send and result is False:
if self.raise_exceptions:
raise ConnectionError(
"Could not connect to server at {}:{}.".format(
self.server, self.port
)
)
else:
logger.warning(
"Could not connect to server at {}:{}.".format(
self.server, self.port
)
)
# when talking to a server, get a backchannel
if send and use_incoming_socket:
self.setup_socket()
elif send and use_polling:
self.setup_polling()
elif send and not use_incoming_socket:
logger.warning(
"Without the incoming socket you cannot receive events from "
"the server or register event handlers to your Visdom client."
)
if send:
self._start_session_reaper()
# Wait for initialization before starting
time_spent = 0
inc = 0.1
while self.use_socket and not self.socket_alive and time_spent < 5:
time.sleep(inc)
time_spent += inc
inc *= 2
if time_spent > 5:
logger.warning(
"Visdom python client failed to establish socket to get "
"messages from the server. This feature is optional and "
"can be disabled by initializing Visdom with "
"`use_incoming_socket=False`, which will prevent waiting for "
"this request to timeout."
)
@property
def session(self):
with self._session_lock:
current_pid = os.getpid()
if self._session and self._pid == current_pid:
return self._session
if self._session:
try:
self._session.close()
except Exception:
pass
self._pid = current_pid
logger.warning("Setting up a new session...")
sess = requests.Session()
if self.proxies:
sess.proxies.update(self.proxies)
if isinstance(self.ssl_verify, str):
sess.verify = self.ssl_verify
elif not self.ssl_verify:
sess.verify = False
if self.username:
resp = sess.post(
"%s:%s%s" % (self.server, self.port, self.base_url),
json=dict(username=self.username, password=self.password),
)
if resp.status_code != requests.codes.ok:
raise RuntimeError("Authentication failed")
logger.info("Authentication succeeded")
self._session = sess
return sess
def _start_session_reaper(self):
def run_reaper():
while True:
time.sleep(self.session_idle_check_interval)
idle_for = time.time() - self._last_post_time
if idle_for <= self.session_idle_timeout:
continue
with self._session_lock:
if (
self._session is not None
and time.time() - self._last_post_time
> self.session_idle_timeout
):
logger.info(
"Closing idle visdom HTTP session after %ds of "
"inactivity; it will be recreated on the next send.",
int(idle_for),
)
try:
self._session.close()
except Exception:
pass
self._session = None
self.session_reaper_thread = threading.Thread(
target=run_reaper, name="Visdom-Session-Reaper", daemon=True
)
self.session_reaper_thread.start()
def register_event_handler(self, handler, target, env=None):
assert callable(handler), "Event handler must be a function"
assert (
self.use_socket
), "Must be using the incoming socket to register events to web actions"
key = (env, target)
if key not in self.event_handlers:
self.event_handlers[key] = []
self.event_handlers[key].append(handler)
def clear_event_handlers(self, target, env=None):
self.event_handlers.pop((env, target), None)
def setup_polling(self):
# TODO merge with setup_socket?
# Setup socket to server
def on_message(message):
message = json.loads(message)
if "command" in message:
# Handle server commands
if message["command"] == "alive":
if "data" in message and message["data"] == "vis_alive":
logger.info("Visdom successfully connected to server")
self.socket_alive = True
self.socket_connection_achieved = True
else:
logger.warning(
"Visdom server failed handshake, may not "
"be properly connected"
)
if "target" in message:
env = message.get("eid")
key = (env, message["target"])
for handler in list(self.event_handlers.get(key, [])):
handler(message)
if env is not None:
global_key = (None, message["target"])
for handler in list(self.event_handlers.get(global_key, [])):
handler(message)
def on_close(ws):
self.socket_alive = False
def run_socket(*args):
# open a socket
resp_json = self._handle_post(
"{0}:{1}{2}/vis_socket_wrap".format(
self.server, self.port, self.base_url
),
data=json.dumps({"message_type": "init"}),
)
resp = json.loads(resp_json)
self.vis_sid = resp["sid"]
while self.use_socket:
resp_json = self._handle_post(
"{0}:{1}{2}/vis_socket_wrap".format(
self.server, self.port, self.base_url
),
data=json.dumps({"message_type": "query", "sid": self.vis_sid}),
)
resp = json.loads(resp_json)
for msg in resp["messages"]:
on_message(msg)
time.sleep(0.1)
# Start listening thread
self.socket_thread = threading.Thread(
target=run_socket, name="Visdom-Socket-Thread"
)
self.socket_thread.start()
def setup_socket(self, polling=False):
# Setup socket to server
def on_message(ws, message):
message = json.loads(message)
if "command" in message:
# Handle server commands
if message["command"] == "alive":
if "data" in message and message["data"] == "vis_alive":
logger.info("Visdom successfully connected to server")
self.socket_alive = True
self.socket_connection_achieved = True
else:
logger.warning(
"Visdom server failed handshake, may not "
"be properly connected"
)
if "target" in message:
env = message.get("eid")
key = (env, message["target"])
handlers = list(self.event_handlers.get(key, []))
if env is not None:
global_key = (None, message["target"])
handlers.extend(list(self.event_handlers.get(global_key, [])))
for handler in handlers:
try:
handler(message)
except Exception as e:
logger.warning(
"Visdom failed to handle a handler for {}: {}"
"".format(message, e)
)
import traceback
traceback.print_exc()
def on_error(ws, error):
if hasattr(error, "errno") and error.errno == errno.ECONNREFUSED:
if not self.socket_connection_achieved:
#
# Visdom will stop trying to use the socket only if it
# never succeeded in acquiring it.
#
logger.info("Socket refused connection, running socketless")
self.use_socket = False
logger.error(error)
ws.close()
def on_close(ws, close_status_code=None, close_msg=None):
self.socket_alive = False
if not self.socket_connection_achieved:
logger.warning(
"WebSocket closed before connection achieved "
"(close_status_code=%s). If login is enabled, "
"pass username/password to Visdom().",
close_status_code,
)
self.use_socket = False