-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathvisualization.py
212 lines (164 loc) · 7.21 KB
/
visualization.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
import requests
import json
import webbrowser
import random
import string
class Visualization(object):
def __init__(self, session=None, json=None, auth=None):
self.session = session
self.id = json.get('id')
self.auth = auth
if self.session.lgn.ipython_enabled:
from IPython.kernel.comm import Comm
self.comm = Comm('lightning', {'id': self.id})
self.comm_handlers = {}
self.comm.on_msg(self._handle_comm_message)
def _format_url(self, url):
if not url.endswith('/'):
url += '/'
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
return url + '?host=' + quote(self.session.host)
def _update_image(self, image):
url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/data/images'
url = self._format_url(url)
files = {'file': image}
return requests.put(url, files=files, data={'type': 'image'}, auth=self.auth)
def _append_image(self, image):
url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/data/images'
url = self._format_url(url)
files = {'file': image}
return requests.post(url, files=files, data={'type': 'image'}, auth=self.auth)
def _append_data(self, data=None, field=None):
payload = {'data': data}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/data/'
if field:
url += field
url = self._format_url(url)
return requests.post(url, data=json.dumps(payload), headers=headers, auth=self.auth)
def _update_data(self, data=None, field=None):
payload = {'data': data}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/data/'
if field:
url += field
url = self._format_url(url)
return requests.put(url, data=json.dumps(payload), headers=headers, auth=self.auth)
def get_permalink(self):
return self.session.host + '/visualizations/' + str(self.id)
def get_public_link(self):
return self.get_permalink() + '/public/'
def get_embed_link(self):
return self._format_url(self.get_permalink() + '/embed')
def get_html(self):
r = requests.get(self.get_embed_link(), auth=self.auth)
return r.text
def open(self):
webbrowser.open(self.get_public_link())
def delete(self):
url = self.get_permalink()
return requests.delete(url)
def on(self, event_name, handler):
if self.session.lgn.ipython_enabled:
self.comm_handlers[event_name] = handler
else:
raise Exception('The current implementation of this method is only compatible with IPython.')
def _handle_comm_message(self, message):
# Parsing logic taken from similar code in matplotlib
message = json.loads(message['content']['data'])
if message['type'] in self.comm_handlers:
self.comm_handlers[message['type']](message['data'])
@classmethod
def _create(cls, session=None, data=None, images=None, type=None, options=None, description=None):
if options is None:
options = {}
url = session.host + '/sessions/' + str(session.id) + '/visualizations'
if not images:
payload = {'data': data, 'type': type, 'options': options}
if description:
payload['description'] = description
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(payload, allow_nan=False), headers=headers, auth=session.auth)
if r.status_code == 404:
raise Exception(r.text)
elif not r.status_code == requests.codes.ok:
raise Exception('Problem uploading data')
viz = cls(session=session, json=r.json(), auth=session.auth)
else:
first_image, remaining_images = images[0], images[1:]
files = {'file': first_image}
payload = {'type': type, 'options': json.dumps(options)}
if description:
payload['description'] = description
r = requests.post(url, files=files, data=payload, auth=session.auth)
if r.status_code == 404:
raise Exception(r.text)
elif not r.status_code == requests.codes.ok:
raise Exception('Problem uploading images')
viz = cls(session=session, json=r.json(), auth=session.auth)
for image in remaining_images:
viz._append_image(image)
return viz
class VisualizationLocal(object):
def __init__(self, html):
self._html = html
@classmethod
def _create(cls, data=None, images=None, type=None, options=None):
import base64
from jinja2 import Template, escape
t = Template(cls.load_template())
options = escape(json.dumps(options))
random_id = 'A' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(9))
fields = {'viz': type, 'options': options, 'viz_id': random_id}
if images:
bytes = ['data:image/png;base64,' + base64.b64encode(img) + ',' for img in images]
fields['images'] = escape(json.dumps(bytes))
else:
data = escape(json.dumps(data))
fields['data'] = data
html = t.render(**fields)
viz = cls(html)
return viz
def get_html(self):
"""
Return html for this local visualization.
Assumes that Javascript has already been embedded,
to be used for rendering in notebooks.
"""
return self._html
def save_html(self, filename=None, overwrite=False):
"""
Save self-contained html to a file.
Parameters
----------
filename : str
The filename to save to
"""
if filename is None:
raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").')
import os
base = self._html
js = self.load_embed()
if os.path.exists(filename):
if overwrite is False:
raise ValueError("File '%s' exists. To ovewrite call save_html with overwrite=True."
% os.path.abspath(filename))
else:
os.remove(filename)
with open(filename, "wb") as f:
f.write(base.encode('utf-8'))
f.write('<script>' + js.encode('utf-8') + '</script>')
@staticmethod
def load_template():
import os
location = os.path.join(os.path.dirname(__file__), 'lib/template.html')
return open(location).read()
@staticmethod
def load_embed():
import os
location = os.path.join(os.path.dirname(__file__), 'lib/embed.js')
import codecs
return codecs.open(location, "r", "utf-8").read()