-
Notifications
You must be signed in to change notification settings - Fork 276
/
patches.py
55 lines (38 loc) 路 1.19 KB
/
patches.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
def patch_matplotlib():
import os
from io import BytesIO
# before importing matplotlib
# to avoid the wasm backend (which needs `js.document`, not available in worker)
os.environ["MPLBACKEND"] = "AGG"
import matplotlib.pyplot
from IPython.display import display
from .display import Image
_old_show = matplotlib.pyplot.show
assert _old_show, "matplotlib.pyplot.show"
def show(*, block=None):
buf = BytesIO()
matplotlib.pyplot.savefig(buf, format="png")
buf.seek(0)
display(Image(buf.read()))
matplotlib.pyplot.clf()
matplotlib.pyplot.show = show
def patch_pillow():
import base64
from PIL import Image as PILImage
_old_repr_png = PILImage.Image._repr_png_
assert _old_repr_png
def _repr_png_(self):
byte = _old_repr_png(self)
return base64.b64encode(byte).decode("utf-8")
PILImage.Image._repr_png_ = _repr_png_
ALL_PATCHES = [
patch_pillow,
patch_matplotlib,
]
def apply_patches():
import warnings
for patch in ALL_PATCHES:
try:
patch()
except Exception as err:
warnings.warn("failed to apply patch", patch, err)