forked from plotly/plotly.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_base_renderers.py
639 lines (530 loc) · 19.3 KB
/
_base_renderers.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
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
from __future__ import absolute_import
import base64
import json
import webbrowser
import inspect
import os
import six
from plotly.io import to_json, to_image
from plotly import utils, optional_imports
from plotly.io._orca import ensure_server
from plotly.offline.offline import _get_jconfig, get_plotlyjs
ipython_display = optional_imports.get_module('IPython.display')
IPython = optional_imports.get_module('IPython')
try:
from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
# Python 2.7
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class BaseRenderer(object):
"""
Base class for all renderers
"""
def activate(self):
pass
def __repr__(self):
try:
init_sig = inspect.signature(self.__init__)
init_args = list(init_sig.parameters.keys())
except AttributeError:
# Python 2.7
argspec = inspect.getargspec(self.__init__)
init_args = [a for a in argspec.args if a != 'self']
return "{cls}({attrs})\n{doc}".format(
cls=self.__class__.__name__,
attrs=", ".join("{}={!r}".format(k, self.__dict__[k])
for k in init_args),
doc=self.__doc__)
def __hash__(self):
# Constructor args fully define uniqueness
return hash(repr(self))
class MimetypeRenderer(BaseRenderer):
"""
Base class for all mime type renderers
"""
def to_mimebundle(self, fig_dict):
raise NotImplementedError()
class JsonRenderer(MimetypeRenderer):
"""
Renderer to display figures as JSON hierarchies. This renderer is
compatible with JupyterLab and VSCode.
mime type: 'application/json'
"""
def to_mimebundle(self, fig_dict):
value = json.loads(to_json(
fig_dict, validate=False, remove_uids=False))
return {'application/json': value}
# Plotly mimetype
class PlotlyRenderer(MimetypeRenderer):
"""
Renderer to display figures using the plotly mime type. This renderer is
compatible with JupyterLab (using the @jupyterlab/plotly-extension),
VSCode, and nteract.
mime type: 'application/vnd.plotly.v1+json'
"""
def __init__(self, config=None):
self.config = dict(config) if config else {}
def to_mimebundle(self, fig_dict):
config = _get_jconfig(self.config)
if config:
fig_dict['config'] = config
json_compatible_fig_dict = json.loads(
to_json(fig_dict, validate=False, remove_uids=False))
return {'application/vnd.plotly.v1+json': json_compatible_fig_dict}
# Static Image
class ImageRenderer(MimetypeRenderer):
"""
Base class for all static image renderers
"""
def __init__(self,
mime_type,
b64_encode=False,
format=None,
width=None,
height=None,
scale=None):
self.mime_type = mime_type
self.b64_encode = b64_encode
self.format = format
self.width = width
self.height = height
self.scale = scale
def activate(self):
# Start up orca server to reduce the delay on first render
ensure_server()
def to_mimebundle(self, fig_dict):
image_bytes = to_image(
fig_dict,
format=self.format,
width=self.width,
height=self.height,
scale=self.scale,
validate=False,
)
if self.b64_encode:
image_str = base64.b64encode(image_bytes).decode('utf8')
else:
image_str = image_bytes.decode('utf8')
return {self.mime_type: image_str}
class PngRenderer(ImageRenderer):
"""
Renderer to display figures as static PNG images. This renderer requires
the orca command-line utility and is broadly compatible across IPython
environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode,
PyCharm, etc) and nbconvert targets (HTML, PDF, etc.).
mime type: 'image/png'
"""
def __init__(self, width=None, height=None, scale=None):
super(PngRenderer, self).__init__(
mime_type='image/png',
b64_encode=True,
format='png',
width=width,
height=height,
scale=scale)
class SvgRenderer(ImageRenderer):
"""
Renderer to display figures as static SVG images. This renderer requires
the orca command-line utility and is broadly compatible across IPython
environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode,
PyCharm, etc) and nbconvert targets (HTML, PDF, etc.).
mime type: 'image/svg+xml'
"""
def __init__(self, width=None, height=None, scale=None):
super(SvgRenderer, self).__init__(
mime_type='image/svg+xml',
b64_encode=False,
format='svg',
width=width,
height=height,
scale=scale)
class JpegRenderer(ImageRenderer):
"""
Renderer to display figures as static JPEG images. This renderer requires
the orca command-line utility and is broadly compatible across IPython
environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode,
PyCharm, etc) and nbconvert targets (HTML, PDF, etc.).
mime type: 'image/jpeg'
"""
def __init__(self, width=None, height=None, scale=None):
super(JpegRenderer, self).__init__(
mime_type='image/jpeg',
b64_encode=True,
format='jpg',
width=width,
height=height,
scale=scale)
class PdfRenderer(ImageRenderer):
"""
Renderer to display figures as static PDF images. This renderer requires
the orca command-line utility and is compatible with JupyterLab and the
LaTeX-based nbconvert export to PDF.
mime type: 'application/pdf'
"""
def __init__(self, width=None, height=None, scale=None):
super(PdfRenderer, self).__init__(
mime_type='application/pdf',
b64_encode=True,
format='pdf',
width=width,
height=height,
scale=scale)
# HTML
# Build script to set global PlotlyConfig object. This must execute before
# plotly.js is loaded.
_window_plotly_config = """\
window.PlotlyConfig = {MathJaxConfig: 'local'};"""
_mathjax_config = """\
if (window.MathJax) {MathJax.Hub.Config({SVG: {font: "STIX-Web"}});}"""
class HtmlRenderer(MimetypeRenderer):
"""
Base class for all HTML mime type renderers
mime type: 'text/html'
"""
def __init__(self,
connected=False,
full_html=False,
requirejs=True,
global_init=False,
config=None,
auto_play=False,
post_script=None,
animation_opts=None):
self.config = dict(config) if config else {}
self.auto_play = auto_play
self.connected = connected
self.global_init = global_init
self.requirejs = requirejs
self.full_html = full_html
self.animation_opts = animation_opts
self.post_script = post_script
def activate(self):
if self.global_init:
if not ipython_display:
raise ValueError(
'The {cls} class requires ipython but it is not installed'
.format(cls=self.__class__.__name__))
if not self.requirejs:
raise ValueError(
'global_init is only supported with requirejs=True')
if self.connected:
# Connected so we configure requirejs with the plotly CDN
script = """\
<script type="text/javascript">
{win_config}
{mathjax_config}
if (typeof require !== 'undefined') {{
require.undef("plotly");
requirejs.config({{
paths: {{
'plotly': ['https://cdn.plot.ly/plotly-latest.min']
}}
}});
require(['plotly'], function(Plotly) {{
window._Plotly = Plotly;
}});
}}
</script>
""".format(win_config=_window_plotly_config,
mathjax_config=_mathjax_config)
else:
# If not connected then we embed a copy of the plotly.js
# library in the notebook
script = """\
<script type="text/javascript">
{win_config}
{mathjax_config}
if (typeof require !== 'undefined') {{
require.undef("plotly");
define('plotly', function(require, exports, module) {{
{script}
}});
require(['plotly'], function(Plotly) {{
window._Plotly = Plotly;
}});
}}
</script>
""".format(script=get_plotlyjs(),
win_config=_window_plotly_config,
mathjax_config=_mathjax_config)
ipython_display.display_html(script, raw=True)
def to_mimebundle(self, fig_dict):
from plotly.io import to_html
if self.requirejs:
include_plotlyjs = 'require'
include_mathjax = False
elif self.connected:
include_plotlyjs = 'cdn'
include_mathjax = 'cdn'
else:
include_plotlyjs = True
include_mathjax = 'cdn'
# build post script
post_script = ["""
var gd = document.getElementById('{plot_id}');
var x = new MutationObserver(function (mutations, observer) {{
var display = window.getComputedStyle(gd).display;
if (!display || display === 'none') {{
console.log([gd, 'removed!']);
Plotly.purge(gd);
observer.disconnect();
}}
}});
// Listen for the removal of the full notebook cells
var notebookContainer = gd.closest('#notebook-container');
if (notebookContainer) {{
x.observe(notebookContainer, {childList: true});
}}
// Listen for the clearing of the current output cell
var outputEl = gd.closest('.output');
if (outputEl) {{
x.observe(outputEl, {childList: true});
}}
"""]
# Add user defined post script
if self.post_script:
if not isinstance(self.post_script, (list, tuple)):
post_script.append(self.post_script)
else:
post_script.extend(self.post_script)
html = to_html(
fig_dict,
config=self.config,
auto_play=self.auto_play,
include_plotlyjs=include_plotlyjs,
include_mathjax=include_mathjax,
post_script=post_script,
full_html=self.full_html,
animation_opts=self.animation_opts,
default_width='100%',
default_height=525,
validate=False,
)
return {'text/html': html}
class NotebookRenderer(HtmlRenderer):
"""
Renderer to display interactive figures in the classic Jupyter Notebook.
This renderer is also useful for notebooks that will be converted to
HTML using nbconvert/nbviewer as it will produce standalone HTML files
that include interactive figures.
This renderer automatically performs global notebook initialization when
activated.
mime type: 'text/html'
"""
def __init__(self,
connected=False,
config=None,
auto_play=False,
post_script=None,
animation_opts=None):
super(NotebookRenderer, self).__init__(
connected=connected,
full_html=False,
requirejs=True,
global_init=True,
config=config,
auto_play=auto_play,
post_script=post_script,
animation_opts=animation_opts)
class KaggleRenderer(HtmlRenderer):
"""
Renderer to display interactive figures in Kaggle Notebooks.
Same as NotebookRenderer but with connected=True so that the plotly.js
bundle is loaded from a CDN rather than being embedded in the notebook.
This renderer is enabled by default when running in a Kaggle notebook.
mime type: 'text/html'
"""
def __init__(self,
config=None,
auto_play=False,
post_script=None,
animation_opts=None):
super(KaggleRenderer, self).__init__(
connected=True,
full_html=False,
requirejs=True,
global_init=True,
config=config,
auto_play=auto_play,
post_script=post_script,
animation_opts=animation_opts)
class ColabRenderer(HtmlRenderer):
"""
Renderer to display interactive figures in Google Colab Notebooks.
This renderer is enabled by default when running in a Colab notebook.
mime type: 'text/html'
"""
def __init__(self,
config=None,
auto_play=False,
post_script=None,
animation_opts=None):
super(ColabRenderer, self).__init__(
connected=True,
full_html=True,
requirejs=False,
global_init=False,
config=config,
auto_play=auto_play,
post_script=post_script,
animation_opts=animation_opts)
class IFrameRenderer(MimetypeRenderer):
"""
Renderer to display interactive figures using an IFrame. HTML
representations of Figures are saved to an `iframe_figures/` directory and
iframe HTML elements that reference these files are inserted into the
notebook.
With this approach, neither plotly.js nor the figure data are embedded in
the notebook, so this is a good choice for notebooks that contain so many
large figures that basic operations (like saving and opening) become
very slow.
Notebooks using this renderer will display properly when exported to HTML
as long as the `iframe_figures/` directory is placed in the same directory
as the exported html file.
Note that the HTML files in `iframe_figures/` are numbered according to
the IPython cell execution count and so they will start being overwritten
each time the kernel is restarted. This directory may be deleted whenever
the kernel is restarted and it will be automatically recreated.
mime type: 'text/html'
"""
def __init__(self,
config=None,
auto_play=False,
post_script=None,
animation_opts=None):
self.config = config
self.auto_play = auto_play
self.post_script = post_script
self.animation_opts = animation_opts
def to_mimebundle(self, fig_dict):
from plotly.io import write_html
# Make iframe size slightly larger than figure size to avoid
# having iframe have its own scroll bar.
iframe_buffer = 20
layout = fig_dict.get('layout', {})
if layout.get('width', False):
iframe_width = str(layout['width'] + iframe_buffer) + 'px'
else:
iframe_width = '100%'
if layout.get('height', False):
iframe_height = layout['height'] + iframe_buffer
else:
iframe_height = str(525 + iframe_buffer) + 'px'
# Build filename using ipython cell number
ip = IPython.get_ipython()
cell_number = list(ip.history_manager.get_tail(1))[0][1] + 1
dirname = 'iframe_figures'
filename = '{dirname}/figure_{cell_number}.html'.format(
dirname=dirname, cell_number=cell_number)
# Make directory for
os.makedirs(dirname, exist_ok=True)
write_html(
fig_dict,
filename,
config=self.config,
auto_play=self.auto_play,
include_plotlyjs='directory',
include_mathjax='cdn',
auto_open=False,
post_script=self.post_script,
animation_opts=self.animation_opts,
default_width='100%',
default_height=525,
validate=False,
)
# Build IFrame
iframe_html = """\
<iframe
scrolling="no"
width="{width}"
height="{height}"
src="{src}"
frameborder="0"
allowfullscreen
></iframe>
""".format(width=iframe_width, height=iframe_height, src=filename)
return {'text/html': iframe_html}
class ExternalRenderer(BaseRenderer):
"""
Base class for external renderers. ExternalRenderer subclasses
do not display figures inline in a notebook environment, but render
figures by some external means (e.g. a separate browser tab).
Unlike MimetypeRenderer subclasses, ExternalRenderer subclasses are not
invoked when a figure is asked to display itself in the notebook.
Instead, they are invoked when the plotly.io.show function is called
on a figure.
"""
def render(self, fig):
raise NotImplementedError()
def open_html_in_browser(html, using=None, new=0, autoraise=True):
"""
Display html in a web browser without creating a temp file.
Instantiates a trivial http server and uses the webbrowser module to
open a URL to retrieve html from that server.
Parameters
----------
html: str
HTML string to display
using, new, autoraise:
See docstrings in webbrowser.get and webbrowser.open
"""
if isinstance(html, six.string_types):
html = html.encode('utf8')
class OneShotRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
bufferSize = 1024*1024
for i in range(0, len(html), bufferSize):
self.wfile.write(html[i:i+bufferSize])
def log_message(self, format, *args):
# Silence stderr logging
pass
server = HTTPServer(('127.0.0.1', 0), OneShotRequestHandler)
webbrowser.get(using).open(
'http://127.0.0.1:%s' % server.server_port,
new=new,
autoraise=autoraise)
server.handle_request()
class BrowserRenderer(ExternalRenderer):
"""
Renderer to display interactive figures in an external web browser.
This renderer will open a new browser window or tab when the
plotly.io.show function is called on a figure.
This renderer has no ipython/jupyter dependencies and is a good choice
for use in environments that do not support the inline display of
interactive figures.
mime type: 'text/html'
"""
def __init__(self,
config=None,
auto_play=False,
using=None,
new=0,
autoraise=True,
post_script=None,
animation_opts=None):
self.config = config
self.auto_play = auto_play
self.using = using
self.new = new
self.autoraise = autoraise
self.post_script = post_script
self.animation_opts = animation_opts
def render(self, fig_dict):
from plotly.io import to_html
html = to_html(
fig_dict,
config=self.config,
auto_play=self.auto_play,
include_plotlyjs=True,
include_mathjax='cdn',
post_script=self.post_script,
full_html=True,
animation_opts=self.animation_opts,
default_width='100%',
default_height='100%',
validate=False,
)
open_html_in_browser(html, self.using, self.new, self.autoraise)